Alexa (Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined') - json

My code is not working when I test it in Amazon Developer and I don't see anything wrong with my code. It says my response is invalid.
Here's the code I tried to run but failed(I ran one response but not the other):
var Alexa = require('alexa-sdk');
exports.handler = function(event, context, callback) {
var alexa = Alexa.handler(event, context);
// alexa.dynamoDBTableName = 'YourTableName'; // creates new table for userid:session.attributes
alexa.registerHandlers(handlers);
alexa.execute();
};
var handlers = {
'LaunchRequest': function () {
this.emit('WelcomeIntent');
},
'WelcomeIntent': function () {
this.emit(':ask', 'Welcome to the guessing game! What difficulty would you like to play? Easy, Medium, or Hard?');
},
//------------------------------------------------------------------------------------------------------------------------------------------------
'DifficultyIntent': function (){
var difficulty = this.event.request.intent.slots.difficulty.value;
var range = 10; this.attributes['RandomNumberEnd'] = range;
if (difficulty === 'easy')
{ range = 10;
this.emit[':ask Your range is 1 - ' + range]
}
else if (difficulty === 'medium')
{ range = 100;
this.emit[':ask Your range is 1 - ' + range]
}
else (difficulty === 'hard');
{ range = 1000;
this.emit[':ask Your range is 1 - ' + range]
}
var randomNumber = Math.floor((Math.random()*range)+1);
var rightAnswer = this.attributes['rightAnswer'] = rightAnswer;
}, //check the user's guess with the right answer
'UserGuessIntent': function (){
var guess = this.event.request.intent.slots.guess.value;
this.attributes['guess'] = guess;
this.emit('CheckIntent'); },
'CheckIntent': function (){
var guess = this.attributes['guess'];
this.attributes['rightAnswer'] = randomNumber;
if(guess < rightAnswer){
this.emit(':ask', 'Try Again! Guess higher!');
}
else if(guess > rightAnswer)
{this.emit(':ask', 'Try Again! Guess lower!');
}
else{
this.emit(':tell', 'You are correct! Congratulations!');
}
},
'QuitIntent': function(){
var stop = this.event.request.intent.slots.stop.value;
this.emit('AMAZON.StopIntent');
},
'AMAZON.StopIntent' : function(){
var rightAnswer = this.attributes['rightAnswer'];
this.emit(':tell', 'The right answer is ' + rightAnswer + '. Goodbye!');
}
};

Related

find all label and product in json python

I'm trying to find all label and product in text/javascript, but I don't have any idea to how do it. I'm trying to parse label, id and products.
var spConfigDisabledProducts = [-1
, '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078' ];
var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
jQuery("#attribute959 option").each(function () {
var option = jQuery(this);
var id = option.attr('value');
jQuery.each(spConfig.config.attributes, function () {
jQuery.each(this.options, function () {
if (this.id == id) {
if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
option.data('disabled', true);
}
}
});
});
});
It's possible to do that less elegantly but without regex - just a series of splits and clean ups:
import json
code = [your script above]
code2 = html.replace('½','').split('":"Taglia","options":[{')[1].split('}]}},"template"')[0].split('},{')
for i in range(len(code2)):
data = json.loads('{'+code2[i]+'}')
print(data['id'],data['label'])
Output:
730 36
731 37
732 38
733 38
etc.
You can regex out javascript object and pass to json then parse out info
import re
import json
#html = response.content from requests
html = '''
var spConfigDisabledProducts = [-1
, '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078' ];
var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
jQuery("#attribute959 option").each(function () {
var option = jQuery(this);
var id = option.attr('value');
jQuery.each(spConfig.config.attributes, function () {
jQuery.each(this.options, function () {
if (this.id == id) {
if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
option.data('disabled', true);
}
}
});
});
});'''
p = re.compile(r'Product\.Config\((.*?)\)', re.DOTALL)
data = json.loads(p.findall(html)[0])
for attribute in data['attributes']:
print('-----------------attribute--------------')
print('label = ' + data['attributes'][attribute]['label'], 'id = ' + data['attributes'][attribute]['id'])
print('-----------------options----------------')
for product in data['attributes'][attribute]['options']:
print('label = ' + product['label'], 'id = ' + product['id'], 'product = ' + product['products'][0])

