I am trying to calculate IRR and its giving me result in command line but whenever I am trying to pass the values as a parameter its failing with below error
Code
import numpy
import sys
def irrYearly(array):
array = [array]
irr = round(numpy.irr(array), 2)*100
return irr
def irrCal(tenure, array):
if tenure == "Yearly":
# return irrYearly(array)
# array = [-30000, -30000, -30000, -30000, -30000, 107180] -- if I uncomment this line its works fine
print(irrYearly(array))
elif tenure == "Monthly":
# return irrMonthly(array)
print(irrMonthly(array))
def main():
if len(sys.argv) == 3:
tenure = sys.argv[1]
array = sys.argv[2]
irrCal(tenure, array)
main()
Error
Please find the error
C:\Python27\python.exe C:/Users/abhis/PycharmProjects/IRR/irr.py Yearly -30000.00,-30000.00,-30000.00,-30000.00,-30000.00,107180.00
Traceback (most recent call last):
File "C:/Users/abhis/PycharmProjects/IRR/irr.py", line 74, in <module>
['-30000.00,-30000.00,-30000.00,-30000.00,-30000.00,107180.00']
main()
File "C:/Users/abhis/PycharmProjects/IRR/irr.py", line 64, in main
irrCal(tenure, array)
File "C:/Users/abhis/PycharmProjects/IRR/irr.py", line 49, in irrCal
print(irrYearly(array))
File "C:/Users/abhis/PycharmProjects/IRR/irr.py"", line 19, in irrYearly
irr = round(numpy.irr(array), 2)*100
File "C:\Python27\lib\site-packages\numpy\lib\financial.py", line 669, in irr
res = np.roots(values[::-1])
File "C:\Python27\lib\site-packages\numpy\lib\polynomial.py", line 222, in roots
p = p.astype(float)
ValueError: invalid literal for float(): -30000.00,-30000.00,-30000.00,-30000.00,-30000.00,107180.00
argv[2] is a string with comma separated values, but to numpy it's a string not a list of floats. You first need to convert it like so:
float_vals = [float(x) for x in argv[2].split(",")].
Related
First, this is my code:
import re
clientaddress = ('192.168.10.111', 43567)
x = re.search("\d+.\d+.\d+.\d+\$", clientaddress)
print (x)
if x:
print("YES! We have a match!")
else:
print("No match")
Here is the problem. the 'ClientAddress' is imported from another server and its format is like this:
('IP', port)
So we have an (str, int).
the error is :
Traceback (most recent call last):
File "./prog.py", line 6, in <module>
File "/usr/lib/python3.7/re.py", line 183, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object
After that, if I use this code:
import re
clientaddress = str('192.168.31.111', 43567)
clientaddress = ('192.168.31.111', 43567)
x = re.search("\d+.\d+.\d+.\d+\$", clientaddress)
print (x)
if x:
print("YES! We have a match!")
else:
print("No match")
The error that appeared is :
Traceback (most recent call last):
File "./prog.py", line 4, in <module>
TypeError: str() argument 2 must be str, not int
clientAddress is a tuple containing a string as the first element.
so index the tuple first and do the checking then. (clientaddress[0])
clientaddress = ('192.168.10.111', 43567)
x = re.search("\d+.\d+.\d+.\d+$", clientaddress[0])
print(x)
I'm having an issue trying to make a screen grab of an area defined by lines in a config file:
The following code:
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1,coordstore.y1,coordstore.x2,coordstore.y2 = (line[4]).strip(),(line[5]).strip(),(line[6]).strip(),(line[7]).strip() # note: confusing. 0=line 1, 1=line2 etc.
coordstore.coords = coordstore.x1+',',coordstore.y1+',',coordstore.x2+',',coordstore.y2
coordstore.stripped = ' '.join((coordstore.coords))
print(coordstore.stripped)
return(coordstore.stripped)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
prints exactly this value: 10, 20, 100, 300
it then fails with this Traceback:
Traceback (most recent call last):
File "file location", line 82, in <module>
screenshot()
File "file location", line 80, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.stripped)) # X1,Y1,X2,Y2
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 38, in _grab
x1, y1, x2, y2 = bbox
ValueError: too many values to unpack (expected 4)
If I manually replace (bbox=(coordstore.stripped)) with (bbox=(10, 20, 100, 300)) which is literally identical to what the variable prints, the code works perfectly but is not useful for my needs. What am I not seeing? Thanks for the help!
UPDATE:
I have tried another approach.
def coordstore(): # check line 1 of config file (screencap name)
f=open('config.txt')
line=f.readlines()
coordstore.x1 = (line[4]).strip()
coordstore.y1 = (line[5]).strip()
coordstore.x2 = (line[6]).strip()
coordstore.y2 = (line[7]).strip()
print(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2)
return(coordstore.x1, coordstore.y1, coordstore.x2, coordstore.y2)
coordstore()
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
im.save('tc.png')
screenshot()
This prints
10, 20, 100, 300
but returns the following Traceback errors:
Traceback (most recent call last):
File "module location", line 84, in <module>
screenshot()
File "module location", line 82, in screenshot
im = ImageGrab2.grab(bbox=(coordstore.x1+',', coordstore.y1+',', coordstore.x2+',', coordstore.y2+',')) # X1,Y1,X2,Y2
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 67, in grab
to_file=False, childprocess=childprocess, backend=backend, bbox=bbox)
File "\PYCHARM\venv\lib\site-packages\pyscreenshot\__init__.py", line 42, in _grab
raise ValueError('bbox y2<=y1')
ValueError: bbox y2<=y1
As you have mentioned in comments the value of coordstore.stripped is string. And expected argument by ImageGrab2.grab is type of tuple so, first you have to convert it into tuple.
Update the method like this:
def screenshot():
import pyscreenshot as ImageGrab2
# part of the screen
if __name__ == '__main__':
im = ImageGrab2.grab(bbox=tuple(map(int, coordstore.stripped.split(', ')))) # X1,Y1,X2,Y2
im.save('tc.png')
I am troubling with the code section given below.. when I execute it, I get value error given below.
Segmask = result2
box=[]
[liver_res, num] = measure.label(result1, return_num=True)
region = measure.regionprops(liver_res)
for i in range(num):
box.append(region[i].area)
label_num = box.index(max(box)) + 1
liver_res[liver_res != label_num] = 0
liver_res[liver_res == label_num] = 1
Value error:
Traceback (most recent call last):
File "/content/gdrive/My Drive/LiTS/test.py", line 122, in <module>
predict(args)
File "/content/gdrive/My Drive/LiTS/test.py", line 91, in predict
label_num = box.index(max(box)) + 1
ValueError: max() arg is an empty sequence
How should I fix this?
import pandas as pd
csv_file = 'sample.csv'
count = 1
my_filtered_csv = pd.read_csv(csv_file, usecols=['subDirectory_filePath', 'expression'])
emotion_map = { '0':'6', '1':'3', '2':'4', '3':'5', '4':'2', '5':'1', '6':'0'}
my_filtered_csv['expression'] = my_filtered_csv['expression'].replace(emotion_map)
print(my_filtered_csv)
Error is:
Traceback (most recent call last):
File "/Users/mona/CS585/project/affnet/emotion_map.py", line 11, in <module>
my_filtered_csv['expression'] = my_filtered_csv['expression'].replace(emotion_map)
File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/generic.py", line 3836, in replace
limit=limit, regex=regex)
File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/generic.py", line 3885, in replace
regex=regex)
File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/internals.py", line 3259, in replace_list
masks = [comp(s) for i, s in enumerate(src_list)]
File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/internals.py", line 3259, in <listcomp>
masks = [comp(s) for i, s in enumerate(src_list)]
File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/internals.py", line 3247, in comp
return _maybe_compare(values, getattr(s, 'asm8', s), operator.eq)
File "/Users/mona/anaconda/lib/python3.6/site-packages/pandas/core/internals.py", line 4619, in _maybe_compare
raise TypeError("Cannot compare types %r and %r" % tuple(type_names))
TypeError: Cannot compare types 'ndarray(dtype=int64)' and 'str'
Process finished with exit code 1
A few lines of the csv file looks like:
,subDirectory_filePath,expression
0,689/737db2483489148d783ef278f43f486c0a97e140fc4b6b61b84363ca.jpg,1
1,392/c4db2f9b7e4b422d14b6e038f0cdc3ecee239b55326e9181ee4520f9.jpg,0
2,468/21772b68dc8c2a11678c8739eca33adb6ccc658600e4da2224080603.jpg,0
3,944/06e9ae8d3b240eb68fa60534783eacafce2def60a86042f9b7d59544.jpg,1
4,993/02e06ee5521958b4042dd73abb444220609d96f57b1689abbe87c024.jpg,8
5,979/f675c6a88cdef99a6d8b0261741217a0319387fcf1571a174f99ac81.jpg,6
6,637/94b769d8e880cbbea8eaa1350cb8c094a03d27f9fef44e1f4c0fb2ae.jpg,9
7,997/b81f843f08ce3bb0c48b270dc58d2ab8bf5bea3e2262e50bbcadbec2.jpg,6
8,358/21a32dd1c1ecd57d3e8964621c911df1c0b3348a4ae5203b4a243230.JPG,9
Changing the emotion_map to the following fixed the problem:
emotion_map = { 0:6, 1:3, 2:4, 3:5, 4:2, 5:1, 6:0}
Another possiblity which can also create this error is:
you have already run this code once and the data is already replaced.
To solve this problem, you can go back and load the data set again
Keeping it simple:
----------------------------------
from mpmath import *
from scipy.integrate import *
mp.dps=30
def F(x):
return Q**(x)
Q=735
print fixed_quad(F,0,1,n=1)[0]
print fixed_quad(F,0,1,n=2)[0]
print fixed_quad(F,0,1,n=3)[0]
--------------------
returns
27.1108834235
93.1213589089
109.673420158
However, if I change F(x) from “Q**(x)” to even just a simple function—e.g., “cos(x)”—I get
--------------------
Traceback (most recent call last):
File "Test.py", line 7, in <module>
print fixed_quad(F,0,1,n=1)[0]
File "/usr/lib/python2.7/dist-packages/scipy/integrate/quadrature.py", line 67, in fixed_quad
return (b-a)/2.0*sum(w*func(y,*args),0), None
File "Test.py", line 5, in F
return cos(x)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp_python.py", line 984, in f
x = ctx.convert(x)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp_python.py", line 662, in convert
return ctx._convert_fallback(x, strings)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp.py", line 614, in _convert_fallback
raise TypeError("cannot create mpf from " + repr(x))
TypeError: cannot create mpf from array([ 0.5])
Is this some known bug? Or is “fixed_quad” only meant for certain uses, not general integration (like “trapz”)?
All of the other regulars (“quad”, “dblquad”, “tplquad”, “nquad”) donʼt seem to have that problem/error.