Why does the IndexOf() method give me an error when the documentation states that it should work? - string

I'm looking to parse out a specific blob of text to a different file. However, I'm having an issue with the .IndexOf() method when trying to define my endIndex.
The string I'm looking for will start with the phrase:
/* original invocation */
It will then list the original invocation contained in the same type of comment:
/*
~~~
/"
I just finished "Learn PowerShell in a Month of Lunches" so I'm still fresh. But, my thought process is this:
Get the starting line number of "/* original invocation */" and use that as a startIndex
Get where-ever the last "*/" is after that and make that line the endIndex.
Use those values to parse the blob of text I'm after to a file. I assume I could use something like SubString() and pipe it to Out-File.
Here is my script so far:
$file = Get-Content ("file/to/be/read")
$searchString = "/* original invocation */"
$startIndex = $file.IndexOf($searchString)
# Lets say the value of $startIndex is 18676
$endIndex = $file.IndexOf('\*/',$startIndex)
# The error. int IndexOf(string value, int startIndex)
# MethodException: Cannot find an overload for "IndexOf" and the argument count: "2".
I'm pretty lost. If this is easier in Python, please let me know.
The issue I have is when trying to define the endIndex. I get the following error:
MethodException: Cannot find an overload for "IndexOf" and the argument count: "2".
I looked at the overloads for IndexOf and I seem to be matching it, so I must really be missing something. It doesn't seem to matter how many arguements I put in. I also noticed if I just do a random string, I get results of "-1".

Related

Recursively extract contents of (nested) parentheses in string, replace selected content(s) down to a single (char+int), read again and repeat

This is my first post so please comment down if you need further clarification, Say we take in a string such as:
((((a).(5)).((a)*)).((b)*))*
and through the process, we perhaps count++ the amount of '(' read and count-- the amount of ')' read until we come across our first char or variable (we can consider other operators such as '.' or '|' or '*') that is the left and innermost content such that a is replaced so that our string now reads:
(((R1.(5)).((a)*)).((b)*))*
We must consider when a is selected, we also include its parenthesis as well but only consider the string that is read (perhaps store it in or as a vector, pointer, object, etc.), the same applies for when 5 which results in:
(((R1.R2).((a)*)).((b)*))*
at this moment we perhaps find now that the innermost content found is string (R1.R2) and
this results the string to be converted into R3 and having the string as:
((R3.((a)*)).((b)*))*
We continue the iteration for a to be read too.
((R3.(R4*)).((b)*))*
If a star * is read, we can consider extracting that content with R4 to be replaced as R5
((R3.R5).((b)*))*
Our next iteration follows:
((R3.R5).(R6*))*
((R3.R5).R7)*
(R8.R7)*
R9*
and finally as our final result,
R10
And we end.
I've already tried a variety of algorithms from several sources for hours yet I'm still stuck and puzzled at the same spot and I may not be thinking this through very properly as I had hoped.
The only closest that was modified was this:
https://www.geeksforgeeks.org/extract-substrings-between-any-pair-of-delimiters/
but I'm still puzzled about what must be properly implemented.
How would you make this possible? Any solutions or a straight post of your code could surely help me understand this process.

python f-string include all numbers except 0 while making a file list

I want to make a list of files with extend() while ignoring any file name ending with 0 as in _file0.h5. I have this line for concatenating all the files into a list
data_files_0.extend(sorted(glob(f"{directory}*_file{filenum}.h5") ) )
I am trying to learn how to implement regex here and I tried
filenum = re.match(r'[^0]')
by putting it above the previous line which gives the error
TypeError: match() missing 1 required positional argument: 'string'
I am pretty confused here and all the examples of f-string with regex don't help me at all.
re.match won't automatically look for strings containing that pattern - you have to provide the string to it - that's the cause of the missing argument error.
Example - re.match('[^0]', "abc0123") will check for matches in the string "abc0123" according to the pattern '[^0]'.
[^0] is likely wrong pattern here since this matches any and every character at any position in the string except for a 0. You might want to use something like .*0\.h5, which matches any string ending with '0.h5'. You can also check out regexr.com, which is a very helpful site for figuring out how regex patterns work in general.
For the other part of the problem - finding the files - you might have to just get all the filenames first, then check which ones end with 0 or not:
all_files = glob(f"{directory}*_file*.h5")
for f in all_files:
if not re.match('.*0\.h5', f):
data_files_0.append(f)

How to test if a string variable in Robot Framework is empty?

How to test if a string variable in Robot Framework is empty?
My first naïve attempt looked like this:
Run Keyword If ${myVar}!=${EMPTY}
but it failed:
Evaluating expression '!=' failed: SyntaxError: unexpected EOF while parsing (, line 1)
I then found this issue at Github but it didn't suggest a solution, just that the error message was unclear. An alternative solution was presented here:
${length}= Get Length ${Portfolio_ste}
Run Keyword If ${length} Go To Edit Portfolio
but is this really the best practice?
(The context is that I use a variable argument list and if a certain variable contains a value something should be done, otherwise just ignore it)
The expression needs to be a valid python expression after variable substitution. Assuming for the moment that myVar might be something like the number 42, your expression would end up looking like this after substitution:
Run Keyword if 42!=
When comparing against the empty string you need to add quotes to guarantee that the expression is a proper python expression after substitution. For example:
Run Keyword If "${myVar}"!="${EMPTY}"
Try Get Variable Value. It solved my problem.

