Jump to content

AutoIt Snippets


Chimaera
 Share

Recommended Posts

@rcmaehl, this algorithm yields wrong results unless inputs are very strictly limited to a tiny range and, even if these conditions are met, an infinite number of values make it fail.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

3 minutes ago, jchd said:

@rcmaehl, this algorithm yields wrong results unless inputs are very strictly limited to a tiny range and, even if these conditions are met, an infinite number of values make it fail.

It should work for all integers. Positive and negative.

My UDFs are generally for me. If they aren't updated for a while, it means I'm not using them myself. As soon as I start using them again, they'll get updated.

My Projects

WhyNotWin11
Cisco FinesseGithubIRC UDFWindowEx UDF

 

Link to comment
Share on other sites

Sure?

Local $a = [-350, 283, -3, 0, 5, -46094, 10, 56781]
For $v In $a
    ConsoleWrite($v & @TAB & String(10^$v) & @CRLF)
Next

ConsoleWrite(@LF & "Result: (min, max) = (" & IntLenSort($a) & ")" & @CRLF)

 

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

8 minutes ago, jchd said:

Sure?

Local $a = [-350, 283, -3, 0, 5, -46094, 10, 56781]
For $v In $a
    ConsoleWrite($v & @TAB & String(10^$v) & @CRLF)
Next

ConsoleWrite(@LF & "Result: (min, max) = (" & IntLenSort($a) & ")" & @CRLF)

 

Will double check once I get home but it runs on the principal that

10^5 (100000) is a longer string than 10^0 (1), thus larger

And that 10^-5 (0.00001) is a longer string than 10^-1 (0.1), thus smaller

 

Edit: I haven't tested with multiple negative Ints so I may have messed up on that part.

Edited by rcmaehl
I can't type today. 100000>1

My UDFs are generally for me. If they aren't updated for a while, it means I'm not using them myself. As soon as I start using them again, they'll get updated.

My Projects

WhyNotWin11
Cisco FinesseGithubIRC UDFWindowEx UDF

 

Link to comment
Share on other sites

With:
Local $a = [6,2,0,3,4,5,1]
the snippet yields:

6    1000000
2    100
0    1
3    1000
4    10000
5    100000
1    10

Result: (min, max) = (6, 6)


With:
Local $a = [-350, 283, -3, 0, 5, -46094, 10, 56781]
the snippet yields:

-350     0
283      1e+283
-3       0.001
0        1
5        100000
-46094   0
10       10000000000
56781    1.#INF

Result: (min, max) = (-3, 10)

 

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

11 minutes ago, jchd said:
With:
Local $a = [6,2,0,3,4,5,1]
the snippet yields:

6    1000000
2    100
0    1
3    1000
4    10000
5    100000
1    10

Result: (min, max) = (6, 6)


With:
Local $a = [-350, 283, -3, 0, 5, -46094, 10, 56781]
the snippet yields:

-350     0
283      1e+283
-3       0.001
0        1
5        100000
-46094   0
10       10000000000
56781    1.#INF

Result: (min, max) = (-3, 10)

 

Heck. In THEORY it works. Second example definitely brings up an issue with scientific notation... 

Edited by rcmaehl

My UDFs are generally for me. If they aren't updated for a while, it means I'm not using them myself. As soon as I start using them again, they'll get updated.

My Projects

WhyNotWin11
Cisco FinesseGithubIRC UDFWindowEx UDF

 

Link to comment
Share on other sites

  • 1 month later...

I use these daily; thought I'd share.

Don't use this version, updated one is below

#AutoIt3Wrapper_Au3Check_Parameters=-d -w- 1 -w 2 -w 3 -w 4 -w 5 -w 6

#include-once
#include <Date.au3>

