Amend Javascript code to Print,Tab & enter - javascript

I'm very new to java script, and I have to amend this code to make a product work...If I can't, may end sending it back.
I've tried amending the code very basically.Changed Tab to Enter, and back again.
function processData (arrData)
{
var sData = DataToString(arrData);
Print("Data: " + sData);
if (!SendKeyStrokes (sData.replace(/\x00/g, " ") + "{TAB}"))
NotifyWarning("Ignoring keystrokes sent to TWedge. Please set focus to the target application.");
}
This will output the bar code and tab over to next cell.
I'm hoping its easy, but I would like to amend it to do..
Code,tab,Code,tab,Code,tab,Code,Tab,Code,ENTER

Related

Cannot write a right script for email alerts from google sheets

Try to write a script that will send the email alerts when a specific cell value appears. I have already put the following code:
function sendEmailAlert(w) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cellValue = ss.getActiveSheet().getActiveRange().getA1Notation();
var getColumn = ss.getActiveSheet().getActiveRange().getColumn();
var sheetname = ss.getActiveSheet().getName();
var user = Session.getActiveUser().getEmail();
var Toemail = 'xxxxxxx#xxxxx.com';
var subject = 'xxxxxxx';
var body = 'The status was updated in - ' + sheetname + ' by - ' + user + ' Now the status in '+ cellValue + ' is ' +ss.getActiveCell().getValue()+ ' check file- ' + ss.getUrl();
if (ss.getActiveCell().getValue() == "Accepted" && getColumn == 15 && w.source.getActiveSheet().getName() === "Analysis") {
MailApp.sendEmail(Toemail, subject, body);
}
}
This works only when you make a change in the certain cell manually. If the cell contains the formula that makes the cell to be updated automatically, the script does not send any alerts when a specific cell value appears.
For example
My trigger is number 30. When I type 30 in the cell the script send me an alert message. But when a formula is applied in this cell like =DAYS(A1; A2) where A1 = 10/6/2020 and A2 = 9/6/2020 the script doesn’t send me anything.
Please help me to solve this problem. Hope the issue is clear. Any questions let me know down below
P.S.
I am not a programmer so please add comments to your code to explain the code rows actions
The reason your trigger is not triggering is because onEdit() requires the edit of the cell to be made by a user. Since you are changing the value of the cell using a formula, the trigger won't fire.
You might want to rethink your code and/or choose other methods to trigger the sending of the email.
You can, for example, use a time driven trigger which runs at a time chosen by you and checks if any changes have been made to the cell and send the email. Even though, the change won't be notified as quick as the onEdit(), it's an option since you plan on using formulas for your script.
Reference
Simple Triggers Restrictions;
Time Driven Triggers.

Why is some of my code running before other ones?

So i was running my script and i was wondering why some of my code was running before eachother.
For example, i had a function, and i called it last, AFTER a message was supposed to be displayed. But instead it ran the function first THEN displayed the message.
Also, i was noticing with displaying messages, it would display in a random order each time. (Wierd Huh.)
I managed to fix some of this by creating a bunch of .this's, but i don't want to do that so much in the future as it makes code very confusing.
Here is a snippet of some of my code that this is happening to:
else if (input.startsWith('CALL')) {
//First
bot.sendMessage(message, ':arrow_right: Private Messaging You To Decrease Spam :arrow_left:');
//Second
bot.sendMessage(user.id, ':rotating_light: This feature is experimental. You may experience bugs/glitches when using it. :rotating_light: \n').then(() => getUser()); // << Third
var senderId = message.sender.id; // << Fourth
function getUser() {
try {
var userList = []
for (var user of bot.users) {
if (user.status == "online" && user.bot == false) {
userList.push(user)
}
}
bot.sendMessage(senderId, ':telephone: :arrow_right: Users Found That Meet Search Criteria: ' + userList.length + ' out of ' + bot.users.length + '.'); //Fifth
bot.sendMessage(message, ':telephone: :arrow_right: User Found: ' + userList[Math.floor(Math.random() * userList.length)]); //Sixth
} catch (err) {
bot.sendMessage(message, err)
}
console.log(userList);
console.log(userList.length);
}
}
The code works, it's just the order i was worried about.
Thanks in advance for the help :)
EDIT: I added comments to say what the order should be.
EDIT #2: Clarified Question: I was wondering how i would be able to make the code run in a certain order. And wait for a code prior to run first.
I assume bot.sendMessage makes a network request of some sort to some other system, and the issue you're observing is that those network requests seem to take effect in an unpredictable order. This makes sense, because you're not waiting for one request to finish before starting the next one.
Imagine you opened a web browser and opened two tabs to two different URLs at the same time. Which page would load first? That's basically what your code is doing.
Because I see a .then in one place, I'm going to further assume that bot.sendMessage returns a promise. So go ahead and use the promise to wait for the first request to finish before starting the next one.
Specifically, change this:
bot.sendMessage(senderId, ':telephone: :arrow_right: Users Found That Meet Search Criteria: ' + userList.length + ' out of ' + bot.users.length + '.');
bot.sendMessage(message, ':telephone: :arrow_right: User Found: ' + userList[Math.floor(Math.random() * userList.length)]);
to this:
bot.sendMessage(senderId, ':telephone: :arrow_right: Users Found That Meet Search Criteria: ' + userList.length + ' out of ' + bot.users.length + '.').then(() => {
bot.sendMessage(message, ':telephone: :arrow_right: User Found: ' + userList[Math.floor(Math.random() * userList.length)]);
});
(Ditto with your other messages that you want to happen in a certain order.)
the function you use to send the message runs asynchronously, so you must wait for the end of the first call before invoke the next one (and the rest of the code). smarx gave you a good example about what to do.

