My code is executed after the end of the gulp task - gulp

I built an asyncronous gulp task to convert some sass files into css files and i got some troubles with timeline code execution.
I need to execute this task inside a loop and the code is executed after the end of the gulp task
async build() {
var self = this;
var tasks = await this.themes.map(async(theme) => {
return gulp.src(this.templatesPath + '/' + this.pattern)
.pipe(header('#import \'' + this.themesPath + '/' + theme + '/' + this.themeFile + '\';'))
.pipe(sass.sync().on('error', gutil.log))
.pipe(rename(function (path: any) {
var file = path.basename + path.extname;
path.dirname += '/' + file;
gutil.log(self.folders[theme][file]);
}))
.pipe(gulp.dest(this.themesPath + '/' + theme))
gutil.log('loop');
});
gutil.log('end');
}
gutil.log output inside rename function is always outprinted after end of task
[18:08:34] Starting 'build'...
[18:08:34] end
[18:08:34] Finished 'build' after 33 ms
[18:08:34] [ { '$': { 'jcr:primaryType': 'jnt:file' },
'jcr:content': [ [Object] ] } ]
[18:08:34] [ { '$': { 'jcr:primaryType': 'jnt:file' },
'jcr:content': [ [Object] ] } ]
How can I handle the end of loop to be sure my objects are filled when i execute others tasks ?

Related

Accessing json returning undefined react js

I am trying to grab some json data to display in Ui but when I iterate over it using the map method I keep getting undefined.Any help will be really appreciated.Here is a link on code sandbox https://codesandbox.io/s/late-wood-kx8w2?file=/src/App.js
This line
const [items, setItem] = useState(Object.keys(trees));
is passing the tree keys to the View function and not the actual data. I believe that you meant to pass the data. Your code passes 'name' and 'children' as {items} that then gets displayed by View.js.
The following code shows you how you can parse the tree and get the names and the values. It's incomplete, but it should give you a start on how to do the traversal.
import React, { useState } from "react";
export default function Start(){
const trees = {
name: "root",
children: [
{
name: "child1",
children: [
{ name: "child1-child1", data: "c1-c1 Hello" },
{ name: "child1-child2", data: "c1-c2 JS" }
]
},
{ name: "child2", data: "c2 World" }
]
};
const treesCopy = trees;
function Traverse(tree){
var treesCopy = tree;
var str = [];
for (var prop in treesCopy) {
console.log(prop);
if (prop=="children"){
str = str + "name: "+ prop + ",";
treesCopy = treesCopy[prop][0];
// console.log('New tree: ',treesCopy);
return str + Traverse(treesCopy);
}
str = str + "name: "+ prop +" value: " + treesCopy[prop]+",";
}
return str;
};
const str = Traverse(treesCopy);
return(
<>
{
str ? str.split(",").map(place => <p> {place} </p>)
: ""
}
</>
)
}

Exporting jasmine test results in json format from grunt

I am using Jasmine to execute the tests from the Grunt task. I want to output the results from the test cases in JSON. Below is the configuration for the jasmine. This configuration generates XML files under junit folder.
var conf = {
src: [
// '../../../Test.UnitTest.JS/UnitTests/' + name + '/**/*.js'
],
options: {
template: require('grunt-template-jasmine-requirejs'),
templateOptions: {
requireConfig: {
baseUrl: 'SinglePageApplications/' + name,
//waitSeconds: 30,
paths: mixIn({
'knockout-editables': '../../Assets/scripts/vendor/ko.editables-0.9.0',
'knockout-validation': '../../Assets/scripts/vendor/knockout.validation-1.0.2',
'bignumber': '../../Assets/scripts/vendor/bignumber-1.4.1',
'testutils': '../../../Test.UnitTest.JS/Utils',
'shared': '../../Legacy/Shared',
'testdata': '../../../Test.UnitTest.JS/UnitTests/' + name + '/testdata'
}, addConfigurationPaths(app))
}
},
helpers: [
'Assets/scripts/ato/helperscript.js'
],
specs: [
'../Test.UnitTest.JS/UnitTests/' + name + '/**/*.js'
],
junit: {
path: 'build/junit/' + name + '/'
},
timeout: 100000,
vendor: arr
}
,
//specs : 'src/test/js/unit-headless.html',
phantomjs: {
'ignore-ssl-errors': true
}
}
I want the results to be displayed in JSON format so I installed jasmine-json-test-reporter using npm and tried implemented it in my current config like this:
var conf = {
src: [
// '../../../Test.UnitTest.JS/UnitTests/' + name + '/**/*.js'
],
options: {
template: require('grunt-template-jasmine-requirejs'),
templateOptions: {
requireConfig: {
baseUrl: 'SinglePageApplications/' + name,
//waitSeconds: 30,
paths: mixIn({
'knockout-editables': '../../Assets/scripts/vendor/ko.editables-0.9.0',
'knockout-validation': '../../Assets/scripts/vendor/knockout.validation-1.0.2',
'bignumber': '../../Assets/scripts/vendor/bignumber-1.4.1',
'testutils': '../../../Test.UnitTest.JS/Utils',
'shared': '../../Legacy/Shared',
'testdata': '../../../Test.UnitTest.JS/UnitTests/' + name + '/testdata'
}, addConfigurationPaths(app))
}
},
helpers: [
'Assets/scripts/ato/helperscript.js'
//'Legacy/Shared/common/constants.js'
],
specs: [
//'../Test.UnitTest.JS/UnitTests/' + name + '/common/*.js',
//'../Test.UnitTest.JS/UnitTests/' + name + '/testdata',
'../Test.UnitTest.JS/UnitTests/' + name + '/**/*.js'
],
junit: {
path: 'build/junit/' + name + '/'
},
timeout: 100000,
vendor: arr
}
,
//specs : 'src/test/js/unit-headless.html',
phantomjs: {
'ignore-ssl-errors': true
},
onPrepare: function () {
var JSONReporter = require('jasmine-json-test-reporter');
var jasmine = require('jasmine');
return browser.getProcessedConfig().then(function (config) {
browser.params['browsername'] = config.capabilities.browserName.toUpperCase();
browser.params['version'] = config.capabilities.version || 'latest stable';
browser.params['platform'] = config.capabilities.os + '-' + config.capabilities.os_version;
jasmine.getEnv().addReporter(new JSONReporter({
file: 'results/' + browser.params.platform + '-' + browser.params.version + '.' + browser.params.browsername + '.json',
beautify: true,
indentationLevel: 2 // used if beautify === true
}));
});
}
}
This code is not generating any json file. I am not too sure use jasmine-json-test-reporter with current jasmine config.
I manage to get it working. The source files were not point to the right locations. Changing the following lines fixed it:
src: [
'SinglePageApplications/' + name + '/common/**/*.js',
'SinglePageApplications/' + name + '/viewmodels/**/*.js',
'SinglePageApplications/' + name + '/views/**/*.js',
'SinglePageApplications/' + name + '/main.js'
],