; #FUNCTION# ====================================================================================================================
; Name ..........:  _StringRandom
; Description ...:  Returns a string of random characters
; Syntax ........:  _StringRandom($iAmount[, $iType = 1])
; Parameters ....:  $iAmount            - an integer value. Length of returned string
;                   $iType              - [optional] an integer value. Default is 1.
;                                       1 - Return digits (0 - 9)
;                                       2 - Return hexadecimal (0 - 9, A - F)
;                                       3 - Return Alphanumeric upper (0 - 9, A - Z)
;                                       4 - Return Alphanumeric (0 - 9, A - Z, a - z)
;                                       5 - Return Alpha upper (A - Z)
;                                       6 - Return Alpha (A - Z, a - z)
; Return values .:  Success             - String
;                   Failure             - Empty string and @error flag as follows:
;                   @error :            1 - $iAmount is not a positive integer
;                                       2 - $iType is out of bounds
; Author ........:  Sam Coates
; ===============================================================================================================================
Func _StringRandom($iAmount, $iType = 1)

    If $iAmount < 1 Or IsInt($iAmount) = 0 Then Return(SetError(-1, 0, ""))

    Local $sString = ""
    Local $iRandom = 0, $iRandomLow = 1, $iRandomHigh = 62
    Local $aCharId[63]

    If $iType = 1 Then ;; digits: 1 - 10
        $iRandomHigh = 10
    ElseIf $iType = 2 Then ;; hexadecimal: 1 - 16
        $iRandomHigh = 16
    ElseIf $iType = 3 Then ;; alnumupper: 1 - 36
        $iRandomHigh = 36
    ElseIf $iType = 4 Then ;; alnum: 1 - 62
        $iRandomHigh = 62
    ElseIf $iType = 5 Then ;; alphaupper: 11 - 36
        $iRandomLow = 11
        $iRandomHigh = 36
    ElseIf $iType = 6 Then ;; alpha: 11 = 62
        $iRandomLow = 11
        $iRandomHigh = 62
    Else
        Return(SetError(-2, 0, ""))
    EndIf

    For $i = 1 To 10 ;; loop through our array, assigning ascii values to each element
        $aCharId[$i] = Chr(47 + $i)
    Next

    For $i = 11 to 36
        $aCharId[$i] = Chr(54 + $i)
    Next

    For $i = 37 To 62
        $aCharId[$i] = Chr(60 + $i)
    Next

    For $i = 1 To $iAmount
        $iRandom = Random($iRandomLow, $iRandomHigh, 1) ;; random interger between $iRandomLow and $iRandomHigh
        $sString &= $aCharId[$iRandom] ;; append string with corresponding character from ascii array
    Next

    Return ($sString)

EndFunc

; #FUNCTION# ====================================================================================================================
; Name ..........:  _StringTrimLeft
; Description ...:  Searches for a string inside a string, then removes everything on the left of that string
; Syntax ........:  _StringTrimLeft($sString, $sRemove[, $iCaseSense = 0, $iOccurrence = 1])
; Parameters ....:  $sString            - a string value. The string to search inside.
;                   $sRemove            - a string value. The string to search for.
;                   $iCaseSense         - an integer value. Flag to indicate if the operations should be case sensitive.
;                   $iOccurrence        - an integer value. Which occurrence of the substring to find in the string. Use a
;                                         negative occurrence to search from the right side.
; Return values .:  Success             - String
;                   Failure             - Empty string as returned from StringTrimLeft()
; Author ........:  Sam Coates
; ===============================================================================================================================
Func _StringTrimLeft($sString, $sRemove, $iCaseSense = 0, $iOccurrence = 1)

    Local $sReturn = StringTrimLeft($sString, StringInStr($sString, $sRemove, $iCaseSense, $iOccurrence) + StringLen($sRemove) - 1)
    Return ($sReturn)

EndFunc   ;==>_StringTrimLeft

