JavaScript immediately closes after opening it - javascript

I am working on a Raspberry3 model B.
I've written a code that I want to launch on reboot.
If I launch the script in the bash it works perfectly. But when I try to start the script via doubleclick (execute in terminal) it opens the terminal for a very short duration and closes it immediatly after.
Same thing happens if I want to start this script at reboot.
Can anyone tell me what I'm doing wrong?
var blynkLib = require('blynk-
library');
var sensorLib = require('node-dht-
sensor');
var AUTH = 'xxx';
// Setup Blynk
var blynk = new
blynkLib.Blynk(AUTH);
// Setup sensor, exit if failed
var sensorType = 22; // 11 for DHT11, 22 for DHT22 and AM2302
var sensorPin = 2; // The GPIO pin number for sensor signal
if
(!sensorLib.initialize(sensorType,
sensorPin)) {
console.warn('Failed to
initialize sensor');
process.exit(1);
}
// Automatically update sensor value every 2 seconds
setInterval(function() {
var readout = sensorLib.read();
blynk.virtualWrite(3,
readout.temperature.toFixed(1));
blynk.virtualWrite(4,
readout.humidity.toFixed(1));
console.log('Temperature:',
readout.temperature.toFixed(1) +
'C');
console.log('Humidity: ',
readout.humidity.toFixed(1) +
'%');
}, 2000);

Assuming your question is How can i pause my program :
using python : you should import os then os.system("pause"); :
import os;
os.system("pause");
Using nodejs : use one of the module from npm :
https://www.npmjs.com/package/system-sleep
https://www.npmjs.com/package/pause

Related

How to manipulate URL while executing Test cafe scripts

I tried executing my TestCafe scripts using command prompt. While executing, test cafe starts execution by taking local IP, port number and session ID along side the URL. I want my scripts to execute directly on the URL without the local host IP, port and other details. Refer attached screenshot when I executed my scripts on Test Cafe.
Screenshot of test cafe script with local host IP, port
Attached is the code for test case which was executed on Test Cafe.
import { Selector } from 'testcafe';
import { Crypto } from 'testcafe';
var faker = require('faker');
function randomString(size) {
return crt
.randomBytes(size)
.toString('hex')
.slice(0, size)
};
function numberGen(len) { //Function to Generate random number;
length of number = value specified in 'len'
// var genNum= Math.floor(Math.pow(10, len)*Math.random()).toString()
var text = "";
var charset = "0123456789";
for( var i=0; i < len; i++ ) {
text += charset.charAt(Math.floor(Math.random() * charset.length));}
return text;
};
const dataSet = require('./dataIUT.json');
const crt = require('crypto')
var randomBankAccName = faker.random.alphaNumeric(6)+"Bank";
var AccountNumber = numberGen(9)
var AccountName = "AccName_"+faker.random.alphaNumeric(4)
fixture `CreateBankAccount`
.page `https://dev-assure-claims.dxc-rmcl.com/riskmasterux/#/login?
clientId=3f28130450c00018`
.beforeEach(t => t.resizeWindow(1200, 1100));
dataSet.forEach(data => {
test('CreateBankAccount', async t => {
//==================Login Code With JSON Starts================================
await t
.maximizeWindow()
.typeText(Selector('#username'), data.Username)
.pressKey('tab')
.typeText(Selector('#login-password'), data.Password)
.pressKey('enter')
.click(Selector('[ng-model="dsnSelected"]'))
.click(Selector('[role="option"]').find('span').withText(data.DSN))
.click(Selector('[ng-model="zoneSelected"]'))
.click(Selector('[role="option"]').find('a').withText('Claims'))
.click(Selector('#loginbox').find('button').withText('Continue'))
.wait(1000)
//==================Login Code With JSON Ends================================
//==================Code to Create Bank Account Starts ================================
.click(Selector('#menuBar').find('a').withText('Funds').nth(0))
.click(Selector('#menu_FundsRoot').find('a').withText('Bank Account'))
.switchToIframe(Selector('[id^="bankaccount"]'))
.wait(1000)
//var BankAccount = "BA_"+randomString(4).toUpperCase()
//await t
.click(Selector('#lookup_banklastname'))
.typeText(Selector('#lookup_banklastname'), randomBankAccName).setTestSpeed(0.6).pressKey('tab')
//.click(Selector('#accountnumber'))
.typeText(Selector('#accountnumber'), AccountNumber).setTestSpeed(0.6)
.pressKey('tab')
.click(Selector('#accountname')).typeText(Selector('#accountname'), AccountName).setTestSpeed(0.6)
.pressKey("tab")
.click(Selector('#Save').find('i').withText('save'))
//==================Code to Create Bank Account Endss==================================
//========================Click to RHS Child's Add button Starts=========================
const ele1 = Selector('[class="row main_menu right-panel-bg-hover"]').find('i').withText('add').with({ visibilityCheck: true }) // RHS Menu is available
await t.expect(ele1.exists).ok('', { timeout: 20000 })
.click(ele1)
//========================Click to RHS Child's Add button Ends=========================
//==========================Logout Code Starts==========================================
.switchToMainWindow()
.click(Selector('#morebtn').find('i').withText('more_vert'))
.click(Selector('#menu_othersMenu').find('a').withText('exit_to_appLogout'))
.click(Selector('#btnRoll').find('i').withText('done'));
//===========================Logout Code Ends========================================
});});
What issues is having the tests "run" on localhost causing you? What exactly are you trying to solve for?
What you're seeing is TestCafe communicating with the local TestCafe server. Looking at the docs, it isn't possible to have TestCafe communicate with a device that isn't your current machine, so I don't think what you want to achieve is possible.

Why can I only access window.properties() when running from within Automator?

I am trying to write a JXA script which extends the bounds the current window of the current application vertically so it reaches from the top to the bottom of the screen. If I run the following script in Automator as a "Run JavaScript" quick action, it works:
var app = Application.currentApplication();
var window = app.windows[0];
var orig_bounds = window.properties().bounds;
var vertical_res =
Application("Finder").desktop.window.properties().bounds.height;
window.bounds = {
"x": orig_bounds.x,
"y": 0,
"width": orig_bounds.width,
"height": vertical_res
};
I want this script to be bound to a hotkey. When I bind it in System Preferences -> Keyboard -> Shortcuts -> Services -> General and try to activate it while some app is active (say, iTerm 2), it doesn't work, and I get the error:
The action “Run JavaScript” encountered an error: “Error on line 4: TypeError: undefined is not an object (evaluating 'window.properties')”
Note that if I modify the script to always operate on a specific app (var app = Application("Google Chrome");) and run it in Automator, it works.
You need to get the application currently in use (the front most application), as the current application is the one running the Javascript code. This is why the code works when it's run in Automator and when a certain application is hard-coded.
To get the application in use you can use the two lines below:
var frontAppName = Application("System Events").processes.whose({frontmost: {'=': true }})[0].name();
var frontApp = Application(frontAppName);
I can't be certain about the error but I understand that it is generally considered good practice to include the Standard Definitions, and I've included it in the revised code below which doesn't cause this error when using a hot key combination.
function run(input, parameters) {
var app = Application.currentApplication();
app.includeStandardAdditions = true;
var frontAppName = Application("System Events").processes.whose({frontmost: {'=': true }})[0].name();
var frontApp = Application(frontAppName);
var window = frontApp.windows[0];
var orig_bounds = window.properties().bounds;
var vertical_res = Application("Finder").desktop.window.properties().bounds.height;
var orig_x = orig_bounds.x;
var orig_width = orig_bounds.width;
frontApp.windows[0].bounds = {
x: orig_x,
y: 0,
width: orig_width,
height: vertical_res
};
}

Why does Node hang when using deasync with x11 events?

I'm trying to use the node modules deasync and x11 to perform actions when certain keys are pressed.
When I use deasync inside a callback that has been initiated by a keypress deasync seems to be stuck in an endless loop.
It works fine if I create a generic event myself.
Run the following script using xtrace to see that X11 does respond:
xtrace -D :10 ./the-script
#!/usr/bin/env node
var deasync = require('deasync');
var x11 = require('x11');
var display = (deasync(x11.createClient)());
var client = display.client;
var getInputFocus = deasync(client.GetInputFocus)
.bind(client);
var focus1 = getInputFocus();
console.log("getting focus here works:", focus1);
// grab the "1"-key - keyCode = 10
client.GrabKey(display.screen[0].root, 0, null, 10, 0, 1);
client.on('event', processKeyPressEvent);
// client.emit("event"); // works
function processKeyPressEvent(event) {
console.log("can see this");
var focus2 = getInputFocus(); // problem
console.log("never get here");
}
Thanx for your help.

Updating client image after interval when server sends new image

In my ASP.NET MVC application, server is broadcasting image URL to all clients after 5 seconds
I am using SignalR to send image URL from server which invokes Javascript function.
In the Javascript function I am using following code to auto-refresh <img> element to update the src attribute but though it is updating my src I am not able to see on browser.
// Defining a connection to the server hub.
var myHub = $.connection.myHub;
// Setting logging to true so that we can see whats happening in the browser console log. [OPTIONAL]
$.connection.hub.logging = true;
// Start the hub
$.connection.hub.start();
// This is the client method which is being called inside the MyHub constructor method every 3 seconds
myHub.client.SendServerImageUrl = function (serverImageUrl) {
var N = 5;
// Function that refreshes image
function refresh(imageId, imageSrc) {
var image = document.getElementById(imageId);
var timestamp = new Date().getTime();
image.src = imageSrc + '?' + timestamp;
};
// Refresh image every N seconds
setTimeout(function () {
refresh('SampleImage', serverImageUrl);
}, N * 1000);
My HTML file contains only following code:
<img id="SampleImage">
Backend C# code
public class MyHub : Hub
{
public MyHub()
{
// Create a Long running task to do an infinite loop which will keep sending the server time
// to the clients every 5 seconds.
var taskTimer = Task.Factory.StartNew(async () =>
{
while(true)
{
Random rnd = new Random();
int number = rnd.Next(1,10);
string str = "~/Images/Sample";
Clients.All.SendServerImageUrl(str+Convert.ToString(number)+".jpg");
//Delaying by 5 seconds.
await Task.Delay(5000);
}
}, TaskCreationOptions.LongRunning
);
}
}
Try changing the casing in your callbacks:
myHub.client.sendServerImageUrl = ...;
Clients.All.sendServerImageUrl(...);
There should be no need for polling so get rid of setTimeout() on the client.
Keep an eye on the Console and make sure HTTP requests are working.

Nodejs/Javascript Getting Process Memory of any process

I am looking for a way of getting the process memory of any process running.
I am doing a web application. I have a server (through Nodejs), my file app.js, and an agent sending information to app.js through the server.
I would like to find a way to get the process memory of any process (in order to then sending this information to the agent) ?
Do you have any idea how I can do this ? I have searched on google but I haven't found my answer :/
Thank you
PS : I need a windows compatible solution :)
Windows
For windows, use tasklist instead of ps
In the example below, i use the ps unix program, so it's not windows compatible.
Here, the %MEM is the 4st element of each finalProcess iterations.
On Windows the %MEM is the 5th element.
var myFunction = function(processList) {
// here, your code
};
var parseProcess = function(err, process, stderr) {
var process = (process.split("\n")),
finalProcess = [];
// 1st line is a tab descriptor
// if Windows, i should start to 2
for (var i = 1; i < process.length; i++) {
finalProcess.push(cleanArray(process[i].split(" ")));
}
console.log(finalProcess);
// callback to another function
myFunction(finalProcess);
};
var getProcessList = function() {
var exec = require('child_process').exec;
exec('ps aux', parseProcess.bind(this));
}
// thx http://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript
function cleanArray(actual){
var newArray = new Array();
for(var i = 0; i<actual.length; i++){
if (actual[i]){
newArray.push(actual[i]);
}
}
return newArray;
}
getProcessList();

Categories