qpython hello world not working - qpython

I'm new to qpython (obviously :P )
I was trying the helloworld.py that's built in to the qpython app
From what I gather, it should pop up a text box to collect a name and open a window with "Hello, "
The first part works. it collects the name, but the maketoast(s) is not working. what is wrong?
this was on Nexus 5 running android 5.1.2
Added source code below as suggested:
#-*-coding:utf8;-*-
#qpy:console
#qpy:2
import androidhelper
droid = androidhelper.Android()
line = droid.dialogGetInput()
s = "Hello, %s" % (line.result)
print s
droid.makeToast(s)

Can you post what the code is?
For mine to do that I edited it to say:
import sl4a
droid = sl4a.Android()
name = input('What is your name?: ')
droid.makeToast('Hello,' + name)
print('Hello ' + name)

Related

Shiny App not finding PDF file in www folder

I am trying to create a simple button, link, and/or viewing pane in my Shiny App that allows users to download a pre-existing PDF file that I have saved in my www folder (code below). The App keeps coming back with the error message "File not Found". However, when I check that the file exists with file.exists("www/sample_label.pdf") it returns TRUE. I can't for the life of me figure out where the problem is coming from. The code works if I try a url like "https://cran.r-project.org/doc/manuals/r-release/R-intro.pdf". Any help would be greatly appreciated.
Thanks
library(shiny)
ui <- fluidPage(
titlePanel("Vaccine Label"),
mainPanel(
downloadButton("downloadLabel", label = "Download Label", class = NULL, icon = shiny::icon("download")),
br(),
tags$a("Download Label", href = "www/sample_label.pdf"),
br(),
tags$iframe(style="height:600px; width:100%; scrolling = yes", src = "www/sample_label.pdf")
)
)
server <- function(input, output) {
output$downloadLabel <- downloadHandler(
filename = "www/sample_label.pdf",
content = function(file) {
file.copy("temp.pdf", file)
}
)
}
shinyApp(ui, server)

Python Selenium Failing to Acquire data

