
noellarkin
Active Members-
Posts
156 -
Joined
-
Days Won
2
Everything posted by noellarkin
-
Found a possible solution here but not sure how I can implement it in AutoIt: https://stackoverflow.com/a/75925250 Actually, this exactly what the set_context() method is for. https://github.com/SeleniumHQ/selenium/blob/selenium-4.8.0/py/selenium/webdriver/firefox/webdriver.py#L224-L247 For example: driver.set_context("chrome") driver.execute_script("Services.prefs.setStringPref('intl.accept_languages', 'es-ES');") driver.set_context("context") Make sure you switch back to "context" or else you won't be able to continue. In the linked Github: def set_context(self, context) -> None: self.execute("SET_CONTEXT", {"context": context}) @contextmanager def context(self, context): """Sets the context that Selenium commands are running in using a `with` statement. The state of the context on the server is saved before entering the block, and restored upon exiting it. :param context: Context, may be one of the class properties `CONTEXT_CHROME` or `CONTEXT_CONTENT`. Usage example:: with selenium.context(selenium.CONTEXT_CHROME): # chrome scope ... do stuff ... """ initial_context = self.execute("GET_CONTEXT").pop("value") self.set_context(context) try: yield finally: self.set_context(initial_context) To specify, I want to change a preference when I'm already running geckodriver, it isn't something I want to set in `_WD_CapabilitiesAdd`.
- 1 reply
-
- webdriver
- webdriver udf
-
(and 1 more)
Tagged with:
-
In the old FF.au3 library, there were two functions for getting and setting values of about:config preferences for Firefox. I was wondering if there are any equivalents for WebDriver au3, @Danp2 Func _FFPrefGet($sName) Local Const $sFuncName = "_FFPrefGet" Local $sCommand Local $iType = _FFCmd('FFau3.obj=Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch); FFau3.obj.getPrefType("' & $sName & '");') If @error Then SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, $sName)) Return 0 EndIf Switch $iType Case 0 SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sName: " & $sName)) Return 0 Case 32 ; PREF_STRING $sCommand = "getCharPref" Case 64 ; PREF_INT $sCommand = "getIntPref" Case 128 ; PREF_BOOL $sCommand = "getBoolPref" EndSwitch $sCommand = StringFormat('FFau3.obj.%s("%s");', $sCommand, $sName) Return _FFCmd($sCommand) EndFunc ;==>_FFPrefGet Func _FFPrefSet($sName, $vValue) Local Const $sFuncName = "_FFPrefSet" Local $sCommand Local $iType = _FFCmd('FFau3.obj=Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);FFau3.obj.getPrefType("' & $sName & '");') If @error Then SetError(__FFError($sFuncName, $_FF_ERROR_InvalidValue, $sName)) Return 0 EndIf Local $vOldValue = _FFPrefGet($sName) Switch $iType Case 0 SetError(__FFError($sFuncName, $_FF_ERROR_NoMatch, "$sName: " & $sName)) Return 0 Case 32 ; PREF_STRING If Not IsString($vValue) Then SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(string) $vValue: " & $vValue)) Return 0 EndIf $sCommand = StringFormat('FFau3.obj.%s("%s","%s");', "setCharPref", $sName, $vValue) Case 64 ; PREF_INT If Not IsInt($vValue) Then SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(int) $vValue: " & $vValue)) Return 0 EndIf $sCommand = StringFormat('FFau3.obj.%s("%s",%s);', "setIntPref", $sName, $vValue) Case 128 ; PREF_BOOL If Not IsBool($vValue) Then SetError(__FFError($sFuncName, $_FF_ERROR_InvalidDataType, "(bool) $vValue: " & $vValue)) Return 0 EndIf $sCommand = StringFormat('FFau3.obj.%s("%s",%s);', "setBoolPref", $sName, __FFB2S($vValue)) EndSwitch _FFCmd($sCommand) If Not @error Then Local $vRetVal = _FFPrefGet($sName) If Not @error And $vRetVal = $vValue Then SetExtended($vOldValue) Return 1 Else SetError(__FFError($sFuncName, $_FF_ERROR_RetValue, "$vValue <> " & $vRetVal)) Return 0 EndIf EndIf Return 0 EndFunc ;==>_FFPrefSet
- 1 reply
-
- webdriver
- webdriver udf
-
(and 1 more)
Tagged with:
-
Eigen4AutoIt - Matrix computing with Eigen
noellarkin replied to RTFC's topic in AutoIt Example Scripts
hey, this thread doesn't get much love, but just wanted to say thanks for this, I use the vector operations (cosine similarity, primarily) to compare embeddings and do RAG (retrieval augmented generation) with LLMs- 93 replies
-
- matrix
- scientific computing
-
(and 1 more)
Tagged with:
-
This snippet works perfectly for nested spintax: However, I can't figure out how I can write a function that will output all the permutations of nested spintax. For example: for a string "John went to the {{grocery |}store|library}" I would get: John went to the library John went to the store John went to the grocery store ... I can't figure this out - - I can kinda figure it out if there isn't any nesting (regex out all the text between brackets)...but nesting makes it pretty complicated for me to wrap my head around :)
-
Script Fails when EXE, runs as au3
noellarkin replied to noellarkin's topic in AutoIt General Help and Support
@Danp2 thanks! -
This is strange. I wrote this function: Func _AU3_RunScript($scriptstring) Local $ReturnValue = 0 Local $ScriptFile = _WinAPI_GetTempFileName(@TempDir, "~") FileWrite($ScriptFile, $scriptstring) Local $ScriptRunning = RunWait(@AutoItExe & ' /AutoIt3ExecuteScript "' & $ScriptFile & '"', @TempDir, @SW_HIDE) If $ScriptRunning = 0 Then FileDelete($ScriptFile) $ReturnValue = 1 Else ConsoleWrite("ScriptRunning:" & $ScriptRunning) EndIf Return $ReturnValue EndFunc And to test it: _AU3_RunScript('MsgBox(0, "this", "message")') When I run it from SCITE it runs just fine. No errors, shows the message box. When I compile it into an exe (using SCITE) and run the EXE file, I get an an error at `If $ScriptRunning = 0 Then` - - I'm getting $ScriptRunning = -1 What am I missing?
-
Pool - Post Office for Organised Labour
noellarkin replied to RTFC's topic in AutoIt Example Scripts
At the moment I'm using the HTTPAPI server and have prescripted endpoints that I send requests to (each "agent" (slave in POOL terminology) computer on the LAN has the HTTPAPI server running as a service, and it catches the requests, adds them to queue. Each request is a POST with a request body containing the AutoIt script I want to run as a string. The agent parses the request body, compiles it into an EXE file and 'RunWait's it. It sends the exit code and errors, if any, back as an HTTP response to the "master" system). I've also figured out a way for the "Master" to broadcast commands to all the systems on LAN (for example, to update an application) using ChildProc + HTTP requests (spawns a new process for each HTTP request). How would POOL be an improvement over my rather rudimentary methods? -
Pool - Post Office for Organised Labour
noellarkin replied to RTFC's topic in AutoIt Example Scripts
@RTFC are you still using/maintaining this UDF? I was looking for a single UDF that covers remote execution within a LAN, coprocess and IPC, and this seems to cover everything :) -
So far, I've stuck to MsgBox and ConsoleWrite to debug scripts (+some SciTE Syntax Checks), but looking for something a little better. It seems both Heron's Debugger: http://www.autoitscript.com/forum/index.php?showtopic=103142 and "Another Debugger for Autoit" have been abandoned. I'm curious what tools forum members are using to debug scripts?
-
Nested Spintax in AutoIt?
noellarkin replied to noellarkin's topic in AutoIt General Help and Support
Ah I think this may have been it. The pipes shouldn't be there, of course, that threw me off, but I tried with this simpler example: $spintext = "{Hello{ooo| There}|Hi}, how's it going?" And got: Helloooo, how's it going? Hi, how's it going? Hi, how's it going? Hello There, how's it going? So yeah, script works, the input string in the example isn't valid spintax :) For future reference, a working script an example for nested spintax in Autoit: ;Spintax Test #include <Array.au3> ; Text in Spintax format ;~ Global $a = 1 $spintext = "{Hello{ooo| There}|Hi}, how's it going?" ConsoleWrite(Spintax($spintext) & @CRLF) ConsoleWrite(Spintax($spintext) & @CRLF) ConsoleWrite(Spintax($spintext) & @CRLF) ConsoleWrite(Spintax($spintext) & @CRLF) Func Spintax($sInput) ;~ ConsoleWrite("- Iteration "&$a&" Start -" & @CRLF) $SpinArray = StringRegExp($sInput, '{([^{]*?|[^{]*?)}',3); Global matches ;~ _ArrayDisplay($SpinArray,"") $sfinrep = StringReplace($sInput,"}|{","|") ; look For final replacing If Not IsArray($SpinArray) Then ;~ ConsoleWrite("!No Array!" & @CRLF) If $sfinrep = $sInput then ; Nothing replaced, so free of }|{ --> end string ;~ ConsoleWrite("+EndResult: " & @CRLF) Return $sInput EndIf ;else replace workstring with the string without }|{ for further processing $sInput = $sfinrep $SpinArray = StringRegExp($sInput, '{([^{]*?|[^{]*?)}',3); Global matches ;~ ConsoleWrite("final replaced string:" & @CRLF) ;~ ConsoleWrite($sInput & @CRLF) EndIf $TrimmedText = StringRegExpReplace($sInput, '{([^{]*?|[^{]*?)}',chr(0x1A)); or any other special char to mark where to insert $RNDText = $TrimmedText For $i = 0 To UBound($SpinArray)-1 $WordArray = StringSplit($SpinArray[$i], "|",3) $rnum = Random(0, UBound($WordArray)-1, 1); get random Array index $RNDText = StringReplace($RNDText, chr(0x1A), $WordArray[$rnum],1); replace only the next occurrence Next ;~ ConsoleWrite($RNDText & @CRLF) ;~ ConsoleWrite("- Iteration "&$a&" End -" & @CRLF) ;~ $a += 1 Return Spintax($RNDText) EndFunc Thanks @qsek and @water :)- 5 replies
-
- spintax
- nested spintax
-
(and 2 more)
Tagged with:
-
EXAMPLE #3 - TRANSPOSING A MATRIX #include <Eigen4AutoIt.au3> _Eigen_Startup() Local $Matrix = _Eigen_CreateMatrix(12, 15) _Eigen_SetRandom($Matrix) _MatrixDisplay($Matrix) Local $TransposedMatrix = _Eigen_Transpose($Matrix) _MatrixDisplay($TransposedMatrix) _Eigen_ReleaseMatrix($Matrix) _Eigen_ReleaseMatrix($TransposedMatrix) _Eigen_CleanUp()
- 3 replies
-
- machine learning
- artificial intelligence
-
(and 2 more)
Tagged with:
-
Nested Spintax in AutoIt?
noellarkin replied to noellarkin's topic in AutoIt General Help and Support
The solution by @qsek. I'm attaching a copy so you can try running it: spintax-example.au3- 5 replies
-
- spintax
- nested spintax
-
(and 2 more)
Tagged with:
-
EXAMPLE #2 - SETTING ZERO VALUES FOR ALL COLUMNS AND ROWS #include <Eigen4AutoIt.au3> _Eigen_Startup() Local $Matrix = _Eigen_CreateMatrix(2,6) _Eigen_WriteMatrixValue($Matrix, 0, 0, 34) _Eigen_WriteMatrixValue($Matrix, 0, 1, 254) _Eigen_WriteMatrixValue($Matrix, 0, 2, 9) _Eigen_WriteMatrixValue($Matrix, 0, 3, 94) _Eigen_WriteMatrixValue($Matrix, 0, 4, 2) _Eigen_WriteMatrixValue($Matrix, 0, 5, 7) _Eigen_WriteMatrixValue($Matrix, 1, 0, 23) _Eigen_WriteMatrixValue($Matrix, 1, 1, 98) _Eigen_WriteMatrixValue($Matrix, 1, 2, 10) _Eigen_WriteMatrixValue($Matrix, 1, 3, 120) _Eigen_WriteMatrixValue($Matrix, 1, 4, 8) _Eigen_WriteMatrixValue($Matrix, 1, 5, 5) _MatrixDisplay($Matrix) _MatrixDisplay(_Eigen_SetZero($Matrix)) _Eigen_ReleaseMatrix($Matrix) _Eigen_CleanUp()
- 3 replies
-
- machine learning
- artificial intelligence
-
(and 2 more)
Tagged with:
-
EXAMPLE #1 - MATRIX MULTIPLICATION FOR 2 MATRICES Make sure that your matrices are the right size before multiplying (The number of columns in the first matrix must match the number of rows in the second). #include <Eigen4AutoIt.au3> _Eigen_Startup() Local $MatrixA = _Eigen_CreateMatrix(2,4) Local $MatrixB = _Eigen_CreateMatrix(4,2) ; Matrix A _Eigen_WriteMatrixValue($MatrixA, 0, 0, 34) _Eigen_WriteMatrixValue($MatrixA, 0, 1, 254) _Eigen_WriteMatrixValue($MatrixA, 0, 2, 9) _Eigen_WriteMatrixValue($MatrixA, 0, 3, 94) _Eigen_WriteMatrixValue($MatrixA, 1, 0, 23) _Eigen_WriteMatrixValue($MatrixA, 1, 1, 98) _Eigen_WriteMatrixValue($MatrixA, 1, 2, 10) _Eigen_WriteMatrixValue($MatrixA, 1, 3, 120) _MatrixDisplay($MatrixA) ; Matrix B _Eigen_WriteMatrixValue($MatrixB, 0, 0, 13) _Eigen_WriteMatrixValue($MatrixB, 0, 1, 45) _Eigen_WriteMatrixValue($MatrixB, 1, 0, 75) _Eigen_WriteMatrixValue($MatrixB, 1, 1, 30) _Eigen_WriteMatrixValue($MatrixB, 2, 0, 239) _Eigen_WriteMatrixValue($MatrixB, 2, 1, 876) _Eigen_WriteMatrixValue($MatrixB, 3, 0, 54) _Eigen_WriteMatrixValue($MatrixB, 3, 1, 32) _MatrixDisplay($MatrixB) Local $MatMul = _Eigen_Multiply_AB($MatrixA, $MatrixB, 0) _MatrixDisplay($MatMul) _Eigen_ReleaseMatrix($MatrixA) _Eigen_ReleaseMatrix($MatrixB) _Eigen_CleanUp()
- 3 replies
-
- machine learning
- artificial intelligence
-
(and 2 more)
Tagged with:
-
I'm going to grok matrix operations over the next few months, and I wanted to use AutoIt, because I'm sick of all ML examples I come across being in Python :) I'll post example scripts here, starting from the most basic operations (addition, subtraction, multiplication etc). This is primarily so that people checking out basic ML applications of AutoIt have some resources to work with. My own use cases are to do with natural language processing and vector embeddings, so I'll eventually throw in domain-specific examples. I'm going to use the excellent Eigen4AutoIt UDF by @RTFC - - it's a monster of a UDF, and I hope to scratch its surface, example by example...wish me luck NOTE: When using the Eigen4AutoIt library, remember to set the value of $EIGEN_DLLPATH - - read the Eigen4AutoIt QuickStart Manual (page 2) for details.
- 3 replies
-
- machine learning
- artificial intelligence
-
(and 2 more)
Tagged with:
-
When I started using AutoIt, I used to dump all the community UDFs as well as my own frequently-used scripts into C:\Program Files (x86)\AutoIt3\Include - - terrible idea, of course, and I wouldn't advise anyone to do this. These days I have the following folder structure for UDFs: - I have a folder C:\AutoIt which has subfolders: - - C:\AutoIt\MyLibraries, which has my own scripts, organized as C:\AutoIt\MyLibraries\MyUDFName\MyUDFName.au3 - - C:\AutoIt\CommunityLibraries, which has scripts from other forum members, organized as: C:\AutoIt\CommunityLibraries\CommunityMemberUsername\UDFName\UDFName.au3 For example, I've been playing around with TheXman's "jq" UDF, and this is the storage path: This in itself won't make everything run. Some UDFs will have hardcoded DLL paths which you'll have to edit. And finally, you'll have to make registry edits so you can #include these UDFs without entering the entire path. Here's what I did: #include <Array.au3> #include <File.au3> Global Const $CUSTOMINCLUDE_REGKEYNAME = "HKEY_CURRENT_USER\Software\AutoIt v3\AutoIt" Global Const $CUSTOMINCLUDE_REGKEYVALUENAME = "Include" Global Const $CUSTOMINCLUDE_REGKEYVALUETYPE = "REG_SZ" Global Const $FOLDER_COMMUNITYLIBRARIES = "C:\AutoIt\CommunityLibraries" Global Const $FOLDER_MYLIBRARIES = "C:\AutoIt\MyLibraries" Global $CUSTOMINCLUDE_REGKEYVALUE = "" Local $CommunityUsers = _FileListToArray($FOLDER_COMMUNITYLIBRARIES, "*", $FLTA_FOLDERS, False) _ArrayDelete($CommunityUsers, 0) Local $CommunityLibraries = 0 Local $UDFPath = "" For $i = 0 To UBound($CommunityUsers) - 1 $CommunityLibraries = _FileListToArray($FOLDER_COMMUNITYLIBRARIES & "\" & $CommunityUsers[$i], "*", $FLTA_FOLDERS, False) _ArrayDelete($CommunityLibraries, 0) For $j = 0 To UBound($CommunityLibraries) - 1 $UDFPath = $FOLDER_COMMUNITYLIBRARIES & "\" & $CommunityUsers[$i] & "\" & $CommunityLibraries[$j] If FileExists($UDFPath) Then $CUSTOMINCLUDE_REGKEYVALUE &= $UDFPath & ";" Next Next Local $MyLibraries = _FileListToArray($FOLDER_MYLIBRARIES, "*", $FLTA_FOLDERS, False) _ArrayDelete($MyLibraries, 0) For $j = 0 To UBound($MyLibraries) - 1 $UDFPath = $FOLDER_MYLIBRARIES & "\" & $MyLibraries[$j] If FileExists($UDFPath) Then $CUSTOMINCLUDE_REGKEYVALUE &= $UDFPath & ";" Next $CUSTOMINCLUDE_REGKEYVALUE = StringTrimRight($CUSTOMINCLUDE_REGKEYVALUE, 1) ConsoleWrite($CUSTOMINCLUDE_REGKEYVALUE) RegWrite("HKEY_CURRENT_USER\Software\AutoIt v3\AutoIt", "Include", "REG_SZ", $CUSTOMINCLUDE_REGKEYVALUE) This script scans the "CommunityLibraries" and "MyLibraries" folders and adds all the folder paths where the folder name matches the au3 file name to the registry. So far, it has worked out great for me, because now I can use this: #include <jq.au3> instead of: #include "C:\AutoIt\CommunityLibraries\TheXman\jq\jq.au3" Okay, that's all, I hope this'll be useful for newbies who want an easy system for storing their UDFs :)
-
I was trying to use the script here: But this is the console output I'm getting from the example provided: Hello World!|Greetings Everyone, C++ is an awesome|n astonishing programming language. Howdy Dude!|Good Day Everyone, Java is an awesome| wonderful programming language. Hi Dude!|Excuse Me Everyone, C is an amazing| wonderful programming language. Howdy World!|Excuse Me Ladys and Gents, Java is an awesome|n astonishing language. It can handle spintax that isn't nested, but not nested. I'm currently using python for spintax, using this library https://github.com/AceLewis/spintax But I'd love to not have to make that py CMD call and just use AutoIt instead.
- 5 replies
-
- spintax
- nested spintax
-
(and 2 more)
Tagged with:
-
Eigen4AutoIt - Matrix computing with Eigen
noellarkin replied to RTFC's topic in AutoIt Example Scripts
Thanks for the detailed response :) I'm still pretty wet behind the ears when it comes to anything ML related, but I'm really interested in utilizing AutoIt as much as possible, since all my other scripts are in AutoIt. That's primarily why I checked out this UDF. I only mention python because I know about the ML packages that it offers. I'm not partial to using it at all, I'd much rather have my entire codebase in AutoIt :) I'm curious what languages you usually work with? Most people I've come across working in ML are using Python. Can you share some applications/use cases of this UDF with autoit that're out in the wild/used in production?- 93 replies
-
- matrix
- scientific computing
-
(and 1 more)
Tagged with:
-
Eigen4AutoIt - Matrix computing with Eigen
noellarkin replied to RTFC's topic in AutoIt Example Scripts
Noob question: what python library would this UDF be most similar to/drop-in replacement for? I used it for cosine similarity a few months back (I was using sentence-transformers py library before) but this one seems a lot more lower level (dealing directly with matrix operations etc).- 93 replies
-
- matrix
- scientific computing
-
(and 1 more)
Tagged with:
-
Glad I could help :) I was working on this today and I wrote some helper functions for HTTP API as well, perhaps some of these will be useful. Helpers: _HTTPAPI_BindGroupIDRequestQueue, _HTTPAPI_UnbindGroupIDRequestQueue and _HTTPAPI_CaptureCmd are directly from your example script. _HTTPAPI_CreateRequestCaseArray and _HTTPAPI_AddRequestCase make it easier to add different cases, replacing the switch/case with a search function. _HTTPAPI_ProcessRequests does exactly that. _HTTPAPI_Run abstracts away everything but the essentials. These are the functions: #include-once Func _HTTPAPI_BindGroupIDRequestQueue($groupid, $requestqueue) Local $FunctionName = _DebugEX_StartFunc("_HTTPAPI_BindGroupIDRequestQueue") Local $ReturnValue = 0 Local $BindingInfo = DllStructCreate($__HTTPAPI_gtagHTTP_BINDING_INFO) $BindingInfo.Flags = $__HTTPAPI_HTTP_PROPERTY_FLAG_PRESENT $BindingInfo.RequestQueueHandle = $requestqueue Local $GroupPropertySet = _HTTPAPI_HttpSetUrlGroupProperty($groupid, $__HTPPAPI_HttpServerBindingProperty, DllStructGetPtr($BindingInfo), DllStructGetSize($BindingInfo)) If $GroupPropertySet = True Then $ReturnValue = 1 Else _DebugEX_ERROR($FunctionName, "GroupPropertySet:" & $GroupPropertySet) Endif Return $ReturnValue EndFunc Func _HTTPAPI_UnbindGroupIDRequestQueue($groupid) Local $FunctionName = _DebugEX_StartFunc("_HTTPAPI_UnbindGroupIDRequestQueue") Local $ReturnValue = 0 Local $BindingInfo = DllStructCreate($__HTTPAPI_gtagHTTP_BINDING_INFO) $BindingInfo.Flags = 0 $BindingInfo.RequestQueueHandle = Null Local $GroupPropertySet = _HTTPAPI_HttpSetUrlGroupProperty($groupid, $__HTPPAPI_HttpServerBindingProperty, DllStructGetPtr($BindingInfo), DllStructGetSize($BindingInfo)) If $GroupPropertySet = True Then $ReturnValue = 1 Else _DebugEX_ERROR($FunctionName, "GroupPropertySet:" & $GroupPropertySet) Endif Return $ReturnValue EndFunc Func _HTTPAPI_CaptureCmd($sCmd, $sWorkingDir = @WorkingDir) Local $iPID = 0 Local $sOutput = "" ;resolve defaults If $sWorkingDir = Default Then $sWorkingDir = @WorkingDir ;execute command $iPID = Run(@ComSpec & ' /c ' & $sCmd, $sWorkingDir, @SW_HIDE, $STDERR_MERGED) If @error Then ConsoleWrite("Error: Unable to execute command - " & $sCmd & @CRLF) Return SetError(1, 0, "") EndIf ;wait for process to end ProcessWaitClose($iPID) ;get output $sOutput = StdoutRead($iPID) ;if no output, set @error and return empty string If $sOutput = "" Then Return SetError(2, 0, "") ;return output Return $sOutput EndFunc Func _HTTPAPI_CreateRequestCaseArray() ; verb, path, statuscode, reason, messsage, responsetype, execute (0/1) Local $ReturnValue[0][7] Return $ReturnValue EndFunc Func _HTTPAPI_AddRequestCase(ByRef $thisrequestcasearray, $verb, $path, $statuscode, $reason, $message, $responsetype, $execute = 0) Local $FunctionName = _DebugEX_StartFunc("_HTTPAPI_AddCase") Local $Append[1][7] $Append[0][0] = String($verb) $Append[0][1] = String($path) $Append[0][2] = Int($statuscode) $Append[0][3] = String($reason) $Append[0][4] = String($message) $Append[0][5] = String($responsetype) $Append[0][6] = Int($execute) _ArrayConcatenate($thisrequestcasearray, $Append) Return 1 EndFunc Func _HTTPAPI_ProcessRequests(ByRef $thisrequestcasearray, $requestqueue) Local $FunctionName = _DebugEX_StartFunc("_HTTPAPI_ProcessRequests") Local $GETCase[0][6] Local $POSTCase[0][6] Local $Append[1][6] For $i = 0 To _ArrayEnd($thisrequestcasearray) $Append[0][0] = $thisrequestcasearray[$i][1] $Append[0][1] = $thisrequestcasearray[$i][2] $Append[0][2] = $thisrequestcasearray[$i][3] $Append[0][3] = $thisrequestcasearray[$i][4] $Append[0][4] = $thisrequestcasearray[$i][5] $Append[0][5] = $thisrequestcasearray[$i][6] Switch $thisrequestcasearray[$i][0] Case "GET" _ArrayConcatenate($GETCase, $Append) Case "POST" _ArrayConcatenate($POSTCase, $Append) EndSwitch Next Local $tBuffer = "" Local $tRequest = "" Local $sPath = "" Local $QueryString = "" Local $RequestBody = "" Local $SearchThisArray = "" Local $SearchResult = -1 Local $StatusCode = 0 Local $Reason = "" Local $Message = "" Local $ResponseType = "" Local $Execute = 0 Local $FunctionExecuteOutput = 0 While 1 $tBuffer = _HTTPAPI_HttpReceiveHttpRequest($requestqueue) $tRequest = DllStructCreate($__HTTPAPI_gtagHTTP_REQUEST_V2 & StringFormat("byte body[%i];", $__HTTPAPI_REQUEST_BODY_SIZE), DllStructGetPtr($tBuffer)) $sPath = _WinAPI_GetString($tRequest.pAbsPath) $QueryString = _WinAPI_GetString($tRequest.pQueryString) $RequestBody = "" If $tRequest.pEntityChunks > 0 Then $RequestBody = _HTTPAPI_GetRequestBody($tRequest) ConsoleWrite(@CRLF & "RequestBody:" & $RequestBody) EndIf If StringRight($sPath, 1) = "/" Then $sPath = StringTrimRight($sPath, 1) If _StringContainsSubstring($sPath, "/stop") Then _HTTPAPI_HttpSendHttpResponse($requestqueue, $tRequest.RequestId, 200, "OK", "Shutting down API...", "text/plain") ConsoleWrite(@CRLF & "Shutting down API...") ExitLoop Else If $tRequest.Verb = $__HTTPAPI_HttpVerbGET Then $SearchThisArray = $GETCase ConsoleWrite(@CRLF & "GET") EndIf If $tRequest.Verb = $__HTTPAPI_HttpVerbPOST Then $SearchThisArray = $POSTCase ConsoleWrite(@CRLF & "POST") EndIf $SearchResult = _ArraySearch($SearchThisArray, $sPath, 0, 0, 0, 2, Default, Default, Default) If _ArraySearchFound($SearchResult) Then ConsoleWrite(@CRLF & "found") $StatusCode = $SearchThisArray[$SearchResult][1] $Reason = $SearchThisArray[$SearchResult][2] $Message = $SearchThisArray[$SearchResult][3] $ResponseType = $SearchThisArray[$SearchResult][4] $Execute = $SearchThisArray[$SearchResult][5] ConsoleWrite(@CRLF & "StatusCode:" & $StatusCode) ConsoleWrite(@CRLF & "Reason:" & $Reason) ConsoleWrite(@CRLF & "Message:" & $Message) ConsoleWrite(@CRLF & "ResponseType:" & $ResponseType) ConsoleWrite(@CRLF & "Execute:" & $Execute) If $Execute Then $FunctionExecuteOutput = Execute($Message) $Message = $FunctionExecuteOutput EndIf _HTTPAPI_HttpSendHttpResponse($requestqueue, $tRequest.RequestId, $StatusCode, $Reason, $Message, $ResponseType) Else _HTTPAPI_HttpSendHttpResponse($requestqueue, $tRequest.RequestId, 404, "Not Found", "<h2>Not Found</h2><hr><p>HTTP Error 404. The requested resource is not found.</p>", "text/html") ConsoleWrite(@CRLF & "not found") EndIf $tBuffer = 0 Sleep(100) EndIf WEnd EndFunc Func _HTTPAPI_Run($host, $path, $requestcases) Local $FunctionName = _DebugEX_StartFunc("_HTTPAPI_Run") Local $ReturnValue = 1 Local $EnvironmentInitialized = _HTTPAPI_Startup(True) If $EnvironmentInitialized Then Local $ServerInitialized = _HTTPAPI_HttpInitialize() If $ServerInitialized Then Local $ServerSessionID = _HTTPAPI_HttpCreateServerSession() If $ServerSessionID <> 0 Then Local $URLGroupID = _HTTPAPI_HttpCreateUrlGroup($ServerSessionID) If $URLGroupID <> 0 Then Local $RequestQueue = _HTTPAPI_HttpCreateRequestQueue() If $RequestQueue <> 0 Then Local $GroupQueueBound = _HTTPAPI_BindGroupIDRequestQueue($URLGroupID, $RequestQueue) If $GroupQueueBound Then Local $BaseURLAdded = _HTTPAPI_HttpAddUrlToUrlGroup($URLGroupID, $host & $path) If $BaseURLAdded Then _HTTPAPI_ProcessRequests($requestcases, $RequestQueue) OnAutoItExitRegister(_HTTPAPI_HttpRemoveUrlFromUrlGroup($URLGroupID, "", $__HTTPAPI_HTTP_URL_FLAG_REMOVE_ALL)) Else _DebugEX_ERROR($FunctionName, "BaseURLAdded:" & $BaseURLAdded) EndIf OnAutoItExitRegister(_HTTPAPI_UnbindGroupIDRequestQueue($URLGroupID)) Else _DebugEX_ERROR($FunctionName, "GroupQueueBound:" & $GroupQueueBound) EndIf OnAutoItExitRegister(_HTTPAPI_HttpShutdownRequestQueue($RequestQueue)) Else _DebugEX_ERROR($FunctionName, "RequestQueue:" & $RequestQueue) EndIf Else _DebugEX_ERROR($FunctionName, "URLGroupID:" & $URLGroupID) EndIf OnAutoItExitRegister(_HTTPAPI_HttpCloseServerSession($ServerSessionID)) Else _DebugEX_ERROR($FunctionName, "ServerSessionID:" & $ServerSessionID) EndIf OnAutoItExitRegister(_HTTPAPI_HttpTerminate()) Else _DebugEX_ERROR($FunctionName, "ServerInitialized:" & $ServerInitialized) EndIf Else _DebugEX_ERROR($FunctionName, "EnvironmentInitialized:" & $EnvironmentInitialized) EndIf Return $ReturnValue EndFunc An example use case: #AutoIt3Wrapper_AU3Check_Parameters=-w 3 -w 4 -w 5 -w 6 -d #include <HTTPAPI.au3> _DebugEX_Console("ENABLE") Local $HostURL = "http://127.0.0.1:9000" Local $Path = "/vm" Local $RequestCases = _HTTPAPI_CreateRequestCaseArray() _HTTPAPI_AddRequestCase($RequestCases, "GET", $Path, 200, "OK", "<h1>Hello World</h1>", "text/html") _HTTPAPI_AddRequestCase($RequestCases, "GET", $Path & "/username", 200, "OK", '{"username":"' & @UserName & '"}', "application/json") _HTTPAPI_AddRequestCase($RequestCases, "POST", $Path & "/requestbody", 200, "OK", '$RequestBody', "text/plain", 1) _HTTPAPI_AddRequestCase($RequestCases, "GET", $Path & "/python", 200, "OK", '_HTTPAPI_CaptureCmd("python helloworld.py", "C:\AutoIt\CommunityLibraries\TheXman\HTTPAPI\examples")', "text/plain", 1) _HTTPAPI_Run($HostURL, $Path, $RequestCases) Note: the code has some functions that I use internally for work, you may want to add them in so there aren't any errors: Global $DEBUG_CONSOLE = 0 Global $DEBUG_COUNTER_ERROR = 0 Global $DEBUG_COUNTER_WARNING = 0 Func _ArraySearchFound($arraysearchresult) Local $FunctionName = "_ArraySearchFound" Local $ReturnValue = 0 If $arraysearchresult <> -1 Then $ReturnValue = 1 Return $ReturnValue EndFunc Func _ArrayEnd(ByRef $thisarray) Local $FunctionName = "_ArrayEnd" Local $ReturnValue = -1 $ReturnValue = UBound($thisarray) - 1 Return $ReturnValue EndFunc Func _StringContainsSubstring($string, $substring) Local $ReturnValue = 0 If StringInStr(String($string), String($substring)) <> 0 Then $ReturnValue = 1 Return $ReturnValue EndFunc Func _DebugEX_ConsoleWrite($thisfunction, $string, $guid = "") Local $ConsoleWriteGUID = "" If $guid <> "" Then $ConsoleWriteGUID = "::::" & $guid Local $ConsoleWriteString = "::::" & $string Local $ConsoleText = @CRLF & $thisfunction & $ConsoleWriteGUID & $ConsoleWriteString If $DEBUG_CONSOLE Then ConsoleWrite($ConsoleText) If _StringContainsSubstring($string, "ERROR ") Then $DEBUG_COUNTER_ERROR += 1 If _StringContainsSubstring($string, "WARNING ") Then $DEBUG_COUNTER_WARNING += 1 EndFunc Func _DebugEX_Console($switch) Switch $switch Case "ENABLE" $DEBUG_CONSOLE = 1 Case "DISABLE" $DEBUG_CONSOLE = 0 EndSwitch EndFunc Func _DebugEX_StartFunc(ByRef $thisfunction) Local $ConsoleText = @CRLF & @CRLF & "starting " & $thisfunction & "..." If $DEBUG_CONSOLE Then ConsoleWrite($ConsoleText) Return $thisfunction EndFunc Func _DebugEX_ERROR($thisfunction, $string, $guid = "") $string = "ERROR " & $string _DebugEX_ConsoleWrite($thisfunction, $string, $guid) EndFunc Func _DebugEX_WARNING($thisfunction, $string, $guid = "") $string = "WARNING " & $string _DebugEX_ConsoleWrite($thisfunction, $string, $guid) EndFunc The code is pretty rough, I haven't polished it up much, but I like the RequestCase array thing
-
Been using this for a personal project, love it:) Just had a suggestion: In the function _HTTPAPI_HttpSendHttpResponse adding an additional parameter $sResponseType Func _HTTPAPI_HttpSendHttpResponse($hRequestQueue, $iRequestId, $iStatusCode, $sReason, $sBody, $sResponseType = "text/html") And replacnig "text/html" in the function with $sResponseType. Allows one to use other formats, like JSON :) For example: Switch $sPath Case $path & "/username" $iStatusCode = 200 $sReason = "OK" $sMsg = '{"username":"' & @UserName & '"}' EndSwitch _HTTPAPI_HttpSendHttpResponse($requestqueue, $tRequest.RequestId, $iStatusCode, $sReason, $sMsg, "application/json")
-
Would love to :) but nothing in my workflow (so far) has warranted anything extremely complex - - at most, I'm using SBERT embeddings + Milvus vector DB and doing some vector comparisons, indexing corpus, some n-gram extractions with Yake.
- 9 replies
-
- cosine similarity
- vector
-
(and 3 more)
Tagged with: