Python parsing error message functions - parsing

The code below was created by me with the help of many SO veterans:
The code takes an entered math expression and splits it into operators and operands for later use. I have created two functions, the parsing function that splits, and the error function. I am having problems with the error function because it won't display my error messages and I feel the function is being ignored when the code runs. An error should print if an expression such as this is entered: 3//3+4,etc. where there are two operators together, or there are more than two operators in the expression overall, but the error messages dont print. My code is below:
def errors():
numExtrapolation,opExtrapolation=parse(expression)
if (len(numExtrapolation) == 3) and (len(opExtrapolation) !=2):
print("Bad1")
if (len(numExtrapolation) ==2) and (len(opExtrapolation) !=1):
print("Bad2")
def parse(expression):
operators= set("*/+-")
opExtrapolate= []
numExtrapolate= []
buff=[]
for i in expression:
if i in operators:
numExtrapolate.append(''.join(buff))
buff= []
opExtrapolate.append(i)
opExtrapolation=opExtrapolate
else:
buff.append(i)
numExtrapolate.append(''.join(buff))
numExtrapolation=numExtrapolate
#just some debugging print statements
print(numExtrapolation)
print("z:", len(opExtrapolation))
return numExtrapolation, opExtrapolation
errors()
Any help would be appreciated. Please don't introduce new code that is any more advanced than the code already here. I am looking for a solution to my problem... not large new code segments. Thanks.

The errors() function is called after parse() returns because it appears inside the body of parse(). Hopefully that is a typo.
For this particular input, numExtrapolate is appended with an empty buffer because there is no operand between / and /. That makes its length 4 and your check for Bad1 fails. So put a check like this
if buff:
numExtrapolate.append(''.join(buff))

Related

How to detect if a field contains a character in Lua

I'm trying to modify an existing lua script that cleans up subtitle data in Aegisub.
I want to add the ability to delete lines that contain the symbol "♪"
Here is the code I want to modify:
-- delete commented or empty lines
function noemptycom(subs,sel)
progress("Deleting commented/empty lines")
noecom_sel={}
for s=#sel,1,-1 do
line=subs[sel[s]]
if line.comment or line.text=="" then
for z,i in ipairs(noecom_sel) do noecom_sel[z]=i-1 end
subs.delete(sel[s])
else
table.insert(noecom_sel,sel[s])
end
end
return noecom_sel
end
I really have no idea what I'm doing here, but I know a little SQL and LUA apparently uses the IN keyword as well, so I tried modifying the IF line to this
if line.text in (♪) then
Needless to say, it didn't work. Is there a simple way to do this in LUA? I've seen some threads about the string.match() & string.find() functions, but I wouldn't know where to start trying to put that code together. What's the easiest way for someone with zero knowledge of Lua?
in is only used in the generic for loop. Your if line.text in (♪) then is no valid Lua syntax.
Something like
if line.comment or line.text == "" or line.text:find("\u{266A}") then
Should work.
In Lua every string have the string functions as methods attached.
So use gsub() on your string variable in loop like...
('Text with ♪ sign in text'):gsub('(♪)','note')
...thats replace the sign and output is...
Text with note sign in text
...instead of replacing it with 'note' an empty '' deletes it.
gsub() is returning 2 values.
First: The string with or without changes
Second: A number that tells how often the pattern matches
So second return value can be used for conditions or success.
( 0 stands for "pattern not found" )
So lets check above with...
local str,rc=('Text with strange ♪ sign in text'):gsub('(♪)','notation')
if rc~=0 then
print('Replaced ',rc,'times, changed to: ',str)
end
-- output
-- Replaced 1 times, changed to: Text with strange notation sign in text
And finally only detect, no change made...
local str,rc=('Text with strange ♪ sign in text'):gsub('(♪)','%1')
if rc~=0 then
print('Found ',rc,'times, Text is: ',str)
end
-- output is...
-- Found 1 times, Text is: Text with strange ♪ sign in text
The %1 holds what '(♪)' found.
So ♪ is replaced with ♪.
And only rc is used as a condition for further handling.

How to determine if sysdig field exists or handle error if it doesn't

I'm using Sysdig to capture some events and have a small chisel (LUA script) to capture and format the events as necessary. On the on_init() I'm requesting fields like so :
f_field = chisel.request_field("<field>")
My question is how can I check if a field exists before requesting it? I'm going to use a new field only just released on 0.24.1 but ideally I'd like my chisel to continue to work on older versions of sysdig without this field. I've tried wrapping the call to chisel.request_field in a pcall() like so :
ok, f_field = pcall(chisel.request_field("<field>"))
and even implementing my own "get_field" function :
function get_field(field)
ok, f = pcall(chisel.request_field(field))
if ok then return f else return nil end
end
f_field = get_field("<field>")
if f_field ~= nil then
-- do something
end
but the error ("chisel requesting nonexistent field <field>") persists.
I can't see a way to check if a field exists but I can't seem to handle the error either. I really don't want multiple versions of my scripts if possible.
Thanks
Steve H
You're almost there. Your issue is in how you're using pcall. Pcall takes a function value and any arguments you wish to call that function with. In your example you're passing the result of the request_field function call to pcall. Try this instead..
ok, f = pcall(chisel.request_field, "field")
pcall will call the chisel method with your args in a protected mode and catch any subsequent errors.

Embedding mRuby: retrieving mrb_parser_message after parse error