Sorting BIM 360Issues through Forge

So I am working on this sample of forge: https://github.com/Autodesk-Forge/bim360-csharp-issues
I am struggling to sort the issues portrayed within the PropertyPanel. I am asking how I should go about doing this as I'm unsure?
Currently the sample loads your BIM36O document with the viewer, on the viewer there is an extension which when clicked shows all the issues one by one.
These issues are currently sorted by (Issue1,Issue2,Issue3).
I have manually used this line of code to sort the issues before they're shown on the panel:
_this.issues = _.sortBy(_this.issues, function (i) { return i.attributes.title });
I have also introduced panel buttons with onclick events, how do I sort the issues once the button is clicked and reshow the now sorted issues on the panel?
Here is my code for the panel:
function BIM360IssuePanel(viewer, container, id, title, options) {
this.viewer = viewer;
Autodesk.Viewing.UI.PropertyPanel.call(this, container, id, title, options);
var _this = this;
this.scrollContainer.style.height = 'calc(100% - 100px)';
const controlsContainer = document.createElement('div');
controlsContainer.classList.add('docking-panel-container-solid-color-a');
controlsContainer.style.height = '30px';
controlsContainer.style.padding = '4px';
const titleButton = document.createElement('button');
const assignedToButton = document.createElement('button');
const dueDateButton = document.createElement('button');
const createdAtButton = document.createElement('button');
const versionButton = document.createElement('button');
titleButton.innerText = 'Title';
versionButton.innerText = 'Version';
assignedToButton.innerText = 'Assigned To';
dueDateButton.innerText = 'Due Date';
createdAtButton.innerText = 'Created At';
titleButton.style.color = 'black';
versionButton.style.color = 'black';
assignedToButton.style.color = 'black';
dueDateButton.style.color = 'black';
createdAtButton.style.color = 'black';
controlsContainer.appendChild(titleButton);
controlsContainer.appendChild(versionButton);
controlsContainer.appendChild(assignedToButton);
controlsContainer.appendChild(dueDateButton);
controlsContainer.appendChild(createdAtButton);
this.container.appendChild(controlsContainer);
assignedToButton.onclick = function (e) {
};
titleButton.onclick = function (e) {
};
createdAtButton.onclick = function (e) {
};
dueDateButton.onclick = function (e) {
};
versionButton.onclick = function (e) {
};
}
Code for showIssues():
BIM360IssueExtension.prototype.showIssues = function () {
var _this = this;
//remove the list of last time
var pushPinExtension = _this.viewer.getExtension(_this.pushPinExtensionName);
pushPinExtension.removeAllItems();
pushPinExtension.showAll();
var selected = getSelectedNode();
//sorting issues
_this.issues = _.sortBy(_this.issues, function (i) { return i.attributes.title });
//_this.issues = _.sortBy(_this.issues, function (i) { if (i.attributes.due_date === null) return ''; else return Date.parse(i.attributes.due_date) });
//_this.issues = _.sortBy(_this.issues, function (i) { return i.attributes.assigned_to_name });
//_this.issues = _.sortBy(_this.issues, function (i) { return i.attributes.starting_version });
// _this.issues = _.sortBy(_this.issues, function (i) { return i.attributes.dateCreated });
_this.issues.forEach(function (issue) {
var dateCreated = moment(issue.attributes.created_at);
// show issue on panel
if (_this.panel) {
_this.panel.addProperty('Title', issue.attributes.title, 'Issue ' + issue.attributes.identifier);
_this.panel.addProperty('Assigned to', issue.attributes.assigned_to_name, 'Issue ' + issue.attributes.identifier);
_this.panel.addProperty('Version', 'V' + issue.attributes.starting_version + (selected.version != issue.attributes.starting_version ? ' (Not current)' : ''), 'Issue ' + issue.attributes.identifier)
_this.panel.addProperty('Due Date', issue.attributes.due_date, 'Issue ' + issue.attributes.identifier);
_this.panel.addProperty('Created at', dateCreated.format('MMMM Do YYYY, h:mm a'), 'Issue ' + issue.attributes.identifier);
}
// add the pushpin
var issueAttributes = issue.attributes;
var pushpinAttributes = issue.attributes.pushpin_attributes;
if (pushpinAttributes) {
issue.type = issue.type.replace('quality_', ''); // temp fix during issues > quality_issues migration
pushPinExtension.createItem({
id: issue.id,
label: issueAttributes.identifier,
status: issue.type && issueAttributes.status.indexOf(issue.type) === -1 ? `${issue.type}-${issueAttributes.status}` : issueAttributes.status,
position: pushpinAttributes.location,
type: issue.type,
objectId: pushpinAttributes.object_id,
viewerState: pushpinAttributes.viewer_state
});
}
})
}
Just did a quick check with the source code, there are 2 quick ideas:
If there would be some updates to issues while clicking the sort button, I would suggest to add a status of current sort order(sortOrder), and sorting the issues with different ways depending on sortOrder in the method showIssues, while clicking the different sort buttons, you may just call the BIM360IssueExtension.prototype.loadIssues() method to refresh all the issues in panel.
If the issue list would not be updated while clicking the sort button, I would suggest to cache the current issue list, and add a new method like sortIssueInPanel() to sort button, the main steps should be cleaning up the Issue Panel, sort the cached issue list, and add these issues one by one to the Issue Panel, the sample code snip should be something as follow, but be noted that's just code snip to show the main steps, i did not test or verify it, just for your reference:
var sortIssueInPanel = function(sortOrder){
var issueExtension = NOP_VIEWER.getExtension('BIM360IssueExtension');
issueExtension.panel.removeAllProperties()
// Sort the cached issues by sortOrder
switch(sortOrder){
case SORT_ORDER.BY_TITLE:
issuesCached = _.sortBy(issuesCached, function (i) { return i.attributes.title });
break;
case SORT_ORDER.BY_DUE_DATE:
issuesCached = _.sortBy(issuesCached, function (i) { if (i.attributes.due_date === null) return ''; else return Date.parse(i.attributes.due_date) });
break;
case SORT_ORDER.BY_ASSIGNED_TO_NAME:
issuesCached = _.sortBy(issuesCached, function (i) { return i.attributes.assigned_to_name });
break;
case SORT_ORDER.BY_DATECREATED:
issuesCached = _.sortBy(issuesCached, function (i) { return i.attributes.dateCreated });
break;
default:
break;
}
issuesCached.forEach(function (issue) {
var dateCreated = moment(issue.attributes.created_at);
// show issue on panel
if (issueExtension.panel) {
issueExtension.panel.addProperty('Title', issue.attributes.title, 'Issue ' + issue.attributes.identifier);
issueExtension.panel.addProperty('Assigned to', issue.attributes.assigned_to_name, 'Issue ' + issue.attributes.identifier);
issueExtension.panel.addProperty('Version', 'V' + issue.attributes.starting_version + (selected.version != issue.attributes.starting_version ? ' (Not current)' : ''), 'Issue ' + issue.attributes.identifier)
issueExtension.panel.addProperty('Due Date', issue.attributes.due_date, 'Issue ' + issue.attributes.identifier);
issueExtension.panel.addProperty('Created at', dateCreated.format('MMMM Do YYYY, h:mm a'), 'Issue ' + issue.attributes.identifier);
}
})
};
Hope it helps.

Funky IE JSON conversions

When running our AngularJS app in IE11 everything looks great in the debugger, but when our app encodes the data as JSON to save to our database, we get bad results.
Our app obtains a record from our database, then some manipulation is done and then the data is saved back to the server from another model.
Here is the data I got back from the server in the setAttendanceGetSInfo() function below:
{"data":{"Start":"2014-10-16T19:36:00Z","End":"2014-10-16T19:37:00Z"},
This is the code used to "convert the data" to 3 properties in our model:
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: new Date(e).toLocaleDateString(),
examStartTime: (new Date(e)).toLocaleTimeString(),
examEndTime: (new Date(f)).toLocaleTimeString()
});
return result.sInfo;
});
};
fromISO is defined as:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Take a look at the screenshot of the event model data:
But, if I eval the event model using JSON.stringify(model.event), I get this:
{\"examDate\":\"?10?/?16?/?2014\",\"examStartTime\":\"?2?:?44?:?00? ?PM\",\"examEndTime\":\"?2?:?44?:?00? ?PM\"}
And this is the JSON encoded data that actually got stored on the DB:
"examDate":"¿10¿/¿16¿/¿2014","examStartTime":"¿2¿:¿36¿:¿00¿ ¿PM","examEndTime":"¿2¿:¿37¿:¿00¿ ¿PM"
What is wrong here and how can I fix this? It works exactly as designed in Chrome and Firefox. I have not yet tested on Safari or earlier versions of IE.
The toJSON for the date class isn't defined perfectly the same for all browsers.
(You can see a related question here: Discrepancy in JSON.stringify of date values in different browsers
I would suspect that you have a custom toJSON added to the Date prototype since your date string doesn't match the standard and that is likely where your issue is. Alternatively, you can use the Date toJSON recommended in the above post to solve your issues.
First, I modified the fromISO prototype to this:
(function () {
var D = new Date('2011-06-02T09:34:29+02:00');
if (!D || +D !== 1307000069000) {
Date.fromISO = function (s) {
var D, M = [], hm, min = 0, d2,
Rx = /([\d:]+)(\.\d+)?(Z|(([+\-])(\d\d):(\d\d))?)?$/;
D = s.substring(0, 10).split('-');
if (s.length > 11) {
M = s.substring(11).match(Rx) || [];
if (M[1]) D = D.concat(M[1].split(':'));
if (M[2]) D.push(Math.round(M[2] * 1000));// msec
}
for (var i = 0, L = D.length; i < L; i++) {
D[i] = parseInt(D[i], 10);
}
D[1] -= 1;
while (D.length < 6) D.push(0);
if (M[4]) {
min = parseInt(M[6]) * 60 + parseInt(M[7], 10);// timezone not UTC
if (M[5] == '+') min *= -1;
}
try {
d2 = Date.fromUTCArray(D);
if (min) d2.setUTCMinutes(d2.getUTCMinutes() + min);
}
catch (er) {
// bad input
}
return d2;
}
}
else {
Date.fromISO = function (s) {
return new Date(s);
}
}
Date.fromUTCArray = function (A) {
var D = new Date;
while (A.length < 7) A.push(0);
var T = A.splice(3, A.length);
D.setUTCFullYear.apply(D, A);
D.setUTCHours.apply(D, T);
return D;
}
Date.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
})()
Then I added moment.js and formatted the dates when they get stored:
var SaveAffRow = function () {
// make sure dates on coursedate and event are correct.
var cd = model.a.courseDate;
var ed = model.event.examDate;
var est = model.event.examStartTime;
var eet = model.event.examEndTime;
model.a.courseDate = moment(cd).format("MM/DD/YYYY");
model.event.examDate = moment(ed).format("MM/DD/YYYY");
model.event.examStartTime = moment(est).format("MM/DD/YYYY hh:mm A");
model.event.examEndTime = moment(eet).format("MM/DD/YYYY hh:mm A");
affRow.DocumentsJson = angular.toJson({a: model.a, event: model.event});
var aff = {};
if (affRow.Id != 0)
aff = affRow.$update({ Id: affRow.Id });
else
aff = affRow.$save({ Id: affRow.Id });
return aff;
};
and when they get read (just in case they are messed up already):
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: moment(e).format("MM/DD/YYYY"),
examStartTime: moment(e).format("MM/DD/YYYY hh:mm A"),
examEndTime: moment(f).format("MM/DD/YYYY hh:mm A")
});
return result.sInfo;
});
};

