Auto Hot Key
220 subscribers
7 files
17 links
Created using ahk with love ❤️

@Lencore
Download Telegram
🔢 FormatNumber()

Функция превращает обычные числа в более читаемые, разделяя каждые три символа с конца числа запятой для улучшения читаемости. Символ разделения можно заменить на пробел, точку или любой другой. В приложении код для первой и второй версии ahk.

The function creates comma-separated numbers from integers for better readability. It separates every 3 symbols from the ending by comma. Separator can be changed to space, dot etc. There are scripts for both ahk v1 and v2 in the attachment.

v1:
FormatNumber(Amount) {
StringReplace Amount, Amount, -
IfEqual ErrorLevel,0, SetEnv Sign,-
Loop Parse, Amount, .
If (A_Index = 1) {
len := StrLen(A_LoopField)
Loop Parse, A_LoopField
If (Mod(len-A_Index,3) = 0 and A_Index != len)
x = %x%%A_LoopField%,
Else x = %x%%A_LoopField%
} Else Return Sign x " " A_LoopField
Return Sign x
}

v2:
FormatNumber(Amount) 
{
Amount := StrReplace(Amount, "-",,,, 1)
x := ""
Sign := ""
Loop Parse, Amount, "."
If (A_Index = 1) {
len := StrLen(A_LoopField)
Loop Parse, A_LoopField
If (Mod(len-A_Index,3) = 0 and A_Index != len)
x := x . "" . A_LoopField . ","
Else x := x . "" . A_LoopField
} Else Return Sign x " " A_LoopField
Return Sign x
}

Источник / Source: link
v2: @Lencore
#Script
📆 Получение Unix-времени / Getting Unix-time

Получение текущего Unix-времени (количество секунд от января 1970) для первой и второй версии ahk.

