Repeat loop with if conditions for first and last time - loops

I have a script that I made that works fine but I have to make some very minor edits to the output. Instead I'd like to just do it correctly.
on run {input, parameters}
set the formatted to {}
set listContents to get the clipboard
set delimitedList to paragraphs of listContents
repeat with listitem in delimitedList
set myVar to "#\"" & listitem & "\"," & (ASCII character 10)
copy myVar to the end of formatted
end repeat
display dialog formatted as string
return formatted as string
end run
I'd like prepend the first item slightly differently and append the last a little different.
I tried the following but the script is not right.
repeat with n from 1 to count of delimitedList
-- not sure how to if/else n == 0 or delimitedList.count
end repeat

There is a more efficient way, text item delimiters. It can insert the comma and the linefeed character between the list items
on run {input, parameters}
set the formatted to {}
set listContents to get the clipboard
set delimitedList to paragraphs of listContents
repeat with listitem in delimitedList
copy "#" & quote & listitem & quote to the end of formatted
end repeat
set {saveTID, text item delimiters} to {text item delimiters, {"," & linefeed}}
set formatted to formatted as text
set text item delimiters to saveTID
display dialog formatted
return formatted
end run
Side note: ASCII character 10 is deprecated since macOS 10.5 Leopard, there is linefeed, tab (9), return (13), space (32) and quote (34).

