Python syntax (running bempp) - python

I tried to test a found code in the site of the bempp library (http://nbviewer.jupyter.org/github/bempp/tutorials/blob/master/notebooks/osrc_burton_miller.ipynb). It is a library implemented in python. I have problems when executing the following istructions :
from scipy.sparse.linalg import gmres
it_count = 0
def iteration_counter(x):
global it_count
it_count += 1
x, info = gmres(discrete_op, rhs_coefficients, callback=iteration_counter)
I got the following error message :
from scipy.sparse.linalg import gmres
>>>
>>> it_count = 0
>>> def iteration_counter(x):
... global it_count
... it_count += 1
...
... x, info = gmres(discrete_op, rhs_coefficients, callback=iteration_counter)
File "<stdin>", line 5
x, info = gmres(discrete_op, rhs_coefficients, callback=iteration_counter)
^
SyntaxError: invalid syntax
Could you help me solving this syntaxe problem please ?

In interactive mode, you need to enter an empty line to terminate multi-line statements. You entered a line with four spaces, which Python interprets as you wanting to continue your function definition.

Related

How to solve OverflowError when generating same random numbers between R and Python using SyncRNG

I am trying to reproduce R codes in Python and I have to generate same random numbers in both languages. I know that using the same seed is not enough to get same random numbers and reading one of the answers on this platform regarding this topic I have discovered that there exists: SyncRNG library, which generates same random numbers between R and Python. Everything looks fine as long as I have discovered that on Python 3.7.3 I can generate via SyncRNG just one number because as soon as you iterate the procedure, for instance, with a for loop you get this error:
OverflowError: Python int too large to convert to C long.
As I was mentioning:
>>> from SyncRNG import SyncRNG
>>> s = SyncRNG(seed=123)
>>> r = s.rand()
>>> r
0.016173338983207965
and as we can see it works. The method ".rand()" generates random numbers between zero and one.
But if I try to iterate:
>>> from SyncRNG import SyncRNG
>>> s = SyncRNG(seed=123)
>>> b = []
>>> for i in range(5):
temp = s.rand()
b.append(temp)
and I get this:
OverflowError: Python int too large to convert to C long
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<pyshell#41>", line 2, in <module>
temp = s.rand()
File "C:\Users\Stefano\AppData\Local\Programs\Python\Python37\lib\site-packages\SyncRNG\__init__.py", line 27, in rand
return self.randi() * 2.3283064365387e-10
File "C:\Users\Stefano\AppData\Local\Programs\Python\Python37\lib\site-packages\SyncRNG\__init__.py", line 22, in randi
tmp = syncrng.rand(self.state)
SystemError: <built-in function rand> returned a result with an error set
So, I humbly ask if someone is able to solve this problem. If I lost old answers about this topic I'm sorry, please link them in the answer section.
Thank you!
This is not a solution, but a workaround. The overflow bug is not reproducible on my system. The workaround:
from SyncRNG import SyncRNG
s = SyncRNG(seed=123)
ct = 0
b = []
while ct < 5:
try:
temp = s.rand()
b.append(temp)
ct += 1
except OverflowError:
pass
Performance will be compromised due to the try/except on each loop.

Take error on wlst console when work with statements or loops

Not able to make loop and statement after it.
Example:
wls:/ADMIN_server/serverConfig> serverRuntime()
Location changed to serverRuntime tree. This is a read-only tree with ServerRuntimeMBean as the root.
For more help, use help(serverRuntime)
wls:/ADMIN_server/serverRuntime> dsMBeans = cmo.getJDBCServiceRuntime().getJDBCDataSourceRuntimeMBeans()
wls:/ADMIN_server/serverRuntime> ds_name = "ADMIN_DB"
wls:/ADMIN_server/serverRuntime> for ds in dsMBeans:
...
Traceback (innermost last):
(no code object) at line 0
File "<console>", line 2
SyntaxError: invalid syntax
Not sure is it need to import something before that options like and for that reason not able to make loop with statement:
import time
import sys
You shouldn't need to import anything specific to have access to the looping mechanism in WLST. For instance, try the following:
slist=range(1,4)
for i in slist: print 'i = ' + str(i);
The result should be:
i = 1
i = 2
i = 3
The syntax of your statements after the for loop are probably causing a problem in your python script OR if you are manually typing the commands in, you need to make sure you put a space after ... for it to interpret the next line like:
wls:/offline> j = 0
wls:/offline> while j<4:
... print 'j = ' + str(j)
... j = j + 1
...
jms 0
jms 1
jms 2
jms 3
Notice it is very important to type in a space character after ... or you will have the invalid syntax error.

SPOJ: runtime error (NZEC)

I tried to do this problem at spoj.com, but I keep getting the error runtime error (NZEC). I code in python. I don't know why. Here is my code,
import sys
def unique(lines, exact=True):
for L in lines:
if L.count('#') != 1 and exact:
return False
if L.count('#') > 1 and not exact:
return False
return True
def resolve(N, lines):
diags = [
[lines[i][i+j] for i in range(max(0, -j), min(N, N-j))]
for j in range(-N+1, N)]
anti_diags = [
[lines[i][N-1 -(i+j)] for i in range(max(0, -j), min(N, N-j))]
for j in range(-N+1, N)]
if unique(lines) and unique(zip(*lines)) and unique(diags, False) and unique(anti_diags, False):
return "YES"
return "NO"
input_file = sys.stdin
output_file = sys.stdout
T = int(raw_input())
for i in range(1, T + 1):
n = int(raw_input())
lines = []
for _ in range(n):
line = raw_input().strip()
lines.append(list(line))
print resolve(n, lines)
It works fine locally with input like:
2
3
..#
#..
.#.
4
.#..
...#
#...
..#.
When I run your code, I get the following:
$ python spoj.py < input
Traceback (most recent call last):
File "spoj.py", line 38, in <module>
print resolve(n, lines)
File "spoj.py", line 15, in resolve
for j in range(-N+1, N)]
IndexError: list index out of range
That's the runtime error you're getting. But the problem is actually in this part:
for _ in range(n):
line = raw_input().strip()
lines.append(list(line))
print resolve(n, lines)
Since the print statement is indented, your program reads a single line, appends to line and calls resolve before reading the following lines. After removing the extra indent, it works fine on my computer.
There's plenty of room to further improve this program, both in style and logic. Let me know if you would like some further advice.
EDIT:
You mentioned in the comments that this indentation problem was a copypasting error. In that case, as sp1r pointed out in his comment, it's most likely that, as a comment in the problem's page suggests, the input used by the online judge is malformed.
In that case, you have to do more rigorous parsing of the input, as it may not be formatted as the example input suggests. That is, instead of:
2
3
..#
#..
.#.
(etc)
you could have something more like:
2 3
..#
#.. .#.
(etc)
That might break your code because it assumes whoever posted the problem was competent enough to make an input that looks like the example. That is not always the case in SPOJ, a lot of the input files is malformed and you can find other cases where malformed input causes otherwise correct programs to fail.
Spoj does not use sys and sys.stdin and sys.stdout. use raw_input() and print.
"I am on windows not on linux. I simply change this line to switch to console modes for tests."
In any language and in any os, these works fine.
#for Python
spoj.py < input.txt > output.txt
#If you are using C/C++, for any EXE file
spoj.exe < input.txt > output.txt
Spoj will nether test this in your computer nor using any UI. They will test your code, in a "console" and it might be a linux / any-OS machine. Use this input / output to Test your code.