Getting current Unix-timestamp (measure in seconds since 1970's January) for both v1 and v2.

v1:
Time := A_NowUTC
EnvSub, Time, 19700101000000, Seconds

v2:
UnixTime := DateDiff(A_NowUTC, 19700101000000, "Seconds")

Источник / Source: документация / docs
#Script
📆 Конвертация UNIX-времени в DATE / Convert from UNIX to DATE

Облазил кучу сайтов, но почему-то для всех это оказалось слишком трудной задачей, хотя решается в одну строку. Вместо UNIXTIME подставить свое значение.

Replace the UNIXTIME with your value.

v1:
Date := 19700101000000
Date += UNIXTIME, seconds

v2:
Date := FormatTime(DateAdd(19700101000000, UNIXTIME, "seconds"), "d MMMM yyyy, H:mm")


Источник / Source: документация / docs
#Script
💱 Кодирование текста в URI / Encoding text to URI

Скрипт форматирует заданный текст в URI по одному символу без использования сторонних скриптов.

The script converts given text to URI char by char without using external scripts/libs.

v1:
URIEncodeChar(c) {
char := Chr(c)
If (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or (c >= 48 and c <= 57) or (c = 45) or (c = 95) or (c = 46) or (c = 33) or (c = 126) or (c = 42) or (c = 39) or (c = 40) or (c = 41) {
Return char
}
enc := ""
hex := Format("{:x}", c)
if (Len(hex) = 1)
hex := "0" . hex
enc .= "%" . hex
Return enc
}

URIEncode(str) {
encStr := ""
Loop, Parse, str
{
c := Ord(A_LoopField)
encStr .= URIEncodeChar(c)
}
Return encStr
}


v2:
URIEncodeChar(c) 
{
char := Chr(c)
If (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or (c >= 48 and c <= 57) or (c = 45) or (c = 95) or (c = 46) or (c = 33) or (c = 126) or (c = 42) or (c = 39) or (c = 40) or (c = 41)
Return char
enc := ""
hex := Format("{:x}", c)
if (strLen(hex) = 1)
hex := "0" . hex
enc .= "%" . hex
Return enc
}

URIEncode(str)
{
encStr := ""
Loop Parse str
{
c := Ord(A_LoopField)
encStr .= URIEncodeChar(c)
}
Return encStr
}

Источник / Source: ChatGPT
#Script
📩 Отправка и получение данных по MQTT / Sending and receiving data using MQTT

Скрипт отправляет и получает данные от брокера. Можно добавить логин и пароль. На v1 не переводил, если кому-то не лень, можете заняться, добавлю. В папку со скриптом нужно закинуть папку mosquitto.

The script sends and gets data from broker. It is possible to use login and password. Have no time to transfer to v1, pm me if you are ready to do this. The script needs a mosquitto folder in the script's folder.

v2:

Send data

publish(topic, message)
{
shell := ComObject("WScript.Shell")
pubCmd := a_scriptdir "\mosquitto\mosquitto_pub.exe -h test.mosquitto.org -p 1883 -t " topic " -m '" message "'"
shell.Run(pubCmd, 0, true)
shell.ObjRelease()
}


Get data

shell := ComObject("WScript.Shell")
subCmd := a_scriptdir "\mosquitto\mosquitto_sub.exe -h " mqttHost " -p " mqttPort " -t " topic
subProcess := shell.Exec(subCmd)
OnMessage(subProcess)

OnMessage(subProcess) {
While (!subProcess.StdOut.AtEndOfStream) {
msg := subProcess.StdOut.ReadLine()
MsgBox "Сообщение получено:" "`n" msg
}
}

Источник / Source:
GPT-4, @Lencore
#Script
Please open Telegram to view this post
VIEW IN TELEGRAM
📬 Отправка данных в другой скрипт / Send data to another script

В первой функции меняем ANOTHER SCRIPT на название своего второго скрипта, аргумент функции — что нужно передать. Во втором скрипте после получения данных можно обработать их прямо в функции, либо вернуть в тело и работать там.

In the first function, change ANOTHER SCRIPT onto your another script name, an argument of functions is data to send. In the second function, you can catch data into variable and proceed directly in function or return it to script body.

v2:

Send data:

SendWM(StringToSend)
{
TargetScriptTitle := "ANOTHER SCRIPT.ahk ahk_class AutoHotkey"
CopyDataStruct := Buffer(3*A_PtrSize)
SizeInBytes := (StrLen(StringToSend) + 1) * 2
NumPut( "Ptr", SizeInBytes, "Ptr", StrPtr(StringToSend), CopyDataStruct, A_PtrSize)
DetectHiddenWindows True
SetTitleMatchMode 2
TimeOutTime := 4000
SendMessage(0x004A, 0, CopyDataStruct,, TargetScriptTitle)
}


Get data:

Persistent 1
OnMessage 0x004A, Receive_WM_COPYDATA

Receive_WM_COPYDATA(wParam, lParam, msg, hwnd)
{
data := StrGet(NumGet(lParam, 2*A_PtrSize, "Ptr"))
}


Источник / Source: неизвестно / unknown

@AutoHotKey
#Script
Please open Telegram to view this post
VIEW IN TELEGRAM
🌐 Rufaydium — упрощенная замена Selenium для ahk v1/2, которая осталась незамеченной. Про него рассказал только Automator, и он же опубликовал версию для V2 под своим "лейблом". Может, кому-то будет полезно. Но так как по инструменту мало гайдов, у него все еще высокий порог входа. Пользуйтесь на здоровье.

🌐 Rufaydium — simplified Selenium analogue for ahk v1/2 that was not mentioned. Only the Automator told about it and published its version for v2 under his "label". Maybe it will be useful for you. There are still few guides about Rufaydium, and it requires some skills to use. Enjoy.

Источник / Source: Xeo786

@AutoHotKey
#Script #Library #Class
📊 Вычисление среднего отклонения по массиву (стандартная девиация). В основном используется в финансах. Если вы не знаете, для чего он, скорее всего он вам не нужен, но скрипт в любом случае полезный.

📊 Standard deviation calculation for array, Mainly used in finance. If you don't know what it's for, you probably don't need it, but the script is useful anyway.

v1 / v2:

nums := [20.4, 18.0, 1.4, -8.6, -14.4, 3.0, -38.8, 20.9, -4.2, 131.0, -43.2, 4.6]
msgbox Round((StandardDeviation(nums)/100), 2)

StandardDeviation(arr) {
mean := sd2 := 0
for val in arr
mean += val
mean /= arr.Length
for val in arr
sd2 += (val - mean) ** 2
return sqrt(sd2 / arr.Length)
}


Источник / Source:
https://www.autohotkey.com/boards/viewtopic.php?p=560434#p560434

@AutoHotKey
#Script
Please open Telegram to view this post
VIEW IN TELEGRAM