Loop for urls and a nice result - dalekjs

The question is how can i do a loop and how can i have a nice result like
94 Urls are ok and this three are not working.
var urls = [
'http://www.testify/page1',
'http://www.testify/page2'
];
module.exports = {
'validate some url': function (test) {
test.open('http://www.testify/page1')
.wait(500)
.assert.title().is.not('Die Seite wurde leider nicht gefunden')
.assert.url('http://www.testify/page1', 'URL is as expected')
.assert.numberOfElements('.product').is.gt(0, 'There are more than 0 products')
.done();
},
};

great to see that you found an answer to that question yourself.
In case somebody stumbles upon this question again, this would be the code needed for your initial code snippet:
var urls = [
'http://www.testify/page1',
'http://www.testify/page2'
];
module.exports = {
'validate some url': function (test) {
urls.forEach(function (url) {
test.open(url)
.wait(500)
.assert.title().is.not('Die Seite wurde leider nicht gefunden')
.assert.url(url, 'URL is as expected')
.assert.numberOfElements('.product').is.gt(0, 'There are more than 0 products')
});
test.done();
}
};

module.exports = {
'A lot of screenshots': function (test) {
var resolutions = [{width: 1280, height: 1024}, {width: 1024, height: 768}, {width: 800, height: 600}];
var pages = ['http://facebook.com', 'http://twitter.com', 'http://dalekjs.com'];
resolutions.forEach(function (res) {
pages.forEach(function (page) {
test.open(page)
.resize(res)
.screenshot('pics/' + res.width + '_' + res.height + '_' + page.replace('http://', '') + '.png')
});
});
test.done();
}
}

Related

Api-Service and HTTP-Service in Angular 2