Reload page if error "IndexError: list index out of range" occures

I am scraping web pages and sometimes the age does not load correctly and the error occurs
IndexError: list index out of range
This is because with the page not loading correctly it does not have the index. reloading the page solves this.
Is there away to add in error handling so if page is not loaded and the error occurs... reload the page?
I have searched the internet and cannot find anything
for link in links:
#print('Fetching from link: ' + link)
browser.get('http://www.racingpost.com' + link)
time.sleep(5)
print('http://www.racingpost.com' + link)
tree = html.fromstring(browser.page_source)
#print(browser.page_source)
if count == 0:
browser.find_element_by_xpath("//*[#id='re_']/div[2]/a[1]").click()
browser.find_element_by_xpath("//*[#id='re_']/div[2]/a[2]").click()
count = count + 1
#first of all pull all the data about the event its self like going distance ect
title = tree.xpath('//*[#id="mainwrapper"]/div/div/div[2]/div[1]/div[2]/h3/text()[2]')
title = map(lambda x:x.strip(),title)
title = [x.strip(' ') for x in title]
details = tree.xpath('//*[#id="mainwrapper"]/div/div/div[2]/div[1]/div[2]/ul/li[1]/text()[1]')
prizemoney = tree.xpath('//*[#id="mainwrapper"]/div/div/div[2]/div[1]/div[2]/ul/li[2]/text()[1]')
setoff = tree.xpath('//*[#id="mainwrapper"]/div/div/div[2]/div[1]/div[2]/h3/span/text()')
course = tree.xpath('//*[#id="mainwrapper"]/div/div/div[2]/div[1]/div[2]/h1/text()[1]')
print(course)
course[0] = course[0].replace('Result', '')
date = tree.xpath('//*[#id="mainwrapper"]/div/div/div[2]/div[1]/div[2]/h1/text()[2]')
timeoff = tree.xpath('//div[#class="raceInfo"]/text()[3]')
above is a code snippit -> if borwser.get does not grab page (server rejects or timeout) then id need to retry.
You can add a try/exception error which will return some kind of variable to tell the page that it has not loaded properly then you can use javascript function location.reload() to reload the page.
For example:
In your Python Script:
try:
'Your Code Goes Here'
except IndexError:
return 'e'
And in your Javascript:
if(xml.responsetext=='e'){
location.reload(true);//true if you dont want to load from cache,otherwise leave it blank
}
Report me if there is any error , as I am also trying to use python script with AJAX in my website and I am quite new to it.I would have loved to comment instead of answering it but my reputation doesnt allow me to do so.
Cheers
I think you need to make a little refactoring.
It should be something like this:
def get_page(link):
# all code stuff for fetching page
# this code could return ether error code or throw Exception
return data
for link in links:
try:
result = get_page(link)
# here you need to add this result
except IndexError:
#log this error
result = get_page(link) #this is retry. you can add slip() here too
This is quick and dirty example, you can improve it with better retries logging, counting retries for each link globally and so on.

JSON file / script preventing page from displaying.

