2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -46,3 +46,4 @@ We also have an option that contains multiple parameters. These may be stored in
'''See also:'''
* [[Update a configuration file]]
<br><br>

View file

@ -0,0 +1,253 @@
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Read a Configuration File V1.0 '
' '
' Developed by A. David Garza Marín in VB-DOS for '
' RosettaCode. December 2, 2016. '
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
OPTION EXPLICIT ' For VB-DOS, PDS 7.1
' OPTION _EXPLICIT ' For QB64
' SUBs and FUNCTIONs
DECLARE FUNCTION ErrorMessage$ (WhichError AS INTEGER)
DECLARE FUNCTION YorN$ ()
DECLARE FUNCTION FileExists% (WhichFile AS STRING)
DECLARE FUNCTION ReadConfFile% (NameOfConfFile AS STRING)
DECLARE FUNCTION getVariable$ (WhichVariable AS STRING)
DECLARE FUNCTION getArrayVariable$ (WhichVariable AS STRING, WhichIndex AS INTEGER)
' Register for values located
TYPE regVarValue
VarName AS STRING * 20
VarType AS INTEGER ' 1=String, 2=Integer, 3=Real
VarValue AS STRING * 30
END TYPE
' Var
DIM rVarValue() AS regVarValue, iErr AS INTEGER, i AS INTEGER, iHMV AS INTEGER
DIM otherfamily(1 TO 2) AS STRING
DIM fullname AS STRING, favouritefruit AS STRING, needspeeling AS INTEGER, seedsremoved AS INTEGER
CONST ConfFileName = "config.fil"
' ------------------- Main Program ------------------------
CLS
PRINT "This program reads a configuration file and shows the result."
PRINT
PRINT "Default file name: "; ConfFileName
PRINT
iErr = ReadConfFile(ConfFileName)
IF iErr = 0 THEN
iHMV = UBOUND(rVarValue)
PRINT "Variables found in file:"
FOR i = 1 TO iHMV
PRINT RTRIM$(rVarValue(i).VarName); " = "; RTRIM$(rVarValue(i).VarValue); " (";
SELECT CASE rVarValue(i).VarType
CASE 0: PRINT "Undefined";
CASE 1: PRINT "String";
CASE 2: PRINT "Integer";
CASE 3: PRINT "Real";
END SELECT
PRINT ")"
NEXT i
PRINT
' Sets required variables
fullname = getVariable$("FullName")
favouritefruit = getVariable$("FavouriteFruit")
needspeeling = VAL(getVariable$("NeedSpeeling"))
seedsremoved = VAL(getVariable$("SeedsRemoved"))
FOR i = 1 TO 2
otherfamily(i) = getArrayVariable$("OtherFamily", i)
NEXT i
PRINT "Variables requested to set values:"
PRINT "fullname = "; fullname
PRINT "favouritefruit = "; favouritefruit
PRINT "needspeeling = ";
IF needspeeling = 0 THEN PRINT "false" ELSE PRINT "true"
PRINT "seedsremoved = ";
IF seedsremoved = 0 THEN PRINT "false" ELSE PRINT "true"
FOR i = 1 TO 2
PRINT "otherfamily("; i; ") = "; otherfamily(i)
NEXT i
ELSE
PRINT ErrorMessage$(iErr)
END IF
' --------- End of Main Program -----------------------
END
FileError:
iErr = ERR
RESUME NEXT
FUNCTION ErrorMessage$ (WhichError AS INTEGER)
' Var
DIM sError AS STRING
SELECT CASE WhichError
CASE 0: sError = "Everything went ok."
CASE 1: sError = "Configuration file doesn't exist."
CASE 2: sError = "There are no variables in the given file."
END SELECT
ErrorMessage$ = sError
END FUNCTION
FUNCTION FileExists% (WhichFile AS STRING)
' Var
DIM iFile AS INTEGER
DIM iItExists AS INTEGER
SHARED iErr AS INTEGER
ON ERROR GOTO FileError
iFile = FREEFILE
iErr = 0
OPEN WhichFile FOR BINARY AS #iFile
IF iErr = 0 THEN
iItExists = LOF(iFile) > 0
CLOSE #iFile
IF NOT iItExists THEN
KILL WhichFile
END IF
END IF
ON ERROR GOTO 0
FileExists% = iItExists
END FUNCTION
FUNCTION getArrayVariable$ (WhichVariable AS STRING, WhichIndex AS INTEGER)
' Var
DIM i AS INTEGER, iHMV AS INTEGER, iCount AS INTEGER
DIM sVar AS STRING, sVal AS STRING, sWV AS STRING
SHARED rVarValue() AS regVarValue
' Looks for a variable name and returns its value
iHMV = UBOUND(rVarValue)
sWV = UCASE$(LTRIM$(RTRIM$(WhichVariable)))
sVal = ""
DO
i = i + 1
sVar = UCASE$(RTRIM$(rVarValue(i).VarName))
IF sVar = sWV THEN
iCount = iCount + 1
IF iCount = WhichIndex THEN
sVal = LTRIM$(RTRIM$(rVarValue(i).VarValue))
END IF
END IF
LOOP UNTIL i >= iHMV OR sVal <> ""
' Found it or not, it will return the result.
' If the result is "" then it didn't found the requested variable.
getArrayVariable$ = sVal
END FUNCTION
FUNCTION getVariable$ (WhichVariable AS STRING)
' Var
DIM i AS INTEGER, iHMV AS INTEGER
DIM sVal AS STRING
' For a single variable, looks in the first (and only)
' element of the array that contains the name requested.
sVal = getArrayVariable$(WhichVariable, 1)
getVariable$ = sVal
END FUNCTION
FUNCTION ReadConfFile% (NameOfConfFile AS STRING)
' Var
DIM iFile AS INTEGER, iType AS INTEGER, iVar AS INTEGER, iHMV AS INTEGER
DIM iVal AS INTEGER, iCurVar AS INTEGER, i AS INTEGER, iErr AS INTEGER
DIM dValue AS DOUBLE
DIM sLine AS STRING, sVar AS STRING, sValue AS STRING
SHARED rVarValue() AS regVarValue
' This procedure reads a configuration file with variables
' and values separated by the equal sign (=) or a space.
' It needs the FileExists% function.
' Lines begining with # or blank will be ignored.
IF FileExists%(NameOfConfFile) THEN
iFile = FREEFILE
REDIM rVarValue(1 TO 10) AS regVarValue
OPEN NameOfConfFile FOR INPUT AS #iFile
WHILE NOT EOF(iFile)
LINE INPUT #iFile, sLine
sLine = RTRIM$(LTRIM$(sLine))
IF LEN(sLine) > 0 THEN ' Does it have any content?
IF LEFT$(sLine, 1) <> "#" THEN ' Is not a comment?
IF LEFT$(sLine,1) = ";" THEN ' It is a commented variable
sLine = LTRIM$(MID$(sLine, 2))
END IF
iVar = INSTR(sLine, "=") ' Is there an equal sign?
IF iVar = 0 THEN iVar = INSTR(sLine, " ") ' if not then is there a space?
GOSUB AddASpaceForAVariable
iCurVar = iHMV
IF iVar > 0 THEN ' Is a variable and a value
rVarValue(iHMV).VarName = LEFT$(sLine, iVar - 1)
ELSE ' Is just a variable name
rVarValue(iHMV).VarName = sLine
rVarValue(iHMV).VarValue = ""
END IF
IF iVar > 0 THEN ' Get the value(s)
sLine = LTRIM$(MID$(sLine, iVar + 1))
DO ' Look for commas
iVal = INSTR(sLine, ",")
IF iVal > 0 THEN ' There is a comma
rVarValue(iHMV).VarValue = RTRIM$(LEFT$(sLine, iVal - 1))
GOSUB AddASpaceForAVariable
rVarValue(iHMV).VarName = rVarValue(iHMV - 1).VarName ' Repeats the variable name
sLine = LTRIM$(MID$(sLine, iVal + 1))
END IF
LOOP UNTIL iVal = 0
rVarValue(iHMV).VarValue = sLine
' Determine the variable type of each variable found in this step
FOR i = iCurVar TO iHMV
GOSUB DetermineVariableType
NEXT i
END IF
END IF
END IF
WEND
CLOSE iFile
IF iHMV > 0 THEN
REDIM PRESERVE rVarValue(1 TO iHMV) AS regVarValue
iErr = 0 ' Everything ran ok.
ELSE
REDIM rVarValue(1 TO 1) AS regVarValue
iErr = 2 ' No variables found in configuration file
END IF
ELSE
iErr = 1 ' File doesn't exist
END IF
ReadConfFile = iErr
EXIT FUNCTION
AddASpaceForAVariable:
iHMV = iHMV + 1
IF UBOUND(rVarValue) < iHMV THEN ' Are there space for a new one?
REDIM PRESERVE rVarValue(1 TO iHMV + 9) AS regVarValue
END IF
RETURN
DetermineVariableType:
sValue = RTRIM$(rVarValue(i).VarValue)
IF ASC(LEFT$(sValue, 1)) < 48 OR ASC(LEFT$(sValue, 1)) > 57 THEN
rVarValue(i).VarType = 1 ' String
ELSE
dValue = VAL(sValue)
IF CLNG(dValue) = dValue THEN
rVarValue(i).VarType = 2 ' Integer
ELSE
rVarValue(i).VarType = 3 ' Real
END IF
END IF
RETURN
END FUNCTION