; #FUNCTION# ====================================================================================================================
; Name ..........:  _StringLeft
; Description ...:  Searches for a string inside a string, then removes everything on the right of that string
; Syntax ........:  _StringLeft($sString, $sRemove[, $iCaseSense = 0, $iOccurrence = 1])
; Parameters ....:  $sString            - a string value. The string to search inside.
;                   $sRemove            - a string value. The string to search for.
;                   $iCaseSense         - an integer value. Flag to indicate if the operations should be case sensitive.
;                   $iOccurrence        - an integer value. Which occurrence of the substring to find in the string. Use a
;                                         negative occurrence to search from the right side.
; Return values .:  Success             - String
;                   Failure             - Empty string as returned from StringLeft()
; Author ........:  Sam Coates
; ===============================================================================================================================
Func _StringLeft($sString, $sRemove, $iCaseSense = 0, $iOccurrence = 1)

    Local $sReturn = StringLeft($sString, StringInStr($sString, $sRemove, $iCaseSense, $iOccurrence) - 1)
    Return ($sReturn)

EndFunc   ;==>_StringLeft

; #FUNCTION# ====================================================================================================================
; Name ..........:  _FileToFileName
; Description ...:  Returns a filename from a FQPN (Fully Qualified Path Name)
; Syntax ........:  _FileToFileName($sPath[, $bIncludeExtension = True])
; Parameters ....:  $sPath              - a string value.
;                   $bIncludeExtension  - [optional] a boolean value. Default is True.
; Return values .:  Success             - String
;                   Failure             - Empty string as returned from StringLeft()
; Author ........:  Sam Coates
; ===============================================================================================================================
Func _FileToFileName($sPath, $bIncludeExtension = True)

    Local $sReturn = StringTrimLeft($sPath, StringInStr($sPath, "\", 0, -1))
    If $bIncludeExtension = False Then $sReturn = StringLeft($sReturn, StringInStr($sReturn, ".", 0, -1) - 1)
    Return ($sReturn)

EndFunc   ;==>_FileToFileName

; #FUNCTION# ====================================================================================================================
; Name ..........:  _FileToFilePath
; Description ...:  Returns a folder path from a FQPN (Fully Qualified Path Name)
; Syntax ........:  _FileToFilePath($sPath)
; Parameters ....:  $sPath              - a string value.
; Return values .:  Success             - String
;                   Failure             - Empty string as returned from StringLeft()
; Author ........:  Sam Coates
; ===============================================================================================================================
Func _FileToFilePath($sPath)

    Local $sReturn = StringLeft($sPath, StringInStr($sPath, "\", 0, -1) - 1)
    Return ($sReturn)

EndFunc   ;==>_FileToFilePath

; #FUNCTION# ====================================================================================================================
; Name ..........:  _FileToFileExtension
; Description ...:  Returns a file extension from a filename/FQPN (Fully Qualified Path Name)
; Syntax ........:  _FileToFileExtension($sPath)
; Parameters ....:  $sPath              - a string value.
; Return values .:  Success             - String
;                   Failure             - Empty string as returned from StringTrimLeft()
; Author ........:  Sam Coates
; ===============================================================================================================================
Func _FileToFileExtension($sPath)

    Return (StringTrimLeft($sPath, StringInStr($sPath, ".", 0, -1)))

EndFunc   ;==>_FileToFileExtension

; #FUNCTION# ====================================================================================================================
; Name ..........:  _DateTimeGet
; Description ...:  Returns the date and time formatted for use in sortable filenames, logs, listviews, etc.
; Syntax ........:  _DateTimeGet(iType = 1[, $bHumanFormat = False])
; Parameters ....:  $iType              - [optional] an integer value. Default is 1.
;                                       1 - Date and time in file-friendly format; 20190115_113756
;                                       2 - Date in file-friendly format; 20190115
;                                       3 - Time in file friendly format; 113756
;                   $bHumanFormat       - [optional] a boolean value. Default is False.
;                                       True - Includes slashes in the date and colons in the time with a space inbetween
;                                       False - No slashes or colons included with an underscore inbetween
; Return values .:  Success             - String
;                   Failure             - Sets @error to non-zero and returns an empty string
; Author ........:  Sam Coates
; ===============================================================================================================================
Func _DateTimeGet($iType = 1, $bHumanFormat = False)

    If $iType < 1 Or $iType > 3 Then Return(SetError(-1, 0, ""))

    ;; Param1:
    ;; 1 = Date and time in file friendly format:   20190115_113756
    ;; 2 = Date in file friendly format:            20190115
    ;; 3 = Time in file friendly format:            113756

    ;; Param2:
    ;; True = Use human-readable format:            15/01/2019 11:37:56

    Local $sTime = _NowTime()
    Local $sDate = _NowDate()

    If $iType = 1 Then
        If $bHumanFormat = False Then
            $sTime = StringReplace($sTime, ":", "")
            $sDate = StringReplace($sDate, "/", "")
            $sDate = StringTrimLeft($sDate, 4) & StringMid($sDate, 3, 2) & StringLeft($sDate, 2)
            Return ($sDate & "_" & $sTime)
        Else
            Return ($sDate & " " & $sTime)
        EndIf
    ElseIf $iType = 2 Then
        If $bHumanFormat = False Then
            $sDate = StringReplace($sDate, "/", "")
            $sDate = StringTrimLeft($sDate, 4) & StringMid($sDate, 3, 2) & StringLeft($sDate, 2)
        EndIf
        Return ($sDate)
    ElseIf $iType = 3 Then
        If $bHumanFormat = False Then
            $sTime = StringReplace($sTime, "/", "")
        EndIf
        Return ($sTime)
    EndIf


EndFunc   ;==>_DateTimeGet

EDIT: I have no idea why I claim digits are 1 - 10 instead of 0 - 9... Excuse my brainfart. Amended.

Edited by Inpho
Fatuity mitigation
Link to comment
Share on other sites

  • 4 weeks later...

Perfix Number to negative

sometimes regular prefixing Using "&"  or stringFormat() won't do for example with what i have tried in Here

And as I Didn't look too far for a way .., Hence the bookmark:

Func _PerfixNeg($iNumber)
    For $i = "-" & $iNumber To "-" & $iNumber
        Return $i
    Next
EndFunc   ;==>_PerfixNeg

 

Edited by Deye
Link to comment
Share on other sites

Sorry, I do not understand the point of this post. I would mark a negative number/string this way:

Func _PrefixNeg($vNumber)
    If IsNumber($vNumber) Then ; $vNumber is numeric
        If $vNumber > 0 Then 
            Return $vNumber * -1 ; $vNumber is > 0
        Else  
            Return $vNumber ; $vNumber is already negative, return unchanged
        EndIf
    ElseIf IsString($vNumber) Then ; $vNumber is a string
        Return "-" & $vNumber ; Prefix $vNUmber with "-"
    Else Return SetError(1, 0, 0) ; Neither string nor number, return error
EndFunc   ;==>_PrefixNeg

 

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2024-07-28 - Version 1.6.3.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

Another I use almost daily.

As we know, using _ArrayDelete in a loop is terrible practice. I wanted to search an array for empty rows, using a function (which mimics the return format from _ArrayFindAll) so that the returned array can be fed straight into _ArrayDelete.

For 2D arrays, only fully empty rows are marked for deletion. If the row contains a single cell which isn't empty, the row isn't marked.

; #FUNCTION# ====================================================================================================================
; Name ..........: _ArrayFindEmptyRows
; Description ...: Returns an array of indexes (similar to _ArrayFindAll) ready to feed straight into _ArrayDelete.
; Syntax ........: _ArrayFindEmptyRows(Const Byref $aArray[, $iStartRow = 1])
; Parameters ....: $aArray              - [in/out and const] The array to search for empty rows
;                  $iStartRow           - [optional] an integer value. The index to start searching from
; Return values .: Success:             - An array of indexes
;                  Failure              - Empty string and @error flag as follows:
;                                       1 - $aArray is not an array
;                                       2 - $aArray contains one row
;                                       3 - $iStartRow is out of bounds
;                                       4 - No results (unable to find any blank rows)
; Author ........: Sam Coates
; ===============================================================================================================================
Func _ArrayFindEmptyRows(ByRef Const $aArray, $iStartRow = 1)

    If Not IsArray($aArray) Then Return(SetError(-1, 0, "")) ;; Array isn't an array
    If UBound($aArray) < 2 Then Return(SetError(-2, 0, "")) ;; Array only contains one row

    Local $i, $ii
    Local $sResults = ""
    Local $aReturn
    Local $iArrayRows = UBound($aArray) - 1 ;; hold the number of rows
    If $iStartRow > $iArrayRows Then Return(SetError(-3, 0, "")) ;; Check if StartRow isn't out of bounds

    Local $iArrayColumns = UBound($aArray, 2) ;; hold the number of columns
    If @error = 2 Then $iArrayColumns = 1 ;; if error, then 1d array

    If $iArrayColumns = 1 Then ;; if 1d array

        For $i = $iStartRow To $iArrayRows ;; loop through rows
            If $aArray[$i] = "" Then $sResults &= $i & ";" ;; if its blank, save the index
        Next

    ElseIf $iArrayColumns > 1 Then ;; if 2d array

        For $i = $iStartRow To $iArrayRows ;; loop through rows
            For $ii = 0 To $iArrayColumns - 1 ;; loop through columns
                If $aArray[$i][$ii] <> "" Then ExitLoop ;; if a non-blank is found in any cell on a row, skip to next row
                If $ii = $iArrayColumns - 1 Then $sResults &= $i & ";" ;; if we reach the end of the columns and still havent found a non-blank, save the index
            Next
        Next

    EndIf

    If $sResults <> "" Then ;; if we made changes
        $sResults = StringTrimRight($sResults, 1) ;; strip the final semi-colon
    Else ;; if we made no changes
        Return(SetError(-4, 0, "")) ;; No results
    EndIf

    $aReturn = StringSplit($sResults, ";") ;; split the final string

    Return($aReturn) ;; return it

EndFunc

 

Link to comment
Share on other sites

  • 2 weeks later...

Inpho,

@Why not try delete them with a faster function than creating another array just to list valid element points?

Better yet, Try this (I'm only assuming it will be fast enough for you, for 2D arrays, it will still use _array delete but with the range option and no looping ..
Please Let us know  ..

Note: this method doesn't work if the chosen delimiter exists in any of elements in the array ..(not about the "|" one) 

 

; 1D & 2D
Func _ArrayDelEmptyRows(ByRef $Array, $bUBound = False, $sDelim = ",") ; $bUBound return the $Array[0] with elements count
    If UBound($Array, 2) Then
        Local $str, $sString, $ai
        ;If $Array[0][0] = UBound($Array) Then _ArrayDelete($Array, 0)
        $str = _ArrayToString($Array, "|", Default, Default, $sDelim)
        $sString = StringRegExpReplace($sDelim & $str, $sDelim & "[|]*[|]", $sDelim)
        $ai = _ArrayFindAll(StringSplit(StringTrimLeft($sString, 1), $sDelim, 3), "")
        If Not IsArray($ai) Then Return $Array

        Local $aTemp[UBound($Array) - UBound($ai)][UBound($Array, 2)]
        Local $sAi = "," & _ArrayToString($ai, ",") & ","
        $x = -1
        For $i = 0 To UBound($Array) - 1
            If StringInStr($sAi, "," & $i & ",") Then ContinueLoop
            $x += 1
            For $j = 0 To UBound($aTemp, 2) - 1
                $aTemp[$x][$j] = $Array[$i][$j]
            Next
        Next
        If $bUBound Then _ArrayInsert($aTemp, 0, UBound($aTemp))
        Return $aTemp
    Else
        Local $pattern = $sDelim & "[" & $sDelim & "|]*[" & $sDelim & "|]"
        Local $str = StringRegExpReplace($sDelim & _ArrayToString($Array, $sDelim), $pattern, "|")
        If StringRight($str, 1) = "|" Or StringRight($str, 1) = $sDelim Then $str = StringTrimRight($str, 1)
        Return StringSplit(StringTrimLeft($str, 1), StringInStr($str, $sDelim) ? $sDelim : "|", $bUBound ? "" : 3)
    EndIf
EndFunc   ;==>_ArrayDelEmptyRows

 

Edited by Deye
Removed the use of _arraydelete
Link to comment
Share on other sites

@Deye

I don't mind creating another array to list the items personally; my main goal was to increase speed at the potential sacrifice of memory. I'm not a fan of converting an array to a string in this way; it makes for (please don't take offence) un-pretty code that's hard to understand.

Unfortunately using your function on a 35,000 x 10 array takes too long; I let it run for 4 minutes and stopped it. Conversely, my function completed in less than one second.

Conversely again; using your function on a 35,000 row 1D array appears to be faster than mine on first tests :)

Of course a better use case would be to make the changes as a 1D array, but I'm weird and like to account for every use. Sometimes I'm reading huge csv files into an array; converting this to a 1D array or a string to search for blank rows is a lot of expense when _ArrayFindEmptyRows will do it extremely quickly without playing ping pong with the data conversion.

Thanks for sharing the function, there's something for me to learn from :)

FYI how I created the test array:

Global $aArray[35000][10]

For $i = 1 To UBound($aArray) - 1
    For $ii = 0 To UBound($aArray, 2) - 1
        $aArray[$i][$ii] = _StringRandom(20, 4)
        If Mod($i, 10) = 0 Then
            $aArray[$i][$ii] = ""
        EndIf
    Next
Next

 

Link to comment
Share on other sites

May be an unpopular opinion but I love the Static keyword...

Optimised _StringRandom 

Global $hTimer

For $i = 1 to 10
    $hTimer = _Timer_Init()
    _StringRandom(20, 4)
    ConsoleWrite($i & ": " & _Timer_Diff($hTimer) & @CRLF)
Next

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

For $i = 1 to 10
    $hTimer = _Timer_Init()
    _StringRandom2(20, 4)
    ConsoleWrite($i & ": " & _Timer_Diff($hTimer) & @CRLF)
Next

; #FUNCTION# ====================================================================================================================
; Name ..........:  _StringRandom
; Description ...:  Returns a string of random characters
; Syntax ........:  _StringRandom($iAmount[, $iType = 1])
; Parameters ....:  $iAmount            - an integer value. Length of returned string
;                   $iType              - [optional] an integer value. Default is 1.
;                                       1 - Return digits (0 - 9)
;                                       2 - Return hexadecimal (0 - 9, A - F)
;                                       3 - Return Alphanumeric upper (0 - 9, A - Z)
;                                       4 - Return Alphanumeric (0 - 9, A - Z, a - z)
;                                       5 - Return Alpha upper (A - Z)
;                                       6 - Return Alpha (A - Z, a - z)
; Return values .:  Success             - String
;                   Failure             - Empty string and @error flag as follows:
;                   @error :            1 - $iAmount is not a positive integer
;                                       2 - $iType is out of bounds
; Author ........:  Sam Coates
; ===============================================================================================================================
Func _StringRandom($iAmount, $iType = 1)

    If $iAmount < 1 Or IsInt($iAmount) = 0 Then Return(SetError(-1, 0, ""))

    Local $sString = ""
    Local $iRandom = 0, $iRandomLow = 1, $iRandomHigh = 62
    Local $aCharId[63]

    If $iType = 1 Then ;; digits: 1 - 10
        $iRandomHigh = 10
    ElseIf $iType = 2 Then ;; hexadecimal: 1 - 16
        $iRandomHigh = 16
    ElseIf $iType = 3 Then ;; alnumupper: 1 - 36
        $iRandomHigh = 36
    ElseIf $iType = 4 Then ;; alnum: 1 - 62
        $iRandomHigh = 62
    ElseIf $iType = 5 Then ;; alphaupper: 11 - 36
        $iRandomLow = 11
        $iRandomHigh = 36
    ElseIf $iType = 6 Then ;; alpha: 11 = 62
        $iRandomLow = 11
        $iRandomHigh = 62
    Else
        Return(SetError(-2, 0, ""))
    EndIf

    For $i = 1 To 10 ;; loop through our array, assigning ascii values to each element
        $aCharId[$i] = Chr(47 + $i)
    Next

    For $i = 11 to 36
        $aCharId[$i] = Chr(54 + $i)
    Next

    For $i = 37 To 62
        $aCharId[$i] = Chr(60 + $i)
    Next

    For $i = 1 To $iAmount
        $iRandom = Random($iRandomLow, $iRandomHigh, 1) ;; random interger between $iRandomLow and $iRandomHigh
        $sString &= $aCharId[$iRandom] ;; append string with corresponding character from ascii array
    Next

    Return ($sString)

EndFunc

; #FUNCTION# ====================================================================================================================
; Name ..........:  _StringRandom
; Description ...:  Returns a string of random characters
; Syntax ........:  _StringRandom($iAmount[, $iType = 1])
; Parameters ....:  $iAmount            - an integer value. Length of returned string
;                   $iType              - [optional] an integer value. Default is 1.
;                                       1 - Return digits (0-9)
;                                       2 - Return hexadecimal (0-9, A - F)
;                                       3 - Return Alphanumeric upper (0-9, A - Z)
;                                       4 - Return Alphanumeric (0-9, A - Z, a - z)
;                                       5 - Return Alpha upper (A - Z)
;                                       6 - Return Alpha (A - Z, a - z)
; Return values .:  Success             - String
;                   Failure             - Empty string and @error flag as follows:
;                   @error :            1 - $iAmount is not a positive integer
;                                       2 - $iType is out of bounds
; Author ........:  Sam Coates
; ===============================================================================================================================
Func _StringRandom2($iAmount, $iType = 1)

    If $iAmount < 1 Or IsInt($iAmount) = 0 Then Return(SetError(-1, 0, ""))

    Local $sString = ""
    Local $iRandomLow = 1, $iRandomHigh = 62
    Local Static $aCharId[63] =     [0,     Chr(48), Chr(49), Chr(50), Chr(51), Chr(52), Chr(53), Chr(54), Chr(55), Chr(56), Chr(57), Chr(65), Chr(66), _
                                    Chr(67), Chr(68), Chr(69), Chr(70), Chr(71), Chr(72), Chr(73), Chr(74), Chr(75), Chr(76), Chr(77), Chr(78), _
                                    Chr(79), Chr(80), Chr(81), Chr(82), Chr(83), Chr(84), Chr(85), Chr(86), Chr(87), Chr(88), Chr(89), Chr(90), _
                                    Chr(97), Chr(98), Chr(99), Chr(100), Chr(101), Chr(102), Chr(103), Chr(104), Chr(105), Chr(106), Chr(107), _
                                    Chr(108), Chr(109), Chr(110), Chr(111), Chr(112), Chr(113), Chr(114), Chr(115), Chr(116), Chr(117), Chr(118), _
                                    Chr(119), Chr(120), Chr(121), Chr(122)]

    If $iType = 1 Then ;; digits: 1 - 10
        $iRandomHigh = 10
    ElseIf $iType = 2 Then ;; hexadecimal: 1 - 16
        $iRandomHigh = 16
    ElseIf $iType = 3 Then ;; alnumupper: 1 - 36
        $iRandomHigh = 36
    ElseIf $iType = 4 Then ;; alnum: 1 - 62
        $iRandomHigh = 62
    ElseIf $iType = 5 Then ;; alphaupper: 11 - 36
        $iRandomLow = 11
        $iRandomHigh = 36
    ElseIf $iType = 6 Then ;; alpha: 11 = 62
        $iRandomLow = 11
        $iRandomHigh = 62
    Else
        Return(SetError(-2, 0, ""))
    EndIf


    For $i = 1 To $iAmount
        $sString &= $aCharId[Random($iRandomLow, $iRandomHigh, 1)] ;; append string with corresponding character from ascii array
    Next

    Return ($sString)

EndFunc
Old:
1: 0.380358214711124
2: 0.379736206183387
3: 0.343037703046909
4: 0.323755438687064
5: 0.359520929031937
6: 0.345214732893988
7: 0.35485586507391
8: 0.319401378992906
9: 0.331841549547644

New:
1: 0.465262378747213
2: 0.133731833463437
3: 0.12502371407512
4: 0.439138020582262
5: 0.125956726866725
6: 0.123779697019646
7: 0.124090701283515
8: 0.119736641589356
9: 0.121291662908698

 

Edited by Inpho
Link to comment
Share on other sites

I use .ini files a LOT. Sometimes I'm reading multiple ini sections from multiple files and it can become a bit of a headache remembering which element is where. This is especially noticable in my largest projects.

After playing around with Maps as a way of storing and accessing all this data, I can safely say that this has taken the headache from me. This allows me to stop thinking about where data is located in an array and just focus on solving problems.

I use the below function to read all of my sections from various .inis all into one Map of Maps. I only have to remember the name of the ini section, and the name of the key.

Global $mMapIni = _IniToMap("config.ini")

ConsoleWrite($mMapIni["FlashCountTargets"]["Amounts"] & @CRLF)
ConsoleWrite($mMapIni["Last"]["1"] & @CRLF)
ConsoleWrite($mMapIni["FlashCountEmails"]["Users"] & @CRLF)
ConsoleWrite($mMapIni["ListType"]["ListType"] & @CRLF)
ConsoleWrite($mMapIni["Variants"]["Deep Black"] & @CRLF)

Func _IniToMap($sFile, $sSection = "")

    Local $mMapReturn[]
    Local $sText
    Local $i, $ii
    Local $aArraySection
    Local $aArray = IniReadSectionNames($sFile)

    For $i = 1 To UBound($aArray) - 1
        $aArraySection = IniReadSection($sFile, $aArray[$i])
        Local $mMapScratch[]
        For $ii = 1 To UBound($aArraySection) - 1
            $mMapScratch[$aArraySection[$ii][0]] = $aArraySection[$ii][1]
        Next
        $sText = $aArray[$i]
        $mMapReturn[$sText] = $mMapScratch
    Next

    Return($mMapReturn)

EndFunc

Sample .ini:

#region Last - Last 10 models updated using Muninn
[Last]
1=SM-N976B|EVR|3.13
2=SM-T585|BTU|3.13
3=SM-T295|BTU|3.13
4=SM-G973F|EVR|3.13
5=SM-A600FN|EVR|3.13
6=SM-A202F|EVR|3.13
7=SM-J415FN|BTU|3.13
8=SM-G975F|EVR|3.13
9=SM-G970F|EVR|3.13
10=SM-A510F|EVR|3.13
#endregion

#region FlashCountTargets - flash counts that will trigger an email
[FlashCountTargets]
Amounts=140000|150000|175000|200000|250000|300000|350000|400000|450000|500000|600000|700000|800000|900000|1000000
#endregion

#region FlashCountEmails - email addresses used when triggered by FlashCountTargets
[FlashCountEmails]
Users=melba23|junkew|jchd|water|iamtheky
#endregion

#region ListType - Top10 for the top 10 used models by hits. Last10 for the Last 10 models assigned by .init
[ListType]
ListType=Top10
#endregion

#region Variants - Key - RadioButton text ;; Value - 2-letter code from .init. Add |Locked to disable the radio from Flash Gui
[Variants]
Deep Black = DB|Locked
La Fleur =LF|Locked
Hugo Boss =HB|Locked
#endregion

 

Link to comment
Share on other sites

Also be aware that the Map datatype is deprecated.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

The map functions don't work as expected, so don't rely on them too much. Use a scripting.dictionary instead for future proofing, plus not everyone uses the Beta versions.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...