I have a JSON file that is approx 500 lines long. The script that reads in the file is the first thing to happen when the page is loaded. The script works perfectly. It updates a drop down box automatically depending on a users choice.
A moment ago I added an additional 50 lines or so to the JSON file, maintained correct syntax etc etc. When I reloaded the page there was nothing but a white screen, no error logs etc. I removed what I had added to the JSON and received the same white screen, I'd also reloaded the page after clearing cache and on different browsers, same thing.
I then commented out the script that calls the JSON, reloaded and voila, it's fine. I un-comment the script again so it is as it was and magic, it now works.
Can anyone explain what could be happening and how I might solve it please? I can't force it to happen again but that doesn't mean it won't.
Many thanks.
Simplified sample of JSON:
"angle" : [
{
"value":"degree",
"name":"Degree (deg)"
},
{
"value":"grad",
"name":"Grad (grad)"
}]
The script that calls it:
<script>
$.getJSON('JSON/conversionJSON.json', function(data){
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
}
});
});
});
</script>
Thanks

crm2011 plugin call js function

How can I run JavaScript function from appropriate web resource with a plugin in CRM2011.
I couldn't find any information on the Internet. Most of the resources describes how to trigger plugin from JS, but not opposite.
Here's JS code taht is copying the notes to the description field.
When save is clicked. you can see that the data is correctly display in a description field. However if you press save and close and open form again the description field will be empty.
I thought that the reason for that is that the JS executed after safe event but later tests descovered that it's false. Could someone point out an error in this JS code which cause that data is not saving?
Or give a suggestion how's write a plugin which is retrieving data from related entity and writes it into field in the form. thanx
function copyNotes()
{
// CLEAR DESCRIPTION FIELD
alert("JS");
Xrm.Page.getAttribute("description").setValue('');
// GET ID OF THE CASE AND CLEAN IT AND GET URL for oData stuff
//THEN CALL RETRIEVE FUNCTION
var caseID = Xrm.Page.data.entity.getId();
caseID = caseID.replace('{', '').replace('}', '');
var oDataPath = Xrm.Page.context.getServerUrl() + "/xrmservices/2011/organizationdata.svc";
ODataPath = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc";
retrieveRecord(caseID);
}
// CREATE AN HTTP REQUEST AND SEND IT
function retrieveRecord(Id) {
var retrieveReq = new XMLHttpRequest();
retrieveReq.open("GET", ODataPath + "/AnnotationSet?$filter=ObjectId/Id" + " eq (guid'" + Id + "')", true);
retrieveReq.setRequestHeader("Accept", "application/json");
retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveReq.onreadystatechange = function() {
// THIS HANDLES A CALLBACK
retrieveReqCallBack(this);
};
retrieveReq.send();
}
function retrieveReqCallBack(retrieveReq) {
if (retrieveReq.readyState == 4 /* complete */ )
{
if (retrieveReq.status == 200) {
//Success
var retrieved = this.parent.JSON.parse(retrieveReq.responseText).d;
// ITERATE THROUGH THE NOTES FOR THIS CASE
for (var i = 0; i < retrieved.results.length; i++) {
// IF IS AN EMPTY FIELD ADD 'case details:'
if (Xrm.Page.getAttribute("description").getValue() == null || Xrm.Page.getAttribute("description").getValue() == 'null') {
Xrm.Page.getAttribute("description").setValue('Case details:');
}
// BOF PARSE DATE
var date = retrieved.results[i].CreatedOn;
date = new Date(parseInt(date.replace("/Date(", "").replace(")/", ""), 10));
// EOF PARSE DATE
var newtext = "--------------------\r\n" + "Created by: " + retrieved.results[i].CreatedBy.Name + " - " + date + "\r\n" + retrieved.results[i].NoteText + "\r\n--------------------\r\n";
var text = Xrm.Page.getAttribute("description").getValue() + "\r\n" + newtext;
Xrm.Page.getAttribute("description").setValue(text);
}
}
}
}
There is no supported way to call back to the client from the server from within the plugin. I'm also not aware of any unsupported way.
I don't think this question even makes sense. Plugin's only trigger when there has been a CRUD operation of some sort. Any CRUD operation triggered by the GUI will result in a refresh of the entity any way. You could perform an update via javascript and an Odata call, but then once the plugin has finished, you can run whatever javascript you'd like to run.
There's no (reasonable) way to do that.
The reason for that is the fact that plugin is a server-size executed thingy. It can't even assume there's a GUI. (Of course, we know there is but generally, a server-size code can't interact with the GUI directly).
JavaScript is client-side code and a client assumes a server. That's (roughly) why JS can call a plugin (although I wouldn't put it that way) but not the other way around.
I've never had a need of such an operation so I'm curious as to what your task is. Are you asking of pure, academic interest or is it a part of a design? Perhaps there's a better way to reach your goal?

Categories

Resources