How can I turn part of my casperjs script into a function so I can use it multiple times

Okay, so here is a part of my casperjs script below which works fine
if(casper.exists(ac1)){
var uel = "https://example.ws/send.html?f=1099817";
this.thenOpen(uel, function() {
casper.wait(10000, function() {
casper.then(function() {
this.evaluate(function() {
var amount = 0.29
var result = amount * 0.019
var result2 = result.toFixed(6);
var fresult = amount - result2;
var needed = fresult.toFixed(3);
document.getElementById('account').value = 'ydfg028';
document.getElementsByName('data')[0].value = needed;
});
this.click("input#sbt.button[type='submit']");
casper.wait(10000, function() {
casper.then(function() {
this.capture("filenadfgmedsfg.jpg");
var el2 = this.getHTML();
fs.write('results23.html', el2, 'w');
});
});
});
});
});
} else {
this.exit();
}
The problem I have is over 14 of the following statements
if(casper.exists()){
So what I am trying to do, is use the casperjs steps as a function. This is what I have tried below, but it just does nothing and casperjs ends when it reaches the function. Here's what I am trying
This is the casperjs function I have made
function casperstep(amount, user, location) {
var uel = "https://example.ws/send.html?f=" + location;
this.thenOpen(uel, function() {
casper.wait(10000, function() {
casper.then(function() {
this.evaluate(function() {
var result = amount * 0.019
var result2 = result.toFixed(6);
var fresult = amount - result2;
var needed = fresult.toFixed(3);
document.getElementById('account').value = user;
document.getElementsByName('data')[0].value = needed;
});
this.click("input#sbt.button[type='submit']");
casper.wait(10000, function() {
casper.then(function() {
this.capture("filenadfgmedsfg.jpg");
var el2 = this.getHTML();
fs.write('results23.html', el2, 'w');
});
});
});
});
});
}
Then when I try the following
if(casper.exists(ac1)){
casperstep(0.29, "username", "3245324");
}
it just does not work at all. The casper steps just do not fire. How can I fix this in theory? It should have worked.
What I have been trying with your answers...
My function
casper.captchaget = function (selector) {
var Loc = this.getHTML(selector, true).match(/src="(.*?)"/)[1];
var Ilocation = 'https://perfectmoney.is' + Loc;
var image = Loc;
var imagesplit = image.split ('?');
var split1 = imagesplit[1];
var string = split1 + ".jpg";
this.download(Ilocation, string);
}
and how I am trying to use it
casper.then(function(){
this.captchaget('img#cpt_img');//this.casperstep(0.29, "username", "3245324");
});
I tried the above to test out using casper extension.
Well, you want to add your own method to a casper object instance : http://casperjs.readthedocs.org/en/latest/extending.html
so :
casper.casperstep = function (amount, user, location) {
{your instructions....}
}
Then call it :
casper.start();
casper.then(function(){
if(casper.exists(ac1)){
casper.casperstep(0.29, "username", "3245324");//this.casperstep(0.29, "username", "3245324");
}
})
.run(function() {
test.done();
});
Old-monkey patching :)
To see other ways to do it : Custom casperjs modules

