Can this Python script be made in JavaScript? - javascript

I'm very new to computer programming, and me and some friends are making a small project that chooses a random line of text from a text file full of data. I have a Python script that chooses a random line of a text file and returns it.
import random
filePath = "../data/strats.txt"
count = len(open(filePath).readlines( ))
lineNum = randint(1, count)
lines = [0]
with open(filePath) as strats:
while strats.readline():
lines.append(strats.tell())
strats.seek(lines[lineNum])
line = strats.readline()
return line
This connects to some JavaScript code, but I'm having trouble using the python script without a web server. I would like to make the website all client side, and that means making this same program in JavaScript. If there is another way, please let me know. Otherwise: Can this Python script be translated into JavaScript?

Related

Python Bokeh: How can i use Python callbacks or external functions while having HTML/JS output [duplicate]

I am a beginner to using Python's bokeh plotting tool and widgets. In my following code I am trying to have the title of the graph change to the value of the TextInput box. However, while the box appears upon entering in text and unfocusing, nothing changes. What could be causing this issue and what can I do to fix it?
p=figure(
height=400,
x_axis_type='datetime',
title=(company+' ('+tickerstring+') ')
)
thedates = np.array(stockdates, dtype=np.datetime64)
source = ColumnDataSource(data=dict(
x=thedates,
y=stockcloseprices
))
p.line('x', 'y', source=source)
p.grid.grid_line_color="white"
p.xaxis.axis_label = 'Date'
p.yaxis.axis_label = 'Price'
p.add_tools(HoverTool(
tooltips=[
("Date", "#x{%F}"),
('Close',"#y")
],
formatters={
'x':'datetime', # use 'datetime' formatter for 'date' field
},
mode='vline'
))
def update_title(attrname, old, new):
p.title = text.value
div = Div(text='<br><b> Key Points </b><br><br>'+percentagechange+'<br><br>'+performance,
width=200, height=100)
text = TextInput(value='Name', title="Enter Ticker Here:")
text.on_change('value', update_title)
grid = gridplot([p, div, text], ncols=2, plot_width=570, plot_height=400)
show(grid)
By you using show(grid) you are creating a standalone HTML document as output. This has no possible way of running real python callbacks, because browsers have no ability to run python code. Running real callbacks requires having a connection to a persistent Python process. That is the Bokeh server. Using real python callbacks (i.e. with on_change) is only possible in bokeh server applications (that is the purpose of the bokeh server, to be the thing that runs real python callbacks.) See:
https://docs.bokeh.org/en/latest/docs/user_guide/server.html
It's also possible to embed Bokeh server apps in Juyter notebooks, for an example of that, see here:
https://github.com/bokeh/bokeh/blob/master/examples/howto/server_embed/notebook_embed.ipynb

Pycurl javascript

I created a python 3 script that allows me to search on a search engine (DuckDuckGo), get the HTML source code and write it in a textfile.
import pycurl
from io import BytesIO
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://duckduckgo.com/?q=test')
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.FOLLOWLOCATION, True)
c.perform()
c.close()
body = buffer.getvalue()
with open("output.htm", "w") as text_file:
text_file.write(str(body))
print(body.decode('iso-8859-1'))
That part of the code is working properly. However, when I try to open the output.htm file containing the HTML source code of the search engine, I don't get anything (I get an input with my search topic written inside). I would like to have the same HTML source code that I would get by running curl https://duckduckgo.com/?q=test on my terminal.
Duckduckgo's html pages uses javascript to load their search result into their html markups, so curl or PyCurl will not be able to get the same html content you'd see in a browser since curl/pycurl merely fetches internet resources but does not provide any javascript processing.
Use https://duckduckgo.com/api instead of scraping to find search results in their servers/databases.

How to read and write to a file (Javascript) in ui automation?

