edited..
full traceback:
Traceback (most recent call last):
File "dscli.py", line 36, in <module>
main()
File "dscli.py", line 31, in main
instance_StreamingDownloader.download_all()
File "file.py", line 283, in download_all
time_first_frame_last_segment = self.get_time_saved_segment(crrt_segment - 1)
File "file.py", line 239, in get_time_saved_segment
return(start_time)
UnboundLocalError: local variable 'start_time' referenced before assignment
code here
It gets only first segment and then error.
How can I solve this issue?
code from github
the answer is quite simple -
the condition allows some case when start_time is not defined during script run
so as it is not defined - it fails
start_time is defined inside an if statement that's inside a for loop.
What if you don't enter the loop, or the condition isn't met? What should the function return?
start_time needs to be initialized (eg start_time = 0 / None / False) in the function body, outside any control flow clauses, so that it's always defined, and therefore you can always return it.
when condition isn't met then:
Traceback (most recent call last):
File "dscli.py", line 36, in <module>
main()
File "dscli.py", line 31, in main
instance_StreamingDownloader.download_all()
File "file.py", line 286, in download_all
lenght_ahead_buffered = time_first_frame_last_segment - time_if_streaming + random_perturbation
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'
line 280-286:
while continue_download:
time_first_frame_last_segment = self.get_time_saved_segment(crrt_segment - 1)
time_if_streaming = time.time() - init_time
random_perturbation = random.gauss(0, self.random_time)
if self.verbose > 1:
print("time in video if streaming: " + str(time_if_streaming))
Related
The goal is to overlay pfp on top of template, and then place the string description underneath pfp. When I run the code, I get the error TypeError: argument must be sequence.
def edit(template, pfp, description):
x = (template.size[0] - image.size[0])/2
y = (template.size[1] - image.size[1])/2
Image.Image.paste(template, pfp, (round(x), round(y)))
draw = ImageDraw.Draw(template)
draw.text(round((template.size[0]/8), round(y-15)), description)
template.show()
return template
Full error message:
Traceback (most recent call last):
File "/Users/shalim/PycharmProjects/EDPtigerstars/main.py", line 30, in <module>
edit(background, image, x[1]).save(x[0])
File "/Users/shalim/PycharmProjects/EDPtigerstars/main.py", line 18, in edit
draw.text(round((template.size[0]/8), round(y-15)), description)
File "/Users/shalim/PycharmProjects/EDPtigerstars/venv/lib/python3.8/site-packages/PIL/ImageDraw.py", line 512, in text
draw_text(ink)
File "/Users/shalim/PycharmProjects/EDPtigerstars/venv/lib/python3.8/site-packages/PIL/ImageDraw.py", line 496, in draw_text
self.draw.draw_bitmap(coord, mask, ink)
TypeError: argument must be sequence
Process finished with exit code 1
Try putting your x, y coordinates inside a tuple:
draw.text((x,y)), "Text")
My program removes the substring 'rotten' from the string list:
bag_of_fruits = ["apple","rottenBanana","apple"]
def remove_rotten(bag_of_fruits):
bag_of_fruits = [x.removeprefix('rotten') for x in bag_of_fruits]
return [x.lower() for x in bag_of_fruits]
print(remove_rotten(bag_of_fruits))
All tests is completed, but in the end program shows 'Unexpected exception raised':
Traceback (most recent call last):
File "/workspace/default/.venv/lib/python3.10/site-packages/codewars_test/test_framework.py", line 112, in wrapper
func()
File "/workspace/default/tests.py", line 21, in fixed_tests
test.assert_equals(remove_rotten(tst[0]), tst[1], f"Input = {tst[0]}")
File "/workspace/default/solution.py", line 4, in remove_rotten
bag_of_fruits = [x.removeprefix('rotten') for x in bag_of_fruits]
TypeError: 'NoneType' object is not iterable
Try to change the name of the variable to avoid the error
bag_of_fruits = ["apple","rottenBanana","apple"]
def remove_rotten(bag_of_fruits):
# ---- > variable name should be changed
bag_of_fruits_edited = [x.removeprefix('rotten') for x in bag_of_fruits]
return [x.lower() for x in bag_of_fruits_edited]
print(remove_rotten(bag_of_fruits))
I am trying to use multiprocessing in a class in the following code:
class test:
def __init__(self):
return
global calc_corr
#staticmethod
def calc_corr(idx, df1, df2):
arr1 = df1.iloc[idx:idx+5, :].values.flatten('F')
arr2 = df2.iloc[idx:idx+5, :].values.flatten('F')
df_tmp = pd.DataFrame([arr1, arr2]).T
df_tmp.dropna(how='any', inplace=True)
corr = df_tmp.corr().iloc[0, 1]
return corr
def aa(self):
df1 = pd.DataFrame(np.random.normal(size=(100, 6)))
df2 = pd.DataFrame(np.random.normal(size=(100, 6)))
with concurrent.futures.ProcessPoolExecutor() as executor:
results = [executor.submit(calc_corr, (i, df1, df2)) for i in range(20)]
for f in concurrent.futures.as_completed(results):
print(f.result())
if __name__ == '__main__':
t = test()
t.aa()
I am using a #staticmethod because it is not related to the class, it's just a computing tool. But using it raises the following error when running the code:
D:\anaconda3\python.exe C:/Users/jonas/Desktop/728_pj/test.py
concurrent.futures.process._RemoteTraceback:
"""
Traceback (most recent call last):
File "D:\anaconda3\lib\multiprocessing\queues.py", line 245, in _feed
obj = _ForkingPickler.dumps(obj)
File "D:\anaconda3\lib\multiprocessing\reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: cannot pickle 'staticmethod' object
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\jonas\Desktop\728_pj\test.py", line 31, in <module>
t.aa()
File "C:\Users\jonas\Desktop\728_pj\test.py", line 26, in aa
print(f.result())
File "D:\anaconda3\lib\concurrent\futures\_base.py", line 438, in result
return self.__get_result()
File "D:\anaconda3\lib\concurrent\futures\_base.py", line 390, in __get_result
raise self._exception
File "D:\anaconda3\lib\multiprocessing\queues.py", line 245, in _feed
obj = _ForkingPickler.dumps(obj)
File "D:\anaconda3\lib\multiprocessing\reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
TypeError: cannot pickle 'staticmethod' object
Process finished with exit code 1
Can anyone help me fix this?
I think it is somehow caused by the staticmethod being declared as global. When I tried removing the global calc_corr line and changing
results = [executor.submit(calc_corr, (i, df1, df2)) for i in range(20)] to
results = [executor.submit(self.calc_corr, i, df1, df2) for i in range(20)] it seemed to work fine. I'm not actually sure of the reason what you wrote doesn't work but hopefully this will.
Note: Removing the tuple for the arguments is unrelated to this issue but was causing another issue afterwards.
Traceback (most recent call last):
File "C:\Users\Evan\Desktop\Gamble\main.py", line 159, in <module>
main()
File "C:\Users\Evan\Desktop\Gamble\main.py", line 128, in main
link = create_clip(count, "WITHDRAW", root)
File "C:\Users\Evan\Desktop\Gamble\main.py", line 53, in create_clip
new = video.subclip(int(frame / 60 - 5), int(frame / 60 + 5))
File "C:\Users\Evan\anaconda3\envs\F\lib\site-packages\decorator.py", line 232, in fun
return caller(func, *(extras + args), **kw)
File "C:\Users\Evan\anaconda3\envs\F\lib\site-packages\moviepy\decorators.py", line 79, in wrapper
names = inspect.getfullargspec(func).args
NameError: name 'func' is not defined
I haven't altered anything in the package nor could I find anything online about this the code causing this error in question is
with VideoFileClip(root) as video:
new = video.subclip(int(frame / 60 - 5), int(frame / 60 + 5))
new.write_videofile(f'{root.split(".")[0]}/{claim}{str(datetime.timedelta(seconds=int(frame / 60)))}', audio_codec='aac')
It looks like they accepted a PR that broke the code. I managed to fix it by going into decorators.py and changing any instance of "func" to "f"
I wish to do some kind of reflection thing where given a line number and a module, I get back the name of the function in that module containing that line. Is this possible in Python?
There is no built-in way to do this in python. However, you could define a function to do something like that, but it would handle modules as files in your current directory:
import re
def get_function_name(module, line):
module_file = module.replace('.', '/') + '.py'
lines = open(module_file, 'r').xreadlines()
i = line - 1
try:
while i:
tmp = next(lines)
i -= 1
except StopIteration:
raise EOFError('Not enought lines in module %s' % module)
function_line = next(lines)
function_name = re.match('def (\w+)\([^)]*\):', function_line)
if function_name:
return function_name.group(1)
raise ValueError('No function declared on line %s' % line)
This function is opening the module passed as a file, iterating until reached the passed line, and then, searching the name of the function using regular expressions. If there was no function declared on the passed line or the line passed exceeded the number of lines of the file, it will raise an Error. E.g.:
>>> get_function_name('my_module.my_submodule', 24)
'my_function_name'
>>> get_function_name('my_module.my_submodule', 25)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 15, in get_function_name
ValueError: No function declared on line 17
>>> get_function_name('my_module.my_submodule', 123456)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in get_function_name
EOFError: Not enought lines in module