I don't understand the error traceback gives me - string

I'm currently trying to understand Pyth. I know Python quite well, but I don't get Pyth sometimes.
My code:
DhNKlNFzrKZaY#Nz;Y;hQ
It's just a basic script for reversing string, and traceback gives me ValueError,
ValueError: malformed node or string: <_ast.Name object at 0x7ff2fde45c18>
Despite my Python knowledge I have no idea what does this error mean. Can you show me where is this error coming from?

I assume you are getting an error like this one here:
Traceback (most recent call last):
File "pyth.py", line 771, in <module>
File "<string>", line 3, in <module>
File "/app/macros.py", line 691, in eval_input
File "/app/.heroku/python/lib/python3.4/ast.py", line 84, in literal_eval
File "/app/.heroku/python/lib/python3.4/ast.py", line 83, in _convert
ValueError: malformed node or string: <_ast.Name object at 0x7fac26eb2b70>
First off, you use z and Q inconsistently. With your current code, input should have been taken like this instead:
"abcd"
abcd
When Q is used in a Pyth program, z implicitly jumps to the next line of input, it just skips whatever has been inputted before using Q. Instead, just use:
DhNKlNFzrKZaY#Nz;Y;hz
And the errors should go away.
I am not sure why you would want to perform string reversal that way, though. I use _z if the input is not quoted and _ alone otherwise, since Q is implicit at the end of any Pyth program.

Related

Hello everyone, I'm currently doing a school project and I'm using python, But I keep running into this error "string argument w/o encoding"

So basically on this block:
if len(args) > 0:
text = u''join(map(bytes, args))
else:
text = sys.stdin.read().strip()
I get an error saying:
Traceback (most recent call last):
File "/home/pi/test.py", line 198, in <module>
text = u''.str.encode()
AttributeError: 'str' object has no attribute 'str'.
If anyone can help me please do. Thank u in advance :)
First, you lost the . between u'' and join in your posted code.
Second, from your posted error log, we can know there is an another syntax error for text = u''.str.encode() in your /home/pi/test.py file. It should be text = u''.encode().

Does IPOPT not support Pyomo's quicksum function? ValueError for unsupported expression type

I am trying to solve a nonlinear feasibility problem on Pyomo using ipopt solver. The problem has 2 RangeSet declarations of a combined size 28, 4 Param declarations of a combined size 68, and 5 Var declarations of a combined size 88. There's also 90 constraint declarations (2 redundant) of which some are linear and some are non-linear.
This model is supposed to be simulating a chemical system. Calling model.pprint() gives all the information that it must: all the declarations as stated above. This is the error output I received:
Traceback (most recent call last):
File "sample.py", line 420, in <module>
main()
File "sample.py", line 416, in main
org_n, aq_n, org, aq = _equilibrium_solver(inputfile, T, org_n, aq_n, org, aq)
File "sample.py", line 370, in _equilibrium_solver
opt.solve(model, tee=True)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/opt/base/solvers.py", line 569, in solve
self._presolve(*args, **kwds)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/opt/solver/shellcmd.py", line 200, in _presolve
OptSolver._presolve(self, *args, **kwds)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/opt/base/solvers.py", line 669, in _presolve
**kwds)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/opt/base/solvers.py", line 740, in _convert_problem
**kwds)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/opt/base/convert.py", line 105, in convert_problem
problem_files, symbol_map = converter.apply(*tmp, **tmpkw)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/solvers/plugins/converter/model.py", line 191, in apply
io_options=io_options)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/core/base/block.py", line 1716, in write
io_options)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/repn/plugins/ampl/ampl_.py", line 378, in __call__
include_all_variable_bounds=include_all_variable_bounds)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/repn/plugins/ampl/ampl_.py", line 1528, in _print_model_NL
wrapped_repn.repn.nonlinear_expr)
File "$HOME/.local/lib/python3.6/site-packages/pyomo/repn/plugins/ampl/ampl_.py", line 527, in _print_nonlinear_terms_NL
self._print_nonlinear_terms_NL(exp.arg(1))
File "$HOME/.local/lib/python3.6/site-packages/pyomo/repn/plugins/ampl/ampl_.py", line 637, in _print_nonlinear_terms_NL
% (exp_type))
ValueError: Unsupported expression type (<class 'pyomo.core.expr.expr_pyomo5.LinearExpression'>) in _print_nonlinear_terms_NL
I thought it was a fairly simple calculation that shouldn't have any problems, but now I am out of ideas as to what went wrong. I am not sure what it means by that value error it raises. Am I asking it to print some linear expression in nonlinear terms? There is only thing I can think of: I used quicksum twice, which uses the linear_expression object. Should I replace it with some other sum expression like summation (not sure if summation uses the same object)?
Edit:
I traced the error back to this specific constraint. The constraint gives the relationship between mole fractions and moles.
def x2n_org(m,i):
return model.org[i]*sum_product(model.org_n) == model.org_n[i]
model.xton_org = Constraint(model.nc, rule=x2n_org)
Somehow, sum_product or Summation are the reason for the raised ValueError. It would be nice if someone can see what is wrong with the expression.
If I disable this constraint, the solver returns a different error:
ValueError: Cannot load a SolverResults object with bad status: error
However, this error at least tells me that the solver is trying to solve the model even though it couldn't find a solution.
I solved it by reformulating the constraint. Basically just rearranged the terms to have the sum_product on one side and the two variables (model.org[i] and model.org_n[i]) on the other side:
def x2n_org(m,i):
return sum_product(model.org_n) == model.org_n[i]/model.org[i]
model.xton_org = Constraint(model.nc, rule=x2n_org)
Now IPOPT says the problem failed the restoration phase, but that's a different problem. So this question can be marked as solved.

