content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to fill python dictionary while creating it I'm searching for a way of filling a python dictionary at the same time it is created I have this simple method that firstly creates a dictionary with all the keys at value 0 and then it reads the string again to fill it def letter_count(word): letter_dic = {} ...
How to fill python dictionary while creating it
I'm searching for a way of filling a python dictionary at the same time it is created I have this simple method that firstly creates a dictionary with all the keys at value 0 and then it reads the string again to fill it def letter_count(word): letter_dic = {} for w in word: letter_dic[w] = 0 for w ...
[ "Yes it is!\nThe most pythonic way would be to use the Counter\nfrom collections import Counter\n\nletter_dic = Counter(word)\n\nBut there are other options, like with pure python:\nfor w in word:\n if w not in letter_dic: \n letter_dic[w] = 0\n letter_dic[w] += 1\n\nOr with defaultdict. You pass one c...
[ 3, 3, 0 ]
[]
[]
[ "dictionary", "optimization", "python" ]
stackoverflow_0074572613_dictionary_optimization_python.txt
Q: Field 'id' expected a number but got 'create' This a my django project code, i have an error in this project please help me to solve this error. so i can run my project. **Question ** Exception Value: Field 'id' expected a number but got 'create' Traceback (most recent call last): C:\Users\acer\Desktop\Air\air_sit...
Field 'id' expected a number but got 'create'
This a my django project code, i have an error in this project please help me to solve this error. so i can run my project. **Question ** Exception Value: Field 'id' expected a number but got 'create' Traceback (most recent call last): C:\Users\acer\Desktop\Air\air_site\todo\views.py, line 15, in todo_details 15. t...
[ "In your views.py try send the id into function;\ndef todo_create(request,id):\n\n", "in urls instead of this\npath('create/', views.todo_create),\n\nadd this\npath('create/<int:id>', views.todo_create),\n\nin views\ndef todo_create(request):\n\nto\ndef todo_create(request,id):\n\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0071282586_django_python.txt
Q: Secrets pip not downloading MacOS the secrets library is not downloading when I try to install the pip. My python is updated to 3.11.0. Wondering if that may be the issue? Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exi...
Secrets pip not downloading MacOS
the secrets library is not downloading when I try to install the pip. My python is updated to 3.11.0. Wondering if that may be the issue? Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [13 lines of output] ...
[ "A the error mentions: ImportError: Installing this module requires OpenSSL python bindings, you are probably missing OpenSSL bindings. They are part of the cryptography package.\nInstall them with pip install cryptography and try again.\nEDIT: Python 3.11 is like a few days old. If it does not work you can also tr...
[ 0 ]
[]
[]
[ "command_line", "macos", "pip", "python" ]
stackoverflow_0074572540_command_line_macos_pip_python.txt
Q: When and where to call super().__init__() when overriding QT methods? When overriding virtual functions of QtWidgets, in which cases should I call super().__init__()? And in which cases does its position make a difference? Example: class Window(QtWidgets.QMainWindow): def keyPressEvent(self, event: QtGui.QKeyE...
When and where to call super().__init__() when overriding QT methods?
When overriding virtual functions of QtWidgets, in which cases should I call super().__init__()? And in which cases does its position make a difference? Example: class Window(QtWidgets.QMainWindow): def keyPressEvent(self, event: QtGui.QKeyEvent) -> None: """Variant A: Top""" super().__init__(event)...
[ "When you call super().__init__(...), you are literally invoking the parent classes constructor method. This typically should only be done once for each instance of the child widget in it's own constructor (aka __init__) method, and should be the very first call made.\nFor example:\nclass MyWidget(QWidget):\n de...
[ 1 ]
[]
[]
[ "pyqt", "pyside", "python" ]
stackoverflow_0074572500_pyqt_pyside_python.txt
Q: Why is Python Turtle listen() not working? I am very, and by that I mean very new to Python (i know literally nothing). I'm attemtping to create a little game using the turtle module, and following a tutorial I don't see the listen() function working here's my code I'm trying to create a controllable character fro...
Why is Python Turtle listen() not working?
I am very, and by that I mean very new to Python (i know literally nothing). I'm attemtping to create a little game using the turtle module, and following a tutorial I don't see the listen() function working here's my code I'm trying to create a controllable character from turtle import * #background Screen().bgcolor(...
[ "When you do from turtle import * it imports everything into the built-in namespace, i.e., you can then just do:\nlisten()\n\nrather than\nturtle.listen()\n\nIf you had just done\nimport turtle\n\nthen everything in the turtle package would then be accessed through the turtle namespace, i.e.,\nturtle.listen()\n\n",...
[ 0, 0 ]
[]
[]
[ "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074572564_python_python_turtle_turtle_graphics.txt
Q: Field 'id' expected a number but got '' in django blog_id is not get. help me to solve this --- models.py class Blog(models.Model): title = models.CharField(max_length=500) body = models.TextField() last_updated_on = models.DateTimeField(auto_now=True) created_on = models.DateTimeField(auto_now_add...
Field 'id' expected a number but got '' in django
blog_id is not get. help me to solve this --- models.py class Blog(models.Model): title = models.CharField(max_length=500) body = models.TextField() last_updated_on = models.DateTimeField(auto_now=True) created_on = models.DateTimeField(auto_now_add=True) author_instance = models.ForeignKey(AuthorIn...
[ "views should be like\ndef like_post(request,id):\n post = get_object_or_404(Blog, id=request.POST.get('blog_id'))\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0072895325_django_django_models_django_views_python.txt
Q: Visual Studio Code - How to add multiple paths to python path? I am experimenting with Visual Studio Code and so far, it seems great (light, fast, etc). I am trying to get one of my Python apps running that uses a virtual environment, but also uses libraries that are not in the site-package of my virtual environme...
Visual Studio Code - How to add multiple paths to python path?
I am experimenting with Visual Studio Code and so far, it seems great (light, fast, etc). I am trying to get one of my Python apps running that uses a virtual environment, but also uses libraries that are not in the site-package of my virtual environment. I know that in settings.json, I can specify a python.pythonPath ...
[ "This worked for me:-\nin your launch.json profile entry, specify a new entry called \"env\", and set PYTHONPATH yourself.\n\"configurations\": [\n {\n \"name\": \"Python\",\n \"type\": \"python\",\n \"stopOnEntry\": false,\n \"request\": \"launch\",\n \"pythonPath\": \"${confi...
[ 55, 45, 9, 5, 4, 1, 0, 0, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0041471578_python_visual_studio_code.txt
Q: How to check if an element is present in a Django queryset? Is it like a regular python set? Suppose I have the following queryset entry_set = Entry.objects.all() How do I check if Entry Object e is present in entry_set? A: You can use the following code: if e in Entry.objects.all(): #do something Or ...
How to check if an element is present in a Django queryset?
Is it like a regular python set? Suppose I have the following queryset entry_set = Entry.objects.all() How do I check if Entry Object e is present in entry_set?
[ "You can use the following code:\nif e in Entry.objects.all():\n #do something\n\nOr the best approach:\nif Entry.objects.filter(id=e.id).exists():\n #do something\n\n", "The best approach, according to Django documentation: https://docs.djangoproject.com/en/2.1/ref/models/querysets/#exists\nif Entr...
[ 63, 14, 2, 0 ]
[ "You can just filter the queryset on the basis of a unique key present in the Entry model. Say, that key is id, your code would become:\nis_present = Entry.objects.filter(id=e.id)\nif is_present:\n print \"Present\"\nelse:\n print \"Not Present\"\n\n" ]
[ -1 ]
[ "django", "django_models", "python", "python_2.7", "python_3.x" ]
stackoverflow_0032002207_django_django_models_python_python_2.7_python_3.x.txt
Q: Python flask how can i insert a variable in LIKE sql Im struggeling on this problem with excuting sql in my flask python app. Im trying to excecute a like function with a variable that im recieving from my get reqs. for example i've tried this yet : rows = cursor.execute(f"SELECT * FROM vragen WHERE vraag LIKE ':t...
Python flask how can i insert a variable in LIKE sql
Im struggeling on this problem with excuting sql in my flask python app. Im trying to excecute a like function with a variable that im recieving from my get reqs. for example i've tried this yet : rows = cursor.execute(f"SELECT * FROM vragen WHERE vraag LIKE ':text'", {"text": '%' + query + '%'})....
[ "You shouldn't have quotes around :text:\nrows = cursor.execute(f\"SELECT * FROM vragen WHERE vraag LIKE :text\",\n {\"text\": '%' + query + '%'}).fetchall()\n\n" ]
[ 1 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0074572657_python_sql_sqlite.txt
Q: Cannot label math symbol in regular font and italic style Referring to this question thread Matplotlib: Italic style in regular font, I'm not able to achieve the same results with the latest python version 3.9.13 (I can achieve this previously). I want to label the x-axis as the displacement in Angstrom mathsymbol...
Cannot label math symbol in regular font and italic style
Referring to this question thread Matplotlib: Italic style in regular font, I'm not able to achieve the same results with the latest python version 3.9.13 (I can achieve this previously). I want to label the x-axis as the displacement in Angstrom mathsymbol with the same Times New Roman font in italic style. plt.rcPara...
[ "Use \\mathrm{\\AA} with the STIXGeneral font family, which comes with Matplotlib. This will render the symbol in non-italic style; \\AA will render it in italics. I included both in the following examples.\nimport matplotlib.pyplot as plt\nplt.rcParams['mathtext.fontset'] = 'stix'\nplt.xlabel(r'Displacement ($\\ma...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074564063_matplotlib_python.txt
Q: Bash - evaluate ENV Variable being stored in a command I want to save a command in a variable like this: [user@smat-jupyterhub-nb-user ~]$ TESTCMD='python script.py' [user@smat-jupyterhub-nb-user ~]$ SCRIPT=script.py Running $TESTCMD works fine. But I also want to pass a variable to that command: [user@smat-jupyt...
Bash - evaluate ENV Variable being stored in a command
I want to save a command in a variable like this: [user@smat-jupyterhub-nb-user ~]$ TESTCMD='python script.py' [user@smat-jupyterhub-nb-user ~]$ SCRIPT=script.py Running $TESTCMD works fine. But I also want to pass a variable to that command: [user@smat-jupyterhub-nb-user ~]$ TESTCMD2='python $SCRIPT' When I run this...
[ "That's because you used ' quotes, instead of \" preventing variable substitution.\n$ FOO=echo\n$ BAR=bar\n$ XXX='${FOO} ${BAR}'\n$ $XXX\n${FOO}: command not found\n\n$ XXX=\"${FOO} ${BAR}\"\n$ $XXX\nbar\n\nIn fact the last one should be rather\n$ XXX=\"\"${FOO}\" \"${BAR}\"\"\n\nwith variables additionally quoted ...
[ 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0074572778_bash_python.txt
Q: If it possible to filter out names of objects returned in Django Admin For my Django CMS Admin I would like to prevent it returning a specific object to the CMS. What is the best way to do this? I would like to do something like class MyModuleAdmin(admin.ModelAdmin): list_display = ['name'] list_filter = ...
If it possible to filter out names of objects returned in Django Admin
For my Django CMS Admin I would like to prevent it returning a specific object to the CMS. What is the best way to do this? I would like to do something like class MyModuleAdmin(admin.ModelAdmin): list_display = ['name'] list_filter = ('my_module__name__is_not=moduleidontwant',)
[ "You can simply overload get_queryset admin function and filter out items you do not want:\nclass MyModuleAdmin(admin.ModelAdmin):\n list_display = ['name']\n\n def get_queryset(self, request):\n queryset = super(MyModuleAdmin, self).get_queryset(request)\n return queryset.exclude(name='moduleid...
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "django_cms", "python" ]
stackoverflow_0074571953_django_django_admin_django_cms_python.txt
Q: How to PassOptionsToPackage from inside a quarto document? Consider the following quarto document: --- title: "Some title" author: X date: "2022" format: pdf: number-sections: true fontsize: 12 pt papersize: A4 fig-pos: 'H' geometry: "left=2.54cm,right=2.54cm,top=2.54cm,bottom=2.54cm" include-...
How to PassOptionsToPackage from inside a quarto document?
Consider the following quarto document: --- title: "Some title" author: X date: "2022" format: pdf: number-sections: true fontsize: 12 pt papersize: A4 fig-pos: 'H' geometry: "left=2.54cm,right=2.54cm,top=2.54cm,bottom=2.54cm" include-in-header: text: | \usepackage[font=small]{caption} ...
[ "As explained in this answer on Tex StackExchange, one possible solution could be passing table as a classoption and you do not need to declare using xcolor explicitly since it is used by-default.\n---\ntitle: \"Some title\"\nauthor: X\ndate: \"2022\"\nformat: \n pdf:\n number-sections: true\n fontsize: 12 pt\...
[ 3 ]
[]
[]
[ "latex", "python", "quarto", "r_markdown" ]
stackoverflow_0074572630_latex_python_quarto_r_markdown.txt
Q: how to call a entries in dictionary when it is in a list? So basically I have this list in code list_names = [ {"name":"Jullemyth","seat_number":4,"category":"Student"}, {"name":"Leonhard","seat_number":1,"category":"OFW"}, {"name":"Scarion","seat_number":3,"category":"Businessman"}, {"name":"Jagua...
how to call a entries in dictionary when it is in a list?
So basically I have this list in code list_names = [ {"name":"Jullemyth","seat_number":4,"category":"Student"}, {"name":"Leonhard","seat_number":1,"category":"OFW"}, {"name":"Scarion","seat_number":3,"category":"Businessman"}, {"name":"Jaguar","seat_number":2,"category":"Animal Manager"}, {"name":"C...
[ "You can do it with a list comprehension like :\nprint([lst[\"name\"] for lst in list_names])\n\n", "You cannot iterate upon all items without looping through them , the shortest way is to use list comprehension ,\nfor name in [D['name'] for D in list_names]:\n print(name)\n\n", "Another approach is using it...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074571624_dictionary_python.txt
Q: WSGI application 'Uploading.wsgi.application' could not be loaded while i am run my project after add this middleware social_auth.middleware.SocialAuthExceptionMiddleware i got this error raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: WSGI application 'Uploading.wsgi.application' could ...
WSGI application 'Uploading.wsgi.application' could not be loaded
while i am run my project after add this middleware social_auth.middleware.SocialAuthExceptionMiddleware i got this error raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: WSGI application 'Uploading.wsgi.application' could not be loaded; Error importing module.
[ "probably not installed middleware\ntry:\npip install whitenoise\n" ]
[ 0 ]
[]
[]
[ "django", "django_middleware", "python" ]
stackoverflow_0073918381_django_django_middleware_python.txt
Q: How do I convert a datetime to date? How do I convert a datetime.datetime object (e.g., the return value of datetime.datetime.now()) to a datetime.date object in Python? A: Use the date() method: datetime.datetime.now().date() A: From the documentation: datetime.datetime.date() Return date object with same ye...
How do I convert a datetime to date?
How do I convert a datetime.datetime object (e.g., the return value of datetime.datetime.now()) to a datetime.date object in Python?
[ "Use the date() method:\ndatetime.datetime.now().date()\n\n", "From the documentation:\n\ndatetime.datetime.date()\nReturn date object with same year, month and day.\n\n", "You use the datetime.datetime.date() method:\ndatetime.datetime.now().date()\n\nObviously, the expression above can (and should IMHO :) be ...
[ 1442, 161, 75, 57, 11, 10, 6, 0, 0 ]
[ "If you are using pandas then this can solve your problem:\nLets say that you have a variable called start_time of type datetime64 in your dataframe then you can get the date part like this:\ndf.start_time.dt.date\n\n" ]
[ -1 ]
[ "datetime", "python" ]
stackoverflow_0003743222_datetime_python.txt
Q: Is there a way to skip python-O365 Account authentication or make it possible to complete it on a UI? I want to read outlook emails and save the attachments, and I'm using python-O365 module for that. The problem is this module requires account authentication in order to access outlook. The workflow is in this way...
Is there a way to skip python-O365 Account authentication or make it possible to complete it on a UI?
I want to read outlook emails and save the attachments, and I'm using python-O365 module for that. The problem is this module requires account authentication in order to access outlook. The workflow is in this way: User accesses the function/api, which then uses predefined/hardcoded credentials to connect to the outlo...
[ "I got my answer myself. Basically I imported the functions that are being used in O365 library into my code, and reworked them a bit to get what I wanted done.\nHere it goes,\nSo by default on a GET request, this django API shows the link that user needs to visit, sign-in and provide consent.(client and secret are...
[ 0 ]
[]
[]
[ "python", "python_o365" ]
stackoverflow_0074543496_python_python_o365.txt
Q: Python generator yield behaviour So I have the following generator function: def gen(n=5): for i in range(n): n = yield n for i in gen(3): print(i) The result: 3 None None I understand the first result of yield is 3. Because I assigned 3 to function argument n. But where are the None in the seco...
Python generator yield behaviour
So I have the following generator function: def gen(n=5): for i in range(n): n = yield n for i in gen(3): print(i) The result: 3 None None I understand the first result of yield is 3. Because I assigned 3 to function argument n. But where are the None in the second and third yield coming from? Is it...
[ "This is explained in the documentation of yield expressions, especially this part:\n\nThe value of the yield expression after resuming depends on the method\nwhich resumed the execution. If next() is used (typically via\neither a for or the next() builtin) then the result is None.\nOtherwise, if send() is used, th...
[ 3, 2 ]
[]
[]
[ "generator", "python", "yield" ]
stackoverflow_0074572759_generator_python_yield.txt
Q: How to solve AttributeError: 'list' object has no attribute 'rhs' while solving differential equation using python? from sympy import * import matplotlib.pyplot as plt x,y=symbols('x y', real =True) M=5*x*sqrt(x)+7*y**2/sqrt(x) N=28*y*sqrt(x) if diff(M,y) == diff(N,x): print("The equation is exact") else: ...
How to solve AttributeError: 'list' object has no attribute 'rhs' while solving differential equation using python?
from sympy import * import matplotlib.pyplot as plt x,y=symbols('x y', real =True) M=5*x*sqrt(x)+7*y**2/sqrt(x) N=28*y*sqrt(x) if diff(M,y) == diff(N,x): print("The equation is exact") else: print("The equation is not Exact") y=Function('y') deq=(5*x*sqrt(x)+7*y(x)**2/sqrt(x))+(28*y(x)*sqrt(x))*diff(y(x),x) yso...
[ "First off, you need to update SymPy to the latest version (1.11).\nThen, plt.plot doesn't know how to deal with sympy objects. Hence you need to use sympy's plot. So, you have to modify the last line code to this:\nplot(ysoln.rhs, (x,-2,2))\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python", "sympy" ]
stackoverflow_0074572158_matplotlib_python_sympy.txt
Q: Pydantic AttributeError: '' object has no attribute '__fields_set__' from pydantic import BaseModel class A(BaseModel): date = '' class B(A): person: float def __init__(self): self.person = 0 B() tried to initiate class B but raised error AttributeError: 'B' object has no attribute 'fi...
Pydantic AttributeError: '' object has no attribute '__fields_set__'
from pydantic import BaseModel class A(BaseModel): date = '' class B(A): person: float def __init__(self): self.person = 0 B() tried to initiate class B but raised error AttributeError: 'B' object has no attribute 'fields_set', why is it?
[ "It's because you override the __init__ and do not call super there so Pydantic cannot do it's magic with setting proper fields.\nWith pydantic it's rare you need to implement your __init__ most cases can be solved different way:\nfrom pydantic import BaseModel\n\nclass A(BaseModel):\n date = \"\"\n\nclass B(A):...
[ 0 ]
[]
[]
[ "class", "inheritance", "pydantic", "python" ]
stackoverflow_0074572953_class_inheritance_pydantic_python.txt
Q: drop a dictionary with nan value I have the following dictionary: my_dict = {'fields': ['id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': nan, 'name': 'bbb', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}, {'id': nan, 'name':...
drop a dictionary with nan value
I have the following dictionary: my_dict = {'fields': ['id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': nan, 'name': 'bbb', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}, {'id': nan, 'name': 'ddd', 'type': 'string'}], 'type':...
[ "I do not know why would you need pandas for that if u can simply do:\nmy_dict[\"fields\"] = [i for i in my_dict[\"fields\"] if not np.isnan(i[\"id\"])]\n\n** UPDATE **\nif you really do need for some reason to use pandas, you may try this constructiion:\nmy_dict[\"fields\"] = pd.Series(my_dict[\"fields\"]).apply(p...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "nan", "numpy", "pandas", "python" ]
stackoverflow_0074562395_dictionary_nan_numpy_pandas_python.txt
Q: Match integer values from end of string until second dot I have following string GA1.2.4451363243.9414195136 and I want to match 4451363243.9414195136 using regular expression for python. I have tried the following which is not working ([\d].[\d])$ Where am I going wrong here? A: A few ideas (string operations o...
Match integer values from end of string until second dot
I have following string GA1.2.4451363243.9414195136 and I want to match 4451363243.9414195136 using regular expression for python. I have tried the following which is not working ([\d].[\d])$ Where am I going wrong here?
[ "A few ideas (string operations or regex):\ns = 'GA1.2.4451363243.9414195136'\n\nout = '.'.join(s.rsplit('.', 2)[-2:])\n# '4451363243.9414195136'\n\nimport re\nout = re.search(r'[^.]*\\.[^.]*$', s)\n# <re.Match object; span=(6, 27), match='4451363243.9414195136'>\n\nNB. to ensure matching digits, you can replace [^...
[ 2, 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074572945_python_string.txt
Q: Reserved word as an attribute name in a dataclass when parsing a JSON object I stumbled upon a problem, when I was working on my ETL pipeline. I am using dataclasses dataclass to parse JSON objects. One of the keywords of the JSON object is a reserved keyword. Is there a way around this: from dataclasses import da...
Reserved word as an attribute name in a dataclass when parsing a JSON object
I stumbled upon a problem, when I was working on my ETL pipeline. I am using dataclasses dataclass to parse JSON objects. One of the keywords of the JSON object is a reserved keyword. Is there a way around this: from dataclasses import dataclass import jsons out = {"yield": 0.21} @dataclass class PriceObj: asOfDa...
[ "You can decode / encode using a different name with the dataclasses_json lib, from their docs:\nfrom dataclasses import dataclass, field\n\nfrom dataclasses_json import config, dataclass_json\n\n@dataclass_json\n@dataclass\nclass Person:\n given_name: str = field(metadata=config(field_name=\"overriddenGivenName...
[ 6, 0 ]
[]
[]
[ "json", "python", "python_3.x", "python_dataclasses" ]
stackoverflow_0060074344_json_python_python_3.x_python_dataclasses.txt
Q: Django celery results does not store task results The problem speaks for itself - django-celery-results does not store any task results. I did everything as it was described in 'getting started' section in documentation, but still no results. I'm using django 4.1.2 and django-celery-results 2.4.0 Here is related v...
Django celery results does not store task results
The problem speaks for itself - django-celery-results does not store any task results. I did everything as it was described in 'getting started' section in documentation, but still no results. I'm using django 4.1.2 and django-celery-results 2.4.0 Here is related variables from settings.py: CACHES = { 'default': { ...
[ "You have to migrate first then you will able to store such information.Follow this link you will get your solution for sure:\nhttps://docs.celeryq.dev/en/stable/django/first-steps-with-django.html#django-celery-results-using-the-django-orm-cache-as-a-result-backend\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074571316_django_python.txt
Q: Use Selenium to click on items in a UL one by one and scrape some information i'm just practicing scraping with selenium What i would like to do is go through each item in the unordered list get every list item wait.until(EC.presence_of_element_located((By.XPATH, "//*[@id='main_content']/ul" ))) ul_element = dr...
Use Selenium to click on items in a UL one by one and scrape some information
i'm just practicing scraping with selenium What i would like to do is go through each item in the unordered list get every list item wait.until(EC.presence_of_element_located((By.XPATH, "//*[@id='main_content']/ul" ))) ul_element = driver.find_element(By.XPATH, "//*[@id='main_content']/ul") all_li_element = ul_elem...
[ "Probably this can be done much faster, without opening all those links, but not with Selenium. Selenium imitates human GUI actions, so as a human do scrape all that data you do need to open all those links and read the data on the opened pages. However this can be done much clearer and faster via API calls or with...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074566903_python_selenium_web_scraping.txt
Q: Dynamically define model attributes / database fields in Django I would like to define a Django Model looking like this: from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Foo(models.Model): object_id_1...
Dynamically define model attributes / database fields in Django
I would like to define a Django Model looking like this: from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Foo(models.Model): object_id_1 = models.UUIDField() content_type_1 = models.ForeignKey(ContentT...
[ "My solution\nI'm not entirely satisfied with this piece of code because it means relying on undocumented\ninternals which have no stability guarantee whatsoever, but this is what I've finally done, for future readers:\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttyp...
[ 0 ]
[]
[]
[ "django", "django_models", "python", "python_3.x", "python_class" ]
stackoverflow_0074560142_django_django_models_python_python_3.x_python_class.txt
Q: Scipy binom pmf for a dataframe I have 3 dataframes, df1 is 18x19, df2 is 18x1 and df3 is 18x19. I want a new dataframe which gives df4=scipy.stats.binom.pmf(df1,df2,df3) and I am not able to run it for dataframes. So for example df4[0,0] = scipy.stats.binom.pmf(df1[0,0],df2[0,0],df3[0,0]) or df4[2,3] = scipy.sta...
Scipy binom pmf for a dataframe
I have 3 dataframes, df1 is 18x19, df2 is 18x1 and df3 is 18x19. I want a new dataframe which gives df4=scipy.stats.binom.pmf(df1,df2,df3) and I am not able to run it for dataframes. So for example df4[0,0] = scipy.stats.binom.pmf(df1[0,0],df2[0,0],df3[0,0]) or df4[2,3] = scipy.stats.binom.pmf(df1[2,3],df2[2,0],df3[2,...
[ "import pandas as pd\nfrom scipy import stats\nimport numpy as np\n# create the dataset\nrow = 18\ncol = 19\ndf2 = pd.DataFrame(np.random.randint(1,20,size=(row,1)))\ndf1 = pd.DataFrame({c: [np.random.randint(0, df2.loc[r,0]) for r in range(row)] for c in range(col)})\ndf3 = pd.DataFrame(np.random.uniform(0,1, size...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "scipy" ]
stackoverflow_0074572637_dataframe_pandas_python_scipy.txt
Q: Error in installing dlib library in python3.11 I am facing issue installing dlib on windows 10 Edition Windows 10 Home Single Language Version 22H2 Installed on ‎13-‎07-‎2022 OS build 19045.2251 Experience Windows Feature Experience Pack 120.2212.4180.0 I have cmake installed ➜ cmake --version cmake version...
Error in installing dlib library in python3.11
I am facing issue installing dlib on windows 10 Edition Windows 10 Home Single Language Version 22H2 Installed on ‎13-‎07-‎2022 OS build 19045.2251 Experience Windows Feature Experience Pack 120.2212.4180.0 I have cmake installed ➜ cmake --version cmake version 3.24.0-rc3 CMake suite maintained and supported by ...
[ "Yes. I made it successful using python3.11\nAll you need to do is\n\nClone the repo using\ngit clone https://github.com/davisking/dlib\nGet inside the directory in cmd using\ncd dlib\nMake sure you have visual studio desktop development with c++\n\nInstall cmake from https://cmake.org/download/\nUsing pip to insta...
[ 0 ]
[]
[]
[ "cmake", "dlib", "python" ]
stackoverflow_0074476152_cmake_dlib_python.txt
Q: Print list without brackets in a single row I have a list in Python e.g. names = ["Sam", "Peter", "James", "Julian", "Ann"] I want to print the array in a single line without the normal " [] names = ["Sam", "Peter", "James", "Julian", "Ann"] print (names) Will give the output as; ["Sam", "Peter", "James", "Julia...
Print list without brackets in a single row
I have a list in Python e.g. names = ["Sam", "Peter", "James", "Julian", "Ann"] I want to print the array in a single line without the normal " [] names = ["Sam", "Peter", "James", "Julian", "Ann"] print (names) Will give the output as; ["Sam", "Peter", "James", "Julian", "Ann"] That is not the format I want instead...
[ "print(', '.join(names))\n\nThis, like it sounds, just takes all the elements of the list and joins them with ', '.\n", "Here is a simple one. \nnames = [\"Sam\", \"Peter\", \"James\", \"Julian\", \"Ann\"]\nprint(*names, sep=\", \")\n\nthe star unpacks the list and return every element in the list. \n", "Genera...
[ 339, 112, 61, 27, 22, 13, 12, 7, 6, 4, 3, 1, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0011178061_list_python.txt
Q: Python openpyxl to automate entire column in excel import openpyxl i=2 workbook= openpyxl.load_workbook() sheet = workbook.active for i, cellObj in enumerate (sheet['I'],2): cellObj.value = '=IF(ISNUMBER(A2)*(A2<>0),A2,IF(ISNUMBER(F2)*(F2<>0),F2,IF(ISBLANK(A2)*ISBLANK(F2)*ISBLANK(H2),0,H2)))' workbook.save() Us...
Python openpyxl to automate entire column in excel
import openpyxl i=2 workbook= openpyxl.load_workbook() sheet = workbook.active for i, cellObj in enumerate (sheet['I'],2): cellObj.value = '=IF(ISNUMBER(A2)*(A2<>0),A2,IF(ISNUMBER(F2)*(F2<>0),F2,IF(ISBLANK(A2)*ISBLANK(F2)*ISBLANK(H2),0,H2)))' workbook.save() Using openpxl, I tried to apply formula to entire column '...
[ "You'd probably be better off to do it this way, auto skip row 1 by starting the iteration at row 2 and update the formula using the cell row number.\nimport openpyxl\n\nexcelfile = 'foo.xlsx'\nworkbook= openpyxl.load_workbook(excelfile)\nsheet = workbook.active\n\nmr = sheet.max_row # Last row to add formula to \...
[ 0, 0 ]
[]
[]
[ "openpyxl", "pandas", "python" ]
stackoverflow_0074571240_openpyxl_pandas_python.txt
Q: Python, KivyMD and Threading I'm trying to develop an application that makes some test on computer to check the components, etc... I have the first KivyMD screen which prints welcome to the users and when the user clicks on the button "Start the test", I want to switch the screen to LoadingScreen and start the tes...
Python, KivyMD and Threading
I'm trying to develop an application that makes some test on computer to check the components, etc... I have the first KivyMD screen which prints welcome to the users and when the user clicks on the button "Start the test", I want to switch the screen to LoadingScreen and start the test. At the end of the test, the scr...
[ "The code for getHardware was not present so I added something to make an example.\nfrom kivy.clock import mainthread\nclass TitleScreen(Screen):\n\n def getHardware(self, delay_seconds):\n for i in range(delay_seconds):\n time.sleep(1.0)\n print(i)\n self.change_screen()\n\n ...
[ 0 ]
[]
[]
[ "kivy", "kivymd", "python", "python_multithreading" ]
stackoverflow_0074571486_kivy_kivymd_python_python_multithreading.txt
Q: Remove text between two certain characters (multiple occurrences) I want to remove the text inside the character "-" and string "\n" (the characters as well) For example, string = "hi.-hello\n good morning" the result I want to get is string = "hi. good morning" and for string = "hi.-hello\n good morning -axq\n" t...
Remove text between two certain characters (multiple occurrences)
I want to remove the text inside the character "-" and string "\n" (the characters as well) For example, string = "hi.-hello\n good morning" the result I want to get is string = "hi. good morning" and for string = "hi.-hello\n good morning -axq\n" the result I want to get is string = "hi. good morning axq" I found thes...
[ "This works when you want to delete the text between one pair e.g. (-,\\n). When the problem is to delete text between several different pairs then I have to look better into the function how it really works.\nimport re\nstr = \"hi.-hello\\n good morning and a good-long \\n day\"\nre.sub(r\"-.*\\n\", \"\", str)\n>>...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074572979_python_regex.txt
Q: Convert Pandas Dataframe to nested json-keep 2 columns I have a DF with the following columns and data: I hope it could be converted to two columns, studentid and info, with the following format. the dataset is """ studentid course teacher grade rank 1 math A 91 1 1 history B 79 2 2 math ...
Convert Pandas Dataframe to nested json-keep 2 columns
I have a DF with the following columns and data: I hope it could be converted to two columns, studentid and info, with the following format. the dataset is """ studentid course teacher grade rank 1 math A 91 1 1 history B 79 2 2 math A 88 2 2 history B 83 1 3 math A 85 3 3 h...
[ "You don't really need groupby() and the single sub-dictionaries shouldn't really be in a list, but as value's for the nested dict. After setting the columns you want as index, with df.to_dict() you can achieve the desired output:\ndf = df.set_index(['studentid','course'])\n\ndf.to_dict(orient='index')\n\nOutputs:\...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "to_json" ]
stackoverflow_0073289999_dataframe_pandas_python_to_json.txt
Q: I'm writing an automation code for notepad I want user to enter a path and then my program should open all txt files in that folder. i wrote my code like this and i have no idea how to tell it to open all the txt files. thanks for your help. from pywinauto import application import psutil import os def Open_file(...
I'm writing an automation code for notepad
I want user to enter a path and then my program should open all txt files in that folder. i wrote my code like this and i have no idea how to tell it to open all the txt files. thanks for your help. from pywinauto import application import psutil import os def Open_file(): app = application.Application() pat...
[ "def Open_file():\n app = application.Application()\n path = input(\"path : \")\n DOCs = os.listdir(path)\n absolutePath = os.getcwd()+\"/\"+path\n if len(DOCs) > 0:\n for i in os.listdir(path):\n if i.endswith('.txt'):\n app.start(f\"notepad.exe {absolutePath}/{i}\")...
[ 0 ]
[]
[]
[ "automation", "notepad", "python" ]
stackoverflow_0074571320_automation_notepad_python.txt
Q: Marshmallow Date Validation I have written a validation for the input that I receive but now the issue is that i have mentioned a type as date and whenever the date is empty I receive it as "". So is there any way that I can skip validation if input is ""? My input: {"suggested_relieving_date": ""} My validation c...
Marshmallow Date Validation
I have written a validation for the input that I receive but now the issue is that i have mentioned a type as date and whenever the date is empty I receive it as "". So is there any way that I can skip validation if input is ""? My input: {"suggested_relieving_date": ""} My validation code: class OffboardingSchema(Sche...
[ "What do you think about switching empty strings to None in advance and accepting them?\nThis code converts all empty strings to None. But you can also differentiate based on the field name if you use a simple if condition.\nfrom marshmallow import pre_load\n\nclass OffboardingSchema(Schema):\n suggested_relievi...
[ 0 ]
[]
[]
[ "flask", "flask_marshmallow", "python" ]
stackoverflow_0074570057_flask_flask_marshmallow_python.txt
Q: i want to get ride of the index that gets printed year(): print("Type '2018' to select the data of 2018") print("Type '2019' to select the data of 2019") print("Type '2020' to select the data of 2020") print("Type '0' to close selection") ,,, def data_frame(): while True: y...
i want to get ride of the index that gets printed
year(): print("Type '2018' to select the data of 2018") print("Type '2019' to select the data of 2019") print("Type '2020' to select the data of 2020") print("Type '0' to close selection") ,,, def data_frame(): while True: year() a=int(input("Select the year:")) ...
[]
[]
[ "Try index_col=\"month\"\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074573211_python.txt
Q: GeoPandas DataFrame how to explode data by rows with geometry !unzip https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_ua10_500k.zip I'm using the above dataset to explode rows in geopandas dataframe # Read shapefile test = gpd.read_file("cb_2018_us_ua10_500k") # Split Name10 column to extract city & stat...
GeoPandas DataFrame how to explode data by rows with geometry
!unzip https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_ua10_500k.zip I'm using the above dataset to explode rows in geopandas dataframe # Read shapefile test = gpd.read_file("cb_2018_us_ua10_500k") # Split Name10 column to extract city & state test[['city', 'state_names']] = test['NAME10'].str.split(',', 1,...
[ "In this case, the data can be read in as a data frame and then converted to a geopandas data frame after some processing.\nimport geopandas as gpd\n\nurl = 'https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_ua10_500k.zip'\n\ntest = gpd.read_file(url)\ndf = pd.DataFrame(test)\n\ndf[['city', 'state_names']] ...
[ 1 ]
[]
[]
[ "dataframe", "geopandas", "pandas", "python" ]
stackoverflow_0074572186_dataframe_geopandas_pandas_python.txt
Q: How can I modify my __repr__ to respresent correctly? My __repr__ method works fine using objects created in it's class, but with objects that were created with the help of importing a library and using methods from it, it only represented the memory address... from roster import student_roster #I only got the li...
How can I modify my __repr__ to respresent correctly?
My __repr__ method works fine using objects created in it's class, but with objects that were created with the help of importing a library and using methods from it, it only represented the memory address... from roster import student_roster #I only got the list if students from here import itertools as it class Cla...
[ "The issue I was facing was linked to me not understanding the nature of th object. itertools.combinations is an iterable, and in order to represent the values stored I needed to\n1. unpack it inside a variable like:\ndef get_combinations(self, r):\n *res, = it.combinations(self.sorted_names, r)\n return re...
[ 0 ]
[]
[]
[ "built_in", "inheritance", "python", "python_itertools", "repr" ]
stackoverflow_0074566443_built_in_inheritance_python_python_itertools_repr.txt
Q: Sum of N numbers in Fibonacci I am trying to implement the total sum of N whole numbers in Fibonacci def fibo(n): if n<2: return 1 else: res = fibo(n-1) + fibo(n-2) sum = sum + res return res, sum n=7 sum = 0 for i in range(1, n): print(fibo(i)) print("Suma", sum) #ex...
Sum of N numbers in Fibonacci
I am trying to implement the total sum of N whole numbers in Fibonacci def fibo(n): if n<2: return 1 else: res = fibo(n-1) + fibo(n-2) sum = sum + res return res, sum n=7 sum = 0 for i in range(1, n): print(fibo(i)) print("Suma", sum) #example: if n=7 then print : 1,1,2,3,...
[ "You simply need to calculate sum in the for loop, not in the fibo(n).\nHere take a look:\ndef fibo(n):\nif n<2:\n return 1\nelse:\n res = fibo(n-1) + fibo(n-2)\n return res\n\nn=7\nsum = 0\nfor i in range(0, n):\n r = fibo(i)\n sum += r\n print(r)\n\nprint(\"Suma\", sum)\n\nI used r in order to c...
[ 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "fibonacci", "jupyter_notebook", "python", "python_3.x" ]
stackoverflow_0052487490_fibonacci_jupyter_notebook_python_python_3.x.txt
Q: Why do none of my check buttons stay checked? So I've been trying to code some check buttons for a program I'm creating for a school project (please ignore the fact it's organs lmao). So, when I try to code these checkbuttons they all format and appear correctly with the value set to off as I wanted but then it wo...
Why do none of my check buttons stay checked?
So I've been trying to code some check buttons for a program I'm creating for a school project (please ignore the fact it's organs lmao). So, when I try to code these checkbuttons they all format and appear correctly with the value set to off as I wanted but then it won't allow me to click on the checks and I'm not sur...
[ "Since the color of the tick are in white which is the same as the tick box, so it looks invisible.\nYou can either set fg (the tick) or selectcolor (the tick box) to other color.\nBelow code set fg=\"black\" of the first checkbox (\"Liver\") and selectcolor=\"black\" of the second checkbox (\"Heart\"):\nliver_var=...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074565232_python_tkinter.txt
Q: Append a new line to csv file using python enter image description hereI have a csv file and I want to append new lines to it when I used the code, the list didn't append to a new line, it appended the list to the last line of the csv file ` List1=["test2"] List2=["test1"] with open (folder + '\\' + 'test.csv', '...
Append a new line to csv file using python
enter image description hereI have a csv file and I want to append new lines to it when I used the code, the list didn't append to a new line, it appended the list to the last line of the csv file ` List1=["test2"] List2=["test1"] with open (folder + '\\' + 'test.csv', 'a+', newline = '') as f_object: writer_objec...
[ "Try this:\nList1=[\"test2\"] \nList2=[\"test1\"]\nwith open (r\"Z:\\Images\\Test\\test.csv\", 'a+') as f_object:\n writer_object = csv.writer(f_object)\n writer_object.writerow(List1)\n writer_object.writerow(List2)\n\n" ]
[ 0 ]
[]
[]
[ "append", "csv", "python", "python_3.x", "writer" ]
stackoverflow_0074572993_append_csv_python_python_3.x_writer.txt
Q: How to run a Python script on Azure Release? I have a python script on my Azure Repository. It is called build.py and it's inside folder swagger_updater. I am able to use it in a Build Pipeline easily, with the following script: steps: - task: PythonScript@0 inputs: scriptSource: filePath scriptP...
How to run a Python script on Azure Release?
I have a python script on my Azure Repository. It is called build.py and it's inside folder swagger_updater. I am able to use it in a Build Pipeline easily, with the following script: steps: - task: PythonScript@0 inputs: scriptSource: filePath scriptPath: swagger_updater/build.py pythonInterpre...
[ "Since the release pipeline will download the artifact from the build pipeline. You could use the \"Publish pipeline artifact\" in your build pipeline. And then use the artifact in your release pipeline.\nIn build pipeline:\n\nIn release pipeline:\n\nUpdate:\nIf you are using Azure Repo directly, please check the f...
[ 0 ]
[]
[]
[ "azure_devops", "azure_pipelines", "azure_releases", "python" ]
stackoverflow_0074572895_azure_devops_azure_pipelines_azure_releases_python.txt
Q: TypeError: 'int' object is not subscriptable in trying to make a blackjack game Currently attempting to make a blackjack game with the code: cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] while blackjack_start == "y": #player card and comp card list player_cards = [(random.choice(cards)), (random.choi...
TypeError: 'int' object is not subscriptable in trying to make a blackjack game
Currently attempting to make a blackjack game with the code: cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] while blackjack_start == "y": #player card and comp card list player_cards = [(random.choice(cards)), (random.choice(cards))] comp_cards = [(random.choice(cards)), (random.choice(cards))] #scores...
[ "The problem is that when evaluating player_cards[0][1][2][3][4] python would first evaluate player_cards[0] which is a number (let's suppose it's 4) and then try to do something like 4[1][2][3][4], so it tries to interpret 4[1] which obviously fails because 4 cannot be subscripted, hence the error.\nIf you want th...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074573171_python.txt
Q: Python with Selenium || how to select first option in listbox? In a constantly updated listbox, I have to select the first tile each time. This list will be constantly updated and I have to regularly click on the first option. WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.CLASS_NAME,"dual-listbox...
Python with Selenium || how to select first option in listbox?
In a constantly updated listbox, I have to select the first tile each time. This list will be constantly updated and I have to regularly click on the first option. WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.CLASS_NAME,"dual-listbox__available"))).click() I can't get a response from your code.
[ "In the above code, you can get the first element by a CssSelector. Find the google chrome extension SelectorsHub so you can get the CssSelector easily which will solve your problem.\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074571922_python_selenium_selenium_webdriver.txt
Q: How to import physical constants from scipy.constants.physical_constants? I'm trying to import the electron volt-joule relationship from scipy.constants.physical_constants for use in a numerical physics problem. This is probably a very simple issue, or a misunderstanding of the physical_constants dictionary, but a...
How to import physical constants from scipy.constants.physical_constants?
I'm trying to import the electron volt-joule relationship from scipy.constants.physical_constants for use in a numerical physics problem. This is probably a very simple issue, or a misunderstanding of the physical_constants dictionary, but after googling for 2 hrs I'm still at a loss. I've tried from scipy.constants.ph...
[ "It looks like the original poster's import statement is not formatted correctly.\nTo get access to the constants include this import statement:\nfrom scipy import constants\n\nThen to access a specific constant, try:\nprint(constants.electron_volt)\n\nreturns:\n1.602176634e-19\n\nIf the scipy package is not found,...
[ 0, 0 ]
[]
[]
[ "dictionary", "python", "scipy" ]
stackoverflow_0067101481_dictionary_python_scipy.txt
Q: Visual Studio Code Intellisense is very slow - Is there anything I can do? Edit: Pylance seems to be much better at this and has so far resolved all problems with the previous Python language server from Microsoft. I'm using VS Code and it's wonderful is all areas but code completion, where it is usually just too ...
Visual Studio Code Intellisense is very slow - Is there anything I can do?
Edit: Pylance seems to be much better at this and has so far resolved all problems with the previous Python language server from Microsoft. I'm using VS Code and it's wonderful is all areas but code completion, where it is usually just too slow to be of any use. This example shows how long intellisense took to to find ...
[ "It turned out it was a particular VS Code extension for me.\nAngular Language Service. Disabling this made it lightning quick.\nTry this to see if it is a particular extension.\n\nOpen Command Palette (Ctrl+Shift+P)\nType in \"Disable all installed extensions\"\nEnable them one by one or in groups and test the in...
[ 65, 47, 36, 23, 15, 7, 7, 5, 4, 4, 2, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "code_completion", "intellisense", "python", "visual_studio_code" ]
stackoverflow_0051874486_code_completion_intellisense_python_visual_studio_code.txt
Q: How to add Bleed and Crop Marks to an image in Python Trying to programmatic-ally add bleed and crop marks to an image before printing. The issue is that I don't want to loose the 3mm at each side of the image, and for this reason, the manual procedure is used to be extending the sides of the image by mirroring th...
How to add Bleed and Crop Marks to an image in Python
Trying to programmatic-ally add bleed and crop marks to an image before printing. The issue is that I don't want to loose the 3mm at each side of the image, and for this reason, the manual procedure is used to be extending the sides of the image by mirroring them over a bleed line using InDesign, I wonder how to do som...
[ "I managed to do this using cv2.copyMakeBorder() from OpenCV librar method, as following:\nimport cv2\nimage = cv2.imread(\"illustration1.jpg\")\n\n#Window name in which image is displayed\nwindow_name = 'Image.jpg'\n\n#Using cv2.copyMakeBorder() method\nimage = cv2.copyMakeBorder(borderoutput, 35, 35, 35, 35, \ncv...
[ 0 ]
[]
[]
[ "printing", "python", "python_imaging_library" ]
stackoverflow_0074573013_printing_python_python_imaging_library.txt
Q: HOW TO FIX IT? AttributeError: module 'keras.preprocessing.image' has no attribute 'load_img' import numpy as np from keras.preprocessing import image import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.pyplot as plt import matplotlib.image as mpimg ...
HOW TO FIX IT? AttributeError: module 'keras.preprocessing.image' has no attribute 'load_img'
import numpy as np from keras.preprocessing import image import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.pyplot as plt import matplotlib.image as mpimg %matplotlib inline path = './test/paper2.png' img = image.load_img(...
[ "I'm facing the same problem today.\nYou can try using tensorflow 2.8.0 to fix it or try tf.keras.utils.load_img instead of image.load_img.\n", "Replace:\nfrom keras.preprocessing import image\n\nfor:\nimport keras.utils as image\n\n", "I also face the same error.\nI used from tensorflow.keras.utils import load...
[ 10, 3, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "image_preprocessing", "jupyter_lab", "keras", "python", "tensorflow" ]
stackoverflow_0072383347_image_preprocessing_jupyter_lab_keras_python_tensorflow.txt
Q: Is it possible to write a negative python type annotation This might sound unreasonable but right now I need to negate a type annotation. I mean something like this an_int : Not[Iterable] a_string: Iterable This is because I wrote an overload for a function and mypy does not understand me. My function looks like ...
Is it possible to write a negative python type annotation
This might sound unreasonable but right now I need to negate a type annotation. I mean something like this an_int : Not[Iterable] a_string: Iterable This is because I wrote an overload for a function and mypy does not understand me. My function looks like this... @overload def iterable(o: Iterable) -> Literal[True] : ...
[ "For your given example you can use Type Guards introduced in Python 3.10.\nfrom typing import TypeGuard, Iterable, Any\n\ndef is_iterable(o: Any) -> TypeGuard[Iterable]:\n \"\"\"\n Check if an object is an iterable\n\n See https://stackoverflow.com/questions/1952464\n \"\"\"\n try:\n iter(o)\...
[ 0 ]
[]
[]
[ "python", "python_typing", "type_annotation" ]
stackoverflow_0070618057_python_python_typing_type_annotation.txt
Q: Ungroup pandas dataframe after bfill I'm trying to write a function that will backfill columns in a dataframe adhearing to a condition. The upfill should only be done within groups. I am however having a hard time getting the group object to ungroup. I have tried reset_index as in the example bellow but that gets ...
Ungroup pandas dataframe after bfill
I'm trying to write a function that will backfill columns in a dataframe adhearing to a condition. The upfill should only be done within groups. I am however having a hard time getting the group object to ungroup. I have tried reset_index as in the example bellow but that gets an AttributeError. Accessing the original ...
[ "You should use 'transform' method on the grouped DataFrame, like this:\nimport pandas as pd\n\ndef test_upfill():\n df = pd.DataFrame({\n \"id\":[1,2,3,4,5],\n \"group\":[1,2,2,3,3],\n \"x_value\": [4,4,None,None,5],\n })\n result = df.groupby(\"group\").transform(lambda x: x.bfill())...
[ 1, 1 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074573267_group_by_pandas_python.txt
Q: How to use a class attribute as the type hint for a method inside the class? class Foo: method_type: type def method(self) -> ???: # code # Example use: class FooStr(Foo): method_type = str foo_str = FooStr().method() # should be str according to vscode's intellisense class FooInt(Foo): ...
How to use a class attribute as the type hint for a method inside the class?
class Foo: method_type: type def method(self) -> ???: # code # Example use: class FooStr(Foo): method_type = str foo_str = FooStr().method() # should be str according to vscode's intellisense class FooInt(Foo): method_type = int foo_int = FooInt().method() # similarly, this should be i...
[ "A class attribute is a runtime value and Python doesn't really support types dependent on values. Python also doesn't have type members. So in conclusion, no this isn't possible. You'd need to use a generic\nT = TypeVar(\"T\")\n\nclass Foo(Generic[T]):\n def method(self) -> T:\n ...\n\nclass FooStr(Foo[s...
[ 2 ]
[]
[]
[ "python", "type_hinting", "vscode_python" ]
stackoverflow_0074571468_python_type_hinting_vscode_python.txt
Q: Cloud Function http - send back results live as they arrive I have a Cloud Function (Python) who does some long(not heavy) calculation that depend on other external APIs so the respond might take some time ( 30 seconds). def test(request): request_json = request.get_json() for x in y: r = get_extern...
Cloud Function http - send back results live as they arrive
I have a Cloud Function (Python) who does some long(not heavy) calculation that depend on other external APIs so the respond might take some time ( 30 seconds). def test(request): request_json = request.get_json() for x in y: r = get_external_api_respond() calculate r and return partial respond ...
[ "You need to use some intermediary storage, which you will top-up from your function, and read in your HTTP request from web page. I wouldn't call it producer-consumer pattern, really, as you produce once, but consumes as many times as you need to.\nYou can use a Table Storage or Blob Storage if you use Azure.\nhtt...
[ 1 ]
[]
[]
[ "google_cloud_functions", "google_cloud_platform", "python" ]
stackoverflow_0074573488_google_cloud_functions_google_cloud_platform_python.txt
Q: Python to download file from FTP Server if file has been added into FTP server in last N hour ago? Can you please help with download file from FTP server if file has been added into last 12 hours ago, currently I'm able to download latest file from FTP server, but not sure how to add logic for last 12 hours ago if...
Python to download file from FTP Server if file has been added into FTP server in last N hour ago?
Can you please help with download file from FTP server if file has been added into last 12 hours ago, currently I'm able to download latest file from FTP server, but not sure how to add logic for last 12 hours ago if files has been added into ftp server import csv from ftplib import FTP import os import time,glob from ...
[ "Calculate the time threshold. Parse the times returned by MDTM. And compare:\nn = 4\nlimit = datetime.now() - timedelta(hours=n)\n\nfor name in finale_names:\n resp = ftp.sendcmd(\"MDTM \" + name)\n # extract \"yyyymmddhhmmss\" part of the 213 response\n timestr = resp[4:18]\n time = datetime.strptime(...
[ 0 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0074573297_ftp_ftplib_python.txt
Q: Trend Trigger Factor Indicator (TTF) in Python? I am trying to convert TTF Indicator from TradingView Pine Script to Python. (with no plotting) This is the Pine Script code I am trying to convert: //@version=3 // Copyright (c) 2018-present, Alex Orekhov (everget) // Trend Trigger Factor script may be freely distri...
Trend Trigger Factor Indicator (TTF) in Python?
I am trying to convert TTF Indicator from TradingView Pine Script to Python. (with no plotting) This is the Pine Script code I am trying to convert: //@version=3 // Copyright (c) 2018-present, Alex Orekhov (everget) // Trend Trigger Factor script may be freely distributed under the MIT license. study("Trend Trigger Fac...
[ "After I struggled a little bit I have found the right answer.\nI was right about where it could be the wrong part in my code above:\nbuyPower = hh - nz(ll[length])\nsellPower = nz(hh[length]) - ll\n\nIt is not equal to this:\nbuyPower = hh - ll.fillna(0) \nsellPower = hh.fillna(0) - ll\n\nThe correct python conver...
[ 0 ]
[]
[]
[ "pine_script", "pine_script_v4", "pinescript_v5", "python", "python_3.x" ]
stackoverflow_0074495637_pine_script_pine_script_v4_pinescript_v5_python_python_3.x.txt
Q: Can't install python-docx library, failed building wheel for python-docx I'm trying to install python-docx library, when i run: pip install python-docx I get this error, then the package says it's installed but I can't import anything I'm new to python programming and I don't know what a building wheel is nor h...
Can't install python-docx library, failed building wheel for python-docx
I'm trying to install python-docx library, when i run: pip install python-docx I get this error, then the package says it's installed but I can't import anything I'm new to python programming and I don't know what a building wheel is nor how to fix this. I already tried to uninstall and install lxml again I'm using ...
[ "It's a python version problem, I just updated it to Python 3.10 and it worked\n" ]
[ 0 ]
[]
[]
[ "lxml", "pip", "python", "python_3.8", "python_docx" ]
stackoverflow_0074563624_lxml_pip_python_python_3.8_python_docx.txt
Q: i tried this but my answer came 0.00 in every input The series:- I want to write a python program in which we can can input the the value of x and n and solve this series. can anyone help me please? The Series:- x-x^2+x^3/3-x^4/4+...x^n/n x = int (input ("Enter value of x: ")) numbed = int (input ("Enter value of...
i tried this but my answer came 0.00 in every input
The series:- I want to write a python program in which we can can input the the value of x and n and solve this series. can anyone help me please? The Series:- x-x^2+x^3/3-x^4/4+...x^n/n x = int (input ("Enter value of x: ")) numbed = int (input ("Enter value of n: ")) summed = 0 for a in range (numbed + 1) : if ...
[ "This should do the trick:\nx = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\ntotal = x\n\nfor i in range(2, n+1):\n if i%2==0:\n total -= x**i/i\n else:\n total += x**i/i\n \nprint(\"Sum: \", total)\n\n", "I assume the series you mentioned in your question...
[ 1, 1, 0 ]
[]
[]
[ "list", "python", "python_2.7", "python_3.x" ]
stackoverflow_0074571988_list_python_python_2.7_python_3.x.txt
Q: Is there a regex pattern that can change different values based on different matches in python I am appending a column in data-frame column name = 'Name' which is a string comprising of a few different columns concatenation. Now, I want to replace certain characters with certain values. Lets say & -> and < -> les...
Is there a regex pattern that can change different values based on different matches in python
I am appending a column in data-frame column name = 'Name' which is a string comprising of a few different columns concatenation. Now, I want to replace certain characters with certain values. Lets say & -> and < -> less than -> greater than ' -> this is an apostrophe " -> this is a double quotation Now how can I ef...
[ "One can use pandas.DataFrame.apply with a custom lambda function, using pandas.Series.str.replace as follows\nregex = r'(<|>|&)'\n\ndf_new = df.apply(lambda x: x.str.replace(regex, lambda m: 'less than' if m.group(1) == '<' else 'greater than' if m.group(1) == '>' else 'and', regex=True))\n\n[Out]:\n\n ...
[ 2, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "replace" ]
stackoverflow_0074573386_dataframe_pandas_python_replace.txt
Q: Can you dynamically create a python function, based on user input? Is it possible to create functions dynamically at runtime, based on user input? For example: I have a function 'add_i(x)', which adds i to x. Now, if a user calls 'add_2(x)' I want to create the function, that adds 2 to x. Is it possible to create ...
Can you dynamically create a python function, based on user input?
Is it possible to create functions dynamically at runtime, based on user input? For example: I have a function 'add_i(x)', which adds i to x. Now, if a user calls 'add_2(x)' I want to create the function, that adds 2 to x. Is it possible to create this function at runtime, without the user noticing it? The add_i(x) fun...
[ "Yes, you can define functions at runtime, you can use eval but it is insecure and if you just want to add some function with specific job like adding i to x you can do something better! look at this code:\ndef define(i):\n def add_i(x):\n return i+x\n return add_i\n\nWhen you call define(2) it will define...
[ 1 ]
[]
[]
[ "dynamic", "function", "python", "user_input" ]
stackoverflow_0074573157_dynamic_function_python_user_input.txt
Q: ImportError: cannot import name 'Enum' from 'discord' (unknown location) How to fix? | Python import nextcord from nextcord.ext import commands import wavelink class Music(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot bot.loop.create_task(self.connect_nodes()) as...
ImportError: cannot import name 'Enum' from 'discord' (unknown location)
How to fix? | Python import nextcord from nextcord.ext import commands import wavelink class Music(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot bot.loop.create_task(self.connect_nodes()) async def connect_nodes(self): await self.bot.wait_until_ready() ...
[ "The problem is wavelink needs discord.py to run and you are using nextcord\n, so with nextcord you can use nextwave\n" ]
[ 1 ]
[]
[]
[ "bots", "discord", "nextcord", "python", "python_3.x" ]
stackoverflow_0074569905_bots_discord_nextcord_python_python_3.x.txt
Q: Scapy change packet length I try change ICMP packet length on 1 byte from Scapy. But I still see 100 bytes sent in the traffic. Yes, I want send 100 bytes and see packet length 1 byte in traffic dump. What options need use? or it is impossible? >>> data = 'A'*100 >>> packet = IP(dst='1.1.1.1')/ICMP(length=1)/Raw(l...
Scapy change packet length
I try change ICMP packet length on 1 byte from Scapy. But I still see 100 bytes sent in the traffic. Yes, I want send 100 bytes and see packet length 1 byte in traffic dump. What options need use? or it is impossible? >>> data = 'A'*100 >>> packet = IP(dst='1.1.1.1')/ICMP(length=1)/Raw(load=data) >>> send(packet) ente...
[ "There is no length field in ICMP header. There is one in IP header.\nSo you can try something like that:\ndata = 'A' * 100\npacket = IP(dst='1.1.1.1', len=29)/ICMP()/Raw(load=data)\nsend(packet)\n\nHere I put 29 as length since my IP header is 20 bytes long and my\nICMP header is 8 byte long. So this leaves 1 by...
[ 0 ]
[]
[]
[ "icmp", "packet", "python", "scapy" ]
stackoverflow_0074534121_icmp_packet_python_scapy.txt
Q: Why does json.dump not call __getstate__ I have a python class which about the following contents, the important part is the ctypes library. from ctypes import * class PyClassExample: def __init__(self): self.path = '/some/unix/path/file.so' self.lib = CDLL(self.path) # non-serializable elemen...
Why does json.dump not call __getstate__
I have a python class which about the following contents, the important part is the ctypes library. from ctypes import * class PyClassExample: def __init__(self): self.path = '/some/unix/path/file.so' self.lib = CDLL(self.path) # non-serializable element self.arr = [1, 2, 3, 4] # serializab...
[ "The protocol that includes __getstate__ was made for Pickle, which in turn was designed to be able to serialise pretty much any Python object. It is a flexible format which stores both an objects type and its state.\nJSON doesn't have that. It only supports a fixed set of types, and extending the format is general...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074573166_python.txt
Q: My app consists with three buttons with window switching. How do you solve Attribute Error release? Here is my code. Basically I am doing this for my project, whereby I am trying to create a main menu, with three different button events that allows switches to different screens (one for a survey, one for a hyperli...
My app consists with three buttons with window switching. How do you solve Attribute Error release?
Here is my code. Basically I am doing this for my project, whereby I am trying to create a main menu, with three different button events that allows switches to different screens (one for a survey, one for a hyperlink, and one for a checklist). I tried diagnosing the problem, and I just do not get the attribute error....
[ "you should add the screens manually and give them names\nBuilder.load_file(\"Test Integration.kv\")\n\nclass MyMainApp(App):\n def build(self):\n _my_top_widget = WindowManager()\n _my_top_widget.add_widget(FirstWindow(name='FirstWindow'))\n _my_top_widget.add_widget(SecondWindow(name='Main...
[ 0 ]
[]
[]
[ "kivy", "pycharm", "python" ]
stackoverflow_0074568581_kivy_pycharm_python.txt
Q: sprite.rect.colliderect AttributeError' In hits = pygame.sprite.spritecollide(fallschirme,bullets,False) i get the message sprite.rect.colliderect AttributErros and 'Group' object has no attribute 'rect'. The relevant code is listed below. i looked similar question but i didn't find something simular. class Fal...
sprite.rect.colliderect AttributeError'
In hits = pygame.sprite.spritecollide(fallschirme,bullets,False) i get the message sprite.rect.colliderect AttributErros and 'Group' object has no attribute 'rect'. The relevant code is listed below. i looked similar question but i didn't find something simular. class Fallschirm(pygame.sprite.Sprite): ...
[ "In your code fallschirme is a sprite.Group(), but you're passing it as the first argument to spritecollide(...), which expects a sprite.\nI think you should be initialising fallschirme as:\nfallschirme = Fallschirm(x_position, y_position)\n\nIf that is not what you want, you'll need to edit your question to add mo...
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074572120_pygame_python.txt
Q: Lists in lists and for loops If I have lists with x lists and and for example [[(1,2),(1,4)],[(7,5),(5,4)]] How do I get another list that takes the first numbers of all the tuples in the lists and puts them in a list, and then takes the second numbers of all the tuples in the lists and puts them in a second list...
Lists in lists and for loops
If I have lists with x lists and and for example [[(1,2),(1,4)],[(7,5),(5,4)]] How do I get another list that takes the first numbers of all the tuples in the lists and puts them in a list, and then takes the second numbers of all the tuples in the lists and puts them in a second list.how should I get that with 3 for ...
[ "L = [[(1,2),(1,4)],[(7,5),(5,4)]]\n\nresult = list()\nfIndexesList = list() #first items\nsIndexesList = list() #second items\n\nfor item in L:\n \n fIndexesTuple = list()\n sIndexesTuple = list()\n \n for innerItem in item:\n fIndexesTuple.append(innerItem[0])\n sIndexesTuple.append(innerItem...
[ 0, 0 ]
[]
[]
[ "list", "nested", "python" ]
stackoverflow_0074572432_list_nested_python.txt
Q: Keras tf backend predict speed slow for batch size of 1 I am combining a Monte-Carlo Tree Search with a convolutional neural network as the rollout policy. I've identified the Keras model.predict function as being very slow. After experimentation, I found that surprisingly model parameter size and prediction sampl...
Keras tf backend predict speed slow for batch size of 1
I am combining a Monte-Carlo Tree Search with a convolutional neural network as the rollout policy. I've identified the Keras model.predict function as being very slow. After experimentation, I found that surprisingly model parameter size and prediction sample size don't affect the speed significantly. For reference: ...
[ "The batch size controls parallelism when predicting, so it is expected that increasing the batch size will have better performance, as you can use more cores and use GPU more efficiently.\nYou cannot really workaround, there is nothing really to work around, using a batch size of one is the worst case for performa...
[ 1, 1, 0 ]
[]
[]
[ "keras", "performance", "python" ]
stackoverflow_0056052206_keras_performance_python.txt
Q: No module named 'huggingface_hub.snapshot_download' When I try to run the quick start notebook of this repo, I get the error ModuleNotFoundError: No module named 'huggingface_hub.snapshot_download'. How can I fix it? I already installed huggingface_hub using pip. I get the error after compiling the following cell:...
No module named 'huggingface_hub.snapshot_download'
When I try to run the quick start notebook of this repo, I get the error ModuleNotFoundError: No module named 'huggingface_hub.snapshot_download'. How can I fix it? I already installed huggingface_hub using pip. I get the error after compiling the following cell: !CUDA_VISIBLE_DEVICES=0 python -u ../scripts/main.py --s...
[ "Updating to the latest version of sentence-transformers fixes it (no need to install huggingface-hub explicitly):\npip install -U sentence-transformers\n\nI've proposed a pull request for this in the original repo.\n" ]
[ 3 ]
[]
[]
[ "huggingface", "python" ]
stackoverflow_0074556349_huggingface_python.txt
Q: ScrollView not scrolling when using RelativeLayout as the layout I want to be able to build a midi sheet as shown here: I've used a relative layout to place the buttons at certain positions (not finalised, still in testing). However, I can't get the scrollview to scroll horizontally or vertically for that matter....
ScrollView not scrolling when using RelativeLayout as the layout
I want to be able to build a midi sheet as shown here: I've used a relative layout to place the buttons at certain positions (not finalised, still in testing). However, I can't get the scrollview to scroll horizontally or vertically for that matter. Could someone help me out? Or if you have any suggestions for a bette...
[ "You need to set the height of the GridLayout. Since you don't know in advance how many Buttons you will be adding to the GridLayut, you can use the minimum_height property of the GridLayout:\n layout = GridLayout(cols=1, spacing=10, size_hint_y=None)\n layout.bind(minimum_height=layout.setter('height'))\n\n"...
[ 1, 0 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0074539598_kivy_python.txt
Q: Why does the dtype of a numpy array automatically change to 'object' if you multiply the array with a number equal to or larger than 10**20? Given an arbitrary numpy array (its size and shape don't seem to play a role) import numpy as np a = np.array([1.]) print(a.dtype) # float64 it changes its dtype if you mu...
Why does the dtype of a numpy array automatically change to 'object' if you multiply the array with a number equal to or larger than 10**20?
Given an arbitrary numpy array (its size and shape don't seem to play a role) import numpy as np a = np.array([1.]) print(a.dtype) # float64 it changes its dtype if you multiply it with a number equal or larger than 10**20 print((a*10**19).dtype) # float64 print((a*10**20).dtype) # object a *= 10**20 # Throws Ty...
[ "I expect it is the size a \"natural\" integer can take on the system.\nprint(sys.maxsize, sys.getsizeof(sys.maxsize))\n=> 9223372036854775807 36\nprint(10**19, sys.getsizeof(10**19))\n=> 10000000000000000000 36\n\nAnd this is where on my system the conversion to object starts, when I do\nfor i in range(1, 24):\n ...
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074573624_numpy_python.txt
Q: Python function with cache give me an error, but why? I have the task to write a program with a function, that takes 2 integer and returns the numbers between the 2 integers. Example calc_range(3,5) -> 3,4. The function should save the data in a cache, for the reason, that if I ask the same numbers, the function s...
Python function with cache give me an error, but why?
I have the task to write a program with a function, that takes 2 integer and returns the numbers between the 2 integers. Example calc_range(3,5) -> 3,4. The function should save the data in a cache, for the reason, that if I ask the same numbers, the function should return the cache and not go through the code again. c...
[ "First check if the range is in the your cache (dictionary) if yes return it's value. If not, append all values in the range to a list and then add it to the cache (dictionary) and return the result. View the below code\nSolution\ncache = dict()\n\ndef calc_range(lower: int, higher: int)->list:\n new_liste = []\...
[ 0 ]
[]
[]
[ "assert", "caching", "function", "python", "range" ]
stackoverflow_0074573663_assert_caching_function_python_range.txt
Q: How to Properly Use FunctionTransformer in a Pipeline? I am trying to train a support vector machine on sentence embeddings I created with universal sentence encoder. I use FunctionTransformer inside of a pipeline to fit my model, but I get the following error: TypeError: can't pickle _thread.RLock objects Code %...
How to Properly Use FunctionTransformer in a Pipeline?
I am trying to train a support vector machine on sentence embeddings I created with universal sentence encoder. I use FunctionTransformer inside of a pipeline to fit my model, but I get the following error: TypeError: can't pickle _thread.RLock objects Code %tensorflow_version 1.x import tensorflow as tf import tensor...
[ "You should be passing the instance of FunctionTransformer directly in pipeline rather than wrapping it inside a ColumnTransformer.\nI have not checked the code as I dont have tensorflow_hub installed in my machine. So excuse me if this does not work out for you.\npipe = make_pipeline( \n FunctionTransfor...
[ 0 ]
[]
[]
[ "pipeline", "python", "scikit_learn", "tensorflow" ]
stackoverflow_0072372026_pipeline_python_scikit_learn_tensorflow.txt
Q: Related Field got invalid lookup: contains I am trying to include a search field inside my home page. It works for some of the module field. My problem is when I use a ForeignKey field (correct me please if I am wrong). models.py class Training_Lead(models.Model): handel_by = models.ForeignKey(UserInstance, on_del...
Related Field got invalid lookup: contains
I am trying to include a search field inside my home page. It works for some of the module field. My problem is when I use a ForeignKey field (correct me please if I am wrong). models.py class Training_Lead(models.Model): handel_by = models.ForeignKey(UserInstance, on_delete=models.PROTECT) learning_partner = models.Fo...
[ "You can't use __contains lookup in ForeignKey since it is used on strings so the Queryset should be:\ntrainers_info = Training_Lead.objects.filter(\n start_date__gte=start_date,\n end_date__lte=end_date,\n lead_status__contains=lead_status,\n assign_to_trainer=assign_to_...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0074572650_django_django_models_django_templates_django_views_python.txt
Q: Python - Scraping web data - using Ecommercetools module I'm new to python, I'm still familiar with Scraping web data function. Here's my code from ecommercetools import seo mysearch=input('What do you need to search?') results = seo.get_serps(mysearch,pages=2,domain=google.com) My question: regarding the last f...
Python - Scraping web data - using Ecommercetools module
I'm new to python, I'm still familiar with Scraping web data function. Here's my code from ecommercetools import seo mysearch=input('What do you need to search?') results = seo.get_serps(mysearch,pages=2,domain=google.com) My question: regarding the last function seo.get_serps, it has the option to change the domain,...
[ "First, upgrade to the latest version of EcommerceTools by entering pip3 install --upgrade ecommercetools\n... then, try this. You'll need to set the domain to your preferred one and set the host_language. The domain needs to be a valid Google domain and the host_language needs to be a valid two-letter language cod...
[ 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074482985_python_web_scraping.txt
Q: Remove line breaks between certain lines in python I have a txt file which has data in this form: Fact 1: YouTube has over 1 Billion users daily` Fact 2: Owls don't sleep at night What I want is to get one fact per line like this: Fact 1: YouTube has over 1 Billion users daily Fact 2: Owls don't sleep at night ...
Remove line breaks between certain lines in python
I have a txt file which has data in this form: Fact 1: YouTube has over 1 Billion users daily` Fact 2: Owls don't sleep at night What I want is to get one fact per line like this: Fact 1: YouTube has over 1 Billion users daily Fact 2: Owls don't sleep at night I tried using strip() like with open("facts.txt", 'r'...
[ "Assuming the file's content is always in that form:\n\nSplit lines with 1 '\\n'\nJoin back the list with 1 space (' ')\nReplace converted 3 spaces (' ') to 1 '\\n'\n\nwith open('facts.txt') as f:\n lines = f.read()\n print(' '.join(lines.split('\\n')).replace(' ', '\\n'))\n\nOr:\nwith open('facts.txt') a...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074572865_python.txt
Q: Efficient procedure to fill in a dataframe (recoding code with lists to use ndarrays) I am trying to calculate some function results using predefined parameters that are generated before and stored in lists. But I need to recode this solution to save all results to a dataframe of appropriate structure, where each ...
Efficient procedure to fill in a dataframe (recoding code with lists to use ndarrays)
I am trying to calculate some function results using predefined parameters that are generated before and stored in lists. But I need to recode this solution to save all results to a dataframe of appropriate structure, where each row contain next parameters: E | number_of_iteration | result The actual mapping is like t...
[ "Putting some random data together according to your description, and running the code you provided:\nfrom random import random\n\n\ndef _3gaussian(x, *y):\n return x * sum([*y]) # some arbitrary value, not relevant to the question\n\n\nn = 10 # size is arbitrary, scale up to see performance impacts\nm = 20\nn...
[ 0, 0 ]
[]
[]
[ "dataframe", "performance", "python" ]
stackoverflow_0074552765_dataframe_performance_python.txt
Q: Tkinter GUI with progress bar I have a simple Tk GUI and a long process in a function attached to a button. I want a progress bar when I click on the button, just like it starts a long process. How can I do that? This is my current code: from tkinter import Button, Tk, HORIZONTAL from tkinter.ttk import Progressb...
Tkinter GUI with progress bar
I have a simple Tk GUI and a long process in a function attached to a button. I want a progress bar when I click on the button, just like it starts a long process. How can I do that? This is my current code: from tkinter import Button, Tk, HORIZONTAL from tkinter.ttk import Progressbar import time class MonApp(Tk): ...
[ "You can find ttk.Progressbar at tkdocs\nimport time\nfrom tkinter import *\nfrom tkinter.ttk import *\n\ntk = Tk()\nprogress = Progressbar(tk, orient=HORIZONTAL, length=100, mode='determinate')\n\n\ndef bar():\n progress['value'] = 20\n tk.update_idletasks()\n time.sleep(1)\n progress['value'] = 50\n ...
[ 30, 3, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0033768577_python_tkinter.txt
Q: Deleting a target folder in many subfolders with python i have a folder X with many (over 500) subfolders in it. In those subfolders there is sometimes a subfolder TARGET that i want to delete. I was considering using a script for doing this. i am not python expert but i tried to make this script, before using it ...
Deleting a target folder in many subfolders with python
i have a folder X with many (over 500) subfolders in it. In those subfolders there is sometimes a subfolder TARGET that i want to delete. I was considering using a script for doing this. i am not python expert but i tried to make this script, before using it risking to lose files i'd need, can you please check if it is...
[ "Here it is, I fixed your code and made it a bit more useful so anyone can use it :) enjoy\n#coded by antoclk @ antonioaunix@gmail.com\nimport os\nimport shutil\n\n#in dir variable you should put the path you need to scan\ndir = '/Users/YOURUSERNAME/Desktop/main' \n#in target variable you should put the exact name ...
[ 1, 0 ]
[]
[]
[ "directory", "operating_system", "python", "shell" ]
stackoverflow_0069658310_directory_operating_system_python_shell.txt
Q: Difference between histogram and pandas value_count() I suppose both the pandas value_counts() and histogram gives the frequency of an item. I have a case where this is different. When I plot a histogram, I get two peaks as shown below, d = pd.read_csv('sample.csv') d.hist() d['value'].value_counts().nlargest(3) ...
Difference between histogram and pandas value_count()
I suppose both the pandas value_counts() and histogram gives the frequency of an item. I have a case where this is different. When I plot a histogram, I get two peaks as shown below, d = pd.read_csv('sample.csv') d.hist() d['value'].value_counts().nlargest(3) 200000000.0 906 20.0 219 10.0 158 N...
[ "A histogram, gives you the counts over bins. This means the count/frequency of consecutive groups of values.\ndf['value'].plot.hist()\n\n\nThe (approximate) equivalent using a bar graph, would be to first compute bins with pandas.cut:\npd.cut(df['value'], bins=10).value_counts(sort=False).plot.bar()\n\n\nOutput of...
[ 1, 0 ]
[]
[]
[ "histogram", "pandas", "python" ]
stackoverflow_0074573878_histogram_pandas_python.txt
Q: Apply function to each cell in a row, based on another cell For example, I have the following: . a b benchmark 0 1 2 1 1 1 5 3 and I would like to apply a condition in Pandas for each column as: def f(x): if x > benchmark: # X being the values of a or b return x else: return 0 But I don't know...
Apply function to each cell in a row, based on another cell
For example, I have the following: . a b benchmark 0 1 2 1 1 1 5 3 and I would like to apply a condition in Pandas for each column as: def f(x): if x > benchmark: # X being the values of a or b return x else: return 0 But I don't know how to do that. If I did df.apply(f) I can't access ot...
[ "You don't need a function, instead use vectorial operations:\nout = df.where(df.gt(df['benchmark'], axis=0), 0)\n\nTo change the values in place:\ndf[df.le(df['benchmark'], axis=0)] = 0\n\nOutput:\n a b benchmark\n0 0 2 0\n1 0 5 0\n\nIf you don't want to affect benchmark:\nm = df.le(df['b...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074574018_dataframe_pandas_python.txt
Q: how to check membership of keys and values a dictionaries in python with user defined function something like this but in a defined function # Check if a key exists in a dictionary info = {'Breakfast': 'Egg', 'time' :'05:30 am'} if 'lunch' in info.keys(): print('Exists!') else: print("Doesn't exist!") A:...
how to check membership of keys and values a dictionaries in python with user defined function
something like this but in a defined function # Check if a key exists in a dictionary info = {'Breakfast': 'Egg', 'time' :'05:30 am'} if 'lunch' in info.keys(): print('Exists!') else: print("Doesn't exist!")
[ "Here's a one liner:\ndef key_in_dict(d, key):\n return 'Exists!' if key in d else \"Doesn't exist!\"\n\n" ]
[ 0 ]
[]
[]
[ "defined", "function", "python", "user_defined_functions" ]
stackoverflow_0074574004_defined_function_python_user_defined_functions.txt
Q: extract value from previous df to new df based on column criteria extract value from previous df (df1) to new df(df2) based on the corresponding criteria of DATE and symbol in df2 in shorter way. I usually transform df1 structure use pd.melt, then use pd.merge to merge with df2. I want to do it in shorter way sinc...
extract value from previous df to new df based on column criteria
extract value from previous df (df1) to new df(df2) based on the corresponding criteria of DATE and symbol in df2 in shorter way. I usually transform df1 structure use pd.melt, then use pd.merge to merge with df2. I want to do it in shorter way since I have many dfs. any link reference or suggestion? many thanks in adv...
[ "This is a variant on an indexing lookup, using a reindexing of df1:\nidx, cols = pd.factorize(df2['symbol'])\n\ndf2['desired output'] = (\n df1.set_index('DATE')\n .reindex(index=df2['DATE'],\n columns=cols)\n .to_numpy()\n)[np.arange(len(df1)), idx]\n\nAnother approach (probably less efficient) ...
[ 1 ]
[]
[]
[ "merge", "pandas", "python" ]
stackoverflow_0074574102_merge_pandas_python.txt
Q: manage.py runserver python not found I'm trying to learn django and I'm almost completely new to python, I'm using pycharm btw. My problem is that when i try to type python manage.py runserver in the PyCharm terminal it just tells me that Python was not found. I have already tried to reinstall python and add it t...
manage.py runserver python not found
I'm trying to learn django and I'm almost completely new to python, I'm using pycharm btw. My problem is that when i try to type python manage.py runserver in the PyCharm terminal it just tells me that Python was not found. I have already tried to reinstall python and add it to system variables.
[ "You must configure your PyCharm path to show where is interpreter of Python on your PC.\nhttps://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html\n" ]
[ 0 ]
[]
[]
[ "django", "django_runserver", "manage.py", "python" ]
stackoverflow_0074574139_django_django_runserver_manage.py_python.txt
Q: IB_insync - Sanic error after one successful order preventing any further orders I'm writing an API using ib_insync, Sanic and ngrok to forward webhook signals from Tradingview onto Interactive Brokers. It works on only the first attempt and the following error is thrown preventing any further orders: [ERROR] Exc...
IB_insync - Sanic error after one successful order preventing any further orders
I'm writing an API using ib_insync, Sanic and ngrok to forward webhook signals from Tradingview onto Interactive Brokers. It works on only the first attempt and the following error is thrown preventing any further orders: [ERROR] Exception occurred while handling uri: 'http://url.ngrok.io/webhook' Traceback (most rece...
[ "You are seeing this error because you have forgotten to send a response to the first POST request. All HTTP requests need a corresponding response, even if it is just for triggering an action.\nIe, change your webhook code to this:\n@app.route('/webhook', methods=['POST'])\nasync def webhook(request):\n if requ...
[ 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "interactive_brokers", "ngrok", "python", "sanic", "tradingview_api" ]
stackoverflow_0070560834_interactive_brokers_ngrok_python_sanic_tradingview_api.txt
Q: How to apply function to each block of a numpy array in python I have an n x m array and a function 'switch(A,J)' that takes array (A) and integer(J) input and outputs an array of size n x m. I wish to split my n x m array into arrays of dimension c x c and apply the function with a fixed J to each c x c array and...
How to apply function to each block of a numpy array in python
I have an n x m array and a function 'switch(A,J)' that takes array (A) and integer(J) input and outputs an array of size n x m. I wish to split my n x m array into arrays of dimension c x c and apply the function with a fixed J to each c x c array and output the resulting array.c may not be a factor of n or m. Would a...
[ "import numpy as np\narray = np.array([[1, 2, 3, 1], [4, 5, 6, 4], [7, 8, 9, 7], [11, 22, 33, 44]])\n\ndef somefunc(some_array, some_integer):\n return some_array*3\n# say that your blocks needs to be 2X2\nfor i in range(array.shape[0]):\n for j in range(array.shape[1]):\n array[i*2:(i+1)*2, j*2:(j+1)*...
[ 0, 0 ]
[]
[]
[ "matrix", "numpy", "numpy_slicing", "python", "python_3.x" ]
stackoverflow_0074573581_matrix_numpy_numpy_slicing_python_python_3.x.txt
Q: IndexError out of range in Python Hi I am hoping you could help me in this python error that i could not solve def remove_dots(string): lst = [] for i in range(len(string)): lst.append(string[i]) for i in range(len(lst)): if i <= len(lst): if lst[i] == ".": ...
IndexError out of range in Python
Hi I am hoping you could help me in this python error that i could not solve def remove_dots(string): lst = [] for i in range(len(string)): lst.append(string[i]) for i in range(len(lst)): if i <= len(lst): if lst[i] == ".": lst.remove(lst[i]) els...
[ "Lenght should <.\ndef remove_dots(string):\n lst = []\n\n for i in range(len(string)):\n lst.append(string[i])\n\n for i in range(len(lst)):\n\n if i< len(lst): \n\n if lst[i] == \".\":\n lst.remove(lst[i])\n\n else:\n continue\n\n nstri...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "if_statement", "list", "loops", "python" ]
stackoverflow_0074573955_if_statement_list_loops_python.txt
Q: How to split string to a list in Python I want this string: {"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"78cb7b69-bbfa-4d6c-8156-ada66201bf73","id_v1":"/sensors/22","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"4b16b918-485a-44de-82aa-4ff467f6591a","rtype":"device"},"type":"motion"}],"id":"...
How to split string to a list in Python
I want this string: {"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"78cb7b69-bbfa-4d6c-8156-ada66201bf73","id_v1":"/sensors/22","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"4b16b918-485a-44de-82aa-4ff467f6591a","rtype":"device"},"type":"motion"}],"id":"813e2ed1-f28e-451b-9ac6-9eef76ef7b4a","type":...
[ "Your input data looks like a json array but without the square brackets [].\nTrying to decode your input data into a json object -\nimport json\ndata = '''{\"creationtime\":\"2022-11-25T09:12:44Z\",\"data\":[{\"id\":\"78cb7b69-bbfa-4d6c-8156-ada66201bf73\",\"id_v1\":\"/sensors/22\",\"motion\":{\"motion\":true,\"mo...
[ 1, 1 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0074574135_python_split_string.txt
Q: Python ThreadPoolExecutor shutdown behaviour varies with where it's called from I've run two variants of code that, to me, should run exactly identically - so I'm very surprised to see different output from each... First up: from concurrent.futures import ThreadPoolExecutor from time import sleep executor = Threa...
Python ThreadPoolExecutor shutdown behaviour varies with where it's called from
I've run two variants of code that, to me, should run exactly identically - so I'm very surprised to see different output from each... First up: from concurrent.futures import ThreadPoolExecutor from time import sleep executor = ThreadPoolExecutor(max_workers=2) def func(x): print(f"In func {x}") sleep(1) ...
[ "This surprised me too. This code also reproduces your behaviour\nfrom concurrent.futures import ThreadPoolExecutor\nfrom time import sleep\n\n\ndef run_test():\n executor = ThreadPoolExecutor(max_workers=2)\n\n def func(x):\n print(f\"In func {x}\")\n sleep(1)\n\n foo = executor.map(func, ra...
[ 1 ]
[]
[]
[ "concurrency", "concurrent.futures", "python", "threadpoolexecutor" ]
stackoverflow_0074573019_concurrency_concurrent.futures_python_threadpoolexecutor.txt
Q: Multiple column sorting in multiindex dataframe I have the following dataframe: dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}}, 'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':10738}}} d1 = defaultdict(dict) for k, v in dic.items(): fo...
Multiple column sorting in multiindex dataframe
I have the following dataframe: dic = {'US':{'Traffic':{'new':1415, 'repeat':670}, 'Sales':{'new':67068, 'repeat':105677}}, 'UK': {'Traffic':{'new':230, 'repeat':156}, 'Sales':{'new':4568, 'repeat':10738}}} d1 = defaultdict(dict) for k, v in dic.items(): for k1, v1 in v.items(): for k2, v2 in v1.items...
[ "Your indexing is incorrect, use:\ndf.sort_values(by=[('', 'Mode'), ('', 'Symbol')], ascending=[False, True])\n\nOutput:\nSkateboard US UK \nQ3 Mode Symbol new repeat new repeat\nSales 5 1 67068 105677 4568 10738\nTraffic 0 2 1415 670 ...
[ 1 ]
[]
[]
[ "columnsorting", "dataframe", "pandas", "python" ]
stackoverflow_0074574281_columnsorting_dataframe_pandas_python.txt
Q: Running Docplex package in Python "docplex.mp.utils.DOcplexException: Cannot solve model: no CPLEX runtime found" I wanted to solve my Oprimization model in Python by Cplex so I installed Cplex in my system (Windows 11) and based on Cplex help insttall setup.py with this command: python C:\Program Files\IBM\ILOG\C...
Running Docplex package in Python "docplex.mp.utils.DOcplexException: Cannot solve model: no CPLEX runtime found"
I wanted to solve my Oprimization model in Python by Cplex so I installed Cplex in my system (Windows 11) and based on Cplex help insttall setup.py with this command: python C:\Program Files\IBM\ILOG\CPLEX_Studio221\python\setup.py install There are two examples in IBM "Docplex.cp" and "Docplex.mp". I run these example...
[ "what you followed (setup.py) is in documentation\nCPLEX > CPLEX Optimizers > Getting Started with CPLEX > Tutorials > Python tutorial\nand this sets the matrix python api but you want to use the other python interface (docplex)\nYou should follow\nhttp://ibmdecisionoptimization.github.io/docplex-doc/mp/getting_st...
[ 0, 0 ]
[]
[]
[ "docplex", "linear_programming", "optimization", "python", "visual_studio_code" ]
stackoverflow_0074567332_docplex_linear_programming_optimization_python_visual_studio_code.txt
Q: For Loop overwrites previous iteration I try to extract the second frame of every video in a video list and save every frame as a single individual image file. frame_no = 2 dir_list = ['a', 'b'] dir_lust_full = ['C:/User/video/a.mp4','c:/User/video/b.mp4'] # Loop currently overwrites each iteration. for i in l...
For Loop overwrites previous iteration
I try to extract the second frame of every video in a video list and save every frame as a single individual image file. frame_no = 2 dir_list = ['a', 'b'] dir_lust_full = ['C:/User/video/a.mp4','c:/User/video/b.mp4'] # Loop currently overwrites each iteration. for i in list(dir_list_full): cap = cv2.VideoCapt...
[ "Probably you want to do something like that:\nframe_no = 2\ndir_list_source = [\"C:/User/video/a.mp4\", \"c:/User/video/b.mp4\"]\ndir_list_target = [\"a\", \"b\"]\n\nfor i in range(len(dir_list_source)): \n cap = cv2.VideoCapture(dir_list_source[i])\n\n if not cap.isOpened():\n print(f\"Cannot open {d...
[ 0 ]
[]
[]
[ "file", "for_loop", "path", "python" ]
stackoverflow_0074572731_file_for_loop_path_python.txt
Q: Visual Studio Code quick-fix & python Visual Studio Code is never able to populate the 'Quick Fix' contextual drop down, only displaying 'No Code Actions Available' Python extension is installed, along with python3.7.3 and flake8, pep8. A: The Python extension for VS Code currently doesn't offer any quick fixes....
Visual Studio Code quick-fix & python
Visual Studio Code is never able to populate the 'Quick Fix' contextual drop down, only displaying 'No Code Actions Available' Python extension is installed, along with python3.7.3 and flake8, pep8.
[ "The Python extension for VS Code currently doesn't offer any quick fixes.\n", "Python extension started to support Quick Fix.\nFirst, function adding imports is supported.\nPython in Visual Studio Code – November 2019 Release | Python\nHowever\nPython extension ver.2020.1.58038 and 2020.1.57204 have bug that it ...
[ 15, 3, 3, 0, 0, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0055582277_python_visual_studio_code.txt
Q: Python; Cant import module from other directory I am trying to decompose my program on python. I have read a lot of information and other answers about how import works, but still cant understand how exactly. I want to use my module Graph.Graph2D for implementation in InteractiveGraph2D. Before importing it, I add...
Python; Cant import module from other directory
I am trying to decompose my program on python. I have read a lot of information and other answers about how import works, but still cant understand how exactly. I want to use my module Graph.Graph2D for implementation in InteractiveGraph2D. Before importing it, I add path to this module. But it tells NameError: name 'G...
[ "You say that the modules path is ~/MyData/Python/Pygame/MY_MODULES/Graph while in the python code you added the string '/home/rayxxx/MyData/Python/MY_MODULES' to the os.path. Maybe the point is this\n", "this is a common error, when you run a python script it looks at the dir where you are running the script so ...
[ 1, 1, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0074574072_import_module_python.txt
Q: Python HTTPS requests slow with openssl 3 I updated from Ubuntu 20.04 to 22.04 and now all my python scripts with HTTPS requests are much slower than before (0.7 sec vs. ~2 sec). import requests import threading import time def req(): r = requests.get('https://www.google.com/') for i in range(10): thre...
Python HTTPS requests slow with openssl 3
I updated from Ubuntu 20.04 to 22.04 and now all my python scripts with HTTPS requests are much slower than before (0.7 sec vs. ~2 sec). import requests import threading import time def req(): r = requests.get('https://www.google.com/') for i in range(10): thread_amount = 50 threads = [] s = time.t...
[ "try disabling the verification of the SSL certificate (this should increase loading times) (also this works with the latest version of OpenSSL\ndef req():\n r = requests.get('https://www.google.com/', verify=False)\n\n" ]
[ 0 ]
[]
[]
[ "openssl", "python", "python_requests", "ubuntu_22.04" ]
stackoverflow_0074574427_openssl_python_python_requests_ubuntu_22.04.txt
Q: Problems implementing a wrapper-program for the camera remote sdk by sony so... I am trying to create a wrapper program for the new Sony Camera Remote SDK listed on their website. I was able to get a few functions to work. See below: import ctypes from ctypes import * from sys import platform shared_lib_path = r"...
Problems implementing a wrapper-program for the camera remote sdk by sony
so... I am trying to create a wrapper program for the new Sony Camera Remote SDK listed on their website. I was able to get a few functions to work. See below: import ctypes from ctypes import * from sys import platform shared_lib_path = r"CrSDK_v1.05.00_20211207a_Linux64ARMv8/external/crsdk/libCr_Core.so" if platfor...
[ "I am late to the party, but I am working to with a RX0-MII. I tried to work a bit to write a python wrapper and I couldn't. Based on the discussion Python wrapper for C++ class (when only \".h\" and \".dll\" files are available), I would say that is not possible directly due to absence of any C-linkage in some of...
[ 0 ]
[]
[]
[ "ctypes", "ffi", "python", "sdk", "sony_camera_api" ]
stackoverflow_0073442612_ctypes_ffi_python_sdk_sony_camera_api.txt
Q: str.replace backslash with forward slash I would like to replace the backslash \ in a windows path with forward slash / using python. Unfortunately I'm trying from hours but I cannot solve this issue.. I saw other questions here but still I cannot find a solution Can someone help me? This is what I'm trying: path ...
str.replace backslash with forward slash
I would like to replace the backslash \ in a windows path with forward slash / using python. Unfortunately I'm trying from hours but I cannot solve this issue.. I saw other questions here but still I cannot find a solution Can someone help me? This is what I'm trying: path = "\\ftac\admin\rec\pir" path = path.replace("...
[ "Oh boy, this is a bit more complicated than first appears.\nYour problem is that you have stored your windows paths as normal strings, instead of raw strings. The conversion from strings to their raw representation is lossy and ugly.\nThis is because when you make a string like \"\\a\", the intperter sees a specia...
[ 0 ]
[]
[]
[ "path", "python", "string" ]
stackoverflow_0074574222_path_python_string.txt
Q: Install package in grater version with string in name I have a problem do add to requirements.txt package with string in version and install this in grater version. I need this to development process when i push commit i create a new package and on main project i can update them by: pip install -r .\requirements.t...
Install package in grater version with string in name
I have a problem do add to requirements.txt package with string in version and install this in grater version. I need this to development process when i push commit i create a new package and on main project i can update them by: pip install -r .\requirements.txt without manually changing version. The version name look...
[ "Ok i had a bug in my setup.py\nWhen number is in schema: branch_name.version_number.build_number work as i expect.\n" ]
[ 0 ]
[]
[]
[ "python", "python_packaging", "setuptools" ]
stackoverflow_0074571741_python_python_packaging_setuptools.txt
Q: Django: Too many open client connections I am using Django on EC2 server. After a while, the number of open connections with clients increases to a very high number (>500) (I find the number using command "sudo lsof -i :8919 | wc -l"). Now, this is not easily reproducible, but I see that when the server this happe...
Django: Too many open client connections
I am using Django on EC2 server. After a while, the number of open connections with clients increases to a very high number (>500) (I find the number using command "sudo lsof -i :8919 | wc -l"). Now, this is not easily reproducible, but I see that when the server this happens, I see requests coming in, but no response ...
[ "As mentioned here, you can disable debug mode. Also you can add CONN_MAX_AGE to persist connections.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0038840225_django_python.txt
Q: How to prevent IP blocking while scraping data I was trying to scrape data from a website. The code is working but the site blocks my IP address when I was trying to scrape all scrolling pages. Please let me know if there is any suggestions on how to solve this problem. Thanks A: You could use proxies. Ip-addres...
How to prevent IP blocking while scraping data
I was trying to scrape data from a website. The code is working but the site blocks my IP address when I was trying to scrape all scrolling pages. Please let me know if there is any suggestions on how to solve this problem. Thanks
[ "You could use proxies.\nIp-addresses can be bought very cheaply then you can iterate through a list of IP-addresses while simultaneously varying your browser and other user agent parameters.\n", "When first starting out with a web scraper, a common mistake is to send a request directly to the website (using a co...
[ 0, 0 ]
[]
[]
[ "json", "python", "request", "selenium" ]
stackoverflow_0067010968_json_python_request_selenium.txt
Q: Python: If any variable in list exists, then print the item I have a list of 0s, named "variables". One of the 0s will become -1 spontaneously, and I'm trying to print the element which does. For example, this is my code: while True: if any(variables): print(variables[i]) Now, obviously "i" doesn't ...
Python: If any variable in list exists, then print the item
I have a list of 0s, named "variables". One of the 0s will become -1 spontaneously, and I'm trying to print the element which does. For example, this is my code: while True: if any(variables): print(variables[i]) Now, obviously "i" doesn't correlate to anything, but I'd like it to represent the index of ...
[ "Try\nprint(list(filter(lambda x: x==-1, variables)))\n\n", "Do you want to get the index? Outputting the element would be equal to just writing print(-1)\nprint (variables.index(-1))\n\n", "Printing the element would just give you -1.\nYou can loop through the list:\nfor e in variables:\n if e != 0:\n ...
[ 0, 0, 0 ]
[]
[]
[ "any", "if_statement", "list", "python" ]
stackoverflow_0074574438_any_if_statement_list_python.txt
Q: Testing messages when using RequestFactory() I am testing a class based view using mock to raise an exception. On exception, a message should be created and then a redirect executed. Whilst I am able to test that the redirect has been executed, I am unable as yet to retrieve the message to be able to verify it. vi...
Testing messages when using RequestFactory()
I am testing a class based view using mock to raise an exception. On exception, a message should be created and then a redirect executed. Whilst I am able to test that the redirect has been executed, I am unable as yet to retrieve the message to be able to verify it. view CustomUser = get_user_model() class SignUpView...
[ "After digging a little deeper the message(s) can be found here:\nrequest._messages._queued_messages[0]\n\nAnd therefore the assertEqual would be:\nself.assertEqual(str(request._messages._queued_messages[0]), 'Something went wrong, please try to register again')\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_testing", "mocking", "python" ]
stackoverflow_0074574415_django_django_forms_django_testing_mocking_python.txt
Q: [python-selenium 4.3.0]How to get element by text under tag a? i would like to get the element and click on it by the text under tag a: <a href="https://www.presidency.ucsb.edu/ws/index.php?pid=29433">1791</a> The text "1791" is what I used to locate this element and click on it. My code looks like this: driver.f...
[python-selenium 4.3.0]How to get element by text under tag a?
i would like to get the element and click on it by the text under tag a: <a href="https://www.presidency.ucsb.edu/ws/index.php?pid=29433">1791</a> The text "1791" is what I used to locate this element and click on it. My code looks like this: driver.find_element(By.XPATH,("//div[text()='1791']")).click() and it does ...
[ "You are trying to click on the div with the text '1791'.\nBut in the provided info this text is inside a tag.\nTry the following:\ndriver.find_element(By.XPATH,(\"//a[text()='1791']\")).click()\n\nUPD\nExcept for the incorrect XPath the problem was in unused WebDriverWait for the element (the expectation for check...
[ 0 ]
[]
[]
[ "python", "selenium_webdriver" ]
stackoverflow_0074574360_python_selenium_webdriver.txt