In addition to an index or range, the various items of a list can also be accessed by using location parameters such as first, last, beginning, etc (note that AppleScript lists start at index 1). To deal with the first and last items separately, you can do something like:
on run {input, parameters} -- example
set formatted to {}
set delimitedList to paragraphs of (the clipboard)
if delimitedList is not {} then
if (count delimitedList) > 2 then repeat with anItem in items 2 thru -2 of delimitedList
set the end of formatted to "#" & quote & anItem & quote
end repeat
set the beginning of formatted to "#" & quote & "First: " & first item of delimitedList & quote -- or whatever
if rest of delimitedList is not {} then set the end of formatted to "#" & quote & "Last: " & last item of delimitedList & quote -- or whatever
set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "," & linefeed}
set {formatted, AppleScript's text item delimiters} to {formatted as text, tempTID}
end if
display dialog formatted as text
return formatted as text
end run

Related

Python joining a list by "\"

Lets say I have a list of elements.
l = ["xf3", "x03", "x8c"] etc.
Now I would like to join the elements inside my list with a "\". I tried r"\".join(l) but it didn't work.
\ is used to escape 'special' characters, hence a Python string can not terminate with a single \ because it escapes the closing quote.
You have to escape it by using a second \, ie '\\'.join(l)
l = ["xf3", "x03", "x8c"]
'\\'.join(l)
The important part is to escape the '\\' as inn Python Strings:
the backslash "\" is a special character, also called the "escape"
character. It is used in representing certain whitespace characters:
"\t" is a tab, "\n" is a newline, and "\r" is a carriage return. As well "\"
can be used to escape itself: "\" is the literal backslash character.
I'm assuming is what you actually want is to create a string containing those escaped characters. The easiest way I can think of is ast.literal_eval:
>>> import ast
>>> ast.literal_eval("'\\" + "\\".join(l) + "'")
'ó\x03\x8c'
This works by first creating a string of those strings joined by backslash characters (xf3\x03\x8c), surrounding those by quotes and adding the initial backslash ('\xf3\x03\x8c'), and finally, by evaluating it as a literal, to turn it from a length 12 string into a length 3 string.

Getting "#ERROR" in certain fields when using Split function in SSRS

I am using a split function to separate a column with two street addresses.
The information is separated by ,.
Some of the rows only have one address associated with them.
In those rows for my Street Address 2, I'm getting #ERROR when I want it to be null.
I've tried an IIF() statement for the expression, but I am having trouble with it.
Split(Fields!Street.Value, ",").GetValue(2)
(Use a custom function for each Address.
Adapted from: Split String
Public Function GetAddress1(ByVal a as String)
Dim b() as string
b=Split(a,",")
Dim str_1(b.Length) As String
Dim i As Integer
For i = 0 To b.Length - 1
str_1(i) = b(i).Split(",")(0)
Next
return str_1
End Function
Public Function GetAddress2 (ByVal a as String)
Dim b() as string
b=Split(a,",")
Dim str_1(b.Length) As String
Dim i As Integer
For i = 0 To b.Length - 1
str_1(i) = b(i).Split(",")(1)
Next
return str_1
End Function
Unlike the If statement, IIf statements evaluate all code paths even though only one code path is used. This means that an error in an unused code-path will bubble up to an error in the IIf statement, preventing it from executing correctly.
To fix this, you need to use functions that won't throw an error when there is nothing to split.
Here is an example of code that should do what you want:
=IIf(
InStr(
InStr(
Parameters!Street.Value
, ","
) + 1
,
Parameters!Street.Value
, ","
) = 0
, Nothing
, Right(
Parameters!Street.Value
, Parameters!Street.Value.ToString().Length - (
InStr(
InStr(
Parameters!Street.Value
, ","
) + 1
,
Parameters!Street.Value
, ","
)
)
)
)
Let's break this down.
I've used a combination of InStr(), Right(), Length(), and IIf() functions to split the string without throwing an error.
InStr() is used to find the position of the string "," within the address. This returns 0 rather than an error if it can't find the string.
InStr(Parameters!Street.Value, ",")
Since you appear to be looking for the second comma in your split function you will need to nest the InStr function. Use the location of the first comma as the start location to search for the second comma. Don't forget to +1 or you will find the first comma again.
InStr(InStr(Parameters!Street.Value, ",") + 1, Parameters!Street.Value, ",")
Now you can find the second comma without throwing an error even if no commas exist.
Based on the location of the second comma use the Right() function to grab all characters to the right of the second comma. Since Right() needs to know how many characters from the end rather than from the beginning, you will need to subtract the location of the comma from the Length() of the string. This effectively splits the string at the comma.
Right(
Parameters!Street.Value
, Parameters!Street.Value.ToString().Length - (
InStr(InStr(Parameters!Street.Value, ",") + 1, Parameters!Street.Value, ","))
)
)
If you have more than 2 commas you can grab just the string between the 2nd and 3rd comma by following up with a Left() function that finds the location of the 3rd comma.
Now you can use your IIf() function to return NULL (Nothing) if there is not a 2nd comma. The function at the top shows how this all fits together.
This could be cleaned up by using functions, but the provided code shows you how it can be done.

SQL Select statement until a character

I'm looking to extract all the text up until a '\' (backslash).
The substring is required to remove all proceeding characters (17 in total) and so I would like to return all after the 17th until it comes across a backslash.
I've tried using charindex but it doesn't seem to stop at the \ it returns characters afterward. My code is as follows
SELECT path, substring(path,17, CHARINDEX('\',Path)+ LEN(Path)) As Data
FROM [Table].[dbo].[Projects]
WHERE Path like '\ENQ%\' AND
Deleted = '0'
Example
The below screen shot shows the basic query and result i.e the whole string
I then use substring to remove the first X characters as there will always be the same amount of proceeding characters
But what Im actually after is (based on the above result) the "Testing 1" "Testing 2" and "Testing ABC" section
The substring is required to remove all proceeding characters (17 in total) and so I would like to return all after the 17th until it comes across a backslash.
select
substring(path,17,CHARINDEX('\',Path)-17)
from
table
To overcome Invalid length parameter passed to the LEFT or SUBSTRING function error, you can use CASE
select
substring(path,17,
CASE when CHARINDEX('\',Path,17)>0
Then CHARINDEX('\',Path)-17)
else VA end
)
from
table

Remove lines in text files that have "." Batch File

I have a text file that looks like this.
/var/www/xxx/html/TEST/VIDEOS/video3.mp4
/var/www/xxx/html/TEST/video_folder_1/cideo.mp4
/var/www/xxx/TEST/video_folder_1/sadasd
/var/www/xxx/html/TEST/video_folder_2/asdsadasdasdsadsadsadsadas
/var/www/xxx/html/TEST/video_folder_2/cideo2.mp4
/var/www/xxx/html/TEST/video_folder_2/sadsada
I would like it to look like this:
/var/www/xxx/TEST/video_folder_1/sadasd
/var/www/xxx/html/TEST/video_folder_2/asdsadasdasdsadsadsadsadas
/var/www/xxx/html/TEST/video_folder_2/sadsada
The idea would be to remove any line that have an extension. I.E mp4 in this case.
So I guess it would look for 4 character in at the end of the line and see if it has a "."
If it does, remove the line.
In batch you should be able to do this in many ways:
findstr /V /L "." theFile.txt
As Aacini suggests, which checks if the line contains a . and works fine when tested.
If you want to user regular expression
findstr /V /R "\....$" theFile.txt
Which does exactly what you asked for by checking if a line ends with a .***
Lastly what I would recommend is using this:
findstr /V /R "\.[a-z0-9]*$" theFile.txt
which checks if the line ends with any sort of extension, thus including possible 4-letter extensions.
I have tested each of these and they all work fine.
I really don't know why Serenity insists you use VBscript which is no doubt a great language but for a simple thing like this batch is so much more simpler.
This is a vbs regex replace program. Far more powerful than FindStr. It works globably so you can target line endings.
This is help from a similar line based, not global, program of mine. The point is to show sample RegEx expressions.
To extract all section headers, ie, lines without an equal sign
filter filter iv "=" < "%systemroot%\win.ini"
To extract all section headers starting with a lower case letter
filter filter n "\[[a-z].+" < "%systemroot%\win.ini"
This shows the caret escaping an opening bracket for CMD.EXE and the backslash escaping the opening bracket for the RegEx engine
filter filter n "\^(" < "%systemroot%\win.ini"
This shows searching for a quote character
filter filter n "\x22" < "%systemroot%\win.ini"
Use $1, $2, $..., $n to specify sub matches in the replace string
filter replace i "=" "No equal sign" < "%systemroot%\win.ini"
This searches for text within square brackets and replaces the line with cat followed by the text within brackets
Filter replace i "^\[^(.*^)\]" "cat$1" < %windir%\win.ini
This searches for any text and prints from the 11th character to the end of the line.
Filter replace i "^.{10}^(.*^)$" "$1" < %windir%\win.ini
This searches a CSV file and prints the second and fourth field
Filter replace i "^.+,^(.+^),.+,^(.+^)$" "$1,$2" < csv.txt
The script.
On Error Resume Next
Set ShellApp = CreateObject("Shell.Application")
ReportErrors "Creating Shell.App"
set WshShell = WScript.CreateObject("WScript.Shell")
ReportErrors "Creating Wscript.Shell"
Set objArgs = WScript.Arguments
ReportErrors "Creating Wscript.Arg"
Set regEx = New RegExp
ReportErrors "Creating RegEx"
Set fso = CreateObject("Scripting.FileSystemObject")
ReportErrors "Creating FSO"
If objArgs.Count = 0 then
wscript.echo "No parameters", 16, "Serenity's ReplaceRegExp"
ReportErrors "Help"
ElseIf objArgs.Count = 1 then
wscript.echo "Only one parameter", 16, "Serenity's ReplaceRegExp"
ReportErrors "Help"
ElseIf objArgs.Count = 2 then
Set srcfile = fso.GetFile(objArgs(0))
ReportErrors "srcFile"
If err.number = 0 then Set TS = srcFile.OpenAsTextStream(1, 0)
If err.number <> 0 then
wscript.echo err.description & " " & srcFile.path, 48, "Serenity's Search"
err.clear
else
ReportErrors "TS" & " " & srcFile.path
Src=ts.readall
If err.number = 62 then
err.clear
else
ReportErrors "ReadTS" & " " & srcFile.path
regEx.Pattern = objArgs(1)
regEx.IgnoreCase = True
regEx.Global = True
If regEx.Test(Src) = True then
wscript.echo "Found in " & srcfile.path, 64, "Serenity's Search"
End If
End If
End If
ReportErrors "Check OK" & " " & srcFile.path
Elseif objArgs.count = 3 then
Set srcfile = fso.GetFile(objArgs(0))
ReportErrors "srcFile"
If err.number = 0 then Set TS = srcFile.OpenAsTextStream(1, 0)
If err.number <> 0 then
wscript.echo err.description & " " & srcFile.path, 48, "Serenity's Search"
err.clear
else
ReportErrors "TS" & " " & srcFile.path
Src=ts.readall
If err.number = 62 then
err.clear
else
ReportErrors "ReadTS" & " " & srcFile.path
regEx.Pattern = objArgs(1)
regEx.IgnoreCase = True
regEx.Global = True
NewSrc= regEx.Replace(Src, objArgs(2))
If NewSrc<>Src then
wscript.echo "Replacement made in " & srcfile.path, 64, "Serenity's Search"
TS.close
Set TS = srcFile.OpenAsTextStream(2, 0)
ts.write newsrc
ReportErrors "Writing file"
End If
End If
End If
ReportErrors "Check OK" & " " & srcFile.path
Else
wscript.echo "Too many parameters", 16, "Serenity's ReplaceRegExp"
ReportErrors "Help"
ReportErrors "All Others"
End If
Sub ReportErrors(strModuleName)
If err.number<>0 then wscript.echo "An unexpected error occurred. This dialog provides details on the error." & vbCRLF & vbCRLF & "Error Details " & vbCRLF & vbCRLF & "Script Name" & vbTab & Wscript.ScriptFullName & vbCRLF & "Module" & vbtab & vbTab & strModuleName & vbCRLF & "Error Number" & vbTab & err.number & vbCRLF & "Description" & vbTab & err.description, vbCritical + vbOKOnly, "Something unexpected"
Err.clear
End Sub
RegEx Reference
Regular Expressions Reference
From the Windows Vista SDK, VBScript Language Reference © Microsoft Corp 2006
Character Description
\ Marks the next character as either a special character or a literal. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\" matches "\" and "\(" matches "(".
^ Matches the beginning of input.
$ Matches the end of input.
* Matches the preceding character zero or more times. For example, "zo*" matches either "z" or "zoo".
+ Matches the preceding character one or more times. For example, "zo+" matches "zoo" but not "z".
? Matches the preceding character zero or one time. For example, "a?ve?" matches the "ve" in "never".
. Matches any single character except a newline character.
(pattern) Matches pattern and remembers the match. The matched substring can be retrieved from the resulting Matches collection, using Item [0]...[n]. To match parentheses characters ( ), use "\(" or "\)".
x|y Matches either x or y. For example, "z|wood" matches "z" or "wood". "(z|w)oo" matches "zoo" or "wood".
{n} n is a nonnegative integer. Matches exactly n times. For example, "o{2}" does not match the "o" in "Bob," but matches the first two o's in "foooood".
{n,} n is a nonnegative integer. Matches at least n times. For example, "o{2,}" does not match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".
{ n , m } m and n are nonnegative integers. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to "o?".
[ xyz ] A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".
[^ xyz ] A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".
[ a-z ] A range of characters. Matches any character in the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z".
[^ m-z ] A negative range characters. Matches any character not in the specified range. For example, "[m-z]" matches any character not in the range "m" through "z".
\b Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".
\B Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".
\d Matches a digit character. Equivalent to [0-9].
\D Matches a non-digit character. Equivalent to [^0-9].
\f Matches a form-feed character.
\n Matches a newline character.
\r Matches a carriage return character.
\s Matches any white space including space, tab, form-feed, etc. Equivalent to "[ \f\n\r\t\v]".
\S Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".
\t Matches a tab character.
\v Matches a vertical tab character.
\w Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".
\W Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".
\num Matches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.
\ n Matches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the equivalent of "\001" & "1". Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.
\xn Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". Allows ASCII codes to be used in regular expressions.
Go to top of page
If you want to eliminate lines with "." from the output created in your previous question, then a much simpler solution is to insert a test in that code:
#echo off
setlocal EnableDelayedExpansion
(for /F "delims=" %%a in (test.txt) do (
set "line=%%a"
if "!line:~0,1!" equ "/" (
set "header=%%a"
) else (
if "!line:.=!" equ "!line!" echo !header:~0,-1!/%%a
)
)) > testnew.txt

How do I set word delimiters?

User's guide chapter 6.1.5 The Word Chunk A word is a string of characters delimited by space, tab, or return characters or enclosed by double quotes. Is it possible to have additional word delimiters?
I have the following code snippet taken from the User's Guide chapter 6.5.1 'When to use arrays', p. 184
on mouseUp
--cycle through each word adding each instance to an array
repeat for each word tWord in field "sample text"
add 1 to tWordCount[tWord]
end repeat
-- combine the array into text
combine tWordCount using return and comma
answer tWordCount
end mouseUp
It counts the number of occurences of each word form in the field "Sample text".
I realize that full stops after words are counted as part of the word with the default setting.
How do I change the settings that a full stop (and, or a comma) is considered a word boundary?
Alternatively you could simply remove the offending characters before processing.
This can be done using either the REPLACE function or the "REPLACETEXT function.
The REPLACETEXT function can use a regular expression matchstring but is slower than the REPLACE function. So here I am using the REPLACE function.
on mouseUp
put field "sample" into twords
--remove all trailing puncuation and quotes
replace "." with "" in twords
replace "," with "" in twords
replace "?" with "" in twords
replace ";" with "" in twords
replace ":" with "" in twords
replace quote with "" in twords
--hyphenated words need to be seperated?
replace "-" with " " in twords
repeat for each word tword in twords
add 1 to twordcount[tword]
end repeat
combine twordcount using return and comma
answer twordcount
end mouseUp
I think you are asking a question about delimiters. Some delimiters are built-in:
spaces for words,
commas for items,
return (CR) for lines.
The ability to create your own custom delimiter property (the itemDelimiter) is a powerful feature of the language, and pertains to "items". You can set this to any single character:
set the itemDelimiter to "C"
answer the number of items in "XXCXXCXX" --call this string "theText"
The result will be "3"
As others have pointed out, the method of replacing one string for another allows formidable control over custom parsing of text:
replace "C" with space in theText
yields "XX XX XX"
Craig Newman
As the User's guide says in chapter 6.1.5 The Word Chunk A word is a string of characters delimited by space, tab, or return characters or enclosed by double quotes.
There is itemDelimiter but not wordDelimiter.
So punctuation as to be removed first before adding the word to the word count array.
This may be done with a function effectiveWord.
function effectiveWord aWord
put last char of aWord into it
if it is "." then delete last char of aWord
if it is "," then delete last char of aWord
if it is ":" then delete last char of aWord
if it is ";" then delete last char of aWord
return aWord
end effectiveWord
on mouseUp
--cycle through each word adding each instance to an array
repeat for each word tWord in field "Sample text"
add 1 to tWordCount[effectiveWord(tWord)]
end repeat
-- combine the array into text
combine tWordCount using return and comma
answer tWordCount
end mouseUp

Resources