IndexError: Constraint 'restr1': Cannot initialize multiple indices of a constraint with a single expression

Please I need helping hands to resolve the above error I posted as my title. I am new to pyomo. I was recently following this link:
https://github.com/amianAA/ALNS. In the MadridALNS.py, everything works perfectly up to the where the constraints are created:
#2 // arrival flow to each destination "wd" equal to demand of the destination origin pair "w"
def resd1_rule(model,w):
wo=model.tabla[w,'wo']
expr=0
for l in model.L:
if model.b[wo,l]==1:
expr += model.fo[w,l]
if expr!=0:
return (expr + model.h[w]==model.tabla[w,'g']*model.factorg)
else:
return Constraint.Skip
model.restr1 = Constraint(model.W,expr=resd1_rule)
This is the error i get whenever i run the code:
ERROR: Constructing component 'restr1' from data=None failed:
IndexError: Constraint 'restr1': Cannot initialize multiple indices of
a constraint with a single expression
Traceback (most recent call last):
File "ALNS.py", line 16, in <module>
instance = model.create_instance('madridALNS.dat')
File "/usr/local/lib/python3.5/dist-packages/pyomo/core/base/PyomoModel.py", line 723, in create_instance
profile_memory=profile_memory )
File "/usr/local/lib/python3.5/dist-packages/pyomo/core/base/PyomoModel.py", line 806, in load
profile_memory=profile_memory)
File "/usr/local/lib/python3.5/dist-packages/pyomo/core/base/PyomoModel.py", line 870, in _load_model_data
self._initialize_component(modeldata, namespaces, component_name, profile_memory)
File "/usr/local/lib/python3.5/dist-packages/pyomo/core/base/PyomoModel.py", line 925, in _initialize_component
declaration.construct(data)
File "/usr/local/lib/python3.5/dist-packages/pyomo/core/base/constraint.py", line 786, in construct
(self.name,) )
IndexError: Constraint 'restr1': Cannot initialize multiple indices of a constraint with a single expression
The files can be found here https://github.com/amianAA/ALNS
The expr= argument is intended for a single non-indexed expression. You should try rule=resid1_rule instead.

PyPDF2, why am I getting an index error? List index out of range