Python-RPy - "Error in x$terms : $ operator is invalid for atomic vectors"

I am new in RPy, so excuse me, if my question is trivial. I'm trying to write the top solution from this topic: Screening (multi)collinearity in a regression model in Python, but I get following error:
rpy.RPy_RException: Error in x$terms : $ operator is invalid for atomic vectors
Code I wrote:
from rpy import *
r.set_seed(42)
a=r.rnorm(100)
b=r.rnorm(100)
m=r.model_matrix('~a+b')
What am I doing wrong?
EDIT:
using reply written by agstudy (thank You for help!) I prepared solution working for rpy2
from rpy2 import robjects
rset_seed = robjects.r('set.seed')
fmla = robjects.Formula('~a+b')
model_matrix = robjects.r('model.matrix')
rnorm = robjects.r('rnorm')
rset_seed(42)
env = fmla.environment
env['a']=rnorm(100)
env['b']=rnorm(100)
m=model_matrix(fmla)
This should work
fmla = r.Formula('~a+b')
env = fmla.environment
env['a'] = a
env['b'] = b
r.model_matrix(fmla)
In R, you can reproduce the error
set_seed(42)
a=rnorm(100)
b=rnorm(100)
m=model.matrix('~a+b')
Error: $ operator is invalid for atomic vectors
m=model.matrix(formula('~a+b')) ## this works
(Intercept) a b
1 1 -0.1011361 0.4354445
2 1 0.3782215 -1.5322641
3 1 1.4772023 0.3280948
4 1 0.2892421 1.9012016
5 1 -0.2596562 0.2036678
6 1 -0.5585396 -0.1536021