Im fairly new to Angular 2 and i have got a question.
In my "older" Angular 1 Webapps i had a "Api-Service" and a "Http-Service" every time.
They looked like this:
"ApiService":
angular.module('ionicApp.apiServices', [])
.service('apiService', function(httpService) {
return {
getProfile: function(){
return httpService.async('get', 'profile', {}, {}, {});
},
addSkills: function(skillList) {
var url = 'profile/skills';
return httpService.async('post', url, {}, {}, skillList);
}
}
HTTP-Service:
angular.module('ionicApp.httpService', [])
.service('httpService', function ($http, $rootScope, $state, $ionicLoading, $ionicHistory) {
var httpCall = {
async : function (method, url, header, params, data) {
// Setze den X-AUTH-TOKEN in den Header, welcher für die Authentifizierung des Users verantwortlich ist
if (url != 'login' || url != 'user/registerApp' || url != 'view/cities' || url != 'view/occupationals' || url != 'view/industries') {
header['X-AUTH-TOKEN'] = $rootScope.userToken;
}
header['Access-Control-Allow-Origin'] = '*';
// $http returns a promise, which has a then function, which also returns a promise
var promise = $http({
method : method,
url : ipurl + url,
headers : header,
params : params,
data : data,
timeout: 10000,
withCredentials : true
}).then(function successCallback(response) {
if (url != 'user/registerApp' || url != 'view/cities' || url != 'view/occupationals' || url != 'view/industries') {
$rootScope.userToken = response.headers('X-AUTH-TOKEN');
}
return response;
}, function errorCallback(response) {
if (response.status === 401) {
$rootScope.isFailure = true;
$rootScope.failure = "Sie haben keine gültige Session mehr. Bitte loggen Sie sich erneut ein.";
doLogout();
} else {
return response;
}
});
// Return the promise to the controller
return promise;
},
doLogout : doLogout
};
return httpCall;
});
Ok, now my question is, how can i do this with angular 2?
I already did an Api-Service and an HTTP-Service (both are Injectables), and injected them in each component.
But what´s the trick to get them functional?
Thanks so much!

How can I pipe the output from gulp-w3c-css to the console

When I follow the examples for gulp-w3c-css I am unable to get the results to print in the console instead of in an output directory.
Compare how I am using CSSLint and W3C-CSS below. I'd like the function to be identical.
var gulp = require('gulp'),
csslint = require('gulp-csslint'),
cssvalidate = require('gulp-w3c-css');
gulp.task('csslint', () =>
gulp.src('testcss/laxhjalpen.css')
.pipe(csslint('.csslintrc'))
.pipe(csslint.reporter())
);
// Does not work
gulp.task('cssvalid', () =>
gulp.src('testcss/*css')
.pipe(cssvalidate())
// Next line works but is not what I want
.pipe(gulp.dest('reports'))
// I suppose I need to get this construct to work but I can't
.pipe(gutil.buffer(function(err, files) {
if (err) {
gutil.log('An error occured', err);
} else {
// No idea what to write
// files - array of validation results (from manual)
}
}))
);
The very best solution would be just to have a reporter function that works like the csslint.reporter does.
The gulp-w3c-css plugin serializes the validation results for each file to JSON and stores that JSON in the file.contents property. The format of that JSON serialization looks roughly like the following (for more details see the w3c-css documentation):
{
errors: [ { line: 5, message: 'Some error' },
{ line: 42, message: 'Some error' } ],
warnings: [ { line: 13, message: 'Some warning' },
{ line: 23, message: 'Some warning' } ]
}
So all you have to do is parse that JSON and then log the information to the console in any way you want.
Here's a simple example of how you could do it:
var gulp = require('gulp');
var cssvalidate = require('gulp-w3c-css');
var gutil = require('gulp-util');
var map = require('map-stream');
gulp.task('cssvalid', function () {
return gulp.src('testcss/*css')
.pipe(cssvalidate())
.pipe(map(function(file, done) {
if (file.contents.length == 0) {
console.log('Success: ' + file.path);
console.log(gutil.colors.green('No errors or warnings\n'));
} else {
var results = JSON.parse(file.contents.toString());
results.errors.forEach(function(error) {
console.log('Error: ' + file.path + ': line ' + error.line);
console.log(gutil.colors.red(error.message) + '\n');
});
results.warnings.forEach(function(warning) {
console.log('Warning: ' + file.path + ': line ' + warning.line);
console.log(gutil.colors.yellow(warning.message) + '\n');
});
}
done(null, file);
}));
});
I used map-stream instead of gutil.buffer() so that the results for each file are printed as soon as they are available instead of printing everything at the very end.

How to access image src nativescript

How can I get photo src, from nativescript camera module?
public takePicture() {
cameraModule.takePicture().then(function(picture) {
console.log("Result is an image source instance");
var image = new imageModule.Image();
image.imageSource = picture;
console.dir(picture);
});
}
console.dir output:
=== dump(): dumping members ===
{
"android": {
"constructor": "constructor()function () { [native code] }"
}
}
=== dump(): dumping function and properties names ===
loadFromResource()
fromResource()
loadFromFile()
fromFile()
loadFromData()
fromData()
loadFromBase64()
fromBase64()
setNativeSource()
saveToFile()
height: 480
width: 640
=== dump(): finished ===
How do I get the image src ?
I want to upload it to firebase, so i need the src.
To upload to firebase, you need to upload the image via its path:
let imgsrc = this.imageSource.fromNativeSource(data);
let path = this.utils.documentsPath(randomName);
imgsrc.saveToFile(path, this.enums.ImageFormat.png);
this.firebase.uploadFile(path).then((uploadedFile: any) => {
this.appSettings.setString("fileName", uploadedFile.name);
this.router.navigate(['/soundcloud']);
this.LoadingIndicator.hide();
}, (error: any) => {
alert("File upload error: " + error);
});
}, (err: any) => {
alert(err);
});
Figured it out, this works:
public takePicture() {
cameraModule.takePicture().then((picture) => {
var image = new imageModule.Image();
image.imageSource = picture;
let savePath = fs.knownFolders.documents().path;
let fileName = 'img_' + new Date().getTime() + '_' + this.currentUserId.getValue() + '.' + enumsModule.ImageFormat.jpeg;
let filePath = fs.path.join( savePath, fileName );
picture.saveToFile(filePath, enumsModule.ImageFormat.jpeg);
this.photoService.uploadImage(filePath, fileName).then((data) => {
this._router.navigate(["/upload", fileName, this.currentUserId.getValue()]);
});
});
}

httpParamSerializerJQLike in angular2?

