xn=input()
c=input()
xn1 = .5(xn+(c/xn))
print(str(xn1))
I can't seem to get this code to run. I get the following error message:
Traceback (most recent call last):
File "eq.py", line 3, in <module>
xn1 = .5(xn+(c/xn))
TypeError: 'float' object is not callable
I've looked up a number of other assignment statements in Python, but I can't seem to figure out what's wrong with this one. I also tried casting all the variables as floats.
You're trying to invoke .5 as if it were a function. Change the line:
xn1 = .5*(xn+(c/xn))
Example here: https://repl.it/F55K
Related
Actually I have a problem when calling a Matlab script from Python.
import matlab.engine
import os
import random
import numpy as np
a=[str(random.randint(1,3)) for _ in range(3)]
print(a)
eng=matlab.engine.start_matlab()
eng.cd("/Users/dha/Documents/MATLAB/test-matlab/",nargout=0)
sr, state=eng.test_func()
print(sr)
print(state)
In fact I want to return "sr" which is a float and an array of integer "state", e.g. sr = 34.31 and state = [1,2,5]. The function test_func() work well on Matlab, but when I run this in Python from terminal (python test_matlab_engine.py) I received the following error:
Traceback (most recent call last):
File "test_matlab_engine.py", line 10, in <module>
sr, state=eng.mabuc_drl(a)
TypeError: 'float' object is not iterable
Anyone please give me the solution. Thank you so much in advance.
It seems that the result from MATLAB to Python has been cut off. If you have two parameters, you only get one which is the first parameter from the MATLAB. So, the question is how to get two or more parameters.
In a word, you should write this in your Python file:
re = eng.your_function_name(parameter1, parameter2, nargout=2)
where re contains two parameters which come from MATLAB.
You can find more information in the official documentation: Call MATLAB Functions from Python
This works:
ss = 'insert into images (file_path) values(?);'
dddd = (('dd1',), ('dd2',))
conn.executemany(ss, dddd)
However this does not:
s = 'insert into images (file_path) values (:v)'
ddddd = ({':v': 'dd11'}, {':v': 'dd22'})
conn.executemany(s, ddddd)
Traceback (most recent call last):
File "/Users/Wes/.virtualenvs/ppyy/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 3035, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-31-a999de59f73b>", line 1, in <module>
conn.executemany(s, ddddd)
ProgrammingError: You did not supply a value for binding 1.
I am wondering if it is possible to use named parameters with executemany and, if so, how.
The documentation at section 11.13.3 talks generally about parameters but doesn't discuss the two styles of parameters that are described for other flavors of .executexxx().
I have checked out Python sqlite3 execute with both named and qmark parameters which does not pertain to executemany.
The source shows that execute() simply constructs a one-element list and calls executemany(), so the problem is not with executemany() itself; the same call fails with execute():
>>> conn.execute('SELECT :v', {':v': 42})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.ProgrammingError: You did not supply a value for binding 1.
As shown in the Python documentation, named parameters do not include the colon:
# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
So you have to use ddddd = ({'v': 'dd11'}, {'v': 'dd22'}).
The : isn't part of the parameter name.
>>> s = 'insert into images (file_path) values (:v)'
>>> ddddd = ({'v': 'dd11'}, {'v': 'dd22'})
>>> conn.executemany(s, ddddd)
<sqlite3.Cursor object at 0x0000000002C0E500>
>>> conn.execute('select * from images').fetchall()
[(u'dd11',), (u'dd22',)]
I am looking to call an rPy2 function with multiple input parameters. Here is the R function write.csv that I am trying to use. It has multiple input parameters and I need to specify more than one such parameter.
If I use it without the optional parameter row.names and column.names, it works like this:
r("write.csv")(d,file='myfilename.csv')
For my requirements, I must issue this command with the optional parameters row.names and column.names. So, I tried:
r('write.csv')(d, file='myfilename.csv', row.names=FALSE, column.names=FALSE)
but I got this error message:
File "/home/UserName/test.py", line 12
r("write.csv")(d,file='myfilename.csv',row.names=FALSE, column.names=FALSE)
SyntaxError: keyword can't be an expression
[Finished in 0.0s with exit code 1]
[shell_cmd: python -u "/home/UserName/test.py"]
[dir: /home/UserName]
[path: /home/UserName/bin:/home/UserName/.local/bin:/usr/local/sbin:/usr/local/bin:
.../usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]
How can I achieve write.csv with row.names=FALSE and column.names=FALSE, in rPy2?
You can use Python's **.
See the note here: http://rpy2.readthedocs.io/en/version_2.8.x/robjects_functions.html#callable
Ony of my mistakes was that I should have replaced . by _, as shown in the docs here:
from rpy2.robjects.packages import importr
base = importr('base')
base.rank(0, na_last = True)
so I would analogously need row_names = TRUE. However, the . in write.csv() still remained, so this only solved part of the question. Ok, so I tried a few things to get an answer:
Generating sample data:
from rpy2.robjects import r, globalenv
from rpy2.robjects import IntVector, DataFrame
d = {'a': IntVector((1,2,3)), 'b': IntVector((4,5,6))}
dataf = DataFrame(d)
Attempts follow - 1. did not work, 2. and 3. did work:
1:
r('write_csv')(x=dataf,file='testing.csv',row_names=False)
Traceback (most recent call last):
File "C:\Users\UserName\FileD\test.py", line 18, in <module>
r('write_csv')(x=dataf,file='testing.csv',row_names=False)
File "C:\Python27\lib\site-packages\rpy2\robjects\__init__.py", line 321, in __call__
res = self.eval(p)
File "C:\Python27\lib\site-packages\rpy2\robjects\functions.py", line 178, in __call__
return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
File "C:\Python27\lib\site-packages\rpy2\robjects\functions.py", line 106, in __call__
res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in eval(expr, envir, enclos) : object 'write_csv'
..not found
Error in eval(expr, envir, enclos) : object 'write_csv' not found
2.
r('''
write_csv <- function(x,verbose=FALSE)
write.csv(x,file='testing.csv',row.names=FALSE)
''')
r['write_csv'](dataf)
3.
globalenv['dataf'] = dataf
r("write.csv(dataf,file='testing2.csv',row.names=FALSE)")
I was really hoping attempt 1. would have worked. It seemed I had reproduced the example in the docs base.rank(0, na_last = True), but I think something might have still been missing.
I've setup Orange and tried to execute this code in PythonWin
And got error on 2nd line
Was my setup of Orange incomplete or it's something else?
>>> from Orange.data import *
>>> color = DiscreteVariable("color", values=["orange", "green", "yellow"])
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'DiscreteVariable' is not defined
I'm not sure what the guy in the blog post is doing, or maybe there are some other steps that he explained in previous blog posts, but this code 'as is' is not going to work.
I searched the source code for Orange, and DiscreteVariable isn't mentioned anywhere, not as class, not as regular word, nothing.
What I did find however is
Discrete = core.EnumVariable
in Orange/feature/__init__.py. As you can see this points to core.EnumVariable, which appears, looking at it's usage:
orange.EnumVariable('color', values = ["green", "red"])\
to be the same as DiscreteVariable in your link.
So I suggest you use from Orange.feature import Discrete instead and use that.
I am currently investigating interfaces between python and C-dll's.
Using the ctypes library, I'm able to load the dll.
I have a very simple software setup for a proof of concept:
The function I call in the DLL, expects 1 argument; a function pointer to a function which takes a string to be printed by the python code.
Python code:
lib = ctypes.WinDLL(LIB_PATH)
# 1) Create callback function type
CB_FUNC_TYPE = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p)
# 2) Create the function which will be called back
def foo(text):
print text
# 3) create ctype callback function
cb_func = CB_FUNC_TYPE(foo)
# 4) Call the function
print lib.Test2(cb_func)
Exported C function (Test2):
__declspec(dllexport) void Test2(T_LOG_CALLBACK pf_log)
{
pf_log("Hello Python Log function!);
return;
}
When executing the python code, I get the following error output message:
Hello Python Log function!
Traceback (most recent call last):
File "C:\version\vcs\py\workspace\workspace\tests\python-c integration\test.py", line 32, in <module>
print lib.Test2(cb_func)
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
Which means that the callback is executed correctly, but an error on the stack has been triggered.
I don't understand the error, because the c-function only has one parameter (the function pointer to the function foo in this case).
If I update the line :
cb_func = CB_FUNC_TYPE(foo)
to
print lib.Test2(cb_func, "extra")
I get the same error, but 8 bytes in excess:
Hello Python Log function!
Traceback (most recent call last):
File "C:\version\vcs\py\workspace\workspace\tests\python-c integration\test.py", line 32, in <module>
print lib.Test2(cb_func, "extra")
ValueError: Procedure probably called with too many arguments (8 bytes in excess)
I cannot find the error, as I at least need to add the callback function's address.
Anybody can see what I'm doing wrong?
this might be way off base, but I think you need to define an argtype and restype for each ctypes function..