I'm trying to embed mRuby in a Max MSP object. One of the first things I want to setup is error logging in the Max IDE console window. To that effect, after I parse the code ( stored in a C string ) with mrb_parse_string, I expect errors to be available in the parser's error_buffer array, but the structures in this array are always empty ( lineno and column set to 0 and message set to NULL ) even when there is an error.
Is there a special way to set up the parser before parsing the code so it fills its error_buffer array properly in case an error occurs ? I've looked into the mirb source, but it doesn't look like it. I'm lost. Here is the code I'm using, taken from a small C program I'm using as test:
mrb_state *mrb;
char *code;
struct mrb_parser_state *parser;
parser = mrb_parse_string(mrb, code, mrbc_context_new(mrb));
if (parser->nerr > 0) {
for(i = 0; i < parser->nerr; i++) {
printf("line %d:%d: %s\n", parser->error_buffer[i].lineno,
parser->error_buffer[i].column,
parser->error_buffer[i].message);
}
return -1;
}
When passed the following faulty ruby code:
[1,1,1]]
the previous code outputs :
line 1:8: syntax error, unexpected ']', expecting $end
line 0:0: (null)
I don't know where the first line comes from, since I compiled mRuby with MRB_DISABLE_STDIO defined and as line 14 and following in mrbconf.md suggests, but it is accurate.
The second line is the actual output from my code and shows that the returned mrb_parser_state structure's error_buffer is empty, which is surprising since the parser did see an error.
Sorry totally misunderstood your question.
So you want to:
capture script's syntax errors instead of printing.
make MRB_DISABLE_STDIO work.
For 1st issue
struct mrb_parser_state *parser;
parser = mrb_parse_string(mrb, code, mrbc_context_new(mrb));
should be replaced with:
struct mrbc_context *cxt;
struct mrb_parser_state *parser;
cxt = mrbc_context_new(mrb);
cxt->capture_errors = TRUE;
parser = mrb_parse_string(mrb, code, cxt);
like what mirb does.
For 2nd issue I don't know your build_config.rb so I can't say much about it.
Some notes to make things accurate:
MRB_DISABLE_STDIO is a compile flag for building mruby so you need to pass it in build_config.rb like:
cc.defines << %w(MRB_DISABLE_STDIO)
(see build_config_ArduinoDue.rb)
line 1:8: syntax error, unexpected ']', expecting $end
is the parsing error of mruby parser([1,1,1]] must be [1,1,1]).
And 1:8 means 8th column of 1st line (which points to unnecessary ]) so it seems like your C code is working correctly to me.
(For a reference your code's compilation error in CRuby:
https://wandbox.org/permlink/KRIlW2956TnS6puD )
prog.rb:1: syntax error, unexpected ']', expecting end-of-input
[1,1,1]]
^

action script 2.0 simple string comparing with conditional statement

So I have this crazy problem with comparing 2 strings in ActionScript 2.0
I have a global variable which holds some text (usually it is "statistic") from xml feed
_root.var_name = fields.firstChild.attributes.value;
when I trace() it it gives me the expected message
trace(_root.var_name); // echoes "statistik"
and when I try to use it in conditional statement the rest of code is not being executed because comparing :
if(_root.overskrift == "statistik"){
//do stuff
}
returns false!
I tried also with:
if(_root.overskrift.equals("statistik"))
but with the same result.
Any input will be appreciated.
Years later but on a legacy project I had the same problem and the solution was in a comment to this unanswered question. So let's make it an anwer:
Where var a:String="some harmless but in my case long string" and var b:String="some harmless but in my case long string" but (a==b) -> false the following works just fine: (a.indexOf(b)>=0) -> true. If the String were not found indexOf would give -1. Why the actual string comparison fails I coudn't figure out either. AS2 is ancient and almost obsolete...

what is the difference between chunk.write and chunk.render

I saw this,
chunk = chunk.write("<li>").render(bodies.block, context.push(items[i])).write("</li>\n");
Before seeing this code, i thought, render as something similar to flush, and write as something similar to "write in buffer", naturally leading to a code like below.
for loop
chunk.write("something")
end for loop
chunck.render();
But, as you can see in the first code, render is coming in between the writes. Can somebody explain the difference between these two functions.
#JAiro:
After reading your answer i tried the below code:
temaplate: You have {render} {write}
data:
{
"name": "Mick",
"render": function(c,ct,b){
chunk.render("Rendered {~n}");
},
write:function(c,ct,b){
chunk.write("Written {~n}")
}
}
Expected output:
you have Rendered
Written {~n}
Please note the {~n} after the word "Rendered" is interpreted but the {~n} after "Written" is not interpreted.
But the actual output is not same as the expected output.
Could you post a jsfiddle, that will help me in understanding.
The actual output is an empty string, which also indicate that there could be an error in the code.
The chunk.write method writes strings directly to the buffer.
On the other hand, chunk.render resolves variables contained in its argument and then writes the resulting string to the buffer.
You don't have to override the write and render function in the context.
Let me show you how it works.
Template
Hello {name}!, how are you?
Dust compiles the template to convert them in javascript. After compiling that template you are going to obtain something like:
return chk.write("Hello ").reference(ctx.get("name"), ctx, "h").write("! how are you?");
As you can see for "Hello" and "how are you?", dust uses chunk.write because it knows what it should print. However, dust doesn't know the value of {name} until it gets the context (JSON).
For that reason, it uses chunk.reference, because it will have to resolve the value of the variable name in the future. Dust is going to obtain the value of name from the JSON data.
You can read more about dust.js here:
http://linkedin.github.com/dustjs/wiki
And you can see working examples and try yours here:
http://linkedin.github.com/dustjs/test/test.html

Resources