Setting returned text to open an app in applescript - ios

I have a apple script program that I am programming and I want the text the user sends to open an application, But I keep getting error messages saying "Can't get application {"name_of_app"} of <>. The code I very simple and I cant figure out the problem
set deReturnedItems to (display dialog "How many spam messages?" with icon stop default answer "" buttons {"Quit", "OK"} default button 2)
set xpp to text returned of deReturnedItems
set theReturnedItems to (display dialog "How many spam messages?" with icon stop default answer "" buttons {"Quit", "OK"} default button 2)
set amt to the text returned of theReturnedItems
set daReturnedItems to (display dialog "Last thing, what should the spam message say?" default answer "" buttons {"Quit", "OK"} default button 2)
set msg to the text returned of daReturnedItems
repeat [amt] times
tell application [xpp]
activate
tell application "System Events"
keystroke [msg]
keystroke return
end tell
end tell
end repeat

Get rid of those square brackets. Don't use them for variables. Use underscores before and after if you must, like:
repeat _amt_ times
…
end
Also, you need to check to make sure your variable is an integer before you use it in the repeat block.
Incidentally, when you set a variable and then include it in brackets, that's applescript syntax for set the string to a list. For example:
set [x, y, z] to "123"
return x
-- returns "1", and y is set to "2", and z is set to "3"

Related

How to detect if a field contains a character in Lua

I'm trying to modify an existing lua script that cleans up subtitle data in Aegisub.
I want to add the ability to delete lines that contain the symbol "♪"
Here is the code I want to modify:
-- delete commented or empty lines
function noemptycom(subs,sel)
progress("Deleting commented/empty lines")
noecom_sel={}
for s=#sel,1,-1 do
line=subs[sel[s]]
if line.comment or line.text=="" then
for z,i in ipairs(noecom_sel) do noecom_sel[z]=i-1 end
subs.delete(sel[s])
else
table.insert(noecom_sel,sel[s])
end
end
return noecom_sel
end
I really have no idea what I'm doing here, but I know a little SQL and LUA apparently uses the IN keyword as well, so I tried modifying the IF line to this
if line.text in (♪) then
Needless to say, it didn't work. Is there a simple way to do this in LUA? I've seen some threads about the string.match() & string.find() functions, but I wouldn't know where to start trying to put that code together. What's the easiest way for someone with zero knowledge of Lua?
in is only used in the generic for loop. Your if line.text in (♪) then is no valid Lua syntax.
Something like
if line.comment or line.text == "" or line.text:find("\u{266A}") then
Should work.
In Lua every string have the string functions as methods attached.
So use gsub() on your string variable in loop like...
('Text with ♪ sign in text'):gsub('(♪)','note')
...thats replace the sign and output is...
Text with note sign in text
...instead of replacing it with 'note' an empty '' deletes it.
gsub() is returning 2 values.
First: The string with or without changes
Second: A number that tells how often the pattern matches
So second return value can be used for conditions or success.
( 0 stands for "pattern not found" )
So lets check above with...
local str,rc=('Text with strange ♪ sign in text'):gsub('(♪)','notation')
if rc~=0 then
print('Replaced ',rc,'times, changed to: ',str)
end
-- output
-- Replaced 1 times, changed to: Text with strange notation sign in text
And finally only detect, no change made...
local str,rc=('Text with strange ♪ sign in text'):gsub('(♪)','%1')
if rc~=0 then
print('Found ',rc,'times, Text is: ',str)
end
-- output is...
-- Found 1 times, Text is: Text with strange ♪ sign in text
The %1 holds what '(♪)' found.
So ♪ is replaced with ♪.
And only rc is used as a condition for further handling.

IsTradeAllowed not returning what I would expect