I am trying to download the 24-month data from www1.nseindia.com and it fails on Chrome and Firefox drivers. It just freezes after filling all the values in the required places and does not click. The webpage does not respond...
Below is the code that I am trying to execute:
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
id_list = ['ACC', 'ADANIENT']
# Chrome
def EOD_data_Chrome():
driver = webdriver.Chrome(executable_path="C:\Py388\Test\chromedriver.exe")
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
s1= Select(driver.find_element_by_id('dataType'))
s1.select_by_value('priceVolume')
s2= Select(driver.find_element_by_id('series'))
s2.select_by_value('EQ')
s3= Select(driver.find_element_by_id('dateRange'))
s3.select_by_value('24month')
driver.find_element_by_name("symbol").send_keys("ACC")
driver.find_element_by_id("get").click()
time.sleep(9)
s6 = Select(driver.find_element_by_class_name("download-data-link"))
s6.click()
# FireFox(Gecko)
def EOD_data_Gecko():
driver = webdriver.Firefox(executable_path="C:\Py388\Test\geckodriver.exe")
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
s1= Select(driver.find_element_by_id('dataType'))
s1.select_by_value('priceVolume')
s2= Select(driver.find_element_by_id('series'))
s2.select_by_value('EQ')
s3= Select(driver.find_element_by_id('dateRange'))
s3.select_by_value('24month')
driver.find_element_by_name("symbol").send_keys("ACC")
driver.find_element_by_id("get").click()
time.sleep(9)
s6 = Select(driver.find_element_by_class_name("download-data-link"))
s6.click()
EOD_data_Gecko()
# Change the above final line to "EOD_data_Chrome()" and still it just remains stuck...
Kindly help with what is missing in that code to download the 24-month data... When I perform the same in a normal browser, with manual clicks, it is successful...
When you are manually doing it in a browser, you can change the values as below:
Set first drop down to : Security wise price volume data
"Enter Symbol" : ACC
"Select Series" : EQ
"Period" (radio button: "For Past") : 24 Months
Then click on the button, "Get Data", and in about 3-5seconds, the data loads, and then when you click on "Download file in CSV format", you can have the CSV file in your downloads
Need help using any library you know for scraping in Python: Selenium, Beautifulsoup, Requests, Scrappy, etc... Doesn't really matters unless it is python...
Edit: #Patrick Bormann, pls find the screenshot... The get data button works..
When you say that it works manually, have you try to simulate a click with action chains instead of the internal click function
from selenium.webdriver.common.action_chains import ActionChains
easy_apply = Select(driver.find_element_by_id('dateRange'))
actions = ActionChains(driver)
actions.move_to_element(easy_apply)
actions.click(easy_apply)
actions.perform()
and then you simulate a mouse movement to the specific value?
In addition, I tried it on my own and I didnt get any data when pushing on the button Get Data, as it seems to have a class of "get" as you mentioned, but this button doesnt work, but as you can see there exists a second button called full download, perhaps ypu try to use this one? Because the GetData Button doesnt work on Firefox and Chrome (when i tested it).
Did you already try to catch it through the link?
Update
As the OP asks for help in this urgent matter I delivered a working solution.
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
from selenium.webdriver.support.ui import Select
chrome_driver_path = "../chromedriver.exe"
driver = webdriver.Chrome(executable_path=chrome_driver_path)
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
driver.execute_script("document.body.style.zoom='zoom 25%'")
time.sleep(2)
price_volume = driver.find_element_by_xpath('//*[#id="dataType"]/option[2]').click()
time.sleep(2)
date_range = driver.find_element_by_xpath('//*[#id="dateRange"]/option[8]').click()
time.sleep(2)
series = driver.find_element_by_name('series')
time.sleep(2)
drop = Select(series)
drop.select_by_value("EQ")
time.sleep(2)
driver.find_element_by_name("symbol").send_keys("ACC")
ez_download = driver.find_element_by_xpath('//*[#id="wrapper_btm"]/div[1]/div[3]/a')
actions = ActionChains(driver)
actions.move_to_element(ez_download)
actions.click(ez_download)
actions.perform()
Here you go, sorry, took a little, had to bring my son to bed...
This solution provides this output: I hope its correct. If you want to select other drop down menus you can change the string in the select (string because of too much indezes too handle) or the number in the xpath as the number highlights the index. The time is normally only for elements which need time to build themselves up on a webpage. But I made the experience that a too fast change sometimes causes errors. Feel free to change the time limit and see if it still works.
I hope you can now go on again in making some money for your living in India.
All the best Patrick,
Do not hesitate to ask if you have any questions.
UPDATE2
After one long night and another day we figured out that the Freezing originates from the website, as the website uses:
Boomerang | Akamai Developer developer.akamai.com/tools/… Boomerangis
a JavaScript library forReal User Monitoring (commonly called RUM).
Boomerang measures the performance characteristics of real-world page
loads and interactions. The documentation on this page is for mPulse’s
Boomerang. General API documentation for Boomerang can be found
atdocs.soasta.com/boomerang-api/.
.
What I discovered from the html header.
This is clearly a bot detection network/javascript. With the help of this SO post:
Can a website detect when you are using Selenium with chromedriver?
And the second paragraph from that post:https://piprogramming.org/articles/How-to-make-Selenium-undetectable-and-stealth--7-Ways-to-hide-your-Bot-Automation-from-Detection-0000000017.html
I finally solved the issue:
we changed the
var_key in chromedriver to something else like:
var key = '$dsjfgsdhfdshfsdiojisdjfdsb_';
In addition I changed the code to:
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
options = webdriver.ChromeOptions()
chrome_driver_path = "../chromedriver.exe"
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
driver.get('http://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
driver.execute_script("document.body.style.zoom='zoom 25%'")
time.sleep(5)
price_volume = driver.find_element_by_xpath('//*[#id="dataType"]/option[2]').click()
time.sleep(3)
date_range = driver.find_element_by_xpath('//*[#id="dateRange"]/option[8]').click()
time.sleep(5)
series = driver.find_element_by_name('series')
time.sleep(3)
drop = Select(series)
drop.select_by_value("EQ")
time.sleep(4)
driver.find_element_by_name("symbol").send_keys("ACC")
actions = ActionChains(driver)
ez_download = driver.find_element_by_xpath('/html/body/div[2]/div[3]/div[2]/div[1]/div[3]/div/div[1]/form/div[2]/div[3]/p/img')
actions.move_to_element(ez_download)
actions.click(ez_download)
actions.perform()
#' essential because the button has to be loaded
time.sleep(5)
driver.find_element_by_class_name('download-data-link').click()
The code finally worked and the OP is happy.
I have edited the chromedriver.exe using hex editor and replaced cdc_ with dog_ and saved it. Then executed the below code using chrome driver.
import selenium
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument("--disable-blink-features")
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options)
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'})
print(driver.execute_script("return navigator.userAgent;"))
# Open the website
driver.get('https://www1.nseindia.com/products/content/equities/equities/eq_security.htm')
symbol_box = driver.find_element_by_id('symbol')
symbol_box.send_keys('20MICRONS')
driver.implicitly_wait(10)
#rd_period=driver.find_element_by_id('rdPeriod')
#rd_period.click()
list_daterange=driver.find_element_by_id('dateRange')
list_daterange=Select(list_daterange)
list_daterange.select_by_value('24month')
driver.implicitly_wait(10)
btn_getdata=driver.find_element_by_xpath('//*[#id="get"]')
btn_getdata.click()
driver.implicitly_wait(100)
print("Clicked button")
lnk_downloadData=driver.find_element_by_xpath('/html/body/div[2]/div[3]/div[2]/div[1]/div[3]/div/div[3]/div[1]/span[2]/a')
lnk_downloadData.click()
This code is working fine as of now. But the problem is that - this is not a permanent solution. NSE keeps on updating the logic to detect BOT execution in a better way. Like NSE, we will also have update our code. Please let me know if this code is not working. Will figure out some other solution.

