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 = {} for w in word: letter_dic[w] = 0 for w in word: letter_dic[w] += 1 return letter_dic The method above should count all the occurrences of each letter in a given string Input: "leumooeeyzwwmmirbmf" Output: {'l': 1, 'e': 3, 'u': 1, 'm': 4, 'o': 2, 'y': 1, 'z': 1, 'w': 2, 'i': 1, 'r': 1, 'b': 1, 'f': 1} Is there a form of creating and filling the dictionary at the same time without using two loops? A: Yes it is! The most pythonic way would be to use the Counter from collections import Counter letter_dic = Counter(word) But there are other options, like with pure python: for w in word: if w not in letter_dic: letter_dic[w] = 0 letter_dic[w] += 1 Or with defaultdict. You pass one callable there and on first key access it will create the key with specific value: from collections import defaultdict letter_dic = defaultdict(int) for w in word: letter_dic[w] += 1 A: You can use dictionary comprehension, e.g. x = "leumooeeyzwwmmirbmf" y = {l: x.count(l) for l in x} A: You can use Counter from collections: from collections import Counter src = "leumooeeyzwwmmirbmf" print(dict(Counter(src)) gives expected {'l': 1, 'e': 3, 'u': 1, 'm': 4, 'o': 2, 'y': 1, 'z': 1, 'w': 2, 'i': 1, 'r': 1, 'b': 1, 'f': 1}
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 in word: letter_dic[w] += 1 return letter_dic The method above should count all the occurrences of each letter in a given string Input: "leumooeeyzwwmmirbmf" Output: {'l': 1, 'e': 3, 'u': 1, 'm': 4, 'o': 2, 'y': 1, 'z': 1, 'w': 2, 'i': 1, 'r': 1, 'b': 1, 'f': 1} Is there a form of creating and filling the dictionary at the same time without using two loops?
[ "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 callable there and on first key access it will create the key with specific value:\nfrom collections import defaultdict\n\nletter_dic = defaultdict(int)\nfor w in word:\n letter_dic[w] += 1\n\n", "You can use dictionary comprehension, e.g.\nx = \"leumooeeyzwwmmirbmf\"\ny = {l: x.count(l) for l in x}\n\n", "You can use Counter from collections:\nfrom collections import Counter\nsrc = \"leumooeeyzwwmmirbmf\"\nprint(dict(Counter(src))\n\ngives expected\n{'l': 1, 'e': 3, 'u': 1, 'm': 4, 'o': 2, 'y': 1, 'z': 1, 'w': 2, 'i': 1, 'r': 1, 'b': 1, 'f': 1}\n\n" ]
[ 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_site\todo\views.py, line 15, in todo_details 15. todo = Todo.objects.get(id=id) Code views.py def todo_details(request, id): todo = Todo.objects.get(id=id) context = { "todo": todo } return render(request, "todo/todo_details.html", context) def todo_create(request): todo = Todo.objects.get(id=id) form =TodoForm(request.POST or None) if form.is_valid(): form.save() return redirect('/') context = {"form": form} return render(request, "todo/todo_create.html", context) 0001_initial.py operations = [ migrations.CreateModel( name='Todo', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('due_date', models.DateField()), ], ), ] urls files is hear app_name = 'todos' urlpatterns = [ path("", views.todo_list), path('<id>/', views.todo_details), path('create/', views.todo_create), path('delete/', views.todo_delete), ] templates files are hear todo_detail.html {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Todo Details</title> </head> <body> {% if request.user.is_authenticated %} Hello {{ request.user.username }} {% else %} Hello anonymous user {% endif %} The todo name is :- {{ todo.name }} The due date is :- {{ todo.due_date }} <h1>Hello</h1> </body> </html> todo_create {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Todo Create</title> </head> <body> <h4>Create a todo</h4> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" name="button">submit</button> </form> </body> </html> A: In your views.py try send the id into function; def todo_create(request,id): A: in urls instead of this path('create/', views.todo_create), add this path('create/<int:id>', views.todo_create), in views def todo_create(request): to def todo_create(request,id):
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. todo = Todo.objects.get(id=id) Code views.py def todo_details(request, id): todo = Todo.objects.get(id=id) context = { "todo": todo } return render(request, "todo/todo_details.html", context) def todo_create(request): todo = Todo.objects.get(id=id) form =TodoForm(request.POST or None) if form.is_valid(): form.save() return redirect('/') context = {"form": form} return render(request, "todo/todo_create.html", context) 0001_initial.py operations = [ migrations.CreateModel( name='Todo', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('due_date', models.DateField()), ], ), ] urls files is hear app_name = 'todos' urlpatterns = [ path("", views.todo_list), path('<id>/', views.todo_details), path('create/', views.todo_create), path('delete/', views.todo_delete), ] templates files are hear todo_detail.html {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Todo Details</title> </head> <body> {% if request.user.is_authenticated %} Hello {{ request.user.username }} {% else %} Hello anonymous user {% endif %} The todo name is :- {{ todo.name }} The due date is :- {{ todo.due_date }} <h1>Hello</h1> </body> </html> todo_create {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Todo Create</title> </head> <body> <h4>Create a todo</h4> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" name="button">submit</button> </form> </body> </html>
[ "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. │ exit code: 1 ╰─> [13 lines of output] Traceback (most recent call last): File "/private/var/folders/bb/30cx945s3g9ftgw4q18zyw900000gn/T/pip-install-ll7ks8fq/secrets_1a6d2e6558c34836a716331c20614163/setup.py", line 10, in <module> import OpenSSL ModuleNotFoundError: No module named 'OpenSSL' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/private/var/folders/bb/30cx945s3g9ftgw4q18zyw900000gn/T/pip-install-ll7ks8fq/secrets_1a6d2e6558c34836a716331c20614163/setup.py", line 12, in <module> raise ImportError('Installing this module requires OpenSSL python bindings') ImportError: Installing this module requires OpenSSL python bindings [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. The last note leads me to believe that it is to do with the library itself. A: 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. Install them with pip install cryptography and try again. EDIT: Python 3.11 is like a few days old. If it does not work you can also try to downscale to 3.10 or 3.9 as the packages is probably not supported yet in 3.11.
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] Traceback (most recent call last): File "/private/var/folders/bb/30cx945s3g9ftgw4q18zyw900000gn/T/pip-install-ll7ks8fq/secrets_1a6d2e6558c34836a716331c20614163/setup.py", line 10, in <module> import OpenSSL ModuleNotFoundError: No module named 'OpenSSL' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/private/var/folders/bb/30cx945s3g9ftgw4q18zyw900000gn/T/pip-install-ll7ks8fq/secrets_1a6d2e6558c34836a716331c20614163/setup.py", line 12, in <module> raise ImportError('Installing this module requires OpenSSL python bindings') ImportError: Installing this module requires OpenSSL python bindings [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. The last note leads me to believe that it is to do with the library itself.
[ "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 try to downscale to 3.10 or 3.9 as the packages is probably not supported yet in 3.11.\n" ]
[ 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.QKeyEvent) -> None: """Variant A: Top""" super().__init__(event) # my code def mousePressEvent(self, event: QtGui.QMouseEvent) -> None: """Variant B: Bottom""" # my code super().__init__(event) def showEvent(self, event: QtGui.QShowEvent) -> None: """Variant C: Without""" # my code ... I'm asking this, because I noticed that in my grown code I have all three variants, and I don't notice anything not working or any difference. Are there any general rules or best practices I could/should follow? A: 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. For example: class MyWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) # ....... everything else In my experience, there shouldn't be any need for it to be called in any other method other than the constructor. Since your examples are all dealing with events, you might actually be referring to other superclass methods. For example if your widget handles an event, but you would still like to have the even propogated to it's parents then you would call the super().eventmethodname(args). For example: def mousePressEvent(self, event: QtGui.QMouseEvent) -> None: """Variant B: Bottom""" # ... your code here super().mousePressEvent(event)
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) # my code def mousePressEvent(self, event: QtGui.QMouseEvent) -> None: """Variant B: Bottom""" # my code super().__init__(event) def showEvent(self, event: QtGui.QShowEvent) -> None: """Variant C: Without""" # my code ... I'm asking this, because I noticed that in my grown code I have all three variants, and I don't notice anything not working or any difference. Are there any general rules or best practices I could/should follow?
[ "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 def __init__(self, parent=None):\n super().__init__(parent)\n # ....... everything else\n\nIn my experience, there shouldn't be any need for it to be called in any other method other than the constructor.\nSince your examples are all dealing with events, you might actually be referring to other superclass methods. For example if your widget handles an event, but you would still like to have the even propogated to it's parents then you would call the super().eventmethodname(args).\nFor example:\ndef mousePressEvent(self, event: QtGui.QMouseEvent) -> None:\n \"\"\"Variant B: Bottom\"\"\"\n # ... your code here\n super().mousePressEvent(event)\n\n" ]
[ 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 from turtle import * #background Screen().bgcolor("orange") #player pl = Turtle() pl.color('dodgerblue') pl.shape('turtle') pl.penup() def turnleft(): player.left(30) turtle.listen() onkeypress(turnleft, "Left") speed = 1 while True: pl.forward(speed) A: When you do from turtle import * it imports everything into the built-in namespace, i.e., you can then just do: listen() rather than turtle.listen() If you had just done import turtle then everything in the turtle package would then be accessed through the turtle namespace, i.e., turtle.listen() A: You have plenty of mistakes here, totally normal because you are so new, that's the way to get better. I will ""arrange"" a bit your code. import turtle #background turtle.Screen().bgcolor("orange") #player pl = turtle.Turtle() pl.color('dodgerblue') pl.shape('turtle') pl.penup() def turnleft(): pl.left(30) turtle.listen() turtle.onkeypress(turnleft, "Left") speed = 1 while True: pl.forward(speed) First of all i recommend you to check in google what is "OOP" and check how it works on Python. When you use "functions" from a module (in this case turtle) , you need to call first the module and after the function for example: turtle.onkeypress(turnleft, "Left") # Instead onkeypress(turnleft,"Left") Another thing it's in your function "turnleft" you call the variable "player", but "player" doesnt exist, you want to call "pl". Good luck with your small new projects, keep trying.
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("orange") #player pl = Turtle() pl.color('dodgerblue') pl.shape('turtle') pl.penup() def turnleft(): player.left(30) turtle.listen() onkeypress(turnleft, "Left") speed = 1 while True: pl.forward(speed)
[ "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", "You have plenty of mistakes here, totally normal because you are so new, that's the way to get better.\nI will \"\"arrange\"\" a bit your code.\nimport turtle\n\n#background\nturtle.Screen().bgcolor(\"orange\")\n\n#player\npl = turtle.Turtle()\npl.color('dodgerblue')\npl.shape('turtle')\npl.penup()\n\ndef turnleft():\n pl.left(30)\n\nturtle.listen()\nturtle.onkeypress(turnleft, \"Left\")\n\nspeed = 1\nwhile True:\n pl.forward(speed)\n\nFirst of all i recommend you to check in google what is \"OOP\" and check how it works on Python.\nWhen you use \"functions\" from a module (in this case turtle) , you need to call first the module and after the function for example:\nturtle.onkeypress(turnleft, \"Left\")\n# Instead\nonkeypress(turnleft,\"Left\")\n\nAnother thing it's in your function \"turnleft\" you call the variable \"player\", but \"player\" doesnt exist, you want to call \"pl\".\nGood luck with your small new projects, keep trying.\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=True) author_instance = models.ForeignKey(AuthorInstance, on_delete=models.PROTECT) status_draft = models.BooleanField(default=False, blank=True, null=True) status_publish = models.BooleanField(default=False, blank=True, null=True) likes = models.ManyToManyField(UserInstance, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') def total_likes(self): return self.likes.count() views.py def like_post(request): post = get_object_or_404(Blog, id=request.POST.get('blog_id')) how to solve???? A: views should be like def like_post(request,id): post = get_object_or_404(Blog, id=request.POST.get('blog_id'))
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(AuthorInstance, on_delete=models.PROTECT) status_draft = models.BooleanField(default=False, blank=True, null=True) status_publish = models.BooleanField(default=False, blank=True, null=True) likes = models.ManyToManyField(UserInstance, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') def total_likes(self): return self.likes.count() views.py def like_post(request): post = get_object_or_404(Blog, id=request.POST.get('blog_id')) how to solve????
[ "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 environment. I know that in settings.json, I can specify a python.pythonPath setting, which I have done and is pointing to a virtual environment. I also know that I can add additional paths to python.autoComplete.extraPaths, where thus far I am adding the external libraries. The problem is, when I am debugging, it's failing because it's not finding the libraries specified in python.autoComplete.extraPaths. Is there another setting that must be used for this? Thanks A: This worked for me:- in your launch.json profile entry, specify a new entry called "env", and set PYTHONPATH yourself. "configurations": [ { "name": "Python", "type": "python", "stopOnEntry": false, "request": "launch", "pythonPath": "${config.python.pythonPath}", "program": "${file}", "cwd": "${workspaceRoot}", "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", "RedirectOutput" ], "env": { "PYTHONPATH": "/path/a:path/b" } } ] A: The Python Extension in VS Code has a setting for python.envFile which specifies the path to a file containing environment variable definitions (Refer to: https://code.visualstudio.com/docs/python/environments#_environment-variable-definitions-file). By default it is set to: "python.envFile": "${workspaceFolder}/.env" So to add your external libraries to the path, create a file named .env in your workspace folder and add the below line to it if you are using Windows: PYTHONPATH="C:\path\to\a;C:\path\to\b" The advantage of specifying the path here is that both the auto-complete as well as debugging work with this one setting itself. You may need to close and re-open VS Code for the settings to take effect. A: I had the same issue, malbs answer doesn't work for me until I change semicolon to a colon,you can find it from ZhijiaCHEN's comments "env": { "PYTHONPATH": "/path/to/a:/path/to/b" } Alternatively, I have a hack way to achieve the same: # at the top of project app script: import sys sys.path.append('/path/to/a') sys.path.append('/path/to/b') A: You could add a .pth file to your virtualenv's site-packages directory. This file should have an absotute path per line, for each module or package to be included in the PYTHONPATH. https://docs.python.org/2.7/install/index.html#modifying-python-s-search-path A: Based on https://github.com/microsoft/vscode-python/issues/12085, I added the following to the settings portion of the workspace config file. I'm using Linux. For Windows, use terminal.integrated.env.windows. "terminal.integrated.env.linux": { "PYTHONPATH": "addl-path-entry1:addl-path-entry2" } I also added an .env file as described by many posts/comments above. Finally, I added the PyLance extension per https://stackoverflow.com/a/64103291/11262633. I also reloaded my workspace. These two changes allowed me to run Python programs using the debugger and the Run menu. AutoComplete is aware of the added path, and my VSCode linter (was the default linter pylint, now ``pylance```) now works. A: I made it work through adding "python.analysis.extraPaths" when using Pylance and IntelliCode. A: bash escamotage (works with debugger AND autocomplete); need to install code command in PATH (vsc shell command: install...) #!/bin/bash # # vscode python setup # function fvscode { # you just want one of this: export PYTHONPATH=<your python installation ../bin/python3> # you may want many of these: export PYTHONPATH=<your lib dir here>:$PYTHONPATH # launch vscode code } alias vscode='fvscode' the launch VSC by typing 'vscode'. A: According to the environments doc, the places the extension looks for environments include some defaults and also the setting value for python.venvPath in the workspace settings eg: "python.venvPath": "~/.virtualenvs" This allows you to find several (eg: virtualenvs) as mentioned: To select a specific environment, use the Python: Select Interpreter command from the Command Palette A: In 2022, the configuration is as file .vscode/settings.json: { "python.analysis.extraPaths": ["C:/Program Files/obs-studio/data/obs-scripting/64bit"], "terminal.integrated.env.windows": { "PYTHONPATH": "C:/Program Files/obs-studio/data/obs-scripting/64bit;${env:PYTHONPATH}", "PATH": "C:/Program Files/obs-studio/data/obs-scripting/64bit;${env:PATH}" } }
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 setting, which I have done and is pointing to a virtual environment. I also know that I can add additional paths to python.autoComplete.extraPaths, where thus far I am adding the external libraries. The problem is, when I am debugging, it's failing because it's not finding the libraries specified in python.autoComplete.extraPaths. Is there another setting that must be used for this? Thanks
[ "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\": \"${config.python.pythonPath}\",\n \"program\": \"${file}\",\n \"cwd\": \"${workspaceRoot}\",\n \"debugOptions\": [\n \"WaitOnAbnormalExit\",\n \"WaitOnNormalExit\",\n \"RedirectOutput\"\n ],\n \"env\": {\n \"PYTHONPATH\": \"/path/a:path/b\"\n }\n }\n]\n\n", "The Python Extension in VS Code has a setting for python.envFile which specifies the path to a file containing environment variable definitions (Refer to: https://code.visualstudio.com/docs/python/environments#_environment-variable-definitions-file). By default it is set to:\n\"python.envFile\": \"${workspaceFolder}/.env\"\n\nSo to add your external libraries to the path, create a file named .env in your workspace folder and add the below line to it if you are using Windows:\nPYTHONPATH=\"C:\\path\\to\\a;C:\\path\\to\\b\"\n\nThe advantage of specifying the path here is that both the auto-complete as well as debugging work with this one setting itself. You may need to close and re-open VS Code for the settings to take effect.\n", "I had the same issue, malbs answer doesn't work for me until I change semicolon to a colon,you can find it from ZhijiaCHEN's comments \n\"env\": { \"PYTHONPATH\": \"/path/to/a:/path/to/b\" }\n\nAlternatively, I have a hack way to achieve the same:\n# at the top of project app script:\nimport sys\nsys.path.append('/path/to/a')\nsys.path.append('/path/to/b')\n\n", "You could add a .pth file to your virtualenv's site-packages directory.\nThis file should have an absotute path per line, for each module or package to be included in the PYTHONPATH.\nhttps://docs.python.org/2.7/install/index.html#modifying-python-s-search-path\n", "Based on https://github.com/microsoft/vscode-python/issues/12085, I added the following to the settings portion of the workspace config file. I'm using Linux. For Windows, use terminal.integrated.env.windows.\n\"terminal.integrated.env.linux\": {\n \"PYTHONPATH\": \"addl-path-entry1:addl-path-entry2\"\n}\n\nI also added an .env file as described by many posts/comments above.\nFinally, I added the PyLance extension per https://stackoverflow.com/a/64103291/11262633.\nI also reloaded my workspace.\nThese two changes allowed me to run Python programs using the debugger and the Run menu. AutoComplete is aware of the added path, and my VSCode linter (was the default linter pylint, now ``pylance```) now works.\n", "I made it work through adding \"python.analysis.extraPaths\" when using Pylance and IntelliCode.\n", "bash escamotage (works with debugger AND autocomplete); need to install code command in PATH (vsc shell command: install...)\n#!/bin/bash\n\n#\n# vscode python setup\n#\n\nfunction fvscode {\n # you just want one of this:\n export PYTHONPATH=<your python installation ../bin/python3>\n # you may want many of these:\n export PYTHONPATH=<your lib dir here>:$PYTHONPATH\n # launch vscode\n code \n}\nalias vscode='fvscode'\n\nthe launch VSC by typing 'vscode'.\n", "According to the environments doc, the places the extension looks for environments include some defaults and also the setting value for python.venvPath in the workspace settings\neg: \"python.venvPath\": \"~/.virtualenvs\"\nThis allows you to find several (eg: virtualenvs) as mentioned:\n\nTo select a specific environment, use the Python: Select Interpreter\n command from the Command Palette\n\n", "In 2022, the configuration is as file .vscode/settings.json:\n{\n \"python.analysis.extraPaths\": [\"C:/Program Files/obs-studio/data/obs-scripting/64bit\"],\n \"terminal.integrated.env.windows\": {\n \"PYTHONPATH\": \"C:/Program Files/obs-studio/data/obs-scripting/64bit;${env:PYTHONPATH}\",\n \"PATH\": \"C:/Program Files/obs-studio/data/obs-scripting/64bit;${env:PATH}\"\n }\n}\n\n" ]
[ 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 the best approach: if Entry.objects.filter(id=e.id).exists(): #do something A: The best approach, according to Django documentation: https://docs.djangoproject.com/en/2.1/ref/models/querysets/#exists if Entry.objects.filter(id=item.id).exists(): # Do something But you can also do: if item in Entry.objects.all(): # Do something Although this approach is the worser as possible. Because it will loop over the whole Queryset pulling elements from the database one by one, compared to the other approach that is almost everything done in the Database level. If you have a list of ids or a Queryset others approaches would be use __in Example with a Queryset: query_ids = other_queryset.values_list('field_id', flat=True) if Entry.objects.filter(id__in=query_ids).exists(): # Do something Or if you have a list of ids: if Entry.objects.filter(id__in=[1, 2, 3, 4, 5]).exists(): # Do something Keep in mind that every time that you do len(queryset), item in queryset or list(queryset) you decrees heavily the performance of Django. I already see cases where by avoiding this practices We improved dozens of seconds in an application. A: You can use in operator: entry_set = Entry.objects.all() if an_entry in entry_set: # The element present. A: in Django >= 4.0, contains(obj) is faster than the other methods. if some_queryset.contains(obj): print('Object entry is in queryset') This will be faster than the following which requires evaluating and iterating through the entire queryset: if obj in some_queryset: print('Object entry is in queryset')
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 Entry.objects.filter(id=item.id).exists():\n # Do something\n\nBut you can also do:\nif item in Entry.objects.all():\n # Do something\n\nAlthough this approach is the worser as possible. Because it will loop over the whole Queryset pulling elements from the database one by one, compared to the other approach that is almost everything done in the Database level.\nIf you have a list of ids or a Queryset others approaches would be use __in\nExample with a Queryset:\nquery_ids = other_queryset.values_list('field_id', flat=True)\nif Entry.objects.filter(id__in=query_ids).exists():\n # Do something\n\nOr if you have a list of ids:\nif Entry.objects.filter(id__in=[1, 2, 3, 4, 5]).exists():\n # Do something\n\nKeep in mind that every time that you do len(queryset), item in queryset or list(queryset) you decrees heavily the performance of Django. I already see cases where by avoiding this practices We improved dozens of seconds in an application.\n", "You can use in operator:\nentry_set = Entry.objects.all()\nif an_entry in entry_set:\n # The element present.\n\n", "in Django >= 4.0, contains(obj) is faster than the other methods.\nif some_queryset.contains(obj):\n print('Object entry is in queryset')\n\nThis will be faster than the following which requires evaluating and iterating through the entire queryset:\nif obj in some_queryset:\n print('Object entry is in queryset')\n\n" ]
[ 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 ':text'", {"text": '%' + query + '%'}).fetchall() but this gives me an empty array unfortunately. This gives me data but then im not using a variable which i need in this case. rows = cursor.execute(f"SELECT * FROM vragen WHERE vraag LIKE '%which%'").fetchall() Does anyone know an easy to way to solve this? Thanks for advance A: You shouldn't have quotes around :text: rows = cursor.execute(f"SELECT * FROM vragen WHERE vraag LIKE :text", {"text": '%' + query + '%'}).fetchall()
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 + '%'}).fetchall() but this gives me an empty array unfortunately. This gives me data but then im not using a variable which i need in this case. rows = cursor.execute(f"SELECT * FROM vragen WHERE vraag LIKE '%which%'").fetchall() Does anyone know an easy to way to solve this? Thanks for advance
[ "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 with the same Times New Roman font in italic style. plt.rcParams['mathtext.fontset'] = 'stix' plt.xlabel("Displacement ($\mathregular{\mathit{\AA}}$)",fontname="Times New Roman",fontsize=12) I can obtain the Angstrom symbol in italic style, but not same Times New Roman fontstyle (Even though I have applied the mathtext fontset stix). If I try this: plt.xlabel("Displacement ($\mathregular{\AA}$)",fontname="Times New Roman",fontsize=12) I can obtain the Angstrom symbol in Times New Roman, but not in Italic style... What should I change to achieve this? Thanks Picture of x-label: A: 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. import matplotlib.pyplot as plt plt.rcParams['mathtext.fontset'] = 'stix' plt.xlabel(r'Displacement ($\mathrm{\AA}$) ($\AA$)', fontname='STIXGeneral', fontsize=12) plt.show() Note that the ticks on the x-axis and y-axis still use the default font (DejaVu Sans). If you want to use Times New Roman for everything, just set the font.family parameter. import matplotlib.pyplot as plt plt.rcParams['mathtext.fontset'] = 'stix' plt.rcParams['font.family'] = 'STIXGeneral' plt.xlabel(r'Displacement ($\mathrm{\AA}$) ($\AA$)', fontsize=12) plt.show() Tested on Python 3.8.10 and 3.10.8.
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.rcParams['mathtext.fontset'] = 'stix' plt.xlabel("Displacement ($\mathregular{\mathit{\AA}}$)",fontname="Times New Roman",fontsize=12) I can obtain the Angstrom symbol in italic style, but not same Times New Roman fontstyle (Even though I have applied the mathtext fontset stix). If I try this: plt.xlabel("Displacement ($\mathregular{\AA}$)",fontname="Times New Roman",fontsize=12) I can obtain the Angstrom symbol in Times New Roman, but not in Italic style... What should I change to achieve this? Thanks Picture of x-label:
[ "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 ($\\mathrm{\\AA}$) ($\\AA$)', fontname='STIXGeneral', fontsize=12)\nplt.show()\n\n\nNote that the ticks on the x-axis and y-axis still use the default font (DejaVu Sans). If you want to use Times New Roman for everything, just set the font.family parameter.\nimport matplotlib.pyplot as plt\nplt.rcParams['mathtext.fontset'] = 'stix'\nplt.rcParams['font.family'] = 'STIXGeneral'\nplt.xlabel(r'Displacement ($\\mathrm{\\AA}$) ($\\AA$)', fontsize=12)\nplt.show()\n\n\nTested on Python 3.8.10 and 3.10.8.\n" ]
[ 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-jupyterhub-nb-user ~]$ TESTCMD2='python $SCRIPT' When I run this, I get an error. The Variable does not get evaluated. [user@smat-jupyterhub-nb-user ~]$ $TESTCMD2 python: can't open file '/jup/projects/$SCRIPT': [Errno 2] No such file or directory How can I make this variable being evaluated after being stored in a variable itself? A: That's because you used ' quotes, instead of " preventing variable substitution. $ FOO=echo $ BAR=bar $ XXX='${FOO} ${BAR}' $ $XXX ${FOO}: command not found $ XXX="${FOO} ${BAR}" $ $XXX bar In fact the last one should be rather $ XXX=""${FOO}" "${BAR}"" with variables additionally quoted in case any of their value contains space.
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, I get an error. The Variable does not get evaluated. [user@smat-jupyterhub-nb-user ~]$ $TESTCMD2 python: can't open file '/jup/projects/$SCRIPT': [Errno 2] No such file or directory How can I make this variable being evaluated after being stored in a variable itself?
[ "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 in case any of their value contains space.\n" ]
[ 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 = ('my_module__name__is_not=moduleidontwant',) A: You can simply overload get_queryset admin function and filter out items you do not want: class MyModuleAdmin(admin.ModelAdmin): list_display = ['name'] def get_queryset(self, request): queryset = super(MyModuleAdmin, self).get_queryset(request) return queryset.exclude(name='moduleidontwant') A: # custom_filters.py from django.contrib.admin import SimpleListFilter class testFilter(SimpleListFilter): """ This filter is being used in django admin panel in specified model.""" title = 'Title of you field' parameter_name = 'field_name' def queryset(self, request, queryset): if not self.value(): return queryset else: return queryset.filter(my_module__name__is_not='moduleidontwant') #add your filter here. Add this testFilter in your list_filter in admin.py file. # admin.py from django.contrib import admin from .models import * from .custom_filters import testFilter class MyModuleAdmin(admin.ModelAdmin): list_display = ['name'] list_filter = (testFilter) You can use this reference in case you get stuck in between https://www.dothedev.com/blog/django-admin-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='moduleidontwant')\n\n", "# custom_filters.py\nfrom django.contrib.admin import SimpleListFilter\n\nclass testFilter(SimpleListFilter):\n \"\"\" This filter is being used in django admin panel in specified model.\"\"\"\n title = 'Title of you field'\n parameter_name = 'field_name'\n \n def queryset(self, request, queryset):\n if not self.value():\n return queryset\n else:\n return queryset.filter(my_module__name__is_not='moduleidontwant') #add your filter here.\n\nAdd this testFilter in your list_filter in admin.py file.\n# admin.py\nfrom django.contrib import admin\nfrom .models import *\nfrom .custom_filters import testFilter\n\nclass MyModuleAdmin(admin.ModelAdmin):\n list_display = ['name']\n list_filter = (testFilter)\n\nYou can use this reference in case you get stuck in between\nhttps://www.dothedev.com/blog/django-admin-list_filter/\n" ]
[ 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-in-header: text: | \usepackage[font=small]{caption} \usepackage{float} \usepackage[table]{xcolor} engine: jupyter jupyter: r-reticulate --- \begin{center} \begin{tabular}{|c|c|} \hline 1 & 2\tabularnewline \hline \cellcolor{blue} 3 & \cellcolor{red} 4\tabularnewline \hline \end{tabular} \end{center} I get the following error, when rendering it: LaTeX Error: Option clash for package xcolor. See the LaTeX manual or LaTeX Companion for explanation. Type H <return> for immediate help. ... l.83 \KOMAoption {captions}{tableheading} A solution that works is to add table to the following line of the tex file generated by quarto: \PassOptionsToPackage{dvipsnames,svgnames,x11names}{xcolor} That is: \PassOptionsToPackage{dvipsnames,svgnames,x11names, table}{xcolor} My question is: How can I do that from inside the quarto document instead of hacking the tex file? A: 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. --- 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" classoption: table include-in-header: text: | \usepackage[font=small]{caption} \usepackage{float} --- \begin{center} \begin{tabular}{|c|c|} \hline 1 & 2\tabularnewline \hline \cellcolor{blue} 3 & \cellcolor{red} 4\tabularnewline \hline \end{tabular} \end{center}
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} \usepackage{float} \usepackage[table]{xcolor} engine: jupyter jupyter: r-reticulate --- \begin{center} \begin{tabular}{|c|c|} \hline 1 & 2\tabularnewline \hline \cellcolor{blue} 3 & \cellcolor{red} 4\tabularnewline \hline \end{tabular} \end{center} I get the following error, when rendering it: LaTeX Error: Option clash for package xcolor. See the LaTeX manual or LaTeX Companion for explanation. Type H <return> for immediate help. ... l.83 \KOMAoption {captions}{tableheading} A solution that works is to add table to the following line of the tex file generated by quarto: \PassOptionsToPackage{dvipsnames,svgnames,x11names}{xcolor} That is: \PassOptionsToPackage{dvipsnames,svgnames,x11names, table}{xcolor} My question is: How can I do that from inside the quarto document instead of hacking the tex file?
[ "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\n papersize: A4\n fig-pos: 'H'\n geometry: \"left=2.54cm,right=2.54cm,top=2.54cm,bottom=2.54cm\"\n classoption: table\n include-in-header:\n text: |\n \\usepackage[font=small]{caption}\n \\usepackage{float}\n---\n\n\\begin{center}\n\\begin{tabular}{|c|c|}\n\\hline \n1 & 2\\tabularnewline\n\\hline \n\\cellcolor{blue} 3 & \\cellcolor{red} 4\\tabularnewline\n\\hline \n\\end{tabular}\n\\end{center}\n\n\n\n\n" ]
[ 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":"Jaguar","seat_number":2,"category":"Animal Manager"}, {"name":"Cutiepie","seat_number":10,"category":"Streamer"}, {"name":"Hannah Bee","seat_number":11,"category":"Streamer"} ] I was thinking I could print only all the names by this print(list_names[:]["name"]) but it doesn't work...how can I do that? I just want to get all the list of names in dict. Is that possible or not? without using loops. A: You can do it with a list comprehension like : print([lst["name"] for lst in list_names]) A: You cannot iterate upon all items without looping through them , the shortest way is to use list comprehension , for name in [D['name'] for D in list_names]: print(name) A: Another approach is using itemgetter from operator module import operator 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":"Cutiepie","seat_number":10,"category":"Streamer"}, {"name":"Hannah Bee","seat_number":11,"category":"Streamer"} ] output_names = list(map(operator.itemgetter('name'), list_names))
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":"Cutiepie","seat_number":10,"category":"Streamer"}, {"name":"Hannah Bee","seat_number":11,"category":"Streamer"} ] I was thinking I could print only all the names by this print(list_names[:]["name"]) but it doesn't work...how can I do that? I just want to get all the list of names in dict. Is that possible or not? without using loops.
[ "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 itemgetter from operator module\nimport operator\n\nlist_names = [\n {\"name\":\"Jullemyth\",\"seat_number\":4,\"category\":\"Student\"},\n {\"name\":\"Leonhard\",\"seat_number\":1,\"category\":\"OFW\"},\n {\"name\":\"Scarion\",\"seat_number\":3,\"category\":\"Businessman\"},\n {\"name\":\"Jaguar\",\"seat_number\":2,\"category\":\"Animal Manager\"},\n {\"name\":\"Cutiepie\",\"seat_number\":10,\"category\":\"Streamer\"},\n {\"name\":\"Hannah Bee\",\"seat_number\":11,\"category\":\"Streamer\"}\n]\n\noutput_names = list(map(operator.itemgetter('name'), list_names))\n\n" ]
[ 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 not be loaded; Error importing module. A: probably not installed middleware try: pip install whitenoise
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 year, month and day. A: You use the datetime.datetime.date() method: datetime.datetime.now().date() Obviously, the expression above can (and should IMHO :) be written as: datetime.date.today() A: You can convert a datetime object to a date with the date() method of the date time object, as follows: <datetime_object>.date() A: Answer updated to Python 3.7 and more Here is how you can turn a date-and-time object (aka datetime.datetime object, the one that is stored inside models.DateTimeField django model field) into a date object (aka datetime.date object): from datetime import datetime #your date-and-time object # let's supposed it is defined as datetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893) # where # datetime_element = datetime(year, month, day, hour, minute, second, milliseconds) # WHAT YOU WANT: your date-only object date_element = datetime_element.date() And just to be clear, if you print those elements, here is the output : print(datetime_element) 2020-07-10 12:56:54.324893 print(date_element) 2020-07-10 A: you could enter this code form for (today date & Names of the Day & hour) : datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S') '19-09-09 Mon 17:37:56' and enter this code for (today date simply): datetime.date.today().strftime('%y-%m-%d') '19-09-10' for object : datetime.datetime.now().date() datetime.datetime.today().date() datetime.datetime.utcnow().date() datetime.datetime.today().time() datetime.datetime.utcnow().date() datetime.datetime.utcnow().time() A: import time import datetime # use mktime to step by one day # end - the last day, numdays - count of days to step back def gen_dates_list(end, numdays): start = end - datetime.timedelta(days=numdays+1) end = int(time.mktime(end.timetuple())) start = int(time.mktime(start.timetuple())) # 86400 s = 1 day return xrange(start, end, 86400) # if you need reverse the list of dates for dt in reversed(gen_dates_list(datetime.datetime.today(), 100)): print datetime.datetime.fromtimestamp(dt).date() A: I use data.strftime('%y-%m-%d') with lambda to transfer column to date A: Solved: AttributeError: 'Series' object has no attribute 'date' You can use as below, df["date"] = pd.to_datetime(df["date"]).dt.date where in above code date contains both date and time (2020-09-21 22:32:00), using above code we can get only date as (2020-09-21)
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 written as:\ndatetime.date.today()\n\n", "You can convert a datetime object to a date with the date() method of the date time object, as follows:\n<datetime_object>.date()\n\n", "Answer updated to Python 3.7 and more\nHere is how you can turn a date-and-time object\n(aka datetime.datetime object, the one that is stored inside models.DateTimeField django model field)\ninto a date object (aka datetime.date object):\nfrom datetime import datetime\n\n#your date-and-time object\n# let's supposed it is defined as\ndatetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893)\n\n# where\n# datetime_element = datetime(year, month, day, hour, minute, second, milliseconds)\n\n# WHAT YOU WANT: your date-only object\ndate_element = datetime_element.date()\n\nAnd just to be clear, if you print those elements, here is the output :\nprint(datetime_element)\n\n\n2020-07-10 12:56:54.324893\n\n\nprint(date_element)\n\n\n2020-07-10\n\n", "you could enter this code form for (today date & Names of the Day & hour) :\ndatetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')\n'19-09-09 Mon 17:37:56'\nand enter this code for (today date simply):\ndatetime.date.today().strftime('%y-%m-%d')\n\n'19-09-10'\nfor object :\ndatetime.datetime.now().date()\ndatetime.datetime.today().date()\ndatetime.datetime.utcnow().date()\ndatetime.datetime.today().time()\ndatetime.datetime.utcnow().date()\ndatetime.datetime.utcnow().time()\n", "import time\nimport datetime\n\n# use mktime to step by one day\n# end - the last day, numdays - count of days to step back\ndef gen_dates_list(end, numdays):\n start = end - datetime.timedelta(days=numdays+1)\n end = int(time.mktime(end.timetuple()))\n start = int(time.mktime(start.timetuple()))\n # 86400 s = 1 day\n return xrange(start, end, 86400)\n\n# if you need reverse the list of dates\nfor dt in reversed(gen_dates_list(datetime.datetime.today(), 100)):\n print datetime.datetime.fromtimestamp(dt).date()\n\n", "I use data.strftime('%y-%m-%d') with lambda to transfer column to date\n", "Solved: AttributeError: 'Series' object has no attribute 'date'\n\nYou can use as below,\ndf[\"date\"] = pd.to_datetime(df[\"date\"]).dt.date\n\nwhere in above code date contains both date and time (2020-09-21 22:32:00), using above code we can get only date as (2020-09-21)\n" ]
[ 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: User accesses the function/api, which then uses predefined/hardcoded credentials to connect to the outlook account. client = "XXXXXXXXXX-XXXX-XXXX-XXXXXXXXXXXXXXX" secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" credentials = (client, secret) account = Account(credentials) At this point the function provides a url in the console for the user to go visit and provide consent and asks the user to paste the authenticated url back in the console. Image below for reference. The problem here is that I want this authentication to be done on UI, not in the console. Im pushing this API to a server, where it will be not possible for the user to access the console to get this url and paste back the authenticated url. Is there a way to either skip this authentication on whole? Or atleast a way to redirect the user directly to this mentioned url in console and provide the authenticated url to console directly from UI? A: 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. Here it goes, So 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 hardcoded). consent_url, _ = con.get_authorization_url(**kwargs) This line of code is being used in oauth_authentication_flow function in O365 module to print out the consent_url in console. I used it to just return the consent_url to UI. Once user sign-in and consent is provided and they copy the token-url to paste it back to console, result = con.request_token(token_url, **kwargs) this line of code is used in the same oauth_authentication_flow function in O365 module to check if access token and refresh token are successfully generated and stored. So using a POST request, now a user can submit the token_url back to my django API to get access to O365 api without relying on console. @api_view(['GET','POST']) def setupMail(request,**kwargs): client = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" credentials = (client, secret) scopes=['basic', 'message_all'] global account account = Account(credentials) protocol = MSGraphProtocol() con = O365.Connection(credentials, scopes=protocol.get_scopes_for(scopes),**kwargs) if request.method == "GET": consent_url, _ = con.get_authorization_url(**kwargs) return Response('Visit the following url to give consent: ' + consent_url) if request.method == "POST": token_url = request.data.get('token') if token_url: result = con.request_token(token_url, **kwargs) # no need to pass state as the session is the same if result: return Response('Authentication Flow Completed. Oauth Access Token Stored. ' 'You can now use the API.') else: return Response('Something go wrong. Please try again. ' + str(bool(result))) else: return Response('Authentication Flow aborted.') else: return Response('Bad Request',status=status.HTTP_400_BAD_REQUEST) Please let me know if there are any security concerns that I need to be worried about.
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 outlook account. client = "XXXXXXXXXX-XXXX-XXXX-XXXXXXXXXXXXXXX" secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" credentials = (client, secret) account = Account(credentials) At this point the function provides a url in the console for the user to go visit and provide consent and asks the user to paste the authenticated url back in the console. Image below for reference. The problem here is that I want this authentication to be done on UI, not in the console. Im pushing this API to a server, where it will be not possible for the user to access the console to get this url and paste back the authenticated url. Is there a way to either skip this authentication on whole? Or atleast a way to redirect the user directly to this mentioned url in console and provide the authenticated url to console directly from UI?
[ "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 hardcoded).\nconsent_url, _ = con.get_authorization_url(**kwargs) This line of code is being used in oauth_authentication_flow function in O365 module to print out the consent_url in console. I used it to just return the consent_url to UI.\nOnce user sign-in and consent is provided and they copy the token-url to paste it back to console, result = con.request_token(token_url, **kwargs) this line of code is used in the same oauth_authentication_flow function in O365 module to check if access token and refresh token are successfully generated and stored.\nSo using a POST request, now a user can submit the token_url back to my django API to get access to O365 api without relying on console.\n@api_view(['GET','POST'])\ndef setupMail(request,**kwargs):\n client = \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n secret = \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n credentials = (client, secret)\n scopes=['basic', 'message_all']\n global account\n account = Account(credentials)\n protocol = MSGraphProtocol()\n con = O365.Connection(credentials, scopes=protocol.get_scopes_for(scopes),**kwargs)\n if request.method == \"GET\":\n consent_url, _ = con.get_authorization_url(**kwargs)\n return Response('Visit the following url to give consent: ' + consent_url)\n if request.method == \"POST\":\n token_url = request.data.get('token')\n if token_url:\n result = con.request_token(token_url, **kwargs) # no need to pass state as the session is the same\n if result:\n return Response('Authentication Flow Completed. Oauth Access Token Stored. '\n 'You can now use the API.')\n else:\n return Response('Something go wrong. Please try again. ' + str(bool(result)))\n else:\n return Response('Authentication Flow aborted.')\n else:\n return Response('Bad Request',status=status.HTTP_400_BAD_REQUEST)\n\nPlease let me know if there are any security concerns that I need to be worried about.\n" ]
[ 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 second and third yield coming from? Is it because in the for-loop, yield n returns None and this None is assigned to n in this line: n = yield n? A: This is explained in the documentation of yield expressions, especially this part: The value of the yield expression after resuming depends on the method which resumed the execution. If next() is used (typically via either a for or the next() builtin) then the result is None. Otherwise, if send() is used, then the result will be the value passed in to that method. As you use a for loop, n just gets None as a value when resuming after the first yield. So, from now on, n is None, and this is what will be yielded the last two times. A: It seems to me that you answered your own question: because in the for-loop, yield n returns None and None is assigned to n in this line: n = yield n You can read more at this answer.
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 because in the for-loop, yield n returns None and this None is assigned to n in this line: n = yield n?
[ "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, then the result will be the value passed\nin to that method.\n\nAs you use a for loop, n just gets None as a value when resuming after the first yield. So, from now on, n is None, and this is what will be yielded the last two times.\n", "It seems to me that you answered your own question:\n\nbecause in the for-loop, yield n returns None and None is assigned to n in this line: n = yield n\n\nYou can read more at this answer.\n" ]
[ 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: 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) ysoln=dsolve(deq,y(x),hint='1st_exact',ics={y(1):1}) print("The solution of the given differential equation is:") pprint(ysoln) plt.plot(ysoln.rhs, (x,-2,2)) this is the python program for solving a differential equation deq. but while running this code it shows attribute error. I tried changing the values and changing the equation A: First off, you need to update SymPy to the latest version (1.11). Then, 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: plot(ysoln.rhs, (x,-2,2))
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) ysoln=dsolve(deq,y(x),hint='1st_exact',ics={y(1):1}) print("The solution of the given differential equation is:") pprint(ysoln) plt.plot(ysoln.rhs, (x,-2,2)) this is the python program for solving a differential equation deq. but while running this code it shows attribute error. I tried changing the values and changing the equation
[ "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 'fields_set', why is it? A: It's because you override the __init__ and do not call super there so Pydantic cannot do it's magic with setting proper fields. With pydantic it's rare you need to implement your __init__ most cases can be solved different way: from pydantic import BaseModel class A(BaseModel): date = "" class B(A): person: float = 0 B()
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):\n person: float = 0\n\nB()\n\n" ]
[ 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': 'ddd', 'type': 'string'}], 'type': 'struct' } From this dictionary, I would like to drop the dictionary with the id value nan value and would like to get the following. my_updated_dict = {'fields': ['id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}], 'type': 'struct' } I was trying changing to data frame and dropping the id value with the nan value and changing to dictionary back but couldn't get the intended result. my_updated_dict = pd.DataFrame(my_dict ).dropna().to_dict('list') A: I do not know why would you need pandas for that if u can simply do: my_dict["fields"] = [i for i in my_dict["fields"] if not np.isnan(i["id"])] ** UPDATE ** if you really do need for some reason to use pandas, you may try this constructiion: my_dict["fields"] = pd.Series(my_dict["fields"]).apply(pd.Series).dropna().to_dict(orient="records") though I do not see any advantages over simple list comprehension, except may be on big volume of information. A: You can use update() to overwrite the value of the key, then you can try: my_dict.update({'fields':[x for x in my_dict['fields'] if np.nan not in x.values()]}) Returning: {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}], 'type': 'struct'} A: Considering the dictionary json import numpy as np json = {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': np.nan, 'name': 'bbb', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}, {'id': np.nan, 'name': 'ddd', 'type': 'string'}], 'type': 'struct'} In order to remove the parts where id is np.nan, one can use a list comprehension with numpy.isnan as follows json['fields'] = [x for x in json['fields'] if not np.isnan(x['id'])] [Out]: {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}], 'type': 'struct'}
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': 'struct' } From this dictionary, I would like to drop the dictionary with the id value nan value and would like to get the following. my_updated_dict = {'fields': ['id': 1.0, 'name': 'aaa', 'type': 'string'}, {'id': 3.0, 'name': 'eee', 'type': 'string'}, {'id': 4.0, 'name': 'ccc', 'type': 'string'}], 'type': 'struct' } I was trying changing to data frame and dropping the id value with the nan value and changing to dictionary back but couldn't get the intended result. my_updated_dict = pd.DataFrame(my_dict ).dropna().to_dict('list')
[ "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(pd.Series).dropna().to_dict(orient=\"records\")\n\nthough I do not see any advantages over simple list comprehension, except may be on big volume of information.\n", "You can use update() to overwrite the value of the key, then you can try:\nmy_dict.update({'fields':[x for x in my_dict['fields'] if np.nan not in x.values()]})\n\nReturning:\n{'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'},\n {'id': 3.0, 'name': 'eee', 'type': 'string'},\n {'id': 4.0, 'name': 'ccc', 'type': 'string'}],\n 'type': 'struct'}\n\n", "Considering the dictionary json\nimport numpy as np\n\njson = {'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'},\n {'id': 3.0, 'name': 'eee', 'type': 'string'},\n {'id': np.nan, 'name': 'bbb', 'type': 'string'},\n {'id': 4.0, 'name': 'ccc', 'type': 'string'},\n {'id': np.nan, 'name': 'ddd', 'type': 'string'}],\n 'type': 'struct'}\n\nIn order to remove the parts where id is np.nan, one can use a list comprehension with numpy.isnan as follows\njson['fields'] = [x for x in json['fields'] if not np.isnan(x['id'])]\n\n[Out]:\n\n{'fields': [{'id': 1.0, 'name': 'aaa', 'type': 'string'},\n {'id': 3.0, 'name': 'eee', 'type': 'string'},\n {'id': 4.0, 'name': 'ccc', 'type': 'string'}],\n 'type': 'struct'}\n\n" ]
[ 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 or regex): s = 'GA1.2.4451363243.9414195136' out = '.'.join(s.rsplit('.', 2)[-2:]) # '4451363243.9414195136' import re out = re.search(r'[^.]*\.[^.]*$', s) # <re.Match object; span=(6, 27), match='4451363243.9414195136'> NB. to ensure matching digits, you can replace [^.] (any character but .) with \d. For an arbitrary N: N = 3 out = '.'.join(s.rsplit('.', N)[-N:]) # '2.4451363243.9414195136' out = re.search(fr'[^.]*(?:\.[^.]*){{{N-1}}}$', s) # <re.Match object; span=(4, 27), match='2.4451363243.9414195136'> A: It could be done using pure python! but if you want to use regex here is the code: regex: (?:[\w\d]*.){2}(.*) python: import re s = 'GA1.2.4451363243.9414195136' re.match(r'(?:[\w\d]*.){2}(.*)',s).groups()[0] # output: '4451363243.9414195136' OR Just use python: s.split('.',2)[-1] # output: '4451363243.9414195136' A: The following regex ([0-9]+.[0-9]+)$ matches the expected part of the example. Note that more specific solutions may arise as you provide more details, restrictions, etc. regarding the part to be matched: >>> import re >>> data = "GA1.2.4451363243.941419513" >>> re.findall(r"([0-9]+.[0-9]+)$", data) ['4451363243.941419513'] It requests the matched part to be made of: digit(s) dot digit(s) end of line.
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 [^.] (any character but .) with \\d.\nFor an arbitrary N:\nN = 3\n\nout = '.'.join(s.rsplit('.', N)[-N:])\n# '2.4451363243.9414195136'\n\nout = re.search(fr'[^.]*(?:\\.[^.]*){{{N-1}}}$', s)\n# <re.Match object; span=(4, 27), match='2.4451363243.9414195136'>\n\n", "It could be done using pure python! but if you want to use regex here is the code:\nregex:\n(?:[\\w\\d]*.){2}(.*)\n\npython:\nimport re\ns = 'GA1.2.4451363243.9414195136'\nre.match(r'(?:[\\w\\d]*.){2}(.*)',s).groups()[0] # output: '4451363243.9414195136'\n\nOR\nJust use python:\ns.split('.',2)[-1] # output: '4451363243.9414195136'\n\n", "The following regex ([0-9]+.[0-9]+)$ matches the expected part of the example. Note that more specific solutions may arise as you provide more details, restrictions, etc. regarding the part to be matched:\n>>> import re\n>>> data = \"GA1.2.4451363243.941419513\"\n>>> re.findall(r\"([0-9]+.[0-9]+)$\", data)\n['4451363243.941419513']\n\nIt requests the matched part to be made of:\n\ndigit(s)\ndot\ndigit(s)\nend of line.\n\n" ]
[ 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 dataclass import jsons out = {"yield": 0.21} @dataclass class PriceObj: asOfDate: str price: float yield: float jsons.load(out, PriceObj) This will obviously fail because yield is reserved. Looking at the dataclasses field definition, there doesn't seem to be anything in there that can help. Go, allows one to define the name of the JSON field, wonder if there is such a feature in the dataclass? A: You can decode / encode using a different name with the dataclasses_json lib, from their docs: from dataclasses import dataclass, field from dataclasses_json import config, dataclass_json @dataclass_json @dataclass class Person: given_name: str = field(metadata=config(field_name="overriddenGivenName")) Person(given_name="Alice") # Person('Alice') Person.from_json('{"overriddenGivenName": "Alice"}') # Person('Alice') Person('Alice').to_json() # {"overriddenGivenName": "Alice"} A: I found next solution for my purposes. @dataclass class ExampleClass: def __post_init__(self): self.__setattr__("class", self.class_) self.__delattr__("class_") class_: str It requires to set init value in class_ attribute. Also you can't directly use this attribute like example_class_instance.class, workaround is example_class_instance.__getattribute__("class"). And the dataclass has broken repr, can be avoided by changing decorator to dataclass(repr=False)
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: asOfDate: str price: float yield: float jsons.load(out, PriceObj) This will obviously fail because yield is reserved. Looking at the dataclasses field definition, there doesn't seem to be anything in there that can help. Go, allows one to define the name of the JSON field, wonder if there is such a feature in the dataclass?
[ "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\"))\n\nPerson(given_name=\"Alice\") # Person('Alice')\nPerson.from_json('{\"overriddenGivenName\": \"Alice\"}') # Person('Alice')\nPerson('Alice').to_json() # {\"overriddenGivenName\": \"Alice\"}\n\n", "I found next solution for my purposes.\n@dataclass\nclass ExampleClass:\n def __post_init__(self):\n self.__setattr__(\"class\", self.class_)\n self.__delattr__(\"class_\") \n\n class_: str\n\nIt requires to set init value in class_ attribute.\nAlso you can't directly use this attribute like example_class_instance.class, workaround is example_class_instance.__getattribute__(\"class\").\nAnd the dataclass has broken repr, can be avoided by changing decorator to dataclass(repr=False)\n" ]
[ 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 variables from settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://redis:6379', } } CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "django-db") CELERY_CACHE_BACKEND = "django-cache" CELERY_RESULT_EXTENDED = True I also tried database cache - nothing changed. How can I get this to work? UPD: I can create TaskResult and GroupResult objects manually with django admin panel or django shell, the problem is that they are not created automatically. A: You have to migrate first then you will able to store such information.Follow this link you will get your solution for sure: https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html#django-celery-results-using-the-django-orm-cache-as-a-result-backend
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': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://redis:6379', } } CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "django-db") CELERY_CACHE_BACKEND = "django-cache" CELERY_RESULT_EXTENDED = True I also tried database cache - nothing changed. How can I get this to work? UPD: I can create TaskResult and GroupResult objects manually with django admin panel or django shell, the problem is that they are not created automatically.
[ "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 = driver.find_element(By.XPATH, "//*[@id='main_content']/ul") all_li_element = ul_element.find_elements(By.CSS_SELECTOR, "li") then after i got the list items to go to each one and scrape some data is there a better way because the way i'm thinking about it, it will turn into a nested list A: 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 Beautifulsoup etc. But again, these are not Selenium UI approaches. A: the way i'm thinking about it, it will turn into a nested list unless you concatenate all details into one string [which I would not advise], or you only need one detail, there will have to be some nesting to whatever data structure you have the output as; since you a set of details for a list of items, there will have to be at least one level of nesting [list of items -> set of details] However, it's not that complicated - you can just make a list of dictionaries with the details you want from each card [including, and especially, the link], and then go through that list of dictionaries and add to each dictionary by going to the link and scraping the rest of the info. First, I like to separate out the actual detail-extraction into a function that I can reuse. [This is a simplified version of another function I often use when scraping; if interested, check out the full version.] def extractAttr(elem, sel, attr, defVal=None): e = elem.find_elements(By.CSS_SELECTOR, sel) aVal = e[0].get_attribute(attr) if e else None return defVal if aVal is None else aVal and also prepare most of the inputs the function will need: liSels = [ # selectors for the list items ('name', 'span[itemprop="name"]', 'innerText'), ('link', 'a[itemprop="url"][href]', 'href'), ('imgUrl', 'img[itemprop="photo"][src]', 'src') ] pgSels = [ # selectors for the individual pages ('description', 'p.description', 'innerText'), ('moreInfo', 'li.large-margin-bottom > h3 + ul', 'innerText') ] (You can add or remove from liSels and pgSels according to whatever details you need/want. Also, I'm using CSS selectors due to personal preference; you can swap them out for their XPath equivalents if you're more comfortable with that - just make sure to adjust the function to match.) Now that the function and selectors are ready, you can just get to going through the pages to build that list of dictionaries # driver = webdriver.Chrome() # wait = WebDriverWait(driver, 5) rootUrl = 'https://www.crunchyroll.com' cardSel = '#main_content > ul > li' driver.get(f'{rootUrl}/comics/manga') wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, cardSel))) cards = [{ k: extractAttr(c, s, a) for k, s, a in liSels } for c in driver.find_elements(By.CSS_SELECTOR, cardSel)] for i, c in enumerate(cards): driver.get(c['link']) for k, s, a in pgSels: cards[i][k] = extractAttr(driver, s, a) # driver.quit() and cards[:5] will look something like      (only 5 of 50 dictionaries are included below) [ {'name': 'Genshin Impact', 'link': 'https://www.crunchyroll.com/comics/manga/genshin-impact/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/9e6d8c402f2916bd093fc7a1524265ca_1544713688_large.jpg', 'description': 'Aeons ago, the elder elemental gods granted civilization to the human race, but the world soon splintered as corruption and greed grew without check. Can the forces holding this world together be balanced against human desires, or is everything ultimately doomed to end in destruction? http://genshin.mihoyo.com/', 'moreInfo': 'Publisher: miHoYo Limited\nFirst Published:\nAuthor: miHoYo\nArtist: miHoYo\nCopyright: © 2017-2018 miHoYo Limited ALL RIGHTS RESERVED'} , {'name': 'Inside Mari', 'link': 'https://www.crunchyroll.com/comics/manga/inside-mari/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/70d74c2842e6ebed097c8309889c67e8_1389837055_large.jpg', 'description': 'A young man is a shut-in, with nothing to do but kill time. The sole pleasure in his life is following home an angelic high school girl he sees every day in a convenience store. Today, like any other day, he follows her, but… Shuzo Oshimi, the creator of Drifting Net Café and Flowers of Evil, continues to open hidden doors of the heart in this monthly serialized story!', 'moreInfo': 'Publisher: Futabasha\nFirst Published:\nAuthor:\nArtist: Shuzo Oshimi\nCopyright: ©Shuzo Oshimi/FUTABASHA PUBLISHERS LTD.\nTranslator: Sheldon Drzka\nEditor: Emily Martha Sorensen\nLetterer: Carl Vanstiphout'} , {'name': 'To Your Eternity', 'link': 'https://www.crunchyroll.com/comics/manga/to-your-eternity/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/c49832d6c4e25d693e6b88b0328e70a5_1519720335_large.jpg', 'description': 'A new manga from the creator of the acclaimed A Silent Voice, featuring intimate, emotional drama and an epic story spanning time and space, To Your Eternity is a totally unique and moving manga about death, life, reincarnation, and the nature of love. A lonely boy wandering the Arctic regions of North America meets a wolf, and the two become fast friends, depending on each other to survive the harsh environment. But the boy has a history, and the wolf is more than meets the eye as well …', 'moreInfo': 'Publisher: Kodansha\nFirst Published:\nAuthor:\nArtist:\nCopyright: Based on the manga "Fumetsu no Anata he" by Yoshitoki Oima originally serialized in the Weekly Shonen magazine published by KODANSHA LTD. To Your Eternity copyright © Yoshitoki Oima/KODANSHA LTD. English translation copyright © Yoshitoki Oima/KODANSHA LTD. All rights reserved.\nTranslator: Steven LeCroy\nEditor: Alexandra Swanson\nLetterer: Darren Smith'} , {'name': 'Sun-Ken Rock', 'link': 'https://www.crunchyroll.com/comics/manga/sun-ken-rock/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/368cba1b39ae46b3435e6ac1d4f5987e_1391991276_large.jpg', 'description': 'Ken left Japan, pursuing the woman he loves to Korea. However, while she became a policewoman, Ken somehow wound up in a gang, even becoming their boss! The man who came from Japan now rises in Korea. It\'s Korean "Rock-Action" with a powerful punch!', 'moreInfo': 'Publisher: Shonen Gahosha\nFirst Published:\nAuthor:\nArtist: Boichi\nCopyright: ©BOICHI/Shonen-gahosha Co., Ltd.'} , {'name': 'Fire Force', 'link': 'https://www.crunchyroll.com/comics/manga/fire-force/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/83fa13859c8baee6f20708b5d4bd5c35_1640071967_large.jpg', 'description': 'A new action fantasy set in a steampunk Tokyo from the creator of the smash-hit Soul Eater!The city of Tokyo is plagued by a deadly phenomenon: spontaneous human combustion! Luckily, a special team is there to quench the inferno: The Fire Force! The fire soldiers at Special Fire Cathedral 8 are about to get a unique addition. Enter Shinra, a boy who possesses the power to run at the speed of a rocket, leaving behind the famous “devil’s footprints” (and destroying his shoes in the process). ... more', 'moreInfo': 'Publisher: Kodansha\nFirst Published:\nAuthor: Atsushi Ohkubo\nArtist: Atsushi Ohkubo\nCopyright: Based on the manga "En\'en no Shōbōtai" by Atsushi Ohkubo originally serialized in the weekly Shonen Magazine published by KODANSHA LTD. Fire Force copyright © Atsushi Ohkubo/KODANSHA LTD. English translation copyright © Atsushi Ohkubo/KODANSHA LTD. All rights reserved.'} , ] At this point, it would be very easy to save or view this with something like pandas # import pandas pandas.DataFrame(cards).to_csv('crunchyCards.csv', index=False) would produce a spreadsheet like
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_element.find_elements(By.CSS_SELECTOR, "li") then after i got the list items to go to each one and scrape some data is there a better way because the way i'm thinking about it, it will turn into a nested list
[ "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 Beautifulsoup etc. But again, these are not Selenium UI approaches.\n", "\nthe way i'm thinking about it, it will turn into a nested list\n\nunless you concatenate all details into one string [which I would not advise], or you only need one detail, there will have to be some nesting to whatever data structure you have the output as; since you a set of details for a list of items, there will have to be at least one level of nesting [list of items -> set of details]\nHowever, it's not that complicated - you can just make a list of dictionaries with the details you want from each card [including, and especially, the link], and then go through that list of dictionaries and add to each dictionary by going to the link and scraping the rest of the info.\n\nFirst, I like to separate out the actual detail-extraction into a function that I can reuse.\n[This is a simplified version of another function I often use when scraping; if interested, check out the full version.]\ndef extractAttr(elem, sel, attr, defVal=None):\n e = elem.find_elements(By.CSS_SELECTOR, sel)\n aVal = e[0].get_attribute(attr) if e else None\n return defVal if aVal is None else aVal\n\nand also prepare most of the inputs the function will need:\nliSels = [ # selectors for the list items\n ('name', 'span[itemprop=\"name\"]', 'innerText'),\n ('link', 'a[itemprop=\"url\"][href]', 'href'),\n ('imgUrl', 'img[itemprop=\"photo\"][src]', 'src')\n]\npgSels = [ # selectors for the individual pages\n ('description', 'p.description', 'innerText'),\n ('moreInfo', 'li.large-margin-bottom > h3 + ul', 'innerText')\n]\n\n(You can add or remove from liSels and pgSels according to whatever details you need/want. Also, I'm using CSS selectors due to personal preference; you can swap them out for their XPath equivalents if you're more comfortable with that - just make sure to adjust the function to match.)\n\nNow that the function and selectors are ready, you can just get to going through the pages to build that list of dictionaries\n# driver = webdriver.Chrome()\n# wait = WebDriverWait(driver, 5)\nrootUrl = 'https://www.crunchyroll.com'\ncardSel = '#main_content > ul > li'\n\ndriver.get(f'{rootUrl}/comics/manga')\nwait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, cardSel)))\n\ncards = [{\n k: extractAttr(c, s, a) for k, s, a in liSels\n} for c in driver.find_elements(By.CSS_SELECTOR, cardSel)]\nfor i, c in enumerate(cards):\n driver.get(c['link'])\n for k, s, a in pgSels:\n cards[i][k] = extractAttr(driver, s, a)\n\n# driver.quit()\n\nand cards[:5] will look something like      (only 5 of 50 dictionaries are included below)\n[\n {'name': 'Genshin Impact', 'link': 'https://www.crunchyroll.com/comics/manga/genshin-impact/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/9e6d8c402f2916bd093fc7a1524265ca_1544713688_large.jpg', 'description': 'Aeons ago, the elder elemental gods granted civilization to the human race, but the world soon splintered as corruption and greed grew without check. Can the forces holding this world together be balanced against human desires, or is everything ultimately doomed to end in destruction? http://genshin.mihoyo.com/', 'moreInfo': 'Publisher: miHoYo Limited\\nFirst Published:\\nAuthor: miHoYo\\nArtist: miHoYo\\nCopyright: © 2017-2018 miHoYo Limited ALL RIGHTS RESERVED'} ,\n {'name': 'Inside Mari', 'link': 'https://www.crunchyroll.com/comics/manga/inside-mari/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/70d74c2842e6ebed097c8309889c67e8_1389837055_large.jpg', 'description': 'A young man is a shut-in, with nothing to do but kill time. The sole pleasure in his life is following home an angelic high school girl he sees every day in a convenience store. Today, like any other day, he follows her, but… Shuzo Oshimi, the creator of Drifting Net Café and Flowers of Evil, continues to open hidden doors of the heart in this monthly serialized story!', 'moreInfo': 'Publisher: Futabasha\\nFirst Published:\\nAuthor:\\nArtist: Shuzo Oshimi\\nCopyright: ©Shuzo Oshimi/FUTABASHA PUBLISHERS LTD.\\nTranslator: Sheldon Drzka\\nEditor: Emily Martha Sorensen\\nLetterer: Carl Vanstiphout'} ,\n {'name': 'To Your Eternity', 'link': 'https://www.crunchyroll.com/comics/manga/to-your-eternity/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/c49832d6c4e25d693e6b88b0328e70a5_1519720335_large.jpg', 'description': 'A new manga from the creator of the acclaimed A Silent Voice, featuring intimate, emotional drama and an epic story spanning time and space, To Your Eternity is a totally unique and moving manga about death, life, reincarnation, and the nature of love. A lonely boy wandering the Arctic regions of North America meets a wolf, and the two become fast friends, depending on each other to survive the harsh environment. But the boy has a history, and the wolf is more than meets the eye as well …', 'moreInfo': 'Publisher: Kodansha\\nFirst Published:\\nAuthor:\\nArtist:\\nCopyright: Based on the manga \"Fumetsu no Anata he\" by Yoshitoki Oima originally serialized in the Weekly Shonen magazine published by KODANSHA LTD. To Your Eternity copyright © Yoshitoki Oima/KODANSHA LTD. English translation copyright © Yoshitoki Oima/KODANSHA LTD. All rights reserved.\\nTranslator: Steven LeCroy\\nEditor: Alexandra Swanson\\nLetterer: Darren Smith'} ,\n {'name': 'Sun-Ken Rock', 'link': 'https://www.crunchyroll.com/comics/manga/sun-ken-rock/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/368cba1b39ae46b3435e6ac1d4f5987e_1391991276_large.jpg', 'description': 'Ken left Japan, pursuing the woman he loves to Korea. However, while she became a policewoman, Ken somehow wound up in a gang, even becoming their boss! The man who came from Japan now rises in Korea. It\\'s Korean \"Rock-Action\" with a powerful punch!', 'moreInfo': 'Publisher: Shonen Gahosha\\nFirst Published:\\nAuthor:\\nArtist: Boichi\\nCopyright: ©BOICHI/Shonen-gahosha Co., Ltd.'} ,\n {'name': 'Fire Force', 'link': 'https://www.crunchyroll.com/comics/manga/fire-force/volumes', 'imgUrl': 'https://api-manga.crunchyroll.com/i/croll_manga/83fa13859c8baee6f20708b5d4bd5c35_1640071967_large.jpg', 'description': 'A new action fantasy set in a steampunk Tokyo from the creator of the smash-hit Soul Eater!The city of Tokyo is plagued by a deadly phenomenon: spontaneous human combustion! Luckily, a special team is there to quench the inferno: The Fire Force! The fire soldiers at Special Fire Cathedral 8 are about to get a unique addition. Enter Shinra, a boy who possesses the power to run at the speed of a rocket, leaving behind the famous “devil’s footprints” (and destroying his shoes in the process). ... more', 'moreInfo': 'Publisher: Kodansha\\nFirst Published:\\nAuthor: Atsushi Ohkubo\\nArtist: Atsushi Ohkubo\\nCopyright: Based on the manga \"En\\'en no Shōbōtai\" by Atsushi Ohkubo originally serialized in the weekly Shonen Magazine published by KODANSHA LTD. Fire Force copyright © Atsushi Ohkubo/KODANSHA LTD. English translation copyright © Atsushi Ohkubo/KODANSHA LTD. All rights reserved.'} ,\n]\n\n\nAt this point, it would be very easy to save or view this with something like pandas\n# import pandas\npandas.DataFrame(cards).to_csv('crunchyCards.csv', index=False)\n\nwould produce a spreadsheet like\n\n" ]
[ 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 = models.UUIDField() content_type_1 = models.ForeignKey(ContentType) object_id_2 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) object_id_3 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) # etc. d1 = GenericForeignKey("content_type_1", "object_id_1") d2 = GenericForeignKey("content_type_2", "object_id_2") d3 = GenericForeignKey("content_type_3", "object_id_3") # etc. Obviously, the more dimensions (d stands for "dimension") I add, the messier it gets: this isn't very DRY, all the more since I've removed the many fields options in this example. Is there a way to dynamically define these model attributes, for instance in a for loop, without using eval? If not, what would be the cleanest and safest way to resort to eval here? I've found a very similar Stackoverflow question here but it is more specific and it hasn't got any generic answer. A: My solution I'm not entirely satisfied with this piece of code because it means relying on undocumented internals which have no stability guarantee whatsoever, but this is what I've finally done, for future readers: from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Foo(models.Model): NB_DIMENSIONS = N pass # outside of the class for i in range(1, Foo.NB_DIMENSIONS + 1): Foo.add_to_class(f"object_id_{i}", models.UUIDField()) Foo.add_to_class(f"content_type_{i}", models.ForeignKey(ContentType)) Foo.add_to_class(f"d{i}", GenericForeignKey(f"content_type_{i}", f"object_id_{i}")) Here, I'm indirectly using the Managers contribute_to_class hook as described in this old Stackoverflow question. It is mentioned here as well. One should pay attention to the fact that this method is an undocumented, private, internal API. Django does not provide backwards-compatibility guarantees for it, and if you make use of it you accept the risk that it might change or break at any time. Alternative 1 The following code seems to work as well, but note that it's a bad idea to modify locals in Python: from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Foo(models.Model): NB_DIMENSIONS = N for i in range(1, NB_DIMENSIONS + 1): locals()[f"object_id_{i}"] = models.UUIDField() locals()[f"content_type_{i}"] = models.ForeignKey(ContentType) locals()[f"d{i}"] = GenericForeignKey(f"content_type_{i}", f"object_id_{i}") Let me insist on this: using locals() may be a bad idea for various reasons, even if it seems more readable. Alternative 2 As suggested by @Abdul Aziz Barkat above, it should be possible be to create a intermediate class with type() (cf. this Stackoverflow thread). This has its downsides: that implies one more class to manage and I believe it's harder to understand and to maintain for less experienced developers.
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(ContentType) object_id_2 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) object_id_3 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) # etc. d1 = GenericForeignKey("content_type_1", "object_id_1") d2 = GenericForeignKey("content_type_2", "object_id_2") d3 = GenericForeignKey("content_type_3", "object_id_3") # etc. Obviously, the more dimensions (d stands for "dimension") I add, the messier it gets: this isn't very DRY, all the more since I've removed the many fields options in this example. Is there a way to dynamically define these model attributes, for instance in a for loop, without using eval? If not, what would be the cleanest and safest way to resort to eval here? I've found a very similar Stackoverflow question here but it is more specific and it hasn't got any generic answer.
[ "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.contenttypes.models import ContentType\nfrom django.db import models\n\nclass Foo(models.Model):\n NB_DIMENSIONS = N\n pass\n\n# outside of the class\nfor i in range(1, Foo.NB_DIMENSIONS + 1):\n Foo.add_to_class(f\"object_id_{i}\", models.UUIDField())\n Foo.add_to_class(f\"content_type_{i}\", models.ForeignKey(ContentType))\n Foo.add_to_class(f\"d{i}\", GenericForeignKey(f\"content_type_{i}\", f\"object_id_{i}\"))\n\nHere, I'm indirectly using the Managers contribute_to_class hook as described in this old Stackoverflow question. It is mentioned here as well. One should pay attention to the fact that this method is an undocumented, private, internal API. Django does not provide backwards-compatibility guarantees for it, and if you make use of it you accept the risk that it might change or break at any time.\nAlternative 1\nThe following code seems to work as well, but note that it's a bad idea to modify locals in Python:\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db import models\n\nclass Foo(models.Model):\n NB_DIMENSIONS = N\n for i in range(1, NB_DIMENSIONS + 1):\n locals()[f\"object_id_{i}\"] = models.UUIDField()\n locals()[f\"content_type_{i}\"] = models.ForeignKey(ContentType)\n locals()[f\"d{i}\"] = GenericForeignKey(f\"content_type_{i}\", f\"object_id_{i}\")\n\nLet me insist on this: using locals() may be a bad idea for various reasons, even if it seems more readable.\nAlternative 2\nAs suggested by @Abdul Aziz Barkat above, it should be possible be to create a intermediate class with type() (cf. this Stackoverflow thread). This has its downsides: that implies one more class to manage and I believe it's harder to understand and to maintain for less experienced developers.\n" ]
[ 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.stats.binom.pmf(df1[2,3],df2[2,0],df3[2,3]) and so on. I have tried using map function but it is not working in this case. I can use loops but that wouldn’t be an efficient solution. A: import pandas as pd from scipy import stats import numpy as np # create the dataset row = 18 col = 19 df2 = pd.DataFrame(np.random.randint(1,20,size=(row,1))) df1 = pd.DataFrame({c: [np.random.randint(0, df2.loc[r,0]) for r in range(row)] for c in range(col)}) df3 = pd.DataFrame(np.random.uniform(0,1, size = (row,col))) # implementation # can use # row, col = df1.shape df4 = pd.DataFrame({c: [ stats.binom.pmf(df1.loc[r,c],df2.loc[r,0],df3.loc[r,c] ) for r in range(row) ] for c in range(col)})
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,3]) and so on. I have tried using map function but it is not working in this case. I can use loops but that wouldn’t be an efficient solution.
[ "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 = (row,col)))\n\n# implementation \n# can use \n# row, col = df1.shape\n\ndf4 = pd.DataFrame({c: [\n stats.binom.pmf(df1.loc[r,c],df2.loc[r,0],df3.loc[r,c]\n ) for r in range(row)\n ] for c in range(col)})\n\n" ]
[ 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 3.24.0-rc3 CMake suite maintained and supported by Kitware I have python 3.11 installed ➜ py --version Python 3.11.0 I have tried to install dlib using pip The error I recieved have been uploaded to pastebin File "C:\Program Files\Python311\Lib\site-packages\setuptools\command\bdist_egg.py", line 151, in call_command self.run_command(cmdname) File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\cmd.py", line 319, in run_command self.distribution.run_command(command) File "C:\Program Files\Python311\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Program Files\Python311\Lib\site-packages\setuptools\command\install_lib.py", line 11, in run self.build() File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\command\install_lib.py", line 112, in build self.run_command('build_ext') File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\cmd.py", line 319, in run_command self.distribution.run_command(command) File "C:\Program Files\Python311\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Users\alent\Downloads\dlib-19.24\setup.py", line 134, in run self.build_extension(ext) File "C:\Users\alent\Downloads\dlib-19.24\setup.py", line 174, in build_extension subprocess.check_call(cmake_build, cwd=build_folder) File "C:\Program Files\Python311\Lib\subprocess.py", line 413, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['cmake', '--build', '.', '--config', 'Release', '--', '/m']' returned non-zero exit status 1. https://pastebin.com/8N5kb75D Then I tried building it from source So I downloaded the latest release from https://github.com/davisking/dlib/releases/tag/v19.24 The error I recied have been uploaded to pastebin https://pastebin.com/YjiVTMEp Please help me. Thank you for looking into this. When I try to build it from source, I get https://pastebin.com/YjiVTMEp When I try to install using pip, I get https://pastebin.com/8N5kb75D A: Yes. I made it successful using python3.11 All you need to do is Clone the repo using git clone https://github.com/davisking/dlib Get inside the directory in cmd using cd dlib Make sure you have visual studio desktop development with c++ Install cmake from https://cmake.org/download/ Using pip to install cmake py -m pip install cmake Then try installing dlib by py setup.py install If this worked please upvote my solution. Thank you
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 Kitware I have python 3.11 installed ➜ py --version Python 3.11.0 I have tried to install dlib using pip The error I recieved have been uploaded to pastebin File "C:\Program Files\Python311\Lib\site-packages\setuptools\command\bdist_egg.py", line 151, in call_command self.run_command(cmdname) File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\cmd.py", line 319, in run_command self.distribution.run_command(command) File "C:\Program Files\Python311\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Program Files\Python311\Lib\site-packages\setuptools\command\install_lib.py", line 11, in run self.build() File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\command\install_lib.py", line 112, in build self.run_command('build_ext') File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\cmd.py", line 319, in run_command self.distribution.run_command(command) File "C:\Program Files\Python311\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Program Files\Python311\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Users\alent\Downloads\dlib-19.24\setup.py", line 134, in run self.build_extension(ext) File "C:\Users\alent\Downloads\dlib-19.24\setup.py", line 174, in build_extension subprocess.check_call(cmake_build, cwd=build_folder) File "C:\Program Files\Python311\Lib\subprocess.py", line 413, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['cmake', '--build', '.', '--config', 'Release', '--', '/m']' returned non-zero exit status 1. https://pastebin.com/8N5kb75D Then I tried building it from source So I downloaded the latest release from https://github.com/davisking/dlib/releases/tag/v19.24 The error I recied have been uploaded to pastebin https://pastebin.com/YjiVTMEp Please help me. Thank you for looking into this. When I try to build it from source, I get https://pastebin.com/YjiVTMEp When I try to install using pip, I get https://pastebin.com/8N5kb75D
[ "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 install cmake\npy -m pip install cmake\nThen try installing dlib by\npy setup.py install\n\nIf this worked please upvote my solution. Thank you\n" ]
[ 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", "Julian", "Ann"] That is not the format I want instead I want it to be like this; Sam, Peter, James, Julian, Ann Note: It must be in a single row. A: print(', '.join(names)) This, like it sounds, just takes all the elements of the list and joins them with ', '. A: Here is a simple one. names = ["Sam", "Peter", "James", "Julian", "Ann"] print(*names, sep=", ") the star unpacks the list and return every element in the list. A: General solution, works on arrays of non-strings: >>> print str(names)[1:-1] 'Sam', 'Peter', 'James', 'Julian', 'Ann' A: If the input array is Integer type then you need to first convert array into string type array and then use join method for joining with , or space whatever you want. e.g: >>> arr = [1, 2, 4, 3] >>> print(", " . join(arr)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected string, int found >>> sarr = [str(a) for a in arr] >>> print(", " . join(sarr)) 1, 2, 4, 3 >>> Direct using of join which will join the integer and string will throw error as show above. A: There are two answers , First is use 'sep' setting >>> print(*names, sep = ', ') The other is below >>> print(', '.join(names)) A: try to use an asterisk before list's name with print statement: names = ["Sam", "Peter", "James", "Julian", "Ann"] print(*names) output: Sam Peter James Julian Ann A: This is what you need ", ".join(names) A: ','.join(list) will work only if all the items in the list are strings. If you are looking to convert a list of numbers to a comma separated string. such as a = [1, 2, 3, 4] into '1,2,3,4' then you can either str(a)[1:-1] # '1, 2, 3, 4' or str(a).lstrip('[').rstrip(']') # '1, 2, 3, 4' although this won't remove any nested list. To convert it back to a list a = '1,2,3,4' import ast ast.literal_eval('['+a+']') #[1, 2, 3, 4] A: For array of integer type, we need to change it to string type first and than use join function to get clean output without brackets. arr = [1, 2, 3, 4, 5] print(', '.join(map(str, arr))) OUTPUT - 1, 2, 3, 4, 5 For array of string type, we need to use join function directly to get clean output without brackets. arr = ["Ram", "Mohan", "Shyam", "Dilip", "Sohan"] print(', '.join(arr) OUTPUT - Ram, Mohan, Shyam, Dilip, Sohan A: print(*names) this will work in python 3 if you want them to be printed out as space separated. If you need comma or anything else in between go ahead with .join() solution A: You need to loop through the list and use end=" "to keep it on one line names = ["Sam", "Peter", "James", "Julian", "Ann"] index=0 for name in names: print(names[index], end=", ") index += 1 A: I don't know if this is efficient as others but simple logic always works: import sys name = ["Sam", "Peter", "James", "Julian", "Ann"] for i in range(0, len(names)): sys.stdout.write(names[i]) if i != len(names)-1: sys.stdout.write(", ") Output: Sam, Peter, James, Julian, Ann A: The following function will take in a list and return a string of the lists' items. This can then be used for logging or printing purposes. def listToString(inList): outString = '' if len(inList)==1: outString = outString+str(inList[0]) if len(inList)>1: outString = outString+str(inList[0]) for items in inList[1:]: outString = outString+', '+str(items) return outString A: Try this print(*name) I found this from AssemblyAI video on youtube, watch this part A: In Kotlin you can use names.joinToString() Output: Sam, Peter, James, Julian, Ann
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 I want it to be like this; Sam, Peter, James, Julian, Ann Note: It must be in a single row.
[ "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", "General solution, works on arrays of non-strings:\n>>> print str(names)[1:-1]\n'Sam', 'Peter', 'James', 'Julian', 'Ann'\n\n", "If the input array is Integer type then you need to first convert array into string type array and then use join method for joining with , or space whatever you want. e.g:\n>>> arr = [1, 2, 4, 3]\n>>> print(\", \" . join(arr))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: sequence item 0: expected string, int found\n>>> sarr = [str(a) for a in arr]\n>>> print(\", \" . join(sarr))\n1, 2, 4, 3\n>>>\n\nDirect using of join which will join the integer and string will throw error as show above.\n", "There are two answers , First is use 'sep' setting\n>>> print(*names, sep = ', ')\n\nThe other is below\n>>> print(', '.join(names))\n\n", "try to use an asterisk before list's name with print statement:\nnames = [\"Sam\", \"Peter\", \"James\", \"Julian\", \"Ann\"] \nprint(*names)\n\noutput:\nSam Peter James Julian Ann\n\n", "This is what you need\n\", \".join(names)\n\n", "','.join(list) will work only if all the items in the list are strings. If you are looking to convert a list of numbers to a comma separated string. such as a = [1, 2, 3, 4] into '1,2,3,4' then you can either\nstr(a)[1:-1] # '1, 2, 3, 4'\n\nor\nstr(a).lstrip('[').rstrip(']') # '1, 2, 3, 4'\n\nalthough this won't remove any nested list.\nTo convert it back to a list\na = '1,2,3,4'\nimport ast\nast.literal_eval('['+a+']')\n#[1, 2, 3, 4]\n\n", "For array of integer type, we need to change it to string type first and than use join function to get clean output without brackets.\n arr = [1, 2, 3, 4, 5] \n print(', '.join(map(str, arr)))\n\nOUTPUT - 1, 2, 3, 4, 5\nFor array of string type, we need to use join function directly to get clean output without brackets.\n arr = [\"Ram\", \"Mohan\", \"Shyam\", \"Dilip\", \"Sohan\"]\n print(', '.join(arr)\n\nOUTPUT - Ram, Mohan, Shyam, Dilip, Sohan\n", "\nprint(*names) \n\nthis will work in python 3\nif you want them to be printed out as space separated.\nIf you need comma or anything else in between go ahead with .join() solution\n", "You need to loop through the list and use end=\" \"to keep it on one line\nnames = [\"Sam\", \"Peter\", \"James\", \"Julian\", \"Ann\"]\n index=0\n for name in names:\n print(names[index], end=\", \")\n index += 1\n\n", "I don't know if this is efficient as others but simple logic always works:\nimport sys\nname = [\"Sam\", \"Peter\", \"James\", \"Julian\", \"Ann\"]\nfor i in range(0, len(names)):\n sys.stdout.write(names[i])\n if i != len(names)-1:\n sys.stdout.write(\", \")\n\nOutput:\n\nSam, Peter, James, Julian, Ann\n\n", "The following function will take in a list and return a string of the lists' items.\nThis can then be used for logging or printing purposes.\ndef listToString(inList):\n outString = ''\n if len(inList)==1:\n outString = outString+str(inList[0])\n if len(inList)>1:\n outString = outString+str(inList[0])\n for items in inList[1:]:\n outString = outString+', '+str(items)\n return outString\n\n", "Try this\nprint(*name)\n\nI found this from AssemblyAI video on youtube, watch this part\n", "In Kotlin you can use\nnames.joinToString()\n\nOutput: Sam, Peter, James, Julian, Ann\n" ]
[ 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() Using openpxl, I tried to apply formula to entire column 'I' its not working as per the formula, I wanted formula to start from I2 but its start from I1 and wrong output as well. I have attached a screenshot. . Can someone please correct the code? Output of print(list(enumerate(sheet['I']))): A: 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. import openpyxl excelfile = 'foo.xlsx' workbook= openpyxl.load_workbook(excelfile) sheet = workbook.active mr = sheet.max_row # Last row to add formula to for row in sheet.iter_rows(min_col=9, max_col=9, min_row=2, max_row=mr): for cell in row: cr = cell.row # Get the current row number to use in formula cell.value = f'=IF(ISNUMBER(A{cr})*(A{cr} <> 0), A{cr}, IF(ISNUMBER(F{cr})*(F{cr} <> 0), F{cr}, IF(ISBLANK(A{cr})*ISBLANK(F{cr})*ISBLANK(H{cr}), 0, H{cr})))' workbook.save(excelfile) A: If you know the from and to row numbers, then you can use it like this: from openpyxl import load_workbook wb = load_workbook(filename="/content/sample_data/Book1.xlsx") ws = wb.active from_row = 2 to_row = 4 for i in range(from_row, to_row+1): ws[f"C{i}"] = f'=_xlfn.CONCAT(A{i}, "_", B{i})' wb.save("/content/sample_data/formula.xlsx") Input (Book1.xlsx): Output (formula.xlsx): I don't have your data, so I did not test the following formula; but your formula can be translated to format string as: for i in range(from_row, to_row+1): ws[f"I{i}"] = f'=IF(ISNUMBER(A{i})*(A{i}<>0),A{i},IF(ISNUMBER(F{i})*(F{i}<>0),F{i},IF(ISBLANK(A{i})*ISBLANK(F{i})*ISBLANK(H{i}),0,H{i})))' It formats the formula as: =IF(ISNUMBER(A2)*(A2<>0),A2,IF(ISNUMBER(F2)*(F2<>0),F2,IF(ISBLANK(A2)*ISBLANK(F2)*ISBLANK(H2),0,H2))) =IF(ISNUMBER(A3)*(A3<>0),A3,IF(ISNUMBER(F3)*(F3<>0),F3,IF(ISBLANK(A3)*ISBLANK(F3)*ISBLANK(H3),0,H3))) =IF(ISNUMBER(A4)*(A4<>0),A4,IF(ISNUMBER(F4)*(F4<>0),F4,IF(ISBLANK(A4)*ISBLANK(F4)*ISBLANK(H4),0,H4)))
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 'I' its not working as per the formula, I wanted formula to start from I2 but its start from I1 and wrong output as well. I have attached a screenshot. . Can someone please correct the code? Output of print(list(enumerate(sheet['I']))):
[ "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 \nfor row in sheet.iter_rows(min_col=9, max_col=9, min_row=2, max_row=mr):\n for cell in row:\n cr = cell.row # Get the current row number to use in formula\n cell.value = f'=IF(ISNUMBER(A{cr})*(A{cr} <> 0), A{cr}, IF(ISNUMBER(F{cr})*(F{cr} <> 0), F{cr}, IF(ISBLANK(A{cr})*ISBLANK(F{cr})*ISBLANK(H{cr}), 0, H{cr})))'\n\nworkbook.save(excelfile)\n\n", "If you know the from and to row numbers, then you can use it like this:\nfrom openpyxl import load_workbook\nwb = load_workbook(filename=\"/content/sample_data/Book1.xlsx\")\nws = wb.active\nfrom_row = 2\nto_row = 4\nfor i in range(from_row, to_row+1):\n ws[f\"C{i}\"] = f'=_xlfn.CONCAT(A{i}, \"_\", B{i})'\nwb.save(\"/content/sample_data/formula.xlsx\")\n\nInput (Book1.xlsx):\n\nOutput (formula.xlsx):\n\nI don't have your data, so I did not test the following formula; but your formula can be translated to format string as:\nfor i in range(from_row, to_row+1):\n ws[f\"I{i}\"] = f'=IF(ISNUMBER(A{i})*(A{i}<>0),A{i},IF(ISNUMBER(F{i})*(F{i}<>0),F{i},IF(ISBLANK(A{i})*ISBLANK(F{i})*ISBLANK(H{i}),0,H{i})))'\n\nIt formats the formula as:\n=IF(ISNUMBER(A2)*(A2<>0),A2,IF(ISNUMBER(F2)*(F2<>0),F2,IF(ISBLANK(A2)*ISBLANK(F2)*ISBLANK(H2),0,H2)))\n\n=IF(ISNUMBER(A3)*(A3<>0),A3,IF(ISNUMBER(F3)*(F3<>0),F3,IF(ISBLANK(A3)*ISBLANK(F3)*ISBLANK(H3),0,H3)))\n\n=IF(ISNUMBER(A4)*(A4<>0),A4,IF(ISNUMBER(F4)*(F4<>0),F4,IF(ISBLANK(A4)*ISBLANK(F4)*ISBLANK(H4),0,H4)))\n\n" ]
[ 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 test. At the end of the test, the screen must switch to end screen. My problem is that the screen loading doesn't appear before the entire test completion... and the application switch immediately to the last screen after the test. So actually when i click on the start button, the test start, and when it's finished, the laoding screen appear. I want this: Click on button < Loading Screen < Test < EndScreen Thanks a lot ! My .py file ` class IconButtonTooltips(MDIconButton, MDTooltip): pass class DeclarativeHardwareScreen(Screen): pass class DeclarativeScreenScreen(Screen): pass class DeclarativeChargerScreen(Screen): pass class DeclarativeKeyBoardScreen(Screen): pass class TitleScreen(Screen): def startGetAllHardware(self): self.manager.current = "LoadingScreen" threading.Thread(target=myHardware.getHardware()).start() class LoadingScreen(Screen): pass class EndScreen(Screen): pass class Certifitech(MDApp): def build(self): Builder.load_file("main.kv") screen_manager = ScreenManager() screen_manager.add_widget(TitleScreen(name='TitleScreen')) screen_manager.add_widget(LoadingScreen(name='LoadingScreen')) screen_manager.add_widget(EndScreen(name='EndScreen')) screen_manager.add_widget(DeclarativeHardwareScreen(name='DeclarativeHardwareScreen')) screen_manager.add_widget(DeclarativeScreenScreen(name='DeclarativeScreenScreen')) screen_manager.add_widget(DeclarativeChargerScreen(name='DeclarativeChargerScreen')) screen_manager.add_widget(DeclarativeKeyBoardScreen(name='DeclarativeKeyBoardScreen')) return screen_manager if __name__ == "__main__": Certifitech().run() ` My .kv file ` #: import utils kivy.utils <TitleScreen> MDFloatLayout: md_bg_color: kivy.utils.get_color_from_hex("#5B66FF") Image: source: "ressources/logo.png" size_hint: (0.3,0.3) pos_hint: {'center_x': 0.5, 'center_y': 0.8} Label: text: "Bienvenue dans le diagnostic de votre ordinateur !" font_size: 33.5 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.6} Label: text: "Manufacturer | Model" font_size: 33.5 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.4} MDRectangleFlatButton: text: "Démarrer" font_size: 25 padding: 20 pos_hint: {'center_x': 0.5, 'center_y': 0.2} text_color: "white" line_color: "white" on_press: root.startGetAllHardware() <LoadingScreen> MDFloatLayout: md_bg_color: kivy.utils.get_color_from_hex("#5B66FF") Image: source: "ressources/logo.png" size_hint: (0.3,0.3) pos_hint: {'center_x': 0.5, 'center_y': 0.8} Label: text: "Diagnostic en cours, veuillez patienter..." font_size: 33.5 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.5} MDSpinner: size_hint: None, None size: dp(46), dp(46) pos_hint: {'center_x': .5, 'center_y': .3} active: True color: (1,1,1,1) <EndScreen> MDFloatLayout: md_bg_color: kivy.utils.get_color_from_hex("#5B66FF") Image: source: "ressources/logo.png" size_hint: (0.3,0.3) pos_hint: {'center_x': 0.5, 'center_y': 0.8} Label: text: "Le diagnostic est termine !" font_size: 33.5 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.6} Label: text: "Vous allez être redirigé(e) d'ici quelques secondes..." font_size: 25 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.4} MDRectangleFlatButton: text: "Télecharger mon rapport de diagnostic" font_size: 25 padding: 20 pos_hint: {'center_x': 0.5, 'center_y': 0.2} text_color: "white" line_color: "white" ` A: The code for getHardware was not present so I added something to make an example. from kivy.clock import mainthread class TitleScreen(Screen): def getHardware(self, delay_seconds): for i in range(delay_seconds): time.sleep(1.0) print(i) self.change_screen() @mainthread def change_screen(self): self.manager.current = "EndScreen" def startGetAllHardware(self): self.manager.current = "LoadingScreen" threading.Thread(target=self.getHardware, args=(5, )).start() print("startGetAllHardware has executed") This will create and start a new Thread and it can continue as long as it needs, freeing the gui to display the loading screen. When the threaded function completes its job it will force changing the screen. The imports were missing so I added this chunk to make it run. #!/usr/bin/env python3 # -*- coding: utf-8 -*- import time from kivymd.uix.button import MDIconButton from kivymd.uix.tooltip import MDTooltip from kivymd.uix.screen import Screen import threading from kivy.lang import Builder from kivymd.app import MDApp from kivymd.uix.screenmanager import ScreenManager
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 screen must switch to end screen. My problem is that the screen loading doesn't appear before the entire test completion... and the application switch immediately to the last screen after the test. So actually when i click on the start button, the test start, and when it's finished, the laoding screen appear. I want this: Click on button < Loading Screen < Test < EndScreen Thanks a lot ! My .py file ` class IconButtonTooltips(MDIconButton, MDTooltip): pass class DeclarativeHardwareScreen(Screen): pass class DeclarativeScreenScreen(Screen): pass class DeclarativeChargerScreen(Screen): pass class DeclarativeKeyBoardScreen(Screen): pass class TitleScreen(Screen): def startGetAllHardware(self): self.manager.current = "LoadingScreen" threading.Thread(target=myHardware.getHardware()).start() class LoadingScreen(Screen): pass class EndScreen(Screen): pass class Certifitech(MDApp): def build(self): Builder.load_file("main.kv") screen_manager = ScreenManager() screen_manager.add_widget(TitleScreen(name='TitleScreen')) screen_manager.add_widget(LoadingScreen(name='LoadingScreen')) screen_manager.add_widget(EndScreen(name='EndScreen')) screen_manager.add_widget(DeclarativeHardwareScreen(name='DeclarativeHardwareScreen')) screen_manager.add_widget(DeclarativeScreenScreen(name='DeclarativeScreenScreen')) screen_manager.add_widget(DeclarativeChargerScreen(name='DeclarativeChargerScreen')) screen_manager.add_widget(DeclarativeKeyBoardScreen(name='DeclarativeKeyBoardScreen')) return screen_manager if __name__ == "__main__": Certifitech().run() ` My .kv file ` #: import utils kivy.utils <TitleScreen> MDFloatLayout: md_bg_color: kivy.utils.get_color_from_hex("#5B66FF") Image: source: "ressources/logo.png" size_hint: (0.3,0.3) pos_hint: {'center_x': 0.5, 'center_y': 0.8} Label: text: "Bienvenue dans le diagnostic de votre ordinateur !" font_size: 33.5 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.6} Label: text: "Manufacturer | Model" font_size: 33.5 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.4} MDRectangleFlatButton: text: "Démarrer" font_size: 25 padding: 20 pos_hint: {'center_x': 0.5, 'center_y': 0.2} text_color: "white" line_color: "white" on_press: root.startGetAllHardware() <LoadingScreen> MDFloatLayout: md_bg_color: kivy.utils.get_color_from_hex("#5B66FF") Image: source: "ressources/logo.png" size_hint: (0.3,0.3) pos_hint: {'center_x': 0.5, 'center_y': 0.8} Label: text: "Diagnostic en cours, veuillez patienter..." font_size: 33.5 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.5} MDSpinner: size_hint: None, None size: dp(46), dp(46) pos_hint: {'center_x': .5, 'center_y': .3} active: True color: (1,1,1,1) <EndScreen> MDFloatLayout: md_bg_color: kivy.utils.get_color_from_hex("#5B66FF") Image: source: "ressources/logo.png" size_hint: (0.3,0.3) pos_hint: {'center_x': 0.5, 'center_y': 0.8} Label: text: "Le diagnostic est termine !" font_size: 33.5 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.6} Label: text: "Vous allez être redirigé(e) d'ici quelques secondes..." font_size: 25 color: (1,1,1,1) pos_hint: {'center_x': 0.5, 'center_y': 0.4} MDRectangleFlatButton: text: "Télecharger mon rapport de diagnostic" font_size: 25 padding: 20 pos_hint: {'center_x': 0.5, 'center_y': 0.2} text_color: "white" line_color: "white" `
[ "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 @mainthread\n def change_screen(self):\n self.manager.current = \"EndScreen\"\n\n def startGetAllHardware(self):\n self.manager.current = \"LoadingScreen\"\n threading.Thread(target=self.getHardware, args=(5, )).start()\n print(\"startGetAllHardware has executed\")\n\nThis will create and start a new Thread and it can continue as long as it needs, freeing the gui to display the loading screen. When the threaded function completes its job it will force changing the screen.\nThe imports were missing so I added this chunk to make it run.\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport time\nfrom kivymd.uix.button import MDIconButton\nfrom kivymd.uix.tooltip import MDTooltip\nfrom kivymd.uix.screen import Screen\nimport threading\nfrom kivy.lang import Builder\nfrom kivymd.app import MDApp\nfrom kivymd.uix.screenmanager import ScreenManager\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" the result I want to get is string = "hi. good morning axq" I found these examples (as a reference on how to tweak the one I want) import re str = "hi.)hello| good morning" re.sub(r"(?<=\)).*?(?=\|)", "", str) >>>'hi.)| good morning' and also this one >>> import re >>> x = "This is a sentence. (once a day) [twice a day]" >>> re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", x) 'This is a sentence. () []' and this one >>> import re >>> x = "This is a sentence. (once a day) [twice a day]" >>> re.sub("[\(\[].*?[\)\]]", "", x) 'This is a sentence. ' But I still can't get the syntax for my case. I want to learn the general syntax of this as well (i.e., customization). A: 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. import re str = "hi.-hello\n good morning and a good-long \n day" re.sub(r"-.*\n", "", str) >>> hi. good morning and a good day Edit: I have found out the trick for several symbol pairs: str = "hi.-hello\n good morning and a good-long \n day (delete this), bye" strt =re.sub(r"[\(\-].*?[\n\)]", "", str) print(strt) >>> hi. good morning and a good day , bye For several pairs put all into the brackets [<remove from>].*?[<remove to>]. Then each symbol that you want to remove has the form \<symbol to remove start/end>. In this example \-, \n (or \(\n)).
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 these examples (as a reference on how to tweak the one I want) import re str = "hi.)hello| good morning" re.sub(r"(?<=\)).*?(?=\|)", "", str) >>>'hi.)| good morning' and also this one >>> import re >>> x = "This is a sentence. (once a day) [twice a day]" >>> re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", x) 'This is a sentence. () []' and this one >>> import re >>> x = "This is a sentence. (once a day) [twice a day]" >>> re.sub("[\(\[].*?[\)\]]", "", x) 'This is a sentence. ' But I still can't get the syntax for my case. I want to learn the general syntax of this as well (i.e., customization).
[ "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>>> hi. good morning and a good day\n\nEdit: I have found out the trick for several symbol pairs:\nstr = \"hi.-hello\\n good morning and a good-long \\n day (delete this), bye\"\nstrt =re.sub(r\"[\\(\\-].*?[\\n\\)]\", \"\", str)\nprint(strt)\n>>> hi. good morning and a good day , bye\n\nFor several pairs put all into the brackets [<remove from>].*?[<remove to>]. Then each symbol that you want to remove has the form \\<symbol to remove start/end>. In this example \\-, \\n (or \\(\\n)).\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 A 88 2 2 history B 83 1 3 math A 85 3 3 history B 76 3 and the desire output is studentid info 1 "{""math"":[{""teacher"":""A"",""grade"":91,""rank"":1}], ""history"":[{""teacher"":""B"",""grade"":79,""rank"":2}]}" 2 "{""math"":[{""teacher"":""A"",""grade"":88,""rank"":2}], ""history"":[{""teacher"":""B"",""grade"":83,""rank"":1}]}" 3 "{""math"":[{""teacher"":""A"",""grade"":85,""rank"":3}], ""history"":[{""teacher"":""B"",""grade"":76,""rank"":3}]}" A: 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: df = df.set_index(['studentid','course']) df.to_dict(orient='index') Outputs: {(1, 'math'): {'teacher': 'A', 'grade': 91, 'rank': 1}, (1, 'history'): {'teacher': 'B', 'grade': 79, 'rank': 2}, (2, 'math'): {'teacher': 'A', 'grade': 88, 'rank': 2}, (2, 'history'): {'teacher': 'B', 'grade': 83, 'rank': 1}, (3, 'math'): {'teacher': 'A', 'grade': 85, 'rank': 3}, (3, 'history'): {'teacher': 'B', 'grade': 76, 'rank': 3}} A: Considering that the initial dataframe is df, there are various options, depending on the exact desired output. If one wants the info column to be a dictionary of lists, this will do the work df_new = df.groupby('studentid').apply(lambda x: x.drop('studentid', axis=1).to_dict(orient='list')).reset_index(name='info') [Out]: studentid info 0 1 {'course': ['math', 'history'], 'teacher': ['A... 1 2 {'course': ['math', 'history'], 'teacher': ['A... 2 3 {'course': ['math', 'history'], 'teacher': ['A... If one wants a list of dictionaries, then do the following df_new = df.groupby('studentid').apply(lambda x: x.drop('studentid', axis=1).to_dict(orient='records')).reset_index(name='info') [Out]: studentid info 0 1 [{'course': 'math', 'teacher': 'A', 'grade': 9... 1 2 [{'course': 'math', 'teacher': 'A', 'grade': 8... 2 3 [{'course': 'math', 'teacher': 'A', 'grade': 8...
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 history B 76 3 and the desire output is studentid info 1 "{""math"":[{""teacher"":""A"",""grade"":91,""rank"":1}], ""history"":[{""teacher"":""B"",""grade"":79,""rank"":2}]}" 2 "{""math"":[{""teacher"":""A"",""grade"":88,""rank"":2}], ""history"":[{""teacher"":""B"",""grade"":83,""rank"":1}]}" 3 "{""math"":[{""teacher"":""A"",""grade"":85,""rank"":3}], ""history"":[{""teacher"":""B"",""grade"":76,""rank"":3}]}"
[ "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:\n{(1, 'math'): {'teacher': 'A', 'grade': 91, 'rank': 1},\n (1, 'history'): {'teacher': 'B', 'grade': 79, 'rank': 2},\n (2, 'math'): {'teacher': 'A', 'grade': 88, 'rank': 2},\n (2, 'history'): {'teacher': 'B', 'grade': 83, 'rank': 1},\n (3, 'math'): {'teacher': 'A', 'grade': 85, 'rank': 3},\n (3, 'history'): {'teacher': 'B', 'grade': 76, 'rank': 3}}\n\n", "Considering that the initial dataframe is df, there are various options, depending on the exact desired output.\n\nIf one wants the info column to be a dictionary of lists, this will do the work\ndf_new = df.groupby('studentid').apply(lambda x: x.drop('studentid', axis=1).to_dict(orient='list')).reset_index(name='info')\n\n[Out]:\n\n studentid info\n0 1 {'course': ['math', 'history'], 'teacher': ['A...\n1 2 {'course': ['math', 'history'], 'teacher': ['A...\n2 3 {'course': ['math', 'history'], 'teacher': ['A...\n\n\nIf one wants a list of dictionaries, then do the following\ndf_new = df.groupby('studentid').apply(lambda x: x.drop('studentid', axis=1).to_dict(orient='records')).reset_index(name='info')\n\n[Out]:\n\n studentid info\n0 1 [{'course': 'math', 'teacher': 'A', 'grade': 9...\n1 2 [{'course': 'math', 'teacher': 'A', 'grade': 8...\n2 3 [{'course': 'math', 'teacher': 'A', 'grade': 8...\n\n\n\n" ]
[ 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(): app = application.Application() path = input("path : ") DOCs = os.listdir(path) if len(DOCs) > 0: for i in os.listdir(path): if i.endswith('.txt'): app.start("notepad.exe") app.Notepad.menu_select("File->Open") Open_file() i wrote it like this. it opens notepad but i can't open all the txt files in that folder. A: def Open_file(): app = application.Application() path = input("path : ") DOCs = os.listdir(path) absolutePath = os.getcwd()+"/"+path if len(DOCs) > 0: for i in os.listdir(path): if i.endswith('.txt'): app.start(f"notepad.exe {absolutePath}/{i}")
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() path = input("path : ") DOCs = os.listdir(path) if len(DOCs) > 0: for i in os.listdir(path): if i.endswith('.txt'): app.start("notepad.exe") app.Notepad.menu_select("File->Open") Open_file() i wrote it like this. it opens notepad but i can't open all the txt files in that folder.
[ "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}\")\n\n" ]
[ 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 code: class OffboardingSchema(Schema): suggested_relieving_date = fields.Date(format="%Y-%m-%d")` The output: { "success": false, "errors": { "suggested_relieving_date": [ "Not a valid date." ] }, "status": 400 } I have changed the type to string for now but it is not a proper fix. I need to know if "" cases can be skipped or handled in anyway for date format. A: What do you think about switching empty strings to None in advance and accepting them? This code converts all empty strings to None. But you can also differentiate based on the field name if you use a simple if condition. from marshmallow import pre_load class OffboardingSchema(Schema): suggested_relieving_date = fields.Date( required=False, allow_none=True, format='%Y-%m-%d' ) @pre_load def string_to_none(self, data, many, **kwargs): for k, v in data.items(): data[k] = v or None return data
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(Schema): suggested_relieving_date = fields.Date(format="%Y-%m-%d")` The output: { "success": false, "errors": { "suggested_relieving_date": [ "Not a valid date." ] }, "status": 400 } I have changed the type to string for now but it is not a proper fix. I need to know if "" cases can be skipped or handled in anyway for date format.
[ "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_relieving_date = fields.Date(\n required=False, \n allow_none=True, \n format='%Y-%m-%d'\n )\n\n @pre_load\n def string_to_none(self, data, many, **kwargs):\n for k, v in data.items():\n data[k] = v or None\n return data\n\n" ]
[ 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: year() a=int(input("Select the year:")) if a == 2018: csv = pd.read_csv("C:\\\\Users\\\\seena\\\\OneDrive\\\\Desktop\\\\2022-11-18 20.55.00\\\\Project csv BOTH.csv")#importing a csv file df1=pd.DataFrame(csv) print(df1) elif a == 0: break else : print("Invalid choice") c = input("Press Enter to continue selection") ,,, i tryed making index as false but its not working for me i also cant seem to find a better way what i get is : select the year :2020 output: 0 1 203 283 1 2 376 249 what i want is to get rid of the index or replace it with the month is all
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:")) if a == 2018: csv = pd.read_csv("C:\\\\Users\\\\seena\\\\OneDrive\\\\Desktop\\\\2022-11-18 20.55.00\\\\Project csv BOTH.csv")#importing a csv file df1=pd.DataFrame(csv) print(df1) elif a == 0: break else : print("Invalid choice") c = input("Press Enter to continue selection") ,,, i tryed making index as false but its not working for me i also cant seem to find a better way what i get is : select the year :2020 output: 0 1 203 283 1 2 376 249 what i want is to get rid of the index or replace it with the month is all
[]
[]
[ "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 & state test[['city', 'state_names']] = test['NAME10'].str.split(',', 1, expand=True) # Remove trailing & leading spaces test[['city', 'state_names']] = test[['city', 'state_names']].apply(lambda x: x.str.strip()) test.head() UACE10 AFFGEOID10 GEOID10 NAME10 LSAD10 UATYP10 ALAND10 AWATER10 geometry city state_names 0 88732 400C100US88732 88732 Tucson, AZ 75 U 915276150 2078695 MULTIPOLYGON (((-110.81345 32.11910, -110.7987... Tucson AZ 1 01819 400C100US01819 01819 Alturas, CA 76 C 4933312 16517 MULTIPOLYGON (((-120.54610 41.51264, -120.5459... Alturas CA 2 22366 400C100US22366 22366 Davenport, IA--IL 75 U 357345121 21444164 MULTIPOLYGON (((-90.36678 41.53636, -90.36462 ... Davenport IA--IL 3 93322 400C100US93322 93322 Waynesboro, PA--MD 76 C 45455957 88872 MULTIPOLYGON (((-77.50746 39.71577, -77.50605 ... Waynesboro PA--MD 4 02548 400C100US02548 02548 Angola, IN 76 C 23646957 3913803 MULTIPOLYGON (((-85.01157 41.59300, -85.00589 ... Angola IN I'm trying to explode state_names by rows test.assign(state=test["state_names"].str.split("--")).explode('state') Error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-47-5532b7b6cbdf> in <module> ----> 1 test.assign(state=city_geo["state_names"].str.split("--")).explode('state') TypeError: explode() takes 1 positional argument but 2 were given when I'm trying to do without the geometry it's working test = test[['UACE10', 'AFFGEOID10', 'GEOID10', 'NAME10', 'LSAD10', 'UATYP10', 'ALAND10', 'AWATER10', 'city', 'state_names']].head() test.assign(state=test["state_names"].str.split("--")).explode('state') UACE10 AFFGEOID10 GEOID10 NAME10 LSAD10 UATYP10 ALAND10 AWATER10 city state_names state 0 88732 400C100US88732 88732 Tucson, AZ 75 U 915276150 2078695 Tucson AZ AZ 1 01819 400C100US01819 01819 Alturas, CA 76 C 4933312 16517 Alturas CA CA 2 22366 400C100US22366 22366 Davenport, IA--IL 75 U 357345121 21444164 Davenport IA--IL IA 2 22366 400C100US22366 22366 Davenport, IA--IL 75 U 357345121 21444164 Davenport IA--IL IL 3 93322 400C100US93322 93322 Waynesboro, PA--MD 76 C 45455957 88872 Waynesboro PA--MD PA 3 93322 400C100US93322 93322 Waynesboro, PA--MD 76 C 45455957 88872 Waynesboro PA--MD MD 4 02548 400C100US02548 02548 Angola, IN 76 C 23646957 3913803 Angola IN IN How to explode geopandas dataframe with Geometry? A: In this case, the data can be read in as a data frame and then converted to a geopandas data frame after some processing. import geopandas as gpd url = 'https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_ua10_500k.zip' test = gpd.read_file(url) df = pd.DataFrame(test) df[['city', 'state_names']] = df['NAME10'].str.split(',', 1, expand=True) df = df.assign(state=df["state_names"].str.split("--")).explode('state') # convert df to gdf test = gpd.GeoDataFrame(df, geometry='geometry') test.crs output <Geographic 2D CRS: EPSG:4269> Name: NAD83 Axis Info [ellipsoidal]: - Lat[north]: Geodetic latitude (degree) - Lon[east]: Geodetic longitude (degree) Area of Use: - name: North America - onshore and offshore: Canada - Alberta; British Columbia; Manitoba; New Brunswick; Newfoundland and Labrador; Northwest Territories; Nova Scotia; Nunavut; Ontario; Prince Edward Island; Quebec; Saskatchewan; Yukon. Puerto Rico. United States (USA) - Alabama; Alaska; Arizona; Arkansas; California; Colorado; Connecticut; Delaware; Florida; Georgia; Hawaii; Idaho; Illinois; Indiana; Iowa; Kansas; Kentucky; Louisiana; Maine; Maryland; Massachusetts; Michigan; Minnesota; Mississippi; Missouri; Montana; Nebraska; Nevada; New Hampshire; New Jersey; New Mexico; New York; North Carolina; North Dakota; Ohio; Oklahoma; Oregon; Pennsylvania; Rhode Island; South Carolina; South Dakota; Tennessee; Texas; Utah; Vermont; Virginia; Washington; West Virginia; Wisconsin; Wyoming. US Virgin Islands. British Virgin Islands. - bounds: (167.65, 14.92, -47.74, 86.46) Datum: North American Datum 1983 - Ellipsoid: GRS 1980 - Prime Meridian: Greenwich
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, expand=True) # Remove trailing & leading spaces test[['city', 'state_names']] = test[['city', 'state_names']].apply(lambda x: x.str.strip()) test.head() UACE10 AFFGEOID10 GEOID10 NAME10 LSAD10 UATYP10 ALAND10 AWATER10 geometry city state_names 0 88732 400C100US88732 88732 Tucson, AZ 75 U 915276150 2078695 MULTIPOLYGON (((-110.81345 32.11910, -110.7987... Tucson AZ 1 01819 400C100US01819 01819 Alturas, CA 76 C 4933312 16517 MULTIPOLYGON (((-120.54610 41.51264, -120.5459... Alturas CA 2 22366 400C100US22366 22366 Davenport, IA--IL 75 U 357345121 21444164 MULTIPOLYGON (((-90.36678 41.53636, -90.36462 ... Davenport IA--IL 3 93322 400C100US93322 93322 Waynesboro, PA--MD 76 C 45455957 88872 MULTIPOLYGON (((-77.50746 39.71577, -77.50605 ... Waynesboro PA--MD 4 02548 400C100US02548 02548 Angola, IN 76 C 23646957 3913803 MULTIPOLYGON (((-85.01157 41.59300, -85.00589 ... Angola IN I'm trying to explode state_names by rows test.assign(state=test["state_names"].str.split("--")).explode('state') Error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-47-5532b7b6cbdf> in <module> ----> 1 test.assign(state=city_geo["state_names"].str.split("--")).explode('state') TypeError: explode() takes 1 positional argument but 2 were given when I'm trying to do without the geometry it's working test = test[['UACE10', 'AFFGEOID10', 'GEOID10', 'NAME10', 'LSAD10', 'UATYP10', 'ALAND10', 'AWATER10', 'city', 'state_names']].head() test.assign(state=test["state_names"].str.split("--")).explode('state') UACE10 AFFGEOID10 GEOID10 NAME10 LSAD10 UATYP10 ALAND10 AWATER10 city state_names state 0 88732 400C100US88732 88732 Tucson, AZ 75 U 915276150 2078695 Tucson AZ AZ 1 01819 400C100US01819 01819 Alturas, CA 76 C 4933312 16517 Alturas CA CA 2 22366 400C100US22366 22366 Davenport, IA--IL 75 U 357345121 21444164 Davenport IA--IL IA 2 22366 400C100US22366 22366 Davenport, IA--IL 75 U 357345121 21444164 Davenport IA--IL IL 3 93322 400C100US93322 93322 Waynesboro, PA--MD 76 C 45455957 88872 Waynesboro PA--MD PA 3 93322 400C100US93322 93322 Waynesboro, PA--MD 76 C 45455957 88872 Waynesboro PA--MD MD 4 02548 400C100US02548 02548 Angola, IN 76 C 23646957 3913803 Angola IN IN How to explode geopandas dataframe with Geometry?
[ "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']] = df['NAME10'].str.split(',', 1, expand=True)\ndf = df.assign(state=df[\"state_names\"].str.split(\"--\")).explode('state')\n\n# convert df to gdf\ntest = gpd.GeoDataFrame(df, geometry='geometry')\n\ntest.crs\n\noutput\n<Geographic 2D CRS: EPSG:4269>\nName: NAD83\nAxis Info [ellipsoidal]:\n- Lat[north]: Geodetic latitude (degree)\n- Lon[east]: Geodetic longitude (degree)\nArea of Use:\n- name: North America - onshore and offshore: Canada - Alberta; British Columbia; Manitoba; New Brunswick; Newfoundland and Labrador; Northwest Territories; Nova Scotia; Nunavut; Ontario; Prince Edward Island; Quebec; Saskatchewan; Yukon. Puerto Rico. United States (USA) - Alabama; Alaska; Arizona; Arkansas; California; Colorado; Connecticut; Delaware; Florida; Georgia; Hawaii; Idaho; Illinois; Indiana; Iowa; Kansas; Kentucky; Louisiana; Maine; Maryland; Massachusetts; Michigan; Minnesota; Mississippi; Missouri; Montana; Nebraska; Nevada; New Hampshire; New Jersey; New Mexico; New York; North Carolina; North Dakota; Ohio; Oklahoma; Oregon; Pennsylvania; Rhode Island; South Carolina; South Dakota; Tennessee; Texas; Utah; Vermont; Virginia; Washington; West Virginia; Wisconsin; Wyoming. US Virgin Islands. British Virgin Islands.\n- bounds: (167.65, 14.92, -47.74, 86.46)\nDatum: North American Datum 1983\n- Ellipsoid: GRS 1980\n- Prime Meridian: Greenwich\n\n" ]
[ 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 list if students from here import itertools as it class ClassroomOrganizer: def __init__(self): self.sorted_names = self._sort_alphabetically(student_roster) def __repr__(self): return f'{self.get_combinations(2)}' def __iter__(self): self.c = 0 return self def __next__(self): if self.c < len(self.sorted_names): x = self.sorted_names[self.c] self.c += 1 return x else: raise StopIteration def _sort_alphabetically(self,students): names = [] for student_info in students: name = student_info['name'] names.append(name) return sorted(`your text`names) def get_students_with_subject(self, subject): selected_students = [] for student in student_roster: if student['favorite_subject'] == subject: selected_students.append((student['name'], subject)) return selected_students def get_combinations(self, r): return it.combinations(self.sorted_names, r) a = ClassroomOrganizer() # for i in a: # print(i) print(repr(a)) I tried displaying objects that don't rely on anther library, and they dispayed properly. A: 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 1. unpack it inside a variable like: def get_combinations(self, r): *res, = it.combinations(self.sorted_names, r) return res OR 2. Iter through it insede a loop and leave the original code intact like for i in a.get_combinations(2): print(i) The second solution I preffered
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 ClassroomOrganizer: def __init__(self): self.sorted_names = self._sort_alphabetically(student_roster) def __repr__(self): return f'{self.get_combinations(2)}' def __iter__(self): self.c = 0 return self def __next__(self): if self.c < len(self.sorted_names): x = self.sorted_names[self.c] self.c += 1 return x else: raise StopIteration def _sort_alphabetically(self,students): names = [] for student_info in students: name = student_info['name'] names.append(name) return sorted(`your text`names) def get_students_with_subject(self, subject): selected_students = [] for student in student_roster: if student['favorite_subject'] == subject: selected_students.append((student['name'], subject)) return selected_students def get_combinations(self, r): return it.combinations(self.sorted_names, r) a = ClassroomOrganizer() # for i in a: # print(i) print(repr(a)) I tried displaying objects that don't rely on anther library, and they dispayed properly.
[ "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 res\n\nOR\n2. Iter through it insede a loop and leave the original code intact like\n for i in a.get_combinations(2):\n print(i)\n\nThe second solution I preffered\n" ]
[ 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) #example: if n=7 then print : 1,1,2,3,5,8,13 and sum is 32 The error I have is, when I put sum = sum + res Doesnt print & run the program Currently, how could you implement the total sum? A: You simply need to calculate sum in the for loop, not in the fibo(n). Here take a look: def fibo(n): if n<2: return 1 else: res = fibo(n-1) + fibo(n-2) return res n=7 sum = 0 for i in range(0, n): r = fibo(i) sum += r print(r) print("Suma", sum) I used r in order to call fibo once in each loop. A: Let me first point out that the sum of the first 7 terms of the Fibonacci sequence is not 32. That sum is 33. Now to the problem. Here is how I would solve the problem. I would first define the function that calculates the n th term of the Fibonacci sequence as follows: def fibo(n): if n in [1,2]: return 1 else: res = fibo(n-1) + fibo(n-2) return res Then I would define a function to calculate the sum of the first n terms of the Fibonacci sequence as follows. def sum_fibo(n): res = [fibo(i) for i in range(1, n+1)] print(res) return sum(res) So if I do [In] sum_fibo(7) I get [1, 1, 2, 3, 5, 8, 13] out >>> 33 NOTE: In defining the functions above, I have assumed that the input of the function is always going to be a positive integer though the Fibonacci can be extended to cover all real and complex numbers as shown on this wiki page. A: actually i don't think this needs to be that complicated the fibonacci sequence is very interesting in a maltitude of ways for example, if you want the sum up the 7th fibonacci number, then have checked what the 9th fibonacci number - 1 is? Now how do we find the n'th fibonacci number? p = (1+5**.5)/2 q = (1-5**.5)/2 def fibo(n): return 1/5**.5*(p**n-q**n) and now we can can find the sum up to any number in one calculation! for example for 7 fibo(9)- 1 output 33 and what is the actual answer 1+1+2+3+5+8+13=33 summa summarum: the fibonachi number that is two places further down the sequence minus 1 is the sum of the fibonachi numbers up to the number A: def sumOfNFibonacciNumbers(n): # Write your code here i = 1 sum = 2 fib_list = [0, 1, 1] if n == 1: return 0 if n == 2: return 1 if n == 3: return 2 for x in range(1,n-2): m = fib_list[-1] + fib_list[-2] fib_list.append(m) sum = sum + m return sum result = sumOfNFibonacciNumbers(10) print(result) A: Made some modifications to your code: def fibo(n): print(1) counter = 1 old_num = 0 new_num = 1 sum_fib = 1 while counter < n: fib = old_num + new_num print(fib) if counter < n: old_num = new_num new_num = fib sum_fib = sum_fib + fib counter = counter + 1 print('sum:' + str(sum_fib)) #fibo(5) A: First of all, the line sum = sum + res makes no sense because you never defined sum in the first place. So, your function should look like def fibo(n): if n<2: return 1 else: return fibo(n-1) + fibo(n-2) Second, you can get the sum by simply sum_ = 0 for i in range(0, n): sum_ += fibo(i) Or maybe sum_ = sum(fibo(i) for i in range(0, n)) Notice that the latter would only work if you have not overridden the built-in function named sum A: You are referring the variable sum before assignment. You may want to use the variable sum inside the for loop and assign the fibo to it. def fibo(n): if n<2: return 1 else: return fibo(n-1) + fibo(n-2) n=7 sum = 0 for i in range(1, n): sum += fibo(i) print(fibo(i)) print("suma", sum) A: Considering the start of the Fibonacci series with 1 rather than 0. def fib(no_of_elements): elements, start = [], 1 while start <= no_of_elements: if start in [1, 2]: elements.append(1) elif start >= 3: elements.append(elements[start-2]+elements[start-3]) start += 1 return elements, sum(elements) print(fib(8)) Output: ([1, 1, 2, 3, 5, 8, 13, 21], 54)
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,5,8,13 and sum is 32 The error I have is, when I put sum = sum + res Doesnt print & run the program Currently, how could you implement the total sum?
[ "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 call fibo once in each loop.\n", "Let me first point out that the sum of the first 7 terms of the Fibonacci sequence is not 32. That sum is 33. Now to the problem. Here is how I would solve the problem. I would first define the function that calculates the n th term of the Fibonacci sequence as follows: \ndef fibo(n):\n if n in [1,2]:\n return 1\n else:\n res = fibo(n-1) + fibo(n-2)\n return res\n\nThen I would define a function to calculate the sum of the first n terms of the Fibonacci sequence as follows.\ndef sum_fibo(n):\n res = [fibo(i) for i in range(1, n+1)]\n print(res)\n return sum(res)\n\nSo if I do \n[In] sum_fibo(7)\n\nI get \n [1, 1, 2, 3, 5, 8, 13]\nout >>> 33\n\nNOTE: In defining the functions above, I have assumed that the input of the function is always going to be a positive integer though the Fibonacci can be extended to cover all real and complex numbers as shown on this wiki page.\n", "actually i don't think this needs to be that complicated the fibonacci sequence is very interesting in a maltitude of ways for example, if you want the sum up the 7th fibonacci number, then have checked what the 9th fibonacci number - 1 is? Now how do we find the n'th fibonacci number?\np = (1+5**.5)/2\nq = (1-5**.5)/2\ndef fibo(n):\n return 1/5**.5*(p**n-q**n)\n\nand now we can can find the sum up to any number in one calculation! for example for 7\nfibo(9)- 1\n\noutput\n33\n\nand what is the actual answer\n1+1+2+3+5+8+13=33\n\nsumma summarum: the fibonachi number that is two places further down the sequence minus 1 is the sum of the fibonachi numbers up to the number\n", "def sumOfNFibonacciNumbers(n):\n# Write your code here\ni = 1\nsum = 2\nfib_list = [0, 1, 1]\nif n == 1:\n return 0\nif n == 2:\n return 1\nif n == 3:\n return 2\nfor x in range(1,n-2):\n m = fib_list[-1] + fib_list[-2]\n fib_list.append(m)\n sum = sum + m\nreturn sum\n\nresult = sumOfNFibonacciNumbers(10)\nprint(result)\n", "Made some modifications to your code:\ndef fibo(n):\n print(1)\n counter = 1\n old_num = 0\n new_num = 1\n sum_fib = 1\n while counter < n:\n fib = old_num + new_num\n print(fib)\n\n if counter < n:\n old_num = new_num\n new_num = fib\n sum_fib = sum_fib + fib\n counter = counter + 1\n\n print('sum:' + str(sum_fib))\n\n\n#fibo(5)\n\n", "First of all, the line sum = sum + res makes no sense because you never defined sum in the first place. \nSo, your function should look like\ndef fibo(n):\n if n<2:\n return 1\n else:\n return fibo(n-1) + fibo(n-2)\n\nSecond, you can get the sum by simply\nsum_ = 0\nfor i in range(0, n):\n sum_ += fibo(i)\n\nOr maybe\nsum_ = sum(fibo(i) for i in range(0, n))\n\nNotice that the latter would only work if you have not overridden the built-in function named sum\n", "You are referring the variable sum before assignment.\nYou may want to use the variable sum inside the for loop and assign the fibo to it.\n def fibo(n):\n if n<2:\n return 1\n else:\n return fibo(n-1) + fibo(n-2)\n\n\nn=7\nsum = 0\nfor i in range(1, n):\n sum += fibo(i)\n print(fibo(i))\n\nprint(\"suma\", sum)\n\n", "Considering the start of the Fibonacci series with 1 rather than 0.\ndef fib(no_of_elements):\n elements, start = [], 1\n while start <= no_of_elements:\n if start in [1, 2]:\n elements.append(1)\n elif start >= 3:\n elements.append(elements[start-2]+elements[start-3])\n start += 1\n return elements, sum(elements)\n\nprint(fib(8)) \n\nOutput:\n([1, 1, 2, 3, 5, 8, 13, 21], 54)\n" ]
[ 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 won't allow me to click on the checks and I'm not sure why? The checkmark appears momentarily when I click and then if I hold, it will stay there until I take my finger off the mouse but then will disappear again when I do. Not sure what's happening but here's the code: checkbutton_frame=tkinter.Frame(frame1, bg="#0073CF") checkbutton_frame.grid(row=5,column=0) liver_var=tkinter.StringVar(value=0) liver_check=tkinter.Checkbutton(checkbutton_frame, text="Liver", font=("Calibri",20), fg="#FFFFFF", variable=liver_var, onvalue=1, offvalue=0, bg="#0073CF") liver_check.grid(row=0, column=0) heart_var=tkinter.StringVar(value=0) heart_check=tkinter.Checkbutton(checkbutton_frame, text="Heart", font=("Calibri",20), fg="#FFFFFF", variable=heart_var, onvalue=1, offvalue=0, bg="#0073CF") heart_check.grid(row=0, column=1) lungR_var=tkinter.StringVar(value=0) lungR_check=tkinter.Checkbutton(checkbutton_frame, text="Lung(R)", font=("Calibri",20), fg="#FFFFFF", variable=lungR_var, onvalue=1, offvalue=0, bg="#0073CF") lungR_check.grid(row=0, column=2) lungL_var=tkinter.StringVar(value=0) lungL_check=tkinter.Checkbutton(checkbutton_frame, text="Lung(L)", font=("Calibri",20), fg="#FFFFFF", variable=lungL_var, onvalue=1, offvalue=0, bg="#0073CF") lungL_check.grid(row=0, column=3) kidneyR_var=tkinter.StringVar(value=0) kidneyR_check=tkinter.Checkbutton(checkbutton_frame, text="Kidney(R)", font=("Calibri",20), fg="#FFFFFF", variable=kidneyR_var, onvalue=1, offvalue=0, bg="#0073CF") kidneyR_check.grid(row=0, column=4) kidneyL_var=tkinter.StringVar(value=0) kidneyL_check=tkinter.Checkbutton(checkbutton_frame, text="Kidney(L)", font=("Calibri",20), fg="#FFFFFF", variable=kidneyL_var, onvalue=1, offvalue=0, bg="#0073CF") kidneyL_check.grid(row=0, column=5) pancreas_var=tkinter.StringVar(value=0) pancreas_check=tkinter.Checkbutton(checkbutton_frame, text="Pancreas", font=("Calibri",20), fg="#FFFFFF", variable=pancreas_var, onvalue=1, offvalue=0, bg="#0073CF") pancreas_check.grid(row=1, column=2) sbowel_var=tkinter.StringVar(value=0) sbowel_check=tkinter.Checkbutton(checkbutton_frame, text="Small Bowel", font=("Calibri",20), fg="#FFFFFF", variable=sbowel_var, onvalue=1, offvalue=0, bg="#0073CF") sbowel_check.grid(row=1, column=3) cornea_var=tkinter.StringVar(value=0) cornea_check=tkinter.Checkbutton(checkbutton_frame, text="Cornea", font=("Calibri",20), fg="#FFFFFF", variable=cornea_var, onvalue=1, offvalue=0, bg="#0073CF") cornea_check.grid(row=1, column=4) for widget in checkbutton_frame.winfo_children(): widget.grid_configure(pady=5, padx=10) Have found myself really confused especially since I've sampled this code from another program I have and it works there and I can't seem to find any differences in the code. Any thoughts? Thanks! A: Since the color of the tick are in white which is the same as the tick box, so it looks invisible. You can either set fg (the tick) or selectcolor (the tick box) to other color. Below code set fg="black" of the first checkbox ("Liver") and selectcolor="black" of the second checkbox ("Heart"): liver_var=tkinter.StringVar(value=0) liver_check=tkinter.Checkbutton(checkbutton_frame, text="Liver", font=("Calibri",20), fg="black", variable=liver_var, onvalue=1, offvalue=0, bg="#0073CF") liver_check.grid(row=0, column=0) heart_var=tkinter.StringVar(value=0) heart_check=tkinter.Checkbutton(checkbutton_frame, text="Heart", font=("Calibri",20), fg="#FFFFFF", variable=heart_var, onvalue=1, offvalue=0, bg="#0073CF", selectcolor="black") heart_check.grid(row=0, column=1) The result:
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 sure why? The checkmark appears momentarily when I click and then if I hold, it will stay there until I take my finger off the mouse but then will disappear again when I do. Not sure what's happening but here's the code: checkbutton_frame=tkinter.Frame(frame1, bg="#0073CF") checkbutton_frame.grid(row=5,column=0) liver_var=tkinter.StringVar(value=0) liver_check=tkinter.Checkbutton(checkbutton_frame, text="Liver", font=("Calibri",20), fg="#FFFFFF", variable=liver_var, onvalue=1, offvalue=0, bg="#0073CF") liver_check.grid(row=0, column=0) heart_var=tkinter.StringVar(value=0) heart_check=tkinter.Checkbutton(checkbutton_frame, text="Heart", font=("Calibri",20), fg="#FFFFFF", variable=heart_var, onvalue=1, offvalue=0, bg="#0073CF") heart_check.grid(row=0, column=1) lungR_var=tkinter.StringVar(value=0) lungR_check=tkinter.Checkbutton(checkbutton_frame, text="Lung(R)", font=("Calibri",20), fg="#FFFFFF", variable=lungR_var, onvalue=1, offvalue=0, bg="#0073CF") lungR_check.grid(row=0, column=2) lungL_var=tkinter.StringVar(value=0) lungL_check=tkinter.Checkbutton(checkbutton_frame, text="Lung(L)", font=("Calibri",20), fg="#FFFFFF", variable=lungL_var, onvalue=1, offvalue=0, bg="#0073CF") lungL_check.grid(row=0, column=3) kidneyR_var=tkinter.StringVar(value=0) kidneyR_check=tkinter.Checkbutton(checkbutton_frame, text="Kidney(R)", font=("Calibri",20), fg="#FFFFFF", variable=kidneyR_var, onvalue=1, offvalue=0, bg="#0073CF") kidneyR_check.grid(row=0, column=4) kidneyL_var=tkinter.StringVar(value=0) kidneyL_check=tkinter.Checkbutton(checkbutton_frame, text="Kidney(L)", font=("Calibri",20), fg="#FFFFFF", variable=kidneyL_var, onvalue=1, offvalue=0, bg="#0073CF") kidneyL_check.grid(row=0, column=5) pancreas_var=tkinter.StringVar(value=0) pancreas_check=tkinter.Checkbutton(checkbutton_frame, text="Pancreas", font=("Calibri",20), fg="#FFFFFF", variable=pancreas_var, onvalue=1, offvalue=0, bg="#0073CF") pancreas_check.grid(row=1, column=2) sbowel_var=tkinter.StringVar(value=0) sbowel_check=tkinter.Checkbutton(checkbutton_frame, text="Small Bowel", font=("Calibri",20), fg="#FFFFFF", variable=sbowel_var, onvalue=1, offvalue=0, bg="#0073CF") sbowel_check.grid(row=1, column=3) cornea_var=tkinter.StringVar(value=0) cornea_check=tkinter.Checkbutton(checkbutton_frame, text="Cornea", font=("Calibri",20), fg="#FFFFFF", variable=cornea_var, onvalue=1, offvalue=0, bg="#0073CF") cornea_check.grid(row=1, column=4) for widget in checkbutton_frame.winfo_children(): widget.grid_configure(pady=5, padx=10) Have found myself really confused especially since I've sampled this code from another program I have and it works there and I can't seem to find any differences in the code. Any thoughts? Thanks!
[ "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=tkinter.StringVar(value=0)\nliver_check=tkinter.Checkbutton(checkbutton_frame, text=\"Liver\", font=(\"Calibri\",20),\nfg=\"black\", variable=liver_var, onvalue=1, offvalue=0, bg=\"#0073CF\")\nliver_check.grid(row=0, column=0)\n\nheart_var=tkinter.StringVar(value=0)\nheart_check=tkinter.Checkbutton(checkbutton_frame, text=\"Heart\", font=(\"Calibri\",20),\nfg=\"#FFFFFF\", variable=heart_var, onvalue=1, offvalue=0, bg=\"#0073CF\",\nselectcolor=\"black\")\nheart_check.grid(row=0, column=1)\n\nThe result:\n\n" ]
[ 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', 'a+', newline = '') as f_object: writer_object = writer(f_object) writer_object.writerow(List1) writer_object.writerow(List2) this is the output of the code output of the python code A: Try this: List1=["test2"] List2=["test1"] with open (r"Z:\Images\Test\test.csv", 'a+') as f_object: writer_object = csv.writer(f_object) writer_object.writerow(List1) writer_object.writerow(List2)
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_object = writer(f_object) writer_object.writerow(List1) writer_object.writerow(List2) this is the output of the code output of the python code
[ "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 scriptPath: swagger_updater/build.py pythonInterpreter: /usr/bin/python3 Now, I want to run in the Release Pipeline, my release.py script which is in the same swagger_updater folder. What should I write in the Script Path? If I write swagger_updater/release.py it does not work. Please, see this image A: 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. In build pipeline: In release pipeline: Update: If you are using Azure Repo directly, please check the following steps:
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 pythonInterpreter: /usr/bin/python3 Now, I want to run in the Release Pipeline, my release.py script which is in the same swagger_updater folder. What should I write in the Script Path? If I write swagger_updater/release.py it does not work. Please, see this image
[ "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 following steps:\n\n\n" ]
[ 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.choice(cards))] comp_cards = [(random.choice(cards)), (random.choice(cards))] #scores player_score = sum(player_cards) comp_score = sum(comp_cards) print(f"Your Cards: {player_cards[0][1][2][3][4]}, current score: {player_score} Computer's first card: {comp_cards[0]}") hit = input("Type 'y' to get another card, type 'n' to pass: \n") The error occurs on the print statement and says that TypeError: 'int' object is not subscriptable in trying to make a blackjack game I tried to convert it into a string but ran into TypeError: list indices must be integers or slices, not str Any help from anyone anywhere is greatly appreciated as I am new to this so. I was trying to assign 2 random scores selected from the list and assign them to player_cards and comp_cards I was then attempting to print out these said scores to the user, using the scores positions in the given list A: 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. If you want the first at most 5 elements of the array you can use a slice, so {player_cards[0:4]} Which, since we're starting from the beginning of the array, can be abbreviated to {player_cards[:4]}
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 player_score = sum(player_cards) comp_score = sum(comp_cards) print(f"Your Cards: {player_cards[0][1][2][3][4]}, current score: {player_score} Computer's first card: {comp_cards[0]}") hit = input("Type 'y' to get another card, type 'n' to pass: \n") The error occurs on the print statement and says that TypeError: 'int' object is not subscriptable in trying to make a blackjack game I tried to convert it into a string but ran into TypeError: list indices must be integers or slices, not str Any help from anyone anywhere is greatly appreciated as I am new to this so. I was trying to assign 2 random scores selected from the list and assign them to player_cards and comp_cards I was then attempting to print out these said scores to the user, using the scores positions in the given list
[ "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 the first at most 5 elements of the array you can use a slice, so\n{player_cards[0:4]}\n\nWhich, since we're starting from the beginning of the array, can be abbreviated to\n{player_cards[:4]}\n\n" ]
[ 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__available"))).click() I can't get a response from your code. A: 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.
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 after googling for 2 hrs I'm still at a loss. I've tried from scipy.constants.physical_constants import electron volt_joule relationship I also tried import scipy.constants.physical_constants["electron volt-joule relationship"] Which produces File "<ipython-input-22-7c2fb3ec2156>", line 3 import scipy.constants.physical_constants["electron volt-joule relationship"] ^ SyntaxError: invalid syntax Am I misunderstanding the use of these physical constants? From scipy.org documentation I'm seeing that they come in the form physical_constants[name] = (value, unit, uncertainty) so I can get print(scipy.constants.physical_constants["electron volt-joule relationship"]) to return (1.602176634e-19, 'J', 0.0) but even import scipy.constants.physical_constants returns an error of ModuleNotFoundError Traceback (most recent call last) <ipython-input-21-b4d34ca28080> in <module> ----> 1 import scipy.constants.physical_constants ModuleNotFoundError: No module named 'scipy.constants.physical_constants' Is this constants library full of values you can reference the value, unit, and uncertainty of and not actually use in computations? A: It looks like the original poster's import statement is not formatted correctly. To get access to the constants include this import statement: from scipy import constants Then to access a specific constant, try: print(constants.electron_volt) returns: 1.602176634e-19 If the scipy package is not found, it can be added with: pip install scipy A: As 'electron volt_joule relationship' is one key inside a python dictionary called scypy.constants.physical_constants, it can not be imported, whereas the whole dictionary can be imported. As examples, let's load scipy.constants and physical_constants, and also, astropy.constants: import scipy.constants as syc import astropy.constants as ayc from scipy.constants import physical_constants as pyc Note that: print(type(syc),type(ayc),type(pyc)) returns: <class 'module'> <class 'module'> <class 'dict'>. You can also investigate contents of syc, ayc and pyc with function dir, or to make it shorter, a lambda function I like to call tab defined as: tab = lambda obj: [atr for atr in dir(obj) if '__' not in atr] tab(pyc) will return atributes and methods of python dicts, like dict.keys() and dict.values(). Inside pyc.keys() there is one called 'electron volt_joule relationship', and as it happens with all pyc contents or keys, returns a tuple containing value, unit and uncertainty for this definition: v,u,uc = pyc['electron volt_joule relationship'] so that v is a value, u is the physical unit and uc is the uncertainty. print(f'1eV = {v}{u} \u00B1 {uc}{u}') will print the relationship: 1eV = 1.602176634e-19J ± 0.0J Note that according to scipy, there is no uncertainty for this definition. Note also that there is an eV directly under syc: print(syc.eV) 1.602176634e-19 and it happens to be numerically identical to the absolute value of the electrical charge of one electron (firstly measured by Millikan in 1909), or the elementary charge, in Coulombs, also in syc.elementary_charge. At our example from astropy, ayp is a special class that gives us the physical units together with the constants values. To see it, just type ayc.e in a jupyter notebook, for instance: ayc.e 1.6021766×10−19C and: print(ayc.e) will give: Name = Electron charge Value = 1.6021766208e-19 Uncertainty = 9.8e-28 Unit = C Reference = CODATA 2014 so that there are other important attributes under ayc.e: print(f'{ayc.e.name} = {ayc.e.value}{ayc.e.unit} \u00B1 {ayc.e.uncertainty}{ayc.e.unit} ') Electron charge = 1.6021766208e-19C ± 9.8e-28C and we can see that according to astropy, there is a small uncertainty related with the elementary unit of electrical charge, that must be related with the eV to J relationship uncertainty by definition, after all.
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.physical_constants import electron volt_joule relationship I also tried import scipy.constants.physical_constants["electron volt-joule relationship"] Which produces File "<ipython-input-22-7c2fb3ec2156>", line 3 import scipy.constants.physical_constants["electron volt-joule relationship"] ^ SyntaxError: invalid syntax Am I misunderstanding the use of these physical constants? From scipy.org documentation I'm seeing that they come in the form physical_constants[name] = (value, unit, uncertainty) so I can get print(scipy.constants.physical_constants["electron volt-joule relationship"]) to return (1.602176634e-19, 'J', 0.0) but even import scipy.constants.physical_constants returns an error of ModuleNotFoundError Traceback (most recent call last) <ipython-input-21-b4d34ca28080> in <module> ----> 1 import scipy.constants.physical_constants ModuleNotFoundError: No module named 'scipy.constants.physical_constants' Is this constants library full of values you can reference the value, unit, and uncertainty of and not actually use in computations?
[ "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, it can be added with:\npip install scipy\n\n", "As 'electron volt_joule relationship' is one key inside a python dictionary called scypy.constants.physical_constants, it can not be imported, whereas the whole dictionary can be imported. As examples, let's load scipy.constants and physical_constants, and also, astropy.constants:\nimport scipy.constants as syc\nimport astropy.constants as ayc\nfrom scipy.constants import physical_constants as pyc\n\nNote that:\nprint(type(syc),type(ayc),type(pyc))\n\nreturns: <class 'module'> <class 'module'> <class 'dict'>. You can also investigate contents of syc, ayc and pyc with function dir, or to make it shorter, a lambda function I like to call tab defined as:\ntab = lambda obj: [atr for atr in dir(obj) if '__' not in atr]\n\ntab(pyc) will return atributes and methods of python dicts, like dict.keys() and dict.values(). Inside pyc.keys() there is one called 'electron volt_joule relationship', and as it happens with all pyc contents or keys, returns a tuple containing value, unit and uncertainty for this definition:\nv,u,uc = pyc['electron volt_joule relationship']\n\nso that v is a value, u is the physical unit and uc is the uncertainty.\nprint(f'1eV = {v}{u} \\u00B1 {uc}{u}')\n\nwill print the relationship:\n1eV = 1.602176634e-19J ± 0.0J\n\nNote that according to scipy, there is no uncertainty for this definition. Note also that there is an eV directly under syc:\nprint(syc.eV)\n1.602176634e-19\n\nand it happens to be numerically identical to the absolute value of the electrical charge of one electron (firstly measured by Millikan in 1909), or the elementary charge, in Coulombs, also in syc.elementary_charge. At our example from astropy, ayp is a special class that gives us the physical units together with the constants values. To see it, just type ayc.e in a jupyter notebook, for instance:\nayc.e\n1.6021766×10−19C\n\nand:\nprint(ayc.e)\n\nwill give:\nName = Electron charge\nValue = 1.6021766208e-19\nUncertainty = 9.8e-28\nUnit = C\nReference = CODATA 2014\n\nso that there are other important attributes under ayc.e:\nprint(f'{ayc.e.name} = {ayc.e.value}{ayc.e.unit} \\u00B1 {ayc.e.uncertainty}{ayc.e.unit} ')\nElectron charge = 1.6021766208e-19C ± 9.8e-28C\n\nand we can see that according to astropy, there is a small uncertainty related with the elementary unit of electrical charge, that must be related with the eV to J relationship uncertainty by definition, after all.\n" ]
[ 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 slow to be of any use. This example shows how long intellisense took to to find a local variable, and this is only after it was prompted to do so after I hit ctrl+enter. I've not been able to find a solution to this as of yet, so I am here to ask if anyone else has had a similar issue and ask how they have overcome it. A: It turned out it was a particular VS Code extension for me. Angular Language Service. Disabling this made it lightning quick. Try this to see if it is a particular extension. Open Command Palette (Ctrl+Shift+P) Type in "Disable all installed extensions" Enable them one by one or in groups and test the intellisense speed A: The problem might be with wrong setting configuration. You might want to make sure these setting are on: Controls if suggestions should automatically show up while typing "editor.quickSuggestions": { "other": true, "comments": false, "strings": false }, Controls the delay in ms after which quick suggestions will show up "editor.quickSuggestionsDelay": 10, A: Maybe it's Jedi. I mean its awesome but ... Tinkering with Jedi myself on bigger code bases I can confirm that it might be uber slow at times and pretty hard to figure out what the problems are... :/ Solution might be to switch to another language server! The VSCode Python extension has a "Language Server"-setting: aka python.languageServer. Pylance is MS own new language server. I just tried it and it all seems a little snappier. As of today this is tagged as Preview. So there might be improvements around the corner. A: My answer's for c++ but still kinda related. I'm using the C/C++ extension from Microsoft, and when I switched its Intelli Sense Engine setting from Default, with "context-aware results", to Tag Parser, with "'fuzzy' results that are not context-aware", it immediately started showing IntelliSense options instead of delaying for 5+ seconds. So maybe check the particular options of your language's or environment's extension(s). A: Open Command Palette (Ctrl+Shift+P) Select Developer: show running extension You will get their list of extensions and their reboot time If extension takes more than 500ms to activate there seems to be a problem with it You can press on right click and stop it more details... A: I had the same problem with Python on VS Code. In my case, disabling Jedi for IntelliSence made things faster. Just set "python.jediEnabled": false in the options. As memory is not a problem for me, I also enabled code analysis to keep parser trees in memory: "python.analysis.memory.keepLibraryAst": true A: I had the same problem. Disabling the checkbox for the "Snippets Prevent Quick Suggestions" option in VSCode settings seems to solve the problem of the loading time. Disable Quick Preview A: If you're working with Angular and noticed intellisense slowness in the past days, it could be Angular Language Service with its new Experimental-ivy feature. You can disable it by opening the extension settings: Then disable the Experimental-ivy feature: VS Code prompted me to enable it at some point, I enabled and since then intellisense is super slow. By disabling this with the steps above, now it's fast again. A: my issue was solved by disabling this extension that was not installed completely Visual Studio IntelliCode A: Use Below Values in settings.json file "editor.suggest.snippetsPreventQuickSuggestions": false, A: Strange solution for me, but disabling then re-enabling all extensions fixed the issue for me. A: For me, I had installed the Arduino extension. This was problematic as it thought it should be in use every time I was coding in C++ so it was really slowing down the autocompletes. I just disabled it for my workspace and everything work really quickly A: None of these solutions worked for me. What worked for me, is that I went to the extension settings and: changed IntelliSense mode to windows-gcc-arm64 (I was selecting different options for this one based on my os, till I found the fastest one) changed IntelliSense update delay from 2000 to 500 (this added a bigger boost, after the first boost from a change in IntelliSense mode) A: I used git without .gitignore . Add .gitignore and add unnecessary files and directories like virtualenv in that. A: Click the Windows key and R at the same time, then type %temp%, then find .vscode file. Delete it. Happy coding. A: I had the same issue, I disabled extensions one by one. Disabling "Live Server (v5.7.9)" extension fixed it for me. A: You could check as previously suggested, to disable some extensions and retry using the reference finder function. For my case, the Makefile Tools extension (https://marketplace.visualstudio.com/items?itemName=ms-vscode.makefile-tools), minutes after overtaking C/C++ IntelliSense, it just plainly broke over and over. A: For me it was the "Multiple clipboards for VSCode" extension, disabling it fixed my issues.
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 a local variable, and this is only after it was prompted to do so after I hit ctrl+enter. I've not been able to find a solution to this as of yet, so I am here to ask if anyone else has had a similar issue and ask how they have overcome it.
[ "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 intellisense speed\n\n", "The problem might be with wrong setting configuration.\nYou might want to make sure these setting are on:\nControls if suggestions should automatically show up while typing\n\"editor.quickSuggestions\": {\n \"other\": true,\n \"comments\": false,\n \"strings\": false\n},\n\nControls the delay in ms after which quick suggestions will show up\n\"editor.quickSuggestionsDelay\": 10,\n\n", "Maybe it's Jedi. I mean its awesome but ... Tinkering with Jedi myself on bigger code bases I can confirm that it might be uber slow at times and pretty hard to figure out what the problems are... :/\nSolution might be to switch to another language server! The VSCode Python extension has a \"Language Server\"-setting:\n\naka python.languageServer.\nPylance is MS own new language server. I just tried it and it all seems a little snappier. As of today this is tagged as Preview. So there might be improvements around the corner.\n", "My answer's for c++ but still kinda related.\nI'm using the C/C++ extension from Microsoft, and when I switched its Intelli Sense Engine setting from Default, with \"context-aware results\", to Tag Parser, with \"'fuzzy' results that are not context-aware\", it immediately started showing IntelliSense options instead of delaying for 5+ seconds.\nSo maybe check the particular options of your language's or environment's extension(s).\n", "Open Command Palette (Ctrl+Shift+P)\n\nSelect Developer: show running extension\nYou will get their list of extensions and their reboot time\n\nIf extension takes more than 500ms to activate there seems to be a problem with it\nYou can press on right click and stop it\n\nmore details...\n", "I had the same problem with Python on VS Code. In my case, disabling Jedi for IntelliSence made things faster.\nJust set \"python.jediEnabled\": false in the options.\nAs memory is not a problem for me, I also enabled code analysis to keep parser trees in memory: \"python.analysis.memory.keepLibraryAst\": true\n", "I had the same problem. Disabling the checkbox for the \"Snippets Prevent Quick Suggestions\" option in VSCode settings seems to solve the problem of the loading time.\nDisable Quick Preview\n", "If you're working with Angular and noticed intellisense slowness in the past days, it could be Angular Language Service with its new Experimental-ivy feature.\nYou can disable it by opening the extension settings:\n\nThen disable the Experimental-ivy feature:\n\n\nVS Code prompted me to enable it at some point, I enabled and since then intellisense is super slow. By disabling this with the steps above, now it's fast again.\n\n", "my issue was solved by disabling this extension that was not installed completely\n\nVisual Studio IntelliCode\n\n", "Use Below Values in settings.json file\n\"editor.suggest.snippetsPreventQuickSuggestions\": false,\n\n", "Strange solution for me, but disabling then re-enabling all extensions fixed the issue for me.\n", "For me, I had installed the Arduino extension.\nThis was problematic as it thought it should be in use every time I was coding in C++ so it was really slowing down the autocompletes.\nI just disabled it for my workspace and everything work really quickly\n", "None of these solutions worked for me. What worked for me, is that I went to the extension settings and:\n\nchanged IntelliSense mode to windows-gcc-arm64 (I was selecting different options for this one based on my os, till I found the fastest one)\n\nchanged IntelliSense update delay from 2000 to 500 (this added a bigger boost, after the first boost from a change in IntelliSense mode)\n\n\n", "I used git without .gitignore . Add .gitignore and add unnecessary files and directories like virtualenv in that.\n", "Click the Windows key and R at the same time, then type %temp%, then find .vscode file. Delete it. Happy coding.\n", "I had the same issue, I disabled extensions one by one.\nDisabling \"Live Server (v5.7.9)\" extension fixed it for me.\n", "You could check as previously suggested, to disable some extensions and retry using the reference finder function.\nFor my case, the Makefile Tools extension (https://marketplace.visualstudio.com/items?itemName=ms-vscode.makefile-tools), minutes after overtaking C/C++ IntelliSense, it just plainly broke over and over.\n", "For me it was the \"Multiple clipboards for VSCode\" extension, disabling it fixed my issues.\n" ]
[ 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 them over a bleed line using InDesign, I wonder how to do something similar using Python. A: I managed to do this using cv2.copyMakeBorder() from OpenCV librar method, as following: import cv2 image = cv2.imread("illustration1.jpg") #Window name in which image is displayed window_name = 'Image.jpg' #Using cv2.copyMakeBorder() method image = cv2.copyMakeBorder(borderoutput, 35, 35, 35, 35, cv2.BORDER_REFLECT_101, None, value = 0) #Displaying the image cv2.imwrite(window_name, image)
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 something similar using Python.
[ "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, \ncv2.BORDER_REFLECT_101, None, value = 0)\n\n#Displaying the image\ncv2.imwrite(window_name, image)\n\n" ]
[ 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 %matplotlib inline path = './test/paper2.png' img = image.load_img(path, target_size=(150,150)) imgplot = plt.imshow(img) x = image.img_to_array(img) img_test = np.expand_dims(x, axis=0) classes = model.predict(img_test, batch_size=10) print(classes) paper, rock, scissors = classes[0] if paper==1.: print('paper') elif rock==1.: print('rock') else: print('scissors') output : AttributeError: module 'keras.preprocessing.image' has no attribute 'load_img' when I try to run. What does the error mean and how can I fix it? help guys :) I'm trying to learn I don't know anymore which one is wrong A: I'm facing the same problem today. You can try using tensorflow 2.8.0 to fix it or try tf.keras.utils.load_img instead of image.load_img. A: Replace: from keras.preprocessing import image for: import keras.utils as image A: I also face the same error. I used from tensorflow.keras.utils import load_img, img_to_array and it work for me. A: there is no 'load_img' https://github.com/keras-team/keras/blob/master/keras/preprocessing/image.py I suppose you trying to use load_img of keras.utils.image_utils A: use keras.utils.load_img import keras import tensorflow as tf image = keras.utils.load_img('path_to_image', target_size=(img_size, img_size)) A: I just added 'tensorflow.' infront of the keras like 'tensorflow.keras.' and it worked. A: first import import tensorflow.compat.v2 as tf then tf.keras.preprocessing.image.load_img A: Try this out change this from keras.preprocessing import image test_image = image.load_img('$PATH', target_size = (64, 64)) test_image = image.img_to_array(test_image) To this from keras.utils import load_img, img_to_array test_image = load_img('$PATH', target_size = (64, 64)) test_image = img_to_array(test_image) reff :- https://keras.io/api/data_loading/image/ Source :- https://github.com/keras-team/keras/blob/v2.10.0/keras/utils/image_utils.py#L364 A: I too had this and fixed changes in import "from keras.utils import load_img, img_to_array instead" of "from keras.preprocessing import image" and change "img = image.load_img(path, target_size=(150,150))" to "load_img(path, target_size=(150,150))" "x = image.img_to_array(img)" to "x = img_to_array(img)"
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(path, target_size=(150,150)) imgplot = plt.imshow(img) x = image.img_to_array(img) img_test = np.expand_dims(x, axis=0) classes = model.predict(img_test, batch_size=10) print(classes) paper, rock, scissors = classes[0] if paper==1.: print('paper') elif rock==1.: print('rock') else: print('scissors') output : AttributeError: module 'keras.preprocessing.image' has no attribute 'load_img' when I try to run. What does the error mean and how can I fix it? help guys :) I'm trying to learn I don't know anymore which one is wrong
[ "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_img, img_to_array and it work for me.\n", "there is no 'load_img'\nhttps://github.com/keras-team/keras/blob/master/keras/preprocessing/image.py\nI suppose you trying to use load_img of keras.utils.image_utils\n", "use keras.utils.load_img\nimport keras\nimport tensorflow as tf\n\nimage = keras.utils.load_img('path_to_image', target_size=(img_size, img_size))\n\n", "I just added 'tensorflow.' infront of the keras like 'tensorflow.keras.' and it worked.\n", "first import\nimport tensorflow.compat.v2 as tf\n\nthen\ntf.keras.preprocessing.image.load_img\n\n", "Try this out\nchange this\nfrom keras.preprocessing import image\ntest_image = image.load_img('$PATH', target_size = (64, 64))\ntest_image = image.img_to_array(test_image)\n\nTo this\nfrom keras.utils import load_img, img_to_array\ntest_image = load_img('$PATH', target_size = (64, 64))\ntest_image = img_to_array(test_image)\n\nreff :- https://keras.io/api/data_loading/image/\nSource :- https://github.com/keras-team/keras/blob/v2.10.0/keras/utils/image_utils.py#L364\n", "I too had this and fixed\nchanges in import\n\n\"from keras.utils import load_img, img_to_array instead\" of \"from keras.preprocessing import image\"\n\nand\nchange\n\n\"img = image.load_img(path, target_size=(150,150))\" to \"load_img(path, target_size=(150,150))\"\n\n\"x = image.img_to_array(img)\" to \"x = img_to_array(img)\"\n\n\n" ]
[ 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 this... @overload def iterable(o: Iterable) -> Literal[True] : ... @overload def iterable(o: Any) -> Literal[False] : ... def iterable(o: Iterable|Any) -> Literal[True, False] : return isinstance(o, Iterable) But mypy complains that overload 1 overlaps overload 2 and returns incompatible type. A negating type annotation could easily solve this by using Not[Iterable] instead of Any in overload 2. Does anyone know how to solve this problem? A: For your given example you can use Type Guards introduced in Python 3.10. from typing import TypeGuard, Iterable, Any def is_iterable(o: Any) -> TypeGuard[Iterable]: """ Check if an object is an iterable See https://stackoverflow.com/questions/1952464 """ try: iter(o) except TypeError: return False return True a_list = [1,2] if is_iterable(a_list): reveal_type(a_list) # Revealed type is "typing.Iterable[Any]" a_int = 1 if not is_iterable(a_int): reveal_type(a_int) # Revealed type is "builtins.int" Check it out at MyPy Playground. I am still interested in the negative type annotations, but for a use case that can't be solved with TypeGuard.
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] : ... @overload def iterable(o: Any) -> Literal[False] : ... def iterable(o: Iterable|Any) -> Literal[True, False] : return isinstance(o, Iterable) But mypy complains that overload 1 overlaps overload 2 and returns incompatible type. A negating type annotation could easily solve this by using Not[Iterable] instead of Any in overload 2. Does anyone know how to solve this problem?
[ "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)\n except TypeError:\n return False\n return True\n\na_list = [1,2]\nif is_iterable(a_list):\n reveal_type(a_list) # Revealed type is \"typing.Iterable[Any]\"\n \na_int = 1\nif not is_iterable(a_int):\n reveal_type(a_int) # Revealed type is \"builtins.int\"\n\nCheck it out at MyPy Playground.\nI am still interested in the negative type annotations, but for a use case that can't be solved with TypeGuard.\n" ]
[ 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 an AttributeError. Accessing the original df through result.obj doesn't lead to the updated value because there is no inplace for the groupby bfill. def upfill(df:DataFrameGroupBy)->DataFrameGroupBy: for column in df.obj.columns: if column.startswith("x"): df[column].bfill(axis="rows", inplace=True) return df Assigning the dataframe column in the function doesn't work because groupbyobject doesn't support item assingment. def upfill(df:DataFrameGroupBy)->DataFrameGroupBy: for column in df.obj.columns: if column.startswith("x"): df[column] = df[column].bfill() return df The test I'm trying to get to pass: def test_upfill(): df = DataFrame({ "id":[1,2,3,4,5], "group":[1,2,2,3,3], "x_value": [4,4,None,None,5], }) grouped_df = df.groupby("group") result = upfill(grouped_df) result.reset_index() assert result["x_value"].equals(Series([4,4,None,5,5])) A: You should use 'transform' method on the grouped DataFrame, like this: import pandas as pd def test_upfill(): df = pd.DataFrame({ "id":[1,2,3,4,5], "group":[1,2,2,3,3], "x_value": [4,4,None,None,5], }) result = df.groupby("group").transform(lambda x: x.bfill()) assert result["x_value"].equals(pd.Series([4,4,None,5,5])) test_upfill() Here you can find find more information about the transform method on Groupby objects A: Based on the accepted answer this is the full solution I got to although I have read elsewhere there are issues using the obj attribute. def upfill(df:DataFrameGroupBy)->DataFrameGroupBy: columns = [column for column in df.obj.columns if column.startswith("x")] df.obj[columns] = df[columns].transform(lambda x:x.bfill()) return df def test_upfill(): df = DataFrame({ "id":[1,2,3,4,5], "group":[1,2,2,3,3], "x_value": [4,4,None,None,5], }) grouped_df = df.groupby("group") result = upfill(grouped_df) assert df["x_value"].equals(Series([4,4,None,5,5]))
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 df through result.obj doesn't lead to the updated value because there is no inplace for the groupby bfill. def upfill(df:DataFrameGroupBy)->DataFrameGroupBy: for column in df.obj.columns: if column.startswith("x"): df[column].bfill(axis="rows", inplace=True) return df Assigning the dataframe column in the function doesn't work because groupbyobject doesn't support item assingment. def upfill(df:DataFrameGroupBy)->DataFrameGroupBy: for column in df.obj.columns: if column.startswith("x"): df[column] = df[column].bfill() return df The test I'm trying to get to pass: def test_upfill(): df = DataFrame({ "id":[1,2,3,4,5], "group":[1,2,2,3,3], "x_value": [4,4,None,None,5], }) grouped_df = df.groupby("group") result = upfill(grouped_df) result.reset_index() assert result["x_value"].equals(Series([4,4,None,5,5]))
[ "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())\n assert result[\"x_value\"].equals(pd.Series([4,4,None,5,5]))\n\ntest_upfill()\n\nHere you can find find more information about the transform method on Groupby objects\n", "Based on the accepted answer this is the full solution I got to although I have read elsewhere there are issues using the obj attribute.\ndef upfill(df:DataFrameGroupBy)->DataFrameGroupBy:\n columns = [column for column in df.obj.columns if column.startswith(\"x\")]\n df.obj[columns] = df[columns].transform(lambda x:x.bfill())\n return df \n\ndef test_upfill():\n df = 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 grouped_df = df.groupby(\"group\")\n result = upfill(grouped_df)\n assert df[\"x_value\"].equals(Series([4,4,None,5,5]))\n\n\n" ]
[ 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): method_type = int foo_int = FooInt().method() # similarly, this should be int Note that simply replacing the ??? with method_type doesn't work as far as I've tested it. How would I go about doing this? A: 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 T = TypeVar("T") class Foo(Generic[T]): def method(self) -> T: ... class FooStr(Foo[str]): ... class FooInt(Foo[int]): ... which is similar, if not quite the same. If you want to know more about the difference, here's a discussion about it in Scala.
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 int Note that simply replacing the ??? with method_type doesn't work as far as I've tested it. How would I go about doing this?
[ "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[str]):\n ...\n\nclass FooInt(Foo[int]):\n ...\n\nwhich is similar, if not quite the same.\nIf you want to know more about the difference, here's a discussion about it in Scala.\n" ]
[ 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_external_api_respond() calculate r and return partial respond The problems and questions are : Is there a way to start returning to the web client results as they arrive to the Function? right now I know http can only return once to the message and close connection. Pagination in this case will be too complicated to achieve, as results depend on previous results, etc. Are there any solutions in Google Cloud to return live results as they come ? other type of Function ? Will it be very expensive if the function stay open for a minute even tough it does not have heavy calculations, just doing multiple API request in loop ? A: 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. You can use a Table Storage or Blob Storage if you use Azure. https://learn.microsoft.com/en-us/azure/storage/tables/table-storage-overview https://azure.microsoft.com/en-gb/products/storage/blobs/ With Table, you can just add records as you get them calculated. With Blob, you can use Append blob type, or just read and write blob again (it seems like you use single producer). As a bonus, you can distribute your task across multiple functions and get results much faster. This is called scale-out.
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 The problems and questions are : Is there a way to start returning to the web client results as they arrive to the Function? right now I know http can only return once to the message and close connection. Pagination in this case will be too complicated to achieve, as results depend on previous results, etc. Are there any solutions in Google Cloud to return live results as they come ? other type of Function ? Will it be very expensive if the function stay open for a minute even tough it does not have heavy calculations, just doing multiple API request in loop ?
[ "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.\nhttps://learn.microsoft.com/en-us/azure/storage/tables/table-storage-overview\nhttps://azure.microsoft.com/en-gb/products/storage/blobs/\nWith Table, you can just add records as you get them calculated.\nWith Blob, you can use Append blob type, or just read and write blob again (it seems like you use single producer).\nAs a bonus, you can distribute your task across multiple functions and get results much faster. This is called scale-out.\n" ]
[ 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 files has been added into ftp server import csv from ftplib import FTP import os import time,glob from datetime import datetime,timedelta list_of_file =glob.glob(".\*csv*") latest_file = max(list_of_file, key=os.path.getatime,default=None) filename = os.path.basename('latest_file') ftp = FTP(host='hostname') ftp.login(user='username',passwd='pass') ftp.cwd("Inbox") names = ftp.nlst() finale_names = [line for line in names if 'restaurant file' in line] latest_time = None latest_name = None for name in finale_names: time_1 = ftp.sendcmd("MDTM " + name) if (latest_time is None) or (time_1 > latest_time): latest_name = name latest_time = time_1 print(latest_name) if latest_name==filename: print("No new file available in the FTP server") else: print(latest_name," is available for downloading...") with open("C:\Files\restaurant \\" + latest_name, 'wb') as f: ftp.retrbinary('RETR '+ latest_name, f.write) print("filehasbeendownload") A: Calculate the time threshold. Parse the times returned by MDTM. And compare: n = 4 limit = datetime.now() - timedelta(hours=n) for name in finale_names: resp = ftp.sendcmd("MDTM " + name) # extract "yyyymmddhhmmss" part of the 213 response timestr = resp[4:18] time = datetime.strptime(timestr, "%Y%m%d%H%M%S") if time > limit: # Download Though if your server supports MLSD command, you better use that, instead of inefficiently calling MDTM for each and every file: Download only yesterday's file with FTP in Python Or you can use LIST. For understanding ways of retrieving file timestamps, see: How to get FTP file's modify time using Python ftplib
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 datetime import datetime,timedelta list_of_file =glob.glob(".\*csv*") latest_file = max(list_of_file, key=os.path.getatime,default=None) filename = os.path.basename('latest_file') ftp = FTP(host='hostname') ftp.login(user='username',passwd='pass') ftp.cwd("Inbox") names = ftp.nlst() finale_names = [line for line in names if 'restaurant file' in line] latest_time = None latest_name = None for name in finale_names: time_1 = ftp.sendcmd("MDTM " + name) if (latest_time is None) or (time_1 > latest_time): latest_name = name latest_time = time_1 print(latest_name) if latest_name==filename: print("No new file available in the FTP server") else: print(latest_name," is available for downloading...") with open("C:\Files\restaurant \\" + latest_name, 'wb') as f: ftp.retrbinary('RETR '+ latest_name, f.write) print("filehasbeendownload")
[ "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(timestr, \"%Y%m%d%H%M%S\")\n if time > limit:\n # Download\n\n\nThough if your server supports MLSD command, you better use that, instead of inefficiently calling MDTM for each and every file:\nDownload only yesterday's file with FTP in Python\nOr you can use LIST. For understanding ways of retrieving file timestamps, see:\nHow to get FTP file's modify time using Python ftplib\n" ]
[ 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 distributed under the MIT license. study("Trend Trigger Factor", shorttitle="TTF") length = input(title="Lookback Length", type=integer, defval=15) upperLevel = input(title="Upper Trigger Level", type=integer, defval=100, minval=1) lowerLevel = input(title="Lower Trigger Level", type=integer, defval=-100, maxval=-1) highlightBreakouts = input(title="Highlight Overbought/Oversold Breakouts ?", type=bool, defval=true) src = input(title="Source", type=source, defval=close) hh = highest(length) ll = lowest(length) buyPower = hh - nz(ll[length]) sellPower = nz(hh[length]) - ll ttf = 200 * (buyPower - sellPower) / (buyPower + sellPower) ttfColor = ttf > upperLevel ? #0ebb23 : ttf < lowerLevel ? #ff0000 : #f4b77d plot(ttf, title="TTF", linewidth=2, color=ttfColor, transp=0) transparent = color(white, 100) maxLevelPlot = hline(200, title="Max Level", linestyle=dotted, color=transparent) upperLevelPlot = hline(upperLevel, title="Upper Trigger Level", linestyle=dotted) hline(0, title="Zero Level", linestyle=dotted) lowerLevelPlot = hline(lowerLevel, title="Lower Trigger Level", linestyle=dotted) minLevelPlot = hline(-200, title="Min Level", linestyle=dotted, color=transparent) fill(upperLevelPlot, lowerLevelPlot, color=purple, transp=95) upperFillColor = ttf > upperLevel and highlightBreakouts ? green : transparent lowerFillColor = ttf < lowerLevel and highlightBreakouts ? red : transparent fill(maxLevelPlot, upperLevelPlot, color=upperFillColor, transp=90) fill(minLevelPlot, lowerLevelPlot, color=lowerFillColor, transp=90) Here is what I done so far: from finta import TA #import pandas_ta as ta import yfinance as yf import pandas as pd import numpy as np ohlc = yf.download('BTC-USD', start='2022-08-01', interval='1d') length = 15 hh = ohlc['High'].rolling(length).max() ll = ohlc['Low'].rolling(length).min() buyPower = hh - ll.fillna(0) sellPower = hh.fillna(0) - ll ttf = 200 * (buyPower - sellPower) / (buyPower + sellPower) I don't know what I'm not doing the right way but everytime TTF is like this way below: Date 2022-07-31 NaN 2022-08-01 NaN 2022-08-02 NaN 2022-08-03 NaN 2022-08-04 NaN ... 2022-11-14 0.0 2022-11-15 0.0 2022-11-16 0.0 2022-11-17 0.0 2022-11-18 0.0 Length: 111, dtype: float64 I'm thinking that these two Pine Script functions below I did them in the wrong way: buyPower = hh - nz(ll[length]) sellPower = nz(hh[length]) - ll But I'm not sure and also I don't know what would be their Python equivalent. Any idea, please? Thank you in advance! A: After I struggled a little bit I have found the right answer. I was right about where it could be the wrong part in my code above: buyPower = hh - nz(ll[length]) sellPower = nz(hh[length]) - ll It is not equal to this: buyPower = hh - ll.fillna(0) sellPower = hh.fillna(0) - ll The correct python conversion is like so: buyPower = hh - ll.shift(length).fillna(0) sellPower = hh.shift(length).fillna(0) - ll
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 Factor", shorttitle="TTF") length = input(title="Lookback Length", type=integer, defval=15) upperLevel = input(title="Upper Trigger Level", type=integer, defval=100, minval=1) lowerLevel = input(title="Lower Trigger Level", type=integer, defval=-100, maxval=-1) highlightBreakouts = input(title="Highlight Overbought/Oversold Breakouts ?", type=bool, defval=true) src = input(title="Source", type=source, defval=close) hh = highest(length) ll = lowest(length) buyPower = hh - nz(ll[length]) sellPower = nz(hh[length]) - ll ttf = 200 * (buyPower - sellPower) / (buyPower + sellPower) ttfColor = ttf > upperLevel ? #0ebb23 : ttf < lowerLevel ? #ff0000 : #f4b77d plot(ttf, title="TTF", linewidth=2, color=ttfColor, transp=0) transparent = color(white, 100) maxLevelPlot = hline(200, title="Max Level", linestyle=dotted, color=transparent) upperLevelPlot = hline(upperLevel, title="Upper Trigger Level", linestyle=dotted) hline(0, title="Zero Level", linestyle=dotted) lowerLevelPlot = hline(lowerLevel, title="Lower Trigger Level", linestyle=dotted) minLevelPlot = hline(-200, title="Min Level", linestyle=dotted, color=transparent) fill(upperLevelPlot, lowerLevelPlot, color=purple, transp=95) upperFillColor = ttf > upperLevel and highlightBreakouts ? green : transparent lowerFillColor = ttf < lowerLevel and highlightBreakouts ? red : transparent fill(maxLevelPlot, upperLevelPlot, color=upperFillColor, transp=90) fill(minLevelPlot, lowerLevelPlot, color=lowerFillColor, transp=90) Here is what I done so far: from finta import TA #import pandas_ta as ta import yfinance as yf import pandas as pd import numpy as np ohlc = yf.download('BTC-USD', start='2022-08-01', interval='1d') length = 15 hh = ohlc['High'].rolling(length).max() ll = ohlc['Low'].rolling(length).min() buyPower = hh - ll.fillna(0) sellPower = hh.fillna(0) - ll ttf = 200 * (buyPower - sellPower) / (buyPower + sellPower) I don't know what I'm not doing the right way but everytime TTF is like this way below: Date 2022-07-31 NaN 2022-08-01 NaN 2022-08-02 NaN 2022-08-03 NaN 2022-08-04 NaN ... 2022-11-14 0.0 2022-11-15 0.0 2022-11-16 0.0 2022-11-17 0.0 2022-11-18 0.0 Length: 111, dtype: float64 I'm thinking that these two Pine Script functions below I did them in the wrong way: buyPower = hh - nz(ll[length]) sellPower = nz(hh[length]) - ll But I'm not sure and also I don't know what would be their Python equivalent. Any idea, please? Thank you in advance!
[ "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 conversion is like so:\nbuyPower = hh - ll.shift(length).fillna(0) \nsellPower = hh.shift(length).fillna(0) - ll\n\n" ]
[ 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 how to fix this. I already tried to uninstall and install lxml again I'm using Python 3.8 A: It's a python version problem, I just updated it to Python 3.10 and it worked
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 Python 3.8
[ "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 n: ")) summed = 0 for a in range (numbed + 1) : if a%2==0: summed += (x**a)/numbed else: summed -= (x**a)/numbed print ("Sum of series", summed) **I tried this code, but no matter what values I enter, the output is always 0.00. ** A: This should do the trick: x = int(input("Enter value of x: ")) n = int(input("Enter value of n: ")) total = x for i in range(2, n+1): if i%2==0: total -= x**i/i else: total += x**i/i print("Sum: ", total) A: I assume the series you mentioned in your question is this: x - x^2/2 + x^3/3 - x^4/4 +... x^n/n. If yes, try this: x = int (input ("Enter value of x: ")) numbed = int (input ("Enter value of n: ")) sum1 = x for i in range(2,numbed+1): if i%2==0: sum1=sum1-((x**i)/i) else: sum1=sum1+((x**i)/i) print("The sum of series is",round(sum1,2)) A: just as an example of using recurcion: x = int(input("Enter value of x: ")) n = int(input("Enter value of n: ")) def f(x,n,i=1,s=1): return 0 if i>n else x**i/i*s + f(x,n,i+1,-s) f(3,5) # 35.85
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 a%2==0: summed += (x**a)/numbed else: summed -= (x**a)/numbed print ("Sum of series", summed) **I tried this code, but no matter what values I enter, the output is always 0.00. **
[ "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 is this: x - x^2/2 + x^3/3 - x^4/4 +... x^n/n.\nIf yes, try this:\nx = int (input (\"Enter value of x: \"))\n numbed = int (input (\"Enter value of n: \"))\n sum1 = x\n \n for i in range(2,numbed+1):\n if i%2==0:\n sum1=sum1-((x**i)/i)\n else:\n sum1=sum1+((x**i)/i)\n print(\"The sum of series is\",round(sum1,2))\n\n", "just as an example of using recurcion:\nx = int(input(\"Enter value of x: \"))\nn = int(input(\"Enter value of n: \"))\n\ndef f(x,n,i=1,s=1):\n return 0 if i>n else x**i/i*s + f(x,n,i+1,-s)\n\nf(3,5) # 35.85\n\n" ]
[ 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 < -> less than -> greater than ' -> this is an apostrophe " -> this is a double quotation Now how can I efficiently apply this regex on entire column. Also, Can I put it in certain function as I need to apply the same in 4 other columns as well. I tried this df = pd.DataFrame({'A': ['bat<', 'foo>', 'bait&'], 'B': ['abc', 'bar', 'xyz']}) df.replace({'A': r'<','A':r'>','A':r'&'}, {'A': 'less than','A': 'greater than','A': 'and'}, regex=True, inplace=True) I am expecting this A B 0 batless than abc 1 foogreater than bar 2 baitand xyz But this happened. A B 0 bat< abc 1 foo> bar 2 baitand xyz A: One can use pandas.DataFrame.apply with a custom lambda function, using pandas.Series.str.replace as follows regex = r'(<|>|&)' df_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)) [Out]: A B 0 batless than abc 1 foogreater than bar 2 baitand xyz A: Your replacement dict has three keys named A so all but the last is being overwritten. Use a nested dict instead to make multiple replacements to one column: df.replace({'A': {r'<': 'less than', r'>': 'greater than', r'&': 'and'}}, regex=True, inplace=True) See pandas.DataFrame.replace A: You can use a dictionary for the mapping, but it has to look like this: mapping = {'<': 'less than', '>': 'greater than', '&': 'and'} Then you can compile the keys into a regex and proceed similar to Gonçalo Peres's answer: df.apply(lambda col: col.str.replace("|".join(mapping), lambda match: mapping.get(match.group())))
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 efficiently apply this regex on entire column. Also, Can I put it in certain function as I need to apply the same in 4 other columns as well. I tried this df = pd.DataFrame({'A': ['bat<', 'foo>', 'bait&'], 'B': ['abc', 'bar', 'xyz']}) df.replace({'A': r'<','A':r'>','A':r'&'}, {'A': 'less than','A': 'greater than','A': 'and'}, regex=True, inplace=True) I am expecting this A B 0 batless than abc 1 foogreater than bar 2 baitand xyz But this happened. A B 0 bat< abc 1 foo> bar 2 baitand xyz
[ "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 A B\n0 batless than abc\n1 foogreater than bar\n2 baitand xyz\n\n", "Your replacement dict has three keys named A so all but the last is being overwritten. Use a nested dict instead to make multiple replacements to one column:\ndf.replace({'A': {r'<': 'less than', r'>': 'greater than', r'&': 'and'}}, regex=True, inplace=True)\n\nSee pandas.DataFrame.replace\n", "You can use a dictionary for the mapping, but it has to look like this:\nmapping = {'<': 'less than', '>': 'greater than', '&': 'and'}\n\nThen you can compile the keys into a regex and proceed similar to Gonçalo Peres's answer:\ndf.apply(lambda col: col.str.replace(\"|\".join(mapping), \n lambda match: mapping.get(match.group())))\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 this function at runtime, without the user noticing it? The add_i(x) function is used as an argument for another function: def K(*f:Callable): g,*h = f def k(*x): h_res = [i(*x) for i in h] return g(*h_res) return k So K takes some functions as parameters and executes them on some input x. This input should be the same for every possible function, so using the user input as parameter would crash every other function. A: 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: def define(i): def add_i(x): return i+x return add_i When you call define(2) it will define a function that returns 2+x. But what can we do for variables? I don't know want do you mean of using x but if x is a variable that user could use from input I could recommend you to use a dictionary to save variable names and values, Then we use regex to get i and variable name: import re def define(i): def add_i(x): return i+x return add_i variables = {'x':4} # for example now we add x to variables with value 4 # all commands that user could call are saved in `commands` dictionary # you can add commands for user for example we add print function that prints variable value commands = { # <command_name>:<function> 'print':lambda x:x # script will print returned value } while (True): cmd = input('> ') cmd_name, var_name = re.match(r'(\w[\w\d_]*)\((\w[\w\d]*)\)',cmd).groups() # optional: you can create variable if it is not in dictionary if not var_name in variables: variables[var_name]=0 if not cmd_name in commands: _,i = cmd_name.split('_') commands[cmd_name] = define(int(i)) print(commands[cmd_name](variables[var_name])) # call function and print output > add_5(x) 9 > print(x) 9
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) function is used as an argument for another function: def K(*f:Callable): g,*h = f def k(*x): h_res = [i(*x) for i in h] return g(*h_res) return k So K takes some functions as parameters and executes them on some input x. This input should be the same for every possible function, so using the user input as parameter would crash every other function.
[ "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 a function that returns 2+x. But what can we do for variables? I don't know want do you mean of using x but if x is a variable that user could use from input I could recommend you to use a dictionary to save variable names and values, Then we use regex to get i and variable name:\nimport re\n\ndef define(i):\n def add_i(x):\n return i+x\n return add_i\n\nvariables = {'x':4} # for example now we add x to variables with value 4\n# all commands that user could call are saved in `commands` dictionary\n# you can add commands for user for example we add print function that prints variable value\ncommands = {\n # <command_name>:<function>\n 'print':lambda x:x # script will print returned value\n}\n\nwhile (True):\n cmd = input('> ')\n cmd_name, var_name = re.match(r'(\\w[\\w\\d_]*)\\((\\w[\\w\\d]*)\\)',cmd).groups()\n # optional: you can create variable if it is not in dictionary\n if not var_name in variables:\n variables[var_name]=0\n if not cmd_name in commands:\n _,i = cmd_name.split('_')\n commands[cmd_name] = define(int(i))\n print(commands[cmd_name](variables[var_name])) # call function and print output\n\n> add_5(x)\n9\n> print(x)\n9\n\n" ]
[ 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()) async def connect_nodes(self): await self.bot.wait_until_ready() await wavelink.NodePool.create_node(bot=self.bot, host='0.0.0.0', port=2333, password='yousheldnotpass') @commands.Cog.listener async def on_wavelink_node_ready(self, node: wavelink.Node): print(f'Node [{node.identifier}] - ✅') @commands.command() async def play(self, ctx: commands.Context, *, search: wavelink.YouTubeTrack): if not ctx.voice_client: vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player) else: vc: wavelink.Player = ctx.voice_client await vc.play(search) def setup(bot): bot.add_cog(Music(bot)) I tried writing different variations of the code, everything gave out exactly 1 error, but I did not find an answer in Internet resources. A: The problem is wavelink needs discord.py to run and you are using nextcord , so with nextcord you can use nextwave
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() await wavelink.NodePool.create_node(bot=self.bot, host='0.0.0.0', port=2333, password='yousheldnotpass') @commands.Cog.listener async def on_wavelink_node_ready(self, node: wavelink.Node): print(f'Node [{node.identifier}] - ✅') @commands.command() async def play(self, ctx: commands.Context, *, search: wavelink.YouTubeTrack): if not ctx.voice_client: vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player) else: vc: wavelink.Player = ctx.voice_client await vc.play(search) def setup(bot): bot.add_cog(Music(bot)) I tried writing different variations of the code, everything gave out exactly 1 error, but I did not find an answer in Internet resources.
[ "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(load=data) >>> send(packet) enter image description here A: There is no length field in ICMP header. There is one in IP header. So you can try something like that: data = 'A' * 100 packet = IP(dst='1.1.1.1', len=29)/ICMP()/Raw(load=data) send(packet) Here I put 29 as length since my IP header is 20 bytes long and my ICMP header is 8 byte long. So this leaves 1 byte for the payload. You will see in wireshark that 100 A characters are actually sent while the data length displayed by wireshark is 1.
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) enter image description here
[ "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 byte for the payload.\nYou will see in wireshark that 100 A characters are actually sent\nwhile the data length displayed by wireshark is 1.\n" ]
[ 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 element self.arr = [1, 2, 3, 4] # serializable element def __getstate__(self): state = self.__dict__.copy() del state['lib'] return state When I try to call json.dump on an instantiated object of it I get an error message: TypeError: Object of type PyClassExample is not JSON serializable Why does json.dump not call __getstate__ but pickle.dump does call it? What mechanism does json.dump use to get the serializable state of an passed object? A: 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. JSON doesn't have that. It only supports a fixed set of types, and extending the format is generally done by interpreting the values (like reading predefined keys in a dict) in a post-processing step. Here's how you can do that: import json def my_default(o): if isinstance(o, PyClassExample): return {'$type': 'PyClassExample', 'path': o.path, 'arr': o.arr} raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable") def my_object_hook(o): if o.get('$type') == 'PyClassExample': # FIXME: implement an __init__ that supports this return PyClassExample(o) return o And then replace calls to json.dump(...) with json.dump(..., default=my_default) and calls to json.load(...) with json.load(..., object_hook=my_object_hook). If you want to support more classes you may want to make a more general solution, like a protocol that "JSON-able" classes follow. If you really want to, you could even abuse __getstate__ for this, like so: import json # Make all classes you want to be able to serialise that need to use this mechanism a subclass of JSONAble class JSONAble: registry = {} def __init_subclass__(cls, /, **kwargs): super().__init_subclass__(**kwargs) JSONAble.registry[cls.__name__] = cls def my_default(o): if isinstance(o, JSONAble): return {'(type)': type(o).__name__, **o.__getstate__()} raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable") def my_object_hook(o): if '(type)' in o: new_o = JSONAble.registry[o.pop('(type)')]() new_o.__dict__ = o return new_o return o
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] # serializable element def __getstate__(self): state = self.__dict__.copy() del state['lib'] return state When I try to call json.dump on an instantiated object of it I get an error message: TypeError: Object of type PyClassExample is not JSON serializable Why does json.dump not call __getstate__ but pickle.dump does call it? What mechanism does json.dump use to get the serializable state of an passed object?
[ "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 generally done by interpreting the values (like reading predefined keys in a dict) in a post-processing step. Here's how you can do that:\nimport json\n\ndef my_default(o):\n if isinstance(o, PyClassExample):\n return {'$type': 'PyClassExample', 'path': o.path, 'arr': o.arr}\n raise TypeError(f\"Object of type {type(o).__name__} is not JSON serializable\")\n\ndef my_object_hook(o):\n if o.get('$type') == 'PyClassExample':\n # FIXME: implement an __init__ that supports this\n return PyClassExample(o)\n return o\n\nAnd then replace calls to json.dump(...) with json.dump(..., default=my_default) and calls to json.load(...) with json.load(..., object_hook=my_object_hook).\nIf you want to support more classes you may want to make a more general solution, like a protocol that \"JSON-able\" classes follow. If you really want to, you could even abuse __getstate__ for this, like so:\nimport json\n\n# Make all classes you want to be able to serialise that need to use this mechanism a subclass of JSONAble\nclass JSONAble:\n registry = {}\n def __init_subclass__(cls, /, **kwargs):\n super().__init_subclass__(**kwargs)\n JSONAble.registry[cls.__name__] = cls\n\ndef my_default(o):\n if isinstance(o, JSONAble):\n return {'(type)': type(o).__name__, **o.__getstate__()}\n raise TypeError(f\"Object of type {type(o).__name__} is not JSON serializable\")\n\ndef my_object_hook(o):\n if '(type)' in o:\n new_o = JSONAble.registry[o.pop('(type)')]()\n new_o.__dict__ = o\n return new_o\n return o\n\n" ]
[ 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 hyperlink, and one for a checklist). I tried diagnosing the problem, and I just do not get the attribute error. Test integration.ky from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager,Screen class FirstWindow(Screen): pass class SecondWindow(Screen): pass class ThirdWindow(Screen): pass class WindowManager (ScreenManager): pass kv = Builder.load_file("Test Integration.kv") class MyMainApp(App): def build(self): return kv if __name__ == "__main__": MyMainApp().run() Test integration.kv WindowManager: FirstWindow: SecondWindow: ThirdWindow: \<FirstWindow\>: name: "Main Menu" BoxLayout: orientation: "vertical" size: root.width, root.height Label: text: "Safety Checklist" font_size: 24 on_release: app.root.current = "Checklist" root.manager.transition = "left" name: "Test Button." Button: text: "Please complete our survey!" on_release: import webbrowser webbrowser.open('https://forms.gle/k6cfYEU1snzpykxY9') name: "Checklist" BoxLayout: orientation: "vertical" size: root.width, root.height Label: text: "Checklist: Do you acquired all the necessary safety equipment?" font_size: 24 GridLayout: cols:2 Label: text: "Do you have your safety gloves with you?" font_size:16 CheckBox: on_active: root.checkbox_click(self, self.active, "Do you have your safety gloves with you?") Label: text: "Do you have your safety boots with you?" font_size:16 CheckBox: on_active: root.checkbox_click(self, self.active, "Do you have your safety boots with you?") Label: text: "Do you have your safety goggles with you?" font_size:16 CheckBox: on_active: root.checkbox_click(self, self.active, "Do you have your safety goggles with you?") Label: text: "Do you have your helmet with you?" font_size:16 CheckBox: on_active: root.checkbox_click(self, self.active, "Do you have your helmet with you?") Label: id: output_label text: "You are recommended to acquire or purchase the missing safety equipment." Button: text: "Return to main menu." on_release: app.root.current = "Main Menu" root.manager.transition = "right" Error: Traceback (most recent call last): File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 729, in \_apply_rule raise AttributeError(key) AttributeError: release During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\Test Integration.py", line 17, in \<module\> kv = Builder.load_file("Test Integration.kv") File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 305, in load_file return self.load_string(data, \*\*kwargs) File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 407, in load_string self.\_apply_rule( File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 660, in \_apply_rule child.apply_class_lang_rules( File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\uix\\widget.py", line 470, in apply_class_lang_rules Builder.apply( File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 540, in apply self.\_apply_rule( File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 736, in \_apply_rule raise BuilderException( kivy.lang.builder.BuilderException: Parser: File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\Test Integration.kv", line 17: ... 15: font_size: 24 16: on_release: > > 17: app.root.current = "Checklist" > > 18: root.manager.transition = "left" > > 19: > > ... > > AttributeError: release > > File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 729, in \_apply_rule > > raise AttributeError(key) Process finished with exit code 1 A: you should add the screens manually and give them names Builder.load_file("Test Integration.kv") class MyMainApp(App): def build(self): _my_top_widget = WindowManager() _my_top_widget.add_widget(FirstWindow(name='FirstWindow')) _my_top_widget.add_widget(SecondWindow(name='Main Menu')) _my_top_widget.current = "FirstWindow" return _my_top_widget inside the kv file don't do multi-line functions, make a function in your widget to do the actions you want. Button: text: "Return to main menu." on_release: root.return_main() # app.root.current = "Main Menu" # root.manager.transition = "right" and in your widget class definition you can make a function class FirstWindow(Screen): def return_main(self): print("return main") # app.root.current = "Main Menu" # root.manager.transition = "right" this will get you part of the way there. finding attribute errors in kv files can be tough, especially with stackoverflow formatting because it can be difficult to track the white space. I was able to execute the code after I made some adjustments but I didn't complete the part of causing the screen transition.
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. Test integration.ky from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager,Screen class FirstWindow(Screen): pass class SecondWindow(Screen): pass class ThirdWindow(Screen): pass class WindowManager (ScreenManager): pass kv = Builder.load_file("Test Integration.kv") class MyMainApp(App): def build(self): return kv if __name__ == "__main__": MyMainApp().run() Test integration.kv WindowManager: FirstWindow: SecondWindow: ThirdWindow: \<FirstWindow\>: name: "Main Menu" BoxLayout: orientation: "vertical" size: root.width, root.height Label: text: "Safety Checklist" font_size: 24 on_release: app.root.current = "Checklist" root.manager.transition = "left" name: "Test Button." Button: text: "Please complete our survey!" on_release: import webbrowser webbrowser.open('https://forms.gle/k6cfYEU1snzpykxY9') name: "Checklist" BoxLayout: orientation: "vertical" size: root.width, root.height Label: text: "Checklist: Do you acquired all the necessary safety equipment?" font_size: 24 GridLayout: cols:2 Label: text: "Do you have your safety gloves with you?" font_size:16 CheckBox: on_active: root.checkbox_click(self, self.active, "Do you have your safety gloves with you?") Label: text: "Do you have your safety boots with you?" font_size:16 CheckBox: on_active: root.checkbox_click(self, self.active, "Do you have your safety boots with you?") Label: text: "Do you have your safety goggles with you?" font_size:16 CheckBox: on_active: root.checkbox_click(self, self.active, "Do you have your safety goggles with you?") Label: text: "Do you have your helmet with you?" font_size:16 CheckBox: on_active: root.checkbox_click(self, self.active, "Do you have your helmet with you?") Label: id: output_label text: "You are recommended to acquire or purchase the missing safety equipment." Button: text: "Return to main menu." on_release: app.root.current = "Main Menu" root.manager.transition = "right" Error: Traceback (most recent call last): File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 729, in \_apply_rule raise AttributeError(key) AttributeError: release During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\Test Integration.py", line 17, in \<module\> kv = Builder.load_file("Test Integration.kv") File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 305, in load_file return self.load_string(data, \*\*kwargs) File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 407, in load_string self.\_apply_rule( File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 660, in \_apply_rule child.apply_class_lang_rules( File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\uix\\widget.py", line 470, in apply_class_lang_rules Builder.apply( File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 540, in apply self.\_apply_rule( File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 736, in \_apply_rule raise BuilderException( kivy.lang.builder.BuilderException: Parser: File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\Test Integration.kv", line 17: ... 15: font_size: 24 16: on_release: > > 17: app.root.current = "Checklist" > > 18: root.manager.transition = "left" > > 19: > > ... > > AttributeError: release > > File "C:\\Users\\nicho\\PycharmProjects\\Temasek Polytechnic MP (Software App)\\venv\\lib\\site-packages\\kivy\\lang\\builder.py", line 729, in \_apply_rule > > raise AttributeError(key) Process finished with exit code 1
[ "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 Menu'))\n _my_top_widget.current = \"FirstWindow\"\n return _my_top_widget\n\ninside the kv file don't do multi-line functions, make a function in your widget to do the actions you want.\n Button:\n text: \"Return to main menu.\"\n on_release: root.return_main()\n# app.root.current = \"Main Menu\"\n# root.manager.transition = \"right\"\n\nand in your widget class definition you can make a function\nclass FirstWindow(Screen):\n\n def return_main(self):\n print(\"return main\")\n # app.root.current = \"Main Menu\"\n # root.manager.transition = \"right\"\n\nthis will get you part of the way there.\nfinding attribute errors in kv files can be tough, especially with stackoverflow formatting because it can be difficult to track the white space. I was able to execute the code after I made some adjustments but I didn't complete the part of causing the screen transition.\n" ]
[ 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 Fallschirm(pygame.sprite.Sprite): def __init__(self,x,y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("Bilder/fallschirm.png").convert_alpha() self.image = pygame.transform.scale(self.image,(100,150)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y def update(self): self.rect.y +=2 if self.rect.y > hoehe: self.kill() def absprung(self): #Auslöser Fallschirm fallschirm = Fallschirm(self.rect.centerx, self.rect.top) alle_sprites.add(fallschirm) fallschirme.add(fallschirm) sound=pygame.mixer.Sound("Audio/help.mp3") sound.play() hits = pygame.sprite.spritecollide(fallschirme,bullets,False) for hit in hits: fallschirme = pygame.sprite.Group() A: In your code fallschirme is a sprite.Group(), but you're passing it as the first argument to spritecollide(...), which expects a sprite. I think you should be initialising fallschirme as: fallschirme = Fallschirm(x_position, y_position) If that is not what you want, you'll need to edit your question to add more context.
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): def __init__(self,x,y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("Bilder/fallschirm.png").convert_alpha() self.image = pygame.transform.scale(self.image,(100,150)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y def update(self): self.rect.y +=2 if self.rect.y > hoehe: self.kill() def absprung(self): #Auslöser Fallschirm fallschirm = Fallschirm(self.rect.centerx, self.rect.top) alle_sprites.add(fallschirm) fallschirme.add(fallschirm) sound=pygame.mixer.Sound("Audio/help.mp3") sound.play() hits = pygame.sprite.spritecollide(fallschirme,bullets,False) for hit in hits: fallschirme = pygame.sprite.Group()
[ "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 more context.\n" ]
[ 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.how should I get that with 3 for loop Expected output for the sample: [(1,1),(7,5)],[(2,4),(5,4)] A: L = [[(1,2),(1,4)],[(7,5),(5,4)]] result = list() fIndexesList = list() #first items sIndexesList = list() #second items for item in L: fIndexesTuple = list() sIndexesTuple = list() for innerItem in item: fIndexesTuple.append(innerItem[0]) sIndexesTuple.append(innerItem[1]) else: fIndexesList.append(tuple(fIndexesTuple)) sIndexesList.append(tuple(sIndexesTuple)) else: result.append(fIndexesList) result.append(sIndexesList) print(result) This should work By the way ,You can use the loop inside a function A: You could try to use zip: numbers = [[(1, 2), (1, 4)], [(7, 5), (5, 4)]] result = [list(tuples) for tuples in zip(*(zip(*tuples) for tuples in numbers))] Result: [[(1, 1), (7, 5)], [(2, 4), (5, 4)]]
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 loop Expected output for the sample: [(1,1),(7,5)],[(2,4),(5,4)]
[ "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[1])\n \n else: \n fIndexesList.append(tuple(fIndexesTuple)) \n sIndexesList.append(tuple(sIndexesTuple))\n \nelse:\n result.append(fIndexesList)\n result.append(sIndexesList)\nprint(result)\n\nThis should work\nBy the way ,You can use the loop inside a function\n", "You could try to use zip:\nnumbers = [[(1, 2), (1, 4)], [(7, 5), (5, 4)]]\nresult = [list(tuples) for tuples in zip(*(zip(*tuples) for tuples in numbers))]\n\nResult:\n[[(1, 1), (7, 5)], [(2, 4), (5, 4)]]\n\n" ]
[ 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 sample size don't affect the speed significantly. For reference: 0.00135549 s for 3 samples with batch_size = 3 0.00303991 s for 3 samples with batch_size = 1 0.00115528 s for 1 sample with batch_size = 1 0.00136132 s for 10 samples with batch_size = 10 as you can see I can predict 10 samples at about the same speed as 1 sample. The change is also very minimal though noticeable if I decrease parameter size by 100X but I'd rather not change parameter size by that much anyway. In addition, the predict function is very slow the first time run through (~0.2s) though I don't think that's the problem here since the same model is predicting multiple times. I wonder if there is some workaround because clearly the 10 samples can be evaluated very quickly, all I want to be able to do is predict the samples at different times and not all at once since I need to update the Tree Search before making a new prediction. Perhaps should I work with tensorflow instead? A: 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. You cannot really workaround, there is nothing really to work around, using a batch size of one is the worst case for performance. Maybe you should look into a smaller network that is faster to predict, or predict on the CPU if your experiments are done in a GPU, to minimize overhead due to transfer. Don't forget that model.predict does a full forward pass of the network, so its speed completely depends on the network architecture. A: One way that gave me a speed up was switching from model.predict(x) to, model.predict_on_batch(x) making sure your x shape has 1 as the first dimension. A: I don't think working with pure Tensorflow would change the performance much. Keras is a high-level API for low-level Tensorflow primitives. You could use a smaller model instead, like MobileNetV3 or EfficientNet, but this would require retraining. If you need to remain with the existing model, you could try OpenVINO. OpenVINO is optimized for Intel hardware, but it should work with any CPU. It optimizes your model by converting to Intermediate Representation (IR), performing graph pruning and fusing some operations into others while preserving accuracy. Then it uses vectorization in runtime. It's rather straightforward to convert the Keras model to OpenVINO. The full tutorial on how to do it can be found here. Some snippets are below. Install OpenVINO The easiest way to do it is using PIP. Alternatively, you can use this tool to find the best way in your case. pip install openvino-dev[tensorflow2] Save your model as SavedModel OpenVINO is not able to convert the HDF5 model, so you have to save it as SavedModel first. import tensorflow as tf from custom_layer import CustomLayer model = tf.keras.models.load_model('model.h5', custom_objects={'CustomLayer': CustomLayer}) tf.saved_model.save(model, 'model') Use Model Optimizer to convert SavedModel model The Model Optimizer is a command-line tool that comes from OpenVINO Development Package. It converts the Tensorflow model to IR, a default format for OpenVINO. You can also try the precision of FP16, which should give you better performance without a significant accuracy drop (change data_type). Run in the command line: mo --saved_model_dir "model" --data_type FP32 --output_dir "model_ir" Run the inference The converted model can be loaded by the runtime and compiled for a specific device, e.g., CPU or GPU (integrated into your CPU like Intel HD Graphics). If you don't know what the best choice for you is, use AUTO. You care about latency, so I suggest adding a performance hint (as shown below) to use the device that fulfills your requirement. # Load the network ie = Core() model_ir = ie.read_model(model="model_ir/model.xml") compiled_model_ir = ie.compile_model(model=model_ir, device_name="AUTO", config={"PERFORMANCE_HINT":"LATENCY"}) # Get output layer output_layer_ir = compiled_model_ir.output(0) # Run inference on the input image result = compiled_model_ir([input_image])[output_layer_ir] Disclaimer: I work on OpenVINO.
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: 0.00135549 s for 3 samples with batch_size = 3 0.00303991 s for 3 samples with batch_size = 1 0.00115528 s for 1 sample with batch_size = 1 0.00136132 s for 10 samples with batch_size = 10 as you can see I can predict 10 samples at about the same speed as 1 sample. The change is also very minimal though noticeable if I decrease parameter size by 100X but I'd rather not change parameter size by that much anyway. In addition, the predict function is very slow the first time run through (~0.2s) though I don't think that's the problem here since the same model is predicting multiple times. I wonder if there is some workaround because clearly the 10 samples can be evaluated very quickly, all I want to be able to do is predict the samples at different times and not all at once since I need to update the Tree Search before making a new prediction. Perhaps should I work with tensorflow instead?
[ "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 performance. Maybe you should look into a smaller network that is faster to predict, or predict on the CPU if your experiments are done in a GPU, to minimize overhead due to transfer.\nDon't forget that model.predict does a full forward pass of the network, so its speed completely depends on the network architecture.\n", "One way that gave me a speed up was switching from model.predict(x) to,\nmodel.predict_on_batch(x)\n\nmaking sure your x shape has 1 as the first dimension.\n", "I don't think working with pure Tensorflow would change the performance much. Keras is a high-level API for low-level Tensorflow primitives. You could use a smaller model instead, like MobileNetV3 or EfficientNet, but this would require retraining.\nIf you need to remain with the existing model, you could try OpenVINO. OpenVINO is optimized for Intel hardware, but it should work with any CPU. It optimizes your model by converting to Intermediate Representation (IR), performing graph pruning and fusing some operations into others while preserving accuracy. Then it uses vectorization in runtime.\nIt's rather straightforward to convert the Keras model to OpenVINO. The full tutorial on how to do it can be found here. Some snippets are below.\nInstall OpenVINO\nThe easiest way to do it is using PIP. Alternatively, you can use this tool to find the best way in your case.\npip install openvino-dev[tensorflow2]\n\nSave your model as SavedModel\nOpenVINO is not able to convert the HDF5 model, so you have to save it as SavedModel first.\nimport tensorflow as tf\nfrom custom_layer import CustomLayer\nmodel = tf.keras.models.load_model('model.h5', custom_objects={'CustomLayer': CustomLayer})\ntf.saved_model.save(model, 'model')\n\nUse Model Optimizer to convert SavedModel model\nThe Model Optimizer is a command-line tool that comes from OpenVINO Development Package. It converts the Tensorflow model to IR, a default format for OpenVINO. You can also try the precision of FP16, which should give you better performance without a significant accuracy drop (change data_type). Run in the command line:\nmo --saved_model_dir \"model\" --data_type FP32 --output_dir \"model_ir\"\n\nRun the inference\nThe converted model can be loaded by the runtime and compiled for a specific device, e.g., CPU or GPU (integrated into your CPU like Intel HD Graphics). If you don't know what the best choice for you is, use AUTO. You care about latency, so I suggest adding a performance hint (as shown below) to use the device that fulfills your requirement.\n# Load the network\nie = Core()\nmodel_ir = ie.read_model(model=\"model_ir/model.xml\")\ncompiled_model_ir = ie.compile_model(model=model_ir, device_name=\"AUTO\", config={\"PERFORMANCE_HINT\":\"LATENCY\"})\n\n# Get output layer\noutput_layer_ir = compiled_model_ir.output(0)\n\n# Run inference on the input image\nresult = compiled_model_ir([input_image])[output_layer_ir]\n\nDisclaimer: I work on OpenVINO.\n" ]
[ 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: !CUDA_VISIBLE_DEVICES=0 python -u ../scripts/main.py --summarizer gpt3_summarizer --controller longformer_classifier longformer_classifier --loader alignment coherence --controller-load-dir emnlp22_re3_data/ckpt/relevance_reranker emnlp22_re3_data/ckpt/coherence_reranker --controller-model-string allenai/longformer-base-4096 allenai/longformer-base-4096 --save-outline-file output/outline0.pkl --save-complete-file output/complete_story0.pkl --log-file output/story0.log Here's the entire output: Traceback (most recent call last): File "../scripts/main.py", line 20, in <module> from story_generation.edit_module.entity import * File "/home/jovyan/emnlp22-re3-story-generation/story_generation/edit_module/entity.py", line 20, in <module> from story_generation.common.util import * File "/home/jovyan/emnlp22-re3-story-generation/story_generation/common/util.py", line 13, in <module> from sentence_transformers import SentenceTransformer File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/__init__.py", line 3, in <module> from .datasets import SentencesDataset, ParallelSentencesDataset File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/datasets/__init__.py", line 3, in <module> from .ParallelSentencesDataset import ParallelSentencesDataset File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/datasets/ParallelSentencesDataset.py", line 4, in <module> from .. import SentenceTransformer File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/SentenceTransformer.py", line 25, in <module> from .evaluation import SentenceEvaluator File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/evaluation/__init__.py", line 5, in <module> from .InformationRetrievalEvaluator import InformationRetrievalEvaluator File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/evaluation/InformationRetrievalEvaluator.py", line 6, in <module> from ..util import cos_sim, dot_score File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/util.py", line 407, in <module> from huggingface_hub.snapshot_download import REPO_ID_SEPARATOR ModuleNotFoundError: No module named 'huggingface_hub.snapshot_download' A: Updating to the latest version of sentence-transformers fixes it (no need to install huggingface-hub explicitly): pip install -U sentence-transformers I've proposed a pull request for this in the original repo.
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 --summarizer gpt3_summarizer --controller longformer_classifier longformer_classifier --loader alignment coherence --controller-load-dir emnlp22_re3_data/ckpt/relevance_reranker emnlp22_re3_data/ckpt/coherence_reranker --controller-model-string allenai/longformer-base-4096 allenai/longformer-base-4096 --save-outline-file output/outline0.pkl --save-complete-file output/complete_story0.pkl --log-file output/story0.log Here's the entire output: Traceback (most recent call last): File "../scripts/main.py", line 20, in <module> from story_generation.edit_module.entity import * File "/home/jovyan/emnlp22-re3-story-generation/story_generation/edit_module/entity.py", line 20, in <module> from story_generation.common.util import * File "/home/jovyan/emnlp22-re3-story-generation/story_generation/common/util.py", line 13, in <module> from sentence_transformers import SentenceTransformer File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/__init__.py", line 3, in <module> from .datasets import SentencesDataset, ParallelSentencesDataset File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/datasets/__init__.py", line 3, in <module> from .ParallelSentencesDataset import ParallelSentencesDataset File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/datasets/ParallelSentencesDataset.py", line 4, in <module> from .. import SentenceTransformer File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/SentenceTransformer.py", line 25, in <module> from .evaluation import SentenceEvaluator File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/evaluation/__init__.py", line 5, in <module> from .InformationRetrievalEvaluator import InformationRetrievalEvaluator File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/evaluation/InformationRetrievalEvaluator.py", line 6, in <module> from ..util import cos_sim, dot_score File "/opt/conda/lib/python3.8/site-packages/sentence_transformers/util.py", line 407, in <module> from huggingface_hub.snapshot_download import REPO_ID_SEPARATOR ModuleNotFoundError: No module named 'huggingface_hub.snapshot_download'
[ "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. Could someone help me out? Or if you have any suggestions for a better implementation, that would be helpful. Where I create this relative layout is in the screen called MidiSheet: class MidiSheet(Screen): def __init__(self, **kwargs): super(MidiSheet, self).__init__(**kwargs) screen = ScrollView(size=(Window.width, Window.height), do_scroll_x=True, do_scroll_y=False) notes = get_notes_in_song("../data/" + self.name) layout = RelativeLayout(size=(Window.width, Window.height)) layout.add_widget(BackButton(self)) initial_y_pos = Window.height/2 initial_x_pos = Window.width*0.1 for note in notes: note_name = note.split(":")[1] layout.add_widget(MidiButton(note_name, initial_x_pos, initial_y_pos)) initial_x_pos += 100 screen.add_widget(layout) self.add_widget(screen) Here's my full .py from kivy.app import App from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.uix.gridlayout import GridLayout from kivy.core.window import Window from kivy.uix.relativelayout import RelativeLayout from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition import os def get_notes_in_song(song): with open(song) as f: lines = f.readlines() return lines class SongButton(Button): def __init__(self, file_name, **kwargs): super(SongButton, self).__init__(**kwargs) self.background_color = [0, 0, 0, 0] self.size_hint = (0.5, None) self.height = 40 self.file_name = file_name def on_press(self): App.get_running_app().root.add_widget(MidiSheet(name=self.file_name)) App.get_running_app().root.transition.direction = "left" App.get_running_app().root.current = self.file_name class BackButton(Button): def __init__(self, screen_instance, **kwargs): super(BackButton, self).__init__(**kwargs) self.background_color = [1, 1, 1, 1] self.size_hint = (0.1, 0.1) self.text = "Back" self.screen_instance = screen_instance def on_press(self): App.get_running_app().root.remove_widget(self.screen_instance) App.get_running_app().root.transition.direction = "right" App.get_running_app().root.current = "home" class MidiButton(Button): def __init__(self, name, pos_x, pos_y, **kwargs): super(MidiButton, self).__init__(**kwargs) self.background_color = [1, 1, 1, 1] self.size_hint = (0.1, 0.1) self.pos = (pos_x, pos_y) self.text = name self.padding = (10, 10) def on_press(self): self.background_color = [0, 1, 0, 1] if self.background_color == [1, 1, 1, 1] else [1, 1, 1, 1] class Home(Screen): def __init__(self, **kwargs): super(Home, self).__init__(**kwargs) screen = ScrollView(size_hint=(1, None), size=(Window.width, Window.height)) layout = GridLayout(cols=1, spacing=10, size_hint_y=None) songs = [x for x in os.listdir("../data/") if ".txt" in x] for song in songs: name = song.replace("_", " ").replace(".txt", "") layout.add_widget(SongButton(song, text=name)) screen.add_widget(layout) self.add_widget(screen) class MidiSheet(Screen): def __init__(self, **kwargs): super(MidiSheet, self).__init__(**kwargs) screen = ScrollView(size=(Window.width, Window.height), do_scroll_x=True, do_scroll_y=False) notes = get_notes_in_song("../data/" + self.name) layout = RelativeLayout(size=(Window.width, Window.height)) layout.add_widget(BackButton(self)) initial_y_pos = Window.height/2 initial_x_pos = Window.width*0.1 for note in notes: note_name = note.split(":")[1] layout.add_widget(MidiButton(note_name, initial_x_pos, initial_y_pos)) initial_x_pos += 100 screen.add_widget(layout) self.add_widget(screen) class Localiser(App): def build(self): sm = ScreenManager(transition=SlideTransition()) sm.add_widget(Home(name="home")) return sm A: 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: layout = GridLayout(cols=1, spacing=10, size_hint_y=None) layout.bind(minimum_height=layout.setter('height')) A: So actually my problem was that the size of my RelativeLayout wasn't bigger than my ScrollView's size. Only if the RelativeLayout is bigger, will there be something to scroll. So I had to disable the size_hint of my layout, and using the pixel size, I was able to make my layout size, bigger than my ScrollView size screen = ScrollView(size_hint=(None, None), size=(Window.width, Window.height), do_scroll_x=True, do_scroll_y=False) class MidiLayout(RelativeLayout): def __init__(self, midi_buttons, **kwargs): super(MidiLayout, self).__init__(**kwargs) self.size_hint = (None, None) self.window_width = Window.width for note in midi_buttons: self.window_width += note.size[0] self.add_widget(note) self.size = (self.window_width + 100, Window.height)
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 better implementation, that would be helpful. Where I create this relative layout is in the screen called MidiSheet: class MidiSheet(Screen): def __init__(self, **kwargs): super(MidiSheet, self).__init__(**kwargs) screen = ScrollView(size=(Window.width, Window.height), do_scroll_x=True, do_scroll_y=False) notes = get_notes_in_song("../data/" + self.name) layout = RelativeLayout(size=(Window.width, Window.height)) layout.add_widget(BackButton(self)) initial_y_pos = Window.height/2 initial_x_pos = Window.width*0.1 for note in notes: note_name = note.split(":")[1] layout.add_widget(MidiButton(note_name, initial_x_pos, initial_y_pos)) initial_x_pos += 100 screen.add_widget(layout) self.add_widget(screen) Here's my full .py from kivy.app import App from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.uix.gridlayout import GridLayout from kivy.core.window import Window from kivy.uix.relativelayout import RelativeLayout from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition import os def get_notes_in_song(song): with open(song) as f: lines = f.readlines() return lines class SongButton(Button): def __init__(self, file_name, **kwargs): super(SongButton, self).__init__(**kwargs) self.background_color = [0, 0, 0, 0] self.size_hint = (0.5, None) self.height = 40 self.file_name = file_name def on_press(self): App.get_running_app().root.add_widget(MidiSheet(name=self.file_name)) App.get_running_app().root.transition.direction = "left" App.get_running_app().root.current = self.file_name class BackButton(Button): def __init__(self, screen_instance, **kwargs): super(BackButton, self).__init__(**kwargs) self.background_color = [1, 1, 1, 1] self.size_hint = (0.1, 0.1) self.text = "Back" self.screen_instance = screen_instance def on_press(self): App.get_running_app().root.remove_widget(self.screen_instance) App.get_running_app().root.transition.direction = "right" App.get_running_app().root.current = "home" class MidiButton(Button): def __init__(self, name, pos_x, pos_y, **kwargs): super(MidiButton, self).__init__(**kwargs) self.background_color = [1, 1, 1, 1] self.size_hint = (0.1, 0.1) self.pos = (pos_x, pos_y) self.text = name self.padding = (10, 10) def on_press(self): self.background_color = [0, 1, 0, 1] if self.background_color == [1, 1, 1, 1] else [1, 1, 1, 1] class Home(Screen): def __init__(self, **kwargs): super(Home, self).__init__(**kwargs) screen = ScrollView(size_hint=(1, None), size=(Window.width, Window.height)) layout = GridLayout(cols=1, spacing=10, size_hint_y=None) songs = [x for x in os.listdir("../data/") if ".txt" in x] for song in songs: name = song.replace("_", " ").replace(".txt", "") layout.add_widget(SongButton(song, text=name)) screen.add_widget(layout) self.add_widget(screen) class MidiSheet(Screen): def __init__(self, **kwargs): super(MidiSheet, self).__init__(**kwargs) screen = ScrollView(size=(Window.width, Window.height), do_scroll_x=True, do_scroll_y=False) notes = get_notes_in_song("../data/" + self.name) layout = RelativeLayout(size=(Window.width, Window.height)) layout.add_widget(BackButton(self)) initial_y_pos = Window.height/2 initial_x_pos = Window.width*0.1 for note in notes: note_name = note.split(":")[1] layout.add_widget(MidiButton(note_name, initial_x_pos, initial_y_pos)) initial_x_pos += 100 screen.add_widget(layout) self.add_widget(screen) class Localiser(App): def build(self): sm = ScreenManager(transition=SlideTransition()) sm.add_widget(Home(name="home")) return sm
[ "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", "So actually my problem was that the size of my RelativeLayout wasn't bigger than my ScrollView's size. Only if the RelativeLayout is bigger, will there be something to scroll. So I had to disable the size_hint of my layout, and using the pixel size, I was able to make my layout size, bigger than my ScrollView size\nscreen = ScrollView(size_hint=(None, None), size=(Window.width, Window.height), do_scroll_x=True, do_scroll_y=False)\n\nclass MidiLayout(RelativeLayout):\n\n def __init__(self, midi_buttons, **kwargs):\n super(MidiLayout, self).__init__(**kwargs)\n\n self.size_hint = (None, None)\n\n self.window_width = Window.width\n\n for note in midi_buttons:\n self.window_width += note.size[0]\n\n self.add_widget(note)\n\n self.size = (self.window_width + 100, Window.height)\n\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 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 TypeError: ufunc 'multiply' output (typecode 'O') # could not be coerced to provided output parameter (typecode 'd') # according to the casting rule ''same_kind'' a *= 10.**20 # Throws numpy.core._exceptions._UFuncOutputCastingError: # Cannot cast ufunc 'multiply' output from dtype('float64') to # dtype('int32') with casting rule 'same_kind' However, this doesn't happen if you multiply element-wise a[0] *= 10**20 print(a, a.dtype) # [1.e+20] float64 or specifically convert the number to a float (or int) a *= float(10**20) print(a, a.dtype) # [1.e+20] float64 Just for the record, if you do the multiplication outside of numpy, there are no issues b = 1. print(type(b), type(10**20), type(10.**20)) # float int float b *= 10**20 print(type(b)) # float A: I expect it is the size a "natural" integer can take on the system. print(sys.maxsize, sys.getsizeof(sys.maxsize)) => 9223372036854775807 36 print(10**19, sys.getsizeof(10**19)) => 10000000000000000000 36 And this is where on my system the conversion to object starts, when I do for i in range(1, 24): print(f'type of a*10**{i}:', (a * 10**i).dtype) I do expect it is linked to the implementation of the integer: PEP 0237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type. See https://docs.python.org/3.1/whatsnew/3.0.html#integers To notice this, one could use numpy.multiply with a forced output type. This will throw an error and not silently convert (similar to your *= example).
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 TypeError: ufunc 'multiply' output (typecode 'O') # could not be coerced to provided output parameter (typecode 'd') # according to the casting rule ''same_kind'' a *= 10.**20 # Throws numpy.core._exceptions._UFuncOutputCastingError: # Cannot cast ufunc 'multiply' output from dtype('float64') to # dtype('int32') with casting rule 'same_kind' However, this doesn't happen if you multiply element-wise a[0] *= 10**20 print(a, a.dtype) # [1.e+20] float64 or specifically convert the number to a float (or int) a *= float(10**20) print(a, a.dtype) # [1.e+20] float64 Just for the record, if you do the multiplication outside of numpy, there are no issues b = 1. print(type(b), type(10**20), type(10.**20)) # float int float b *= 10**20 print(type(b)) # float
[ "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 print(f'type of a*10**{i}:', (a * 10**i).dtype)\n\nI do expect it is linked to the implementation of the integer:\n\nPEP 0237: Essentially, long renamed to int. That is, there is only one\nbuilt-in integral type, named int; but it behaves mostly like the old\nlong type.\n\nSee https://docs.python.org/3.1/whatsnew/3.0.html#integers\nTo notice this, one could use numpy.multiply with a forced output type. This will throw an error and not silently convert (similar to your *= example).\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 should return the cache and not go through the code again. cache = dict() def calc_range(lower: int, higher: int)->list: new_liste = [] for i in range(lower,higher): if lower and higher in cache.keys(): return cache[lower,higher] break else: new_liste.append(i) cache[lower,higher]=new_liste return cache[lower,higher] res_1 = calc_range(3, 5) res_2 = calc_range(3, 5) print(res_1) print(res_2) res_1 is res_2 test1 cache = dict() res_1 = calc_range(3, 5) res_2 = calc_range(3, 5) assert(res_1 == [3, 4]) assert(res_1 is res_2) test2 assert(any(cached_val is res_1 for cached_val in cache.values())) test3 res_5 = calc_range(3, 3) res_6 = calc_range(3, 3) assert (res_5 == []) assert(res_5 is res_6) A: 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 Solution cache = dict() def calc_range(lower: int, higher: int)->list: new_liste = [] if (lower, higher) in cache: return cache[lower,higher] for i in range(lower,higher): new_liste.append(i) cache[lower,higher]=new_liste return cache[lower,higher] res_1 = calc_range(3, 5) res_2 = calc_range(3, 5) print(res_1) print(res_2) print(res_1 is res_2) Output [3, 4] [3, 4] True
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. cache = dict() def calc_range(lower: int, higher: int)->list: new_liste = [] for i in range(lower,higher): if lower and higher in cache.keys(): return cache[lower,higher] break else: new_liste.append(i) cache[lower,higher]=new_liste return cache[lower,higher] res_1 = calc_range(3, 5) res_2 = calc_range(3, 5) print(res_1) print(res_2) res_1 is res_2 test1 cache = dict() res_1 = calc_range(3, 5) res_2 = calc_range(3, 5) assert(res_1 == [3, 4]) assert(res_1 is res_2) test2 assert(any(cached_val is res_1 for cached_val in cache.values())) test3 res_5 = calc_range(3, 3) res_6 = calc_range(3, 3) assert (res_5 == []) assert(res_5 is res_6)
[ "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 = []\n if (lower, higher) in cache:\n return cache[lower,higher]\n for i in range(lower,higher):\n new_liste.append(i)\n cache[lower,higher]=new_liste\n return cache[lower,higher]\n\nres_1 = calc_range(3, 5)\nres_2 = calc_range(3, 5)\nprint(res_1)\nprint(res_2)\nprint(res_1 is res_2)\n\nOutput\n[3, 4]\n[3, 4]\nTrue\n\n" ]
[ 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 %tensorflow_version 1.x import tensorflow as tf import tensorflow_hub as hub import pandas as pd import numpy as np from sklearn.pipeline import make_pipeline from sklearn.compose import make_column_transformer from sklearn.preprocessing import FunctionTransformer tos = pd.DataFrame({ "Character" : ["KIRK", "SPOCK"], "Lines" : ["Shall we pick some flowers, Doctor?","Check the circuit."] }) X = pd.DataFrame(tos["Lines"], columns = ["Lines"]) Y = tos["Character"] x_train, x_test, y_train, y_test = train_test_split(X,Y) embed = hub.Module("/content/module/") pipe = make_pipeline( make_column_transformer( (FunctionTransformer(embed), "Lines") ), SVC() ) pipe.fit(x_train,y_train); I noticted that the documentation for FunctionTransformer mentions that If a lambda is used as the function, then the resulting transformer will not be pickleable. But this does not seem to be the issue, as I did not define this function to be a lambda. Full Traceback --------------------------------------------------------------------------- Empty Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/joblib/parallel.py in dispatch_one_batch(self, iterator) 821 try: --> 822 tasks = self._ready_batches.get(block=False) 823 except queue.Empty: 21 frames /usr/lib/python3.7/queue.py in get(self, block, timeout) 166 if not self._qsize(): --> 167 raise Empty 168 elif timeout is None: Empty: During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-69-a981c354b190> in <module>() ----> 1 pipe.fit(x_train,y_train) /usr/local/lib/python3.7/dist-packages/sklearn/pipeline.py in fit(self, X, y, **fit_params) 388 """ 389 fit_params_steps = self._check_fit_params(**fit_params) --> 390 Xt = self._fit(X, y, **fit_params_steps) 391 with _print_elapsed_time("Pipeline", self._log_message(len(self.steps) - 1)): 392 if self._final_estimator != "passthrough": /usr/local/lib/python3.7/dist-packages/sklearn/pipeline.py in _fit(self, X, y, **fit_params_steps) 353 message_clsname="Pipeline", 354 message=self._log_message(step_idx), --> 355 **fit_params_steps[name], 356 ) 357 # Replace the transformer of the step with the fitted /usr/local/lib/python3.7/dist-packages/joblib/memory.py in __call__(self, *args, **kwargs) 347 348 def __call__(self, *args, **kwargs): --> 349 return self.func(*args, **kwargs) 350 351 def call_and_shelve(self, *args, **kwargs): /usr/local/lib/python3.7/dist-packages/sklearn/pipeline.py in _fit_transform_one(transformer, X, y, weight, message_clsname, message, **fit_params) 891 with _print_elapsed_time(message_clsname, message): 892 if hasattr(transformer, "fit_transform"): --> 893 res = transformer.fit_transform(X, y, **fit_params) 894 else: 895 res = transformer.fit(X, y, **fit_params).transform(X) /usr/local/lib/python3.7/dist-packages/sklearn/compose/_column_transformer.py in fit_transform(self, X, y) 673 self._validate_remainder(X) 674 --> 675 result = self._fit_transform(X, y, _fit_transform_one) 676 677 if not result: /usr/local/lib/python3.7/dist-packages/sklearn/compose/_column_transformer.py in _fit_transform(self, X, y, func, fitted, column_as_strings) 613 message=self._log_message(name, idx, len(transformers)), 614 ) --> 615 for idx, (name, trans, column, weight) in enumerate(transformers, 1) 616 ) 617 except ValueError as e: /usr/local/lib/python3.7/dist-packages/joblib/parallel.py in __call__(self, iterable) 1041 # remaining jobs. 1042 self._iterating = False -> 1043 if self.dispatch_one_batch(iterator): 1044 self._iterating = self._original_iterator is not None 1045 /usr/local/lib/python3.7/dist-packages/joblib/parallel.py in dispatch_one_batch(self, iterator) 831 big_batch_size = batch_size * n_jobs 832 --> 833 islice = list(itertools.islice(iterator, big_batch_size)) 834 if len(islice) == 0: 835 return False /usr/local/lib/python3.7/dist-packages/sklearn/compose/_column_transformer.py in <genexpr>(.0) 613 message=self._log_message(name, idx, len(transformers)), 614 ) --> 615 for idx, (name, trans, column, weight) in enumerate(transformers, 1) 616 ) 617 except ValueError as e: /usr/local/lib/python3.7/dist-packages/sklearn/base.py in clone(estimator, safe) 84 new_object_params = estimator.get_params(deep=False) 85 for name, param in new_object_params.items(): ---> 86 new_object_params[name] = clone(param, safe=False) 87 new_object = klass(**new_object_params) 88 params_set = new_object.get_params(deep=False) /usr/local/lib/python3.7/dist-packages/sklearn/base.py in clone(estimator, safe) 65 elif not hasattr(estimator, "get_params") or isinstance(estimator, type): 66 if not safe: ---> 67 return copy.deepcopy(estimator) 68 else: 69 if isinstance(estimator, type): /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 178 y = x 179 else: --> 180 y = _reconstruct(x, memo, *rv) 181 182 # If is its own copy, don't memoize. /usr/lib/python3.7/copy.py in _reconstruct(x, memo, func, args, state, listiter, dictiter, deepcopy) 279 if state is not None: 280 if deep: --> 281 state = deepcopy(state, memo) 282 if hasattr(y, '__setstate__'): 283 y.__setstate__(state) /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 148 copier = _deepcopy_dispatch.get(cls) 149 if copier: --> 150 y = copier(x, memo) 151 else: 152 try: /usr/lib/python3.7/copy.py in _deepcopy_dict(x, memo, deepcopy) 239 memo[id(x)] = y 240 for key, value in x.items(): --> 241 y[deepcopy(key, memo)] = deepcopy(value, memo) 242 return y 243 d[dict] = _deepcopy_dict /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 178 y = x 179 else: --> 180 y = _reconstruct(x, memo, *rv) 181 182 # If is its own copy, don't memoize. /usr/lib/python3.7/copy.py in _reconstruct(x, memo, func, args, state, listiter, dictiter, deepcopy) 279 if state is not None: 280 if deep: --> 281 state = deepcopy(state, memo) 282 if hasattr(y, '__setstate__'): 283 y.__setstate__(state) /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 148 copier = _deepcopy_dispatch.get(cls) 149 if copier: --> 150 y = copier(x, memo) 151 else: 152 try: /usr/lib/python3.7/copy.py in _deepcopy_dict(x, memo, deepcopy) 239 memo[id(x)] = y 240 for key, value in x.items(): --> 241 y[deepcopy(key, memo)] = deepcopy(value, memo) 242 return y 243 d[dict] = _deepcopy_dict /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 167 reductor = getattr(x, "__reduce_ex__", None) 168 if reductor: --> 169 rv = reductor(4) 170 else: 171 reductor = getattr(x, "__reduce__", None) TypeError: can't pickle _thread.RLock objects A: You should be passing the instance of FunctionTransformer directly in pipeline rather than wrapping it inside a ColumnTransformer. I 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. pipe = make_pipeline( FunctionTransformer(embed, kw_args={"kw_arg_nm":kw_arg_value}), # Provision someway to pass "Lines" through kw_args. SVC() ) pipe.fit(x_train,y_train);
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 tensorflow_hub as hub import pandas as pd import numpy as np from sklearn.pipeline import make_pipeline from sklearn.compose import make_column_transformer from sklearn.preprocessing import FunctionTransformer tos = pd.DataFrame({ "Character" : ["KIRK", "SPOCK"], "Lines" : ["Shall we pick some flowers, Doctor?","Check the circuit."] }) X = pd.DataFrame(tos["Lines"], columns = ["Lines"]) Y = tos["Character"] x_train, x_test, y_train, y_test = train_test_split(X,Y) embed = hub.Module("/content/module/") pipe = make_pipeline( make_column_transformer( (FunctionTransformer(embed), "Lines") ), SVC() ) pipe.fit(x_train,y_train); I noticted that the documentation for FunctionTransformer mentions that If a lambda is used as the function, then the resulting transformer will not be pickleable. But this does not seem to be the issue, as I did not define this function to be a lambda. Full Traceback --------------------------------------------------------------------------- Empty Traceback (most recent call last) /usr/local/lib/python3.7/dist-packages/joblib/parallel.py in dispatch_one_batch(self, iterator) 821 try: --> 822 tasks = self._ready_batches.get(block=False) 823 except queue.Empty: 21 frames /usr/lib/python3.7/queue.py in get(self, block, timeout) 166 if not self._qsize(): --> 167 raise Empty 168 elif timeout is None: Empty: During handling of the above exception, another exception occurred: TypeError Traceback (most recent call last) <ipython-input-69-a981c354b190> in <module>() ----> 1 pipe.fit(x_train,y_train) /usr/local/lib/python3.7/dist-packages/sklearn/pipeline.py in fit(self, X, y, **fit_params) 388 """ 389 fit_params_steps = self._check_fit_params(**fit_params) --> 390 Xt = self._fit(X, y, **fit_params_steps) 391 with _print_elapsed_time("Pipeline", self._log_message(len(self.steps) - 1)): 392 if self._final_estimator != "passthrough": /usr/local/lib/python3.7/dist-packages/sklearn/pipeline.py in _fit(self, X, y, **fit_params_steps) 353 message_clsname="Pipeline", 354 message=self._log_message(step_idx), --> 355 **fit_params_steps[name], 356 ) 357 # Replace the transformer of the step with the fitted /usr/local/lib/python3.7/dist-packages/joblib/memory.py in __call__(self, *args, **kwargs) 347 348 def __call__(self, *args, **kwargs): --> 349 return self.func(*args, **kwargs) 350 351 def call_and_shelve(self, *args, **kwargs): /usr/local/lib/python3.7/dist-packages/sklearn/pipeline.py in _fit_transform_one(transformer, X, y, weight, message_clsname, message, **fit_params) 891 with _print_elapsed_time(message_clsname, message): 892 if hasattr(transformer, "fit_transform"): --> 893 res = transformer.fit_transform(X, y, **fit_params) 894 else: 895 res = transformer.fit(X, y, **fit_params).transform(X) /usr/local/lib/python3.7/dist-packages/sklearn/compose/_column_transformer.py in fit_transform(self, X, y) 673 self._validate_remainder(X) 674 --> 675 result = self._fit_transform(X, y, _fit_transform_one) 676 677 if not result: /usr/local/lib/python3.7/dist-packages/sklearn/compose/_column_transformer.py in _fit_transform(self, X, y, func, fitted, column_as_strings) 613 message=self._log_message(name, idx, len(transformers)), 614 ) --> 615 for idx, (name, trans, column, weight) in enumerate(transformers, 1) 616 ) 617 except ValueError as e: /usr/local/lib/python3.7/dist-packages/joblib/parallel.py in __call__(self, iterable) 1041 # remaining jobs. 1042 self._iterating = False -> 1043 if self.dispatch_one_batch(iterator): 1044 self._iterating = self._original_iterator is not None 1045 /usr/local/lib/python3.7/dist-packages/joblib/parallel.py in dispatch_one_batch(self, iterator) 831 big_batch_size = batch_size * n_jobs 832 --> 833 islice = list(itertools.islice(iterator, big_batch_size)) 834 if len(islice) == 0: 835 return False /usr/local/lib/python3.7/dist-packages/sklearn/compose/_column_transformer.py in <genexpr>(.0) 613 message=self._log_message(name, idx, len(transformers)), 614 ) --> 615 for idx, (name, trans, column, weight) in enumerate(transformers, 1) 616 ) 617 except ValueError as e: /usr/local/lib/python3.7/dist-packages/sklearn/base.py in clone(estimator, safe) 84 new_object_params = estimator.get_params(deep=False) 85 for name, param in new_object_params.items(): ---> 86 new_object_params[name] = clone(param, safe=False) 87 new_object = klass(**new_object_params) 88 params_set = new_object.get_params(deep=False) /usr/local/lib/python3.7/dist-packages/sklearn/base.py in clone(estimator, safe) 65 elif not hasattr(estimator, "get_params") or isinstance(estimator, type): 66 if not safe: ---> 67 return copy.deepcopy(estimator) 68 else: 69 if isinstance(estimator, type): /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 178 y = x 179 else: --> 180 y = _reconstruct(x, memo, *rv) 181 182 # If is its own copy, don't memoize. /usr/lib/python3.7/copy.py in _reconstruct(x, memo, func, args, state, listiter, dictiter, deepcopy) 279 if state is not None: 280 if deep: --> 281 state = deepcopy(state, memo) 282 if hasattr(y, '__setstate__'): 283 y.__setstate__(state) /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 148 copier = _deepcopy_dispatch.get(cls) 149 if copier: --> 150 y = copier(x, memo) 151 else: 152 try: /usr/lib/python3.7/copy.py in _deepcopy_dict(x, memo, deepcopy) 239 memo[id(x)] = y 240 for key, value in x.items(): --> 241 y[deepcopy(key, memo)] = deepcopy(value, memo) 242 return y 243 d[dict] = _deepcopy_dict /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 178 y = x 179 else: --> 180 y = _reconstruct(x, memo, *rv) 181 182 # If is its own copy, don't memoize. /usr/lib/python3.7/copy.py in _reconstruct(x, memo, func, args, state, listiter, dictiter, deepcopy) 279 if state is not None: 280 if deep: --> 281 state = deepcopy(state, memo) 282 if hasattr(y, '__setstate__'): 283 y.__setstate__(state) /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 148 copier = _deepcopy_dispatch.get(cls) 149 if copier: --> 150 y = copier(x, memo) 151 else: 152 try: /usr/lib/python3.7/copy.py in _deepcopy_dict(x, memo, deepcopy) 239 memo[id(x)] = y 240 for key, value in x.items(): --> 241 y[deepcopy(key, memo)] = deepcopy(value, memo) 242 return y 243 d[dict] = _deepcopy_dict /usr/lib/python3.7/copy.py in deepcopy(x, memo, _nil) 167 reductor = getattr(x, "__reduce_ex__", None) 168 if reductor: --> 169 rv = reductor(4) 170 else: 171 reductor = getattr(x, "__reduce__", None) TypeError: can't pickle _thread.RLock objects
[ "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 FunctionTransformer(embed, kw_args={\"kw_arg_nm\":kw_arg_value}), \n # Provision someway to pass \"Lines\" through kw_args. \n SVC()\n)\npipe.fit(x_train,y_train);\n\n" ]
[ 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_delete=models.PROTECT) learning_partner = models.ForeignKey( Learning_Partner, on_delete=models.PROTECT, blank=False, null=False) assign_to_trainer = models.ForeignKey( Trainer, on_delete=models.PROTECT, null=True, blank=True) course_name = models.CharField(max_length=2000) lead_type = models.CharField(max_length=2000) time_zone = models.CharField(choices=(('IST', 'IST'), ('GMT', 'GMT'), ('BST', 'BST'), ( 'CET', 'CET'), ('SAST', 'SAST'), ('EST', 'EST'), ('PST', 'PST'), ('MST', 'MST'), ('UTC', 'UTC')), max_length=40, blank=False, null=False) getting_lead_date = models.DateTimeField(null=True, blank=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) lead_status = models.CharField(choices=(('Initial', 'Initial'), ('In Progress', 'In Progress'), ('Follow Up', 'Follow Up'), ( 'Cancelled', 'Cancelled'), ('Confirmed', 'Confirmed'), ('PO Received', 'PO Received')), max_length=40, blank=False, null=False) lead_description = models.CharField(max_length=9000, blank=True, null=True) def __str__(self): return str(self.assign_to_trainer) class Meta: ordering = ['start_date'] class Trainer(models.Model): trainer_id = models.AutoField(primary_key=True) trainer_name = models.CharField(max_length=200, null=False, blank=False) address = models.CharField(max_length=500, null=False, blank=False) phone_no = models.CharField(max_length=13, unique=True, null=True, blank=True) phone_no_optional = models.CharField(max_length=13, null=True, blank=True) email = models.CharField(max_length=50) email_optional = models.CharField(max_length=50, null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) primary_language = models.CharField(max_length=50, null=True, blank=True) gender = models.CharField(choices=(('Male', 'Male'), ('Female', 'Female')), max_length=30, blank=True, null=True) trainer_type = models.CharField(choices=(('Corporate Trainer', 'Corporate Trainer'), ('Academic Trainer', 'Academic Trainer')), max_length=30, blank=True, null=True) trainer_pricing = models.CharField(max_length=1000, null=True, blank=True) trainer_course_specialization = models.CharField(max_length=5000) trainer_skill_set = models.CharField(max_length=10000, null=True, blank=True) trainer_enrolled_with = models.ForeignKey(Learning_Partner, on_delete=models.PROTECT, blank=True, null=True) trainer_tier = models.CharField(choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4')), max_length=10, null=True, blank=True) def __str__(self): return str(self.trainer_name) views.py def report_for_trainer(request): if request.user.is_authenticated: user = UserInstance.objects.all() partner = Learning_Partner.objects.all() trainer_info = Trainer.objects.all() trainer = Training_Lead.objects.all() if request.method == "POST": start_date = request.POST.get("start_date") end_date = request.POST.get("end_date") lead_status = request.POST.get("lead_status", default="") assign_to_trainer = request.POST.get("assign_to_trainer") trainers_info = Training_Lead.objects.filter( start_date__gte=start_date, end_date__lte=end_date, lead_status__contains=lead_status, assign_to_trainer_id__contains=assign_to_trainer, ) trainer_info_not_active = Training_Lead.objects.exclude( start_date__gte=start_date, end_date__lte=end_date, lead_status__contains=lead_status, ) df = {"user": user, "partner": partner,"start_date": start_date,"end_date":end_date,"trainer":trainer,"lead_status":lead_status,"assign_to_trainer":assign_to_trainer, "lead_status": lead_status,"trainers_info": trainers_info, "trainer_info": trainer_info, "trainer_info_not_active": trainer_info_not_active} return render(request, "trainers_for_schedule_date.html", df) else: return redirect("router") HTML code <label class="form-label" for="assign_to_trainer"> <h4 style="color: rgb(0, 0, 0);">Assign To Trainer :-</h4> </label> <select name="assign_to_trainer" id="assign_to_trainer" multiple> {% for t in leads %} <option name="assign_to_trainer" id="assign_to_trainer" value="{{ t.assign_to_trainer_id }}">{{ t.assign_to_trainer }}</option> {% endfor %} </select> please help me to solve this My problem is if I use assign_to_trainer inside the filter query instead of Training_Lead I receive the error: enter image description here A: You can't use __contains lookup in ForeignKey since it is used on strings so the Queryset should be: trainers_info = Training_Lead.objects.filter( start_date__gte=start_date, end_date__lte=end_date, lead_status__contains=lead_status, assign_to_trainer=assign_to_trainer, ) A: Hi you can do it this way in your filter query: trainers_info = Training_Lead.objects.filter( start_date__gte=start_date, end_date__lte=end_date, lead_status__contains=lead_status, assign_to_trainer_id=int(assign_to_trainer), ) Here, assign_to_trainer_id expects an integer only.
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.ForeignKey( Learning_Partner, on_delete=models.PROTECT, blank=False, null=False) assign_to_trainer = models.ForeignKey( Trainer, on_delete=models.PROTECT, null=True, blank=True) course_name = models.CharField(max_length=2000) lead_type = models.CharField(max_length=2000) time_zone = models.CharField(choices=(('IST', 'IST'), ('GMT', 'GMT'), ('BST', 'BST'), ( 'CET', 'CET'), ('SAST', 'SAST'), ('EST', 'EST'), ('PST', 'PST'), ('MST', 'MST'), ('UTC', 'UTC')), max_length=40, blank=False, null=False) getting_lead_date = models.DateTimeField(null=True, blank=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) lead_status = models.CharField(choices=(('Initial', 'Initial'), ('In Progress', 'In Progress'), ('Follow Up', 'Follow Up'), ( 'Cancelled', 'Cancelled'), ('Confirmed', 'Confirmed'), ('PO Received', 'PO Received')), max_length=40, blank=False, null=False) lead_description = models.CharField(max_length=9000, blank=True, null=True) def __str__(self): return str(self.assign_to_trainer) class Meta: ordering = ['start_date'] class Trainer(models.Model): trainer_id = models.AutoField(primary_key=True) trainer_name = models.CharField(max_length=200, null=False, blank=False) address = models.CharField(max_length=500, null=False, blank=False) phone_no = models.CharField(max_length=13, unique=True, null=True, blank=True) phone_no_optional = models.CharField(max_length=13, null=True, blank=True) email = models.CharField(max_length=50) email_optional = models.CharField(max_length=50, null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) primary_language = models.CharField(max_length=50, null=True, blank=True) gender = models.CharField(choices=(('Male', 'Male'), ('Female', 'Female')), max_length=30, blank=True, null=True) trainer_type = models.CharField(choices=(('Corporate Trainer', 'Corporate Trainer'), ('Academic Trainer', 'Academic Trainer')), max_length=30, blank=True, null=True) trainer_pricing = models.CharField(max_length=1000, null=True, blank=True) trainer_course_specialization = models.CharField(max_length=5000) trainer_skill_set = models.CharField(max_length=10000, null=True, blank=True) trainer_enrolled_with = models.ForeignKey(Learning_Partner, on_delete=models.PROTECT, blank=True, null=True) trainer_tier = models.CharField(choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4')), max_length=10, null=True, blank=True) def __str__(self): return str(self.trainer_name) views.py def report_for_trainer(request): if request.user.is_authenticated: user = UserInstance.objects.all() partner = Learning_Partner.objects.all() trainer_info = Trainer.objects.all() trainer = Training_Lead.objects.all() if request.method == "POST": start_date = request.POST.get("start_date") end_date = request.POST.get("end_date") lead_status = request.POST.get("lead_status", default="") assign_to_trainer = request.POST.get("assign_to_trainer") trainers_info = Training_Lead.objects.filter( start_date__gte=start_date, end_date__lte=end_date, lead_status__contains=lead_status, assign_to_trainer_id__contains=assign_to_trainer, ) trainer_info_not_active = Training_Lead.objects.exclude( start_date__gte=start_date, end_date__lte=end_date, lead_status__contains=lead_status, ) df = {"user": user, "partner": partner,"start_date": start_date,"end_date":end_date,"trainer":trainer,"lead_status":lead_status,"assign_to_trainer":assign_to_trainer, "lead_status": lead_status,"trainers_info": trainers_info, "trainer_info": trainer_info, "trainer_info_not_active": trainer_info_not_active} return render(request, "trainers_for_schedule_date.html", df) else: return redirect("router") HTML code <label class="form-label" for="assign_to_trainer"> <h4 style="color: rgb(0, 0, 0);">Assign To Trainer :-</h4> </label> <select name="assign_to_trainer" id="assign_to_trainer" multiple> {% for t in leads %} <option name="assign_to_trainer" id="assign_to_trainer" value="{{ t.assign_to_trainer_id }}">{{ t.assign_to_trainer }}</option> {% endfor %} </select> please help me to solve this My problem is if I use assign_to_trainer inside the filter query instead of Training_Lead I receive the error: enter image description here
[ "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_trainer,\n )\n\n", "Hi you can do it this way in your filter query:\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_id=int(assign_to_trainer),\n )\n\n\nHere, assign_to_trainer_id expects an integer only.\n\n" ]
[ 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 function seo.get_serps, it has the option to change the domain, since its default is google.co.uk, I want to change it to www.google.com. How can you specify it in the "results" line though? Thank you results = seo.get_serps(mysearch,pages=2) While I try running this, as compare to google results, there are 1 or 2 results not matched completely. Therefore I was wondering how to change the domain to make it proper. Thank you A: First, upgrade to the latest version of EcommerceTools by entering pip3 install --upgrade ecommercetools ... 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 code, i.e. de or en. from ecommercetools import seo df = seo.get_serps("bmw", pages=1, domain="google.de", host_language="de") df
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, since its default is google.co.uk, I want to change it to www.google.com. How can you specify it in the "results" line though? Thank you results = seo.get_serps(mysearch,pages=2) While I try running this, as compare to google results, there are 1 or 2 results not matched completely. Therefore I was wondering how to change the domain to make it proper. Thank you
[ "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 code, i.e. de or en.\nfrom ecommercetools import seo\n\ndf = seo.get_serps(\"bmw\", pages=1, domain=\"google.de\", host_language=\"de\")\ndf\n\n" ]
[ 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 I tried using strip() like with open("facts.txt", 'r', encoding = "utf-8") as f: lines = f.read() lines.strip("\n") But it isn't working. A: Assuming the file's content is always in that form: Split lines with 1 '\n' Join back the list with 1 space (' ') Replace converted 3 spaces (' ') to 1 '\n' with open('facts.txt') as f: lines = f.read() print(' '.join(lines.split('\n')).replace(' ', '\n')) Or: with open('facts.txt') as f: print(chr(32).join(f.read().split('\n')).replace(chr(32)*3,'\n'))
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', encoding = "utf-8") as f: lines = f.read() lines.strip("\n") But it isn't working.
[ "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') as f: print(chr(32).join(f.read().split('\\n')).replace(chr(32)*3,'\\n'))\n\n" ]
[ 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 row contain next parameters: E | number_of_iteration | result The actual mapping is like this: E -> newenergy_grid[i] number_of_iteration -> [j] result -> gaus_res_ij Here is the code which is running now and collects all data to the "list of lists" object. I have tried to get all data into a dataframe (code commented after list generation) - but it works very slowly. It's about 10000 points in a list and about 10000 in a offset list. I understand that I need to optimize solution to collect and store all the data into single dataframe. How to do it right? Maybe I can use numpy for efficient calculation and after - just save the resulting ndarray into one dataframe? I understand the idea but I don't really get how to realize it.. # TODO: IMPORTANT(!) it's much easier to work with dataframes... # here I want to have such structure of resulting dataframe # E | number_of_iteration | result # results_df = pd.DataFrame() all_res = [] #global list of lists - each list for one energy level for i in range(0, len(newenergy_grid)): # res_for_one_E = np.empty(len(energy_grid)) #iterating through the energy grid list_for_one_E = [] for j in range(0, len(doffset)): #iterating through the seeding steps # selection of parameters for function calculation - they are stored in the lists p = [ damp1[j], dcen1[j], dsigma1[j], damp2[j], dcen2[j], dsigma2[j], damp3[j], dcen3[j], dsigma3[j], doffset[j] ] gaus_res_ij = _3gaussian(newenergy_grid[i], *p) # for the i-th energy level and for j-th realization of a curve list_for_one_E.append(gaus_res_ij) """ #dataframes for future analysis # too slow solution... how to speed up it or use numpy? temp = pd.DataFrame({ "E": newenergy_grid[i], "step_number": j, "res": res_for_one_E }, index=[j]) results_df = pd.concat([results_df, temp]) """ all_res.append(list_for_one_E) #appending the calculated list to the 'list of lists' UPDATE - providing some data for understanding. newenergy_grid [135.11618653 135.12066818 135.12514984 ... 179.91929833 179.92377998 179.92826164] - about 10000 points which represent energy coordinates for a function under test. The number of points depends on data obtained for observation, in my case 100...100000 points on the energy axis. in the middle of the code I have p - list of parameters for the function _3gaussian(newenergy_grid[i], *p) - which calculates the resulting value I need to save for the point with coordinates (newenergy_grid[i], j). So it's the function f(x,y*) that calculates the value at the x = newenergy_grid[i], and y* stands for set of parameters, each element of a set is dependent on iteration number j and is already calculated - so on the each step ij I am only selecting the parameters y using j, and calculating the value of a function f(x[i], y*[j]). List p is constructed on each step j using pregenerated lists (damp1[j], dcen1[j], dsigma1[j], damp2[j], dcen2[j], dsigma2[j], damp3[j], dcen3[j], dsigma3[j], doffset[j]) j - is the index of a point in the lists of parameters, it can be iterated from 0 to len(offset). Each of the parameters of a p list has about 10000 elements, so j changes from 0 to len(doffset) damp1 [19.85128939 19.32065201 ... 19.50304656] dsigma1 [0.07900404 0.0798217 ... 0.08074941] ... A: Putting some random data together according to your description, and running the code you provided: from random import random def _3gaussian(x, *y): return x * sum([*y]) # some arbitrary value, not relevant to the question n = 10 # size is arbitrary, scale up to see performance impacts m = 20 newenergy_grid = [random() * 200 for _ in range(m)] damp1 = [random() * 20 for _ in range(n)] damp2 = [random() * 20 for _ in range(n)] damp3 = [random() * 20 for _ in range(n)] dsigma1 = [random() * .1 for _ in range(n)] dsigma2 = [random() * .1 for _ in range(n)] dsigma3 = [random() * .1 for _ in range(n)] dcen1 = [random() for _ in range(n)] dcen2 = [random() for _ in range(n)] dcen3 = [random() for _ in range(n)] doffset = [random() for _ in range(n)] all_res = [] for i in range(0, len(newenergy_grid)): list_for_one_E = [] for j in range(0, len(doffset)): p = [ damp1[j], dcen1[j], dsigma1[j], damp2[j], dcen2[j], dsigma2[j], damp3[j], dcen3[j], dsigma3[j], doffset[j] ] gaus_res_ij = _3gaussian(newenergy_grid[i], *p) list_for_one_E.append(gaus_res_ij) all_res.append(list_for_one_E) print(all_res) This results in an m x n list of lists, or 2D matrix. So, it's certainly suited to be stored in a DataFrame, although it's not going to be much faster without looking at how you construct the numbered variables before you run this section of code. The naming and structure of damp1, damp2, .., dsigma1, dsigma2, .. suggest there's some substantial optimisation possible before you get to this code. However, starting with those named lists, this would be an improvement, for brevity if anything: from pandas import DataFrame, concat df = DataFrame([ damp1, damp2, damp3, dsigma1, dsigma2, dsigma3, dcen1, dcen2, dcen3, doffset ]) result_df = concat([df.apply(lambda row: _3gaussian(e, *row)) for e in newenergy_grid], axis=1).T from numpy import isclose print(isclose(result_df, DataFrame(all_res))) Note: I'm using isclose here because due to floating point inaccuracy, the results won't actually be identical, as pandas' float64 is not the same as Python's float. As for performance, you'll likely find that using DataFrames here is no faster, in fact probably an order of magnitude or more slower, since you're not leveraging the data types available in numpy and pandas at all. If you load your data in suitable types from the beginning and vectorise your function, you may be able to improve substantially on speed - but that depends not on the code you shared here, but on all the other code and exceeds the scope of a single question. You could try submitting a more comprehensive example on Code Review and ask for help there. A: I have found some solution of my problem. As I am a newbie in Python, I have to make a lot of errors before I will code better (probably :), -> I know that answer was easy and clear from the very first line). The key was to "vectorize" the function _3gaussian(...), and apply it to the entire vector of parameters at once with the minimal use of cycles and iterations. Inside this function I have used numpy and ndarrays as inputs so there weren't any problems with the performance. With such solution the resulting dataframe was calculated more than one hundred times faster. here is the code which is doing the same things as the code in a question. rand_iter_num = N_seed e_len = np.count_nonzero(newenergy_grid) result_arr = np.empty((rand_iter_num, e_len), dtype=np.float64) print(rand_iter_num) print(e_len) for j in range(0, rand_iter_num): p = [ damp1[j], dcen1[j], dsigma1[j], damp2[j], dcen2[j], dsigma2[j], damp3[j], dcen3[j], dsigma3[j], doffset[j] ] gaus_res = _3gaussian(newenergy_grid, *p) result_arr[j] = gaus_res df_res = pd.DataFrame(result_arr, columns=newenergy_grid)
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 this: E -> newenergy_grid[i] number_of_iteration -> [j] result -> gaus_res_ij Here is the code which is running now and collects all data to the "list of lists" object. I have tried to get all data into a dataframe (code commented after list generation) - but it works very slowly. It's about 10000 points in a list and about 10000 in a offset list. I understand that I need to optimize solution to collect and store all the data into single dataframe. How to do it right? Maybe I can use numpy for efficient calculation and after - just save the resulting ndarray into one dataframe? I understand the idea but I don't really get how to realize it.. # TODO: IMPORTANT(!) it's much easier to work with dataframes... # here I want to have such structure of resulting dataframe # E | number_of_iteration | result # results_df = pd.DataFrame() all_res = [] #global list of lists - each list for one energy level for i in range(0, len(newenergy_grid)): # res_for_one_E = np.empty(len(energy_grid)) #iterating through the energy grid list_for_one_E = [] for j in range(0, len(doffset)): #iterating through the seeding steps # selection of parameters for function calculation - they are stored in the lists p = [ damp1[j], dcen1[j], dsigma1[j], damp2[j], dcen2[j], dsigma2[j], damp3[j], dcen3[j], dsigma3[j], doffset[j] ] gaus_res_ij = _3gaussian(newenergy_grid[i], *p) # for the i-th energy level and for j-th realization of a curve list_for_one_E.append(gaus_res_ij) """ #dataframes for future analysis # too slow solution... how to speed up it or use numpy? temp = pd.DataFrame({ "E": newenergy_grid[i], "step_number": j, "res": res_for_one_E }, index=[j]) results_df = pd.concat([results_df, temp]) """ all_res.append(list_for_one_E) #appending the calculated list to the 'list of lists' UPDATE - providing some data for understanding. newenergy_grid [135.11618653 135.12066818 135.12514984 ... 179.91929833 179.92377998 179.92826164] - about 10000 points which represent energy coordinates for a function under test. The number of points depends on data obtained for observation, in my case 100...100000 points on the energy axis. in the middle of the code I have p - list of parameters for the function _3gaussian(newenergy_grid[i], *p) - which calculates the resulting value I need to save for the point with coordinates (newenergy_grid[i], j). So it's the function f(x,y*) that calculates the value at the x = newenergy_grid[i], and y* stands for set of parameters, each element of a set is dependent on iteration number j and is already calculated - so on the each step ij I am only selecting the parameters y using j, and calculating the value of a function f(x[i], y*[j]). List p is constructed on each step j using pregenerated lists (damp1[j], dcen1[j], dsigma1[j], damp2[j], dcen2[j], dsigma2[j], damp3[j], dcen3[j], dsigma3[j], doffset[j]) j - is the index of a point in the lists of parameters, it can be iterated from 0 to len(offset). Each of the parameters of a p list has about 10000 elements, so j changes from 0 to len(doffset) damp1 [19.85128939 19.32065201 ... 19.50304656] dsigma1 [0.07900404 0.0798217 ... 0.08074941] ...
[ "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\nnewenergy_grid = [random() * 200 for _ in range(m)]\ndamp1 = [random() * 20 for _ in range(n)]\ndamp2 = [random() * 20 for _ in range(n)]\ndamp3 = [random() * 20 for _ in range(n)]\ndsigma1 = [random() * .1 for _ in range(n)]\ndsigma2 = [random() * .1 for _ in range(n)]\ndsigma3 = [random() * .1 for _ in range(n)]\ndcen1 = [random() for _ in range(n)]\ndcen2 = [random() for _ in range(n)]\ndcen3 = [random() for _ in range(n)]\ndoffset = [random() for _ in range(n)]\n\nall_res = []\n\nfor i in range(0, len(newenergy_grid)):\n list_for_one_E = []\n\n for j in range(0, len(doffset)):\n p = [\n damp1[j], dcen1[j], dsigma1[j],\n damp2[j], dcen2[j], dsigma2[j],\n damp3[j], dcen3[j], dsigma3[j],\n doffset[j]\n ]\n\n gaus_res_ij = _3gaussian(newenergy_grid[i], *p)\n\n list_for_one_E.append(gaus_res_ij)\n\n all_res.append(list_for_one_E)\n\nprint(all_res)\n\nThis results in an m x n list of lists, or 2D matrix. So, it's certainly suited to be stored in a DataFrame, although it's not going to be much faster without looking at how you construct the numbered variables before you run this section of code.\nThe naming and structure of damp1, damp2, .., dsigma1, dsigma2, .. suggest there's some substantial optimisation possible before you get to this code.\nHowever, starting with those named lists, this would be an improvement, for brevity if anything:\nfrom pandas import DataFrame, concat\n\ndf = DataFrame([\n damp1, damp2, damp3, dsigma1, dsigma2, dsigma3, dcen1, dcen2, dcen3, doffset\n])\nresult_df = concat([df.apply(lambda row: _3gaussian(e, *row)) \n for e in newenergy_grid], axis=1).T\n\nfrom numpy import isclose\nprint(isclose(result_df, DataFrame(all_res)))\n\nNote: I'm using isclose here because due to floating point inaccuracy, the results won't actually be identical, as pandas' float64 is not the same as Python's float.\nAs for performance, you'll likely find that using DataFrames here is no faster, in fact probably an order of magnitude or more slower, since you're not leveraging the data types available in numpy and pandas at all.\nIf you load your data in suitable types from the beginning and vectorise your function, you may be able to improve substantially on speed - but that depends not on the code you shared here, but on all the other code and exceeds the scope of a single question.\nYou could try submitting a more comprehensive example on Code Review and ask for help there.\n", "I have found some solution of my problem. As I am a newbie in Python, I have to make a lot of errors before I will code better (probably :), -> I know that answer was easy and clear from the very first line).\nThe key was to \"vectorize\" the function _3gaussian(...), and apply it to the entire vector of parameters at once with the minimal use of cycles and iterations.\nInside this function I have used numpy and ndarrays as inputs so there weren't any problems with the performance. With such solution the resulting dataframe was calculated more than one hundred times faster.\nhere is the code which is doing the same things as the code in a question.\nrand_iter_num = N_seed\ne_len = np.count_nonzero(newenergy_grid)\n\nresult_arr = np.empty((rand_iter_num, e_len), dtype=np.float64)\n\nprint(rand_iter_num)\nprint(e_len)\n\nfor j in range(0, rand_iter_num):\n\n p = [\n damp1[j], dcen1[j], dsigma1[j],\n damp2[j], dcen2[j], dsigma2[j],\n damp3[j], dcen3[j], dsigma3[j],\n doffset[j]\n ] \n\n gaus_res = _3gaussian(newenergy_grid, *p)\n result_arr[j] = gaus_res\ndf_res = pd.DataFrame(result_arr, columns=newenergy_grid)\n\n" ]
[ 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 Progressbar import time class MonApp(Tk): def __init__(self): super().__init__() bt1 = Button(self, text='Traitement', command=self.traitement) bt1.grid() self.progress = Progressbar(self, orient=HORIZONTAL, length=100, mode='indeterminate') self.progress.grid() self.progress.grid_forget() def traitement(self): self.progress.grid() self.progress.start() time.sleep(15) ## Just like you have many, many code lines... self.progress.stop() if __name__ == '__main__': app = MonApp() app.mainloop() How can I put a progress bar in that application? A: You can find ttk.Progressbar at tkdocs import time from tkinter import * from tkinter.ttk import * tk = Tk() progress = Progressbar(tk, orient=HORIZONTAL, length=100, mode='determinate') def bar(): progress['value'] = 20 tk.update_idletasks() time.sleep(1) progress['value'] = 50 tk.update_idletasks() time.sleep(1) progress['value'] = 80 tk.update_idletasks() time.sleep(1) progress['value'] = 100 progress.pack() Button(tk, text='foo', command=bar).pack() mainloop() It's better to use threading and run your code in another thread. Like this: import threading import time from tkinter import Button, Tk, HORIZONTAL from tkinter.ttk import Progressbar class MonApp(Tk): def __init__(self): super().__init__() self.btn = Button(self, text='Traitement', command=self.traitement) self.btn.grid(row=0, column=0) self.progress = Progressbar(self, orient=HORIZONTAL, length=100, mode='indeterminate') def traitement(self): def real_traitement(): self.progress.grid(row=1,column=0) self.progress.start() time.sleep(5) self.progress.stop() self.progress.grid_forget() self.btn['state']='normal' self.btn['state']='disabled' threading.Thread(target=real_traitement).start() if __name__ == '__main__': app = MonApp() app.mainloop() A: For all the GUI elements to modify themselves (in your case, for the progress bar to move) the execution must hit app.mainloop(). In your case, def traitement(self): starts and then stops the progressbar without hitting the mainloop, so it fails to visibly reflect the intended progressbar movement on the GUI. The catch here is, when the execution hits mainloop, progressbar is configured to 'stop' state. Hence, it is a good idea to execute time consuming activities on a different Thread as shown by @xmcp However, if you DO NOT want to use threading, you can use the after method to achieve what you want: def stop_progressbar(self): self.progress.stop() def traitement(self): self.progress.grid() self.progress.start() self.after(15000, self.stop_progressbar) ## Call Just like you have many, many code lines... The above code used self.after() method which will execute the stop_progressbar method to stop after 15 seconds, instead of time.sleep() which blocks the mainthread. A: tqdm is a popular progressbar library that also has experimental support for tkinter (link to API). It is effectively a wrapper for ttk.Progressbar. The usage is not well documented (and there are obvious bugs) but here is a minimal working example: from tqdm.tk import tqdm from time import sleep from tkinter import Tk, Button window = Tk() pbar = tqdm(total=30, tk_parent=window) def run_task(): for _ in range(30): sleep(0.1) pbar.update(1) pbar.close() # intended usage, might be buggy #pbar._tk_window.destroy() # workaround start_button = Button(window, text="Start", command=run_task) start_button.pack() window.mainloop() Will produce a progressbar in a separate window looking like this:
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): def __init__(self): super().__init__() bt1 = Button(self, text='Traitement', command=self.traitement) bt1.grid() self.progress = Progressbar(self, orient=HORIZONTAL, length=100, mode='indeterminate') self.progress.grid() self.progress.grid_forget() def traitement(self): self.progress.grid() self.progress.start() time.sleep(15) ## Just like you have many, many code lines... self.progress.stop() if __name__ == '__main__': app = MonApp() app.mainloop() How can I put a progress bar in that application?
[ "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 tk.update_idletasks()\n time.sleep(1)\n progress['value'] = 80\n tk.update_idletasks()\n time.sleep(1)\n progress['value'] = 100\n\nprogress.pack()\nButton(tk, text='foo', command=bar).pack()\nmainloop()\n\nIt's better to use threading and run your code in another thread.\nLike this:\nimport threading\nimport time\nfrom tkinter import Button, Tk, HORIZONTAL\nfrom tkinter.ttk import Progressbar\n\nclass MonApp(Tk):\n def __init__(self):\n super().__init__()\n\n self.btn = Button(self, text='Traitement', command=self.traitement)\n self.btn.grid(row=0, column=0)\n self.progress = Progressbar(self, orient=HORIZONTAL, length=100, mode='indeterminate')\n\n def traitement(self):\n def real_traitement():\n self.progress.grid(row=1,column=0)\n self.progress.start()\n time.sleep(5)\n self.progress.stop()\n self.progress.grid_forget()\n\n self.btn['state']='normal'\n\n self.btn['state']='disabled'\n threading.Thread(target=real_traitement).start()\n\n\nif __name__ == '__main__':\n app = MonApp()\n app.mainloop()\n\n", "For all the GUI elements to modify themselves (in your case, for the progress bar to move) the execution must hit app.mainloop(). \nIn your case, def traitement(self): starts and then stops the progressbar without hitting the mainloop, so it fails to visibly reflect the intended progressbar movement on the GUI. The catch here is, when the execution hits mainloop, progressbar is configured to 'stop' state. \nHence, it is a good idea to execute time consuming activities on a different Thread as shown by @xmcp\nHowever, if you DO NOT want to use threading, you can use the after method to achieve what you want:\ndef stop_progressbar(self):\n self.progress.stop()\n\ndef traitement(self):\n self.progress.grid()\n self.progress.start()\n self.after(15000, self.stop_progressbar) \n ## Call Just like you have many, many code lines...\n\nThe above code used self.after() method which will execute the stop_progressbar method to stop after 15 seconds, instead of time.sleep() which blocks the mainthread.\n", "tqdm is a popular progressbar library that also has experimental support for tkinter (link to API). It is effectively a wrapper for ttk.Progressbar.\nThe usage is not well documented (and there are obvious bugs) but here is a minimal working example:\nfrom tqdm.tk import tqdm\nfrom time import sleep\nfrom tkinter import Tk, Button \n\nwindow = Tk() \n\npbar = tqdm(total=30, tk_parent=window) \n\ndef run_task():\n for _ in range(30):\n sleep(0.1)\n pbar.update(1)\n pbar.close() # intended usage, might be buggy\n #pbar._tk_window.destroy() # workaround\n \nstart_button = Button(window, text=\"Start\", command=run_task)\nstart_button.pack()\n \nwindow.mainloop()\n\nWill produce a progressbar in a separate window looking like this:\n\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 risking to lose files i'd need, can you please check if it is correct?? thanks import os import shutil dir = '/Volume/X' targetDir = 'myDir' for subdir, dirs, files in os.walk(dir): dirpath = subdir if dirpath.exists() and dirpath.is_dir(): shutil.rmtree(dirpath) A: Here it is, I fixed your code and made it a bit more useful so anyone can use it :) enjoy #coded by antoclk @ antonioaunix@gmail.com import os import shutil #in dir variable you should put the path you need to scan dir = '/Users/YOURUSERNAME/Desktop/main' #in target variable you should put the exact name of the folder you want to delete. Be careful to use it, it will delete all the files and subfolders contained in the target dir. target = 'x' os.system('cls') os.system('clear') print('Removing '+target+' folder from '+dir+' and all its subfolders.') for dirpath, dirnames, filenames in os.walk(dir): for item in dirnames: fullPath = os.path.join(dirpath, item) #print(os.path.join(dirpath, item)) if item == 'target': print('deleting '+fullPath) shutil.rmtree(fullPath) print('Task completed!') A: Fixed a slight bug in the accepted answer (by antoaunix) at the level of if item == 'target'. It had to be if item == target and also restructured the code a little bit. import shutil import os class FolderCleaner: @staticmethod def _init(target: str, dirname: str) -> None: print(f"Removing '{target}' from '{dirname}' and all it's sub-folders") @staticmethod def _reset_view() -> None: os.system("cls") os.system("clear") @staticmethod def delete_all_folders(dirname: str, folder_name: str) -> None: FolderCleaner._reset_view() FolderCleaner._init(target=folder_name, dirname=dirname) for dir_path, dir_names, filenames in os.walk(dirname): for item in dir_names: full_path = os.path.join(dir_path, item) if item == folder_name: print(f"deleting {full_path}") shutil.rmtree(full_path) print("Task completed!") if __name__ == "__main__": FolderCleaner.delete_all_folders(dirname="./", folder_name="__pycache__")
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 correct?? thanks import os import shutil dir = '/Volume/X' targetDir = 'myDir' for subdir, dirs, files in os.walk(dir): dirpath = subdir if dirpath.exists() and dirpath.is_dir(): shutil.rmtree(dirpath)
[ "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 of the folder you want to delete. Be careful to use it, it will delete all the files and subfolders contained in the target dir.\ntarget = 'x'\n\nos.system('cls') \nos.system('clear')\n\nprint('Removing '+target+' folder from '+dir+' and all its subfolders.')\n\nfor dirpath, dirnames, filenames in os.walk(dir):\n for item in dirnames:\n fullPath = os.path.join(dirpath, item)\n #print(os.path.join(dirpath, item))\n if item == 'target':\n print('deleting '+fullPath)\n shutil.rmtree(fullPath)\n\nprint('Task completed!')\n\n", "Fixed a slight bug in the accepted answer (by antoaunix) at the level of if item == 'target'. It had to be if item == target and also restructured the code a little bit.\nimport shutil\nimport os\n\n\nclass FolderCleaner:\n @staticmethod\n def _init(target: str, dirname: str) -> None:\n print(f\"Removing '{target}' from '{dirname}' and all it's sub-folders\")\n\n @staticmethod\n def _reset_view() -> None:\n os.system(\"cls\")\n os.system(\"clear\")\n \n @staticmethod\n def delete_all_folders(dirname: str, folder_name: str) -> None:\n FolderCleaner._reset_view()\n FolderCleaner._init(target=folder_name, dirname=dirname)\n for dir_path, dir_names, filenames in os.walk(dirname):\n for item in dir_names:\n full_path = os.path.join(dir_path, item)\n if item == folder_name:\n print(f\"deleting {full_path}\")\n shutil.rmtree(full_path)\n print(\"Task completed!\")\n\n\nif __name__ == \"__main__\":\n FolderCleaner.delete_all_folders(dirname=\"./\", folder_name=\"__pycache__\")\n\n" ]
[ 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) 200000000.0 906 20.0 219 10.0 158 Name: value, dtype: int64 But when I use value_counts(), I only get the value 200000000 as the most occurring one, but instead it should be something around 0.02. Can someone explain what exactly happens here. The sample data that I used is here. A: A histogram, gives you the counts over bins. This means the count/frequency of consecutive groups of values. df['value'].plot.hist() The (approximate) equivalent using a bar graph, would be to first compute bins with pandas.cut: pd.cut(df['value'], bins=10).value_counts(sort=False).plot.bar() Output of pd.cut(df['value'], bins=10).value_counts(sort=False): (-199999.996, 20000000.004] 1523 (20000000.004, 40000000.003] 5 (40000000.003, 60000000.003] 9 (60000000.003, 80000000.002] 5 (80000000.002, 100000000.002] 0 (100000000.002, 120000000.002] 8 (120000000.002, 140000000.001] 0 (140000000.001, 160000000.001] 0 (160000000.001, 180000000.0] 0 (180000000.0, 200000000.0] 906 Name: value, dtype: int64 A: they are the same thing if you checked the csv file you will find that 200000000.0 is exactly 906 and that is what they both showing but in the histogram they used apprev to the numbers 1e8
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 Name: value, dtype: int64 But when I use value_counts(), I only get the value 200000000 as the most occurring one, but instead it should be something around 0.02. Can someone explain what exactly happens here. The sample data that I used is here.
[ "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 pd.cut(df['value'], bins=10).value_counts(sort=False):\n(-199999.996, 20000000.004] 1523\n(20000000.004, 40000000.003] 5\n(40000000.003, 60000000.003] 9\n(60000000.003, 80000000.002] 5\n(80000000.002, 100000000.002] 0\n(100000000.002, 120000000.002] 8\n(120000000.002, 140000000.001] 0\n(140000000.001, 160000000.001] 0\n(160000000.001, 180000000.0] 0\n(180000000.0, 200000000.0] 906\nName: value, dtype: int64\n\n", "they are the same thing if you checked the csv file you will find that 200000000.0 is exactly 906 and that is what they both showing\nbut in the histogram they used apprev to the numbers 1e8\n" ]
[ 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 how to do that. If I did df.apply(f) I can't access other cells in the row as x is just the value of the one cell. I don't want to create a new column either. I want to directly change the value of the cell as I compare it to benchmark, clearing or 0'ing the cells that that do not meet the benchmark. Any insight? A: You don't need a function, instead use vectorial operations: out = df.where(df.gt(df['benchmark'], axis=0), 0) To change the values in place: df[df.le(df['benchmark'], axis=0)] = 0 Output: a b benchmark 0 0 2 0 1 0 5 0 If you don't want to affect benchmark: m = df.le(df['benchmark'], axis=0) m['benchmark'] = False df[m] = 0 Output: a b benchmark 0 0 2 1 1 0 5 3
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 other cells in the row as x is just the value of the one cell. I don't want to create a new column either. I want to directly change the value of the cell as I compare it to benchmark, clearing or 0'ing the cells that that do not meet the benchmark. Any insight?
[ "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['benchmark'], axis=0)\nm['benchmark'] = False\n\ndf[m] = 0\n\nOutput:\n a b benchmark\n0 0 2 1\n1 0 5 3\n\n" ]
[ 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: Here's a one liner: def key_in_dict(d, key): return 'Exists!' if key in d else "Doesn't exist!"
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 since I have many dfs. any link reference or suggestion? many thanks in advance df1 = DATE a b c 0 2006-10-31 100 200 300 1 2006-11-30 10 400 5 2 2006-12-28 50 5 90 df2 = DATE symbol desired ouput 0 2006-10-31 a 100 1 2006-11-30 b 400 2 2006-12-28 c 90 A: This is a variant on an indexing lookup, using a reindexing of df1: idx, cols = pd.factorize(df2['symbol']) df2['desired output'] = ( df1.set_index('DATE') .reindex(index=df2['DATE'], columns=cols) .to_numpy() )[np.arange(len(df1)), idx] Another approach (probably less efficient) would be to melt and merge: out = df2.merge(df1.melt('DATE', var_name='symbol', value_name='desired output')) Output: DATE symbol desired output 0 2006-10-31 a 100 1 2006-11-30 b 400 2 2006-12-28 c 90
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 advance df1 = DATE a b c 0 2006-10-31 100 200 300 1 2006-11-30 10 400 5 2 2006-12-28 50 5 90 df2 = DATE symbol desired ouput 0 2006-10-31 a 100 1 2006-11-30 b 400 2 2006-12-28 c 90
[ "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) would be to melt and merge:\nout = df2.merge(df1.melt('DATE', var_name='symbol', value_name='desired output'))\n\nOutput:\n DATE symbol desired output\n0 2006-10-31 a 100\n1 2006-11-30 b 400\n2 2006-12-28 c 90\n\n" ]
[ 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 to system variables. A: You must configure your PyCharm path to show where is interpreter of Python on your PC. https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html
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] Exception occurred while handling uri: 'http://url.ngrok.io/webhook' Traceback (most recent call last): File "handle_request", line 103, in handle_request "_future_listeners", sanic.exceptions.ServerError: Invalid response type None (need HTTPResponse) The code is as follows: from datetime import datetime from sanic import Sanic from sanic import response from ib_insync import * #Create Sanic object app = Sanic(__name__) app.ib = None #Create root @app.route('/') async def root(request): return response.text('online') #Listen for signals and execute orders @app.route('/webhook', methods=['POST']) async def webhook(request): if request.method == 'POST': await checkIfReconnect() #Parse alert data alert = request.json order = MarketOrder(alert['action'],alert['quantity'],account=app.ib.wrapper.accounts[0]) #Submit market order stock_contract = Stock('NVDA','SMART','USD') app.ib.placeOrder(stock_contract,order) #Reconnect if needed async def checkIfReconnect(): if not app.ib.isConnected() or not app.ib.client.isConnected(): app.ib.disconnect() app.ib = IB() app.ib.connect('127.0.0.1',7496,clientId=1) #Run app if __name__ == '__main__': #Connect to IB app.ib = IB() app.ib.connect('127.0.0.1',7496,clientId=1) app.run(port=5000) A: 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. Ie, change your webhook code to this: @app.route('/webhook', methods=['POST']) async def webhook(request): if request.method == 'POST': await checkIfReconnect() #Parse alert data alert = request.json order = MarketOrder(alert['action'],alert['quantity'],account=app.ib.wrapper.accounts[0]) #Submit market order stock_contract = Stock('NVDA','SMART','USD') app.ib.placeOrder(stock_contract,order) return HTTPResponse("ok", 200) #<-- This line added return HTTPResponse("", 405) #<-- else return this A: Im working with the same code, using breakpoints every POST triggers correctly. I see exactly what you mean how only 1 order can be placed each time the app is started. I tried using ib.qualifyContract(Stock) but it creates an error within the loop for the webhook. I wonder if you can move your order placement outside any loop functions. Ill try when I get some time and report back. A: I'm using almost the same script as you do. I'm guessing your problem is not the http response as mentioned before(I don't use it). The thing is that each order sent to IB has to have a unique identifier and im not seeing you applied to your code. You can read about here (https://interactivebrokers.github.io/tws-api/order_submission.html). I found a way for doing that but its complicated for me to explain here. basically you'll have to add the order id to each and every order sent and from there there are two ways to go: connect properly to IBapi and check for the current available unique order ID use an ID of your own(numeric) for example in a form of a loop, and reset the sequence in TWS on each restart of the script as shown on the link I added. A: I encountered the same issue (_future_listeners) while working on the same code. Been looking around to find the solution but none of them worked so far. I am sharing this to see if you guys were able to fix it. I tried (or intended to try) these solutions: 1- I used asynchronous connect (app.ib.connectAsync) instead of app.ib.connect in both places. But it returned the await warning error. The second app.ib.connectAsync is outside an async function so cannot be awaited. You can run the code but it gives another error: "list index out of range" for the MarketOrder function. 2- I added app.ib.qualifyContracts . but it did not resolve the issue as well. I used it and not even the first order was sent to TWS. 3- Adding the unique orderid. I have not tried it because I am not sure if it works. I printed the orders, it seems like they already been ordered. A: I started out with the same widely distributed boilerplate code you are using. After making the changes outlined below, my code works. I lack the expertise to explain why it does--but it does. Assuming you have the following installed: Python 3.10.7_64 Sanic 22.6.2 ib_insync 0.9.71 (1) pip install --upgrade sanic-cors sanic-plugin-toolkit ref: IB_insync - Sanic error after one successful order preventing any further orders (not sure if necessary) (2) Add: import time (see clientId note below) (3) Add: import nest_asyncio nest_asyncio.apply() #ref: RuntimeError: This event loop is already running in python (4) Use Async connect in initial connect at bottom (but not in the reconnect area) app.ib.connectAsync('127.0.0.1',7497,clientId=see below) # 7946=live, 7947=paper ref:IB_insync - Sanic error after one successful order preventing any further orders (5) Use time to derive a unique, ascending clientId in both connect statements clientId=int(int((time.time()*1000)-1663849395690)/1000000)) This helps avoid a "socket in use" condition on reconnect (6) Add HTTPResponse statements as suggested above. (7) Per Ewald de Wit, ib_insync author: "There's no need to set the orderId, it's issued automatically when the order is placed." A: There is an alternative, return return response.json({}) at the end of the async function webhook ........ from sanic import response ...... #Listen for signals and execute orders @app.route('/webhook', methods=['POST']) async def webhook(request): if request.method == 'POST': await checkIfReconnect() #Parse alert data alert = request.json order = MarketOrder(alert['action'],alert['quantity'],account=app.ib.wrapper.accounts[0]) #Submit market order stock_contract = Stock('NVDA','SMART','USD') app.ib.placeOrder(stock_contract,order) return response.json({}) # return a empty JSON
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 recent call last): File "handle_request", line 103, in handle_request "_future_listeners", sanic.exceptions.ServerError: Invalid response type None (need HTTPResponse) The code is as follows: from datetime import datetime from sanic import Sanic from sanic import response from ib_insync import * #Create Sanic object app = Sanic(__name__) app.ib = None #Create root @app.route('/') async def root(request): return response.text('online') #Listen for signals and execute orders @app.route('/webhook', methods=['POST']) async def webhook(request): if request.method == 'POST': await checkIfReconnect() #Parse alert data alert = request.json order = MarketOrder(alert['action'],alert['quantity'],account=app.ib.wrapper.accounts[0]) #Submit market order stock_contract = Stock('NVDA','SMART','USD') app.ib.placeOrder(stock_contract,order) #Reconnect if needed async def checkIfReconnect(): if not app.ib.isConnected() or not app.ib.client.isConnected(): app.ib.disconnect() app.ib = IB() app.ib.connect('127.0.0.1',7496,clientId=1) #Run app if __name__ == '__main__': #Connect to IB app.ib = IB() app.ib.connect('127.0.0.1',7496,clientId=1) app.run(port=5000)
[ "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 request.method == 'POST':\n await checkIfReconnect()\n #Parse alert data\n alert = request.json\n order = MarketOrder(alert['action'],alert['quantity'],account=app.ib.wrapper.accounts[0])\n #Submit market order\n stock_contract = Stock('NVDA','SMART','USD')\n app.ib.placeOrder(stock_contract,order)\n return HTTPResponse(\"ok\", 200) #<-- This line added\n return HTTPResponse(\"\", 405) #<-- else return this\n\n\n", "Im working with the same code, using breakpoints every POST triggers correctly. I see exactly what you mean how only 1 order can be placed each time the app is started. I tried using ib.qualifyContract(Stock) but it creates an error within the loop for the webhook. I wonder if you can move your order placement outside any loop functions. Ill try when I get some time and report back.\n", "I'm using almost the same script as you do.\nI'm guessing your problem is not the http response as mentioned before(I don't use it).\nThe thing is that each order sent to IB has to have a unique identifier and im not seeing you applied to your code.\nYou can read about here (https://interactivebrokers.github.io/tws-api/order_submission.html).\nI found a way for doing that but its complicated for me to explain here.\nbasically you'll have to add the order id to each and every order sent and from there there are two ways to go:\n\nconnect properly to IBapi and check for the current available unique order ID\nuse an ID of your own(numeric) for example in a form of a loop, and reset the sequence in TWS on each restart of the script as shown on the link I added.\n\n", "I encountered the same issue (_future_listeners) while working on the same code. Been looking around to find the solution but none of them worked so far. I am sharing this to see if you guys were able to fix it.\nI tried (or intended to try) these solutions:\n1- I used asynchronous connect (app.ib.connectAsync) instead of app.ib.connect in both places. But it returned the await warning error. The second app.ib.connectAsync is outside an async function so cannot be awaited. You can run the code but it gives another error: \"list index out of range\" for the MarketOrder function.\n2- I added app.ib.qualifyContracts . but it did not resolve the issue as well. I used it and not even the first order was sent to TWS.\n3- Adding the unique orderid. I have not tried it because I am not sure if it works. I printed the orders, it seems like they already been ordered.\n", "I started out with the same widely distributed boilerplate code you are using. After making the changes outlined below, my code works. I lack the expertise to explain why it does--but it does.\nAssuming you have the following installed:\nPython 3.10.7_64\nSanic 22.6.2\nib_insync 0.9.71\n(1) pip install --upgrade sanic-cors sanic-plugin-toolkit\nref: IB_insync - Sanic error after one successful order preventing any further orders\n(not sure if necessary)\n(2) Add:\nimport time (see clientId note below)\n(3) Add:\nimport nest_asyncio\nnest_asyncio.apply()\n#ref: RuntimeError: This event loop is already running in python\n(4) Use Async connect in initial connect at bottom (but not in the reconnect area)\napp.ib.connectAsync('127.0.0.1',7497,clientId=see below) # 7946=live, 7947=paper\nref:IB_insync - Sanic error after one successful order preventing any further orders\n(5) Use time to derive a unique, ascending clientId in both connect statements\nclientId=int(int((time.time()*1000)-1663849395690)/1000000))\nThis helps avoid a \"socket in use\" condition on reconnect\n(6) Add HTTPResponse statements as suggested above.\n(7) Per Ewald de Wit, ib_insync author:\n\"There's no need to set the orderId, it's issued automatically when the\norder is placed.\"\n", "There is an alternative, return return response.json({}) at the end of the async function webhook\n........\nfrom sanic import response\n......\n#Listen for signals and execute orders\n@app.route('/webhook', methods=['POST'])\nasync def webhook(request):\n if request.method == 'POST':\n await checkIfReconnect()\n #Parse alert data\n alert = request.json\n order = MarketOrder(alert['action'],alert['quantity'],account=app.ib.wrapper.accounts[0])\n #Submit market order\n stock_contract = Stock('NVDA','SMART','USD')\n app.ib.placeOrder(stock_contract,order)\n return response.json({}) # return a empty JSON\n\n" ]
[ 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 output the resulting array.c may not be a factor of n or m. Would anyone know how to execute this please. I have tried np.block to split the array and apply to each individual block but then i had trouble reconstructing the matrix. I also attempted to use the slice indexing and store the values in a new array but the issue is my function outputs complex values so these are all discarded when i try and append the new array, A: import numpy as np array = np.array([[1, 2, 3, 1], [4, 5, 6, 4], [7, 8, 9, 7], [11, 22, 33, 44]]) def somefunc(some_array, some_integer): return some_array*3 # say that your blocks needs to be 2X2 for i in range(array.shape[0]): for j in range(array.shape[1]): array[i*2:(i+1)*2, j*2:(j+1)*2] = somefunc(array[i*2:(i+1)*2, j*2:(j+1)*2], 3) A: A rather technical way to do is, but really efficient, is to use stride_tricks, which provides "views" of your array. c=4 N=12 # Note that c is a factor of N # Just an example array A=np.arange(1,N+1).reshape(1,-1)+np.arange(100,100*(N+1),100).reshape(-1,1) stR,stC=A.strides View = np.lib.stride_tricks.as_strided(A, (N//c,N//c,c,c), (c*stR, c*stC,stR,stC)) # You can now vectorize your function to work on such data def switch(X,J): return X.T-J # Just an example switchv=np.vectorize(switch, signature='(c,c),()->(c,c)') # And now switchv can be called on your data J=1 result=switchv(View,J) Explanation. A here is array([[ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112], [ 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212], [ 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312], [ 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412], [ 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512], [ 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612], [ 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712], [ 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812], [ 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912], [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012], [1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112], [1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212]]) A.strides gives the number of bytes separating each level of the array. So here, each lines and then each elements in the lines. In my example A.strides is (96,8), because there are 8 bytes between two consecutive number (we don't really need to bother about bytes. we'll just copy those strides), and 96 between 2 lines (since there are 12 elements per lines, that is not surprising, but again, we don't really care. There could have been some gap between the lines, but that is not our problem). np.lib.stride_tricks.as_strided give a new view of A, with a different shape, and a different way to switch from one level to another. It can even lead to some value being repeated. Note that it is just a view. No array is created here. It is a virtual array. Here, we say that, instead of a NxN array, we want a (N/c)x(N/c)xcxc array. So a (N/c)x(N/c) arrays of blocks, block being cxc arrays of elements. And each we provide a stride of (c*stR, c*stC,stR,stC). Reading that from right to left, that means that inside a row of a block, there are the same amount of bytes than between 2 elements of a line of A. So we will have c succesive elements of A. stR means likewise that between two rows of a block, there is the same gap than between 2 rows of A. So we will also have c subsequent (incomplete but subsequent) rows of A. Then c*stC means that two subsequent blocks are separated by c numbers. And c*stR likewise. So result is array([[[[ 101, 102, 103, 104], [ 201, 202, 203, 204], [ 301, 302, 303, 304], [ 401, 402, 403, 404]], [[ 105, 106, 107, 108], [ 205, 206, 207, 208], [ 305, 306, 307, 308], [ 405, 406, 407, 408]], [[ 109, 110, 111, 112], [ 209, 210, 211, 212], [ 309, 310, 311, 312], [ 409, 410, 411, 412]]], [[[ 501, 502, 503, 504], [ 601, 602, 603, 604], [ 701, 702, 703, 704], [ 801, 802, 803, 804]], [[ 505, 506, 507, 508], [ 605, 606, 607, 608], [ 705, 706, 707, 708], [ 805, 806, 807, 808]], [[ 509, 510, 511, 512], [ 609, 610, 611, 612], [ 709, 710, 711, 712], [ 809, 810, 811, 812]]], [[[ 901, 902, 903, 904], [1001, 1002, 1003, 1004], [1101, 1102, 1103, 1104], [1201, 1202, 1203, 1204]], [[ 905, 906, 907, 908], [1005, 1006, 1007, 1008], [1105, 1106, 1107, 1108], [1205, 1206, 1207, 1208]], [[ 909, 910, 911, 912], [1009, 1010, 1011, 1012], [1109, 1110, 1111, 1112], [1209, 1210, 1211, 1212]]]]) Same array. But viewed as a 3x3 arrays of 4x4 numbers. Again, no copy, no array were created here. It is just another organisation. And here come the second technicality: vectorize. vectorize is a way to tell numpy to call a function on each elements of an array. For a basic example def f(a,b): return a*b fv=np.vectorize(f) fv is a function that can work on array of all shapes. fv(np.arange(10), 2) returns array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) So it sees that the first argument is an array, iterates it, calls f on each of them, and produce an array of the results. Exactly as * already does on numpy arrays. Adding a signature stop iterations at a certain level: since I said that signature of switch was (c,c),()->(c,c) if I call the vectorized version with a (N/c,N/c,c,c) array, it ill iterates the (c,c) subarrays of it, but won't descend through all (c,) subarrays of them, nor all elements, because the atom here is (c,c) arrays. Result is array([[[[ 100, 200, 300, 400], [ 101, 201, 301, 401], [ 102, 202, 302, 402], [ 103, 203, 303, 403]], [[ 104, 204, 304, 404], [ 105, 205, 305, 405], [ 106, 206, 306, 406], [ 107, 207, 307, 407]], [[ 108, 208, 308, 408], [ 109, 209, 309, 409], [ 110, 210, 310, 410], [ 111, 211, 311, 411]]], [[[ 500, 600, 700, 800], [ 501, 601, 701, 801], [ 502, 602, 702, 802], [ 503, 603, 703, 803]], [[ 504, 604, 704, 804], [ 505, 605, 705, 805], [ 506, 606, 706, 806], [ 507, 607, 707, 807]], [[ 508, 608, 708, 808], [ 509, 609, 709, 809], [ 510, 610, 710, 810], [ 511, 611, 711, 811]]], [[[ 900, 1000, 1100, 1200], [ 901, 1001, 1101, 1201], [ 902, 1002, 1102, 1202], [ 903, 1003, 1103, 1203]], [[ 904, 1004, 1104, 1204], [ 905, 1005, 1105, 1205], [ 906, 1006, 1106, 1206], [ 907, 1007, 1107, 1207]], [[ 908, 1008, 1108, 1208], [ 909, 1009, 1109, 1209], [ 910, 1010, 1110, 1210], [ 911, 1011, 1111, 1211]]]]) So as you can see, all an array of 3x3 4x4 blocks, whose all blocks are the blocks from A, transposed, and subtracted with 1, as switch does For example the second block on the first line of A is View[0,1] array([[105, 106, 107, 108], [205, 206, 207, 208], [305, 306, 307, 308], [405, 406, 407, 408]]) Which is consistent with A (numbers starting with 1,2,3,4 are indeed on the 1st, 2nd, 3rd and 4th lines, that is the 1st row of blocks. And numbers ending with 05,06,07,08, are in the 5th, 6th,7th, 8th column, that is the second column of blocks) And the second block of the 1st line of blocks of the result is result[0,1] array([[104, 204, 304, 404], [105, 205, 305, 405], [106, 206, 306, 406], [107, 207, 307, 407]]) Which is indeed, with a difference of J=1 the same thing, transposed. If you wish to recreate a 12x12 arrays with all the subresults, well, there you can use np.block np.block([[result[i,j] for j in range(N//c)] for i in range(N//c)]) returns array([[ 100, 200, 300, 400, 104, 204, 304, 404, 108, 208, 308, 408], [ 101, 201, 301, 401, 105, 205, 305, 405, 109, 209, 309, 409], [ 102, 202, 302, 402, 106, 206, 306, 406, 110, 210, 310, 410], [ 103, 203, 303, 403, 107, 207, 307, 407, 111, 211, 311, 411], [ 500, 600, 700, 800, 504, 604, 704, 804, 508, 608, 708, 808], [ 501, 601, 701, 801, 505, 605, 705, 805, 509, 609, 709, 809], [ 502, 602, 702, 802, 506, 606, 706, 806, 510, 610, 710, 810], [ 503, 603, 703, 803, 507, 607, 707, 807, 511, 611, 711, 811], [ 900, 1000, 1100, 1200, 904, 1004, 1104, 1204, 908, 1008, 1108, 1208], [ 901, 1001, 1101, 1201, 905, 1005, 1105, 1205, 909, 1009, 1109, 1209], [ 902, 1002, 1102, 1202, 906, 1006, 1106, 1206, 910, 1010, 1110, 1210], [ 903, 1003, 1103, 1203, 907, 1007, 1107, 1207, 911, 1011, 1111, 1211]])
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 anyone know how to execute this please. I have tried np.block to split the array and apply to each individual block but then i had trouble reconstructing the matrix. I also attempted to use the slice indexing and store the values in a new array but the issue is my function outputs complex values so these are all discarded when i try and append the new array,
[ "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)*2] = somefunc(array[i*2:(i+1)*2, j*2:(j+1)*2], 3)\n\n", "A rather technical way to do is, but really efficient, is to use stride_tricks, which provides \"views\" of your array.\nc=4\nN=12 # Note that c is a factor of N\n\n# Just an example array\nA=np.arange(1,N+1).reshape(1,-1)+np.arange(100,100*(N+1),100).reshape(-1,1)\n\n\nstR,stC=A.strides\nView = np.lib.stride_tricks.as_strided(A, (N//c,N//c,c,c), (c*stR, c*stC,stR,stC))\n\n# You can now vectorize your function to work on such data\n\ndef switch(X,J):\n return X.T-J # Just an example\n\nswitchv=np.vectorize(switch, signature='(c,c),()->(c,c)')\n\n# And now switchv can be called on your data\nJ=1\nresult=switchv(View,J)\n\nExplanation.\nA here is\narray([[ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112],\n [ 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212],\n [ 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312],\n [ 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412],\n [ 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512],\n [ 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612],\n [ 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712],\n [ 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812],\n [ 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912],\n [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012],\n [1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112],\n [1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, 1209, 1210, 1211, 1212]])\n\nA.strides gives the number of bytes separating each level of the array. So here, each lines and then each elements in the lines.\nIn my example A.strides is (96,8), because there are 8 bytes between two consecutive number (we don't really need to bother about bytes. we'll just copy those strides), and 96 between 2 lines (since there are 12 elements per lines, that is not surprising, but again, we don't really care. There could have been some gap between the lines, but that is not our problem).\nnp.lib.stride_tricks.as_strided give a new view of A, with a different shape, and a different way to switch from one level to another. It can even lead to some value being repeated. Note that it is just a view. No array is created here. It is a virtual array.\nHere, we say that, instead of a NxN array, we want a (N/c)x(N/c)xcxc array. So a (N/c)x(N/c) arrays of blocks, block being cxc arrays of elements.\nAnd each we provide a stride of (c*stR, c*stC,stR,stC). Reading that from right to left, that means that inside a row of a block, there are the same amount of bytes than between 2 elements of a line of A. So we will have c succesive elements of A. stR means likewise that between two rows of a block, there is the same gap than between 2 rows of A. So we will also have c subsequent (incomplete but subsequent) rows of A. Then c*stC means that two subsequent blocks are separated by c numbers. And c*stR likewise.\nSo result is\narray([[[[ 101, 102, 103, 104],\n [ 201, 202, 203, 204],\n [ 301, 302, 303, 304],\n [ 401, 402, 403, 404]],\n\n [[ 105, 106, 107, 108],\n [ 205, 206, 207, 208],\n [ 305, 306, 307, 308],\n [ 405, 406, 407, 408]],\n\n [[ 109, 110, 111, 112],\n [ 209, 210, 211, 212],\n [ 309, 310, 311, 312],\n [ 409, 410, 411, 412]]],\n\n\n [[[ 501, 502, 503, 504],\n [ 601, 602, 603, 604],\n [ 701, 702, 703, 704],\n [ 801, 802, 803, 804]],\n\n [[ 505, 506, 507, 508],\n [ 605, 606, 607, 608],\n [ 705, 706, 707, 708],\n [ 805, 806, 807, 808]],\n\n [[ 509, 510, 511, 512],\n [ 609, 610, 611, 612],\n [ 709, 710, 711, 712],\n [ 809, 810, 811, 812]]],\n\n\n [[[ 901, 902, 903, 904],\n [1001, 1002, 1003, 1004],\n [1101, 1102, 1103, 1104],\n [1201, 1202, 1203, 1204]],\n\n [[ 905, 906, 907, 908],\n [1005, 1006, 1007, 1008],\n [1105, 1106, 1107, 1108],\n [1205, 1206, 1207, 1208]],\n\n [[ 909, 910, 911, 912],\n [1009, 1010, 1011, 1012],\n [1109, 1110, 1111, 1112],\n [1209, 1210, 1211, 1212]]]])\n\nSame array. But viewed as a 3x3 arrays of 4x4 numbers.\nAgain, no copy, no array were created here. It is just another organisation.\nAnd here come the second technicality: vectorize. vectorize is a way to tell numpy to call a function on each elements of an array.\nFor a basic example\ndef f(a,b):\n return a*b\n\nfv=np.vectorize(f)\n\nfv is a function that can work on array of all shapes.\nfv(np.arange(10), 2) returns\narray([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])\nSo it sees that the first argument is an array, iterates it, calls f on each of them, and produce an array of the results.\nExactly as * already does on numpy arrays.\nAdding a signature stop iterations at a certain level: since I said that signature of switch was (c,c),()->(c,c) if I call the vectorized version with a (N/c,N/c,c,c) array, it ill iterates the (c,c) subarrays of it, but won't descend through all (c,) subarrays of them, nor all elements, because the atom here is (c,c) arrays.\nResult is\narray([[[[ 100, 200, 300, 400],\n [ 101, 201, 301, 401],\n [ 102, 202, 302, 402],\n [ 103, 203, 303, 403]],\n\n [[ 104, 204, 304, 404],\n [ 105, 205, 305, 405],\n [ 106, 206, 306, 406],\n [ 107, 207, 307, 407]],\n\n [[ 108, 208, 308, 408],\n [ 109, 209, 309, 409],\n [ 110, 210, 310, 410],\n [ 111, 211, 311, 411]]],\n\n\n [[[ 500, 600, 700, 800],\n [ 501, 601, 701, 801],\n [ 502, 602, 702, 802],\n [ 503, 603, 703, 803]],\n\n [[ 504, 604, 704, 804],\n [ 505, 605, 705, 805],\n [ 506, 606, 706, 806],\n [ 507, 607, 707, 807]],\n\n [[ 508, 608, 708, 808],\n [ 509, 609, 709, 809],\n [ 510, 610, 710, 810],\n [ 511, 611, 711, 811]]],\n\n\n [[[ 900, 1000, 1100, 1200],\n [ 901, 1001, 1101, 1201],\n [ 902, 1002, 1102, 1202],\n [ 903, 1003, 1103, 1203]],\n\n [[ 904, 1004, 1104, 1204],\n [ 905, 1005, 1105, 1205],\n [ 906, 1006, 1106, 1206],\n [ 907, 1007, 1107, 1207]],\n\n [[ 908, 1008, 1108, 1208],\n [ 909, 1009, 1109, 1209],\n [ 910, 1010, 1110, 1210],\n [ 911, 1011, 1111, 1211]]]])\n\nSo as you can see, all an array of 3x3 4x4 blocks, whose all blocks are the blocks from A, transposed, and subtracted with 1, as switch does\nFor example the second block on the first line of A is\nView[0,1]\narray([[105, 106, 107, 108],\n [205, 206, 207, 208],\n [305, 306, 307, 308],\n [405, 406, 407, 408]])\n\nWhich is consistent with A (numbers starting with 1,2,3,4 are indeed on the 1st, 2nd, 3rd and 4th lines, that is the 1st row of blocks. And numbers ending with 05,06,07,08, are in the 5th, 6th,7th, 8th column, that is the second column of blocks)\nAnd the second block of the 1st line of blocks of the result is\nresult[0,1]\narray([[104, 204, 304, 404],\n [105, 205, 305, 405],\n [106, 206, 306, 406],\n [107, 207, 307, 407]])\n\nWhich is indeed, with a difference of J=1 the same thing, transposed.\nIf you wish to recreate a 12x12 arrays with all the subresults, well, there you can use np.block\nnp.block([[result[i,j] for j in range(N//c)] for i in range(N//c)])\n\nreturns\narray([[ 100, 200, 300, 400, 104, 204, 304, 404, 108, 208, 308, 408],\n [ 101, 201, 301, 401, 105, 205, 305, 405, 109, 209, 309, 409],\n [ 102, 202, 302, 402, 106, 206, 306, 406, 110, 210, 310, 410],\n [ 103, 203, 303, 403, 107, 207, 307, 407, 111, 211, 311, 411],\n [ 500, 600, 700, 800, 504, 604, 704, 804, 508, 608, 708, 808],\n [ 501, 601, 701, 801, 505, 605, 705, 805, 509, 609, 709, 809],\n [ 502, 602, 702, 802, 506, 606, 706, 806, 510, 610, 710, 810],\n [ 503, 603, 703, 803, 507, 607, 707, 807, 511, 611, 711, 811],\n [ 900, 1000, 1100, 1200, 904, 1004, 1104, 1204, 908, 1008, 1108, 1208],\n [ 901, 1001, 1101, 1201, 905, 1005, 1105, 1205, 909, 1009, 1109, 1209],\n [ 902, 1002, 1102, 1202, 906, 1006, 1106, 1206, 910, 1010, 1110, 1210],\n [ 903, 1003, 1103, 1203, 907, 1007, 1107, 1207, 911, 1011, 1111, 1211]])\n\n" ]
[ 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] == ".": lst.remove(lst[i]) else: continue nstring = "".join(lst) return nstring The Error: if lst[i] == ".": IndexError: list index out of range And this is the call of the function: print(remove_dots("maj.d")) So if any one can help me and thank you A: Lenght should <. 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]) else: continue nstring = "".join(lst) return nstring print(remove_dots("maj.d")) Gives # majd Code correction You are over complicating solution. This can achieved easily with. string = "maj.d" string = string.replace(".", '') print(string) Also Gives # majd A: Replacing i <= len(lst) with i < len(lst) makes your code work, but it doesn't do what you might think it does. lst.remove('.') removes all dots from the list, so the whole loop is basically superfluous. You aren't supposed to remove elements from a list while iterating over it because it will change the length and you end up with index errors. You prevented that with the if i < len(lst): condition, but computing the length over and over for every iteration is very inefficient. What you really want to do is something like this: def remove_dots(string): output = "" for char in string: if char != ".": output += char return output This is a basic technique that you will use over and over while learning programming. However, if there is a builtin method that does the job, you should use it, so as others pointed out: just do string.replace(".", ""). A: In the second for-to-next loop for i in range(len(lst))) change it to for i in range((len(lst))-1) Its because your lst list index count is being exceeded due to that try using -1 in the second for next loop. A: You should use replace instead: string = string.replace(".", "") A: Calling lst.remove('.') will remove all elements with value '.', so length of list will change. If you want to remove all dots use str.replace function and replace dot with empty string: string.replace('.', '')
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]) else: continue nstring = "".join(lst) return nstring The Error: if lst[i] == ".": IndexError: list index out of range And this is the call of the function: print(remove_dots("maj.d")) So if any one can help me and thank you
[ "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 nstring = \"\".join(lst)\n\n return nstring\n\nprint(remove_dots(\"maj.d\"))\n\nGives #\nmajd\n\nCode correction\nYou are over complicating solution. This can achieved easily with.\nstring = \"maj.d\"\nstring = string.replace(\".\", '')\nprint(string)\n\nAlso Gives #\nmajd\n\n", "Replacing i <= len(lst) with i < len(lst) makes your code work, but it doesn't do what you might think it does. lst.remove('.') removes all dots from the list, so the whole loop is basically superfluous. You aren't supposed to remove elements from a list while iterating over it because it will change the length and you end up with index errors. You prevented that with the if i < len(lst): condition, but computing the length over and over for every iteration is very inefficient.\nWhat you really want to do is something like this:\ndef remove_dots(string):\n output = \"\"\n \n for char in string:\n if char != \".\":\n output += char\n \n return output\n\nThis is a basic technique that you will use over and over while learning programming. However, if there is a builtin method that does the job, you should use it, so as others pointed out: just do string.replace(\".\", \"\").\n", "In the second for-to-next loop for i in range(len(lst))) change it to for i in range((len(lst))-1) Its because your lst list index count is being exceeded due to that try using -1 in the second for next loop.\n", "You should use replace instead:\nstring = string.replace(\".\", \"\")\n\n", "Calling lst.remove('.') will remove all elements with value '.', so length of list will change. If you want to remove all dots use str.replace function and replace dot with empty string:\nstring.replace('.', '')\n\n" ]
[ 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":"813e2ed1-f28e-451b-9ac6-9eef76ef7b4a","type":"update"},{"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"6a743cb9-bcc4-44bb-8592-c4854e8fadcb","id_v1":"/sensors/32","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"cdb31512-997f-4e26-80d1-50dca6b431a3","rtype":"device"},"type":"motion"}],"id":"240698ea-5938-4e7c-a70c-75bad0fe2a7f","type":"update"},{"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"f4fc5daf-a2aa-4c9f-9812-a65c9922b53e","id_v1":"/sensors/2","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"8daa62b1-af26-44b3-8356-15d21cf6642c","rtype":"device"},"type":"motion"}],"id":"124546d2-cf7e-4b64-a99d-2af2c047aaea","type":"update"} To be split up in a list as follows: {"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":"update"}, {"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"6a743cb9-bcc4-44bb-8592-c4854e8fadcb","id_v1":"/sensors/32","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"cdb31512-997f-4e26-80d1-50dca6b431a3","rtype":"device"},"type":"motion"}],"id":"240698ea-5938-4e7c-a70c-75bad0fe2a7f","type":"update"}, {"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"f4fc5daf-a2aa-4c9f-9812-a65c9922b53e","id_v1":"/sensors/2","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"8daa62b1-af26-44b3-8356-15d21cf6642c","rtype":"device"},"type":"motion"}],"id":"124546d2-cf7e-4b64-a99d-2af2c047aaea","type":"update"} So I need the full strings for further breakdown. I tried many things, Google, stackoverflow etc. I do can search the 'creationtime' but the rest is omitted whatever I try. I guess I need some kind of non-greedy RE? Anyhow - It just won't work for me. Anyone - some help would be highly appreciated. A: Your input data looks like a json array but without the square brackets []. Trying to decode your input data into a json object - import json data = '''{"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":"update"},{"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"6a743cb9-bcc4-44bb-8592-c4854e8fadcb","id_v1":"/sensors/32","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"cdb31512-997f-4e26-80d1-50dca6b431a3","rtype":"device"},"type":"motion"}],"id":"240698ea-5938-4e7c-a70c-75bad0fe2a7f","type":"update"},{"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"f4fc5daf-a2aa-4c9f-9812-a65c9922b53e","id_v1":"/sensors/2","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"8daa62b1-af26-44b3-8356-15d21cf6642c","rtype":"device"},"type":"motion"}],"id":"124546d2-cf7e-4b64-a99d-2af2c047aaea","type":"update"}''' data = '[' + data + ']' decoded = json.loads(data) for item in decoded: print(json.dumps(item)) Output: {"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": "update"} {"creationtime": "2022-11-25T09:12:44Z", "data": [{"id": "6a743cb9-bcc4-44bb-8592-c4854e8fadcb", "id_v1": "/sensors/32", "motion": {"motion": true, "motion_valid": true}, "owner": {"rid": "cdb31512-997f-4e26-80d1-50dca6b431a3", "rtype": "device"}, "type": "motion"}], "id": "240698ea-5938-4e7c-a70c-75bad0fe2a7f", "type": "update"} {"creationtime": "2022-11-25T09:12:44Z", "data": [{"id": "f4fc5daf-a2aa-4c9f-9812-a65c9922b53e", "id_v1": "/sensors/2", "motion": {"motion": true, "motion_valid": true}, "owner": {"rid": "8daa62b1-af26-44b3-8356-15d21cf6642c", "rtype": "device"}, "type": "motion"}], "id": "124546d2-cf7e-4b64-a99d-2af2c047aaea", "type": "update"} Here we are decoding the json string into a json object using json.loads() and then after getting each object in the array, encoding it again in a json string using json.dumps(). You can also access the nested items in the json object. e.g. - for item in decoded: print('creationtime', item['creationtime']) print('motion', item['data'][0]['motion']) Output: creationtime 2022-11-25T09:12:44Z motion {'motion': True, 'motion_valid': True} creationtime 2022-11-25T09:12:44Z motion {'motion': True, 'motion_valid': True} creationtime 2022-11-25T09:12:44Z motion {'motion': True, 'motion_valid': True} A: If you don't have split pattern simply create one.It's all in our hands st = "Your string" st = st.replace('"update"},','"update"},|') lis = st.split("|") print(lis) Gives {"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":"update"}, {"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"6a743cb9-bcc4-44bb-8592-c4854e8fadcb","id_v1":"/sensors/32","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"cdb31512-997f-4e26-80d1-50dca6b431a3","rtype":"device"},"type":"motion"}],"id":"240698ea-5938-4e7c-a70c-75bad0fe2a7f","type":"update"}, {"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"f4fc5daf-a2aa-4c9f-9812-a65c9922b53e","id_v1":"/sensors/2","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"8daa62b1-af26-44b3-8356-15d21cf6642c","rtype":"device"},"type":"motion"}],"id":"124546d2-cf7e-4b64-a99d-2af2c047aaea","type":"update"}
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":"update"},{"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"6a743cb9-bcc4-44bb-8592-c4854e8fadcb","id_v1":"/sensors/32","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"cdb31512-997f-4e26-80d1-50dca6b431a3","rtype":"device"},"type":"motion"}],"id":"240698ea-5938-4e7c-a70c-75bad0fe2a7f","type":"update"},{"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"f4fc5daf-a2aa-4c9f-9812-a65c9922b53e","id_v1":"/sensors/2","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"8daa62b1-af26-44b3-8356-15d21cf6642c","rtype":"device"},"type":"motion"}],"id":"124546d2-cf7e-4b64-a99d-2af2c047aaea","type":"update"} To be split up in a list as follows: {"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":"update"}, {"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"6a743cb9-bcc4-44bb-8592-c4854e8fadcb","id_v1":"/sensors/32","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"cdb31512-997f-4e26-80d1-50dca6b431a3","rtype":"device"},"type":"motion"}],"id":"240698ea-5938-4e7c-a70c-75bad0fe2a7f","type":"update"}, {"creationtime":"2022-11-25T09:12:44Z","data":[{"id":"f4fc5daf-a2aa-4c9f-9812-a65c9922b53e","id_v1":"/sensors/2","motion":{"motion":true,"motion_valid":true},"owner":{"rid":"8daa62b1-af26-44b3-8356-15d21cf6642c","rtype":"device"},"type":"motion"}],"id":"124546d2-cf7e-4b64-a99d-2af2c047aaea","type":"update"} So I need the full strings for further breakdown. I tried many things, Google, stackoverflow etc. I do can search the 'creationtime' but the rest is omitted whatever I try. I guess I need some kind of non-greedy RE? Anyhow - It just won't work for me. Anyone - some help would be highly appreciated.
[ "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,\"motion_valid\":true},\"owner\":{\"rid\":\"4b16b918-485a-44de-82aa-4ff467f6591a\",\"rtype\":\"device\"},\"type\":\"motion\"}],\"id\":\"813e2ed1-f28e-451b-9ac6-9eef76ef7b4a\",\"type\":\"update\"},{\"creationtime\":\"2022-11-25T09:12:44Z\",\"data\":[{\"id\":\"6a743cb9-bcc4-44bb-8592-c4854e8fadcb\",\"id_v1\":\"/sensors/32\",\"motion\":{\"motion\":true,\"motion_valid\":true},\"owner\":{\"rid\":\"cdb31512-997f-4e26-80d1-50dca6b431a3\",\"rtype\":\"device\"},\"type\":\"motion\"}],\"id\":\"240698ea-5938-4e7c-a70c-75bad0fe2a7f\",\"type\":\"update\"},{\"creationtime\":\"2022-11-25T09:12:44Z\",\"data\":[{\"id\":\"f4fc5daf-a2aa-4c9f-9812-a65c9922b53e\",\"id_v1\":\"/sensors/2\",\"motion\":{\"motion\":true,\"motion_valid\":true},\"owner\":{\"rid\":\"8daa62b1-af26-44b3-8356-15d21cf6642c\",\"rtype\":\"device\"},\"type\":\"motion\"}],\"id\":\"124546d2-cf7e-4b64-a99d-2af2c047aaea\",\"type\":\"update\"}'''\ndata = '[' + data + ']'\n\ndecoded = json.loads(data)\nfor item in decoded:\n print(json.dumps(item))\n\n\nOutput:\n{\"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\": \"update\"}\n{\"creationtime\": \"2022-11-25T09:12:44Z\", \"data\": [{\"id\": \"6a743cb9-bcc4-44bb-8592-c4854e8fadcb\", \"id_v1\": \"/sensors/32\", \"motion\": {\"motion\": true, \"motion_valid\": true}, \"owner\": {\"rid\": \"cdb31512-997f-4e26-80d1-50dca6b431a3\", \"rtype\": \"device\"}, \"type\": \"motion\"}], \"id\": \"240698ea-5938-4e7c-a70c-75bad0fe2a7f\", \"type\": \"update\"}\n{\"creationtime\": \"2022-11-25T09:12:44Z\", \"data\": [{\"id\": \"f4fc5daf-a2aa-4c9f-9812-a65c9922b53e\", \"id_v1\": \"/sensors/2\", \"motion\": {\"motion\": true, \"motion_valid\": true}, \"owner\": {\"rid\": \"8daa62b1-af26-44b3-8356-15d21cf6642c\", \"rtype\": \"device\"}, \"type\": \"motion\"}], \"id\": \"124546d2-cf7e-4b64-a99d-2af2c047aaea\", \"type\": \"update\"}\n\nHere we are decoding the json string into a json object using json.loads() and then after getting each object in the array, encoding it again in a json string using json.dumps().\n\nYou can also access the nested items in the json object. e.g. -\nfor item in decoded:\n print('creationtime', item['creationtime'])\n print('motion', item['data'][0]['motion'])\n\nOutput:\ncreationtime 2022-11-25T09:12:44Z\nmotion {'motion': True, 'motion_valid': True}\ncreationtime 2022-11-25T09:12:44Z\nmotion {'motion': True, 'motion_valid': True}\ncreationtime 2022-11-25T09:12:44Z\nmotion {'motion': True, 'motion_valid': True}\n\n", "If you don't have split pattern simply create one.It's all in our hands\nst = \"Your string\"\n\nst = st.replace('\"update\"},','\"update\"},|')\nlis = st.split(\"|\")\nprint(lis)\n\nGives\n{\"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\":\"update\"},\n{\"creationtime\":\"2022-11-25T09:12:44Z\",\"data\":[{\"id\":\"6a743cb9-bcc4-44bb-8592-c4854e8fadcb\",\"id_v1\":\"/sensors/32\",\"motion\":{\"motion\":true,\"motion_valid\":true},\"owner\":{\"rid\":\"cdb31512-997f-4e26-80d1-50dca6b431a3\",\"rtype\":\"device\"},\"type\":\"motion\"}],\"id\":\"240698ea-5938-4e7c-a70c-75bad0fe2a7f\",\"type\":\"update\"},\n{\"creationtime\":\"2022-11-25T09:12:44Z\",\"data\":[{\"id\":\"f4fc5daf-a2aa-4c9f-9812-a65c9922b53e\",\"id_v1\":\"/sensors/2\",\"motion\":{\"motion\":true,\"motion_valid\":true},\"owner\":{\"rid\":\"8daa62b1-af26-44b3-8356-15d21cf6642c\",\"rtype\":\"device\"},\"type\":\"motion\"}],\"id\":\"124546d2-cf7e-4b64-a99d-2af2c047aaea\",\"type\":\"update\"}\n\n" ]
[ 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 = ThreadPoolExecutor(max_workers=2) def func(x): print(f"In func {x}") sleep(1) return True foo = executor.map(func, range(0, 10)) for f in foo: print(f"blah {f}") if f: break print("Shutting down") executor.shutdown(wait=False) print("Shut down") this outputs the following - showing remaining futures being run to completion. While that surprised me at first, I believe it's consistent with the docs (in the absence of cancel_futures being set to True), as per https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.shutdown "Regardless of the value of wait, the entire Python program will not exit until all pending futures are done executing." In func 0 In func 1 In func 2 In func 3 blah True Shutting down Shut down In func 4 In func 5 In func 6 In func 7 In func 8 In func 9 So that's fine. But here's the odd thing - if I refactor to call that within a function, it behaves differently. See minor tweak: from concurrent.futures import ThreadPoolExecutor from time import sleep def run_test(): executor = ThreadPoolExecutor(max_workers=2) def func(x): print(f"In func {x}") sleep(1) return True foo = executor.map(func, range(0, 10)) for f in foo: print(f"blah {f}") if f: break print("Shutting down") executor.shutdown(wait=False) print("Shut down") run_test() this outputs the following, suggesting the future are cancelled in this case In func 0 In func 1 In func 2 blah True Shutting down In func 3 Shut down So I guess something is happening as the executor falls out of scope at the end of run_test()? But this seems to contradict the docs (which don't mention this), and surely the executor similarly falls out of scope at the end of the first script?? Seen at both Python 3.8 and 3.9. I expected the same output in the two cases, but they mis-matched A: This surprised me too. This code also reproduces your behaviour from concurrent.futures import ThreadPoolExecutor from time import sleep def run_test(): executor = ThreadPoolExecutor(max_workers=2) def func(x): print(f"In func {x}") sleep(1) foo = executor.map(func, range(0, 10)) # a x = next(foo) # b print("Shutting down") executor.shutdown(wait=False) print("Shut down") run_test() If you run it as-is, it will run for first couple of integers between 0 and 10 and then exit. If you comment out the line between #a and #b then it runs all 10. The reason, as far as I can tell, is that if you loop over the generator object (foo) at all (or call next() on it) then the code ends up in this iterator function in the CPython concurrent.futures._base source code. When the run_test() function exits and foo goes out of scope, then you end up in this finally block, which cancels all pending futures. In your example without a function, I believe your guess is correct that it is related to the order in which objects go out of scope. You can see this by commenting / un-commenting the line between # a and # b below from concurrent.futures import ThreadPoolExecutor from time import sleep executor = ThreadPoolExecutor(max_workers=2) def func(x): print(f"In func {x}") sleep(1) return True foo = executor.map(func, range(0, 10)) next(foo) # a # del foo # b print("Shutting down") executor.shutdown(wait=False) print("Shut down")
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) return True foo = executor.map(func, range(0, 10)) for f in foo: print(f"blah {f}") if f: break print("Shutting down") executor.shutdown(wait=False) print("Shut down") this outputs the following - showing remaining futures being run to completion. While that surprised me at first, I believe it's consistent with the docs (in the absence of cancel_futures being set to True), as per https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.shutdown "Regardless of the value of wait, the entire Python program will not exit until all pending futures are done executing." In func 0 In func 1 In func 2 In func 3 blah True Shutting down Shut down In func 4 In func 5 In func 6 In func 7 In func 8 In func 9 So that's fine. But here's the odd thing - if I refactor to call that within a function, it behaves differently. See minor tweak: from concurrent.futures import ThreadPoolExecutor from time import sleep def run_test(): executor = ThreadPoolExecutor(max_workers=2) def func(x): print(f"In func {x}") sleep(1) return True foo = executor.map(func, range(0, 10)) for f in foo: print(f"blah {f}") if f: break print("Shutting down") executor.shutdown(wait=False) print("Shut down") run_test() this outputs the following, suggesting the future are cancelled in this case In func 0 In func 1 In func 2 blah True Shutting down In func 3 Shut down So I guess something is happening as the executor falls out of scope at the end of run_test()? But this seems to contradict the docs (which don't mention this), and surely the executor similarly falls out of scope at the end of the first script?? Seen at both Python 3.8 and 3.9. I expected the same output in the two cases, but they mis-matched
[ "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, range(0, 10))\n\n # a\n x = next(foo)\n # b\n\n print(\"Shutting down\")\n executor.shutdown(wait=False)\n print(\"Shut down\")\n\nrun_test()\n\n\nIf you run it as-is, it will run for first couple of integers between 0 and 10 and then exit. If you comment out the line between #a and #b then it runs all 10.\nThe reason, as far as I can tell, is that if you loop over the generator object (foo) at all (or call next() on it) then the code ends up in this iterator function in the CPython concurrent.futures._base source code.\nWhen the run_test() function exits and foo goes out of scope, then you end up in this finally block, which cancels all pending futures.\nIn your example without a function, I believe your guess is correct that it is related to the order in which objects go out of scope. You can see this by commenting / un-commenting the line between # a and # b below\nfrom concurrent.futures import ThreadPoolExecutor\nfrom time import sleep\n\nexecutor = ThreadPoolExecutor(max_workers=2)\n\ndef func(x):\n print(f\"In func {x}\")\n sleep(1)\n return True\n\nfoo = executor.map(func, range(0, 10))\n\nnext(foo)\n\n# a\n# del foo\n# b\n\nprint(\"Shutting down\")\nexecutor.shutdown(wait=False)\nprint(\"Shut down\")\n\n" ]
[ 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(): for k1, v1 in v.items(): for k2, v2 in v1.items(): d1[(k, k2)].update({k1: v2}) df = pd.DataFrame(d1) df.insert(loc=0, column=('', 'Mode'), value=[0,5]) df.insert(loc=1, column=('', 'Symbol'), value=[2,1]) df.columns = df.columns.rename("Skateboard", level=0) df.columns = df.columns.rename("Q3", level=1) I want to sort the column-Mode Descending and column-Symbol Ascending. I have tried the following: df.sort_values(by = ['Mode', 'Symbol'], ascending = [False, True]) A: Your indexing is incorrect, use: df.sort_values(by=[('', 'Mode'), ('', 'Symbol')], ascending=[False, True]) Output: Skateboard US UK Q3 Mode Symbol new repeat new repeat Sales 5 1 67068 105677 4568 10738 Traffic 0 2 1415 670 230 156
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(): d1[(k, k2)].update({k1: v2}) df = pd.DataFrame(d1) df.insert(loc=0, column=('', 'Mode'), value=[0,5]) df.insert(loc=1, column=('', 'Symbol'), value=[2,1]) df.columns = df.columns.rename("Skateboard", level=0) df.columns = df.columns.rename("Q3", level=1) I want to sort the column-Mode Descending and column-Symbol Ascending. I have tried the following: df.sort_values(by = ['Mode', 'Symbol'], ascending = [False, True])
[ "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 230 156\n\n" ]
[ 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\CPLEX_Studio221\python\setup.py install There are two examples in IBM "Docplex.cp" and "Docplex.mp". I run these exampleas using the vscode and jupyter. All exampleas of "Docplex.cp" run correctly but when I run examples of "Docplex.mp" I see Cplex runtime error. This is one simple linear model that I have tried: # Define the Model from docplex.mp.model import Model MWMS_model=Model(name="Linear Program") # Variables x=MWMS_model.continuous_var(name='x', lb=0) y=MWMS_model.continuous_var(name='y', lb=0) # Constraints c1=MWMS_model.add_constraint(x+y>=8,ctname="c1") c2=MWMS_model.add_constraint(2*x+y>=10,ctname="c2") c3=MWMS_model.add_constraint(x+4*y>=11,ctname="c3") # Objective Function obj=5*x+4*y MWMS_model.set_objective('min', obj) MWMS_model.print_information() # Solvig MWMS_model.solve() # Output MWMS_model.print_solution() This is the error: "docplex.mp.utils.DOcplexException: Cannot solve model: no CPLEX runtime found." A: what you followed (setup.py) is in documentation CPLEX > CPLEX Optimizers > Getting Started with CPLEX > Tutorials > Python tutorial and this sets the matrix python api but you want to use the other python interface (docplex) You should follow http://ibmdecisionoptimization.github.io/docplex-doc/mp/getting_started_python.html#installing-the-cplex-modeling-library-with-pip A: Your packages may be installed incorrectly. In your Python library, you should have 'cplex' package and 'docplex' package (please note that there is a 'docplex' package which is the correct one inside 'docplex' package).
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 exampleas using the vscode and jupyter. All exampleas of "Docplex.cp" run correctly but when I run examples of "Docplex.mp" I see Cplex runtime error. This is one simple linear model that I have tried: # Define the Model from docplex.mp.model import Model MWMS_model=Model(name="Linear Program") # Variables x=MWMS_model.continuous_var(name='x', lb=0) y=MWMS_model.continuous_var(name='y', lb=0) # Constraints c1=MWMS_model.add_constraint(x+y>=8,ctname="c1") c2=MWMS_model.add_constraint(2*x+y>=10,ctname="c2") c3=MWMS_model.add_constraint(x+4*y>=11,ctname="c3") # Objective Function obj=5*x+4*y MWMS_model.set_objective('min', obj) MWMS_model.print_information() # Solvig MWMS_model.solve() # Output MWMS_model.print_solution() This is the error: "docplex.mp.utils.DOcplexException: Cannot solve model: no CPLEX runtime found."
[ "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_started_python.html#installing-the-cplex-modeling-library-with-pip\n", "Your packages may be installed incorrectly. In your Python library, you should have 'cplex' package and 'docplex' package (please note that there is a 'docplex' package which is the correct one inside 'docplex' package).\n" ]
[ 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 list(dir_list_full): cap = cv2.VideoCapture(i) cap.set(1,frame_no) ret, frame = cap.read() for x in dir_list: isWritten = cv2.imwrite('C:/User/Frames/frame_'+ x +'.png', frame) if isWritten: print('Frames are successfully saved as individual files.') However, the loop saves the exact frame it currently iterates to every image file it created. Ultimately, every file has the same frame (from the last video) as the loop finishes. Can someone help me what I do wrong here? Thanks! =) A: Probably you want to do something like that: frame_no = 2 dir_list_source = ["C:/User/video/a.mp4", "c:/User/video/b.mp4"] dir_list_target = ["a", "b"] for i in range(len(dir_list_source)): cap = cv2.VideoCapture(dir_list_source[i]) if not cap.isOpened(): print(f"Cannot open {dir_list_source[i]}") exit() cap.set(1, frame_no) ret, frame = cap.read() if not ret: print(f"Error reading frame from {dir_list_source[i]}") exit() cv2.imwrite(f"C:/User/Frames/frame_{dir_list_target[i]}.png", frame) cap.release() print("Frames successfully saved as individual files.")
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.VideoCapture(i) cap.set(1,frame_no) ret, frame = cap.read() for x in dir_list: isWritten = cv2.imwrite('C:/User/Frames/frame_'+ x +'.png', frame) if isWritten: print('Frames are successfully saved as individual files.') However, the loop saves the exact frame it currently iterates to every image file it created. Ultimately, every file has the same frame (from the last video) as the loop finishes. Can someone help me what I do wrong here? Thanks! =)
[ "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 {dir_list_source[i]}\")\n exit()\n\n cap.set(1, frame_no)\n ret, frame = cap.read()\n\n if not ret:\n print(f\"Error reading frame from {dir_list_source[i]}\")\n exit()\n\n cv2.imwrite(f\"C:/User/Frames/frame_{dir_list_target[i]}.png\", frame)\n cap.release()\n\nprint(\"Frames successfully saved as individual files.\")\n\n" ]
[ 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. A: Python extension started to support Quick Fix. First, function adding imports is supported. Python in Visual Studio Code – November 2019 Release | Python However Python extension ver.2020.1.58038 and 2020.1.57204 have bug that it doesn't display Quick Fix. Solution Plan A: Use old version of Python extension 1. If you haven't install Python extension, install it once. 2. Install ver.2019.11.50794 or 2019.11.49689 by following steps in below answer. vs code - rollback extension/install specific extension version - Stack Overflow Plan B: Use Insiders version of Python extension 1. Install Visual Studio Code - Insiders. Download Visual Studio Code Insiders 2. Install Python extension once, then click [Reload Required] button. 3. Open Settings editor. (Ctrl + ,) 4. Search by keyword: "Insiders Channel", then change pulldown to "daily" or "weekly", and save Settings. Then, Visual Studio Code start to download Insider version of Python extension. (Below status bar displays progress) 5. When popup message "Please reload Visual Studio Code to use the insiders build of the Python extension." is displayed, click [Reload] button. Requirement Don't forget that there are two requirement to use Quick Fix feature. Use Microsoft Python Language Server Enable linting Use Microsoft Python Language Server Set python.jediEnabled to false in your settings.json file. Enable linting 1. Open Command Palette. (View > Command Palette... or F1 or Ctrl + Shift + P) 2. Run "Python: Enable Linting" command. 3. Select "On" in the drop-down menu. cf. Editing Python Code in Visual Studio Code A: Solution for 2021. I got the same issue with Python for VSCode 1.54.2. I solved it by installing the Pylance extension and making it the default Python language server (a message should pop up just after the installation asking if you want to make it the default Python language server). Now everything works flawlessly. A: I also recently tried the Sourcery VSCode Python Refactoring Extension to provide more refactorings that helps eliminate the errors in some cases implementing the line in question more clearly. A: Having spent ages reading many articles on this, I've slightly improved my position. The right mouse button never comes up with anything, but I can press Ctrl + a full stop (period if you're in the US) to bring up suggested imports - sometimes. I have Pylance installed in VS Code (so do you probably), which should be the default linter, but just in case I forced this in VS Code Settings: // Defines type of the language server (should default to Pylance if installed anyway) "python.languageServer": "Pylance", The comments are mine. But then I read the notes on PyLance, and it seems you have to enable this setting by adding these lines: // Offer auto-import completions. "python.analysis.autoImportCompletions": true, Having said all of this, the feature has now stopped working again! I've left this in just in case a) it gives anyone any ideas or b) I get it working again and can come back to edit this answer. A: For import quick fixes, there is a solution. Use the following VsCode Extension which work just as expected. https://marketplace.visualstudio.com/items?itemName=Bar.python-import-helper
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 doesn't display Quick Fix.\nSolution\nPlan A: Use old version of Python extension\n\n1.\n\nIf you haven't install Python extension, install it once.\n\n2.\n\nInstall ver.2019.11.50794 or 2019.11.49689 by following steps in below answer.\nvs code - rollback extension/install specific extension version - Stack Overflow\nPlan B: Use Insiders version of Python extension\n\n1.\n\nInstall Visual Studio Code - Insiders.\nDownload Visual Studio Code Insiders\n\n2.\n\nInstall Python extension once, then click [Reload Required] button.\n\n3.\n\nOpen Settings editor. (Ctrl + ,)\n\n4.\n\nSearch by keyword: \"Insiders Channel\", then change pulldown to \"daily\" or \"weekly\",\nand save Settings.\nThen, Visual Studio Code start to download Insider version of Python extension.\n(Below status bar displays progress)\n\n5.\n\nWhen popup message\n\"Please reload Visual Studio Code to use the insiders build of the Python extension.\"\nis displayed, click [Reload] button.\nRequirement\nDon't forget that there are two requirement to use Quick Fix feature.\n\nUse Microsoft Python Language Server\nEnable linting\n\nUse Microsoft Python Language Server\nSet python.jediEnabled to false in your settings.json file.\nEnable linting\n\n1.\n\nOpen Command Palette. (View > Command Palette... or F1 or Ctrl + Shift + P)\n\n2.\n\nRun \"Python: Enable Linting\" command.\n\n3.\n\nSelect \"On\" in the drop-down menu. \ncf. Editing Python Code in Visual Studio Code\n", "Solution for 2021.\nI got the same issue with Python for VSCode 1.54.2.\nI solved it by installing the Pylance extension and making it the default Python language server (a message should pop up just after the installation asking if you want to make it the default Python language server). Now everything works flawlessly.\n", "I also recently tried the Sourcery VSCode Python Refactoring Extension to provide more refactorings that helps eliminate the errors in some cases implementing the line in question more clearly.\n", "Having spent ages reading many articles on this, I've slightly improved my position. The right mouse button never comes up with anything, but I can press Ctrl + a full stop (period if you're in the US) to bring up suggested imports - sometimes.\nI have Pylance installed in VS Code (so do you probably), which should be the default linter, but just in case I forced this in VS Code Settings:\n// Defines type of the language server (should default to Pylance if installed anyway)\n \"python.languageServer\": \"Pylance\",\n \n\nThe comments are mine. But then I read the notes on PyLance, and it seems you have to enable this setting by adding these lines:\n // Offer auto-import completions.\n \"python.analysis.autoImportCompletions\": true,\n\nHaving said all of this, the feature has now stopped working again! I've left this in just in case a) it gives anyone any ideas or b) I get it working again and can come back to edit this answer.\n", "For import quick fixes, there is a solution.\nUse the following VsCode Extension which work just as expected.\nhttps://marketplace.visualstudio.com/items?itemName=Bar.python-import-helper\n" ]
[ 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 path to this module. But it tells NameError: name 'Graph2D' is not defined. Project path: ~/MyData/Python/Pygame/RoadSearchAlgorithm/src Module path: ~/MyData/Python/Pygame/MY_MODULES/Graph Code: # ~/MyData/Python/Pygame/RoadSearchAlgorithm/src/Graph_package/InteractiveGraph2D.py ... sys.path.append('./') sys.path.append('/home/rayxxx/MyData/Python/MY_MODULES') try: from Graph.Graph2D import Graph2D, ... ... except Exception as e: assert (e) class InteractiveGraph2D(Graph2D): ... What's the problem? I tried to look at paths, list of imported modules. The Graph module presented in it. A: 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 A: this is a common error, when you run a python script it looks at the dir where you are running the script so four your case when you run from Graph.Graph2D import Graph2D, ... From ~/MyData/Python/Pygame/RoadSearchAlgorithm/src Python at most can import from src. Some solution, make your module installable by adding a setup in MY_MODULE, then doing a pip install . in that folder, here is an example How to setup. And maybe you need to add an init.py to MY_MODULES/, check hereDo I need init.py Another solution is to add MY_MODULES/ to python path, avoid this if possible but here is an example Add to python path. A: You should make the Graph module installable by adding a setup.py file to it's directory (doc). Then you could install it with pip and import it like any library.
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 'Graph2D' is not defined. Project path: ~/MyData/Python/Pygame/RoadSearchAlgorithm/src Module path: ~/MyData/Python/Pygame/MY_MODULES/Graph Code: # ~/MyData/Python/Pygame/RoadSearchAlgorithm/src/Graph_package/InteractiveGraph2D.py ... sys.path.append('./') sys.path.append('/home/rayxxx/MyData/Python/MY_MODULES') try: from Graph.Graph2D import Graph2D, ... ... except Exception as e: assert (e) class InteractiveGraph2D(Graph2D): ... What's the problem? I tried to look at paths, list of imported modules. The Graph module presented in it.
[ "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 four your case when you run\nfrom Graph.Graph2D import Graph2D, ...\n\nFrom\n~/MyData/Python/Pygame/RoadSearchAlgorithm/src\n\nPython at most can import from src.\nSome solution, make your module installable by adding a setup in MY_MODULE, then doing a pip install . in that folder, here is an example How to setup.\nAnd maybe you need to add an init.py to MY_MODULES/, check hereDo I need init.py\nAnother solution is to add MY_MODULES/ to python path, avoid this if possible but here is an example Add to python path.\n", "You should make the Graph module installable by adding a setup.py file to it's directory (doc). Then you could install it with pip and import it like any library.\n" ]
[ 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): thread_amount = 50 threads = [] s = time.time() for i in range(thread_amount): threads.append(threading.Thread(target = req)) for thread in threads: thread.start() for thread in threads: thread.join() e = time.time() total_time = e - s print(f"total time: {total_time} s") time.sleep(1) This is caused by openssl 3.0.2 and any other openssl 3.x.x version. That's why I tried to install openssl 1.1.1s, which worked fine, but afterwards you have to re-compile python to make it use openssl 1.1.1s. Unfortunately this breaks everything for me. I need a solution which works with openssl 3. A: try disabling the verification of the SSL certificate (this should increase loading times) (also this works with the latest version of OpenSSL def req(): r = requests.get('https://www.google.com/', verify=False)
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.time() for i in range(thread_amount): threads.append(threading.Thread(target = req)) for thread in threads: thread.start() for thread in threads: thread.join() e = time.time() total_time = e - s print(f"total time: {total_time} s") time.sleep(1) This is caused by openssl 3.0.2 and any other openssl 3.x.x version. That's why I tried to install openssl 1.1.1s, which worked fine, but afterwards you have to re-compile python to make it use openssl 1.1.1s. Unfortunately this breaks everything for me. I need a solution which works with openssl 3.
[ "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"CrSDK_v1.05.00_20211207a_Linux64ARMv8/external/crsdk/libCr_Core.so" if platform.startswith('win32'): shared_lib_path = r"CrSDK_v1.05.00_20211207a_Win64/external/crsdk/Cr_Core.dll" try: crsdk_lib = CDLL(shared_lib_path) print("Successfully loaded", crsdk_lib) except Exception as e: print(e) cInit = crsdk_lib.Init cInit.argtype = c_uint32 cInit.restype = c_bool cRelease = crsdk_lib.Release cRelease.restype = c_bool cEnumCameraObjects = crsdk_lib.EnumCameraObjects #TODO cCreateCameraObjectInfo.argtypes = [] #TODO cCreateCameraObjectInfo.restype = cCreateCameraObjectInfo = crsdk_lib.CreateCameraObjectInfo cCreateCameraObjectInfo.argtypes = [c_char, c_char, c_int16, c_uint32, c_uint32, c_uint8, c_char, c_char, c_char] #TODO cCreateCameraObjectInfo.restype = cEditSDKInfo = crsdk_lib.EditSDKInfo cEditSDKInfo.argtype = c_uint16 #TODO cEditSDKInfo.restype = cConnect = crsdk_lib.Connect #TODO cConnect.argtypes = [] #TODO cConnect.restypes = [] cDisconnect = crsdk_lib.Disconnect #TODO cDisconnect.argtype = #TODO cDisconnect.restype = cReleaseDevice = crsdk_lib.ReleaseDevice #TODO cReleaseDevice.restype = #TODO cReleaseDevice.argtype = cGetDeviceProperties = crsdk_lib.GetDeviceProperties cGetSelectDeviceProperties = crsdk_lib.GetSelectDeviceProperties cReleaseDeviceProperties = crsdk_lib.ReleaseDeviceProperties cSetDeviceProperty = crsdk_lib.SetDeviceProperty cSendCommand = crsdk_lib.SendCommand cGetLiveViewImage = crsdk_lib.GetLiveViewImage cGetLiveViewImageInfo = crsdk_lib.GetLiveViewImageInfo cGetLiveViewProperties = crsdk_lib.GetLiveViewProperties cGetSelectLiveViewProperties = crsdk_lib.GetSelectLiveViewProperties cReleaseLiveViewProperties = crsdk_lib.ReleaseLiveViewProperties cGetDeviceSetting = crsdk_lib.GetDeviceSetting cSetDeviceSetting = crsdk_lib.SetDeviceSetting cSetSaveInfo = crsdk_lib.SetSaveInfo cGetSDKVersion = crsdk_lib.GetSDKVersion cGetSDKSerial = crsdk_lib.GetSDKSerial cGetDateFolderList = crsdk_lib.GetDateFolderList cGetContentsHandleList = crsdk_lib.GetContentsHandleList cGetContentsDetailInfo = crsdk_lib.GetContentsDetailInfo cReleaseDateFolderList = crsdk_lib.ReleaseDateFolderList cReleaseContentsHandleList = crsdk_lib.ReleaseContentsHandleList cPullContentsFile = crsdk_lib.PullContentsFile cGetContentsThumbnailImage = crsdk_lib.GetContentsThumbnailImage def int_to_bytes(x: int) -> bytes: return x.to_bytes((x.bit_length() + 7) // 8, 'big') def init() -> bytes: return cInit(0) def release() -> bytes: return cRelease() def editsdkinfo(c: int): #TODO implement return editsdkinfo.__name__ + " is Not Implemented" def getsdkversion() -> bytes: return int_to_bytes(cGetSDKVersion()) def string_of_getsdkversion() -> str: temp = getsdkversion() temp = [temp[i:i + 1] for i in range(0, len(temp), 1)] temp = [int.from_bytes(temp[i], byteorder='big') for i in range(0, len(temp), 1)] tmp = str(temp[0]) + "." + str(f"{temp[1]:02}") + "." + str(f"{temp[2]:02}") return tmp def getsdkserial() -> bytes: cGetSDKSerial.restype = c_uint32 return int_to_bytes(cGetSDKSerial()) def string_of_getsdkserial() -> str: temp = getsdkserial() temp = [temp[i:i + 1] for i in range(0, len(temp), 1)] temp = [int.from_bytes(temp[i], byteorder='big') for i in range(0, len(temp), 1)] tmp = "" for i in range(0, 2): try: tmp = str(f"{temp[i]:02}") except Exception: return tmp return tmp Functions that i think work init(), release(), getsdkversion(), getsdkserial(). The first problem i encountered was with the function enumCameraObjects. In the header file you can see that it expects an object from the class ICrEnumCameraObjectInfo and an integer. Unfortunately my knowledge of python is not large and i dont know anything about C/C++. On various websites they talk about pointers and byrefs but it wont work for me. extern "C" SCRSDK_API // This function enumerates the cameras that are connected to the pc via the protocol and the physical connection that the library supports. CrError EnumCameraObjects(ICrEnumCameraObjectInfo** ppEnumCameraObjectInfo, CrInt8u timeInSec = 3); ^This is the excerpt from one of the header files for the sdk. class ICrEnumCameraObjectInfo { public: virtual CrInt32u GetCount() const = 0; virtual const ICrCameraObjectInfo* GetCameraObjectInfo(CrInt32u index) const = 0; virtual void Release() = 0; }; ^This is an excerpt of the header file for the class ICrEnumCameraObjectInfo. class ICrCameraObjectInfo { public: virtual void Release() = 0; // device name virtual CrChar* GetName() const = 0; virtual CrInt32u GetNameSize() const = 0; // model name virtual CrChar *GetModel() const = 0; virtual CrInt32u GetModelSize() const = 0; // pid (usb) virtual CrInt16 GetUsbPid() const = 0; // device id virtual CrInt8u* GetId() const = 0; virtual CrInt32u GetIdSize() const = 0; virtual CrInt32u GetIdType() const = 0; // current device connection status virtual CrInt32u GetConnectionStatus() const = 0; virtual CrChar *GetConnectionTypeName() const = 0; virtual CrChar *GetAdaptorName() const = 0; // device UUID virtual CrChar *GetGuid() const = 0; // device pairing necessity virtual CrChar *GetPairingNecessity() const = 0; virtual CrInt16u GetAuthenticationState() const = 0; }; ^And for reference the class ICrCameraObjectInfo def enumcameraobjects(): #TODO implement class CAMERAOBJECTINFO(ctypes.Structure): __fields__ = [ ("release", c_void_p), ("getName", c_char), ("getNameSize", c_uint32), ("getModel", c_char), ("getModelSize", c_uint32), ("getUSBPid", c_int16), ("getID", c_uint8), ("getIDSize", c_uint32), ("getIDType", c_uint32), ("getConnectionStatus", c_uint32), ("getConnectionTypeName", c_char), ("getAdaptorName", c_char), ("getGUID", c_char), ("getPairingNecessity", c_char), ("getAuthenticationState", c_uint16) ] class ENUMCAMERAOBJECTINFO(ctypes.Structure): __fields__ = [ ("getCount", c_uint32), ("getCameraObjectInfo", POINTER(CAMERAOBJECTINFO)), ("release", c_void_p) ] pass enumCameraObjectInfo = ENUMCAMERAOBJECTINFO() return cEnumCameraObjects(byref(enumCameraObjectInfo), 3) return enumCameraObjectInfo #return enumcameraobjects.__name__ + " is Not Implemented" ^Right now this is what i have and its probably as wrong as it gets cause I literally tried a lot recommended on the internet. Unfortunately there is also no program on the internet which uses this library. All the Sony wrapper program use the old Camera Remote SDK which is discontinued. I look forward to your ideas to solve this problem. Since my last update I managed to edit my code to make a bit more sense. class CAMERAOBJECTINFO(ctypes.Structure): _fields_ = [] class ENUMCAMERAOBJECTINFO(ctypes.Structure): _fields_ = [ ("GetCount", c_uint32) ] class CRERROR(ctypes.Structure): _fields_ = [] ^The three classes that i have to work with in this function. def enumcameraobjects(): #TODO implement crsdk_lib.EnumCameraObjects.argtypes = [POINTER(POINTER(ENUMCAMERAOBJECTINFO)), c_uint8] crsdk_lib.EnumCameraObjects.restype = c_uint32 enumCameraObjectInfo = ENUMCAMERAOBJECTINFO() temp = crsdk_lib.EnumCameraObjects(POINTER(POINTER(ENUMCAMERAOBJECTINFO))(enumCameraObjectInfo), 3) print(int_to_bytes(temp)) return enumCameraObjectInfo.GetCount #return enumcameraobjects.__name__ + " is Not Implemented" The temp variable returns the correct CrError integer. But even when a camera is connected the GetCount still wont work. (I have tried both GetCount() and GetCount) I need to somehow call the function GetCount() inside the class ICrEnumCameraObjectInfo to get the number of connected cameras. I hope my update helped to give a bit more information and an update to my current research. A: 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 the header file. I would say that it may be possible to build bridge libraries (basically one for .cpp in the app folder) and then link all those libraries together with ctypes. At the end I have decided to modify the remote_cli.cpp file and then call it using subprocess in Python, was the easiest thing to do
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 platform.startswith('win32'): shared_lib_path = r"CrSDK_v1.05.00_20211207a_Win64/external/crsdk/Cr_Core.dll" try: crsdk_lib = CDLL(shared_lib_path) print("Successfully loaded", crsdk_lib) except Exception as e: print(e) cInit = crsdk_lib.Init cInit.argtype = c_uint32 cInit.restype = c_bool cRelease = crsdk_lib.Release cRelease.restype = c_bool cEnumCameraObjects = crsdk_lib.EnumCameraObjects #TODO cCreateCameraObjectInfo.argtypes = [] #TODO cCreateCameraObjectInfo.restype = cCreateCameraObjectInfo = crsdk_lib.CreateCameraObjectInfo cCreateCameraObjectInfo.argtypes = [c_char, c_char, c_int16, c_uint32, c_uint32, c_uint8, c_char, c_char, c_char] #TODO cCreateCameraObjectInfo.restype = cEditSDKInfo = crsdk_lib.EditSDKInfo cEditSDKInfo.argtype = c_uint16 #TODO cEditSDKInfo.restype = cConnect = crsdk_lib.Connect #TODO cConnect.argtypes = [] #TODO cConnect.restypes = [] cDisconnect = crsdk_lib.Disconnect #TODO cDisconnect.argtype = #TODO cDisconnect.restype = cReleaseDevice = crsdk_lib.ReleaseDevice #TODO cReleaseDevice.restype = #TODO cReleaseDevice.argtype = cGetDeviceProperties = crsdk_lib.GetDeviceProperties cGetSelectDeviceProperties = crsdk_lib.GetSelectDeviceProperties cReleaseDeviceProperties = crsdk_lib.ReleaseDeviceProperties cSetDeviceProperty = crsdk_lib.SetDeviceProperty cSendCommand = crsdk_lib.SendCommand cGetLiveViewImage = crsdk_lib.GetLiveViewImage cGetLiveViewImageInfo = crsdk_lib.GetLiveViewImageInfo cGetLiveViewProperties = crsdk_lib.GetLiveViewProperties cGetSelectLiveViewProperties = crsdk_lib.GetSelectLiveViewProperties cReleaseLiveViewProperties = crsdk_lib.ReleaseLiveViewProperties cGetDeviceSetting = crsdk_lib.GetDeviceSetting cSetDeviceSetting = crsdk_lib.SetDeviceSetting cSetSaveInfo = crsdk_lib.SetSaveInfo cGetSDKVersion = crsdk_lib.GetSDKVersion cGetSDKSerial = crsdk_lib.GetSDKSerial cGetDateFolderList = crsdk_lib.GetDateFolderList cGetContentsHandleList = crsdk_lib.GetContentsHandleList cGetContentsDetailInfo = crsdk_lib.GetContentsDetailInfo cReleaseDateFolderList = crsdk_lib.ReleaseDateFolderList cReleaseContentsHandleList = crsdk_lib.ReleaseContentsHandleList cPullContentsFile = crsdk_lib.PullContentsFile cGetContentsThumbnailImage = crsdk_lib.GetContentsThumbnailImage def int_to_bytes(x: int) -> bytes: return x.to_bytes((x.bit_length() + 7) // 8, 'big') def init() -> bytes: return cInit(0) def release() -> bytes: return cRelease() def editsdkinfo(c: int): #TODO implement return editsdkinfo.__name__ + " is Not Implemented" def getsdkversion() -> bytes: return int_to_bytes(cGetSDKVersion()) def string_of_getsdkversion() -> str: temp = getsdkversion() temp = [temp[i:i + 1] for i in range(0, len(temp), 1)] temp = [int.from_bytes(temp[i], byteorder='big') for i in range(0, len(temp), 1)] tmp = str(temp[0]) + "." + str(f"{temp[1]:02}") + "." + str(f"{temp[2]:02}") return tmp def getsdkserial() -> bytes: cGetSDKSerial.restype = c_uint32 return int_to_bytes(cGetSDKSerial()) def string_of_getsdkserial() -> str: temp = getsdkserial() temp = [temp[i:i + 1] for i in range(0, len(temp), 1)] temp = [int.from_bytes(temp[i], byteorder='big') for i in range(0, len(temp), 1)] tmp = "" for i in range(0, 2): try: tmp = str(f"{temp[i]:02}") except Exception: return tmp return tmp Functions that i think work init(), release(), getsdkversion(), getsdkserial(). The first problem i encountered was with the function enumCameraObjects. In the header file you can see that it expects an object from the class ICrEnumCameraObjectInfo and an integer. Unfortunately my knowledge of python is not large and i dont know anything about C/C++. On various websites they talk about pointers and byrefs but it wont work for me. extern "C" SCRSDK_API // This function enumerates the cameras that are connected to the pc via the protocol and the physical connection that the library supports. CrError EnumCameraObjects(ICrEnumCameraObjectInfo** ppEnumCameraObjectInfo, CrInt8u timeInSec = 3); ^This is the excerpt from one of the header files for the sdk. class ICrEnumCameraObjectInfo { public: virtual CrInt32u GetCount() const = 0; virtual const ICrCameraObjectInfo* GetCameraObjectInfo(CrInt32u index) const = 0; virtual void Release() = 0; }; ^This is an excerpt of the header file for the class ICrEnumCameraObjectInfo. class ICrCameraObjectInfo { public: virtual void Release() = 0; // device name virtual CrChar* GetName() const = 0; virtual CrInt32u GetNameSize() const = 0; // model name virtual CrChar *GetModel() const = 0; virtual CrInt32u GetModelSize() const = 0; // pid (usb) virtual CrInt16 GetUsbPid() const = 0; // device id virtual CrInt8u* GetId() const = 0; virtual CrInt32u GetIdSize() const = 0; virtual CrInt32u GetIdType() const = 0; // current device connection status virtual CrInt32u GetConnectionStatus() const = 0; virtual CrChar *GetConnectionTypeName() const = 0; virtual CrChar *GetAdaptorName() const = 0; // device UUID virtual CrChar *GetGuid() const = 0; // device pairing necessity virtual CrChar *GetPairingNecessity() const = 0; virtual CrInt16u GetAuthenticationState() const = 0; }; ^And for reference the class ICrCameraObjectInfo def enumcameraobjects(): #TODO implement class CAMERAOBJECTINFO(ctypes.Structure): __fields__ = [ ("release", c_void_p), ("getName", c_char), ("getNameSize", c_uint32), ("getModel", c_char), ("getModelSize", c_uint32), ("getUSBPid", c_int16), ("getID", c_uint8), ("getIDSize", c_uint32), ("getIDType", c_uint32), ("getConnectionStatus", c_uint32), ("getConnectionTypeName", c_char), ("getAdaptorName", c_char), ("getGUID", c_char), ("getPairingNecessity", c_char), ("getAuthenticationState", c_uint16) ] class ENUMCAMERAOBJECTINFO(ctypes.Structure): __fields__ = [ ("getCount", c_uint32), ("getCameraObjectInfo", POINTER(CAMERAOBJECTINFO)), ("release", c_void_p) ] pass enumCameraObjectInfo = ENUMCAMERAOBJECTINFO() return cEnumCameraObjects(byref(enumCameraObjectInfo), 3) return enumCameraObjectInfo #return enumcameraobjects.__name__ + " is Not Implemented" ^Right now this is what i have and its probably as wrong as it gets cause I literally tried a lot recommended on the internet. Unfortunately there is also no program on the internet which uses this library. All the Sony wrapper program use the old Camera Remote SDK which is discontinued. I look forward to your ideas to solve this problem. Since my last update I managed to edit my code to make a bit more sense. class CAMERAOBJECTINFO(ctypes.Structure): _fields_ = [] class ENUMCAMERAOBJECTINFO(ctypes.Structure): _fields_ = [ ("GetCount", c_uint32) ] class CRERROR(ctypes.Structure): _fields_ = [] ^The three classes that i have to work with in this function. def enumcameraobjects(): #TODO implement crsdk_lib.EnumCameraObjects.argtypes = [POINTER(POINTER(ENUMCAMERAOBJECTINFO)), c_uint8] crsdk_lib.EnumCameraObjects.restype = c_uint32 enumCameraObjectInfo = ENUMCAMERAOBJECTINFO() temp = crsdk_lib.EnumCameraObjects(POINTER(POINTER(ENUMCAMERAOBJECTINFO))(enumCameraObjectInfo), 3) print(int_to_bytes(temp)) return enumCameraObjectInfo.GetCount #return enumcameraobjects.__name__ + " is Not Implemented" The temp variable returns the correct CrError integer. But even when a camera is connected the GetCount still wont work. (I have tried both GetCount() and GetCount) I need to somehow call the function GetCount() inside the class ICrEnumCameraObjectInfo to get the number of connected cameras. I hope my update helped to give a bit more information and an update to my current research.
[ "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 the header file. I would say that it may be possible to build bridge libraries (basically one for .cpp in the app folder) and then link all those libraries together with ctypes. At the end I have decided to modify the remote_cli.cpp file and then call it using subprocess in Python, was the easiest thing to do\n" ]
[ 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 = "\\ftac\admin\rec\pir" path = path.replace("\", "/") But I got an error (SyntaxError: EOL while scanning string literal) and is not return the path as I want: //ftac/admin/rec/pir, how can I solve it? I also tried path = path.replace(os.sep, "/") or path = path.replace("\\", "/") but with both methods the first double backslash becomes single and the \a was deleted.. A: Oh boy, this is a bit more complicated than first appears. Your 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. This is because when you make a string like "\a", the intperter sees a special character "\x07". This means you have to manually know which of these special characters you expect, then [lossily] hack back if you see their representation (such as in this example): def str_to_raw(s): raw_map = {8:r'\b', 7:r'\a', 12:r'\f', 10:r'\n', 13:r'\r', 9:r'\t', 11:r'\v'} return r''.join(i if ord(i) > 32 else raw_map.get(ord(i), i) for i in s) >>> str_to_raw("\\ftac\admin\rec\pir") '\\ftac\\admin\\rec\\pir' Now you can use the pathlib module, this can handle paths in a system agnsotic way. In your case, you know you have Windows like paths as input, so you can use as follows: import pathlib def fix_path(path): # get proper raw representaiton path_fixed = str_to_raw(path) # read in as windows path, convert to posix string return pathlib.PureWindowsPath(path_fixed).as_posix() >>> fix_path("\\ftac\admin\rec\pir") '/ftac/admin/rec/pir'
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("\", "/") But I got an error (SyntaxError: EOL while scanning string literal) and is not return the path as I want: //ftac/admin/rec/pir, how can I solve it? I also tried path = path.replace(os.sep, "/") or path = path.replace("\\", "/") but with both methods the first double backslash becomes single and the \a was deleted..
[ "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 special character \"\\x07\".\nThis means you have to manually know which of these special characters you expect, then [lossily] hack back if you see their representation (such as in this example):\ndef str_to_raw(s):\n raw_map = {8:r'\\b', 7:r'\\a', 12:r'\\f', 10:r'\\n', 13:r'\\r', 9:r'\\t', 11:r'\\v'}\n return r''.join(i if ord(i) > 32 else raw_map.get(ord(i), i) for i in s)\n\n>>> str_to_raw(\"\\\\ftac\\admin\\rec\\pir\")\n'\\\\ftac\\\\admin\\\\rec\\\\pir'\n\n\nNow you can use the pathlib module, this can handle paths in a system agnsotic way. In your case, you know you have Windows like paths as input, so you can use as follows:\nimport pathlib\n\ndef fix_path(path):\n # get proper raw representaiton\n path_fixed = str_to_raw(path)\n\n # read in as windows path, convert to posix string\n return pathlib.PureWindowsPath(path_fixed).as_posix()\n\n>>> fix_path(\"\\\\ftac\\admin\\rec\\pir\")\n'/ftac/admin/rec/pir'\n\n\n" ]
[ 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.txt without manually changing version. The version name looks like: Master package name: 1.0.1 dev or other branch package: branch_name.master_version.build_version e.g. dev.1.0.1.3333, branch-1.0.1.3333, branch-bla-bla-12.1.0.1.3333 and i want in requirements checking get only grater master_version.build_version in choosing branch: dev.1.0.1.3333 checking bigger then dev.* branch-1.0.1.3333 checking bigger then branch-1.* branch-bla-bla-12.1.0.1.3333 checking bigger then branch-bla-bla-12.* A: Ok i had a bug in my setup.py When number is in schema: branch_name.version_number.build_number work as i expect.
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 looks like: Master package name: 1.0.1 dev or other branch package: branch_name.master_version.build_version e.g. dev.1.0.1.3333, branch-1.0.1.3333, branch-bla-bla-12.1.0.1.3333 and i want in requirements checking get only grater master_version.build_version in choosing branch: dev.1.0.1.3333 checking bigger then dev.* branch-1.0.1.3333 checking bigger then branch-1.* branch-bla-bla-12.1.0.1.3333 checking bigger then branch-bla-bla-12.*
[ "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 happens, I see requests coming in, but no response sent. Note that this is client connection and not memcache or db connection. How can I debug the issue? What can be the possible causes? Thank you! A: As mentioned here, you can disable debug mode. Also you can add CONN_MAX_AGE to persist connections.
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 sent. Note that this is client connection and not memcache or db connection. How can I debug the issue? What can be the possible causes? Thank you!
[ "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-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. A: When first starting out with a web scraper, a common mistake is to send a request directly to the website (using a code of your choice), and the website’s response will depend on your activity. Many websites have developed systems to detect bots and web scrapers, and if you are caught, you risk having your IP address blocked and being unable to make a request for an extended period of time. That is an issue. So you use IP proxy this time to hide your true IP address. In fact, you used multiple proxy servers to cycle it through, allowing you to make requests much faster. However, there is another issue. Yes, Captcha is another issue you must deal with. As a result, you’ll need to add a Captcha solver layer to your scraper. This is where ScraperApi comes in. It simplifies all of the complicated processes for you. All you have to do is request scraperapi to browse a URL and return a clean HTML page without worrying about IP or captcha. Scraperapi can be used to create an effective web scraper for complex web pages with forms and js.
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 code of your choice), and the website’s response will depend on your activity. Many websites have developed systems to detect bots and web scrapers, and if you are caught, you risk having your IP address blocked and being unable to make a request for an extended period of time. That is an issue.\nSo you use IP proxy this time to hide your true IP address. In fact, you used multiple proxy servers to cycle it through, allowing you to make requests much faster. However, there is another issue. Yes, Captcha is another issue you must deal with.\nAs a result, you’ll need to add a Captcha solver layer to your scraper.\nThis is where ScraperApi comes in. It simplifies all of the complicated processes for you. All you have to do is request scraperapi to browse a URL and return a clean HTML page without worrying about IP or captcha. Scraperapi can be used to create an effective web scraper for complex web pages with forms and js.\n" ]
[ 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 correlate to anything, but I'd like it to represent the index of the non-zero variable in the list "variables". Should I enumerate? Is there an easy way to do this with list comprehension? Thank you! A: Try print(list(filter(lambda x: x==-1, variables))) A: Do you want to get the index? Outputting the element would be equal to just writing print(-1) print (variables.index(-1)) A: Printing the element would just give you -1. You can loop through the list: for e in variables: if e != 0: # -1 found By using print(variables.index(-1)) you can also print the spot where -1 was found.
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 the non-zero variable in the list "variables". Should I enumerate? Is there an easy way to do this with list comprehension? Thank you!
[ "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 # -1 found\n\nBy using print(variables.index(-1)) you can also print the spot where -1 was found.\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. view CustomUser = get_user_model() class SignUpView(FormView): template_name = 'accounts/signup.html' form_class = SignUpForm def form_valid(self, form): try: self.user = CustomUser.objects.filter(email=form.cleaned_data['email']).first() if not self.user: self.user = CustomUser.objects.create_user(email=form.cleaned_data['email'], full_name=form.cleaned_data['full_name'], password=form.cleaned_data['password'], is_verified=False ) else: if self.user.is_verified: self.send_reminder() return super().form_valid(form) self.send_code() except: messages.error(self.request, _('Something went wrong, please try to register again')) return redirect(reverse('accounts:signup')) return super().form_valid(form) My test so far: class SignUpViewTest(TestCase): def setUp(self): self.factory = RequestFactory() def test_database_fail(self): with patch.object(CustomUserManager, 'create_user') as mock_method: mock_method.side_effect = Exception(ValueError) view = SignUpView.as_view() url = reverse('accounts:signup') data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'} request = self.factory.post(url, data) setattr(request, 'session', 'session') messages = FallbackStorage(request) request._messages = messages response = view(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/accounts/signup/') My question is, how do I retrieve the message so that I can make an assertEqual against the message: 'Something went wrong, please try to register again'? A: After digging a little deeper the message(s) can be found here: request._messages._queued_messages[0] And therefore the assertEqual would be: self.assertEqual(str(request._messages._queued_messages[0]), 'Something went wrong, please try to register again')
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(FormView): template_name = 'accounts/signup.html' form_class = SignUpForm def form_valid(self, form): try: self.user = CustomUser.objects.filter(email=form.cleaned_data['email']).first() if not self.user: self.user = CustomUser.objects.create_user(email=form.cleaned_data['email'], full_name=form.cleaned_data['full_name'], password=form.cleaned_data['password'], is_verified=False ) else: if self.user.is_verified: self.send_reminder() return super().form_valid(form) self.send_code() except: messages.error(self.request, _('Something went wrong, please try to register again')) return redirect(reverse('accounts:signup')) return super().form_valid(form) My test so far: class SignUpViewTest(TestCase): def setUp(self): self.factory = RequestFactory() def test_database_fail(self): with patch.object(CustomUserManager, 'create_user') as mock_method: mock_method.side_effect = Exception(ValueError) view = SignUpView.as_view() url = reverse('accounts:signup') data = {'email': 'test@test.com', 'full_name': 'Test Tester', 'password': 'Abnm1234'} request = self.factory.post(url, data) setattr(request, 'session', 'session') messages = FallbackStorage(request) request._messages = messages response = view(request) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/accounts/signup/') My question is, how do I retrieve the message so that I can make an assertEqual against the message: 'Something went wrong, please try to register again'?
[ "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.find_element(By.XPATH,("//div[text()='1791']")).click() and it does not work. My selenium version is 4.3.0, so it does not support command such as find_element_by_xpath. Hence, the answers I found on the internet offers no help. Thank you! A: You are trying to click on the div with the text '1791'. But in the provided info this text is inside a tag. Try the following: driver.find_element(By.XPATH,("//a[text()='1791']")).click() UPD Except for the incorrect XPath the problem was in unused WebDriverWait for the element (the expectation for checking that an element is present on the DOM of a page before clicking on it). Webdriver tries to click an element immediately after opening the desired page, but some elements may not be loaded yet. The final code will be: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,("//a[text()='1791']"))).click() With imports: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
[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 not work. My selenium version is 4.3.0, so it does not support command such as find_element_by_xpath. Hence, the answers I found on the internet offers no help. Thank you!
[ "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 checking that an element is present on the DOM of a page before clicking on it).\nWebdriver tries to click an element immediately after opening the desired page, but some elements may not be loaded yet.\nThe final code will be:\nWebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,(\"//a[text()='1791']\"))).click()\n\nWith imports:\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium_webdriver" ]
stackoverflow_0074574360_python_selenium_webdriver.txt