How to decode HEX code to regular text in Apple Script - perl

I'm using the todo list app Things from Cultured Code on my Mac and when I copy a link to a task to clipboard it ends up encoded as HEX code in the clipboard. No problem when I paste it into a text file – it then shows as decoded text.
But, I need to use the clipboard content in an AppleScript and have difficulties decoding it to plain text there.
I have tried multiple subroutines but they did not work in my case. Most examples that I found online deal with simple encoded URLs. And the code that I have so far works to decode for example "0348" correctly to the number 1000 but my script cannot decode the encoded Things link (that long line of numbers at the top).
Can somebody help me please?
Here's what I have so far:
-- The link to a task in THINGS, encoded: 7468696e67733a2f2f2f73686f773f69643d41463645303746462d394230462d343539332d423143332d313846303337434237363836
-- Above link to the task in THINGS, unencoded: things:///show?id=AF6E07FF-9B0F-4593-B1C3-18F037CB7686
-- Online converter: http://www.unit-conversion.info/texttools/hexadecimal/
-- Number 1000 encoded: 03E8
set theEncodedText to "03E8"
set theDecodedText to (do shell script "perl -e 'printf(hex(\"" & theEncodedText & "\"))'") as string
set theDisplayedText to theDecodedText
display dialog theDisplayedText
Thank you,
Martin

The following example AppleScript code is a proof of concept of how I'd handle setting to a variable a Things URL link that's saved to the clipboard as «data url ...» where ... is Hex Data.
This script writes the «data url ...» to a temporary file, reads the temporary file, which is now a text string of the «data url ...», and sets it as a the value of a variable, and then deletes the temporary file. It then displays the Things URL link as a text string or displays a message that the clipboard did not contain a 'things:///show?id=' URL link.
Example AppleScript code:
if ((clipboard info) as string) contains "URL" then
set thingsURL to "/tmp/thingsURL.tmp"
try
set f to open for access thingsURL with write permission
set eof f to 0
write (the clipboard) to f
close access f
on error
close access f
end try
set thingsURLtext to (read thingsURL)
tell application "System Events" to delete file thingsURL
display dialog thingsURLtext buttons {"OK"} default button 1
else
display dialog "The clipboard did not contain a 'things:///show?id=' URL link." buttons {"OK"} default button 1
end if
Note: The example AppleScript code is just that and does not employ any other error handling then what's shown and is meant only to show one of many ways accomplish a task. The onus is always upon the User to add/use appropriate error handling as needed/wanted.

Related

How to replace value in txt file with powershell from GitHub

I want to build a simple script that may be useful for others as well, but I have only very basic programming knowledge and can't do it myself without learning how to write powershell scripts from scratch.
What this script is supposed to do is, open an INI file (really just a txt), look for a variable with an assigned value and replace that value from a txt hosted on GitHub, save and then run a program.
This is for the tracker list of qBittorrent, since that feature still hasn't been implemented and the only other script that I could find that does this is for linux and mac, there seem to be none for windows.
The basic idea is this:
get-content "c:\users\[user]\appdata\roaming\qbittorrent\qbittorrent.ini"
# This is where pseudo code starts
get file from "[github-link.txt]"
save file to cache # keeping it is useless as it gets updated daily
find variable "Session\AdditionalTrackers=" in qbittorrent.ini
replace value of variable with content of cached file # this is what I struggle with most when looking for example code. Everything I could find specified the exact string that needed replacing, which in this case is quite long and may change with every update of the file.
overwrite original file
launch program qbittorrent.exe
end script
Conveniently or most likely deliberately all (most) of the tracker lists on GitHub are already formatted in a way that they can be directly pasted into the file without having to worry about formatting. Example.
I can totally understand if nobody wants to do the work, but I would greatly appreciate it and possibly others that are looking for a stopgap for the lacking feature.
If this already exists, go ahead and call me an idiot and while you're at it drop a link ;)
I just found a little tool called Power Automate and it pretty much does what I was looking for. It's not quite as elegant as a single click script but it does the job. Sadly I can't share the "flow" I built because, well, there is no option for it - thanks Microsoft. So, I'll try my best to write it out.
Not quite a "solution" but pretty to close to it.
Here is the "flow":
get file from web // from github for example
read text from file // read downloaded .txt file
read text from file // read qBittorrent.ini
crop text // crop between flags in qBittorrent.ini use "Session\AdditionalTrackers=" as start and "Session\GlobalMaxRatio=" as end and save to cropVar2
crop text // crop before flag use "Session\AdditionalTrackers=" as flag and save to cropVar1
crop text // crop after flag use cropVar2 as flag and save to cropVar3
replace text // replace cropVar2 with content of downloaded file and save to cropVar2
write text to file // write cropVar1,cropVar2,cropVar3
end flow
Keep in mind that any changes to the qBittorrent.ini may change the order of the entries. Which means you have to check if it's still correct after every update and after every change you make in the options. This is a massive cludge after all...
You can input fail saves so that you won't break anything if the order changed.