View file

@ -0,0 +1,35 @@
defmodule Configuration_file do
def read(file) do
File.read!(file)
|> String.split(~r/\n|\r\n|\r/, trim: true)
|> Enum.reject(fn line -> String.starts_with?(line, ["#", ";"]) end)
|> Enum.map(fn line ->
case String.split(line, ~r/\s/, parts: 2) do
[option] -> {to_atom(option), true}
[option, values] -> {to_atom(option), separate(values)}
end
end)
end
def task do
defaults = [fullname: "Kalle", favouritefruit: "apple", needspeeling: false, seedsremoved: false]
options = read("configuration_file") ++ defaults
[:fullname, :favouritefruit, :needspeeling, :seedsremoved, :otherfamily]
|> Enum.each(fn x ->
values = options[x]
if is_boolean(values) or length(values)==1 do
IO.puts "#{x} = #{values}"
else
Enum.with_index(values) |> Enum.each(fn {value,i} ->
IO.puts "#{x}(#{i+1}) = #{value}"
end)
end
end)
end
defp to_atom(option), do: String.downcase(option) |> String.to_atom
defp separate(values), do: String.split(values, ",") |> Enum.map(&String.strip/1)
end
Configuration_file.task

View file

@ -0,0 +1,42 @@
\ declare the configuration variables in the FORTH app
FORTH DEFINITIONS
32 CONSTANT $SIZE
VARIABLE FULLNAME $SIZE ALLOT
VARIABLE FAVOURITEFRUIT $SIZE ALLOT
VARIABLE NEEDSPEELING
VARIABLE SEEDSREMOVED
VARIABLE OTHERFAMILY(1) $SIZE ALLOT
VARIABLE OTHERFAMILY(2) $SIZE ALLOT
: -leading ( addr len -- addr' len' )
begin over c@ bl = while 1 /string repeat ; \ remove leading blanks
: trim ( addr len -- addr len) -leading -trailing ; \ remove blanks both ends
\ create the config file interpreter -------
VOCABULARY CONFIG \ create a namespace
CONFIG DEFINITIONS \ put things in the namespace
: SET ( addr --) true swap ! ;
: RESET ( addr --) false swap ! ;
: # ( -- ) 1 PARSE 2DROP ; \ parse line and throw away
: = ( addr --) 1 PARSE trim ROT PLACE ; \ string assignment operator
synonym ; # \ 2nd comment operator is simple
FORTH DEFINITIONS
\ this command reads and interprets the config.txt file
: CONFIGURE ( -- ) CONFIG s" CONFIG.TXT" INCLUDED FORTH ;
\ config file interpreter ends ------
\ tools to validate the CONFIG interpreter
: $. ( str --) count type ;
: BOOL. ( ? --) @ IF ." ON" ELSE ." OFF" THEN ;
: .CONFIG CR ." Fullname : " FULLNAME $.
CR ." Favourite fruit: " FAVOURITEFRUIT $.
CR ." Needs peeling : " NEEDSPEELING bool.
CR ." Seeds removed : " SEEDSREMOVED bool.
CR ." Family:"
CR otherfamily(1) $.
CR otherfamily(2) $. ;

