I want to include files from a folder in my script (I tried to Google but can't seem to find any way to do this with AutoIt). Example of what I want to achieve:
LoadFiles()
Func LoadFiles()
$FL = _FileListToArray(#ScriptDir&"\Test\", "*")
$X=1
Do
#include $FL[$X] <== How ?
$X=$X+1
Until $X=$FL[0]
EndFunc
Can anyone point me in the right direction?
In order to include a file(s) in your compiled script, you need FileInstall.
FileInstall ( "source", "dest" [, flag = 0] )
source The source path of the file to compile. This must be a literal string; it cannot be a variable or the result of a function call. It can be a relative path (using .\ or ..\ in the path) to the source file (.au3).
dest The destination path of the file with trailing backslash if only the directory is used. This can be a variable.
flag [optional] this flag determines whether to overwrite files if they already exist:
$FC_NOOVERWRITE (0) = (default) do not overwrite existing files
$FC_OVERWRITE (1) = overwrite existing files
Another way is adding the files as a resource
Good afternoon! There isn't currently a good way to do what you're asking. I've been working on building a UDF to do what you'd like, but I've been running into a couple of issues with it. I have a working prototype but there are some bugs in it. First things first, download this script and call it _includeDir.au3.
_includeDir.au3
#CS
Name: _includeDir.au3
Developer: Timothy Bomer
Copyright: Amarok Studios LLC 2016
Version: 1.0
Description:
The purpose of this UDF is to dynamically include all files inside of a folder.
It works for the most part, but I am still working on a couple of bugs.
#CE
#Include <File.au3>
Global $mainUDF = "IncludeDirUDF"
Global $includeLib = $mainUDF & "\" & "loadIncludes.au3"
Global $tempLib = $mainUDF & "\" & "lib.txt"
Global $includeRewrite = $mainUDF & "\rewrite.au3"
Global $iDirHolder = ""
Func _includeDir($iDir, $lineToInc = 1, $restart = True)
If (checkInclude()) = 1 Then
FileDelete($tempLib)
return
EndIf
If NOT (FileExists($iDir)) Then
MsgBox(16,"Directory Doesn't Exists | _includeDir","The directory " & $iDir & " does not exist!")
return 0
EndIf
$iDirHolder = $iDir
initializeCheck()
; MsgBox(0,"Include Directory", "Attempting to include: " & $iDir)
populateLib($iDir)
populateIncLib()
finalize($lineToInc, $restart)
EndFunc
Func checkInclude()
FileOpen(#ScriptName, 0)
For $i = 1 to _FileCountLines(#ScriptName)
$checkLine = FileReadLine(#ScriptName, $i)
If ($checkLine = '#Include "IncludeDirUDF\loadIncludes.au3"') Then
return 1
EndIf
Next
EndFunc
; START Initialize Check
Func initializeCheck()
; MsgBox(0,"Checking. . .", "Is this initialized?")
If (FileExists($mainUDF)) Then
If NOT (FileExists($includeLib)) Then
isError(2)
return
EndIf
; MsgBox(0,"Initialized","The UDF has been initialized")
Else
isError(1)
return
EndIf
EndFunc
; END Initialize Check
; START Library Population
Func populateLib($iDir = $iDirHolder)
; MsgBox(0,"Populating","Attempting to populate the library")
If (FileExists($tempLib)) Then
; MsgBox(0,"Temp File Found","The temporary library file has been found. Attempting to populate.")
$tLibCont = _FileListToArray(#ScriptDir & "\" & $iDir & "\", "*")
$iDirSize = $tLibCont[0]
; MsgBox(0,"Size of Included Directory", $iDir & " contains " & $iDirSize & " files to include!")
$writeLib = FileOpen($tempLib, 1)
While $iDirSize > 0
FileWriteLine($writeLib, '#Include "..\' & $iDir & '\' & $tLibCont[$iDirSize] & '"')
$iDirSize -= 1
WEnd
FileClose($writeLib)
Else
isError(3)
return
EndIf
EndFunc
; END Library Population
; START Include Library Population
Func populateIncLib()
; MsgBox(0,"Rewriting. . .", "Attempting to re-write the include library")
#CS
If (FileExists($includeLib)) Then
FileDelete($includeLib)
_FileCreate($includeLib)
EndIf
#CE
FileOpen($tempLib, 0)
For $i = 1 to _FileCountLines($tempLib)
$line = FileReadLine($tempLib, $i)
$reWriteLib = FileOpen($includeLib, 9)
FileWriteLine($reWriteLib, $line)
FileClose($reWriteLib)
Next
FileClose($tempLib)
EndFunc
; END Include Library Population
; START Finalize
Func finalize($lineToInc, $restart)
_FileWriteToLine(#ScriptName, $lineToInc, '#Include "IncludeDirUDF\loadIncludes.au3"', False)
If ($restart = True) Then
runFile(#ScriptName)
EndIf
exit
return
EndFunc
Func runFile($rFile)
$file_loc = $rFile
If #Compiled = 1 Then
$file_exe = FileGetShortName(#AutoItExe & ' /AutoIt3ExecuteScript "' & $file_loc & '"')
Run($file_exe)
Else
$file_au3 = FileGetShortName($file_loc)
Run(#AutoItExe & " " & $file_au3, "", #SW_HIDE)
EndIf
EndFunc
; START Error Reporting
Func isError($eFlag = "", $eMessage = "There was an error!")
If ($eFlag = "") Then
; MsgBox(16,"ERROR", $eMessage)
Exit
EndIf
If ($eFlag = 1) Then
; MsgBox(16,"Not Initialized","This UDF has not been initialized")
DirCreate($mainUDF)
Sleep(250)
initializeCheck()
return
ElseIf ($eFlag = 2) Then
; MsgBox(16,"Missing File","Missing the include library!")
_FileCreate($includeLib)
initializeCheck()
return
ElseIf ($eFlag = 3) Then
; MsgBox(16,"Missing File", "Missing the temporary library! Creating it now!",3)
_FileCreate($tempLib)
populateLib()
return
EndIf
EndFunc
; END Error Reporting
To use this UDF, include the file with:
Include "_includeDir.au3"
Next, call the function by following the below format.
_includeDir("Directory to Include", $lineToIncludeOn, $restart)
The directory to include would be the name of the directory with all of the files you're trying to include.
The $lineToIncludeOn specifies what line of the script the #Include will be written on. This is an optional parameter, and will default to line 1.
Lastly, $restart specifies if the script needs to be restarted or not. Sadly, the biggest bug is that the script needs to be restarted in order for the UDF to include all of the files. Which probably takes away the useful functionality of the entire script. This is an optional parameter, by default, it will be set to True and automatically restart the script.
Here's an example.
INSIDE OF WORKING DIRECTORY
Includes Folder
Example.au3
_includeDir.au3
INSIDE OF Includes Folder
One.au3
Two.au3
Three.au3
Four.au3
Five.au3
One.au3
$oneVar = "First variable"
Two.au3
$twoVar = "Second variable"
Three.au3
$threeVar = "Third variable"
Four.au3
$fourVar = "Fourth variable"
Five.au3
$fiveVar = "Fifth variable"
So, we are going to try to include One.au3, Two.au3, Three.au3, Four.au3, and Five.au3 into Example.au3.
Example.au3
; Exclude the numbers before the code. It's there just to show you the line the code is written on.
(1) #Include "_includeDir.au3"
(2)
(3) _includeDir("Includes Folder")
(4) MsgBox(0,"Included Variables","Variable One: " & $oneVar & #CRLF & "Variable Two: " & $twoVar & #CRLF & "Variable Three: " & $threeVar & #CRLF & "Variable Four: " & $fourVar & #CRLF & "Variable Five: " & $fiveVar)
This will add the line:
#Include "IncludeDirUDF\loadIncludes.au3"
to line one of Examples.au3, then restart Example.au3 to display the variables from the included files. If you changed the files inside of the Included Files directory, you will need to remove the #Include line for the loadIncludes.au3, and delete the folder that was generated. (IncludeDirUDF).
Let's say you don't want the #Include to be written to line one of Example.au3... To specify what line you want it to be written to, simply add the next parameter to the function call. For example, we want to write it to line 5 of Example.au3, we would use this:
_includeDir("Includes Folder", 5)
The last parameter is the restart parameter. This specifies if Example.au3 should be restarted after the directory is included. It is set to True by default. If you want Example.au3 to exit and stay terminated, simply add False to the end of the function call.
_includeDir("Includes Folder", 5, False)
In order to do what you're trying to do, the best way to use this would be to put it at the top of your Example.au3 (or whatever your script is) right underneath the includes. The reason for this is because it will auto-restart your script if when it generates the library and it could cause an error if it's not at the top. I hope this poorly written UDF helps you out! Let me know if there's something it's not doing that you need it to do. If not, let me know and I will fix it! Happy programming my friend! If this is too hard to follow, see my more detailed demonstration on the official AutoIt forum HERE
Thanks,
Tim
This is how i fixed it if anyone have the same issue ..
Only thing IncludeList.au3 have to exsist in the directory before you run the script or you will get include error
#include <WinAPIFiles.au3>
#include <File.au3>
; Delete Old IncludeList.au3
If FileExists("IncludeList.au3") Then
FileDelete("IncludeList.au3")
EndIf
; Get Files From Dir
$IL = _FileListToArray(#ScriptDir&"\Functions\", "*")
; Create New IncludeList.au3
$FH = FileOpen("IncludeList.au3", $FO_APPEND)
; Check For Errors
If #error <> 1 or #error <> 4 Then
; Loop True Files In Dir
For $FC = 1 To UBound($IL)-1 Step +1
; Write New #Include '.\Function\FilesToInclude.au3'
FileWrite($FH, "#Include '.\Functions\"&$IL[$FC]&"'"& #CRLF)
Next
EndIf
; Close File Handler
FileClose($FH)
; Include All The Files In Directory True IncludeList We Created
#include "IncludeList.au3"
; And Now You Can Call Any Functions From The Scripts From That Directory
Related
I'm using this code to load the ECG-ID database into MATLAB:
%% Initialization
clear all; close all; clc
%% read files from folder A
% Specify the folder where the files live.
myFolder = 'Databases\ECG_ID';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder;)
uiwait(warndlg(errorMessage);)
myFolder = uigetdir(; % Ask for a new one.)
if myFolder == 0
% User clicked Cancel
return;
end
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '**/rec_*'; % Change to whatever pattern you need.)
theFiles = dir(filePattern;)
for k = 1 : length(theFiles)
baseFileName = theFiles(k.name;)
fullFileName = fullfile(theFiles(k.folder, baseFileName);)
fprintf(1, 'Now reading %s\n', fullFileName;)
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
[sig, Fs, tm] = rdsamp(fullFileName, [1],[],[],[],1;)
end
But I keep getting this error message:
Now reading C:\Users\******\Documents\MATLAB\Databases\ECG_ID\Person_01\rec_1.atr
Error using rdsamp (line 203)
Could not find record: C:\Users\******\Documents\MATLAB\Databases\ECG_ID\Person_01\rec_1.atr. Search path is set to: '.
C:\Users\******\Documents\MATLAB\mcode\..\database\ http://physionet.org/physiobank/database/'
I can successfully load one signal at a time (but I can't load the entire database using the above code) using this command:
[sig, Fs, tm] = rdsamp('Databases\ECG_ID\Person_01\rec_1');
How do I solve this problem? How can I load all the files in MATLAB?
Thanks in advance.
My AutoIt script doesn't work. It should rename files by actual date and time.
#include <Date.au3>
#include <File.au3>
FileMove("C:\file.csv", "C:\file" & _NowDate() & _NowTime() & ".csv")
There is no syntax error, but the file isn't renamed. I think Windows rejects symbols like : or /. How to convert time to this format: hh-mm-ss_dd-mm-yyyy?
"... how to convert time in this format : hh-mm-ss_dd-mm-yyyy?"
As per Documentation - Macro Reference (as there is nothing to convert):
Global Const $g_sPathFile = 'C:\file.csv'
Global Const $g_sFormat = '%s-%s-%s_%s-%s-%s'
Global Const $g_sTime = StringFormat($g_sFormat, #HOUR, #MIN, #SEC, #MDAY, #MON, #YEAR)
Global Const $g_sNameNew = StringReplace($g_sPathFile, '.', $g_sTime & '.', -1)
FileMove($g_sPathFile, $g_sNameNew)
yyyymmddhhmmss -format conforms to string sort (displays chronological order by Windows Explorer).
Related.
you can sanitize the output inline
#include <Date.au3>
FileMove("file.csv", "file" & stringreplace(_NowTime(5) , ":" , "-") & "_" &
stringregexpreplace(_NowCalcDate() , "(\d\d\d\d)/(\d\d)/(\d\d)" , "$3-$2-$1") &
".csv")
This question already has an answer here:
Inno Setup - How to display localized RTF text in custom page
(1 answer)
Closed 5 years ago.
In another question, I asked about importing an RTF file into InnoSetup to use for a custom wizard page:
Import external RTF file for TRichEditViewer?
Unfortunately, I was only able to figure out how to use the answer so that the external file would be loaded if that file existed on the user's system, and in this case, it doesn't exist on the user's system; it's a file I created to display the installer.
I couldn't figure out how to load the external file so that it would be saved inside the compiled installer script and be visible on someone else's system.
Here is the code I put together. I've experimented with creating separate procedures for loading the string, but haven't been able to figure out how to make it work. I'll be grateful for any help:
procedure CreateTheWizardPages;
var
#ifndef UNICODE
rtfstr: string;
#else
rtfstr: AnsiString;
#endif
var
Page: TWizardPage;
RichEditViewer: TRichEditViewer;
vDosFolder: String;
begin
LoadStringFromFile('c:\dropbox\vdosinst\custom.rtf', rtfstr);
if RegQueryStringValue(HKEY_CURRENT_USER, 'Software\WPDOS.org','vDosDir', vDosFolder) then
begin
if ((DirExists(vDosFolder + '\62Config')) OR (DirExists(vDosFolder + '\61Config')) OR (DirExists(vDosFolder + '\51Config'))) then
begin
Page := CreateCustomPage(wpInfoBefore, 'How to install vDosWP-VDM with an existing vDosWP system', 'Read this message for important information!');
RichEditViewer := TRichEditViewer.Create(Page);
RichEditViewer.Width := Page.SurfaceWidth;
RichEditViewer.Height := Page.SurfaceHeight;
RichEditViewer.Parent := Page.Surface;
RichEditViewer.ScrollBars := ssVertical;
RichEditViewer.UseRichEdit := True;
RichEditViewer.RTFText := rtfstr;
RichEditViewer.ReadOnly := True;
end;
end;
end;
procedure InitializeWizard(); // ISSI_ added to string
begin
CreateTheWizardPages;
end;
You can add this compile time macro before your code block:
#pragma parseroption -p-
#define FileHandle
#define FileLine
#define FileName
#define Result
#sub ProcessFileLine
#define FileLine = FileRead(FileHandle)
#if Len(Result) > 0 && !FileEof(FileHandle)
#expr Result = Result + "#10#13 + \n"
#endif
#if FileLine != '\0'
#expr Result = Result + "'" + FileLine + "'"
#endif
#endsub
#sub ProcessFile
#for {FileHandle = FileOpen(FileName); \
FileHandle && !FileEof(FileHandle); ""} \
ProcessFileLine
#if FileHandle
#expr FileClose(FileHandle)
#endif
#endsub
#define ReadFileAsStr(str AFileName) \
Result = '', FileName = AFileName, ProcessFile, Result
This macro outputs file content as string constant. This works for most RTF files, but some characters inside RTF can broke this code.
To fix this you need to escape ', " and may be some other characters inside ProcessFileLine sub.
Then you can use this macro in [Code] block this way:
RichEditViewer.RTFText := {#emit ReadFileAsStr("custom.rtf")};
I'm running a script made in Groovy from Soap UI and the script needs to generate lots of files.
Those files have also in the name two numbers from a list (all the combinations in that list are different), and there are 1303 combinations
available and the script generates just 1235 files.
A part of the code is:
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
where $file is actually that part of the file name which include those 2 combinations from that list:
file = "abc" + "-$firstNumer"+"_$secondNumber"
For those file which are not created is a message returned:"The filename, directory name or volume label syntax is incorrect".
I've tried puting another path:
filename = "D:\\rez\\" + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
and also:
File parentFolder = new File("D:\\rez\\");
File targetFile = new File(parentFolder, "$file"+"_OK.txt");
targetFile.createNewFile();
(which I've found here: What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect")
but nothing worked.
I have no ideea where the problem is. Is strange that 1235 files are created ok, and the rest of them, 68 aren't created at all.
Thanks,
My guess is that some of the files have illegal characters in their paths. Exactly which characters are illegal is platform specific, e.g. on Windows they are
\ / : * ? " < > |
Why don't you log the full path of the file before targetFile.createNewFile(); is called and also log whether this method succeeded or not, e.g.
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
println "attempting to create file: $targetFile"
if (targetFile.createNewFile()) {
println "Successfully created file $targetFile"
} else {
println "Failed to create file $targetFile"
}
When the process is finished, check the logs and I suspect you'll see a common pattern in the ""Failed to create file...." messages
File.createNewFile() returns false when a file or directory with that name already exists. In all other failure cases (security, I/O) it throws an exception.
Evaluate createNewFile()'s return value or, additionally, use the File.exists() method:
File file = new File("foo")
// works the first time
createNewFile(file)
// prints an error message
createNewFile(file)
void createNewFile(File file) {
if (!file.createNewFile()) {
assert file.exists()
println file.getPath() + " already exists."
}
}
I'm trying to make a simple Vim script that would create very compact top-level folds for c files. Ideally, if it was run on this code:
static void funca(...)
{
...
}
/* Example comment */
static void funcb(...)
{
...
}
Then it would create folds which would look like this when closed:
+-- x Lines: static void funca(...)----------------------
+-- x Lines: static void funcb(...)----------------------
So basically it would be like foldmethod=syntax with foldlevel=1, except that each fold would start one line further up, and would extend further down to include all following blank lines.
I know how to make one of these folds (assuming foldmethod=manual):
/^{<cr>kVnn?^$<cr>zf
But I'm not sure how to put it into a function. This is my effort:
function Cfold()
set foldmethod=manual " Manual folds
ggzE " Delete all folds
while (/^{<cr>) " Somehow loop through each match
kVnn?^$<cr>zf " This would work fine except for the last function
endwhile
endfunction
map <Leader>f :call Cfold()<cr>
But it isn't valid, I'm not entirely sure how functions work. Also, it won't work for the last function in the file, since it won't find '^{' again. If someone could help me get this working, and somehow add a case for the last function in a file, I would be extremely grateful.
Thanks in advance :)
You can create folds programmatically using the foldexpr and foldtext. Try this, though you may have to tweak CFoldLevel so it doesn't swallow non-function parts of the code:
function! CFoldLevel(lnum)
let line = getline(a:lnum)
if line =~ '^/\*'
return '>1' " A new fold of level 1 starts here.
else
return '1' " This line has a foldlevel of 1.
endif
endfunction
function! CFoldText()
" Look through all of the folded text for the function signature.
let signature = ''
let i = v:foldstart
while signature == '' && i < v:foldend
let line = getline(i)
if line =~ '\w\+(.*)$'
let signature = line
endif
let i = i + 1
endwhile
" Return what the fold should show when folded.
return '+-- ' . (v:foldend - v:foldstart) . ' Lines: ' . signature . ' '
endfunction
function! CFold()
set foldenable
set foldlevel=0
set foldmethod=expr
set foldexpr=CFoldLevel(v:lnum)
set foldtext=CFoldText()
set foldnestmax=1
endfunction
See :help 'foldexpr' for more details.