Please see the script below:
void OnStart()
{
Alert(IsTradeAllowed()); //alert 1
Alert(IsTradeAllowed(NULL, TimeGMT())); //alert 2
Alert(IsTradeAllowed(Symbol(), TimeGMT())); //alert 3
Alert(IsTradeAllowed("GBPUSD", TimeGMT())); //alert 4
}
This returns:
true //for alert 1
true //for alert 2
false //for alert 3
false //for alert 4
As alert 2 returns: true, then I would expect alert 3 and alert 4 to return true.
I have tried running the code at multiple times of the day on weekdays. The code returns the same result at weekends. I have also tried putting the code in a script and an EA. Every time I get the same result. Is there an explanation for this? I have tried what is suggested here: https://www.mql5.com/en/docs/runtime/tradepermission
Symbol() returns: "GBPUSD". Each alert should return true in my mind, however this does not appear to be the case here. Incidentally I have notices that Symbol() returns the symbol at the top of the demo account watchlist if the script is run inside MetaEditor, however it returns the symbol displayed on the chart if run inside the demo account.
The broker is Oanda.
Update 04/03/21 at 19:55
I have now discovered that if I right click on the Market Watch and select: show all, then more symbols appear. I can then see that some symbols are greyed out and some symbols are not. The symbols that are not greyed out e.g. USDGBP-g return what I would expect when running the program above i.e. alert 1-alert 4 =true. The symbols that are greyed out e.g. USDGBP returns true; true; false; false in the program above. I now have two questions:
Why does: IsTradeAllowed(NULL, TimeGMT()); //alert 2 return true for symbols that are greyed out?
What does -g mean in GBPUSD-g?
IsTradeAllowed checks if the Expert Advisor is allowed to trade and trading context is not busy.
The version of the function without any arguments will check if the EA has been applied with the correct permissions ("Allow live trading" ticked and "AutoTrading" enabled).
The second form of the function:
bool IsTradeAllowed(const string symbol, datetime tested_time);
checks if the EA would be allowed to trade according to the specifications for the chart selected (to view this, from the Market Watch window right click a symbol, from the menu that pops up select "Specification").
For example
IsTradeAllowed(Symbol(), D'2021.03.06 12:00');
would check if the current symbol can be traded this coming Saturday (which should be false).
If you are getting undesirable results you should check that your broker has set the "Specifications" correctly.
EDIT
I've tested the command in OANDA which is the broker you are using and the command functions as expected.
NULL is not valid for a Symbol and its use makes the command function in its first form (ie timedate is ignored).
I would suggest rather than use Alerts to examine output, try the following.
string cmnt;
cmnt=StringConcatenate("Alert 1: ",IsTradeAllowed());
cmnt=StringConcatenate(cmnt+"\r\n","Alert 2: ",IsTradeAllowed(NULL, TimeGMT()));
cmnt=StringConcatenate(cmnt+"\r\n","Alert 3: ",IsTradeAllowed(Symbol(), TimeGMT()));
cmnt=StringConcatenate(cmnt+"\r\n","Alert 4: ",IsTradeAllowed("GBPUSD", TimeGMT()));
Comment(cmnt);
I tried your script in my ICMarkets version of MetaTrader4. With disabled auto trading i get result:
When I set auto trading to enable using Ctrl+E shortcut, in all cases script return true.
I recommend you to try this script on another account or different broker. If this will help, you should communicate with your broker about this issue. The last option is a reinstall MetaTrader to make sure, that all config files are correct.

Applescript Result (links as text) to URL

It seems not as easy as i thought it should be.
My Script fetches Link URL's from websites
As of now, the resulting URL's are just text and i need them to be put out as URL's (clipboard or variable) to paste them into an email message
I have tried various things from saving first to a rtf file and reading/pasting it to my email message body or copy and paste trough the clipboard.
Any help would be awesome as i can't get this solved since 2 days. Thanks
--prompt for keyword
display dialog "Keyword or Sentence" default answer "mad dog" buttons {"Done"} default button 1
set Keyword to text returned of the result
--create URL filter from Keyword
set my text item delimiters to " "
delay 0.2
set split_list to every text item of Keyword -- split in to list of everything between the spaces
set my text item delimiters to "-"
set Filter to (split_list as text) -- join, using the - as the delimter
--Open Pages
set site_url to "https://teespring.com/search?q=" & Keyword
tell application "Safari"
activate
open location site_url
end tell
-- wait until page loaded
property testingString : "Help" --Text on website to look for
set pageLoaded to false
tell application "Safari"
repeat while pageLoaded is false
set readyState to (do JavaScript "document.readyState" in document 1)
set pageText to text of document 1
if (readyState is "complete") and (pageText contains testingString) then set pageLoaded to true
delay 0.2
end repeat
end tell
-- get number of links
set theLinks to {}
tell application "Safari" to set num_links to (do JavaScript "document.links.length" in document 1)
set linkCounter to num_links - 1
-- retrieve the links
repeat with i from 0 to linkCounter
tell application "Safari" to set end of theLinks to do JavaScript "document.links[" & i & "].href" in document 1
end repeat
theLinks
set nonExcludedURLs to {}
--Filter URLs
repeat with i from 1 to length of theLinks
if item i of theLinks contains Filter then
set end of nonExcludedURLs to item i of theLinks
end if
end repeat
nonExcludedURLs
on page_loaded(timeout_value)
delay 2
repeat with i from 1 to the timeout_value
tell application "Safari"
if (do JavaScript "document.readyState" in document 1) is "complete" then
set nonExcludedURLs to {}
return true
else if i is the timeout_value then
return false
else
delay 1
end if
end tell
end repeat
return false
end page_loaded
Found the solution. Maybe i described the problem not very well.
I just needed to split the resulting url's from a block of text to single lines with the following code:
set Single_URLs to ""
repeat with this_line in nonExcludedURLs -- the URL's as block of text
set Single_URLs to Single_URLs & this_line & return --split into lines
end repeat