How to use 'fprintf' to show the output in a txt file and save it instead of command window in Matlab?

I've been trying to make the output shown in the text file instead of the command window. Im blur right now as i already look at a lot of example but it always show the error on fprintf. I try to edit the code of fprintf(fid,'%s\n',word);%Write 'word' in text file (upper) in one of the Matlab example which is Automatically Detect and Recognize Text in Natural Images.
This is the link of the code.
https://www.mathworks.com/help/vision/examples/automatically-detect-and-recognize-text-in-natural-images.html?s_tid=srchtitle
Basically the above link display the output on the command window. But, i need it to be on the txt file.
Im really new to this, i want to know what code do i need to put, how and where should i put the fprintf to make the output shown on the text file and not on the command window.
Also, can i save the text file after that? do i to put any additional code?
I really need your help. Thank u in advance!
It seems you're looking for the fopen() method. It takes two parameters, the first being the name of the file you'd like to write to, and the second being the mode. If the file specified does not exist in the root directory, it will be created on execution.
fileID = fopen('exp.txt','w');
fprintf(fileID, fid,'%s\n', word);
fclose(fileID); % Make sure to always close the stream after finishing
More on fopen() here

How to have Autohotkey 'listen' for a change to a file?

I have a text file, lets call it C:\to_run.txt. I'd like my Autohotkey script to 'listen' to this file in such a way that when it detects a change, it performs an action immediately based on the contents of the file, and then make the file blank again.
I can handle the last parts, so really I'm asking for an efficient way to detect file changes? I say efficient because my Autohotkey script is getting rather long and I don't want this listening function to hang up the rest of the script in any way.
Assuming we are really talking of only one file to check on:
Surely not as beautiful as Sidola's answer, but without the need for external libraries:
#persistent
lastFileContent := ""
setTimer, checkFile, 20
return
checkFile:
fileread newFileContent, changingDocument.txt
if(newFileContent != lastFileContent) {
lastFileContent := newFileContent
msgbox, content changed to: %newFileContent%
}
return
In this case, for checking on larger files, it might be better to compare MD5-checksums instead of the whole file content.
Note: I have not tested the performance implications on this. This script opens up the file 50 times per second, could be pretty hard drive consuming.
Check out WatchDirectory()
Just make sure you're running the latest version of AHK.
To get it up and running, first download these three scripts and save them to your /lib folder.
WatchDirectory.ahk
_Struct.ahk
sizeof.ahk
After that, simply point to to wherever you want to look, provide a callback function and if you want, a third param to watch for specific changes. Refer to this forum post for full documentation.
If you drop this script in its own folder, save it and run it, then save it again, it should detect changes to that script file.
#Persistent
WatchDirectory(A_ScriptDir "\|.ahk\", "Callback", 0x10)
return
Callback(param1, param2) {
msgBox % param1 "`n" param2
}
Note however, it will fire twice whenever the file is changed. This seems to be a Windows behaviour from what I can gather.

IDA Pro: How to change the virtual segment register T in a script

If I press option/alt-G, IDA shows a dialog which allows me to change the value of the T segment register to 1 to indicate that the following bytes should be interpreted a Thumb code.
I would like to be able to change the value of T in a script.
What script function can I use?
Try
SetRegEx(addr,"T",val,SR_user);
I found this by doing it manually, then clicking File | Produce file | Dump Database to IDC file.. and reading the commands used at the manual process location above.
Then read your idc.idc files to for the syntax of the above command.

Is there a way to attach a file (.txt) in calc open office programmatically (using macro)?

I have a .txt file that I need to attach in a column of my sheet, and i have the path to this file.
So I need to read this path and attach the file in another column programmatically. Is there a way to do it?
thanks in advance.
Indeed there is! And using by using macros it is quite easy to do.
Enabling macros
Go to the Tools > Options menu and click on the Security section under OpenOffice.org. Once there, click the Macro Security button. Now on the Security Level Tab, make sure that your settings will allow you to run Macros.
My settings are on low because I'm the author of all the macros I run, if you are not sure that this will be your case you might want to use a higher setting.
Note: Be careful, if you are unlucky or live in the 90's an evil macro can cause serious damage!
Creating a new macro
Now that you can run them, you must create a new macro. OpenOffice accepts a wide range of languages including Python, but since you didn't specified any I'll use OO's version of basic here.
Go to Tools > Macros > Organize Macros > OpenOffice.org Basic, and once there add a new module under your file's tree. Give it a meaningful name.
The actual macro
Once you create a new module the editor screen will pop up, write this code below:
Sub DataFromFile
Dim FileNo As Integer
Dim CurrentLine As String
Dim File As String
Dim Msg as String
Dim I as Integer
' Get the filename from the cell, in this case B1.
currentSheet=ThisComponent.CurrentController.ActiveSheet
fileName = currentSheet.getCellRangeByName("B1").getString
' Create a new file handler and open it for reading
FileNo = FreeFile
Open fileName For Input As #FileNo
I = 0
' Read file until EOF is reached
Do While not eof(FileNo)
' Read line
Line Input #FileNo, CurrentLine
' Define the range to put the data in as A4:A999 '
curentCell = currentSheet.getCellRangeByName("A4:A999").getCellByPosition(0,I)
' Select the I-th cell on the defined range and put a line of the file there
curentCell.String = CurrentLine
'Increase I by one
I = I + 1
Loop
Close #FileNo
End Sub
To test it, just create a text file and put something in it, then put the path to it on cell B1 and run the macro. You can run the macro in many ways, for test purposes just use the Run button on the same window that you used to create the module. This is the expected result:
Note: If you are unfamiliar with linux, don't be intimidated by that file path, it's just how they are on linux. This would just work the same with windows and it's file path structure.
Further improving the macro
I wrote the code above with the goal of making it as easy to understand as possible, therefore the macro have plenty of room for improvement, such as:
Being able to show the data retrieved on multiple columns/A single column/Something else
Once you have retrieved the data from the file, you can display it on your spreadsheet in nearly anyway you want it. Let me know if the way you initially intended was not addressed and I will edit the answer.
Having to re-run the macro every time you want the data updated.
This is easily fixed. There are many ways to automatize the macro execution, the one I'm most familiar with consists on making it run on a loop in conjunction with a delay of, say, 5 seconds and making it start as soon as the file loads.
Sub Main
Do While True
DataFromFile()
Wait(5000)
Loop
End Sub
And from now on you should call the Main sub instead of the DataFromFile.
To make the macro run at start-up go to Tools > Customize on the Events tab and select Open Document from the list then click on the Macro button. On the dialog to select the macro, pick Main. Now close the document, reopen it, and voila!
Using Cell Ranges
It's easier to keep your code and make changes to it if you name the cell ranges and use their names instead of their absolute address. To name a range (or a single cell) you must first select it then click on Data > Define Range to give it a name, for example B1 could be called 'FilePath' and A4:A999 could be called 'DataRange'. This way if you ever need to change them, you don't have to change the macro, just the defined range name.
Don't forget to update the code to look for the range instead of the address, for example, this bit of code:
getCellRangeByName("A4:A999")
would be rewritten to
getCellRangeByName("DataRange")
Error checking
It is a good idea to check and deal with error or unexpected events. What if the file doesn't exists? What if it is bigger than the defined range?
Further reading
Official reference regarding files for OpenOffice Basic macros.
A guide on different ways to run a macro
A great introduction to macro programming