sage 5.0 confusing syntax error

My OS doesn't support Sage 5.4 so I'm stuck with 5.0 for now.
Defining this function registers no syntax errors in python, and I don't think it makes errors in Sage 5.4 (I'd appreciate confirmation if possible.) I'd like to know why it is failing in 5.0.
def num_matchings(G):
if min(G.degree_sequence())== 0 or G.num_edges()==0:
return 0
elif G.num_edges()==1:
if G.edges()[0][2] ==None:
return 1
else:
return G.edges()[0][2]
else:
H = copy(G)
K = copy(G)
e = G.edges()[0]
if e[2] ==None:
w=1
else:
w = e[2]
H.delete_edge(e)
K.delete_vertices([e[0],e[1]])
return num_matchings(H) + w*num_matchings(K)
The first error I get when I try to define is
File "<ipython console>", line 4
==Integer(1):
^
SyntaxError: invalid syntax
and they pile on after that. To my eye, the syntax looks fine.
I'm on Mac OS 10.5 with GCC 4.0.1.
Any help much appreciated.
[Aside: typo in .delete_vertives().]
Your syntax itself is fine. From the error message, though, it looks like you've simply copied and pasted code into the console. That will only work in certain very simple cases. You're also using tabs for indentation, which can cause a whole other set of headaches too. You should really switch to 4-space tabs instead.
If you want to insert code into a live console, you can use %paste (which copies from the clipboard if it can), or %cpaste instead.
For example, if I copy and paste your code, I get:
sage: def num_matchings(G):
....: if min(G.degree_sequence())== 0 or G.num_edges()==0:
....: return 0
....: elif G.num_edges()==1:
------------------------------------------------------------
File "<ipython console>", line 4
==Integer(1):
^
SyntaxError: invalid syntax
sage: if G.edges()[0][2] ==None:
....: return 1
------------------------------------------------------------
File "<ipython console>", line 2
SyntaxError: 'return' outside function (<ipython console>, line 2)
but if I use %cpaste with the 4-space equivalent (unfortunately %paste isn't working on my 5.4.1 install at the moment):
sage: %cpaste
Pasting code; enter '--' alone on the line to stop.
:
:def num_matchings(G):
: if min(G.degree_sequence())== 0 or G.num_edges()==0:
: return 0
[etc.]
: K.delete_vertices([e[0],e[1]])
: return num_matchings(H) + w*num_matchings(K)
:--
sage: num_matchings(graphs.LadderGraph(5))
8

Categories