I want to identify few properties during my run and form a json object which I would like to write to a ".json"file and save it on the disk.
var target = UIATarget.localTarget();
var properties = new Object();
var jsonObjectToRecord = {"properties":properties}
jsonObjectToRecord.properties.name = "My App"
UIALogger.logMessage("Pretty Print TEST Log"+jsonObjectToRecord.properties.name);
var str = JSON.stringify(jsonObjectToRecord)
UIALogger.logMessage(str);
// -- CODE TO WRITE THIS JSON TO A FILE AND SAVE ON THE DISK --
I tried :
// Sample code to see if it is possible to write data
// onto some file from my automation script
function WriteToFile()
{
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/Volumes/DEV/test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
AND
function WriteFile()
{
// Create an instance of StreamWriter to write text to a file.
sw = new StreamWriter("TestFile.txt");
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
sw.Close();
}
But still unable to read and write data to file from ui automation instruments
Possible Workaround ??
To redirect to the stdout if we can execute a terminal command from my ui automation script. So can we execute a terminal command from the script ?
Haven't Tried :
1. Assuming we can include the library that have those methods and give it a try .
Your assumptions are good, But the XCode UI Automation script is not a full JavaScript.
I don't think you can simply program a normal browser based JavaScript in the XCode UI Automation script.
set fso = CreateObject("Scripting.FileSystemObject");
Is not a JavaScript, it is VBScript which will only work in Microsoft Platforms and testing tools like QTP.
Scripting.FileSystemObject
Is an ActiveX object which only exists in Microsoft Windows
Only few JavaScript functions like basic Math, Array,...etc..Are provided by the Apple JavaScript library, so you are limited to use only the classes provided here https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/UIAutomationRef/
If you want to do more scripting then Try Selenium IOS Driver http://ios-driver.github.io/ios-driver/
Hey so this is something that I was looking into for a project but never fully got around to implementing so this answer will be more of a guide of what to do than step by step copy and paste.
First you're going to need to create a bash script that writes to a file. This can be as simple as
!/bin/bash
echo $1 >> ${filename.json}
Then you call this from inside your Xcode Instruments UIAutomation tool with
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout("your/script/path", ["Object description in JSON format"], 5);
Then after your automation ends you can load up the file path on your computer to look at the results.
EDIT: This will enable to write to a file line by line but the actual JSON formatting will be up to you. Looking at some examples I don't think it would be difficult to implement but obviously you'll need to give it some thought at first.

Running external programs through nodejs and interacting with browser through socket.io

While trying to create a tool(with nodejs, socket.io) which runs an external program (e.g. a C program or a Python program), the program stops responding when it encounters the user input (it sends the line asking input to browser though).
On Server:
var chunk = '';
python.stdout.on('data', function(data){
python.stdout.pipe(python.stdin);
chunk += data;
console.log(chunk);
socket.emit('newdata', chunk);
} );
On Client:
socket.on('newdata', function(d){
var output = document.getElementById('output');
output.innerHTML = d;
})
Everything is working fine in fact, the only problem is that the program you launched requires a user input and your node.js code is not giving it.
Tbh I don't know if you can give an input when it asks for it... but can't you pass arguments at the start of the program to avoid this user input? It's how I solved it on the same system done with Java/J2EE

JXA get file's Size & checksum?

I am using JXA (javascript for automation) on my Mac to try to automate iTunes Connect screenshot uploads. Because of this, I want to automate grabbing each image and uploading it, but for iTunes Connect to allow this (using iTMSTransporter), I need to edit a XML file and add in each image's size in bits, as well as get the checksum (type="md5").
I know I could do this manually, but I want to automate it as this will save me a lot of time in the long run, with tons of different screenshots for each localization.
I've used JXA to grab the images, and get their dimensions, but can't figure out getting the size & checksum. Maybe someone can help? Or if not using JXA, maybe there is some sort of other script that JXA can run (like a shell script, which I have no experience with what so ever as of now), or maybe some script I could just run ahead of time and export the XML to a file manually. From there I could use JXA to parse that file.
Here is what I have so far for what it takes to get the image file:
desktopPath = finder.desktop.url();
desktopPath = desktopPath.substring(7, desktopPath.length);
var imagePath = Application('System Events').folders.byName(desktopPath + '/myImage.png');
imageEvents = Application("Image Events");
imageEvents.launch();
imageEvents.name();
img = imageEvents.open(Path(imagePath));
// now I don't know what to do with the image as the documentation is quite difficult for me to understand
I figured it out. I had to use shell scripts to access this info. Idk if there is another way, but this way worked...
// to get the size (newString is the path (as a string) to the file I am getting the size for
var theSize = app.doShellScript("stat -f%z " + newString.replace(" ", "\\ "));
// to get the MD5 checksum (newString is again the path (as a string) to the file I am getting the checksum for
var md5String = newString;
md5String = md5String.replace(" ", "\\ ");
var checksum = app.doShellScript("md5 " + md5String);
checksum = checksum.replace(/\/$/, "").split(' ').pop();
// I popped because I had to format the returned string so it's just the MD5 and not the file path as well. Maybe there is an easier way in shell script, but I'm a newbie to shell scripting

Categories

Resources