How to serialize JSON for Ruby API?
Angular 1
$scope.submitForm = function() {
var data = {"contato": $scope.contato, "id":$scope.contato.id, "_method":'PUT'};
$http.post(
'http://myApi/contatos/' + $scope.contato.id,
**$httpParamSerializerJQLike(data)**,
{
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
datatype: "JSONP"
}).then(function successCallback(response) {
modalContato.show();
setTimeout(function (){
modalContato.hide();
$state.go('contato-detalhe', {"id":$scope.contato.id});
}, 1500);
});
};
Angular2:
insertContato(contato: Contato) {
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
let options = new RequestOptions({ headers: headers });
this._http
.post(this.urlApi + '/contatos', JSON.stringify(contato), options)
.subscribe(data => {
console.log('Funciona: ' + data.text());
}, error => {
console.log('Erro: ' + error.text())
});
}
"JSON.stringify(contato)"
It does not have the same behavior as $httpParamSerializerJQLike(data).
Json's broken in the server...
Started POST "/contatos" for 127.0.0.1 at 2016-04-13 13:25:55 -0300
Processing by ContatosController#create as HTML
Parameters: {"{\"nome\":\"asd\",\"email\":\"asd#asda.com\",\"telefone\":\"123\"}"=>nil}
Completed 400 Bad Request in 4ms (ActiveRecord: 0.0ms)
Correct is:
Started POST "/contatos" for 127.0.0.1 at 2016-04-12 17:00:24 -0300
Processing by ContatosController#create as JSON
Parameters: {"contato"=>{"nome"=>"felipe", "telefone"=>"5555"}}
Completed 200 OK in 278ms (Views: 0.1ms | ActiveRecord: 229.4ms)
I had a similar problem, i can solve this:
import { Headers, Http, Response, URLSearchParams, RequestOptions } from '#angular/http';
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*'});
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
body.set("message", JSON.stringify(m_dataRequest));
body.set("webService", "authService");
return this.http
.post(this.Url, body.toString(), options)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
URLSearchParams normalized the params of the form and the pipes dimiss, this work for me.
I hope this solve your problem.
I'm going to preface this by saying that this may not be the best way to handle this, but it's how I took care of the problem for myself (The Angular 2 docs don't seem to mention x-www-form-urlencoded anywhere).
So if your data is set up like
var data = {"contato": $scope.contato, "id":$scope.contato.id, "_method":'PUT'};
You want to basically convert it to a form yourself.
var encodedData = "contato=" + contato + "&id=" + contato.id + "&_method=PUT";
then you can modify your POST request to look like this
this._http
.post(this.urlApi + '/contatos', encodedData, options)
.subscribe(data => {
console.log('Funciona: ' + data.text());
}, error => {
console.log('Erro: ' + error.text())
});
There's no need to JSON.stringify it since you're not passing json, you're passing form data.
I hope this helps.
I wrote a function in my http.ts provider like so ---
private formatData(data){
let returnData = '';
console.log(data);
let count = 0;
for (let i in data){
if(count == 0){
returnData += i+'='+data[i];
}else{
returnData += '&'+i+'='+data[i];
}
count = count + 1;
console.log(returnData);
}
return returnData;
}
Call it like this.
post('localhost/url',data){
data = this.formatData(data);
}
Just copy the relative codes from angularjs http module
import {
isArray,
forEach,
isObject,
isDate,
isFunction,
isUndefined,
isNumber,
} from 'lodash';
function toJsonReplacer(key, value) {
let val = value;
if (
typeof key === 'string' &&
key.charAt(0) === '$' &&
key.charAt(1) === '$'
) {
val = undefined;
}
return val;
}
function toJson(obj, pretty = undefined) {
if (isUndefined(obj)) return undefined;
if (!isNumber(pretty)) {
pretty = pretty ? 2 : null; // tslint:disable-line no-parameter-reassignment
}
return JSON.stringify(obj, toJsonReplacer, pretty);
}
function serializeValue(v) {
if (isObject(v)) {
return isDate(v) ? v.toISOString() : toJson(v);
}
return v;
}
function forEachSorted(obj, iterator, context = null) {
const keys = Object.keys(obj).sort();
for (let i = 0; i < keys.length; i += 1) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "#"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces = undefined) {
return encodeURIComponent(val)
.replace(/%40/gi, '#')
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%3B/gi, ';')
.replace(/%20/g, pctEncodeSpaces ? '%20' : '+');
}
export function jQueryLikeParamSerializer(params) {
if (!params) return '';
const parts = [];
serialize(params, '', true);
return parts.join('&');
function serialize(toSerialize, prefix, topLevel = undefined) {
if (isArray(toSerialize)) {
forEach(toSerialize, (value, index) => {
serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
});
} else if (isObject(toSerialize) && !isDate(toSerialize)) {
forEachSorted(toSerialize, (value, key) => {
serialize(
value,
prefix + (topLevel ? '' : '[') + key + (topLevel ? '' : ']'),
);
});
} else {
if (isFunction(toSerialize)) {
toSerialize = toSerialize(); // tslint:disable-line no-parameter-reassignment
}
parts.push(
encodeUriQuery(prefix) +
'=' +
(toSerialize == null
? ''
: encodeUriQuery(serializeValue(toSerialize))),
);
}
}
}
I've met the similar issue when was upgrading from angular 1.x
Here is my solution which also process nested JSON objects:
function Json2FormEncoded(json_obj) {
let path = arguments[1] || '';
let s = '', p = '';
for (let i in json_obj) {
p = path == '' ? i : path + '[' + i + ']';
s = s ? s + "&" : s;
if (typeof json_obj[i] == 'object') {
s += Json2FormEncoded(json_obj[i], p);
} else {
s += p + '=' + encodeURIComponent(json_obj[i]);
}
}
return s;
}
Hope you'll find it useful!
Also check it here