jquery cookies for different countries link

I am trying to do cookie stuff in jquery
but it not getting implemented can you guys fix my problem
html code
<a rel="en_CA" class="selectorCountries marginUnitedStates locale-link" href="http://www.teslamotors.com/en_CA">united states</a>
<a rel="en_US" class="selectorCountries marginSecondCountry locale-link" href="http://www.teslamotors.com/en_CA">canada</a>
<a rel="en_BE" class="selectorCountries marginCanadaFrench locale-link" href="http://www.teslamotors.com/en_BE">canada(french)</a>
i am providing my js code below
http://jsfiddle.net/SSMX4/76/
when i click the different country links in the pop up it should act similar to this site
http://www.teslamotors.com/it_CH
$('.locale-link').click(function(){
var desired_locale = $(this).attr('rel');
createCookie('desired-locale',desired_locale,360);
createCookie('buy_flow_locale',desired_locale,360);
closeSelector('disappear');
})
$('#locale_pop a.close').click(function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',3,360);
}
else if (show_blip_count < 3 ) {
eraseCookie('show_blip_count');
createCookie('show_blip_count',3,360);
}
$('#locale_pop').slideUp();
return false;
});
function checkCookie(){
var cookie_locale = readCookie('desired-locale');
var show_blip_count = readCookie('show_blip_count');
var tesla_locale = 'en_US'; //default to US
var path = window.location.pathname;
// debug.log("path = " + path);
var parsed_url = parseURL(window.location.href);
var path_array = parsed_url.segments;
var path_length = path_array.length
var locale_path_index = -1;
var locale_in_path = false;
var locales = ['en_AT', 'en_AU', 'en_BE', 'en_CA',
'en_CH', 'de_DE', 'en_DK', 'en_GB',
'en_HK', 'en_EU', 'jp', 'nl_NL',
'en_US', 'it_IT', 'fr_FR', 'no_NO']
// see if we are on a locale path
$.each(locales, function(index, value){
locale_path_index = $.inArray(value, path_array);
if (locale_path_index != -1) {
tesla_locale = value == 'jp' ? 'ja_JP':value;
locale_in_path = true;
}
});
// debug.log('tesla_locale = ' + tesla_locale);
cookie_locale = (cookie_locale == null || cookie_locale == 'null') ? false:cookie_locale;
// Only do the js redirect on the static homepage.
if ((path_length == 1) && (locale_in_path || path == '/')) {
debug.log("path in redirect section = " + path);
if (cookie_locale && (cookie_locale != tesla_locale)) {
// debug.log('Redirecting to cookie_locale...');
var path_base = '';
switch (cookie_locale){
case 'en_US':
path_base = path_length > 1 ? path_base:'/';
break;
case 'ja_JP':
path_base = '/jp'
break;
default:
path_base = '/' + cookie_locale;
}
path_array = locale_in_path != -1 ? path_array.slice(locale_in_path):path_array;
path_array.unshift(path_base);
window.location.href = path_array.join('/');
}
}
// only do the ajax call if we don't have a cookie
if (!cookie_locale) {
// debug.log('doing the cookie check for locale...')
cookie_locale = 'null';
var get_data = {cookie:cookie_locale, page:path, t_locale:tesla_locale};
var query_country_string = parsed_url.query != '' ? parsed_url.query.split('='):false;
var query_country = query_country_string ? (query_country_string.slice(0,1) == '?country' ? query_country_string.slice(-1):false):false;
if (query_country) {
get_data.query_country = query_country;
}
$.ajax({
url:'/check_locale',
data:get_data,
cache: false,
dataType: "json",
success: function(data){
var ip_locale = data.locale;
var market = data.market;
var new_locale_link = $('#locale_pop #locale_link');
if (data.show_blip && show_blip_count < 3) {
setTimeout(function(){
$('#locale_msg').text(data.locale_msg);
$('#locale_welcome').text(data.locale_welcome);
new_locale_link[0].href = data.new_path;
new_locale_link.text(data.locale_link);
new_locale_link.attr('rel', data.locale);
if (!new_locale_link.hasClass(data.locale)) {
new_locale_link.addClass(data.locale);
}
$('#locale_pop').slideDown('slow', function(){
var hide_blip = setTimeout(function(){
$('#locale_pop').slideUp('slow', function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',1,360);
}
else if (show_blip_count < 3 ) {
var b_count = show_blip_count;
b_count ++;
eraseCookie('show_blip_count');
createCookie('show_blip_count',b_count,360);
}
});
},10000);
$('#locale_pop').hover(function(){
clearTimeout(hide_blip);
},function(){
setTimeout(function(){$('#locale_pop').slideUp();},10000);
});
});
},1000);
}
}
});
}
This will help you ALOT!
jQuery Cookie Plugin
I use this all the time. Very simple to learn. Has all the necessary cookie functions built-in and allows you to use a tiny amount of code to create your cookies, delete them, make them expire, etc.
Let me know if you have any questions on how to use (although the DOCS have a decent amount of instruction).