need guidance with basic function creation in MATLAB

I have to write a MATLAB function with the following description:
function counts = letterStatistics(filename, allowedChar, N)
This function is supposed to open a text file specified by filename and read its entire contents. The contents will be parsed such that any character that isn’t in allowedChar is removed. Finally it will return a count of all N-symbol combinations in the parsed text. This function should be stored in a file name “letterStatistics.m” and I made a list of some commands and things of how the function should be organized according to my professors' lecture notes:
Begin the function by setting the default value of N to 1 in case:
a. The user specifies a 0 or negative value of N.
b. The user doesn’t pass the argument N into the function, i.e., counts = letterStatistics(filename, allowedChar)
Using the fopen function, open the file filename for reading in text mode.
Using the function fscanf, read in all the contents of the opened file into a string variable.
I know there exists a MATLAB function to turn all letters in a string to lower case. Since my analysis will disregard case, I have to use this function on the string of text.
Parse this string variable as follows (use logical indexing or regular expressions – do not use for loops):
a. We want to remove all newline characters without this occurring:
e.g.
In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.
In my younger and more vulnerableyears my father gave me some advicethat I’ve been turning over in my mindever since.
Replace all newline characters (special character \n) with a single space: ' '.
b. We will treat hyphenated words as two separate words, hence do the same for hyphens '-'.
c. Remove any character that is not in allowedChar. Hint: use regexprep with an empty string '' as an argument for replace.
d. Any sequence of two or more blank spaces should be replaced by a single blank space.
Use the provided permsRep function, to create a matrix of all possible N-symbol combinations of the symbols in allowedChar.
Using the strfind function, count all the N-symbol combinations in the parsed text into an array counts. Do not loop through each character in your parsed text as you would in a C program.
Close the opened file using fclose.
HERE IS MY QUESTION: so as you can see i have made this list of what the function is, what it should do, and using which commands (fclose etc.). the trouble is that I'm aware that closing the file involves use of 'fclose' but other than that I'm not sure how to execute #8. Same goes for the whole function creation. I have a vague idea of how to create a function using what commands but I'm unable to produce the actual code.. how should I begin? Any guidance/hints would seriously be appreciated because I'm having programmers' block and am unable to start!
I think that you are new to matlab, so the documentation may be complicated. The root of the problem is the basic understanding of file I/O (input/output) I guess. So the thing is that when you open the file using fopen, matlab returns a pointer to that file, which is generally called a file ID. When you call fclose you want matlab to understand that you want to close that file. So what you have to do is to use fclose with the correct file ID.
fid = open('test.txt');
fprintf(fid,'This is a test.\n');
fclose(fid);
fid = 0; % Optional, this will make it clear that the file is not open,
% but it is not necessary since matlab will send a not open message anyway
Regarding the function creation the syntax is something like this:
function out = myFcn(x,y)
z = x*y;
fprintf('z=%.0f\n',z); % Print value of z in the command window
out = z>0;
This is a function that checks if two numbers are positive and returns true they are. If not it returns false. This may not be the best way to do this test, but it works as example I guess.
Please comment if this is not what you want to know.

Same for loop, giving out two different results using .write()

this is my first time asking a question so let me know if I am doing something wrong (post wise)
I am trying to create a function that writes into a .txt but i seem to get two very different results between calling it from within a module, and writing the same loop in the shell directly. The code is as follows:
def function(para1, para2): #para1 is a string that i am searching for within para2. para2 is a list of strings
with open("str" + para1 +".txt", 'a'. encoding = 'utf-8') as file:
#opens a file with certain naming convention
n = 0
for word in para2:
if word == para1:
file.write(para2[n-1]+'\n')
print(para2[n-1]) #intentionally included as part of debugging
n+=1
function("targetstr". targettext)
#target str is the phrase I am looking for, targettext is the tokenized text I am
#looking through. this is in the form of a list of strings, that is the output of
#another function, and has already been 'declared' as a variable
when I define this function in the shell, I get the correct words appearing. However, when i call this same function through a module(in the shell), nothing appears in the shell, and the text file shows a bunch of numbers (eg: 's93161), and no new lines.
I have even gone to the extent of including a print statement right after declaration of the function in the module, and commented everything but the print statement, and yet nothing appears in the shell when I call it. However, the numbers still appear in the text file.
I am guessing that there is a problem with how I have defined the parameters or how i cam inputting the parameters when I call the function.
As a reference, here is the desired output:
‘She
Ashley
there
Kitty
Coates
‘Let
let
that
PS: Sorry if this is not very clear as I have very limited knowledge on speaking python
I have found the solution to issue. Turns out that I need to close the shell and restart everything before the compiler recognizes the changes made to the function in the module. Thanks to those who took a look at the issue, and those who tried to help.

Resources