How to import a Python library into Alexa Skill

I am simply trying to import the random library into my Alexa Skill, but I'm getting "There was a problem with the requested skill's response" every time i try to use it in my lambda functions code (e.g. index = random.randrange(len(array)) ). Ive seen answers ranging from simply putting the library into your requirements.txt to using a zip file to do it. Nothing has worked and/or makes sense. Thanks for the help.
The random library is part of the PSL. You just need to add import random at the top of your script with the other import statements. For non-PSL libraries, you should add them to the "requirements.txt" and then import them in the script, just like you'd do with Node and the "package.json" file.
Here's my edited version of the LaunchIntent from the default Python Hello World template in the Alexa Developer Console. The import random was added to the script after import logging up around line 8.
class LaunchRequestHandler(AbstractRequestHandler):
"""Handler for Skill Launch."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_request_type("LaunchRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
rnum = str(random.randint(0,9))
speak_output = "Welcome, your random number is " + rnum
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
Because I'm combining the number with a string to produce a string, I have to cast the integer to a string, but that's about it.
Beyond that there's a "CloudWatch Logs" button at the top of the editor in the Alexa Developer Console. Click that and check your the latest log stream for the output of what error might be occurring.
For example, I don't write Python often and I'm so used to JavaScript's type coercion, I forgot to cast the random number to a string before adding it to a string. I know... bad habit. That error was clearly indicated in the CloudWatch logs. I fixed it and everything worked like a charm.

How to write groovy Script in Jmeter

Hello Stackoverflow Community,
I am new to Jmeter and Related Stuff.
Just Finished with Login Request and Response through Selenium WebDriver Sampler(using Java Script) .
Screen shot is also attached with this post.
All working Well.
Now i go through some articles ,they stress on using groovy script(under JSR223 Sampler) but i am not able to figure out how to convert this same Javascript(WDS sampler) in Groovy(JSR223 sampler) runnable Script.I will be very thankful for any Kind of help in this direction.
Thanks
groovy(Groovy 2.4.15/Groovy Scripting Engine 2.0) is already displayed in my JSR223 Sampler [i m using apache-jmeter-5.0 ] i run hello world program its working fine..further i have no idea abt how to play with groovy script.
Below is my code in Javascipt(selenium WDS)
WDS.sampleResult.sampleStart();
WDS.log.info("Maximo Application ---- Sample started");
var pkg = JavaImporter(org.openqa.selenium); //WebDriver classes
var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait);
var wait = new support_ui.WebDriverWait(WDS.browser, 5000);
var conditions=org.openqa.selenium.support.ui.ExpectedConditions;
var selenium_keys=JavaImporter(org.openqa.selenium.Keys);
WDS.sampleResult.getLatency();
//-----------------------------Login in Application---------------------------------------------
WDS.browser.get('http://xxxxxxxxxxxxxxx/maximo/webclient/login/login.jsp'); //opens website
WDS.log.info("Maximo Application ---- Username and Password dynamicly picked from C:/user.csv ");
//UserName
var userName = WDS.browser.findElement(pkg.By.id('username'));
WDS.log.info("Maximo Application ---- Username "+'${username}');
userName.click();
userName.sendKeys('${username}');
//Password
var password=WDS.browser.findElement(pkg.By.id("password"));
password.click();
WDS.log.info("Maximo Application ---- password "+'${password}');
password.clear();
password.sendKeys('${password}');
WDS.browser.findElement(pkg.By.id("loginbutton")).click();
WDS.log.info("Maximo Application ---- Logged by USER Name--- "+ '${username}');
WDS.sampleResult.sampleEnd();
I really Wann to switch on groovy as all coming scenarios are going to be complex
WDS_javascript
i could give you the guidance about your code.
in general, even when you are using javascript in jmeter - you are calling java methods.
groovy will do the same but in syntax it's closer to java.
so:
declare variables with def instead of var
change JavaImporter(XYZ) to import XYZ at the beginning of script
remove all java imported variables as they not needed. such as support_ui
just an example:
import org.openqa.selenium.*; //need .* to import all classes from package
import org.openqa.selenium.support.ui.WebDriverWait; //import exact class
WDS.sampleResult.sampleStart(); //code remains the same
//var pkg = JavaImporter(org.openqa.selenium); //moved to import
//var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait); //moved to import
def wait = new WebDriverWait(WDS.browser, 5000); //removed `support_ui.`
def userName = WDS.browser.findElement(By.id('username')); //removed `pkg.`
and finally just learn java & groovy

cross platform settings directory

I am making a jython application that needs a config/settings file (and probably eventually directory) but I want it be stored in the expected/correct directory for each os.
~/.app_name/config in linux
c:/documents and Settings/User/app_name ?? in windows.
I have found this:
http://snipplr.com/view/7354/home-directory-crossos/
but this is for python and I have feeling that this might not necessary work for jython/windows and I don't have any dev stuff set up in my windows VM to test at this moment
If someone could provide any insight into the "best practices" (for jython) for achieving this I would greatly appreciate it.
Thanks.
EDIT:
Here is what I have come up with that seems to be working...I would appreciate any feedback
import os
from java.lang import System
from java.io import File
os_name = System.getProperty('os.name')
os_sep = File.separator
app_name = 'ctrlmac'
if os_name == 'Windows':
config_dir = os.environ["APPDATA"] + os_sep + app_name
else:
config_dir = os.path.expanduser("~") + os_sep + '.' + app_name
print config_dir

Resources