Phantomjs doesn't render footers with a custom styles

I have the following example:
var page = require('webpage').create(),
system = require('system');
if (system.args.length < 3) {
console.log('Usage: printheaderfooter.js URL filename');
phantom.exit(1);
} else {
var address = system.args[1];
var output = system.args[2];
page.viewportSize = { width: 600, height: 600 };
page.paperSize = {
format: 'A4',
margin: "1cm"
footer: {
height: "1cm",
contents: phantom.callback(function(pageNum, numPages) {
if (pageNum == numPages) {
return "";
}
return "<h1 class='footer_style'>Footer" + pageNum + " / " + numPages + "</h1>";
})
}
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
}
In the example above I use footer_style class that look likes in my css file the following:
.footer_style {
text-align:right;
}
But unfortunately that dosen't works. I'm trying to create pdf file such as follows:
./phantomjs rasterize.js index.html test.pdf
We know that classes do not work but inline styles do. What we can do is replace the class with the computed style.
Here is a function that will take a piece of html, create a temporary element in the body with the html, compute the style for each element with a class, add the computed style inline and return the new html.
function replaceClassWithStyle(html) {
return page.evaluate(function(html) {
var host = document.createElement('div');
host.innerHTML = html;
document.body.appendChild(host); // if not appended, values will be blank
var elements = host.getElementsByTagName('*');
for (var i in elements) {
if (elements[i].className) {
elements[i].setAttribute('style', window.getComputedStyle(elements[i], null).cssText);
}
}
document.body.removeChild(host);
return host.innerHTML;
}, html);
}
Then simply call this function in your footer:
page.paperSize = {
footer: {
contents: phantom.callback(function(pageNum, numPages) {
if (pageNum == numPages) {
return "";
}
return replaceClassWithStyle("<h1 class='footer_style'>Footer" + pageNum + " / " + numPages + "</h1>");
})
}
};
You will need to move all this inside page.open().
I tested it and the footer is aligned to the right.
I have an update to mak's excellent answer for PhantomJS 1.9.7.
This version fixes:
Circumvent bug which 'blank's the parent document (PhantomJS 1.9.7)
Style mixups when styles are nested (do depth-first traversal instead)
Also works when tags do not have classes
/**
* Place HTML in the parent document, convert CSS styles to fixed computed style declarations, and return HTML.
* (required for headers/footers, which exist outside of the HTML document, and have trouble getting styling otherwise)
*/
function replaceCssWithComputedStyle(html) {
return page.evaluate(function(html) {
var host = document.createElement('div');
host.setAttribute('style', 'display:none;'); // Silly hack, or PhantomJS will 'blank' the main document for some reason
host.innerHTML = html;
// Append to get styling of parent page
document.body.appendChild(host);
var elements = host.getElementsByTagName('*');
// Iterate in reverse order (depth first) so that styles do not impact eachother
for (var i = elements.length - 1; i >= 0; i--) {
elements[i].setAttribute('style', window.getComputedStyle(elements[i], null).cssText);
}
// Remove from parent page again, so we're clean
document.body.removeChild(host);
return host.innerHTML;
}, html);
}
From my past experience, phantomjs does not support styles in custom header/footer.
The only solution that I found is to apply an inline style like this :
var page = require('webpage').create(),
system = require('system');
if (system.args.length < 3) {
console.log('Usage: printheaderfooter.js URL filename');
phantom.exit(1);
} else {
var address = system.args[1];
var output = system.args[2];
page.viewportSize = { width: 600, height: 600 };
page.paperSize = {
format: 'A4',
margin: "1cm",
footer: {
height: "1cm",
contents: phantom.callback(function(pageNum, numPages) {
return "<h1 style='text-align:right'>Footer" + pageNum + " / " + numPages + "</h1>";
})
}
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
}
Note : A comma is missing in your code after margin: "1cm"

Resources