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:
Is there a single line way to run a command in a Python venv?
I have a command that only runs correctly inside a Python virtual environment I've configured (as intended). I know that I can run the command as
$ cmd args
once I've activated the venv. But (due to the constraints of the tool I'm using) I need to act... | Is there a single line way to run a command in a Python venv? | I have a command that only runs correctly inside a Python virtual environment I've configured (as intended). I know that I can run the command as
$ cmd args
once I've activated the venv. But (due to the constraints of the tool I'm using) I need to activate run (and deactivate?) in one line: something equivalent to ru... | [
"You can generally run something in a virtual environment simply by using a fully qualified path to the script. For example, if I have:\nvirtualenv .venv\n\nThen I can install something into that virtual environment without activating it by running:\n.venv/bin/pip install foo\n\nThis should be true for anything in... | [
17,
6,
1,
1,
1,
0,
0
] | [] | [] | [
"command_line_interface",
"python",
"virtualenv"
] | stackoverflow_0048174599_command_line_interface_python_virtualenv.txt |
Q:
Finding the sorted list of prime factors of a number
What is wrong with my code?
def exercise_2(n):
primfac = []
d = 2
while d*d <= n:
if (n%d) == 0:
primfac.append(d)
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
I'm trying to get the prime factors of a numbe... | Finding the sorted list of prime factors of a number | What is wrong with my code?
def exercise_2(n):
primfac = []
d = 2
while d*d <= n:
if (n%d) == 0:
primfac.append(d)
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
I'm trying to get the prime factors of a number, and the output it gives is [2,5,10]. The output I want ... | [] | [] | [
"For your example:\nAfter first loop iteration, n = 50 (100/2) and i = 3\nAfter second loop iteration, n = 50 and i = 4\nAfter third loop iteration, n = 50 and i = 5\nAfter fourth loop iteration, n = 10 (50/5) and i = 6\nNow, 6*6 < 10, hence the while loop terminates.\nYou then append n (which is 10) to your prime ... | [
-1
] | [
"python"
] | stackoverflow_0074163427_python.txt |
Q:
TypeError: () missing 1 required positional argument: 'instance' in Locust
I need to loadtest an Odoo Environment and I have written a test class with different methods in it. Currently I'm trying to test this stuff locally but I'm running in a error that I don't understand right now.
Traceback (most recent call... | TypeError: () missing 1 required positional argument: 'instance' in Locust | I need to loadtest an Odoo Environment and I have written a test class with different methods in it. Currently I'm trying to test this stuff locally but I'm running in a error that I don't understand right now.
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 908, in gevent._gevent_cgreenlet.G... | [
"Looks like you are using legacy style wait times:\nmin_wait = 0.5\nmax_wait = 5.0\n\nAND new style\nwait_time = ... \n\nMaybe remove the legacy ones?\n"
] | [
0
] | [] | [] | [
"load_testing",
"locust",
"odoo",
"python"
] | stackoverflow_0074139576_load_testing_locust_odoo_python.txt |
Q:
Do consecutive window functions with the same partitioning cause additional shuffles?
Suppose I have two different windows with the same partitioning:
window1 = Window.partitionBy("id")
window2 = Window.partitionBy("id").orderBy("date")
And then I call several consecutive window functions using them:
df.withColum... | Do consecutive window functions with the same partitioning cause additional shuffles? | Suppose I have two different windows with the same partitioning:
window1 = Window.partitionBy("id")
window2 = Window.partitionBy("id").orderBy("date")
And then I call several consecutive window functions using them:
df.withColumn("col1", F.sum("x").over(window1))
.withColumn("col2", F.first("x").over(window2))
And ... | [
"TLDR: only one shuffle occurs, repartition is useless here.\nThat's actually quite easy to verify.\n// sample data\ndf = spark.createDataFrame([\n (1, 2, \"2022-10-22\"),\n (1, 3, \"2022-11-22\"),\n (2, 4, \"2023-12-12\"),\n (2, 5, \"2021-01-01\")], ['id', 'x', 'date'])\n\n# let us now introduce 3 wind... | [
1
] | [] | [] | [
"apache_spark",
"apache_spark_sql",
"python"
] | stackoverflow_0074153449_apache_spark_apache_spark_sql_python.txt |
Q:
How to animate the position of an object or sprite in Pygame and move it towards predefined positions or along a defined path?
I learned how to print image in pygame, but I don't know how to make a dynamic position(It can change the image position by itself). What did I miss? Here's my attempt.
import pygame
scre... | How to animate the position of an object or sprite in Pygame and move it towards predefined positions or along a defined path? | I learned how to print image in pygame, but I don't know how to make a dynamic position(It can change the image position by itself). What did I miss? Here's my attempt.
import pygame
screen_size = [360,600]
screen = pygame.display.set_mode(screen_size)
background = pygame.image.load("rocketship.png")
keep_alive = True... | [
"You don't need nested loops to animate objects. You have one loop, the application loop. Use it! You need to redraw the entire scene in each frame. Change the position of the object slightly in each frame. Since the object is drawn at a different position in each frame, the object appears to move smoothly.\nDefine... | [
1
] | [] | [] | [
"dynamic",
"position",
"pygame",
"python"
] | stackoverflow_0074163435_dynamic_position_pygame_python.txt |
Q:
How to click on a download button with Selenium
I try to scrap some informations on a website.
There is my code
from lib2to3.pgen2 import driver
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import pyvirtualdisplay
class Informations:
def __init__(self):
self.l... | How to click on a download button with Selenium | I try to scrap some informations on a website.
There is my code
from lib2to3.pgen2 import driver
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
import pyvirtualdisplay
class Informations:
def __init__(self):
self.list_site_by_siren = ["418 096 392", "334 992 798"]
... | [
"this line can get you nothing: driver.find_element(By.CLASS_NAME, \"button mt2\").click() because you actually look not for this \"button mt2\" but for this \" 'button mt2' \", it tries to find class with name 'button mt2' (=it looks for one name, not for two ones). of course there is no class with such name and ... | [
1,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"selenium"
] | stackoverflow_0074162389_python_python_3.x_selenium.txt |
Q:
Can't find publish_date with newspaper3k
I want to scrape an article from a website with the newspaper library (newspaper3k). However, it doesn't find the published_date for the article, which is div.source-date in the website's source text, and the authors (or source rather), which is div.delfi-source-name in the... | Can't find publish_date with newspaper3k | I want to scrape an article from a website with the newspaper library (newspaper3k). However, it doesn't find the published_date for the article, which is div.source-date in the website's source text, and the authors (or source rather), which is div.delfi-source-name in the website's source text. How can I scrape the d... | [
"The date element in your source is located in 2 locations. The one that you see Wednesday, October 19, 2022 is located in a div tag that newspaper3k cannot parse without using BeautifulSoup.\nThe second date is hidden in the meta tags, which newspaper3k can parse with some additional code.\nfrom newspaper import ... | [
0
] | [] | [] | [
"newspaper3k",
"python",
"python_newspaper"
] | stackoverflow_0074142518_newspaper3k_python_python_newspaper.txt |
Q:
PyQt5 : QMovie is truncated even after resizing
I am adding a gif to my QMainWindow. I want the size of my window to match exactly the size of QMovie but my QMovie is truncated at the first place and even if use resize on that, its still not showing fully.
Here is the code :
from typing import Text
from PyQt5 impo... | PyQt5 : QMovie is truncated even after resizing | I am adding a gif to my QMainWindow. I want the size of my window to match exactly the size of QMovie but my QMovie is truncated at the first place and even if use resize on that, its still not showing fully.
Here is the code :
from typing import Text
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc
f... | [
"You must set both the minimum size of the label and that of the widget.\n\n#!/usr/bin/env python3\nfrom typing import Text\nfrom PyQt5 import QtWidgets\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtGui\nimport sys\n\n\nclass MainWindow(QtWidgets.QDialog):\n def __init__(self, movsize=50, *arg, **kwargs):\n ... | [
1
] | [] | [] | [
"gif",
"pyqt5",
"python",
"qmovie",
"qwidget"
] | stackoverflow_0074163342_gif_pyqt5_python_qmovie_qwidget.txt |
Q:
how to convert a day to a second in python with array list
def konversi(j=0):
def minute(m=0):
def secon(d=0):
return ((j*60)+m)*60+d
return secon
return minute
data = "05:33:05"
data_split = data.split(':')
print("data = ",data)
print("data split = ",data_split)
i'm confuse ... | how to convert a day to a second in python with array list | def konversi(j=0):
def minute(m=0):
def secon(d=0):
return ((j*60)+m)*60+d
return secon
return minute
data = "05:33:05"
data_split = data.split(':')
print("data = ",data)
print("data split = ",data_split)
i'm confuse how to append a value 'day' into fungsion
hours = int(data_split... | [
"I assume this as your input:\ndata = [\"21 day 20 hour 9 minute 20 sec\",\n \"19 day 14 hour 0 minute 13 sec\",\n \"1 day 1 hour 1 minute 1 sec\"]\n\nAnd you want to calculate the total number of seconds for each element in that list.\ndata_seconds = []\nfor date_str in data:\n day, _, hour, _, mi... | [
1,
0
] | [] | [] | [
"currying",
"list",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074160646_currying_list_python_python_2.7_python_3.x.txt |
Q:
Django signals don't work with DEBUG=False
I have the following code that work fine in development mode with DEBUG=True. In a nutshell - signal should invalidate a cache. The project running Django 4.0, Python 3.9, MySQL MarialDB 10.2
signals.py
from django.core.cache import cache
from django.db.models.signals imp... | Django signals don't work with DEBUG=False | I have the following code that work fine in development mode with DEBUG=True. In a nutshell - signal should invalidate a cache. The project running Django 4.0, Python 3.9, MySQL MarialDB 10.2
signals.py
from django.core.cache import cache
from django.db.models.signals import post_delete, post_save
from django.dispatch ... | [
"Problem solved with weak=False added for every signal\n@receiver(signal=post_delete, sender=Marker, dispatch_uid=\"marker_deleted\", weak=False)\n\n"
] | [
0
] | [] | [] | [
"caching",
"django",
"django_signals",
"python"
] | stackoverflow_0074158932_caching_django_django_signals_python.txt |
Q:
How to split integer and add to list?
I want to know how can we program in Python please.
So,
D = read().value
And D value is updated two times
First time D = [50, 11, 18, 21, 34]
Second time D = 1346 (second time D value is always 4 digit integer)
I want to get the final result like this (First time D array with ... | How to split integer and add to list? | I want to know how can we program in Python please.
So,
D = read().value
And D value is updated two times
First time D = [50, 11, 18, 21, 34]
Second time D = 1346 (second time D value is always 4 digit integer)
I want to get the final result like this (First time D array with the second time D with 4 digit integer has ... | [
"You can achieve this result with by using a temporary variable for storing the initial list of numbers contained in D when D is updated to contain an integer. Then you can cast the integer to a string and use substrings to get the first two characters of the string and then cast them back to and integer. Then you ... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074163472_python_python_3.x.txt |
Q:
How do I extract the URL and specific columns from this page using Python?
https://training.lczero.org/networks/?show_all=1
I want to extract the columns called Number, Run, Network, Elo, Games from this website. I was able to do so using Pandas, but then the pd.read_html() function does not extract the href value... | How do I extract the URL and specific columns from this page using Python? | https://training.lczero.org/networks/?show_all=1
I want to extract the columns called Number, Run, Network, Elo, Games from this website. I was able to do so using Pandas, but then the pd.read_html() function does not extract the href values that I need to be able to download this data. I tried using BeautifulSoup but ... | [
"Try:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://training.lczero.org/networks/?show_all=1\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\ndf = pd.read_html(str(soup))[0]\ndf[\"links\"] = [\n \"https://training.lczero.org\" + a[\"href\"] for a ... | [
0
] | [] | [] | [
"beautifulsoup",
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074163380_beautifulsoup_pandas_python_web_scraping.txt |
Q:
PyBind11: simple invoke task, standard C++ library not found
i am trying to wrap the C++ library PyrochloreAFM.hpp which itself uses the lib boost/randoom.hpp so that i can import it as a python module. The C++ part itself works fine and i can succesfully import and use all of this from my main.
#include "Pyrochlo... | PyBind11: simple invoke task, standard C++ library not found | i am trying to wrap the C++ library PyrochloreAFM.hpp which itself uses the lib boost/randoom.hpp so that i can import it as a python module. The C++ part itself works fine and i can succesfully import and use all of this from my main.
#include "PyrochloreAFM.hpp"
int main (int argc, const char *argv[]) {
Pyr... | [
"\"Of course\" the tasks.py file which compiles the .cpp file through the python module invoke has to instruct the compiler g++ to use the libraries we desire. In my case it is the flag -I /opt/homebrew/Cellar/boost/1.80.0/include i also use in my makefile or directly in terminal.\n"
] | [
2
] | [] | [] | [
"c++",
"invoke",
"path",
"pybind11",
"python"
] | stackoverflow_0074163558_c++_invoke_path_pybind11_python.txt |
Q:
Converting kivy code to android app with firebase
I am trying to convert kivy and kivymd code to app using ubuntu latest version. then i get error.
when i try to install proto it says no module named proto
While converting kivy code to apk whick contain modules as
import os
import re
from datetime import date
impo... | Converting kivy code to android app with firebase | I am trying to convert kivy and kivymd code to app using ubuntu latest version. then i get error.
when i try to install proto it says no module named proto
While converting kivy code to apk whick contain modules as
import os
import re
from datetime import date
import firebase_admin
from firebase_admin import credential... | [
"Maybe try to install https://pypi.org/project/0proto/and then add it to the requirements list.\n",
"Try to add protobuf_cpp to your requirements in buildozer file. Remove your \".buildozer\" folder from both project and home, rebuild project.\nIf doesnt work, find \"proto\" in your virtualenv (most probably unde... | [
0,
0
] | [] | [] | [
"buildozer",
"firebase",
"kivy",
"kivymd",
"python"
] | stackoverflow_0072256531_buildozer_firebase_kivy_kivymd_python.txt |
Q:
Pandas .groupby is returning an address
I really don't understand why I am getting an adress location output when creating a Dataframe with groupby for the 'courses'?
code:
import pandas as pd
technologies = ({
'Courses':["Spark","PySpark","Hadoop","Python","Pandas","Hadoop","Spark","Python","NA"],
'Fee'... | Pandas .groupby is returning an address | I really don't understand why I am getting an adress location output when creating a Dataframe with groupby for the 'courses'?
code:
import pandas as pd
technologies = ({
'Courses':["Spark","PySpark","Hadoop","Python","Pandas","Hadoop","Spark","Python","NA"],
'Fee' :[22000,25000,23000,24000,26000,25000,25000,... | [
"provide an aggregate function to perform some calculation on what you are grouping. Look at the examples here: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html\ndf.groupby(['Courses']).size()\nCourses\nHadoop 2\nNA 1\nPandas 1\nPySpark 1\nPython 2\nSpark 2\ndt... | [
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074163655_dataframe_pandas_python.txt |
Q:
Trying to have separate fail_under values for different modules in monorepo using coverage.py
The problem is basically summed up by the title but simply put, I am implementing coverage requirements for a mono-repo codebase that is maintained by multiple teams.
Contraints:
All of our utilities run from the root di... | Trying to have separate fail_under values for different modules in monorepo using coverage.py | The problem is basically summed up by the title but simply put, I am implementing coverage requirements for a mono-repo codebase that is maintained by multiple teams.
Contraints:
All of our utilities run from the root directory, including our tests.
Running our tests runs all of the tests for all of the modules unless... | [
"Coverage.py doesn't provide this as a feature, but I wrote a simple tool to measure goals like this more flexibly: Coverage goals. It will do what you want, and could become a coverage.py feature in the future.\n"
] | [
0
] | [] | [] | [
"code_coverage",
"coverage.py",
"monorepo",
"pytest",
"python"
] | stackoverflow_0074156650_code_coverage_coverage.py_monorepo_pytest_python.txt |
Q:
How to clear screan.blit()
I am doing notification window and I want to do when massage pop up is shows for some time and then it clears it self.
I know how to do that it waits with time.sleep() but I dont know how to clear screen.blip().
A:
I think the best thing for you to do is to draw the whole window again,... | How to clear screan.blit() | I am doing notification window and I want to do when massage pop up is shows for some time and then it clears it self.
I know how to do that it waits with time.sleep() but I dont know how to clear screen.blip().
| [
"I think the best thing for you to do is to draw the whole window again, removing the pop up. So when the condition to send the message is met, redraw the window with the message, and then after a few seconds, redraw it again without that pop up. The window is redrawn all the time when your screen refreshes anyway,... | [
0
] | [] | [] | [
"blit",
"notifications",
"python",
"python_3.x",
"screen"
] | stackoverflow_0074163750_blit_notifications_python_python_3.x_screen.txt |
Q:
pdb.set_trace() not working
When I insert import pdb; pdb.set_trace() in my code, it shows an error message:
'module' object has attribute 'set_trace'
In the pdb.py file, there is the def set_trace() function. How can it not work?
Has anyone had the same problem and knows how to solve this?
A:
if the python f... | pdb.set_trace() not working | When I insert import pdb; pdb.set_trace() in my code, it shows an error message:
'module' object has attribute 'set_trace'
In the pdb.py file, there is the def set_trace() function. How can it not work?
Has anyone had the same problem and knows how to solve this?
| [
"if the python file that you are running is code.py please change the name. For some reasons code.py or pdb.py files can not use pdb package.\n",
"change the name file pdb.py same bdb_test.py it run with me\n",
"What Python version are you using?\nI can reproduce that error if I try to import pdb; pdb.set_trace... | [
1,
0,
0,
0
] | [] | [] | [
"pdb",
"python",
"set",
"trace"
] | stackoverflow_0016228532_pdb_python_set_trace.txt |
Q:
Is there any way to use python script in react native app?
In my case I want to use Vosk in python for offline speech recognition and want to develope complete application on react native for handeling rest of the operation for controlling my phone. And this should be completely offline so don't want to setup sape... | Is there any way to use python script in react native app? | In my case I want to use Vosk in python for offline speech recognition and want to develope complete application on react native for handeling rest of the operation for controlling my phone. And this should be completely offline so don't want to setup saperate python server.
| [
"You can check their example of Android integration https://alphacephei.com/vosk/android and if you want to create a wrapper for React Native. Also, they have a wrapper for Native Script and you can check how they use it for android, for example here is a list of dependencies https://github.com/alphacep/nativescrip... | [
0
] | [] | [] | [
"android",
"mobile",
"python",
"react_native"
] | stackoverflow_0074163568_android_mobile_python_react_native.txt |
Q:
How to nested loop in list comprehension
I have a piece of code down here, and I'm wondering if I can make this simpler with list comprehension in Python...
T: str = 'XY'
combinations: list = [] # Make an empty list
for i in range(len(T)):
for j in range(len(T)): combinations.append((T[i], T[j])) # (T[i], T[j... | How to nested loop in list comprehension | I have a piece of code down here, and I'm wondering if I can make this simpler with list comprehension in Python...
T: str = 'XY'
combinations: list = [] # Make an empty list
for i in range(len(T)):
for j in range(len(T)): combinations.append((T[i], T[j])) # (T[i], T[j]) is act as a tuple here
How can I simplify ... | [
"If you are interested in List-comprehension version of the code you have written:\n>>> [(T[i], T[j]) for j in range(len(T)) for i in range(len(T))]\n[('X', 'X'), ('Y', 'X'), ('X', 'Y'), ('Y', 'Y')]\n\nModified List-comprehension without len and range, but iterating the string itself:\n>>> [(x,y) for x in T for y i... | [
5
] | [] | [] | [
"list_comprehension",
"nested_loops",
"python"
] | stackoverflow_0074163778_list_comprehension_nested_loops_python.txt |
Q:
How to create custom recipe for dlib library for p4a
The code below successfully creates libdlib.so and copies it to .buildozer/android/platform/build-armeabi-v7a/build/libs_collections/<APP>/armeabi-v7a also this file is located in the apk itself along the path .buildozer/android/platform/build-armeabi-v7a/dists/... | How to create custom recipe for dlib library for p4a | The code below successfully creates libdlib.so and copies it to .buildozer/android/platform/build-armeabi-v7a/build/libs_collections/<APP>/armeabi-v7a also this file is located in the apk itself along the path .buildozer/android/platform/build-armeabi-v7a/dists/<APP>__armeabi-v7a/libs/armeabi-v7a. But for some reason, ... | [
"You shouldnt add Python version with {Major} to PYTHON_INCLUDE_DIR and other parameters. So, it will not bind Python packages under site-packages.\nCheck this for an example cmake parameters\nhttps://gist.github.com/jrsa/e83fb8dc5c7ae645113509cc48955f26\n"
] | [
1
] | [] | [] | [
"android",
"kivy",
"p4a",
"python",
"python_for_android"
] | stackoverflow_0069630334_android_kivy_p4a_python_python_for_android.txt |
Q:
Time duration of user input
I'd like to know how long it takes a user to enter an input that I record with raw_input().
I.e. does it take them 1 second or 10 seconds to enter something on the command line.
Is there an established way of doing this, or would I need to invent my own way of doing this?
A:
If all yo... | Time duration of user input | I'd like to know how long it takes a user to enter an input that I record with raw_input().
I.e. does it take them 1 second or 10 seconds to enter something on the command line.
Is there an established way of doing this, or would I need to invent my own way of doing this?
| [
"If all you need is second resolution (not millisecond/microsecond), you can surround the code with time.time() to get the beginning/ending times, then subtract.\nimport time\n\nstart = time.time()\nin_str = raw_input(\"Enter the thing:\")\nend = time.time()\nelapsed = end-start\nprint \"That took you \" + str(elap... | [
5,
1,
0,
0,
0
] | [] | [] | [
"duration",
"input",
"python",
"raw_input",
"time"
] | stackoverflow_0024915577_duration_input_python_raw_input_time.txt |
Q:
Unable to change data type from nested dictionary in list
How do I change data type in a list of nested dictionary?
I have tried the following code but I keep receiving a invalid argument.
results = json.load(response)
for date in results:
last_update = datetime.datetime.fromtimestamp(date[0]['lastUpdatedAt']... | Unable to change data type from nested dictionary in list | How do I change data type in a list of nested dictionary?
I have tried the following code but I keep receiving a invalid argument.
results = json.load(response)
for date in results:
last_update = datetime.datetime.fromtimestamp(date[0]['lastUpdatedAt'])
date[0]['lastUpdatedAt'] = last_update
print(results)
j... | [
"Try like this:\nimport datetime\n\nprint(results[0]['lastUpdatedAt'])\nresults[0]['lastUpdatedAt'] = datetime.datetime.fromtimestamp(results[0]['lastUpdatedAt'])\nprint(results[0]['lastUpdatedAt'])\n\nOutput\n1578265850\n2020-01-06 04:10:50\n\n",
"The issue was related to the for loop in which I did not divide i... | [
0,
0
] | [] | [] | [
"dictionary",
"for_loop",
"json",
"list",
"python"
] | stackoverflow_0074163596_dictionary_for_loop_json_list_python.txt |
Q:
How to Judge the same thread in python?
The threads has the same thread ident but diffent pid, Is it the same thread? Why they has the same thread ident? how can i Judge the same thread?
def send_pic(txt):
print(f'send_pic {txt} pid:{os.getpid() } tid:{threading.current_thread().ident}')
time.sleep(4)
... | How to Judge the same thread in python? | The threads has the same thread ident but diffent pid, Is it the same thread? Why they has the same thread ident? how can i Judge the same thread?
def send_pic(txt):
print(f'send_pic {txt} pid:{os.getpid() } tid:{threading.current_thread().ident}')
time.sleep(4)
print('send_pic %s ..ok ' % txt)
ret... | [
"\nIs it the same thread?\n\nThose messages appear to have been printed by two different processes. Any given thread can only exist in one process. So, No, It is not possible for the same thread to have printed both of those two messages.\n\nFYI: The threading.Thread.native_id attribute is supposed to be unique amo... | [
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0074161677_multithreading_python.txt |
Q:
Find patterns in a music
Let's say I have a piece of music, and I want to find patterns that reproduces themselves so that I can cut out certain areas without it being audible.
For example :
What would be the best approach in python?
I thought about generating a waveform and then slicing it into images to find tw... | Find patterns in a music | Let's say I have a piece of music, and I want to find patterns that reproduces themselves so that I can cut out certain areas without it being audible.
For example :
What would be the best approach in python?
I thought about generating a waveform and then slicing it into images to find two similar ones but I don't kn... | [
"you can split signal into buffers and compare it with fft. If the result of the fft differs from previous one by certain specified value, you can divide the part... but this really depends on what kind of music you are doing this alorithm for - for example, for house music it could be problematic to distinguish pa... | [
0,
0
] | [] | [] | [
"audio",
"python",
"signals"
] | stackoverflow_0069210178_audio_python_signals.txt |
Q:
py to apk using Google Colab
Am trying to convert a .py application to an apk file using Google Colab but I keep encountering this error:
[DEBUG]: ERROR: Could not find a version that satisfies the requirement kivy-deps.angle (from versions: none)
[DEBUG]: ERROR: No matching distribution found for kivy-deps.... | py to apk using Google Colab | Am trying to convert a .py application to an apk file using Google Colab but I keep encountering this error:
[DEBUG]: ERROR: Could not find a version that satisfies the requirement kivy-deps.angle (from versions: none)
[DEBUG]: ERROR: No matching distribution found for kivy-deps.angle
I am using Python 3.9.9 and... | [
"Try putting pillow in the requirements, it might work.\nrequirements = python3, kivy, docutils, kivy-deps.angle, kivy-deps.glew, kivy-deps.sdl2, Kivy-Garden, pygments, pypiwin32, pillow\n",
"Kivy 2.1.0 officially supports Python versions 3.7 - 3.10.\nhttps://kivy.org/doc/stable/gettingstarted/installation.html\n... | [
0,
0
] | [] | [] | [
"android",
"kivy",
"python"
] | stackoverflow_0074138584_android_kivy_python.txt |
Q:
C++ PyObject Python-Type detect/check?
How can I detect / check the Python-Type of a PyObject?
PyObject_HasAttrString can be used to check, but how do I get the AttrString of a given PyObject?
int modify(cv::cuda::GpuMat* cVal, py::object &pobj)
{
py::handle ptype = pobj.get_type(); //?? ...
PyObject *po... | C++ PyObject Python-Type detect/check? | How can I detect / check the Python-Type of a PyObject?
PyObject_HasAttrString can be used to check, but how do I get the AttrString of a given PyObject?
int modify(cv::cuda::GpuMat* cVal, py::object &pobj)
{
py::handle ptype = pobj.get_type(); //?? ...
PyObject *pobject = pobj.ptr();
auto typeCheck = PyO... | [
"Presumably you know what type it should be so you can check if you can convert to that type, for example: PyTuple_Check, PyUnicode_Check, etc.\nAssuming you are using numpy arrays, I would look at PyArray_FROM_OTF which will return an ndarray from any Python object that can be converted into an array:\n PyArray... | [
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0074142374_c++_python.txt |
Q:
How do i fix this "convert list to BST" problem?
why isn't my Tree object retaining the values i pass it?
It always keeps on printing None each time i run the script.
class:
class Tree:
def __init__(self,key=None):
self.left,self.right = None,None
self.key = key
def insert(key):
re... | How do i fix this "convert list to BST" problem? | why isn't my Tree object retaining the values i pass it?
It always keeps on printing None each time i run the script.
class:
class Tree:
def __init__(self,key=None):
self.left,self.right = None,None
self.key = key
def insert(key):
return Tree(key)
def convert(self,list):
if... | [
"The problem is that your convert method doesn't do anything with the current value of self, but overwrites it. The main program calls the method on tree (which is self in the function), but as self is discarded and another value is assigned to this local name, the main's tree remains unaltered.\nIt is also apparen... | [
0
] | [] | [] | [
"binary_search_tree",
"class",
"python",
"recursion"
] | stackoverflow_0074163944_binary_search_tree_class_python_recursion.txt |
Q:
How to determine path to php.exe on Windows - search default paths
I'm currently developing a couple of plugins for Sublime Text 2 on OS X and I would like to make them cross platform, meaning I have to find out if and where php.exe is installed.
Right now I call /usr/bin/php in Python, which obviously works only ... | How to determine path to php.exe on Windows - search default paths | I'm currently developing a couple of plugins for Sublime Text 2 on OS X and I would like to make them cross platform, meaning I have to find out if and where php.exe is installed.
Right now I call /usr/bin/php in Python, which obviously works only on OS X and Linux:
phppath = '/usr/bin/php'<br>
pluginpath = sublime.pac... | [
"If the user has added PHP's bin folder to the system PATH, then you should just be able to try and execute php -v to check that it's present.\nIf you want to obtain the full path to the PHP executable and the target system is Windows Server 2003 or later (so Windows Vista, and Windows 7) then you could use the WHE... | [
47,
7,
6,
1,
0
] | [
"Try\necho PHP_BINDIR;\n\nIt works. I tested it on macOS as with PHP 5.6.\n"
] | [
-2
] | [
"path",
"php",
"python",
"sublimetext",
"windows"
] | stackoverflow_0009645545_path_php_python_sublimetext_windows.txt |
Q:
How to sum the values in specific rows of Pandas DataFrame into one row?
I am working on a chat analyzer, and trying to make a pie chart for most active users. Suppose I have the following data.
Name
Number of messages
A
234
B
128
C
112
D
97
E
86
F
43
G
32
H
24
I
22
J
9
I want to convert it into the fo... | How to sum the values in specific rows of Pandas DataFrame into one row? | I am working on a chat analyzer, and trying to make a pie chart for most active users. Suppose I have the following data.
Name
Number of messages
A
234
B
128
C
112
D
97
E
86
F
43
G
32
H
24
I
22
J
9
I want to convert it into the following
Name
Number of messages
A
234
B
128
C
11... | [
"Use df.where to convert names outside of a defined list to Other:\n# If name is A, B, C, D or E, keep it. Otherwise, change it to Other\nname = df[\"Name\"].where(df[\"Name\"].isin([\"A\", \"B\", \"C\", \"D\" ,\"E\"]), \"Other\")\n\ndf.groupby(name)[\"Number of messages\"].sum()\n\n",
"Try this:\n# Find rows tha... | [
2,
1,
1
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074163865_group_by_pandas_python.txt |
Q:
Plotly: No renderer could be found for mimetype "application/vnd.plotly.v1+json"
Environment:
Visual Code
Jupyter extension (v2022.9.1202862440)
Kernel: Python 3.10.1 64-bit
Pyplot version: 5.10.0
Nbformat version: 5.7.0
What happened?
I am trying to use simple boxplot with plotly.express via this code:
#Basic v... | Plotly: No renderer could be found for mimetype "application/vnd.plotly.v1+json" | Environment:
Visual Code
Jupyter extension (v2022.9.1202862440)
Kernel: Python 3.10.1 64-bit
Pyplot version: 5.10.0
Nbformat version: 5.7.0
What happened?
I am trying to use simple boxplot with plotly.express via this code:
#Basic vizualization
fig = px.box(dataset, y='Rh2')
fig.update_layout(
height=1000
)
Firs... | [
"Try to install Jupyter Notebook Rdnderers extension on vscode it works for me\n"
] | [
2
] | [] | [] | [
"nbformat",
"pandas",
"plotly",
"python"
] | stackoverflow_0074046983_nbformat_pandas_plotly_python.txt |
Q:
Finding Missing Letters
I'm currently trying to create a function that counts the frequency of characters in in a string. I need to store it in a dictionary in ASCII code. From this dictionary I need to calculate which letters do not appear in the string.
enter image description here
import string
result=string.as... | Finding Missing Letters | I'm currently trying to create a function that counts the frequency of characters in in a string. I need to store it in a dictionary in ASCII code. From this dictionary I need to calculate which letters do not appear in the string.
enter image description here
import string
result=string.ascii_uppercase
print(result)
... | [
"You are almost there. Just transform the string to a set first, then subtract the letters from the letters of the alphabet.\ndef find_missing_letter(string_1):\n return set(string.ascii_uppercase) - set(string_1)\n\nresult = find_missing_letter(string_1)\nprint(result) # {'A', 'P', 'Q', 'R', 'Z'}\nprint(f'Numb... | [
1
] | [] | [] | [
"ascii",
"frequency",
"python"
] | stackoverflow_0074163277_ascii_frequency_python.txt |
Q:
Django - Automatically Create Model When Creating User
I have a Student Model, which should extend the Base User Model. Now I did this with a One to One Relation, but once my WebApp is done, I'd like to be able to create all the Users fast. Is there a way of adding all the fields of the Student Model into the User... | Django - Automatically Create Model When Creating User | I have a Student Model, which should extend the Base User Model. Now I did this with a One to One Relation, but once my WebApp is done, I'd like to be able to create all the Users fast. Is there a way of adding all the fields of the Student Model into the User Creating Panel in /admin/? Here is my User Model for anyone... | [
"You can use signals.\n# <appname>/signals.py\n\nfrom django.dispatch import receiver\nfrom django.db import models\nfrom django.contrib.auth import get_user_model\nfrom <model_path> import Student\n\n@receiver(models.signals.post_save, sender=get_user_model())\ndef create_student_after_user_init(sender, instance, ... | [
0
] | [] | [] | [
"class",
"django",
"model",
"python"
] | stackoverflow_0074162698_class_django_model_python.txt |
Q:
pyautogui distance between 2 or more objects
im tryin to make it move to player (detected image or texture) and then scan for near by objects like images or textures
my code:
it looks for an image in the screen and moves mouse to it
import pyautogui
def detect():
L1 = pyautogui.locateCenterOnScreen('danger/pla... | pyautogui distance between 2 or more objects | im tryin to make it move to player (detected image or texture) and then scan for near by objects like images or textures
my code:
it looks for an image in the screen and moves mouse to it
import pyautogui
def detect():
L1 = pyautogui.locateCenterOnScreen('danger/player.png')
pyautogui.moveTo(L1)
while True:
... | [
"To find out of the image is near the mouse position, you'll need to find the distance between them.\nIf the image is found pyautogui.locateCenterOnScreen(image_path) will return a pair (x, y) for the centre of the image.\npyautogui.position() will also return a pair (x, y) for the mouse position.\nYou can then fin... | [
0
] | [] | [] | [
"pyautogui",
"python"
] | stackoverflow_0074164010_pyautogui_python.txt |
Q:
converting mp3 to wav using ffmpeg and pydub
I am trying to convert mp3 file into wav using below code:
from os import path
from pydub import AudioSegment
# assign files
input_file = "recording.mp3"
output_file = "result.wav"
# convert mp3 file to wav file
sound = AudioSegment.from_mp3(input_file)
sound.export(o... | converting mp3 to wav using ffmpeg and pydub | I am trying to convert mp3 file into wav using below code:
from os import path
from pydub import AudioSegment
# assign files
input_file = "recording.mp3"
output_file = "result.wav"
# convert mp3 file to wav file
sound = AudioSegment.from_mp3(input_file)
sound.export(output_file, format="wav")
This is the error:
| [
"Try this:\nimport subprocess\n\n# convert wav to mp3\nsubprocess.call(['ffmpeg', '-i', source_path,\n destination_path])\n\n"
] | [
0
] | [] | [] | [
"ffmpeg",
"python",
"python_3.x"
] | stackoverflow_0074163232_ffmpeg_python_python_3.x.txt |
Q:
elegant way to code if/elif/else statement
indepgroupl = ['numerical', 'categorical']
depgroupl = ["numerical", "categorical", "factors", "count"]
for i in indepgroupl:
for j in depgroupl:
if i == 'categorical':
if i == 'numerical':
if j == 'numerical':
... | elegant way to code if/elif/else statement | indepgroupl = ['numerical', 'categorical']
depgroupl = ["numerical", "categorical", "factors", "count"]
for i in indepgroupl:
for j in depgroupl:
if i == 'categorical':
if i == 'numerical':
if j == 'numerical':
print("utter_indepnumcat_depnum")
... | [
"You can store the conditional value and the string to print in a tupled list\nfor cat, val in [('numerical', 'depnum'), ('categorical', 'depcat'), ('time to event', 'deptimetoevent')]:\n if i == cat:\n print ('utter_indepnumcat_' + val)\n\nFor just three entries you don't save much lines of code; it make... | [
0,
0
] | [] | [] | [
"if_statement",
"pep8",
"python"
] | stackoverflow_0074164090_if_statement_pep8_python.txt |
Q:
How can i scrape multiple values with the same name from a json with python?
Was trying to scrape the stock quantities for a product on this link:
https://sizeer.ro/v2/products/searchnearpos?address=44.4199549%2C26.1238619&distance=50&product=3046070
This is the json that gives as response:
{"pos":[{"id":"1110","n... | How can i scrape multiple values with the same name from a json with python? | Was trying to scrape the stock quantities for a product on this link:
https://sizeer.ro/v2/products/searchnearpos?address=44.4199549%2C26.1238619&distance=50&product=3046070
This is the json that gives as response:
{"pos":[{"id":"1110","name":"BUCURESTI MALL SIZEER","code":"RO31","slug":"bucuresti-mall-sizeer","warehou... | [
"Maybe you should try css selectors. How to Scrape JSON Data Using Scrapy this link seems to be related to your problem. You can have a look.\n",
"This works! :)\nfor i in responsejs[\"pos\"]:\n av = i[\"availability_variants\"]\n # Check if the stock check is available\n if av:\n # If available a... | [
0,
0,
0,
0,
0
] | [] | [] | [
"json",
"python",
"python_3.x",
"web_scraping"
] | stackoverflow_0074163883_json_python_python_3.x_web_scraping.txt |
Q:
darknet_images.py: error: unrecognized arguments: --output ../demo_out2
I have trained the Yolo4 model with a custom dataset in Google Colab mounted with googlge drive. My trained model yolov4-custom_best.weights file is ready on a drive folder and I have input my training image, I want to generate output from the... | darknet_images.py: error: unrecognized arguments: --output ../demo_out2 | I have trained the Yolo4 model with a custom dataset in Google Colab mounted with googlge drive. My trained model yolov4-custom_best.weights file is ready on a drive folder and I have input my training image, I want to generate output from the input images using this below code:
My last training model:
!./darknet detec... | [
"!python darknet_images.py --thresh 0.2 --input ../b076ad266891d7aa.jpg --output ../demo_out --weights ../training/yolov4-custom_best.weights --config_file ./cfg/yolov4-custom.cfg --data_file ./data/obj.data\nIn this code you didn't specify the type of file in output it is jpg,mp4 etc.\nI hope this will help you :... | [
0
] | [] | [] | [
"google_colaboratory",
"python",
"yolo"
] | stackoverflow_0072746894_google_colaboratory_python_yolo.txt |
Q:
Replace all words from word list with another string in python
I have a user entered string and I want to search it and replace any occurrences of a list of words with my replacement string.
import re
prohibitedWords = ["MVGame","Kappa","DatSheffy","DansGame","BrainSlug","SwiftRage","Kreygasm","ArsonNoSexy","Ging... | Replace all words from word list with another string in python | I have a user entered string and I want to search it and replace any occurrences of a list of words with my replacement string.
import re
prohibitedWords = ["MVGame","Kappa","DatSheffy","DansGame","BrainSlug","SwiftRage","Kreygasm","ArsonNoSexy","GingerPower","Poooound","TooSpicy"]
# word[1] contains the user entere... | [
"You can do that with a single call to sub:\nbig_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))\nthe_message = big_regex.sub(\"repl-string\", str(word[1]))\n\nExample:\n>>> import re\n>>> prohibitedWords = ['Some', 'Random', 'Words']\n>>> big_regex = re.compile('|'.join(map(re.escape, prohibitedWords... | [
36,
6,
1,
0
] | [] | [] | [
"for_loop",
"python",
"replace",
"text"
] | stackoverflow_0015658187_for_loop_python_replace_text.txt |
Q:
Selenium .text() doesn't get all text from webpage, and also doesn't omit strikeout text ()
Hi i'm having issues with selenium
My first issue is that when scraping, I accidentally obtain all "strike class" (striked-out) text from the below link, and I want to avoid that text.
My second issue is that selenium won't... | Selenium .text() doesn't get all text from webpage, and also doesn't omit strikeout text () | Hi i'm having issues with selenium
My first issue is that when scraping, I accidentally obtain all "strike class" (striked-out) text from the below link, and I want to avoid that text.
My second issue is that selenium won't capture all the text from my webpage --Selenium gets about half of the text from the below link ... | [
"You do not need the overheads of Selenium to obtain the text from that page, it can be acomplished with Requests and BeautifulSoup, like below (also ignoring the strikeout texts):\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\nr = requests.get('https://custom.statenet.com/public/resources.cgi?id=ID:bill:... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"text",
"web_scraping"
] | stackoverflow_0074164005_python_selenium_selenium_webdriver_text_web_scraping.txt |
Q:
my pip3 is broken, I can't use it in any way
I don't know how this happened but I can't do anything with pip, even when I do a pip3 --version I get these errors also, can not use pip in any way.
things I did before it got broken:
I tried to get some packages from GitHub
couldn't run packages so tried to install r... | my pip3 is broken, I can't use it in any way | I don't know how this happened but I can't do anything with pip, even when I do a pip3 --version I get these errors also, can not use pip in any way.
things I did before it got broken:
I tried to get some packages from GitHub
couldn't run packages so tried to install requirements.
then I got these errors, I looked up ... | [
"rm -rf /home/randle/.local/lib/python3.8/site-packages/OpenSSL*\nrm -rf /home/randle/.local/lib/python3.8/site-packages/pyOpenSSL*\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"python_3.x"
] | stackoverflow_0074163190_pip_python_python_3.x.txt |
Q:
How to avoid automated action beeing executed based on condition ? - Odoo
In Projects Module I created a automated action, which creates a new Project name, based on some fields from the sales order. When a project is automatically created from an confirmed sales order the automated action works fine.
Problem is t... | How to avoid automated action beeing executed based on condition ? - Odoo | In Projects Module I created a automated action, which creates a new Project name, based on some fields from the sales order. When a project is automatically created from an confirmed sales order the automated action works fine.
Problem is that when I want to create an project manually, the automated action is also cal... | [
"Maybe it's better to include your action inside the sale-order model, instead of using automated actions. you could do it like this:\nfrom odoo import api, models\n\n\nclass Order(models.Model):\n _inherit = \"sale.order\"\n\n def action_confirm(self):\n super().action_confirm()\n self._on_orde... | [
0
] | [] | [] | [
"action",
"odoo",
"odoo_15",
"python"
] | stackoverflow_0074123506_action_odoo_odoo_15_python.txt |
Q:
Subtype Polymorphism is broken in Cython v30.0.0a11?
Trying to pass an instance of a derived class to a function which accepts instances of the superclass gives an error in Cython v3.0.0a11:
test.pyx:
class MyInt(int):
pass
def takes_int(a: int):
pass
try.py:
from test import takes_int, MyInt
takes_int(... | Subtype Polymorphism is broken in Cython v30.0.0a11? | Trying to pass an instance of a derived class to a function which accepts instances of the superclass gives an error in Cython v3.0.0a11:
test.pyx:
class MyInt(int):
pass
def takes_int(a: int):
pass
try.py:
from test import takes_int, MyInt
takes_int(MyInt(1))
try.py OUTPUT:
Traceback (most recent call last... | [
"This is (kind of) expected.\nCython has never allowed subtype polymorphism for builtin type arguments. See https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#types:\n\nThis requires an exact match of the class, it does not allow subclasses. This allows Cython to optimize code by accessing i... | [
2
] | [] | [] | [
"cython",
"python"
] | stackoverflow_0074164169_cython_python.txt |
Q:
How to set X-Axis values as dates in matplotlib?
I am generating a plot from a ML model which is predicting stock prices from yahoo finance.
The plot consists of actual_prices + predicted_prices.
I want to change the x axis values to my test data time range, but this removes the plots completely when I try to set ... | How to set X-Axis values as dates in matplotlib? | I am generating a plot from a ML model which is predicting stock prices from yahoo finance.
The plot consists of actual_prices + predicted_prices.
I want to change the x axis values to my test data time range, but this removes the plots completely when I try to set an xlim.
I want these same plots but with the 0-500 x ... | [
"You need to submit the indices themselves, i.e. Date and then the price data. Below I give an example with two lines, the data has different lengths, I took the data through the slice and placed it for drawing. If there is no Date data for predicted prices, then you need to create one and put it in ax.plot.\nimpor... | [
0
] | [] | [] | [
"datetime",
"matplotlib",
"plot",
"python",
"time_series"
] | stackoverflow_0074158868_datetime_matplotlib_plot_python_time_series.txt |
Q:
Unable to use Github API with authentication tuple
query = "https://api.github.com/repos/rhinstaller/anaconda/tags"
response = requests.get(query,auth=(self.username,self.token))
response.raise_for_status() # raises exception when not a 2xx
if response.status_code != 204:
try:
data = re... | Unable to use Github API with authentication tuple | query = "https://api.github.com/repos/rhinstaller/anaconda/tags"
response = requests.get(query,auth=(self.username,self.token))
response.raise_for_status() # raises exception when not a 2xx
if response.status_code != 204:
try:
data = response.json()
print("data = ",data)
... | [
"The error says you have incorrect credentials\nimport requests\nfrom requests.auth import HTTPBasicAuth\n \n# Making a get request\nresponse = requests.get('https://api.github.com/user, ',\n auth = HTTPBasicAuth('user', 'token'))\n \n# print request object\nprint(response)\n\nRef: https://www.geeksfor... | [
0
] | [] | [] | [
"github",
"github_api",
"python"
] | stackoverflow_0074164118_github_github_api_python.txt |
Q:
The STATICFILES_DIRS setting is not a tuple or list. Eventhough it did not contain a comma
HI I am new to static files but I got this error called STATICFILES_DIRS setting is not a tuple or list. Which I do not understand as it is does not contain any commas. I hope someone can help me. Yes, I have imported os.
Tr... | The STATICFILES_DIRS setting is not a tuple or list. Eventhough it did not contain a comma | HI I am new to static files but I got this error called STATICFILES_DIRS setting is not a tuple or list. Which I do not understand as it is does not contain any commas. I hope someone can help me. Yes, I have imported os.
Traceback:
ERRORS:
?: (staticfiles.E001) The STATICFILES_DIRS setting is not a tuple or list.
... | [
"Thanks to @fsimonjetz for helping me answer this question I changed this:\nSTATICFILES_DIRS = (os.path.join(BASE_DIR, '')\n\n)\nto\n STATICFILES_DIRS = (os.path.join(BASE_DIR, ''),)\n\n",
"For people who didn't understand why this error still shown even the location of directory is exist and clear.\nDjango asks ... | [
2,
0
] | [] | [] | [
"python",
"static"
] | stackoverflow_0068347817_python_static.txt |
Q:
Why will this program not move the player room to room?
def show_instructions():
if __name__ == "__main__":
while True:
print('Dragon Text Game\n')
print('\t\t\tDragon Text Game.')
print('---------------------------------------------------------------------------------------
------')
... | Why will this program not move the player room to room? | def show_instructions():
if __name__ == "__main__":
while True:
print('Dragon Text Game\n')
print('\t\t\tDragon Text Game.')
print('---------------------------------------------------------------------------------------
------')
print('Move commands: South, North, East, West')
print('Type... | [
"Try changing directions to be\ndirections = ['NORTH', 'SOUTH', 'EAST', 'WEST']\n\nAnd changing if command in directions: to if command.upper() in directions:\nYour code currently does not work because it is case sensitive. If you enter, South instead of south you will likely be able to move from room to room. By... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074164274_python.txt |
Q:
How to get mempool pending transactions using web3.py and Chainstack websocket
How to subscribe to chainstack node websocket to receive mempool pending transactions using web3.py
from web3 import Web3
w3 = Web3(Web3.WebsocketProvider('wss://ws-nd-732-321-545.p2pify.com/XXXXXXXXXXXXX'))
print(w3.eth.blockNumber)
su... | How to get mempool pending transactions using web3.py and Chainstack websocket | How to subscribe to chainstack node websocket to receive mempool pending transactions using web3.py
from web3 import Web3
w3 = Web3(Web3.WebsocketProvider('wss://ws-nd-732-321-545.p2pify.com/XXXXXXXXXXXXX'))
print(w3.eth.blockNumber)
subscription = w3.eth.filter('pending')
need rest of the code
| [
"I'm with Chainstack. For anyone looking for this, we have the working instructions in our knowledge base: Subscribing to global new pending transactions with web3.js.\n"
] | [
0
] | [] | [] | [
"ethereum",
"python",
"web3py"
] | stackoverflow_0069760348_ethereum_python_web3py.txt |
Q:
Django Models Decimal quantize result has too many digits for current context
Until today i got my models like that:
class Ambiente1m(models.Model):
Zona = models.CharField(max_length=10,default=0)
Timestamp = models.DateTimeField(default=datetime.datetime.now)
Temperatura1 = models.IntegerField()
... | Django Models Decimal quantize result has too many digits for current context | Until today i got my models like that:
class Ambiente1m(models.Model):
Zona = models.CharField(max_length=10,default=0)
Timestamp = models.DateTimeField(default=datetime.datetime.now)
Temperatura1 = models.IntegerField()
Humedad1 = models.IntegerField()
But i tried to get Temperatura and Humedad as a D... | [
"The problem was that Django was trying to migrate an old version of migration file instead of the new one. I don't know why.\nI have solved this editing that file with new customization and deleting the .pyc file forcing to reload it.\n",
"I came across this error, I noticed that the name is taken by many attrib... | [
0,
0
] | [] | [] | [
"django",
"django_models",
"models",
"postgresql",
"python"
] | stackoverflow_0042352973_django_django_models_models_postgresql_python.txt |
Q:
K-Means Clustering Output seems wrong, how can it be explained?
I have a custom dataset that I want to partion using kmeans. This is my MCVE:
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
samples = np.array([[3.2736001e+03, 1.7453293e+00], [3.7256001e+03, 5.2359879e-02], [3.2960000e+03, 1.7366... | K-Means Clustering Output seems wrong, how can it be explained? | I have a custom dataset that I want to partion using kmeans. This is my MCVE:
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
samples = np.array([[3.2736001e+03, 1.7453293e+00], [3.7256001e+03, 5.2359879e-02], [3.2960000e+03, 1.7366025e+00], [3.7112000e+03, 4.3633230e-02],
[3.7136001e... | [
"The data is not scaled properly. The x-dimension is scaled between 500 and 3500 while the y-dimension is scaled between 0 and 1.75.\nThe figure hides this, but the two \"blobs\" on the left look more like parallel lines when scaled properly.\nIf we focus on the part of the data where the x-dimension is less than 1... | [
1
] | [] | [] | [
"k_means",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074163700_k_means_machine_learning_python_scikit_learn.txt |
Q:
time.sleep stops stops whole program
I'm new at python, was trying to do a Paper Rock Scissors game with tkinter.
I did all, but I want to do a 1 sec pause before you can play again. When I use time.sleep(1) it stops program before results of game are shown(code below) however I put time.sleep(1) AFTER it
from tk... | time.sleep stops stops whole program | I'm new at python, was trying to do a Paper Rock Scissors game with tkinter.
I did all, but I want to do a 1 sec pause before you can play again. When I use time.sleep(1) it stops program before results of game are shown(code below) however I put time.sleep(1) AFTER it
from tkinter import *
import time
import random
... | [
"Your code is single threaded meaning that if you add a time.sleep(), it will block the excecution of the rest of your code resulting in the whole program pausing. To mitigate this you need to start the game process in a seperate thread to the UI, this will only sleep the code in your game thread and not your UI th... | [
3
] | [] | [] | [
"python",
"time",
"tkinter"
] | stackoverflow_0074164352_python_time_tkinter.txt |
Q:
founding the precision of a float in python based on a different float number
So, let's say there is a float number: 0.11910000
and here is a list of numbers: 11970, 12020, 12070, 12165, 12400, 11100
I need them to turn to: 0.11970, 0.12020, 0.12070, etc... this is based on the the the decimal point in the float n... | founding the precision of a float in python based on a different float number | So, let's say there is a float number: 0.11910000
and here is a list of numbers: 11970, 12020, 12070, 12165, 12400, 11100
I need them to turn to: 0.11970, 0.12020, 0.12070, etc... this is based on the the the decimal point in the float number is 0.1191, if it were 1.191 then the numbers would have been 1.197, 1.202, 1.... | [
"We need two functions, one of which finds the exponent of a number:\ndef find_exponent(n):\n return math.floor(math.log10(abs(n)))\n\nfind_exponent(0.01) -2\nfind_exponent(0.1) -1\nfind_exponent(1) 0\nfind_exponent(10) 1\nfind_exponent(100) 2\n\nAnd another function that takes one number and shif... | [
3,
1
] | [] | [] | [
"math",
"python",
"python_3.x"
] | stackoverflow_0074163682_math_python_python_3.x.txt |
Q:
How can I write the path in Python on a Windows?
I'm currently trying to set up a webdriver, and I just realised the reason it's not working is because I can't get the path to work. Currently, I'm trying basic code:
file = "D:\\"
if os.path.exists(file):
print(True)
else:
print(False)
And the answer is "F... | How can I write the path in Python on a Windows? | I'm currently trying to set up a webdriver, and I just realised the reason it's not working is because I can't get the path to work. Currently, I'm trying basic code:
file = "D:\\"
if os.path.exists(file):
print(True)
else:
print(False)
And the answer is "False". Now, I do have a D:/ drive on my computer.
I tr... | [
"file = \"D:/\"\n\nUsually works, you could try a raw string literal if you are still having problems:\nfile = r'D:\\'\n\nYou can also look into the excellent pathlib if you find yourself doing a lot of work with paths, such as constructing and joining. The documentation is available here\n",
"Could be a problem ... | [
0,
0
] | [
"You can use - 'C:/mydir'\nhope it should work.\n"
] | [
-1
] | [
"path",
"python",
"windows"
] | stackoverflow_0074164048_path_python_windows.txt |
Q:
Find a closing brace pair, skipping internal open/close pairs, in Python
I have a string that starts "{{ABC..." and which will also contain a closing brace pair. The problem is that it may also contain nested open/close brace pairs, and may contain further brace pairs after the matching closing pair. E.g. this i... | Find a closing brace pair, skipping internal open/close pairs, in Python | I have a string that starts "{{ABC..." and which will also contain a closing brace pair. The problem is that it may also contain nested open/close brace pairs, and may contain further brace pairs after the matching closing pair. E.g. this is possible:
{{ABC foo bar {{baz}} {{fred}} foo2}} other text {{other brace... | [
"You can find all enclosed substrings by scanning the input string only once.\nThe only thing you need is to record the number of left braces you have met. Increase it when you see left brace and decrease it when seeing right brace. When it decreases to 0 you get an enclosed substring.\ndef find_enclosed_string(str... | [
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074164066_python_regex.txt |
Q:
separate values using "," as my delimiter
I have a data set with multiple values for a single column I am trying to separate them using "," as my delimiter.
my data looks like this:
A: B: C:
1 A,B,C,D Square
2 E,F Triangle
3 G,H,I Circle... | separate values using "," as my delimiter | I have a data set with multiple values for a single column I am trying to separate them using "," as my delimiter.
my data looks like this:
A: B: C:
1 A,B,C,D Square
2 E,F Triangle
3 G,H,I Circle
I am trying to process it in such a way as to... | [
"First split the column values using Series.str.split then explode the column:\n>>> df.assign(B=df['B'].str.split(',')).explode('B')\n\n A B C\n0 1 A Square\n0 1 B Square\n0 1 C Square\n0 1 D Square\n1 2 E Triangle\n1 2 F Triangle\n2 3 G Circle\n2 3 H Circle\n2 3 I ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074164402_dataframe_pandas_python.txt |
Q:
redshift_connector: TimeoutError: [Errno 60] Operation timed out
I want to connect to a Redshift Cluster using the redshift_connector library in python.
The cluster is publicly accessible
The associated security group has my hosts IP address added to Inbound rules: Redshift, port 5439 and Whole inbound traffic. Sa... | redshift_connector: TimeoutError: [Errno 60] Operation timed out | I want to connect to a Redshift Cluster using the redshift_connector library in python.
The cluster is publicly accessible
The associated security group has my hosts IP address added to Inbound rules: Redshift, port 5439 and Whole inbound traffic. Same goes for outgoing traffic.
This is how I try to make the connection... | [
"I have found the error:\nI also have to add the inbound rule to allow connections to redshift from 0.0.0.0/0\n"
] | [
0
] | [] | [] | [
"amazon_redshift",
"amazon_web_services",
"python"
] | stackoverflow_0074163886_amazon_redshift_amazon_web_services_python.txt |
Q:
How to share code across python docker services inside monorepo
I have common python code I want to share across services. I currently have a modular monolith but I would like to break it out into a few independent containers.
Ideally the layout would look like the following:
/project
/common
/service-a
... | How to share code across python docker services inside monorepo | I have common python code I want to share across services. I currently have a modular monolith but I would like to break it out into a few independent containers.
Ideally the layout would look like the following:
/project
/common
/service-a
/service-b
I am looking to avoid having to version and publish the... | [] | [] | [
"well, if your using git\nyou can create a .dockerignore file. to ignore the folders and files\n**/common\n\nthis should do the trick (it works for me)\n[sorry, I mistyped]\n"
] | [
-2
] | [
"containers",
"docker",
"monorepo",
"python"
] | stackoverflow_0074164408_containers_docker_monorepo_python.txt |
Q:
How to make sure random string in django python model will unique
I have a question with the random string in python django.
I have created a django model
class Post(models.Model):
slug = models.SlugField(unique=True,blank=True)
title = models.CharField(max_length=200)
description = models.TextField()
... | How to make sure random string in django python model will unique | I have a question with the random string in python django.
I have created a django model
class Post(models.Model):
slug = models.SlugField(unique=True,blank=True)
title = models.CharField(max_length=200)
description = models.TextField()
def save(self, *args, **kwargs):
str_ran = "abcdefghij... | [
"\nyou can create uniq index in database and cache errors when you write to database and get collisions\n\nyou can use (UUID + slag). UUID is generated based on current time, it allows to garanti uniqueness\nhttps://docs.python.org/3/library/uuid.html\n\n\n",
"You should use uuid instead of random.\nPython's uuid... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074161648_django_python.txt |
Q:
Jupyter in VS Code - how to change inline code code render in markdown?
I have an annoying problem, which I cannot find a solution to.
I'm using VS Code + Jupyter as my go-to tool for python projects. I've found out how to customize all colours / styles in it, except for inline code render in markdown. See 2 examp... | Jupyter in VS Code - how to change inline code code render in markdown? | I have an annoying problem, which I cannot find a solution to.
I'm using VS Code + Jupyter as my go-to tool for python projects. I've found out how to customize all colours / styles in it, except for inline code render in markdown. See 2 examples below.
Does anyone know what are the properties (settings.json?) that I n... | [
"The code style in the editor can be modified by the following configuration.\n// settings.json file\n\"editor.tokenColorCustomizations\": {\n \"[Default High Contrast]\": {\n \"textMateRules\": [\n {\n \"scope\":\"markup.inline.raw\",\n \"settings\": {\n ... | [
0,
0
] | [] | [] | [
"colors",
"jupyter",
"python",
"themes",
"visual_studio_code"
] | stackoverflow_0074038348_colors_jupyter_python_themes_visual_studio_code.txt |
Q:
How to issue POST requests to opensearch cluster in VPC?
I've deployed an opensearch cluster into a VPC. I have a VPC endpoint and can successfully issue GET requests to "VPC endpoint URL"/_cluster/settings to get the cluster config, but issuing POST requests to the same URL does not work. Should issuing POST requ... | How to issue POST requests to opensearch cluster in VPC? | I've deployed an opensearch cluster into a VPC. I have a VPC endpoint and can successfully issue GET requests to "VPC endpoint URL"/_cluster/settings to get the cluster config, but issuing POST requests to the same URL does not work. Should issuing POST requests to "VPC endpoint URL"/_cluster/settings work?
Looking at ... | [
"The resolution I discovered was signing the request. - https://docs.aws.amazon.com/opensearch-service/latest/developerguide/request-signing.html\nEx. -\nfrom opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth\nimport boto3\n\nhost = '' # cluster endpoint, for example: my-test-domain.us-east-1.... | [
1,
0
] | [] | [] | [
"amazon_opensearch",
"amazon_web_services",
"aws_lambda",
"opensearch",
"python"
] | stackoverflow_0073955496_amazon_opensearch_amazon_web_services_aws_lambda_opensearch_python.txt |
Q:
pyspark dataframe split column error. How to solve it?
df4[['Title','FirstName','LastName']]=df3.USER_FULL_NAME.str.split(r'\D', expand=True)
I got the below error.
TypeError Traceback (most recent call last)
Cell In [121], line 2
1 #df[['V','allele']] = df['V'].str.split('-'... | pyspark dataframe split column error. How to solve it? | df4[['Title','FirstName','LastName']]=df3.USER_FULL_NAME.str.split(r'\D', expand=True)
I got the below error.
TypeError Traceback (most recent call last)
Cell In [121], line 2
1 #df[['V','allele']] = df['V'].str.split('-',expand=True)
----> 2 df4[['Title','FirstName','LastName']]=... | [
"Assume that df3 is something like this:\n+---+--------------+\n| ID|USER_FULL_NAME|\n+---+--------------+\n| 1| Mr. AA BB|\n| 2| Mrs. BB CC|\n| 3| Dr. DD EE|\n| 4| PhD. FF GG|\n+---+--------------+\n\nYou can split the USER_FULL_NAME and create a new DataFrame with the following code:\ndf4 = df3.... | [
0
] | [] | [] | [
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074073469_dataframe_pyspark_python.txt |
Q:
How do I make a set of tuples of sets?
I understand that a set is not hashable and a tuple is. However,
a = ({1, 2, 3}, {2, 3, 5})
b = ({1, 7}, {3, 0})
{a, b}
returns TypeError: unhashable type: 'set'.
Why is that so?
EDIT:
Yes, sets are mutable and therefore unhashable. However, tuples, even though being immutab... | How do I make a set of tuples of sets? | I understand that a set is not hashable and a tuple is. However,
a = ({1, 2, 3}, {2, 3, 5})
b = ({1, 7}, {3, 0})
{a, b}
returns TypeError: unhashable type: 'set'.
Why is that so?
EDIT:
Yes, sets are mutable and therefore unhashable. However, tuples, even though being immutable, can have their elements change value AND... | [
"as you have already mentioned correctly, Python has both modifiable and non-changeable datatypes. Also correct is that a set is a mutable datatype, while a tuple is a non-changeable datatype. However, this is only true for the first level of a tuple and not for deeper levels, so it is not true for your objects.\nL... | [
0,
0
] | [] | [] | [
"python",
"set"
] | stackoverflow_0039885504_python_set.txt |
Q:
display an image from web using IPython.display.image: sometimes work, sometimes not
This has been solved. As pointed by James in the comment, the link that does not work is not a direct link to an image.
I'm learning python through a ipython notebook online. In the ipython notebook, an image from web is displaye... | display an image from web using IPython.display.image: sometimes work, sometimes not |
This has been solved. As pointed by James in the comment, the link that does not work is not a direct link to an image.
I'm learning python through a ipython notebook online. In the ipython notebook, an image from web is displayed using IPython.display.image. I tried it on my laptop and it works. However, when I try ... | [
"First you have to get image.\nsimply you can do it using requests\nimport requests\nimport IPython.display as Disp\nurl = 'https://upload.wikimedia.org/wikipedia/commons/5/56/Kosaciec_szczecinkowaty_Iris_setosa.jpg'\nDisp.Image(requests.get(url).content)\n\n",
"This is now available without requests in IPython u... | [
7,
0
] | [] | [] | [
"html",
"image",
"jupyter_notebook",
"python"
] | stackoverflow_0040645782_html_image_jupyter_notebook_python.txt |
Q:
How do I output results to a .csv file in Python?
I am new to Python and would like to write a script that that takes a .txt file as input and outputs the results to a .csv file.
The .txt files look as follows
text:eub1
region:euboea
μενανδρεσεμεεποισε
I would like to write a script that creates a new row for eac... | How do I output results to a .csv file in Python? | I am new to Python and would like to write a script that that takes a .txt file as input and outputs the results to a .csv file.
The .txt files look as follows
text:eub1
region:euboea
μενανδρεσεμεεποισε
I would like to write a script that creates a new row for each instance of μ or ν in the third line above. I also wa... | [
"Try:\nimport pandas as pd\n\ndata = {}\nwith open(\"your_file.txt\", \"r\") as f_in:\n for line in map(str.strip, f_in):\n if line == \"\":\n continue\n if line.startswith(\"text:\"):\n data[\"text\"] = line.split(\":\", maxsplit=1)[-1]\n elif line.startswith(\"region:... | [
0
] | [] | [] | [
"csv",
"data_wrangling",
"export_to_csv",
"python",
"text"
] | stackoverflow_0074164438_csv_data_wrangling_export_to_csv_python_text.txt |
Q:
is there a Python graph library that saves the graph as a image?
so I am making a discord bot and when you start it will generate your character with three traits.
async def PersonGenerator(ctx):
athour = ctx.author.mention
with open ("mainData.json", "r") as f:
Stfu = json.load(f)
if str(athou... | is there a Python graph library that saves the graph as a image? | so I am making a discord bot and when you start it will generate your character with three traits.
async def PersonGenerator(ctx):
athour = ctx.author.mention
with open ("mainData.json", "r") as f:
Stfu = json.load(f)
if str(athour.id) in Stfu:
Traits = ("Agile: +30 Attack Speed", "Ambitious... | [
"You can do just that with matplotlib\nHere is an example using a list of made up stats\nimport matplotlib.pyplot as plt\nstats = [2, 4, 7, 2, 4, 5, 2, 5, 1, 4]\nplt.pie(stats);\nplt.savefig('traits.png')\n\n"
] | [
0
] | [] | [] | [
"discord.py",
"graph",
"python"
] | stackoverflow_0074164477_discord.py_graph_python.txt |
Q:
How to update user details in custom user model in django
i just created a custom user model from abstractuser. I can create user but update is not working showing some error. I am also week in english so idk how to share my problem. In short hand i want to edit email and password of a user.
###This is my user mod... | How to update user details in custom user model in django | i just created a custom user model from abstractuser. I can create user but update is not working showing some error. I am also week in english so idk how to share my problem. In short hand i want to edit email and password of a user.
###This is my user model
class User(AbstractUser):
roles =(
('Admin','Adm... | [
"Yh, you'll get that error because the update method is available for only querysets.\nSo you can do this:\n\ndef editPlacementManager(request):\n\n if request.method=='POST':\n name=request.POST.get('name')\n phone=request.POST.get('phone')\n email=request.POST.get('email')\n passwor... | [
1,
0
] | [] | [] | [
"abstractuser",
"django",
"python"
] | stackoverflow_0074028352_abstractuser_django_python.txt |
Q:
Annotate results from related model method onto model Queryset?
I'm trying to figure out the best / most efficient way to get the 'progress' of a Summary object. A Summary object has X Grade objects - a Grade object is_complete when it has a Level chosen and has 1 or more related Evidence objects.
I am trying to t... | Annotate results from related model method onto model Queryset? | I'm trying to figure out the best / most efficient way to get the 'progress' of a Summary object. A Summary object has X Grade objects - a Grade object is_complete when it has a Level chosen and has 1 or more related Evidence objects.
I am trying to tie that Summary 'progress' to a Person.
The models.py look like this:... | [
"Would something like that work for you ?\nSummary.objects.alias(total_grades=Count(\"grade\"), finished_grades=Count(\"grade\", filter=Q(grade__evidences__isnull=False,level__isnull=False))).annotate(progress=F(\"finished_grades\") / F(\"total_grades\")).\n\nThe alias method allows for calculated values (that won'... | [
0,
0
] | [] | [] | [
"django",
"django_annotate",
"django_models",
"python"
] | stackoverflow_0074158649_django_django_annotate_django_models_python.txt |
Q:
Setting the aspect ratio of a Circle Patch in Matplotlib doesn't result in predicted ratio
I want to add a bunch of circles with equal aspect ratio to my plot, but the ratio of the datalimits of my x and y axis aren't equal. Therefore I tried to just create a regular circle of radius 1 first (which will be stretch... | Setting the aspect ratio of a Circle Patch in Matplotlib doesn't result in predicted ratio | I want to add a bunch of circles with equal aspect ratio to my plot, but the ratio of the datalimits of my x and y axis aren't equal. Therefore I tried to just create a regular circle of radius 1 first (which will be stretched if the datalimits ratio is, say 2:1).
from matplotlib.patches import Circle
circle = Circle(... | [
"Try trans = (fig.dpi_scale_trans + transform.ScaledTranslation(x, y, ax.transData)) where x and y are x- and y-coordinates of the center of the circle while keeping the argument xy as (0, 0) in matplotlib.patches.Circle.\nUtilising this, I have plotted a few circles with different radii at different positions:\n\n... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074124364_matplotlib_python.txt |
Q:
ModuleNotFound Pyinstaller
I am using:
PyInstaller 5.3
Python 3.9
Windows 11
I have my directories set up like so:
Project
|
+ -- DoSomething
| |
| +-- doessomething.py
|
+ -- GUIs
|
+--GUI_main.py
The .py files contain the following code:
doessomething.py
def doing():
print('Doing')
GU... | ModuleNotFound Pyinstaller | I am using:
PyInstaller 5.3
Python 3.9
Windows 11
I have my directories set up like so:
Project
|
+ -- DoSomething
| |
| +-- doessomething.py
|
+ -- GUIs
|
+--GUI_main.py
The .py files contain the following code:
doessomething.py
def doing():
print('Doing')
GUI_main.py
from DoSomething.doess... | [
"The short answer is that you're telling PyInstaller the wrong directory; you want to use -p /path/to/Project instead. This is because your DoSomething folder is inside the root Project directory. You're telling PyInstaller where to look for modules/packages that you try to import.\n\nFor a little more context...\n... | [
1,
0
] | [] | [] | [
"exe",
"pycharm",
"pyinstaller",
"python"
] | stackoverflow_0073495388_exe_pycharm_pyinstaller_python.txt |
Q:
Trying to understand If statements when trying to incorporate user Input
I'm an absolute beginner - like I'm Today-years-old with this.
So I'm mucking about with a silly little piece of code to try and help me understand If statements:
print ('How many sausages have you eaten today?')
userInput = ('>5' or '<5')
if... | Trying to understand If statements when trying to incorporate user Input | I'm an absolute beginner - like I'm Today-years-old with this.
So I'm mucking about with a silly little piece of code to try and help me understand If statements:
print ('How many sausages have you eaten today?')
userInput = ('>5' or '<5')
if userInput input == int ('> 5'):
print ('Whoa! Slow down Fatty!')
elif use... | [
"Here is a fixed version:\nThere is some notes to help you understand\n# To get an input you need to use input()\nuserInput = input('How many sausages have you eaten today?')\n# Turn the input from text to a number with int()\nuserInput = int(userInput)\nif userInput > 5:\n print ('Whoa! Slow down Fatty!')\nelif... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074164563_python.txt |
Q:
How to "log in" to a website using access_token
I am trying to post a request to log in to a website using the Requests module.
import requests
session = requests.Session()
url = '...'
payload = '{"email":"my_email@gmail.com","password":"12345678*"}'
HEADER = {"content-type": "application/json"}
r = session.post... | How to "log in" to a website using access_token | I am trying to post a request to log in to a website using the Requests module.
import requests
session = requests.Session()
url = '...'
payload = '{"email":"my_email@gmail.com","password":"12345678*"}'
HEADER = {"content-type": "application/json"}
r = session.post(url=url, data=payload, headers=HEADER)
<Response [... | [
"First: to POST JSON data to a server using requests, use json= parameter:\n# ...\n\npayload = {\"email\": \"my_email@gmail.com\", \"password\": \"12345678*\"} # <-- use dict here\nr = session.post(url=url, json=payload) # <-- use json= parameter\n\n#...\n\n\nIf the response from the server is:\n# data = r.json()\... | [
0
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0074164451_python_python_requests.txt |
Q:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() when using Numpy and Scipy
I am trying to compute an integral in Python using numpy and scipy.
This is my current code:
import scipy
import numpy as N
d = 160
w = 1.8
np = 265
def f(x):
return N.sin(N.powe... | ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() when using Numpy and Scipy | I am trying to compute an integral in Python using numpy and scipy.
This is my current code:
import scipy
import numpy as N
d = 160
w = 1.8
np = 265
def f(x):
return N.sin(N.power(x, 2))
inta = scipy.integrate.quad(f, 0, N.sqrt(N.divide(N.pi, 2)))
a = N.power((N.divide(N.multiply(N.multiply(2, N.sqrt(2)), inta)... | [
"By default, quad returns a tuple as: (value_of_integration, estimated_error).\nSo,\ninta, inta_error = integrate.quad(f, 0, N.sqrt(N.divide(N.pi, 2)))\n\nAnd\nx, x_error = integrate.quad(funx, 0, N.multiply(N.divide(1, np), s))\n\nMaybe You need type this, before all:\nimport scipy.integrate as integrate\n\n"
] | [
0
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0074160255_numpy_python_scipy.txt |
Q:
How to modify a GET request to trigger a file attachment response (legitimately)?
I have a Django project that uses the python chess module to show a chess board in the main view. It defaults to a blank board:
views.py
import chess, chess.pgn
def index(request, pgn_slug=None):
board = chess.Board()
game =... | How to modify a GET request to trigger a file attachment response (legitimately)? | I have a Django project that uses the python chess module to show a chess board in the main view. It defaults to a blank board:
views.py
import chess, chess.pgn
def index(request, pgn_slug=None):
board = chess.Board()
game = chess.pgn.Game.from_board(board)
game.headers["DrawOffered"] = "False"
The main i... | [
"I found that using the html download attribute produces different GET headers. Uncertain of portability but this worked to separate GET from GET-with-download requests on my local system.\nfetch = request.headers.get('Sec-Fetch-Site')\ndest = request.headers.get('Sec-Fetch-Dest')\nif fetch == 'same-origin' and des... | [
0
] | [] | [] | [
"django",
"django_views",
"http_headers",
"javascript",
"python"
] | stackoverflow_0074154854_django_django_views_http_headers_javascript_python.txt |
Q:
In python convert SVG to PNG while resizing and increasing quality
First I note that there are many related questions, but after a day of trying pyvip and cairo and the rest none of them work for me, even after installing other software that they seem to depend on. The exception is svglib with reportlab, it comes ... | In python convert SVG to PNG while resizing and increasing quality | First I note that there are many related questions, but after a day of trying pyvip and cairo and the rest none of them work for me, even after installing other software that they seem to depend on. The exception is svglib with reportlab, it comes close but doesn't quite get there! This is the best post I found and may... | [
"Answering my own question, after lots of code inspections within svglib it appears it is impossible to do resize and increase dpi to predefined values. This is because svglib renders an SVG to a ReportLab drawing without any ability to tell it to render the SVG at the resolution required, which is a shame given th... | [
6,
0
] | [] | [] | [
"python",
"reportlab",
"svg"
] | stackoverflow_0068242812_python_reportlab_svg.txt |
Q:
How do I chain methods in classes?
This is the task I need to complete:
Consider that you are interested in coloured shapes on paper. Write a class 'Shape'which has a hidden attribute of colour, an access method to get the colour (you may wish to have a default colour) and an modifier method to set the colour.
Try... | How do I chain methods in classes? | This is the task I need to complete:
Consider that you are interested in coloured shapes on paper. Write a class 'Shape'which has a hidden attribute of colour, an access method to get the colour (you may wish to have a default colour) and an modifier method to set the colour.
Try and make it so that you can chain your ... | [
"If you return self in the set method this will work. This is because you are calling .set() on the shape class, and if .set() does not return the object it belongs to, you are calling .set() on nothing.\n",
"Return self in the set() method\nclass Shape:\n def __init__(self, colour=None):\n self._colour... | [
0,
0,
0
] | [] | [] | [
"chain",
"class",
"oop",
"python"
] | stackoverflow_0074164703_chain_class_oop_python.txt |
Q:
reading entry values from function and using inside other function
I have a bot, which should scrape website. We have one fixed given URL link placeholder (as an Entry in tkinter) it works well.
Also, I have add button with help of it, user adds as many as button-clicked entry boxes.
When I click scrape, I cannot ... | reading entry values from function and using inside other function | I have a bot, which should scrape website. We have one fixed given URL link placeholder (as an Entry in tkinter) it works well.
Also, I have add button with help of it, user adds as many as button-clicked entry boxes.
When I click scrape, I cannot take the text values from that newly added entry boxes.
here is code;
Li... | [
"There are different solutions to your problem and it is not clear what you really try to achieve. To give some examples:\nGet widget that has currently the focus:\nimport tkinter as tk\n\ndef example():\n print(root.focus_get())\n\nroot = tk.Tk()\ncanvas = tk.Canvas(root)\ncanvasframe = tk.Frame(canvas)\ncanvas... | [
1
] | [] | [] | [
"python",
"tkinter",
"tkinter_entry"
] | stackoverflow_0074164050_python_tkinter_tkinter_entry.txt |
Q:
Graphviz is too slow
I am trying to generate a graph that has 100 nodes and 4000 edges, and it has been over 10 minutes. I am using the python graphviz code. Below is the function used to generate the graph.
def draw_graph(self):
dot = Digraph(format="png")#comment="This assignment sucks")
edge... | Graphviz is too slow | I am trying to generate a graph that has 100 nodes and 4000 edges, and it has been over 10 minutes. I am using the python graphviz code. Below is the function used to generate the graph.
def draw_graph(self):
dot = Digraph(format="png")#comment="This assignment sucks")
edges = set()
for k, v... | [
"Regarding the answer to the link you provided, it lists the attributes: nslimit, nslimit1, mclimit for dot layout engine, and maxiter for neato or fdp layout engines; and attribute splines.\nBy default your code uses dot layout engine as described in documentation. If the choice of engine is not important to you, ... | [
2
] | [] | [] | [
"graphviz",
"python",
"python_3.x"
] | stackoverflow_0064130276_graphviz_python_python_3.x.txt |
Q:
How to get final links from find_all('a') as a list?
import requests
import re
from bs4 import BeautifulSoup
respond = requests.get("http://www.kulugyminiszterium.hu/dtwebe/Irodak.aspx")
print(respond)
soup = BeautifulSoup(respond.text, 'html.parser')
for link in soup.find_all('a'):
links = link.get('href')
... | How to get final links from find_all('a') as a list? | import requests
import re
from bs4 import BeautifulSoup
respond = requests.get("http://www.kulugyminiszterium.hu/dtwebe/Irodak.aspx")
print(respond)
soup = BeautifulSoup(respond.text, 'html.parser')
for link in soup.find_all('a'):
links = link.get('href')
linki_bloc = ('http://www.kulugyminiszterium.hu/dtweb... | [
"Close to your goal, but you overwrite the result wit each iteration - Simply append your manipulated links to a list with list comprehension directly:\n['http://www.kulugyminiszterium.hu/dtwebe/'+link.get('href').replace(' ', '%20' ) for link in soup.find_all('a')]\n\nor as in your example:\nlinks = []\nfor link i... | [
0
] | [] | [] | [
"beautifulsoup",
"list",
"python",
"web_scraping"
] | stackoverflow_0074164743_beautifulsoup_list_python_web_scraping.txt |
Q:
Compare 2 DataFrames gives TypeError: 'NoneType' object is not iterable
Compare two DataFrames gives TypeError: 'NoneType' object is not iterable
The error comes from the final line. if I print the dfs out, all is as expected. Also, if I read the data from UTF-8 .csv files I have the same error message
My code is:... | Compare 2 DataFrames gives TypeError: 'NoneType' object is not iterable | Compare two DataFrames gives TypeError: 'NoneType' object is not iterable
The error comes from the final line. if I print the dfs out, all is as expected. Also, if I read the data from UTF-8 .csv files I have the same error message
My code is:
from io import StringIO
import pandas as pd
import datacompy
data1 = "... | [
"That's actually kind of a bug in datacompy Not a bug per se, but an uncought error from the user. A quick fix would be to provide an on_index argument:\ncompare = datacompy.Compare(df1, df2, on_index=True)\n\nDocs mention that\n\nYou can pass in on_index=True instead of join_columns to join on the index instead.\n... | [
1
] | [] | [] | [
"dataframe",
"python",
"types"
] | stackoverflow_0074164795_dataframe_python_types.txt |
Q:
how can I detect the windows user's name and add it to a file path
I am making a python script as a school project but
I have been using my own user in order to use a file path, but I want to make it so that I can use this program on other devices, please, can someone help
A:
You can use the os library for this.... | how can I detect the windows user's name and add it to a file path | I am making a python script as a school project but
I have been using my own user in order to use a file path, but I want to make it so that I can use this program on other devices, please, can someone help
| [
"You can use the os library for this.\nimport os\nuser_name = os.getlogin()\n\nos.getlogin() returns the currently logged in user's user name as a string. Here is the documentation.\n"
] | [
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0074164879_python_windows.txt |
Q:
Django Template Variables and Javascript
When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}.
Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django ... | Django Template Variables and Javascript | When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}.
Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be ... | [
"The {{variable}} is substituted directly into the HTML. Do a view source; it isn't a \"variable\" or anything like it. It's just rendered text.\nHaving said that, you can put this kind of substitution into your JavaScript.\n<script type=\"text/javascript\"> \n var a = \"{{someDjangoVariable}}\";\n</script>\n\nTh... | [
382,
85,
74,
54,
15,
14,
12,
10,
9,
7,
6,
5,
5,
4,
0,
0,
0
] | [] | [] | [
"django",
"django_templates",
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0000298772_django_django_templates_google_app_engine_javascript_python.txt |
Q:
I made a guessing game and for some reason even though I used the global thing it keeps telling me that it is not defined but I did just earlier
This is the code. Somebody please help. I'm confused. The guess variable is the number of guesses that remain after each guess. I've tried global and it still doesn't wor... | I made a guessing game and for some reason even though I used the global thing it keeps telling me that it is not defined but I did just earlier | This is the code. Somebody please help. I'm confused. The guess variable is the number of guesses that remain after each guess. I've tried global and it still doesn't work. I'm lost at this point. Please help.
import random
# WELCOMING USER
print(" WELCOME TO THE NUMBER GUESSING GAME !! ")
print("The number you'll be... | [
"All you have to do is put user_guess = 0 and winning_or_loose = 0 somewhere before your while loop, and it fixes your game. Your main issue seems to be that you keep trying to use variables that you never created.\nHowever, you code has a lot of redundancy, and is not organized very well. You have no system in pla... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074164440_python.txt |
Q:
How to do finite difference integration in python?
I want to solve a differential equation of a given function S. First, I integrate a function using 4th-order runge kutta:
def rk4_step(r, u, h, f, *args):
k1 = h * f(r, u, *args)
k2 = h * f(r + h/2, u + k1/2, *args)
k3 = h * f(r + h/2, u + k2/2, *args)... | How to do finite difference integration in python? | I want to solve a differential equation of a given function S. First, I integrate a function using 4th-order runge kutta:
def rk4_step(r, u, h, f, *args):
k1 = h * f(r, u, *args)
k2 = h * f(r + h/2, u + k1/2, *args)
k3 = h * f(r + h/2, u + k2/2, *args)
k4 = h * f(r + h, u + k3, *args)
u_new = u + (k... | [
"The second method is also known as the central Euler method. It looks nice, symmetric and all, but in the end it is only weakly stable (the stability region is a segment on the imaginary axis), in many cases it has an oscillating error component that grows very fast.\nAlso your initialization is most likely inappr... | [
1
] | [] | [] | [
"finite_difference",
"numerical_methods",
"python",
"runge_kutta"
] | stackoverflow_0074147564_finite_difference_numerical_methods_python_runge_kutta.txt |
Q:
Python Pandas-Automating Data Gathering from Website
I'm trying to make a script that can read through a table of company names from one website and take the names of each company and put them in an url (the url exists, and it contains more data specific to each company. This data is what I want to analyze).
Howev... | Python Pandas-Automating Data Gathering from Website | I'm trying to make a script that can read through a table of company names from one website and take the names of each company and put them in an url (the url exists, and it contains more data specific to each company. This data is what I want to analyze).
However, I cannot get the names to be put in the url without py... | [
"In your for-loop:\n\nremove name = entry + 1\nreplace url+str(name) with url + entry\n\nAnd so, you get the expected output printed:\n X Filing Date Trade Date Ticker Insider Name Title \\\n0 NaN 2022-10-21 19:03:38 2022-10-19 MIST Wills Robert James Dir \n1 NaN 2022-10-21 1... | [
1
] | [] | [] | [
"automation",
"data_science",
"database",
"pandas",
"python"
] | stackoverflow_0074142304_automation_data_science_database_pandas_python.txt |
Q:
pysimplegui popup button_justification problem
According to the documentation of PySimpleGUI, the popup element should have an argument called button_justification, which position the button in 'right' or 'left', or 'center' within the popup window.
When i added button_justification='center' to the popup element i... | pysimplegui popup button_justification problem | According to the documentation of PySimpleGUI, the popup element should have an argument called button_justification, which position the button in 'right' or 'left', or 'center' within the popup window.
When i added button_justification='center' to the popup element in my project it raised the error: popup() got an une... | [
"Not all enhancements added into the PyPI version.\nDownload from GitHub\n\nThere is code in the PySimpleGUI package that upgrades your previously pip installed package to the latest version checked into GitHub.\nYou can use the commands psgmain to run the test harness or psgupgrade to invoke the GitHub upgrade cod... | [
0
] | [] | [] | [
"button",
"popup",
"pysimplegui",
"python"
] | stackoverflow_0074164580_button_popup_pysimplegui_python.txt |
Q:
Display role separately while creating role discord.py
How can i display role members separately from online members, when i creating role?
Need to enable this
A:
As you can see in the discord.Guild.create_role() documentation, you need to set to true parameter "hoist".
hoist (bool) – Indicates if the role shou... | Display role separately while creating role discord.py | How can i display role members separately from online members, when i creating role?
Need to enable this
| [
"As you can see in the discord.Guild.create_role() documentation, you need to set to true parameter \"hoist\".\n\nhoist (bool) – Indicates if the role should be shown separately in the member list. Defaults to False\n\n"
] | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074164886_discord.py_python.txt |
Q:
Preflight Access-Control-Expose-Headers ignored in CORS on HTTP locally
I'm having trouble getting Access-Control-Expose-Headers from a preflight OPTIONS for a PUT request working in a local development environment - the browser seems to ignore it and doesn't expose the header listed to Javascript code.
Below is a... | Preflight Access-Control-Expose-Headers ignored in CORS on HTTP locally | I'm having trouble getting Access-Control-Expose-Headers from a preflight OPTIONS for a PUT request working in a local development environment - the browser seems to ignore it and doesn't expose the header listed to Javascript code.
Below is an example site that you can run locally, and look in the console to see that ... | [
"The Access-Control-Expose-Headers header belongs, not in the response to a preflight request, but in the response to the associated actual request (i.e. the PUT request, in your case). Specifying that header in a preflight response has no effect.\nFor an authoritative source about this, see the relevant section of... | [
1
] | [] | [] | [
"cors",
"html",
"http",
"javascript",
"python"
] | stackoverflow_0074164861_cors_html_http_javascript_python.txt |
Q:
Search and replace strings in XML using python
I am trying to search and replace certain words in my .xml file and replace it with another, but I struggle a bit.
I have been using this code so far:
import xml.etree.ElementTree as ET
with open('Rom1.xml', encoding="utf8") as f:
tree = ET.parse(f)
#root = tree.... | Search and replace strings in XML using python | I am trying to search and replace certain words in my .xml file and replace it with another, but I struggle a bit.
I have been using this code so far:
import xml.etree.ElementTree as ET
with open('Rom1.xml', encoding="utf8") as f:
tree = ET.parse(f)
#root = tree.find('ExportedObjects')
root = tree.getroot()
f... | [
"If there is no possibility of ambiguity then you could just do this:\nwith open('Rom1.xml', encoding='utf-8', mode='r+') as xml:\n content = xml.read().replace('Rom1', 'Rom2')\n xml.seek(0)\n xml.write(content)\n xml.truncate()\n\nIn this case the truncate() call is not necessary. However, if the second argume... | [
0,
0,
0
] | [] | [] | [
"parsing",
"python",
"replace",
"search",
"xml"
] | stackoverflow_0074164604_parsing_python_replace_search_xml.txt |
Q:
Saving status of all the task in xcom as soon as it gets completed a in airflow
i am writing a dag and i want to save the status of a task with their taskid in a dictonary in XCOM, the status can be success or failed or anything.
For example below are the two task
def task_18(ti):
print("TASK 18 COMPLETE")
def... | Saving status of all the task in xcom as soon as it gets completed a in airflow | i am writing a dag and i want to save the status of a task with their taskid in a dictonary in XCOM, the status can be success or failed or anything.
For example below are the two task
def task_18(ti):
print("TASK 18 COMPLETE")
def task_19(ti):
print("TASK 19 COMPLETE")
opr_task_17 = PythonOperator(task_id='ta... | [
"I'm not sure that an XCom is the most suited, since the status of tasks from any given DagRun is dynamically available at any time.\nThat being said it is straight forward to access this information:\nimport pendulum\nfrom airflow.decorators import dag, task\nfrom airflow.exceptions import AirflowFailException\nfr... | [
1
] | [] | [] | [
"airflow",
"airflow_2.x",
"python"
] | stackoverflow_0074163210_airflow_airflow_2.x_python.txt |
Q:
How do I fix "blocked by CORS policy" error raised using FastAPI, React and Axios?
I'm trying to get data using axios, but facing error of No 'Access-Control-Allow-Origin'. I have try to find solution but no where I found a proper solution including FastAPI, React and Axios.
Here is my backend:
origins = ['https:/... | How do I fix "blocked by CORS policy" error raised using FastAPI, React and Axios? | I'm trying to get data using axios, but facing error of No 'Access-Control-Allow-Origin'. I have try to find solution but no where I found a proper solution including FastAPI, React and Axios.
Here is my backend:
origins = ['https://localhost:3000', 'https://localhost:8080']
app.add_middleware(
CORSMiddleware,
... | [
"You should use allow_origins=origins, without the brackers [] around origins.\nExample:\norigins = ['http://localhost:3000', 'https://localhost:3000']\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\... | [
0
] | [] | [] | [
"axios",
"cors",
"fastapi",
"python",
"reactjs"
] | stackoverflow_0074039807_axios_cors_fastapi_python_reactjs.txt |
Q:
Trying to loop through a pandas df changing all the data type and presentation type
I'm looking for help for a way to loop through pandas DF changing the rows from the current presented object datatype of for example '1.15m' to 1150000 and also change the datatype to an integer.
This is what I have so far but it d... | Trying to loop through a pandas df changing all the data type and presentation type | I'm looking for help for a way to loop through pandas DF changing the rows from the current presented object datatype of for example '1.15m' to 1150000 and also change the datatype to an integer.
This is what I have so far but it doesnt seem to be picking up the 'm' in the object.
int_cols = ['Avg. Likes', 'Posts', 'Ne... | [
"here is one way to do it\nint_cols = ['Avg. Likes', 'Posts', 'New Post Avg. Likes','Total Likes' ]\nint_cols\n\n# create a mapping of the suffixes for multipiers\nm={'m': 1000000.0, 'k': 1000.0, 'b': 1000000000.0}\nm\n\n# remove digits and map to the dictionary\n# then multiply with the numeric part\ndf[int_cols] ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074164179_pandas_python.txt |
Q:
pyinstaller does not support importing kivy screen with exec
I have a kivymd app designed using the lazy loading method (all the screens and their kv files are placed in different folders so that they can be called when the user needs them using exec and eval, something similar to these projects kitchensink and ki... | pyinstaller does not support importing kivy screen with exec | I have a kivymd app designed using the lazy loading method (all the screens and their kv files are placed in different folders so that they can be called when the user needs them using exec and eval, something similar to these projects kitchensink and kivy-lazy-loading-template). that works very well in pycharm.
folder... | [
"I tried different ways to include the screen modules to analyze the imported libraries in the .spec file. But I realized that this is not the right way and I have to manually write the libraries in hiddenimports in .spec, like this:\na = Analysis(['main.py'],\n pathex=[path],\n binaries=[],... | [
0
] | [] | [] | [
"kivy",
"kivymd",
"pyinstaller",
"python"
] | stackoverflow_0074110533_kivy_kivymd_pyinstaller_python.txt |
Q:
Convert SVG to PNG in Python
How do I convert an svg to png, in Python? I am storing the svg in an instance of StringIO. Should I use the pyCairo library? How do I write that code?
A:
Here is what I did using cairosvg:
from cairosvg import svg2png
svg_code = """
<svg xmlns="http://www.w3.org/2000/svg" width... | Convert SVG to PNG in Python | How do I convert an svg to png, in Python? I am storing the svg in an instance of StringIO. Should I use the pyCairo library? How do I write that code?
| [
"Here is what I did using cairosvg:\nfrom cairosvg import svg2png\n\nsvg_code = \"\"\"\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"#000\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <circle cx=\"12\" cy=\"... | [
128,
69,
49,
35,
24,
13,
8,
6,
6,
3,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"cairo",
"python",
"rendering",
"svg"
] | stackoverflow_0006589358_cairo_python_rendering_svg.txt |
Q:
Find max value of a column based on another in python
i have 2d list implementation as follows. It shows no. of times every student topped in exams:-
list = main_record
['student1',1]
['student2',1]
['student2',2]
['student1',5]
['student3',3]
i have another list of unique students as follows:-
list... | Find max value of a column based on another in python | i have 2d list implementation as follows. It shows no. of times every student topped in exams:-
list = main_record
['student1',1]
['student2',1]
['student2',2]
['student1',5]
['student3',3]
i have another list of unique students as follows:-
list = students_enrolled
['student1','student2','student3']
... | [
"You define a dict base key of studentX and save the max value for each student key then sort the students_enrolled base max value of each key.\nfrom collections import defaultdict\n\nmain_record = [['student1',1], ['student2',1], ['student2',2], ['student1',5], ['student3',3]]\nstudents_enrolled = ['student1','stu... | [
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074165004_list_python.txt |
Q:
Element not clickable in the next page by selenium python
I try to scrape all the pages of a URL by selenium python, but only could get the values from the 1st page. The code is going to the next page but same code is not working to scrape ending with an error. The error is " Element ... is not clickable at point ... | Element not clickable in the next page by selenium python | I try to scrape all the pages of a URL by selenium python, but only could get the values from the 1st page. The code is going to the next page but same code is not working to scrape ending with an error. The error is " Element ... is not clickable at point (208, 17). Other element would receive the click: ...". Here is... | [
"While not trivial, it's doable, and here is one way to do it:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom sel... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074151083_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
Game of life in Python: Issue with the function that return the next step of the game
The program consists of 3 main parts: Finding the numbers of Neighbors, creating a list with the rules of the game of life, and one last part which converts 1/0 into True or False.
The issue is that it seems to return a good answ... | Game of life in Python: Issue with the function that return the next step of the game | The program consists of 3 main parts: Finding the numbers of Neighbors, creating a list with the rules of the game of life, and one last part which converts 1/0 into True or False.
The issue is that it seems to return a good answer, but when I evaluate my program in my teacher's website, It says that it returns a wrong... | [
"The problem came from one of the rules (a live cell with 3 neighbors survives) not being actually implemented.\nHere's a fix for the relevant part of the code:\n# Implementation of the rules\n\nfor k in range(len(M)):\n for i in range(len(M)):\n # A cell with 3 neighbors will survive, or be born\n ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074164443_python.txt |
Q:
Python - numpy - use somes recarray by json in one recarray
My goal is to achieve simplified access to the various json files, with recarrays in a global recarray to achieve simplified end access like:
parms.logic.myVarA.
Desired structure
parms (recarray)
[
logic (recarray)
- myVarA (int)
tool (re... | Python - numpy - use somes recarray by json in one recarray | My goal is to achieve simplified access to the various json files, with recarrays in a global recarray to achieve simplified end access like:
parms.logic.myVarA.
Desired structure
parms (recarray)
[
logic (recarray)
- myVarA (int)
tool (recarray)
- myVarA (int)
]
Example:
parms.logic.myVarA
par... | [
"With this dtype:\nIn [169]: dt = np.dtype([('logic',[('myVarA',int)]),('tool',[('myVarA',int)])])\n\nI can make a recarray (with \"random\" values):\nIn [170]: arr = np.recarray(3,dt) \nIn [171]: arr\nOut[171]: \nrec.array([((1969973520,), (598,)), ((1969973584,), (598,)),\n ((1969973552,), (598,))],\... | [
0
] | [] | [] | [
"json",
"numpy",
"python",
"recarray",
"tuples"
] | stackoverflow_0074162531_json_numpy_python_recarray_tuples.txt |
Q:
Find syntax error in data visualization with python
I can't find any error in this syntax. Can you guys help me to find the error in this syntax? Thank You
import pandas as pd
import matplotlib.pyplot as plt
tabel = (pd.read_csv("https://storage.googleapis.com/dqlab-dataset/usia_karyawan.csv")
.sort_valu... | Find syntax error in data visualization with python | I can't find any error in this syntax. Can you guys help me to find the error in this syntax? Thank You
import pandas as pd
import matplotlib.pyplot as plt
tabel = (pd.read_csv("https://storage.googleapis.com/dqlab-dataset/usia_karyawan.csv")
.sort_values("Kelompok Usia", ascending=False)
.set_index(... | [
"Based on line above line with error, you are missing = after xlim:\ntabel[\"Perempuan\"].plot(kind=\"barh\", ax=axes[1], color=\"tab:orange\", fontsize=14, xlim=[0, 550])\n# this is missing ^\n\nThe error tells you, that positional argument (argum... | [
1
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074165081_matplotlib_pandas_python.txt |
Q:
Setiment Analysis - Dataset .map() is not mapping string to int
I’m completely new to python and data analysis.
I’m trying to analyze twitter data and here is a screenshot of my Dataset.
I'm trying to map the sentiment which is (POS, NUT, NEG) to numbers like 0, 1, 2
so i write this code and it doesn’t work, does ... | Setiment Analysis - Dataset .map() is not mapping string to int | I’m completely new to python and data analysis.
I’m trying to analyze twitter data and here is a screenshot of my Dataset.
I'm trying to map the sentiment which is (POS, NUT, NEG) to numbers like 0, 1, 2
so i write this code and it doesn’t work, does anyone knows why?
dfMain['Sentiment'] = dfMain['Sentiment'].map({'POS... | [
"so the map function takes a list and a function and applies that function to every item in that list and then returns a map object. This is great and you can just google it to get more info, but what you want is apply a function to a pandas dataframe.\nPandas uses the .apply method to apply a function to every ite... | [
0
] | [] | [] | [
"data_analysis",
"python",
"twitter"
] | stackoverflow_0074164969_data_analysis_python_twitter.txt |
Q:
I am scraping discord and The function below gives me message: 404 ,code: 404 in json file. I cant understand why. It is my own server
It is my own server and I am trying to retrieve messages, overall my goal is to make a discord scraper.
On a side note,Bots require server permissions and so I am working on web sc... | I am scraping discord and The function below gives me message: 404 ,code: 404 in json file. I cant understand why. It is my own server | It is my own server and I am trying to retrieve messages, overall my goal is to make a discord scraper.
On a side note,Bots require server permissions and so I am working on web scraping, although I guess you need to be a part of the server to scrape it too I guess. If anyone has a better idea to scrape servers that th... | [
"I think you need to add / between /channels{channelid}. Try like this\nr = requests.get(\n f'https://discord.com/api/v9/channels/{channelid}',headers=headers\n )\n\n"
] | [
1
] | [] | [] | [
"discord",
"nlp",
"python",
"web_scraping"
] | stackoverflow_0074165133_discord_nlp_python_web_scraping.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.