View file

@ -24,9 +24,9 @@ grammar ConfFile {
token line:sym<comment> { ^^ [ ';' | '#' ] \N* }
token line:sym<blank> { ^^ \h* $$ }
token line:sym<fullname> {:i fullname» <rest> { $fullname = $<rest>[0].trim } }
token line:sym<favouritefruit> {:i favouritefruit» <rest> { $favouritefruit = $<rest>[0].trim } }
token line:sym<needspeeling> {:i needspeeling» <yes> { $needspeeling = defined $<yes>[0] } }
token line:sym<fullname> {:i fullname» <rest> { $fullname = $<rest>.trim } }
token line:sym<favouritefruit> {:i favouritefruit» <rest> { $favouritefruit = $<rest>.trim } }
token line:sym<needspeeling> {:i needspeeling» <yes> { $needspeeling = defined $<yes> } }
token rest { \h* '='? (\N*) }
token yes { :i \h* '='? \h*
[
@ -38,15 +38,13 @@ grammar ConfFile {
}
grammar MyConfFile is ConfFile {
token line:sym<otherfamily> {:i otherfamily» <many> { @otherfamily = $<many>[0]».trim} }
token many { \h*'='? ([ <![,]> \N ]*) ** ',' }
token line:sym<otherfamily> {:i otherfamily» <rest> { @otherfamily = $<rest>.split(',')».trim } }
}
MyConfFile.parsefile('file.cfg');
.perl.say for
:$fullname,
:$favouritefruit,
:$needspeeling,
:$seedsremoved,
:@otherfamily;
say "fullname: $fullname";
say "favouritefruit: $favouritefruit";
say "needspeeling: $needspeeling";
say "seedsremoved: $seedsremoved";
print "otherfamily: "; say @otherfamily.perl;

View file

@ -0,0 +1,68 @@
function Read-ConfigurationFile
{
[CmdletBinding()]
Param
(
# Path to the configuration file. Default is "C:\ConfigurationFile.cfg"
[Parameter(Mandatory=$false, Position=0)]
[string]
$Path = "C:\ConfigurationFile.cfg"
)
[string]$script:fullName = ""
[string]$script:favouriteFruit = ""
[bool]$script:needsPeeling = $false
[bool]$script:seedsRemoved = $false
[string[]]$script:otherFamily = @()
function Get-Value ([string]$Line)
{
if ($Line -match "=")
{
[string]$value = $Line.Split("=",2).Trim()[1]
}
elseif ($Line -match " ")
{
[string]$value = $Line.Split(" ",2).Trim()[1]
}
$value
}
# Process each line in file that is not a comment.
Get-Content $Path | Select-String -Pattern "^[^#;]" | ForEach-Object {
[string]$line = $_.Line.Trim()
if ($line -eq [String]::Empty)
{
# do nothing for empty lines
}
elseif ($line.ToUpper().StartsWith("FULLNAME"))
{
$script:fullName = Get-Value $line
}
elseif ($line.ToUpper().StartsWith("FAVOURITEFRUIT"))
{
$script:favouriteFruit = Get-Value $line
}
elseif ($line.ToUpper().StartsWith("NEEDSPEELING"))
{
$script:needsPeeling = $true
}
elseif ($line.ToUpper().StartsWith("SEEDSREMOVED"))
{
$script:seedsRemoved = $true
}
elseif ($line.ToUpper().StartsWith("OTHERFAMILY"))
{
$script:otherFamily = (Get-Value $line).Split(',').Trim()
}
}
Write-Verbose -Message ("{0,-15}= {1}" -f "FULLNAME", $script:fullName)
Write-Verbose -Message ("{0,-15}= {1}" -f "FAVOURITEFRUIT", $script:favouriteFruit)
Write-Verbose -Message ("{0,-15}= {1}" -f "NEEDSPEELING", $script:needsPeeling)
Write-Verbose -Message ("{0,-15}= {1}" -f "SEEDSREMOVED", $script:seedsRemoved)
Write-Verbose -Message ("{0,-15}= {1}" -f "OTHERFAMILY", ($script:otherFamily -join ", "))
}

View file

@ -0,0 +1 @@
Read-ConfigurationFile -Path .\temp.txt -Verbose

View file

@ -0,0 +1 @@
Get-Variable -Name fullName, favouriteFruit, needsPeeling, seedsRemoved, otherFamily

View file

@ -1,47 +1,46 @@
/*REXX program to read a config file and assign VARs as found within. */
signal on syntax; signal on novalue /*handle REXX program errors. */
parse arg cFID _ . /*cFID = config file to be read. */
if cFID=='' then cFID='CONFIG.DAT' /*Not specified? Use the default*/
bad= /*this will contain all bad VARs.*/
varList= /*this will contain all the VARs.*/
maxLenV=0; blanks=0; hashes=0; semics=0; badVar=0 /*zero 'em.*/
/*REXX program reads a config (configuration) file and assigns VARs as found within. */
signal on syntax; signal on novalue /*handle REXX source program errors. */
parse arg cFID _ . /*cFID: is the CONFIG file to be read.*/
if cFID=='' then cFID='CONFIG.DAT' /*Not specified? Then use the default.*/
bad= /*this will contain all the bad VARs. */
varList= /* " " " " " good " */
maxLenV=0; blanks=0; hashes=0; semics=0; badVar=0 /*zero all these variables.*/
do j=0 while lines(cFID)\==0 /*J count's the file's lines. */
txt=strip(linein(cFID)) /*read a line (record) from file,*/
/*& strip leading/trailing blanks*/
if txt ='' then do; blanks=blanks+1; iterate; end
if left(txt,1)=='#' then do; hashes=hashes+1; iterate; end
if left(txt,1)==';' then do; semics=semics+1; iterate; end
eqS=pos('=',txt) /*can't use the TRANSLATE bif. */
if eqS\==0 then txt=overlay(' ',txt,eqS) /*replace 1st '=' with blank*/
parse var txt xxx value; upper xxx /*get the variableName and value.*/
value=strip(value) /*strip leading & trailing blanks*/
if value='' then value='true' /*if no value, then use "true". */
if symbol(xxx)=='BAD' then do /*can REXX use the variable name?*/
badVar=badVar+1; bad=bad xxx; iterate
do j=0 while lines(cFID)\==0 /*J: it counts the lines in the file.*/
txt=strip(linein(cFID)) /*read a line (record) from the file, */
/* ··· & strip leading/trailing blanks*/
if txt ='' then do; blanks=blanks+1; iterate; end /*count # blank lines.*/
if left(txt,1)=='#' then do; hashes=hashes+1; iterate; end /* " " lines with #*/
if left(txt,1)==';' then do; semics=semics+1; iterate; end /* " " " " ;*/
eqS=pos('=',txt) /*we can't use the TRANSLATE BIF. */
if eqS\==0 then txt=overlay(' ',txt,eqS) /*replace the first '=' with a blank.*/
parse var txt xxx value; upper xxx /*get the variable name and it's value.*/
value=strip(value) /*strip leading and trailing blanks. */
if value='' then value='true' /*if no value, then use "true". */
if symbol(xxx)=='BAD' then do /*can REXX utilize the variable name ? */
badVar=badVar+1; bad=bad xxx; iterate /*append to list*/
end
varList=varList xxx /*add it to the list of variables*/
call value xxx,value /*now, use VALUE to set the var. */
maxLenV=max(maxLenV,length(value)) /*maxLen of varNames, pretty disp*/
varList=varList xxx /*add it to the list of good variables.*/
call value xxx,value /*now, use VALUE to set the variable. */
maxLenV=max(maxLenV,length(value)) /*maxLen of varNames, pretty display. */
end /*j*/
vars=words(varList)
say #(j) 'record's(j) "were read from file: " cFID
if blanks\==0 then say #(blanks) 'blank record's(blanks) "were read."
if hashes\==0 then say #(hashes) 'record's(hashes) "ignored that began with a # (hash)."
if semics\==0 then say #(semics) 'record's(semics) "ignored that began with a ; (semicolon)."
if badVar\==0 then say #(badVar) 'bad variable name's(badVar) 'detected:' bad
say; say 'The list of' vars "variable"s(vars) 'and' s(vars,'their',"it's") "value"s(vars) 'follows:'; say
do k=1 for vars
vars=words(varList); @ig= 'ignored that began with a'
say #(j) 'record's(j) "were read from file: " cFID
if blanks\==0 then say #(blanks) 'blank record's(blanks) "were read."
if hashes\==0 then say #(hashes) 'record's(hashes) @ig "# (hash)."
if semics\==0 then say #(semics) 'record's(semics) @ig "; (semicolon)."
if badVar\==0 then say #(badVar) 'bad variable name's(badVar) 'detected:' bad
say; say 'The list of' vars "variable"s(vars) 'and' s(vars,'their',"it's"),
"value"s(vars) 'follows:'
say; do k=1 for vars
v=word(varList,k)
say right(v,maxLenV) '=' value(v)
end /*k*/
exit /*stick a fork in it, we're done.*/
/*───────────────────────────────error handling subroutines and others.─*/
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1)
#: return right(arg(1),length(j)+11) /*right justify a number +indent*/
err: say; say; say center(' error! ', max(40, linesize()%2), "*"); say
do j=1 for arg(); say arg(j); say; end; say; exit 13
say; exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1)
#: return right(arg(1),length(j)+11) /*right justify a number & also indent.*/
err: do j=1 for arg(); say '***error*** ' arg(j); say; end /*j*/; exit 13
novalue: syntax: call err 'REXX program' condition('C') "error",,
condition('D'),'REXX source statement (line' sigl"):",sourceline(sigl)