Create a dynamic array for use in grunt concat

I need to concatenate a set files based on variables I have defined my package.json.
// package.json
...
"layouts": [
{
"page": "home",
"version": "a"
},
{
"page": "about",
"version": "a"
},
{
"page": "contact",
"version": "b"
}
]
...
In grunt I am then building these into a JSON array and pumping it into the src parameter in my grunt-concat-contrib task.
// gruntfile.js
...
var package = grunt.file.readJSON('package.json'),
targets = package.layouts,
paths = [];
for (var target = 0; target < targets.length; target++) {
paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
};
var paths = JSON.stringify(paths);
grunt.log.write(paths); // Writing this to console for debugging
grunt.initConfig({
concat: {
build: {
src: paths,
dest: 'mysite/Code.php',
options: {
separator: '?>\n\n'
}
}
}
});
...
My issue is that the paths variable is not working inside of the initConfig when it is assigned to JSON.stringify(paths).
If I manually input the array like the following that I copied from where I logged the paths variable to the console, it works!
var paths = ["layouts/home/a/*.php","layouts/about/a/*.php","layouts/contact/b/*.php"];
What am I missing?
Derp. I fixed it, I didn't need to JSON.stringify() the array.
Final working gruntfile is below:
// gruntfile.js
...
var package = grunt.file.readJSON('package.json'),
targets = package.layouts,
paths = [];
for (var target = 0; target < targets.length; target++) {
paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
};
grunt.initConfig({
concat: {
build: {
src: paths,
dest: 'mysite/Code.php',
options: {
separator: '?>\n\n'
}
}
}
});
...

django-rest pagination with angularjs