Changing contents of global variables in a Lua script for Awesome Window Manager?

So I've been trying to configure my Awesome WM config (rc.lua) to detect if my IBM model M13 is connected to my laptop upon login/reset. This is to change what the modkey should be since the M13 doesn't have a super key.
The following code makes sense to me and changes modkey within the function being made for the awful.spawn.easy_async function, but after finishing the modkey changes back to Mod4.
modkey = "Mod4"
awful.spawn.easy_async(
"xinput list",
function(stdout, stderr, reason, code)
local msg = "Regular keyboard Modkey = Super"
-- Debug notification that shows that the modkey is
-- at its default for the superkey Mod4
naughty.notify({
text = modkey,
timeout =7
})
if code ~= 0 then
msg = "Missing xinput to see devices\nModkey = Super"
elseif stdout:match("CHESEN") == "CHESEN" then
-- CHESEN is my PS/2 to USB adapter
msg = "IBM M13 detected\nModkey = Alt"
modkey = "Mod1" -- Sets new modkey to Alt
end
-- Notification message
naughty.notify({
text = msg,
timeout =7
})
end
)
-- Debug notification to verify key but key goes back to Mod4
naughty.notify({
text = modkey,
timeout =7
})
The output can be seen here. It doesn't print the notifications in order but the prints of Mod 4 are both of the debug prints.
Notification Output
I don't use Lua much aside from changing my configs from time to time so I'm having difficulty understanding how my global variable modkey can be changed with out it resetting. Other methods I tried was to have the function defined as a function I called setModKey to be passed as a parameter to easy_async and I tried setting modkey using _G to set it as _G.modkey, but I end up getting the same result.
Am I missing something fundamental to Lua or is this affected by how Awesome WM utilizes Lua? Any help will be very appreciated.
Use io.popen instead of awful.spawn.easy_async. Yes, normally using io.popen is really not recommended, but here the following happens:
Awesome starts
You call easy_async to capture the output of xinput list
Since it is async, your config continues to be loaded, so e.g. all your keybindings are set
easy_async does its job and you set modkey to something else.
This means that any keybinding which will be defined from now on use the new modkey, but all already-existing keybindings are not modified by this. So, basically nothing happens.
And for your debugging calls to naughty.notify: The one after the function is triggered first and only then, later, the inner one triggers. So it does not go back, but instead you first show the old value and only later the new one.

World of Warcraft Lua - Changing frame:SetAttribute()

I'm working on an addon for World of Warcraft that completely overhauls the interface to adapt to my play style.
In this addon, I would like to have a large button that acts as a "main dps rotation" for my mage. I would like it to change what spell it casts based on what is optimal at any given time. It doesn't cast the spell automatically, it just presents the next best option for the user.
Here is my code so far:
print "Interface Overhaul : LOADED"
heatingUpIsActive = false
print(heatingUpIsActive)
local Button = CreateFrame("Button", "MyButton", UIParent,"SecureActionButtonTemplate")
Button:SetWidth(256)
Button:SetHeight(256)
Button:SetFrameStrata("HIGH")
Button:SetPoint("LEFT")
Button:SetText("Main Rotation")
Button:RegisterForClicks("AnyUp")
Button:SetAttribute("type", "spell")
Button:SetAttribute("spell", "Fireball")
Button:RegisterEvent("UNIT_AURA");
local function auraGained(self, event, ...)
if (UnitAura("player", "Heating Up")) then
if (heatingUpIsActive == false) then
heatingUpIsActive = true
print (heatingUpIsActive)
print ("Heating Up is active!")
Button:SetAttribute("spell", "Inferno Blast")
end
else
heatingUpIsActive = false
print("Heating Up is NOT active.")
print(heatingUpIsActive)
end
end
Button:SetScript("OnEvent", auraGained);
local tex = Button:CreateTexture("ARTWORK");
tex:SetPoint("LEFT")
tex:SetWidth(256)
tex:SetHeight(256)
tex:SetTexture("Interface\\AddOns\\InterfaceOverhaul\\Button2")
If heatingUpIsActive == true, I would like the button to cast ("spell", "Inferno Blast") instead of ("spell", "Fireball"), but it doesn't work if I place that into the correct part of the if statements.
Any thoughts?
As Mud said, you cannot rebind buttons in combat anymore. Blizzard made this change to prevent bots from being able to automate combat. Notably, in order to cast a spell you need to use one of the secure templates, and these secure templates only allow modification of the attributes that control what they do when you're not in combat. So you cannot have one button change spells mid-combat. Similarly, they also prevent you from modifying attributes like their position or visibility, so you cannot move buttons under the mouse either.
The best you can do is display a visual indicator of what spell should be cast, but rely on the user to actually press the correct button.

Resources