I'm following along in Al Sweigart's book 'Automate the Boring Stuff' and I'm at a loss with an index error I'm getting. I'm working with PyPDF2 tring to open an encrypted PDF document. I know the book is from 2015 so I went to the PyPDF2.PdfFileReader docs to see if I'm missing anything and everything seems to be the same, at least from what I can tell. So I'm not sure what's wrong here.
My Code
import PyPDF2
reader = PyPDF2.PdfFileReader('encrypted.pdf')
reader.isEncrypted # is True
reader.pages[0]
gives:
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
pdfReader.getPage(0)
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/pdf.py", line 1176, in getPage
self._flatten()
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/pdf.py", line 1505, in _flatten
catalog = self.trailer["/Root"].getObject()
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/generic.py", line 516, in __getitem__
return dict.__getitem__(self, key).getObject()
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/generic.py", line 178, in getObject
return self.pdf.getObject(self).getObject()
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/pdf.py", line 1617, in getObject
raise utils.PdfReadError("file has not been decrypted")
PyPDF2.utils.PdfReadError: file has not been decrypted
pdfReader.decrypt('rosebud')
1
pageObj = reader.getPage(0)
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
pageObj = pdfReader.getPage(0)
File "/home/user67/.local/lib/python3.6/site-packages/PyPDF2/pdf.py",line 1177, in getPage
return self.flattenedPages[pageNumber]
IndexError: list index out of range
Before asking my question, I did some searching on Google and found this link with a "proposed fix". However, I'm to new at this to see what the fix is. I can't make heads or tails out of this.
I figured it out. The issue is caused by running 'pdfReader.getPage(0)' before you decrypt the file in the IDLE shell. If you take that line out, or start over without using that line after getting the error it will work as it should.
Same error I got. I was working on console and before decrypt I used reader.getPage(0).
Don't use getPage(#) / pages[#] before decrypt.
use code like below:
reader = PyPDF2.PdfFileReader("file.pdf")
# reader.pages[0] # do not use this before decrypt
if reader.isEncrypted:
reader.decrypt('')
reader.pages[0]

Folium popup gets syntax error message

I'm new to folium. I was able to produce the map I wanted from a dataframe.
df_map = folium.Map(location=[37.750999450684, -97.821998596191], zoom_start=4)
for each in df[0:len(df)].iterrows():
folium.CircleMarker(location=[each[1]["GEO_LAT_0"], each[1]["GEO_LNG_0"]],
radius=5.0, color='#3186cc', fill_color='#3186cc').add_to(df_map)
Map comes out nicely.
Next I wanted to add popups from a third column in data frame, and can't seem to get syntax right. Not clear how I might add these popups from folium documentation. An error message I can't interpret results from this code:
df_map = folium.Map(location=[37.750999450684, -97.821998596191], zoom_start=4)
for each in df[0:len(df)].iterrows():
folium.CircleMarker(location=[each[1]["GEO_LAT_0"], each[1]["GEO_LNG_0"]],
**popup=each[1]["GEO_CITY_0"],**
radius=5.0, color='#3186cc',fill_color='#3186cc').add_to(df_map)
To verify my loop and dataframe were ok, I substituted a
print each[1]["GEO_CITY_0"]
within the for-each loop instead of folium.circlemarker and it worked fine. Something is wrong when I use the popup syntax above.
AttributeError: 'float' object has no attribute 'get_name'
Your help appreciated. Thanks p.s. Full message is:
Traceback (most recent call last):
File "", line 4, in
radius=1, color='#3186cc', fill_color='#3186cc').add_to(df_map)
File "C:\Users\Peter\Anaconda3\lib\site-packages\folium\features.py", line 870, in init
super(CircleMarker, self).init(location=location, popup=popup)
File "C:\Users\Peter\Anaconda3\lib\site-packages\folium\map.py", line 652, in init
self.add_child(popup)
File "C:\Users\Peter\Anaconda3\lib\site-packages\branca\element.py", line 96, in add_child
name = child.get_name()
AttributeError: 'float' object has no attribute 'get_name'
I was under the impression that #pzajonc's syntax of popup=each[1]["GEO_CITY_0"] would work in recent versions (OP's has 0.4.0) of folium.
Here's a github issue that mentions the error and the fix
Regardless, changing it to popup=folium.Popup(each[1]["GEO_CITY_0"]) will resolve the issue.

Resources