I have an angularjs app working nicely with django-rest but have hit an issue by introducing pagination. I have a restservice and controller as per the below
// restservices.js
// API call for all images in an event
services.factory('ImageEvent', function ($resource) {
return $resource(rest_api + '/rest/image/?event_id=:eventId&format=json', {}, {
query: { method:'GET', params:{eventId:''}, isArray:true}
})
});
// controllers.js
// all Images in an event
.controller('ImageEventCtrl', ['$scope', '$stateParams', 'ImageEvent', function($scope, $stateParams, ImageEvent) {
$scope.images = ImageEvent.query({eventId: $stateParams.eventId}, function(images) {
});
}])
this returns the following json
[
{
"id": 13,
"title": "01-IMG_4953.JPG",
},
{
"id": 14,
"title": "02-IMG_4975.JPG",
},
{
"id": 15,
"title": "03-IMG_4997.JPG",
}
]
However if I turn on django-rest pagination it returns the following json:
{
"count": 3,
"next": "/rest/image/?event_id=1&page=2",
"previous": null,
"results":
[
{
"id": 13,
"title": "01-IMG_4953.JPG",
},
{
"id": 14,
"title": "02-IMG_4975.JPG",
}
]
}
This change has caused the following console error and everything fails to work:
Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object
Changing the restservice to isArray:false has made no difference. Can my controller be re-written to cope with this and in a perfect world also expose the count, next and previous links?
Thanks
Angular-ui has a pagination directive that I've used with Django Rest Framework before.
http://angular-ui.github.io/bootstrap/#/pagination
To load only X amount of items at a time I have done the following below. Note that I'm using the pagination to recreate the django admin feature in angular.
if request.GET.get('page'):
# Get the page number
page = request.GET.get('page')
# How many items per page to display
per_page = data['admin_attrs']['list_per_page']
begin = (int(page) - 1) * per_page
end = begin + per_page
objects = MODEL.objects.all()[begin:end]
# Serializer for your corresponding itmes. This will grab the particular modelserializer
serializer = serializer_classes[MODEL._meta.object_name](
objects, fields=admin_attrs['list_display']
)
data['objects'] = serializer.data
return Response(data)
My angular code to keep track of page and also allow back button functionality and also update the URL:
modelDetails Factory gets generates the url with the correct page number from pagination
app.factory('modelDetails', function($http, $q){
data = {content: null}
var dataFactory = {}
dataFactory.getObjects = function (app, model, page){
var deferred = $q.defer()
$http.get('api/admin/' + app + '/' + model + '/?page=' + page)
.success(function(result) {
deferred.resolve(result);
});
return deferred.promise
};
return dataFactory
});
$scope.loadObjects = function () {
modelDetails.getObjects(app, model, $scope.currentPage)
.then(function (data){
$scope.headers = data.headers;
$scope.admin_attrs = data.admin_attrs;
blank = new Array()
list_display = data.admin_attrs.list_display
$scope.objects = convertObjects(data.objects, list_display)
$scope.numPerPage = data.admin_attrs.list_per_page
$scope.currentPage = $stateParams.p
$scope.maxSize = 20;
$scope.bigTotalItems = data.object_count;
$scope.numPages = Math.ceil(data.object_count / $scope.admin_attrs.list_per_page);
})
.then( function (data) {
$scope.$watch('currentPage + numPerPage', function(oldVal, newVal) {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
if(oldVal != newVal){
$location.search('p', $scope.currentPage)
}
$rootScope.$on('$locationChangeSuccess', function(event) {
$scope.currentPage = $location.search().p
modelDetails.getObjects(app, model, $scope.currentPage)
.then( function (data) {
// convertObjects just reorders my data in a way I want
$scope.objects = convertObjects(data.objects, list_display)
});
});
});
});
}

Read csv to object of object for d3 [datamaps]

I'm using datamaps and would like to be able to read the data from a csv file.
The data format that datamaps is expecting is the following:
var loadeddata = {
"JPN":{Rate:17.5,fillKey:"firstCat"},
"DNK":{Rate:16.6,fillKey:"secondCat"}
};
I would like to read a csv file of the following structure and transform it into the format that datamaps is expecting:
ISO, Rate, fillKey
JPN, 17.5, firstCat
DNK, 16.6, secondCat
My 'best attempt' was using the following code:
var csvloadeddata;
d3.csv("simpledata.csv", function (error, csv) {
if (error) return console.log("there was an error loading the csv: " + error);
console.log("there are " + csv.length + " elements in my csv set");
var nestFunction = d3.nest().key(function(d){return d.ISO;});
csvloadeddata = nestFunction.entries(
csv.map(function(d){
d.Rate = +d.Rate;
d.fillKey = d.fillKey;
return d;
})
);
console.log("there are " + csvloadeddata.length + " elements in my data");
});
But this code generates a variable 'csvloadeddata' that looks like this:
var csvloadeddata = [
{"key": "JPN", "values": { 0: {Rate:17.5, fillKey:"firstCat"}} },
{"key": "DNK", values : { 1: {Rate:16.6,fillKey:"secondCat"}} }
];
What am I doing wrong?
Found the answer myself. If somebody is interested – this is what I ended up using:
<script>
d3.csv("simpledata.csv", function(error, csvdata1) {
globalcsvdata1 = csvdata1;
for (var i=0;i<csvdata1.length;i++)
{
globalcsvdata1[ globalcsvdata1[i].ISO] = globalcsvdata1[i] ;
//console.log(globalcsvdata1[i]);
delete globalcsvdata1[i].ISO;
delete globalcsvdata1[i] ;
}
myMap.updateChoropleth(globalcsvdata1);
}
);
var myMap = new Datamap({
element: document.getElementById('map'),
scope: 'world',
geographyConfig: {
popupOnHover: true,
highlightOnHover: false
},
fills: {
'AA': '#1f77b4',
'BB': '#9467bd',
defaultFill: 'grey'
}
});
</script>
</body>
The csv has the following structure:
ISO,fillKey
RUS,AA
USA,BB
Here is a working example: http://www.explainingprogress.com/wp-content/uploads/datamaps/uploaded_gdpPerCapita2011_PWTrgdpe/gdpPerCapita2011_PWTrgdpe.html