content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to remove string starting with another string inside brackets?
I have this kind of string:
hello[_ng11][test]hello3[_ngRTf]
and I would like to remove string starting with _ng inside brackets
Result should be:
hello[][test]hello3[]
I did try to do something like this:
st = "hello[_ng11][test]hello3[_ngRTf]"
... | How to remove string starting with another string inside brackets? | I have this kind of string:
hello[_ng11][test]hello3[_ngRTf]
and I would like to remove string starting with _ng inside brackets
Result should be:
hello[][test]hello3[]
I did try to do something like this:
st = "hello[_ng11][test]hello3[_ngRTf]"
modified_string = re.sub(r"/\[\[_ng[^\]]*\]\]/", "[]", st)
print(modifie... | [
"You need to remove the slashes and reduce square brackets to a single occurrence on both sides of the pattern:\nmodified_string = re.sub(r\"\\[_ng[^][]*]\", \"[]\", st)\n\nSee the Python demo:\nimport re\nst = \"hello[_ng11][test]hello3[_ngRTf]\"\nmodified_string = re.sub(r\"\\[_ng[^][]*]\", \"[]\", st)\nprint(mod... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074209181_python_regex.txt |
Q:
Python type-hinting a mixin with its own properties
I know that I need to use a Protocol if I want to type-hint a Mixin class.
from typing import Protocol
class MyProtocol(Protocol):
a: int
class MyMixin:
def method(self: MyProtocol):
return self.a * 10
Here we type-hinting self and this does th... | Python type-hinting a mixin with its own properties | I know that I need to use a Protocol if I want to type-hint a Mixin class.
from typing import Protocol
class MyProtocol(Protocol):
a: int
class MyMixin:
def method(self: MyProtocol):
return self.a * 10
Here we type-hinting self and this does the job.
The problem arises when MyMixin also has its own... | [
"\nMyMixin is not (inherited from) MyProtocol. Should probably be:\n\nclass MyMixin(MyProtocol):\n ...\n\n\nIf your method expects something that has .b it should annotate self with something that has .b (i.e. MyMixin not MyProtocol).\n\nAnnotating self is redundant. It should always be the class the method belo... | [
0,
0
] | [] | [] | [
"mypy",
"python",
"python_typing",
"type_hinting"
] | stackoverflow_0074207135_mypy_python_python_typing_type_hinting.txt |
Q:
Python Tkinter: radio buttons are toggled globally in all menus instead of one
How to achieve that the radio button switches in each menu separately and not globally in all? The moment I switch the radio button in the Family menu, for example, it is unchecked in the Size menu and vice versa.
I also want to set a d... | Python Tkinter: radio buttons are toggled globally in all menus instead of one | How to achieve that the radio button switches in each menu separately and not globally in all? The moment I switch the radio button in the Family menu, for example, it is unchecked in the Size menu and vice versa.
I also want to set a default checked radio button for each menu, but I don't know how to do that.
This is ... | [
"You have to create a variable (Stringvar) for each of the menu and specify it with kwarg variable while instanciating your radiobuttons. That way they will be set independently:\nfrom tkinter import *\n\nroot = Tk ()\nroot.geometry (\"500x500\")\nroot.title (\"Program\")\n\nmenu_bar = Menu (\n master = r... | [
1,
1
] | [] | [] | [
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0074209124_python_python_3.x_tkinter.txt |
Q:
Equivalent of predict_proba of scikit-learn for ONNX C++ API
I have trained a classification model and I use that the ONNX format of that model in C++ to predict value as follow:
auto inputOnnxTensor = Ort::Value::CreateTensor<float>(memoryInfo, inputValues.data(), inputValues.size(), inputDims.data(), inputDims.s... | Equivalent of predict_proba of scikit-learn for ONNX C++ API | I have trained a classification model and I use that the ONNX format of that model in C++ to predict value as follow:
auto inputOnnxTensor = Ort::Value::CreateTensor<float>(memoryInfo, inputValues.data(), inputValues.size(), inputDims.data(), inputDims.size());
auto outputValues = session.Run(Ort::RunOptions{ nullptr ... | [
"When converting your classification model to ONNX (I assume you use skl2onnx), disable ZipMap. I'm not sure about other options, but here is my working code:\nmodel = to_onnx(my_rfc_model, x_train, \n options={'zipmap': False, 'output_class_labels': False, 'raw_scores': False})\nonnx.save_model(model, \"model.o... | [
0
] | [] | [] | [
"c++",
"onnx",
"python",
"scikit_learn"
] | stackoverflow_0073534072_c++_onnx_python_scikit_learn.txt |
Q:
Spark stuck in UNDEFINED status when submit a job in AWS EMR
I am running a spark submit using the following script by using an AWS EMR (version emr-5.26.0) on m4.xlarge instances :
#!/bin/sh
# Define variables to get script parameters
MAIN_SPARK_URI=$1 # looks like s3://bucket/app/src/main.py
MODELS_BASE_URI=$2 ... | Spark stuck in UNDEFINED status when submit a job in AWS EMR | I am running a spark submit using the following script by using an AWS EMR (version emr-5.26.0) on m4.xlarge instances :
#!/bin/sh
# Define variables to get script parameters
MAIN_SPARK_URI=$1 # looks like s3://bucket/app/src/main.py
MODELS_BASE_URI=$2 # looks like s3://bucket/app/models/models.pkl
APP_EGG_URI=$3 # lo... | [
"Solution :\nWhen facing such an issue try to configure memory better to fit with the kind of instance you're running your code on.\nIn my opinion, I over-configured the memory to allocate and the job was not able to start. Here is a configuration that makes the job running :\n--conf spark.driver.cores=1 \\\n--conf... | [
0
] | [] | [] | [
"amazon_emr",
"amazon_web_services",
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0074198514_amazon_emr_amazon_web_services_apache_spark_pyspark_python.txt |
Q:
Print all id numbers from class in http-request
I would like to have a ready-made list containing id numbers.
<dl class="welcome" id="fdgvs_4455256765">
<dl class="welcome" id="34wfdsf_235250861">
<dl class="welcome" id="v3dr234fz_1242566862">
I already have a piece of code, but I miss the cut from the same id nu... | Print all id numbers from class in http-request | I would like to have a ready-made list containing id numbers.
<dl class="welcome" id="fdgvs_4455256765">
<dl class="welcome" id="34wfdsf_235250861">
<dl class="welcome" id="v3dr234fz_1242566862">
I already have a piece of code, but I miss the cut from the same id numbers.
import requests
from requests_html import HTML... | [
"You split the string by id=, then you split the second part by _ then you print the result by removing '> at the end.\nstr = \"<Element 'dl' class=('welcome',) id='v3dr234fz_1242566862'>\"\n\nprint(str.split(\"id=\")[1].split(\"_\")[1][:-2])\n\n"
] | [
1
] | [] | [] | [
"httprequest",
"loops",
"python",
"web_scraping"
] | stackoverflow_0074209284_httprequest_loops_python_web_scraping.txt |
Q:
Uniform Cost Search in Fully Connected Weighed Graph with a Specified Number Of Customers to Visit
The problem: you are a salesman. You have customers in an area. Also, you have office S as a starting point and office F as the target point. Before you arrive at the target point you need to visit a specified number... | Uniform Cost Search in Fully Connected Weighed Graph with a Specified Number Of Customers to Visit | The problem: you are a salesman. You have customers in an area. Also, you have office S as a starting point and office F as the target point. Before you arrive at the target point you need to visit a specified number of customers. You need to find an optimal solution with the least distance you walk. To do that you wil... | [
"Your answer is just as good as the \"true answer\" -- same cost and same customers visited, so no problem there.\nYour program is not correct, though, because the optimal solution won't always reach every customer by the shortest path to that customer.\nYou should be doing UCS on a much larger implicit graph, wher... | [
1
] | [] | [] | [
"algorithm",
"artificial_intelligence",
"graph_theory",
"python",
"search"
] | stackoverflow_0074207227_algorithm_artificial_intelligence_graph_theory_python_search.txt |
Q:
How to calculate the probability that a sample belongs to a certain class from the mixture Gaussian distribution?
I would like to know, for this mixture of Gaussian distributions generated by the data we give ourselves, how do we figure out which component is more likely to belong to a new sample we are given?
I l... | How to calculate the probability that a sample belongs to a certain class from the mixture Gaussian distribution? | I would like to know, for this mixture of Gaussian distributions generated by the data we give ourselves, how do we figure out which component is more likely to belong to a new sample we are given?
I learned that Matlab seems to have functions that can be calculated directly, is there any in python? I haven't found an ... | [] | [] | [
"The problem has been sovled, the answer can refer in the link:\nhttps://stackoverflow.com/questions/42971126/multivariate-gaussian-distribution-scipy\n\n"
] | [
-1
] | [
"gmm",
"numpy",
"python",
"scikit_learn"
] | stackoverflow_0074207989_gmm_numpy_python_scikit_learn.txt |
Q:
Python docstrings to GitHub README.md
How do I transcode Python documentation strings to a GitHub readme.md file?
Even though it seems like something everyone does, I cannot seem to get a decent solution and I am assuming it should be easy, so it seems unlikely folks are going throw two converters…
What I have tri... | Python docstrings to GitHub README.md | How do I transcode Python documentation strings to a GitHub readme.md file?
Even though it seems like something everyone does, I cannot seem to get a decent solution and I am assuming it should be easy, so it seems unlikely folks are going throw two converters…
What I have tried
pydoc Actually simple. The output of py... | [
"The other answers are great. But I thought I (the OP) ought to share what I do these days (a year or two after the question).\nI use Sphinx and its Markdown extension. Do the following:\nTL;DR: See Gist snippet.\nSphinx-markdown-builder\nYou need sphinx-markdown-builder python module.\n pip install sphinx sphinx-m... | [
29,
5,
2,
1
] | [] | [] | [
"docstring",
"manpage",
"markdown",
"python",
"restructuredtext"
] | stackoverflow_0036237477_docstring_manpage_markdown_python_restructuredtext.txt |
Q:
python-access elements from the first list only
I have this fruit.txt which contains the following:
name, color
apple, red
banana, yellow
avocado, green
I managed to read each line of data using this code:
f =open('fruit.txt','r')
lines = f.readlines()
for oneline in lines:
oneline=oneline.strip()
oneline=one... | python-access elements from the first list only | I have this fruit.txt which contains the following:
name, color
apple, red
banana, yellow
avocado, green
I managed to read each line of data using this code:
f =open('fruit.txt','r')
lines = f.readlines()
for oneline in lines:
oneline=oneline.strip()
oneline=oneline.split(',')
print(oneline)
It printed this res... | [
"Use\nfirstline = f.readline()\n\ninstead of f.readlines()\n"
] | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074209416_list_python.txt |
Q:
How to seperate decimal numbers written back to back
How would it be possible to seperate a string of values (in my case, only corresponding to roman numeral values) into elements of a list?
'10010010010100511' -> [100, 100, 100, 10, 100, 5, 1, 1,]
I want to create something that goes like:
if it is a zero add it ... | How to seperate decimal numbers written back to back | How would it be possible to seperate a string of values (in my case, only corresponding to roman numeral values) into elements of a list?
'10010010010100511' -> [100, 100, 100, 10, 100, 5, 1, 1,]
I want to create something that goes like:
if it is a zero add it to side
if it's not a zero create a new element for it
| [
"You were on the right track with zeros, you have to notice that every base roman numeral is either a 1 or 5 followed by some amount of zeros. You can represent that as a very simple regex.\nimport re\n\ns = '10010010010100511'\n\npattern = \"[1|5]0*\"\n\nmatches = re.finditer(pattern=pattern, string=s)\n\nl = [mat... | [
0,
0
] | [] | [] | [
"list",
"python",
"roman_numerals",
"string"
] | stackoverflow_0074208584_list_python_roman_numerals_string.txt |
Q:
Structuring python packages for straightforward importing
I have a number of functions that I have written myself over time, over time I have placed each of these functions in their own modules (as I thought this was best practice).
I would like take the next step and organise these modules that I can import in fe... | Structuring python packages for straightforward importing | I have a number of functions that I have written myself over time, over time I have placed each of these functions in their own modules (as I thought this was best practice).
I would like take the next step and organise these modules that I can import in fewer lines of code. However, I'm finding that I need to need to ... | [
"Create a __init__.py file in both my_functions directory and src directory.\nNow in the my_functions __init__.py file. No need to edit __init__ file inside src.\nfrom src.func1 import func1\nfrom src.func2 import func2\n\n__all__ = [\n 'func1',\n 'func2'\n]\n\nNow you can use my_functions like below\nimport ... | [
1
] | [] | [] | [
"module",
"package",
"python",
"python_3.x"
] | stackoverflow_0074209373_module_package_python_python_3.x.txt |
Q:
How to calculate Frequency for a column where consists integers and blanks
I have a csv file like below, it has 10000+ rows
enter link description here
ID Ref_r
235R23 3
56982B 3
62C879 blank
625478 11
9S4284 11
985U12 11
524555 58
99L852 60
1024T4 58
102W49 3
258q34 blank
.....
I'd li... | How to calculate Frequency for a column where consists integers and blanks | I have a csv file like below, it has 10000+ rows
enter link description here
ID Ref_r
235R23 3
56982B 3
62C879 blank
625478 11
9S4284 11
985U12 11
524555 58
99L852 60
1024T4 58
102W49 3
258q34 blank
.....
I'd like to calculate the frequency for col Ref_r (1 to 99), where consists integers a... | [
"IIUC, you can use pandas with:\nimport pandas as pd\n\n(pd.read_csv('input.csv', sep='\\s+', dtype='str')['Ref_r']\n .value_counts(sort=False)\n .reindex(list(map(str, range(1,100)))+['blank'], fill_value=0)\n .rename_axis('Ref_r')\n .reset_index(name='Frequency')\n .to_csv('out.csv', index=False, sep='\\t')\n)\n\... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074209323_dataframe_pandas_python.txt |
Q:
matplotlib.backends.backend_tkagg is throwing an attribute error for 'blit'
When I try to run python3 module_7.py on my terminal, I get the following error:
File "/opt/CarlaSimulator/PythonClient/live_plotter.py", line 227, in plot_figure
tkagg.blit(photo, fca.get_renderer()._renderer, colormode=2)
Attribute... | matplotlib.backends.backend_tkagg is throwing an attribute error for 'blit' | When I try to run python3 module_7.py on my terminal, I get the following error:
File "/opt/CarlaSimulator/PythonClient/live_plotter.py", line 227, in plot_figure
tkagg.blit(photo, fca.get_renderer()._renderer, colormode=2)
AttributeError: module 'matplotlib.backends.backend_tkagg' has no attribute 'blit'
I have... | [
"It seems that matplotlib has changed some things.\nAccording to the documentation you should use tkagg.FigureCanvasTkAgg.blit instead of tkagg.blit (assuming that you import matplotlib.backends.backend_tkagg as tkagg).\n"
] | [
5
] | [
"As of October 2022, if you are setting up the CARLA simulator for the Intro to Self-Driving Cars course on Coursera, the answer is to downgrade matplotlib from 3.x.x to 2.2.2:\nI got the following answer from a post by Achyutha Krishna Rao Kothapalli on Coursera.\n1) python -m pip uninstall matplotlib (if you have... | [
-1
] | [
"attributeerror",
"matplotlib",
"python"
] | stackoverflow_0061847663_attributeerror_matplotlib_python.txt |
Q:
Timed calculation with additional stop signal in Python
I have the following scenario (for reference, I want to implement the UCI chess engine protocol):
I need to perform a calculation for some time x (possibly infinite). When the time is up, I want to know the current state (intermediate result) of the calculati... | Timed calculation with additional stop signal in Python | I have the following scenario (for reference, I want to implement the UCI chess engine protocol):
I need to perform a calculation for some time x (possibly infinite). When the time is up, I want to know the current state (intermediate result) of the calculation. Additionally, I want to have some kind of stop command, w... | [
"I am not sure if you are asking for Threading advice or how to build a chunked chess algorithm. If it is the former, here is an example of calculating primes in a separate thread.\ndef calculate_prime_after(n):\n if n == 1:\n return 2\n else:\n n = n + 1\n while True:\n for i ... | [
0
] | [] | [] | [
"multiprocessing",
"python",
"timer",
"uci"
] | stackoverflow_0074208822_multiprocessing_python_timer_uci.txt |
Q:
Could not load dynamic library 'libcudart.so.11.0' inside docker container
I have created a docker image with the following Dockerfile
FROM python:latest
WORKDIR /root/my_dir
COPY requirements.txt ./
RUN apt-get update &&\
apt-get upgrade -y &&\
apt-get install -y curl &&\
apt-get install n... | Could not load dynamic library 'libcudart.so.11.0' inside docker container | I have created a docker image with the following Dockerfile
FROM python:latest
WORKDIR /root/my_dir
COPY requirements.txt ./
RUN apt-get update &&\
apt-get upgrade -y &&\
apt-get install -y curl &&\
apt-get install nano &&\
pip3 install -r requirements.txt &&\
and then I use it as servi... | [
"The problem is that you created in the docker composed two different services that cannot communicate with each other.\nThe best thing to do is to create an image with CUDA in which you install python and the requirememnts.txt.\\\nThis is a sample of docker file:\nFROM nvidia/cuda:11.2.0-cudnn8-runtime-ubuntu20.04... | [
2
] | [] | [] | [
"cuda",
"docker",
"gpu",
"python",
"tensorflow"
] | stackoverflow_0074204565_cuda_docker_gpu_python_tensorflow.txt |
Q:
Tkinter background progressbar function while another function runs
I made a GUI Python program with Tkinter.
I made a progressbar using "from tkinter.ttk import Progressbar".
When I press a button, I apply a function that do something and return a Boolean value.
I need that the progressbar will run until that fun... | Tkinter background progressbar function while another function runs | I made a GUI Python program with Tkinter.
I made a progressbar using "from tkinter.ttk import Progressbar".
When I press a button, I apply a function that do something and return a Boolean value.
I need that the progressbar will run until that function ends the process, and after that it will stop.
from tkinter.ttk imp... | [
"I would use root.after(millisecond, function) instead of while True-loop to run function which updates progressbar every few seconds. And I would use directly boolean_wheel.is_alive() in this function to stop updateing.\nimport tkinter as tk\nfrom tkinter import ttk\nimport time\nimport threading\n\n# --- function... | [
2,
1
] | [] | [] | [
"python",
"python_multithreading",
"tkinter",
"user_interface"
] | stackoverflow_0074206890_python_python_multithreading_tkinter_user_interface.txt |
Q:
What is wrong in my code? Swapping first and last letter of a word, using method replace
Given any word, swap the first and the last letter's position then return the new string. If that is a one-letter word, return the word. I'm aware the fastest way to do this is to use slicing, or join but I want to try a new a... | What is wrong in my code? Swapping first and last letter of a word, using method replace | Given any word, swap the first and the last letter's position then return the new string. If that is a one-letter word, return the word. I'm aware the fastest way to do this is to use slicing, or join but I want to try a new approach using replace.
def front_back(any_string):
if len(any_string) <= 1:
return any_s... | [
"def front_back(any_string: str) -> str:\n if len(any_string) < 2:\n return any_string\n else:\n return any_string[-1] + any_string[1:-1] + any_string[0]\n\n\nprint(front_back('line'))\n\n\n",
"def front_back(any_string):\n if len(any_string) <= 1:\n return any_string\n else:\n ... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074208441_python_python_3.x.txt |
Q:
Using sudo with Python script
I'm trying to write a small script to mount a VirtualBox shared folder each time I execute the script. I want to do it with Python, because I'm trying to learn it for scripting.
The problem is that I need privileges to launch mount command. I could run the script as sudo, but I prefer... | Using sudo with Python script | I'm trying to write a small script to mount a VirtualBox shared folder each time I execute the script. I want to do it with Python, because I'm trying to learn it for scripting.
The problem is that I need privileges to launch mount command. I could run the script as sudo, but I prefer it to make sudo by its own.
I alre... | [
"Many answers focus on how to make your solution work, while very few suggest that your solution is a very bad approach. If you really want to \"practice to learn\", why not practice using good solutions? Hardcoding your password is learning the wrong approach!\nIf what you really want is a password-less mount for ... | [
87,
48,
20,
5,
4,
2,
1,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"shell",
"subprocess"
] | stackoverflow_0013045593_python_shell_subprocess.txt |
Q:
How to fix shapes (3,) and (720,1440) not aligned error
I am attempting to use the normal equation to produce a Fermi Map. However, I keep running into an error. Here is where I am with my code so far:
''''
#_=0+1×_+2×ℎ_
#=_−(0+1×_+2×ℎ_)
#These are the normal equations, so let's solve them
P = np.array([np.ones(du... | How to fix shapes (3,) and (720,1440) not aligned error | I am attempting to use the normal equation to produce a Fermi Map. However, I keep running into an error. Here is where I am with my code so far:
''''
#_=0+1×_+2×ℎ_
#=_−(0+1×_+2×ℎ_)
#These are the normal equations, so let's solve them
P = np.array([np.ones(dust_map.size),dust_map, synch_map]).T
PTy = np.dot(P.T, fermi_... | [
"Try this:\nP = np.array([np.ones_like(dust_map).flatten(),dust_map.flatten(), synch_map.flatten()])\navec = np.linalg.lstsq(P.T, fermi_gamma_rays.flatten(), rcond=None)[0]\n\n"
] | [
0
] | [] | [] | [
"astronomy",
"python"
] | stackoverflow_0073981925_astronomy_python.txt |
Q:
How to click on open application alert using Selenium
I am trying to click on open application alert using Selenium, and I am getting this error
NoAlertPresentException: Message: no such alert
So basically I am trying to open zoom application from the browser
And here is my code:
from selenium import webdriver
f... | How to click on open application alert using Selenium | I am trying to click on open application alert using Selenium, and I am getting this error
NoAlertPresentException: Message: no such alert
So basically I am trying to open zoom application from the browser
And here is my code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from... | [
"Thanks to NetworkMeister, I end up using default app method, Like the following:\n1- Open Firefox and go to zoom URL, when Launch application appear choose zoom and click on remember my choice and click open link\n2- Go to firefox and paste this about:support then search for Profile Folder and copy the path\n3- Go... | [
2,
1,
1,
1,
0
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"selenium_webdriver"
] | stackoverflow_0062154160_python_python_3.x_selenium_selenium_webdriver.txt |
Q:
pyqt: messagebox automatically closing after few seconds
I am trying to do a warning message box that disappears automatically after few seconds.
I have done this code:
def warning(self):
messagebox = QtGui.QMessageBox(self)
messagebox.setWindowTitle("wait")
messagebox.setText("wait (closing automatically... | pyqt: messagebox automatically closing after few seconds | I am trying to do a warning message box that disappears automatically after few seconds.
I have done this code:
def warning(self):
messagebox = QtGui.QMessageBox(self)
messagebox.setWindowTitle("wait")
messagebox.setText("wait (closing automatically in {0} secondes.)".format(3))
messagebox.setStandardButton... | [
"Try with my solution, \nI have created a new type of QMessageBox with your requirements\nimport sys\nfrom PyQt4 import QtCore\nfrom PyQt4 import QtGui\n\n\nclass TimerMessageBox(QtGui.QMessageBox):\n def __init__(self, timeout=3, parent=None):\n super(TimerMessageBox, self).__init__(parent)\n self... | [
8,
1
] | [] | [] | [
"pyqt",
"pyqt4",
"pyqt5",
"python",
"qmessagebox"
] | stackoverflow_0040932639_pyqt_pyqt4_pyqt5_python_qmessagebox.txt |
Q:
PyGithub: How to move inside a git branch and list all the content that present in sub folder
from github import Github
access_token = "MYACCESS_TOKEN"
g=Github(access_token, retry=20)
repo = g.get_repo("pygit/git")
print(repo.name)
branches = repo.get_branches()
for branch in branches:
print(branch.name)
... | PyGithub: How to move inside a git branch and list all the content that present in sub folder | from github import Github
access_token = "MYACCESS_TOKEN"
g=Github(access_token, retry=20)
repo = g.get_repo("pygit/git")
print(repo.name)
branches = repo.get_branches()
for branch in branches:
print(branch.name)
for file in repo.get_contents(""):
print(file.name)
Here I can list the branches. [I have 5 b... | [
"You can use this example in the PyGithub docs to list contents in a repository. The get_contents method accepts an optional ref parameter to which you can pass a branch's name.\nFor example:\nfor branch in branches:\n contents = repo.get_contents(\"\", ref=branch.name)\n while contents:\n file_content = conte... | [
0
] | [] | [] | [
"git",
"github",
"pygithub",
"python",
"python_3.x"
] | stackoverflow_0074209079_git_github_pygithub_python_python_3.x.txt |
Q:
I'm trying to create a new colm with the MAX Value from a Range of Months in the dataframe but the condition is to get max value for first 3 month
This is the data format date column shows the first entry date and i am trying to get the max of due missed in the first 3 months and i have data of 30 months and i ne... | I'm trying to create a new colm with the MAX Value from a Range of Months in the dataframe but the condition is to get max value for first 3 month |
This is the data format date column shows the first entry date and i am trying to get the max of due missed in the first 3 months and i have data of 30 months and i need max of dues missed in the first 3 months for each id
| [
"Considering your dataframe, as shown in your picture:\nimport pandas as pd\ndf = pd.DataFrame({\n 'ID':[100,100,100,100,100,\n 101,101,101,101, 101],\n 'Entry Date':['2020-04-10','2020-05-10','2020-06-10','2020-07-10','2020-08-10',\n '2020-07-25','2020-08-25','2020-09-25','2020-10-2... | [
0
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python"
] | stackoverflow_0074205404_dataframe_datetime_pandas_python.txt |
Q:
Trouble understanding the function of : in array indexing? Python
I have this line in the code:
next_J[v] = np.min(Q[v, :] + J)
Where essentially Q is an matrix of size n x n and J is a vector of size n. What does Q[v, :] mean?
I tried to code this out but still do not understand what exactly it does.
A:
Q[v,:] ... | Trouble understanding the function of : in array indexing? Python | I have this line in the code:
next_J[v] = np.min(Q[v, :] + J)
Where essentially Q is an matrix of size n x n and J is a vector of size n. What does Q[v, :] mean?
I tried to code this out but still do not understand what exactly it does.
| [
"Q[v,:] is translated by the interpreter as Q.__getitem__((v, slice(None))\nNote the (,) tuple syntax.\nFor a 2d array, this means select the v row. The slice selects all columns, and isn't actually needed in this context.\nFor a list this produces an error. alist[v] would work.\nQ[v]+J may not work fot lists, de... | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074208570_numpy_python.txt |
Q:
Checking area of overlap between two dataframes with parallel dask GeoPandas
I have two different GeoDataFrames: One of which contain polygon squares in a large grid. The other contains larger, and fewer, polygons.
I wish to calculate the area of overlap within each of the grid squares with the other, larger squar... | Checking area of overlap between two dataframes with parallel dask GeoPandas | I have two different GeoDataFrames: One of which contain polygon squares in a large grid. The other contains larger, and fewer, polygons.
I wish to calculate the area of overlap within each of the grid squares with the other, larger squares.
To do so, I made a simple loop method
for _, patch in tqdm(layer.iterrows(), t... | [
"I managed to speed up the process quite a bit using spatial joins and overlay as suggested by Michael in the comments.\nIn addition I implemented Dask Dataframes so the final code becomes:\nimport dask_geopandas as dg\nimport geopandas as gpd\n\ndef dissolve_shuffle(ddf, by=None, **kwargs):\n \"\"\"Shuffle and ... | [
1
] | [] | [] | [
"dask",
"dask_dataframe",
"geopandas",
"pandas",
"python"
] | stackoverflow_0073785831_dask_dask_dataframe_geopandas_pandas_python.txt |
Q:
pandas write dataframe to parquet format with append
I am trying to write a pandas dataframe to parquet file format (introduced in most recent pandas version 0.21.0) in append mode. However, instead of appending to the existing file, the file is overwritten with new data. What am i missing?
the write syntax is
df.... | pandas write dataframe to parquet format with append | I am trying to write a pandas dataframe to parquet file format (introduced in most recent pandas version 0.21.0) in append mode. However, instead of appending to the existing file, the file is overwritten with new data. What am i missing?
the write syntax is
df.to_parquet(path, mode='append')
the read syntax is
pd.re... | [
"To append, do this:\nimport pandas as pd \nimport pyarrow.parquet as pq\nimport pyarrow as pa\n\ndataframe = pd.read_csv('content.csv')\noutput = \"/Users/myTable.parquet\"\n\n# Create a parquet table from your dataframe\ntable = pa.Table.from_pandas(dataframe)\n\n# Write direct to your parquet file\npq.write_to_d... | [
6,
4,
3,
2,
0
] | [
"Pandas to_parquet() can handle both single files as well as directories with multiple files in it. Pandas will silently overwrite the file, if the file is already there. To append to a parquet object just add a new file to the same parquet directory.\nos.makedirs(path, exist_ok=True)\n\n# write append (replace the... | [
-1
] | [
"apache",
"pandas",
"parquet",
"python"
] | stackoverflow_0047191675_apache_pandas_parquet_python.txt |
Q:
find set of words in list
In the example I made up below, I am trying to get the words STEM Employment from the text list. If I find those set of words in order, I would like to find the index number of the first word so I can then use that same index number for the width and height lists since they are parallel (... | find set of words in list | In the example I made up below, I am trying to get the words STEM Employment from the text list. If I find those set of words in order, I would like to find the index number of the first word so I can then use that same index number for the width and height lists since they are parallel (meaning their len is always the... | [
"You can make data[\"text\"] a string with join and check for \"STEM Employment\" in that. Then find the index of \"STEM\".\nteststring = \"STEM Employment\"\ndata = {\"text\":[\"some\",\"more\",\"STEM\",\"Employment\",\"data\"],\n \"width\":[100,45,50,90,354],\n \"height\":[500,320,320,432,554]}\nif ... | [
1
] | [] | [] | [
"dictionary",
"for_loop",
"list",
"python"
] | stackoverflow_0074209530_dictionary_for_loop_list_python.txt |
Q:
Python Requests - No connection adapters
I'm using the Requests: HTTP for Humans library and I got this weird error and I don't know what is mean.
No connection adapters were found for '192.168.1.61:8080/api/call'
Anybody has an idea?
A:
You need to include the protocol scheme:
'http://192.168.1.61:8080/api/cal... | Python Requests - No connection adapters | I'm using the Requests: HTTP for Humans library and I got this weird error and I don't know what is mean.
No connection adapters were found for '192.168.1.61:8080/api/call'
Anybody has an idea?
| [
"You need to include the protocol scheme:\n'http://192.168.1.61:8080/api/call'\n\nWithout the http:// part, requests has no idea how to connect to the remote server.\nNote that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either... | [
596,
45,
1
] | [] | [] | [
"python",
"python_2.7",
"python_requests"
] | stackoverflow_0015115328_python_python_2.7_python_requests.txt |
Q:
Proper way to update the value of a variable inside a Python function?
My following program doesn't modify the original value of the variable myMatrix:
def transpos(matrixx: list):
newMatrix = [[matrixx[j][i] for j in range(len(matrixx))] for i in range(len(matrixx[0]))]
myMatrix = newMatrix
myMatrix = [... | Proper way to update the value of a variable inside a Python function? | My following program doesn't modify the original value of the variable myMatrix:
def transpos(matrixx: list):
newMatrix = [[matrixx[j][i] for j in range(len(matrixx))] for i in range(len(matrixx[0]))]
myMatrix = newMatrix
myMatrix = [[1, 2], [3, 4]]
transpos(myMatrix)
print(myMatrix)
What is the correct way ... | [
"It's enaugh that you add global myMatrix as below:\ndef transpos(matrixx: list):\n global myMatrix\n newMatrix = [[matrixx[j][i] for j in range(len(matrixx))] for i in range(len(matrixx[0]))]\n\n myMatrix = newMatrix\n\nmyMatrix = [[1, 2], [3, 4]]\ntranspos(myMatrix)\nprint(myMatrix)\n\n",
"Better way t... | [
0,
0
] | [] | [] | [
"function",
"list",
"python"
] | stackoverflow_0074209659_function_list_python.txt |
Q:
Finding the minimum distance from a point to a curve
I need to find the minimum distance from a point (X,Y) to a curve defined by four coefficients C0, C1, C2, C3 like y = C0 + C1X + C2X^2 + C3X^3
I have used a numerical approach using np.linspace and np.polyval to generate discrete (X,Y) for the curve and then t... | Finding the minimum distance from a point to a curve | I need to find the minimum distance from a point (X,Y) to a curve defined by four coefficients C0, C1, C2, C3 like y = C0 + C1X + C2X^2 + C3X^3
I have used a numerical approach using np.linspace and np.polyval to generate discrete (X,Y) for the curve and then the shapely 's Point, MultiPoint and nearest_points to find... | [
"Problem definition\nFor the sake of simplicity let's use P for the point and Px and Py for the coordinates. Let's call the function f(x).\nAn other way to look at you're problem is that you're trying to find an x that minimzes the distance between the P and the point (x, f(x))\nThe problem can then be formulated a... | [
1,
1
] | [] | [] | [
"geometry",
"python",
"shapely"
] | stackoverflow_0074207528_geometry_python_shapely.txt |
Q:
Looking for alternatives to increase performance in a FOR python loop
I'm currently running this five FOR loops to meet certain conditions and fill another dataframe column. Both dataframe sizes approximately 500 row so basically each loop i run I'm iterating over 250k combinations. Although it's working as expect... | Looking for alternatives to increase performance in a FOR python loop | I'm currently running this five FOR loops to meet certain conditions and fill another dataframe column. Both dataframe sizes approximately 500 row so basically each loop i run I'm iterating over 250k combinations. Although it's working as expected, its taking too much time to execute but i didnt find any alternatives y... | [
"You could probably combine the loops, then set a bool value for each condition, replacing the breaks.\ncond1, cond2, ... = False, False, ...\nfor x, linha_calc in calculos.iterrows():\n for z, linha_opf in opf.iterrows(): \n if (linha_calc['E'] == linha_opf['E']) & (\n linha_calc['F'] == linha... | [
1,
1
] | [] | [] | [
"dataframe",
"for_loop",
"pandas",
"performance",
"python"
] | stackoverflow_0074202088_dataframe_for_loop_pandas_performance_python.txt |
Q:
Pandas filter by substrings from two columns
I have two dataframes that are as follows:
Dataframe df1:
Rep
0 ec21b_AI_154OH
1 m2010_AI_066UW
2 20wh1_DS_416FC
Dataframe df2:
Address FirstPart SecondPart
0 address13 m2010 066UW
1 address22 2020e 999GV
2 address26 2020c ... | Pandas filter by substrings from two columns | I have two dataframes that are as follows:
Dataframe df1:
Rep
0 ec21b_AI_154OH
1 m2010_AI_066UW
2 20wh1_DS_416FC
Dataframe df2:
Address FirstPart SecondPart
0 address13 m2010 066UW
1 address22 2020e 999GV
2 address26 2020c 513DT
3 address35 evd18 874GO
4 ad... | [
"IIUC, you can extract the two part to use for a merge (here with named capturing groups, although optional if you use the left_on/right_on parameters or merge):\nout = df1.join(\n df1['Rep']\n .str.extract(r'^(?P<FirstPart>[^_]+).*?(?P<SecondPart>[^_]+)$')\n .merge(df2, how='left')['Address']\n)\n\noutput:\n ... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074206415_dataframe_pandas_python.txt |
Q:
reduce space between dendrogram and color row in Seaborn Clustermap
Hi everyone. I have two questions. First, does anyone know how to reduce the distance between the dendrogram and the color row. And then how to reduce the distance between the colour row and the actual heatmap.
Second, the bottom of the dendrogram... | reduce space between dendrogram and color row in Seaborn Clustermap |
Hi everyone. I have two questions. First, does anyone know how to reduce the distance between the dendrogram and the color row. And then how to reduce the distance between the colour row and the actual heatmap.
Second, the bottom of the dendrogram is really squished and difficult to read. Does anyone know how to chang... | [
"Here is a test to create something similar using the iris data set. To get a larger area for the dendogram, you can experiment with the dendrogram_ratio. The code below uses (.1, .8). The distance above and below the color row seems to be zero in the current version (Seaborn 0.11.1).\nimport seaborn as sns;\nimpor... | [
1,
0
] | [] | [] | [
"data_visualization",
"matplotlib",
"pandas",
"python",
"seaborn"
] | stackoverflow_0067040271_data_visualization_matplotlib_pandas_python_seaborn.txt |
Q:
Python - No module named "modules"
I am currently trying to import some python files inside of a folder named "modules". My file structure is as follows:
src
- classes
- modules
- image generator ( the file where I am trying to import modules)
Error:
from modules.processing import StableDiffusionProces... | Python - No module named "modules" | I am currently trying to import some python files inside of a folder named "modules". My file structure is as follows:
src
- classes
- modules
- image generator ( the file where I am trying to import modules)
Error:
from modules.processing import StableDiffusionProcessingTxt2Img, process_images
ModuleNotFou... | [
"What are packages?\nWe don't usually store all of our files on our computer in the same location. We use a well-organized hierarchy of directories for easier access.\nSimilar files are kept in the same directory, for example, we may keep all the songs in the \"music\" directory. Analogous to this, Python has packa... | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074209338_python.txt |
Q:
Switch to and click through cookie banners with Python Selenium
I've tried to deny the cookies on this website with the common find_element instruction, but it doesn't work and gives me a NoSuchElementException.
My attempt to switch to the new banner puts out the following: WebDriverException: Message: chrome not ... | Switch to and click through cookie banners with Python Selenium | I've tried to deny the cookies on this website with the common find_element instruction, but it doesn't work and gives me a NoSuchElementException.
My attempt to switch to the new banner puts out the following: WebDriverException: Message: chrome not reachable
Can someone please help me out on this problem?
Imports
fro... | [
"This is kind of a work around of the problem. You can make python click through it.\nimport pyautogui\npyautogui.moveTo(x, y) #Move a mouse to (x, y) coordinates on your screen. \npyautogui.click()\n\nPyautogui documentation\nTo get your mouse coordinates use:\npyautogui.position()\n\nThere is also little bit more... | [
0
] | [] | [] | [
"cookies",
"python",
"selenium",
"web_crawler"
] | stackoverflow_0074208816_cookies_python_selenium_web_crawler.txt |
Q:
Pass python variable to javascript to inform ipywidget datepicker timerange
I am trying to pass python variables to Javascript inorder to set the max and min dates of my ipywidget date picker. the goal is to be able to set the time range based off the max and min date of a pandas dataframe. I get an error with the... | Pass python variable to javascript to inform ipywidget datepicker timerange | I am trying to pass python variables to Javascript inorder to set the max and min dates of my ipywidget date picker. the goal is to be able to set the time range based off the max and min date of a pandas dataframe. I get an error with the code below.
code ---
d= DatePicker(
description='pick Date',
disabled=False
)
d.... | [
"This solved my issue.\n...\nimport json\npythondates = ['2022-10-01','2022-10-26']\nscript = Javascript(\"\"\"\nconst dates = %s;\nconst query = '.java_d > input: first-of-type';\ndocument.querySelector(query).setAttribute('min', dates[0];\ndocument.querySelector(query).setAttribute('max', dates[1];\n\"\"\" % json... | [
1
] | [] | [] | [
"datepicker",
"ipywidgets",
"python"
] | stackoverflow_0074207775_datepicker_ipywidgets_python.txt |
Q:
Django/Wagtail Rest API URL Filter with no response
I am using Wagtail and I have an API called 127.0.0.1:8000/api/v2/stories. In the API I am having this JSON response
{
"count": 81,
"results": [
{
"id": 122,
"title": "Test Blog",
"blog_authors": [
... | Django/Wagtail Rest API URL Filter with no response | I am using Wagtail and I have an API called 127.0.0.1:8000/api/v2/stories. In the API I am having this JSON response
{
"count": 81,
"results": [
{
"id": 122,
"title": "Test Blog",
"blog_authors": [
{
"id": 82,
"meta": {
... | [
"You need to add a custom filter to handle your author_name parameter. Like the filters provided by Wagtail itself, it should probably inherit from from rest_framework.filters import BaseFilterBackend\n"
] | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"wagtail",
"wagtail_apiv2"
] | stackoverflow_0074204701_django_django_rest_framework_python_wagtail_wagtail_apiv2.txt |
Q:
Pandas: Filling NaN values in dataframe with monthly mean
The dataframe I am working with is as follows:
date AA1 AB2 AC3 AD4
0 1996-01-01 00:00:00 NaN NaN NaN NaN
1 1996-01-01 01:00:00 NaN 19.2 NaN NaN
2 1996-01-01 02:00:00 NaN 16.4 NaN NaN
3 1996-01-01 03:... | Pandas: Filling NaN values in dataframe with monthly mean | The dataframe I am working with is as follows:
date AA1 AB2 AC3 AD4
0 1996-01-01 00:00:00 NaN NaN NaN NaN
1 1996-01-01 01:00:00 NaN 19.2 NaN NaN
2 1996-01-01 02:00:00 NaN 16.4 NaN NaN
3 1996-01-01 03:00:00 NaN 23.5 NaN NaN
4 1996-01-01 04:00:00 20.4 NaN ... | [
"Assuming your date column is of type datetime64 or equivalent:\ndf['AA2'] = df['AA2'].fillna(df.groupby(df.date.dt.month)['AA2'].transform('mean'))\n\nOr looping over all your columns (except the date column):\nfor col in df.columns.drop('date'):\n df[col] = df[col].fillna(df.groupby(df.date.dt.month)[col].tran... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074209763_pandas_python.txt |
Q:
how to record selenium webdriver test executions in python on window x64
Using python binding selenium3 webdriver for test automation, to record execution steps using castro but it is failing on Windows 7 x64.
Is there any other library or module which can be used for recording purpose
Code with castro
from castro... | how to record selenium webdriver test executions in python on window x64 | Using python binding selenium3 webdriver for test automation, to record execution steps using castro but it is failing on Windows 7 x64.
Is there any other library or module which can be used for recording purpose
Code with castro
from castro import Castro
from selenium import webdriver
from selenium.webdriver.common.k... | [
"I do not recommend using castro. It's really outdated, I've tried using it in my own tests and did get it running but it was too unstable. \nI'm currently using ffmpeg together with screen-capture-recorder (screen recording software) and it works like a charm. It allows you to set the framerate, resolution, bitrat... | [
7,
0,
0,
0
] | [] | [] | [
"automated_tests",
"python",
"selenium"
] | stackoverflow_0041885914_automated_tests_python_selenium.txt |
Q:
Python discord bot deletes every message except specific ones
it's my first time coding something and making a discord bot. But I've been trying to figure it out what is wrong with this code for a long time. I want one channel to only able to type specific words and delete everything else, but in this code no matt... | Python discord bot deletes every message except specific ones | it's my first time coding something and making a discord bot. But I've been trying to figure it out what is wrong with this code for a long time. I want one channel to only able to type specific words and delete everything else, but in this code no matter what i do it deletes everything, cheers
import os
import discord... | [
"to get it to work I changed:\nclient = discord.Client(intents=discord.Intents.default())\nintents = discord.Intents(message_content=True)\n\nto:\nintents = discord.Intents().all()\nclient = commands.Bot(command_prefix=\"$\", intents=intents)\n\nI would only use the intents you need to use however. I only put all f... | [
1
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0074209404_bots_discord_discord.py_python.txt |
Q:
Use static ip for MySQL connection in Heroku app
I have a python script that connects to an external database and outputs the results in JSON
This external database can be only accessed by whitelisted IP's
But this script is INSIDE a Laravel project hosted in Heroku
I installed a Static IP plugin (Proximo) but i n... | Use static ip for MySQL connection in Heroku app | I have a python script that connects to an external database and outputs the results in JSON
This external database can be only accessed by whitelisted IP's
But this script is INSIDE a Laravel project hosted in Heroku
I installed a Static IP plugin (Proximo) but i need how to setup the MySQL connection
// Laravel con... | [
"One option is to use fixie-wrench, a library which does port forwarding over a SOCKS5 proxy. This allows your application to connect to MySQL as if it were running on a local port.\nFixie-wrench was developed and open sourced by Fixie, a provider of a static IP addon for Heroku, but the library works with any SOCK... | [
0
] | [] | [] | [
"heroku",
"laravel",
"mysql",
"python"
] | stackoverflow_0069113932_heroku_laravel_mysql_python.txt |
Q:
What is Python's equivalent of Java's standard for-loop?
I'm writing a simple algorithm to check the primality of an integer and I'm having a problem translating this Java code into Python:
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
So, I've been trying to use this, bu... | What is Python's equivalent of Java's standard for-loop? | I'm writing a simple algorithm to check the primality of an integer and I'm having a problem translating this Java code into Python:
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
So, I've been trying to use this, but I'm obviously skipping the division by 3:
i = 3
while (i < i... | [
"\nThe only for-loop in Python is technically a \"for-each\", so you can use something like\nfor i in xrange(3, int(math.sqrt(n)), 2): # use 'range' in Python 3\n if n % i == 0:\n return False\n\nOf course, Python can do better than that:\nall(n % i for i in xrange(3, int(math.sqrt(n)), 2))\n\nwould be e... | [
23,
4,
3,
1,
0
] | [] | [] | [
"for_loop",
"java",
"loops",
"python",
"translate"
] | stackoverflow_0017415198_for_loop_java_loops_python_translate.txt |
Q:
Join strings in array column group by another array column in pandas dataframe
My dataframe contains three array columns having same length
| col_1 | col_2 | col_3 |
|-------------------------|-------------------------|------------------------------|
|['a'... | Join strings in array column group by another array column in pandas dataframe | My dataframe contains three array columns having same length
| col_1 | col_2 | col_3 |
|-------------------------|-------------------------|------------------------------|
|['a', 'b', 'c', 'd', 'e']|['n', 'n', 'n', 'd', 'd']|['cl', 'cl', 'cl', 'en', 'en']|
|['d... | [
"You can explode and use a double groupby.agg:\nout = (df\n .explode(list(df)) # explode all columns, use a specific list if needed\n .reset_index()\n .groupby(['index', 'col_3'])\n .agg(''.join)\n .reset_index('col_3')\n .groupby(level=0).agg(list)\n [df.columns]\n)\n\noutput:\n col_1 ... | [
1
] | [] | [] | [
"arrays",
"dataframe",
"pandas",
"python",
"string"
] | stackoverflow_0074209918_arrays_dataframe_pandas_python_string.txt |
Q:
Python : How to "merge" two class
I want to add some attributes and methods into various class. The methods and attributes that I have to add are the same but not the class to assign them, so I want to construct a class who assign new methods and attributes for a class given in argument.
I try this but it's not w... | Python : How to "merge" two class | I want to add some attributes and methods into various class. The methods and attributes that I have to add are the same but not the class to assign them, so I want to construct a class who assign new methods and attributes for a class given in argument.
I try this but it's not working:
(I know that is a very wrong wa... | [
"The Best answer is in the comments, it was useful for me so I decided to show it in an answer (thank to sr2222):\nThe way to dynamicaly declare inherance in Python is the type() built-in function.\nFor my example :\nclass A(object) :\n def __init__(self, args):\n self.a = 'a'\n self.args = args\n\... | [
14,
6,
4,
1,
1,
0,
0,
0
] | [] | [] | [
"class",
"merge",
"python"
] | stackoverflow_0009667818_class_merge_python.txt |
Q:
BigQuery execution time
After I send a query to be executed in BigQuery, how can I find the execution time and other statistics about this job?
The Python API for BigQuery has a suggestive field timeline, but barely mentioned in the documentation. However, this method returns an empty iterable.
So far, I have been... | BigQuery execution time | After I send a query to be executed in BigQuery, how can I find the execution time and other statistics about this job?
The Python API for BigQuery has a suggestive field timeline, but barely mentioned in the documentation. However, this method returns an empty iterable.
So far, I have been running this Python code, wi... | [
"When your job is \"DONE\", the BigQuery API returns a JobStatistics object (described here) that is accessible in Python through the attributes of your job object.\nThe available attrs are accessible here.\nFor accessing the time taken by your job you mainly have the job.created, job.started and job.ended attribut... | [
4,
0
] | [] | [] | [
"google_bigquery",
"python"
] | stackoverflow_0067025110_google_bigquery_python.txt |
Q:
Should I reinstall all Python libraries if I install Anaconda's Python as primary in my system?
I have been using Python on Windows for some time to analyze survey data, usually available in the form of Excel files. For this reason I have installed several libraries, including pywin32, holoview, bokeh, pandas, num... | Should I reinstall all Python libraries if I install Anaconda's Python as primary in my system? | I have been using Python on Windows for some time to analyze survey data, usually available in the form of Excel files. For this reason I have installed several libraries, including pywin32, holoview, bokeh, pandas, numpy and so on.
Now I have found that there is a Python distribution called Anaconda which is a prerequ... | [
"Here are the some answers from my side.\n1. Will the libraries & files conflit?\n\n\nNo. - Both local & Anaconda will have separete site packages folders to store installed libraries.No matter how many different versions of python you install there will be separate site-packages folders named with respective versi... | [
1
] | [] | [] | [
"anaconda",
"python"
] | stackoverflow_0074209563_anaconda_python.txt |
Q:
Trying to find the Eigenvectors for the specific Eigen Values
We were given a set of equations which we had to convert into a matrix. We were also given the k, m1 and m2 frequency values. After solving for the eigen values and coressponding vectors we were asked to solve according to the specific eigen values we c... | Trying to find the Eigenvectors for the specific Eigen Values | We were given a set of equations which we had to convert into a matrix. We were also given the k, m1 and m2 frequency values. After solving for the eigen values and coressponding vectors we were asked to solve according to the specific eigen values we calculated!
I've been trying to solve for the specific eigen vectors... | [
"For the future please add codeblocks in the question, as it makes it much easier for anyone to pick up your code and modify it.\nI think the issue (at least the error you have right now) comes from the fact that you are accessing the values of the numpy array using (i, i) instead of [i, i]. The way you are writing... | [
0
] | [] | [] | [
"differential_equations",
"eigenvalue",
"eigenvector",
"python"
] | stackoverflow_0074209617_differential_equations_eigenvalue_eigenvector_python.txt |
Q:
Why does sum(4 >= my_array)) print 6 instead of 10 (because the array starts from 0)?
my_array = np.concatenate((np.arange(10**6), np.array([4])))
my_array
array([ 0, 1, 2, ..., 999998, 999999, 4])
print(sum(4 >= my_array))
Output: 6
This print statement will print 6 instead of 10 which from w... | Why does sum(4 >= my_array)) print 6 instead of 10 (because the array starts from 0)? | my_array = np.concatenate((np.arange(10**6), np.array([4])))
my_array
array([ 0, 1, 2, ..., 999998, 999999, 4])
print(sum(4 >= my_array))
Output: 6
This print statement will print 6 instead of 10 which from what I understand should be (0+1+2+3+4)
I assume that sum(4>=my_array) does not sum the firs... | [
"Assuming print(sum(4 >= my_array)), this returns 6.\nThere are indeed 6 values lower or equal to 4, the first 5 ones:\n0, 1, 2, 3, 4\n\nThe one you added at the end: 4\nThis is easily seen if you just concatenate a short array:\nmy_array = np.concatenate((np.arange(10), np.array([4])))\n# array([0, 1, 2, 3, 4, 5, ... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074209578_python.txt |
Q:
Only 1 PhotoImage will display with tkinter Treeview
I'm trying to create a treeview which also has images for each row. Whenever I run this I only get one image to display. How do I fix this?
BTW: row[0] sends back a file path, not an image
def displayDB(admPag):
admPag.destroy()
DBPag = Tk()
DBPag.t... | Only 1 PhotoImage will display with tkinter Treeview | I'm trying to create a treeview which also has images for each row. Whenever I run this I only get one image to display. How do I fix this?
BTW: row[0] sends back a file path, not an image
def displayDB(admPag):
admPag.destroy()
DBPag = Tk()
DBPag.title("listr.")
DBPag.configure(bg="#31A1FF")
DBTr... | [
"You're only saving a reference to one image, and keep overwriting that reference. You need to keep a reference to all images. The easiest solution is to use a list. The following example shows one possible solution.\nDBTree.images = []\nfor row in cur:\n img = Image.open(str(row[3]))\n resize_img = img.resiz... | [
2
] | [] | [] | [
"python",
"tkinter",
"treeview"
] | stackoverflow_0074210096_python_tkinter_treeview.txt |
Q:
Textractor python library - Is there a way to export key values in reading order to csv?
I'm currently trying to use the textractor python library (https://github.com/aws-samples/amazon-textract-textractor/) to process a pdf using Amazon Textract.
I've been able to call the API and return results using the library... | Textractor python library - Is there a way to export key values in reading order to csv? | I'm currently trying to use the textractor python library (https://github.com/aws-samples/amazon-textract-textractor/) to process a pdf using Amazon Textract.
I've been able to call the API and return results using the library but exporting the key values does not seem to have any specific logical order.
I'm trying to ... | [
"Version 1.0.16 (pip install amazon-textract-textractor==1.0.16) should address this issue. The entities are sorted by their page then Y,X coordinates which should preserve the ordering of your keys and values.\nHowever, depending on the number of questions that you have, Queries might be a better fit (and cheaper)... | [
1
] | [] | [] | [
"amazon_textract",
"python"
] | stackoverflow_0074132842_amazon_textract_python.txt |
Q:
What happens behind the scenes when we execute these two lines of code
vis1 = [0 for i in range(10)]
vis2 = [0] * 10
Result of these two lines is
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
When we execute
name = "ram" * 10
then it multiplies "ram" 10 times and returns whole string
ramramramra... | What happens behind the scenes when we execute these two lines of code | vis1 = [0 for i in range(10)]
vis2 = [0] * 10
Result of these two lines is
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
When we execute
name = "ram" * 10
then it multiplies "ram" 10 times and returns whole string
ramramramramramramramramramram
So why the same is not happening with [0]*10 it should ... | [
"You are not going anywhere wrong. I get the same result. I also intuitively expected that the vis2 would be [[0], [0], ..., [0]], but then again this is just my opinion vs. opinion of whoever designed this particular aspect of Python language. Somebody had to make this choice and this person did it for whatever re... | [
2
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074210106_list_python_python_3.x.txt |
Q:
Global array returns empty despite having an element
I have what might be a quite simple problem, but I still cannot solve it.
I have the following code:
list_of_conditions = []
def function_1():
time.sleep(60)
global list_of_conditions
condition=list_of_conditions.pop()
condition.notify() ... | Global array returns empty despite having an element | I have what might be a quite simple problem, but I still cannot solve it.
I have the following code:
list_of_conditions = []
def function_1():
time.sleep(60)
global list_of_conditions
condition=list_of_conditions.pop()
condition.notify()
print("F1: Done")
def function_2():
condition =... | [
"\nI dont get it why the list is empty\n\nBecause you're using Multiprocessing. Processes do not share mutable state: each Process starts with a blank slate, i.e. it sees the module as it was at intial evaluation. Sharing mutable state in multithreading/multiprocessing paradigms is problematic: what if two threads... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074210053_python.txt |
Q:
tkinter Enter and Leave Bindings
So the problem I am facing is with the "Enter" and "Leave" bind things. It works for hovering which is great but it also fire when the button is clicked which messes up my system which I have.
My system is that when being hovered over the images move up to show they are being highl... | tkinter Enter and Leave Bindings | So the problem I am facing is with the "Enter" and "Leave" bind things. It works for hovering which is great but it also fire when the button is clicked which messes up my system which I have.
My system is that when being hovered over the images move up to show they are being highlighted and then when you click them th... | [
"If I reproduced your problem correctly, I guess it should be something like this:\n\nYou hover over a random image and it goes up when your mouse is on it and goes down when you leave it\nWhen you click the image and leave the image doesn't go down which messes up things later\n\nYou might be thinking its the prob... | [
0
] | [] | [] | [
"button",
"enter",
"python",
"tkinter"
] | stackoverflow_0074201517_button_enter_python_tkinter.txt |
Q:
Repeat Integer Input and Print ; Then Repeat Input and Print
q = int(input("How many numbers do you need to check? "))
dt = 0
ndt = 0
for i in range(q):
w = int(input("Enter number: "))
if w % 3 == 0:
print("{} is divisible by 3.".format(w))
dt = dt + 1
else:
print("{} is not divisible by 3.".form... | Repeat Integer Input and Print ; Then Repeat Input and Print | q = int(input("How many numbers do you need to check? "))
dt = 0
ndt = 0
for i in range(q):
w = int(input("Enter number: "))
if w % 3 == 0:
print("{} is divisible by 3.".format(w))
dt = dt + 1
else:
print("{} is not divisible by 3.".format(w))
ndt = ndt + 1
print("You entered {} number(s) that are ... | [
"I think it's just your tabbing that needs to be changed. To get your if statement inside the loop it needs to be tabbed to the correct position.\nq = int(input(\"How many numbers do you need to check? \"))\ndt = 0\nndt = 0\n\nfor i in range(q):\n w = int(input(\"Enter number: \"))\n if w % 3 == 0:\n p... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074210197_python.txt |
Q:
How to rotate a widget forward another?
I would like to know how I can rotate a widget forward another. Here is what I have:
(I use scatter and animation to rotate my widget, and I don't want to use .kv file here)
terrain = Image(source = "terrain.png")
target = Image(source = "target.png", center = (300, 200))
t... | How to rotate a widget forward another? | I would like to know how I can rotate a widget forward another. Here is what I have:
(I use scatter and animation to rotate my widget, and I don't want to use .kv file here)
terrain = Image(source = "terrain.png")
target = Image(source = "target.png", center = (300, 200))
terrain.add_widget(target)
arrow = Image(sour... | [
"I think it is simpler to just use context instructions, rather than a Scatter widget. Here is an example (based on your posted code):\nclass TestApp(App):\n def build(self):\n\n root = FloatLayout() # use a Layout widget to contain the Images\n\n terrain = Image(source = \"terrain.png\")\n ... | [
0
] | [] | [] | [
"animation",
"kivy",
"python",
"python_3.x",
"rotation"
] | stackoverflow_0074205991_animation_kivy_python_python_3.x_rotation.txt |
Q:
computing pi value using python, division always zero
I am trying to use python to compute an approximation of (pi) using unlimited series.
stopping condition is for accuracy = 10**(-9)
accuracy is abs(exact_pi-computed_pi)
my code:
from math import sqrt
exact_pi=3.14159265358979323846
accuracy=10**(-9)
computed... | computing pi value using python, division always zero | I am trying to use python to compute an approximation of (pi) using unlimited series.
stopping condition is for accuracy = 10**(-9)
accuracy is abs(exact_pi-computed_pi)
my code:
from math import sqrt
exact_pi=3.14159265358979323846
accuracy=10**(-9)
computed_pi=float(sqrt(12))
k=1
while abs(float(computed_pi)-float... | [
"As @quamrana noticed you have missed sum operation.\n# your code before while\n\nwhile abs(computed_pi - exact_pi) > accuracy:\n multiplier = sum((-3)**(-i)/(2 * i + 1) for i in range(k))\n computed_pi = 12**0.5 * multiplier\n k += 1\n\nor slightly optimized version (thanks again to quamrana)\nmultipler =... | [
1,
1
] | [] | [] | [
"math",
"python"
] | stackoverflow_0074209994_math_python.txt |
Q:
How to run an .ipynb Jupyter Notebook from terminal?
I have some code in a .ipynb file and got it to the point where I don't really need the "interactive" feature of IPython Notebook. I would like to just run it straight from a Mac Terminal Command Line.
Basically, if this were just a .py file, I believe I could j... | How to run an .ipynb Jupyter Notebook from terminal? | I have some code in a .ipynb file and got it to the point where I don't really need the "interactive" feature of IPython Notebook. I would like to just run it straight from a Mac Terminal Command Line.
Basically, if this were just a .py file, I believe I could just do python filename.py from the command line. Is there ... | [
"nbconvert allows you to run notebooks with the --execute flag:\njupyter nbconvert --execute <notebook>\n\nIf you want to run a notebook and produce a new notebook, you can add --to notebook:\njupyter nbconvert --execute --to notebook <notebook>\n\nOr if you want to replace the existing notebook with the new output... | [
221,
152,
46,
41,
20,
11,
10,
5,
4,
2,
1,
0,
0,
0
] | [] | [] | [
"ipython",
"jupyter_notebook",
"nbconvert",
"python"
] | stackoverflow_0035545402_ipython_jupyter_notebook_nbconvert_python.txt |
Q:
Python: Dictionary content changes without declaration
I have a Problem in this function:
def show_selected_button(self):
attrbs = required_attributes[self.modeComboBox.currentText()]
layers = QgsProject.instance().mapLayersByName(self.layerComboBox.currentText())
layer = layers[0]
... | Python: Dictionary content changes without declaration | I have a Problem in this function:
def show_selected_button(self):
attrbs = required_attributes[self.modeComboBox.currentText()]
layers = QgsProject.instance().mapLayersByName(self.layerComboBox.currentText())
layer = layers[0]
layer.selectAll()
selected_features = layer.getSelec... | [
"By assigning to attrbs value of required_attributes[self.modeComboBox.currentText()] you've created a link to the same object in memory, so whenever you change attrbs now you are changing list inside dictionary.\nattrbs = required_attributes[self.modeComboBox.currentText()]\n\nCheck this answer for an example: htt... | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074210074_dictionary_python.txt |
Q:
How to filter items in text string by first occurence
I have a method for extracting some values from a text string. But the ordering is now via how many times the word in the list occurrences. And I want to have the ordering via first occurence in text string.
So this is the text:
text = """['
a)
Factuur
Verdi ... | How to filter items in text string by first occurence | I have a method for extracting some values from a text string. But the ordering is now via how many times the word in the list occurrences. And I want to have the ordering via first occurence in text string.
So this is the text:
text = """['
a)
Factuur
Verdi Import Schoolfruit
Factuur nr. : 71201 Koopliedenweg 33
D... | [
"import re\n\ndef regex_fruit_cost(subst):\n return rf\"(?:{subst}).*?(?P<number>[0-9,.]*)\\n\"\n\nfruits_groups = (f\"(?:{fruit})\" for fruit in fruit_words)\nfruits_combined_with_capture = f'({\"|\".join(fruits_groups)})'\nfruits_pattern = regex_fruit_cost(fruits_combined_with_capture)\nprint(re.findall(fruits... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074207382_python.txt |
Q:
Determine position of element in list with low time complexity
I do the following
L = [[1], [2], [3], [1,2], [2,3], [1,2,3]]
L1, L2, L3 = [], [], []
for x in L:
if len(x) == 1:
L1.append(x)
elif len(x) == 2:
L2.append(x)
elif len(x) == 3:
L3.append(x)
and I would like to then b... | Determine position of element in list with low time complexity | I do the following
L = [[1], [2], [3], [1,2], [2,3], [1,2,3]]
L1, L2, L3 = [], [], []
for x in L:
if len(x) == 1:
L1.append(x)
elif len(x) == 2:
L2.append(x)
elif len(x) == 3:
L3.append(x)
and I would like to then be able to as an example
for x in L3:
for i in range(len(x)):
... | [
"I created a dictionary to store the lists by their length.\nThen we create sublists from the lists of length 3 to check if they exist in the lists of length 2.\nlist_of_lists = [[1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]\n\nsublists_by_len = {}\nfor item in list_of_lists:\n key = len(item)\n if key not in sub... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074131272_python.txt |
Q:
How to use str.contains to identify a word within column values in Python?
currently in my data I have a column that contains description of transaction. I want to use str.contains to identify which values/rows are AW (the fast food store) transaction. However, when I use data['cat_desc'].str.contains('AW', case=F... | How to use str.contains to identify a word within column values in Python? | currently in my data I have a column that contains description of transaction. I want to use str.contains to identify which values/rows are AW (the fast food store) transaction. However, when I use data['cat_desc'].str.contains('AW', case=False, na=False), it also identifies values that have string 'aw', for example 'a... | [
"Then use a regex with word boundaries ('\\b'):\ndata['cat_desc'].str.contains(r'\\bAW\\b', case=False, na=False, regex=True)\n\nNB. By default contains uses regex=True.\n",
"import re\n\nx = \"awxxx\"\ny = \"aw\"\n\na = bool(re.match(r\"^aw$\", x))\nb = bool(re.match(r\"^aw$\", y))\n\nprint(a, b)\n\n"
] | [
0,
0
] | [] | [] | [
"contains",
"dataframe",
"pandas",
"python",
"search"
] | stackoverflow_0074210254_contains_dataframe_pandas_python_search.txt |
Q:
Is there a way to define a MongoDB schema using Motor?
There is a way to define MongoDB collection schema using mongoose in NodeJS. Mongoose verifies the schema at the time of running the queries.
I have been unable to find a similar thing for Motor in Python/Tornado. Is there a way to achieve a similar effect in ... | Is there a way to define a MongoDB schema using Motor? | There is a way to define MongoDB collection schema using mongoose in NodeJS. Mongoose verifies the schema at the time of running the queries.
I have been unable to find a similar thing for Motor in Python/Tornado. Is there a way to achieve a similar effect in Motor, or is there a package which can do that for me?
| [
"No there isn't. Motor is a MongoDB driver, it does basic operations but doesn't provide many conveniences. An Object Document Mapper (ODM) library like MongoTor, built on Motor, provides higher-level features like schema validation.\nI don't vouch for MongoTor. Proceed with caution. Consider whether you really nee... | [
4,
2,
0
] | [] | [] | [
"mongodb",
"motordriver",
"python",
"tornado_motor"
] | stackoverflow_0036841121_mongodb_motordriver_python_tornado_motor.txt |
Q:
Unittest mock: return function which receives one pytest fixture and one argument
I'm creating some unit tests and using pytest fixtures in combination with some unittest.mock patch.object calls.
I would like to reuse a function that is called by some of my tests. It makes use of a pytest fixture (specified as the... | Unittest mock: return function which receives one pytest fixture and one argument | I'm creating some unit tests and using pytest fixtures in combination with some unittest.mock patch.object calls.
I would like to reuse a function that is called by some of my tests. It makes use of a pytest fixture (specified as the first "argument" of the function) and it requires an additional argument. It looks som... | [
"What you need right here, is the factory pattern:\nimport pandas as pd\nimport pytest\nimport os\nfrom unittest.mock import patch\n\n@pytest.fixture()\ndef rootdir():\n return os.path.dirname(os.path.abspath(__file__))\n\n@pytest.fixture()\ndef my_mock_ret(rootdir):\n def _my_mock_ret(number):\n print... | [
0
] | [] | [] | [
"pytest",
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0074210146_pytest_python_python_unittest_unit_testing.txt |
Q:
Raise Exception if thread hangs
I have scripts running 24/7 that sometimes get stuck when a thread in concurrent.futures gets no response for a request.
The hanging-threads 2.0.5 module prints out which thread hangs and why.
The print looks something like this:
Thread 139646566659840 "ThreadPoolExecutor-666849_1" ... | Raise Exception if thread hangs | I have scripts running 24/7 that sometimes get stuck when a thread in concurrent.futures gets no response for a request.
The hanging-threads 2.0.5 module prints out which thread hangs and why.
The print looks something like this:
Thread 139646566659840 "ThreadPoolExecutor-666849_1" hangs - ... | [
"\nconcurrent futures can not be cancelled while running\n\nThis is your problem. A hanging thread is still 'running'. Cancelling it from outside is not possible.\nThus you have two options:\n\nswitch to something which can be cancelled, like a ProcessPoolExecutor, or\nrewrite the blocking code so it fails.\n\nSi... | [
0
] | [] | [] | [
"concurrent.futures",
"python",
"threadpool"
] | stackoverflow_0074210269_concurrent.futures_python_threadpool.txt |
Q:
How do I turn the X-ticks and Y-ticks on a matplotlib plot into a tuppled list in python?
I would like to turn the xticks (feature names) and yticks (feature values) into a tuppled list in python so I can eventually export the pairs to a csv. How would I do this? here is the code for the plot below. Thanks in adva... | How do I turn the X-ticks and Y-ticks on a matplotlib plot into a tuppled list in python? | I would like to turn the xticks (feature names) and yticks (feature values) into a tuppled list in python so I can eventually export the pairs to a csv. How would I do this? here is the code for the plot below. Thanks in advance.
from sklearn import svm
import matplotlib.pyplot as plt
def feature_plot(classifier, featu... | [
" classifier = svm.LinearSVC(C=0.01, max_iter=10000, dual=False).fit(Xx_train2, yx_train)\nfeature_names=pandasdfx.drop(columns=['target_label', axis = 1).columns.values\ndef feature_plot(classifier, feature_names, top_features=25):\n coef = classifier.coef_.ravel()\n top_positive_coefficients = np.argsort(coef)[-t... | [
1
] | [] | [] | [
"matplotlib",
"python",
"svm"
] | stackoverflow_0074115816_matplotlib_python_svm.txt |
Q:
How I make color calibration in opencv using a colorchecker?
I have a image of the colorchecker get by a digital camera, how i use this to calibrate the images using opencv?
follow below the colorchecker image:
A:
Are you asking how to do color calibration or how to do it with OpenCV?
In order to do color calib... | How I make color calibration in opencv using a colorchecker? | I have a image of the colorchecker get by a digital camera, how i use this to calibrate the images using opencv?
follow below the colorchecker image:
| [
"Are you asking how to do color calibration or how to do it with OpenCV?\nIn order to do color calibration you use the last row (gray tones) of the calibration board. Here is what you should do for color calibration step by step:\n\nCapture an image and take small regions inside the gray regions. 10x10 pixels in th... | [
2,
0
] | [] | [] | [
"camera_calibration",
"opencv",
"python"
] | stackoverflow_0018897730_camera_calibration_opencv_python.txt |
Q:
Parse json encoded attributes from request body
I'm json encoding an attribute in POST data request (due to it being a list of Sending list of dicts as value of dict with requests.post going wrong ) but I'm having trouble reading it back.
In my endpoint when I receive the request the body looks like this:
The post... | Parse json encoded attributes from request body | I'm json encoding an attribute in POST data request (due to it being a list of Sending list of dicts as value of dict with requests.post going wrong ) but I'm having trouble reading it back.
In my endpoint when I receive the request the body looks like this:
The post request is done like this:
params = {
"listofdic... | [
"Turns out the body content was URL-encoded and that would need to decode it as Url decode UTF-8 in Python says.\nOther option to avoid request library url-encoding your data body is to use a full json as the data object. So doing:\nparams = {\n \"listofdicts\": [\n {\"variable\": \"1\"},\n {\"va... | [
1
] | [] | [] | [
"json",
"python",
"request"
] | stackoverflow_0074207690_json_python_request.txt |
Q:
5 repeats of a for loop multiplication
I'm a beginner at python, and have been given this task:
Write a program that lets a user input numbers and have them multiplied. The user can use the program 5 times, then it should stop. Use at least a for loop and a function.
I believe the code here will ask for the number... | 5 repeats of a for loop multiplication | I'm a beginner at python, and have been given this task:
Write a program that lets a user input numbers and have them multiplied. The user can use the program 5 times, then it should stop. Use at least a for loop and a function.
I believe the code here will ask for the numbers, multiply and give the answer, but how do ... | [
"\nhow do I get it to run 5 times then stop asking for more numbers?\n\n\nGet rid of the for i in range(1,num2+1) loop, since you don't need a loop in order to calculate the product of two numbers.\nAdd a for i in range(5) loop at the very top of your code, and then indent everything under it 4 spaces to the right.... | [
1,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074173213_for_loop_python.txt |
Q:
How to deal with Optional[int] in Protocol classes
I have created the following Protocol class:
from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, Optional, Protocol, runtime_checkable
@runtime_checkable
class PipelineProcess(Protocol):
def update(self):
..... | How to deal with Optional[int] in Protocol classes | I have created the following Protocol class:
from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, Optional, Protocol, runtime_checkable
@runtime_checkable
class PipelineProcess(Protocol):
def update(self):
...
def set_inputs(self, inputs: Dict[str, int]):
... | [
"Since out_value is declared to be of the union type int | None, setting it as value of a dictionary expected to be of type dict[str, int] is incorrect. So you need to assure the type checker (and yourself) that by the time you put into it the dictionary out_value is in fact an int. This can be easily accomplished ... | [
0
] | [] | [] | [
"annotations",
"python",
"python_typing",
"structural_typing"
] | stackoverflow_0074179380_annotations_python_python_typing_structural_typing.txt |
Q:
Getting BeautifulSoup to find a specific
I'm trying to put together a basic HTML scraper for a variety of scientific journal websites, specifically trying to get the abstract or introductory paragraph.
The current journal I'm working on is Nature, and the article I've been using as my sample can be seen at http... | Getting BeautifulSoup to find a specific | I'm trying to put together a basic HTML scraper for a variety of scientific journal websites, specifically trying to get the abstract or introductory paragraph.
The current journal I'm working on is Nature, and the article I've been using as my sample can be seen at http://www.nature.com/nature/journal/v463/n7284/abs... | [
"That html is pretty much malformed, and xml.dom.minidom cannot parse, and BeautiFulSoup parsing not working well.\nI removed some <!-- ... --> parts and parse again with BeautiFulSoup, then its seems better and able to run soup.find('p', attrs={'class' : 'lead'})\nHere's the code I tried\n>>> html =re.sub(re.compi... | [
5,
2,
0
] | [] | [] | [
"beautifulsoup",
"html_content_extraction",
"python"
] | stackoverflow_0002521482_beautifulsoup_html_content_extraction_python.txt |
Q:
Tkinter independent windows
I have a gui that I wrote with tkinter and I want to call it again with a button how do I do this (They will be independent of each other)
I want to do like this:
import tkinter
root = Tk()
root.title("test")
def testt()
root()
Button(root, text='window +', command=testt).pack()
... | Tkinter independent windows | I have a gui that I wrote with tkinter and I want to call it again with a button how do I do this (They will be independent of each other)
I want to do like this:
import tkinter
root = Tk()
root.title("test")
def testt()
root()
Button(root, text='window +', command=testt).pack()
root.mainloop()
| [
"You also have to import some modules as shown.\nTry this:\nfrom tkinter import Tk, Button, Toplevel\n\ndef testt():\n root1 = Toplevel()\n root1.mainloop()\n\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074210406_python_tkinter.txt |
Q:
neo4j unique constraint violation when using MERGE?
I have code to add nodes to a neo4j instance via the python driver. Nodes are matched based on label and 'name', and there is a unique constraint imposed on label and 'name'. I use MERGE so that I either MATCH or CREATE a node depending whether it exists. I then ... | neo4j unique constraint violation when using MERGE? | I have code to add nodes to a neo4j instance via the python driver. Nodes are matched based on label and 'name', and there is a unique constraint imposed on label and 'name'. I use MERGE so that I either MATCH or CREATE a node depending whether it exists. I then add new properties if I matched an existing node but have... | [
"Here is a short Python bit of how I imagine the stripped down version of what you're doing looks like\nimport neo4j\nimport neo4j.exceptions\n\n\ndef main():\n uri = \"neo4j://localhost:7687\"\n user = \"neo4j\"\n password = \"pass\"\n auth = neo4j.basic_auth(user, password)\n with neo4j.GraphDataba... | [
0
] | [] | [] | [
"neo4j",
"python"
] | stackoverflow_0073991749_neo4j_python.txt |
Q:
Why does my image convert to a tensor with only ones?
I am using the GTZAN dataset (containing 1000 songs with 10 genres) to make a music genre classification project.
I tried to convert a dataset of images, which are spectrograms of the songs, into tensors but it only returns a tensor of ones.
This is how I tried... | Why does my image convert to a tensor with only ones? | I am using the GTZAN dataset (containing 1000 songs with 10 genres) to make a music genre classification project.
I tried to convert a dataset of images, which are spectrograms of the songs, into tensors but it only returns a tensor of ones.
This is how I tried to do it:
transform = T.Compose([
T.Resize(image_size),
T.... | [
"Are you sure it is all ones? Try to compute maximum/minimum/mean.\nIf that's the case, maybe you are reading the files assuming the wrong format.\nThis notebook could be of help https://www.kaggle.com/code/mireiaboneta/cnnmodel\n"
] | [
0
] | [] | [] | [
"deep_learning",
"python",
"pytorch",
"tensor",
"transform"
] | stackoverflow_0074197640_deep_learning_python_pytorch_tensor_transform.txt |
Q:
How to create a new matrix using MIN and MAX from original array
I have a matrix named A, and I want to create a new matrix named B, where each element value is generated by this formula:
B[i][j] = (A[i][j] - MIN) / (MAX - MIN), where
i is the line index
j is the column index.
MIN is the minimum from A
MAX is the... | How to create a new matrix using MIN and MAX from original array | I have a matrix named A, and I want to create a new matrix named B, where each element value is generated by this formula:
B[i][j] = (A[i][j] - MIN) / (MAX - MIN), where
i is the line index
j is the column index.
MIN is the minimum from A
MAX is the value with highest value from A.
I tried a for loop but I want to in... | [
"I'm not sure whether the MIN&MAX are standing for\n\nthe MIN&MAX value of the column/row from A, or\nthe MIN&MAX value of the entire matrix(A).\n\nPlz leave a comment if I'm misunderstanding and here's the solution for second meaning of MIN&MAX.\nimport numpy as np\n\nA = np.matrix(np.arange(12).reshape((3,4)))\nM... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074210133_python.txt |
Q:
Fetching specific row of multiple excel files
I want to gather a specific row of multiple excel files in a single sheet. As you can see in the image I am getting bin_depth of 0.5 in each row.
.
But when I am saving the result. It is coming like
.
This is my code for fetching second row of multiple excel files
impo... | Fetching specific row of multiple excel files | I want to gather a specific row of multiple excel files in a single sheet. As you can see in the image I am getting bin_depth of 0.5 in each row.
.
But when I am saving the result. It is coming like
.
This is my code for fetching second row of multiple excel files
import pandas as pd
import os as os
from glob import gl... | [
"the first line being a header. So, with the following code, you're essentially picking up line 3 of excel sheet\nif you need the line 2 change as follows\nrow2 = pd.DataFrame(data.iloc[0]).transpose()\n\naggregate.to_excel(\"/Users/gulfcarbon2/Downloads/Modis/absorption file/aggregate1.xlsx\")\n\n\n"
] | [
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074210442_excel_pandas_python.txt |
Q:
Python: Replace string parts that DO NOT match specific regex
I need to url encode parts of the string that do not match a regex. Current solution (below) is:
to select what regex I match (##.*##)
put found substrings in a list and replace them with some not encodable indexes ~~1~~
encode everything (entire url)
... | Python: Replace string parts that DO NOT match specific regex | I need to url encode parts of the string that do not match a regex. Current solution (below) is:
to select what regex I match (##.*##)
put found substrings in a list and replace them with some not encodable indexes ~~1~~
encode everything (entire url)
put back the elements I found
I have this code that works. But I'm... | [
"You could use re.sub to match the ##.*?## pattern, but also the text that preceded it, so that you have both categories of text as a pair. Then apply the URL encoding only on the first part in the callback function. To deal with the ending of the input, allow the second part to be either the ##.*?## pattern or the... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074209238_python_regex.txt |
Q:
Perform a logical exclusive OR on a Django Q object
I would like to perform a logical exclusive OR (XOR) on django.db.models.Q objects, using operator module to limit the choices of a model field to a subset of foreignkey. I am doing this in Django 1.4.3 along with Python 2.7.2. I had something like this:
import o... | Perform a logical exclusive OR on a Django Q object | I would like to perform a logical exclusive OR (XOR) on django.db.models.Q objects, using operator module to limit the choices of a model field to a subset of foreignkey. I am doing this in Django 1.4.3 along with Python 2.7.2. I had something like this:
import operator
from django.conf import settings
from django.db ... | [
"You could add an __xor__() method to Q that uses and/or/not to do the XOR logic.\nfrom django.db.models import Q\n\nclass QQ:\n def __xor__(self, other): \n not_self = self.clone()\n not_other = other.clone()\n not_self.negate()\n not_other.negate()\n\n x = self & not_other... | [
14,
0
] | [] | [] | [
"django",
"django_q",
"django_queryset",
"python"
] | stackoverflow_0014711203_django_django_q_django_queryset_python.txt |
Q:
How to evaluate coroutine in pycharms interactive debugger
When interrupting execution of python async code with PyCharm's interactive debugger (breakpoints) we can inspect the environment with PyCharm's debugging tools like "evaluate expression" or "Execute Line in Python Console".
How can we evaluate coroutines ... | How to evaluate coroutine in pycharms interactive debugger | When interrupting execution of python async code with PyCharm's interactive debugger (breakpoints) we can inspect the environment with PyCharm's debugging tools like "evaluate expression" or "Execute Line in Python Console".
How can we evaluate coroutines within these debugging tools?
| [
"You can try to use PyCharm Evaluate async code plugin, link to plugin https://plugins.jetbrains.com/plugin/14476-evaluate-async-code\n",
"No way at the moment, please vote for https://youtrack.jetbrains.com/issue/PY-22961\n",
"Update from October 2022\nMake sure you have the latest version of PyCharm, because... | [
3,
2,
0
] | [] | [] | [
"debugging",
"pycharm",
"python",
"python_asyncio"
] | stackoverflow_0059610164_debugging_pycharm_python_python_asyncio.txt |
Q:
What is considered to be a good silhouette score?
I am currently doing some clustering based on words embeddings, and I am using some methods (elbow and David-Boulding) to determine the optimal number of clusters I should consider. In addition, I consider the silhouette measure. If I understood it correctly, it is... | What is considered to be a good silhouette score? | I am currently doing some clustering based on words embeddings, and I am using some methods (elbow and David-Boulding) to determine the optimal number of clusters I should consider. In addition, I consider the silhouette measure. If I understood it correctly, it is a measure of the correct match of the data with the co... | [
"Just searched this myself.\nA silhouette score of one means each data point is unlikely to be assigned to another cluster.\nA score close to zero means each data point could be easily assigned to another cluster\nA score close to -1 means the datapoint is misclassified.\nBased on these assumptions, I'd say 0.55 is... | [
0
] | [] | [] | [
"k_means",
"python"
] | stackoverflow_0066342844_k_means_python.txt |
Q:
Check if there is any selenium already open with firefox in python
I've been trying for some time to get this function to work, but I've tried several ways and I still can't. can anybody help me?
My goal is to prevent multiple browsers from being opened, that is, to check if there is already an instance of seleniu... | Check if there is any selenium already open with firefox in python | I've been trying for some time to get this function to work, but I've tried several ways and I still can't. can anybody help me?
My goal is to prevent multiple browsers from being opened, that is, to check if there is already an instance of selenium firefox already open and return it so that the already open window can... | [
"The below snippet isn't exactly your solution, but it would show a prompt if more than one instance of firefox is commanded by the program to run. The prompt would look like this although this won't focus on the opened window, the code would start running on that already open instance of Firefox, avoiding the clut... | [
0,
0
] | [] | [] | [
"firefox",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074197412_firefox_python_selenium_selenium_webdriver.txt |
Q:
In dataframe, validate phone nuber with country code
In dataframe, some contact numbers have prefixes (country code) and some haven't.
I want to fix and remove the unnecessary thing from numbers
df1
id contact
1 +1(123)-456-7890
2 +552(123)-(456)-(7890)
3 (+91)1234567890 // correct
4 123-456-7890 ... | In dataframe, validate phone nuber with country code | In dataframe, some contact numbers have prefixes (country code) and some haven't.
I want to fix and remove the unnecessary thing from numbers
df1
id contact
1 +1(123)-456-7890
2 +552(123)-(456)-(7890)
3 (+91)1234567890 // correct
4 123-456-7890 // by default add +1, if there is no code
5 ... | [
"You can create a copy of the df and iterate over it, check if contact element starts with () with the library re (findAll), apply a regex with a regular expression to format the contact element and ignores the blank elements.\n"
] | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074118564_dataframe_pandas_python.txt |
Q:
Better way to check if variable is string of integer
I need to check if some variable is an integer within quotes. So, naturally, I did the following:
! pip install smartprint
def isIntStr(n):
# first, the item must be a string
if not isinstance(n, str):
return False
# second, we try to con... | Better way to check if variable is string of integer | I need to check if some variable is an integer within quotes. So, naturally, I did the following:
! pip install smartprint
def isIntStr(n):
# first, the item must be a string
if not isinstance(n, str):
return False
# second, we try to convert it to integer
try:
int(n)
return ... | [
"You could also use the any() function together with the isDigit() function as shown in this answer https://stackoverflow.com/a/19859308/12373911\n",
"I think this solution be better.\ndef is_int_or_str(x):\n if isinstance(x, str):\n return x.strip().isnumeric()\n else:\n return False\n\nprint... | [
3,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074210425_python_python_3.x.txt |
Q:
Convert a pandas.core.indexes.numeric.Int64Index to an integer
I used the below code to return the index of a unique ID value
n = df.index[df['ID'] == 55555]
but n is a value of type pandas.core.indexes.numeric.Int64Index but I need it as an integer to complete the code below.
df.at[n, 'Name'] = 'John'
how can i... | Convert a pandas.core.indexes.numeric.Int64Index to an integer | I used the below code to return the index of a unique ID value
n = df.index[df['ID'] == 55555]
but n is a value of type pandas.core.indexes.numeric.Int64Index but I need it as an integer to complete the code below.
df.at[n, 'Name'] = 'John'
how can i extract the integer value of n ?
| [
"You can just call [0]\ndf.at[n[0], 'Name'] = 'John'\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074210653_pandas_python.txt |
Q:
Opposite of dropna() in pandas
I have a pandas DataFrame that I want to separate into observations for which there are no missing values and observations with missing values. I can use dropna() to get rows without missing values. Is there any analog to get rows with missing values?
#Example DataFrame
import panda... | Opposite of dropna() in pandas | I have a pandas DataFrame that I want to separate into observations for which there are no missing values and observations with missing values. I can use dropna() to get rows without missing values. Is there any analog to get rows with missing values?
#Example DataFrame
import pandas as pd
df = pd.DataFrame({'col1': [... | [
"Check null by row and filter with boolean indexing:\ndf[df.isnull().any(1)]\n\n# col1 col2\n#1 NaN 7.0\n#2 3.0 NaN\n\n",
"~ = Opposite :-)\ndf.loc[~df.index.isin(df.dropna().index)]\n\nOut[234]: \n col1 col2\n1 NaN 7.0\n2 3.0 NaN\n\nOr \ndf.loc[df.index.difference(df.dropna().index)]\nOut[235]: ... | [
29,
8,
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0046626639_pandas_python.txt |
Q:
python exception message capturing
import ftplib
import urllib2
import os
import logging
logger = logging.getLogger('ftpuploader')
hdlr = logging.FileHandler('ftplog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(log... | python exception message capturing | import ftplib
import urllib2
import os
import logging
logger = logging.getLogger('ftpuploader')
hdlr = logging.FileHandler('ftplog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
FTPADDR = "some ftp address"
... | [
"You have to define which type of exception you want to catch. So write except Exception, e: instead of except, e: for a general exception (that will be logged anyway).\nOther possibility is to write your whole try/except code this way:\ntry:\n with open(filepath,'rb') as f:\n con.storbinary('STOR '+ file... | [
1082,
361,
85,
58,
53,
23,
19,
18,
10,
8,
7,
4,
0
] | [] | [] | [
"except",
"exception",
"logging",
"python"
] | stackoverflow_0004690600_except_exception_logging_python.txt |
Q:
Performing calculations on DataFrames of different lengths
I have two different DataFrames that look something like this:
Lat
Lon
28.13
-87.62
28.12
-87.65
......
......
Calculated_Dist_m
34.5
101.7
..............
The first DataFrame (name=df) (consisting of the Lat and Lon columns) has just over 1000 row... | Performing calculations on DataFrames of different lengths | I have two different DataFrames that look something like this:
Lat
Lon
28.13
-87.62
28.12
-87.65
......
......
Calculated_Dist_m
34.5
101.7
..............
The first DataFrame (name=df) (consisting of the Lat and Lon columns) has just over 1000 rows (values) in it. The second DataFrame (na... | [
"If I understood correctly and assuming df1 and df2 as input, you can perform a cross merge to get all combinations of df1 and df2 rows, then apply your computation (here as new columns Lat2/Lon2):\ndf = df1.merge(df2, how='cross')\nr_earth = 6371000\ndf['Lat2'] = df['Lat'] + (df['Calculated_Dist_m'] / r_earth) * (... | [
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074209324_pandas_python.txt |
Q:
ImportError: cannot import name 'sftp_operator' from 'airflow.providers.sftp.operators
I created new connection in Connection tab and called it as sftp_test and conn type as SFTP.
I've also created new dag presented below nevertheless getting such error on the gui. Any thoughts?
Error:
Broken DAG: [/opt/airflow/da... | ImportError: cannot import name 'sftp_operator' from 'airflow.providers.sftp.operators | I created new connection in Connection tab and called it as sftp_test and conn type as SFTP.
I've also created new dag presented below nevertheless getting such error on the gui. Any thoughts?
Error:
Broken DAG: [/opt/airflow/dags/sftp_test.py] Traceback (most recent call last):
File "<frozen importlib._bootstrap>", ... | [
"Your import is incorrect:\nfrom airflow.providers.sftp.operators.sftp import SFTPOperator\n\nSee the documentation page for the provider for the correct path to the SFTPOperator.\n"
] | [
0
] | [] | [] | [
"airflow",
"python"
] | stackoverflow_0074209755_airflow_python.txt |
Q:
Python- problem converting negative numbers to floats, issues with hyphen encoding
I have a Pandas dataframe that I've read from a file - pd.read_csv() - and I'm having trouble converting a column with string values to float.
Firstly, I'm not entirely sure why pandas is even reading the column as string files to b... | Python- problem converting negative numbers to floats, issues with hyphen encoding | I have a Pandas dataframe that I've read from a file - pd.read_csv() - and I'm having trouble converting a column with string values to float.
Firstly, I'm not entirely sure why pandas is even reading the column as string files to begin with - all the values are numeric. The problem seems to be with the hyphen minus si... | [
"Try this:\ndf['Verified_m'] = df['Verified_m'].str.replace(\"\\U00002013\", \"-\").str.replace(r'^-$', '0', regex=True).astype(float)\n\nAfter converting the em-dashes to hyphens, it converts a lone - to zero.\n"
] | [
1
] | [] | [] | [
"pandas",
"python",
"unicode"
] | stackoverflow_0074210559_pandas_python_unicode.txt |
Q:
Python Logging - only show logs from my libraries
I have a relatively complex ecosystem of applications and libraries that are scheduled to run in my environment.
I am trying to improve my logging and in particular I'd like to write debug information to a logging file, and I'd like that log to contain the logger.d... | Python Logging - only show logs from my libraries | I have a relatively complex ecosystem of applications and libraries that are scheduled to run in my environment.
I am trying to improve my logging and in particular I'd like to write debug information to a logging file, and I'd like that log to contain the logger.debug("string") lines from all the imported libraries I... | [
"Python doesn't really have a concept of \"libraries I wrote\" vs \"libraries imported with pypi\" - a library is a library unfortunately.\nHowever, depending on how your libraries are set up, you may be able to get a realllly hacky custom logger?\nBy default, Python libraries installed with pip go to a central loc... | [
0
] | [] | [] | [
"logging",
"python",
"python_3.x",
"python_logging"
] | stackoverflow_0074183304_logging_python_python_3.x_python_logging.txt |
Q:
take the last one id in dataframe using python
how i select row in dataframe based on the last position for every user id. Is there any idea?
data=pd.DataFrame({'User_ID':['122','122','122','233','233','233','233','366','366','366'],'Age':[23,23,np.nan,24,24,24,24,21,21,np.nan]})
data
and the outcomes should be l... | take the last one id in dataframe using python | how i select row in dataframe based on the last position for every user id. Is there any idea?
data=pd.DataFrame({'User_ID':['122','122','122','233','233','233','233','366','366','366'],'Age':[23,23,np.nan,24,24,24,24,21,21,np.nan]})
data
and the outcomes should be like this
data_new=pd.DataFrame({'User_ID':['122','23... | [
"As you want to keep the NaN, you can groupby.tail (groupby.last would drop the NaNs):\nout = data.groupby('User_ID').tail(1)\n\nAnother option is to drop_duplicates:\nout = data.drop_duplicates(subset='User_ID', keep='last') \n\noutput:\n User_ID Age\n2 122 NaN\n6 233 24.0\n9 366 NaN\n\nIf you ... | [
0,
0
] | [] | [] | [
"data_wrangling",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074209005_data_wrangling_dataframe_pandas_python.txt |
Q:
How can I draw lines into numpy arrays?
I would like to be able to draw lines into numpy arrays to get off-line features for on-line handwriting recognition. This means I don't need the image at all, but I need for some positions in a numpy array who an image of a given size would look like.
I would like to be abl... | How can I draw lines into numpy arrays? | I would like to be able to draw lines into numpy arrays to get off-line features for on-line handwriting recognition. This means I don't need the image at all, but I need for some positions in a numpy array who an image of a given size would look like.
I would like to be able to specify an image size and then draw stro... | [
"Thanks to Joe Kington for the answer! I was looking for skimage.draw.line_aa.\nimport scipy.misc\nimport numpy as np\nfrom skimage.draw import line_aa\nimg = np.zeros((10, 10), dtype=np.uint8)\nrr, cc, val = line_aa(1, 1, 8, 4)\nimg[rr, cc] = val * 255\nscipy.misc.imsave(\"out.png\", img)\n\n",
"I stumbled on th... | [
28,
22,
7,
2,
0
] | [] | [] | [
"drawing",
"numpy",
"python"
] | stackoverflow_0031638651_drawing_numpy_python.txt |
Q:
/usr/bin/python3: Error while finding spec for 'virtualenvwrapper.hook_loader' (: No module named 'virtualenvwrapper')
I'm trying to follow How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 and I'm failing at the very earlier stage, due to amount of output, I placed all related information into... | /usr/bin/python3: Error while finding spec for 'virtualenvwrapper.hook_loader' (: No module named 'virtualenvwrapper') | I'm trying to follow How To Serve Django Applications with uWSGI and Nginx on Ubuntu 14.04 and I'm failing at the very earlier stage, due to amount of output, I placed all related information into Pastebin.com - #1 paste tool since 2002!.
the actual error:
root@alexus:~# echo "source /usr/local/bin/virtualenvwrapper.sh... | [
"I faced similar problem, when using python3 with virtualenvwrapper,\nsudo apt-get install python3-pip\n\nThen install virtualenv and virtualenvwrapper from pip3,\nsudo pip3 install virtualenv virtualenvwrapper\n\nthen source it again,\nsource $HOME/.bashrc \n\n",
"Thanks to @Alexander, I was able to fix my issue... | [
99,
93,
35,
17,
16,
10,
8,
8,
7,
6,
4,
4,
3,
1,
1,
0,
0
] | [] | [] | [
"python",
"virtualenv",
"virtualenvwrapper"
] | stackoverflow_0033216679_python_virtualenv_virtualenvwrapper.txt |
Q:
Optimal way of storing stream content on disk using Python
I'd like to stream data directly to disk.
One way of doing that is simply to read data and write to file, but I also want to minimalize RAM usage.
with open("dummy.source", "br") as out, open("dummy.copy", "bw") as in_:
in_.write(out.read()) # this ca... | Optimal way of storing stream content on disk using Python | I'd like to stream data directly to disk.
One way of doing that is simply to read data and write to file, but I also want to minimalize RAM usage.
with open("dummy.source", "br") as out, open("dummy.copy", "bw") as in_:
in_.write(out.read()) # this causes reading the whole stream into memory
I've figured out some... | [
"the optimal value of buffer size is most likely the size of the buffer already reserved by python which is 8192 bytes on most systems, but any value below that is fine as the IO will be buffered by python anyway.\nyou can change that using the buffering argument of open but 8192 is the optimal size on a lot of sys... | [
1
] | [] | [] | [
"file",
"memory",
"python",
"stream"
] | stackoverflow_0074210710_file_memory_python_stream.txt |
Q:
How to generate accurate masks for an image from Mask R-CNN prediction in PyTorch?
I have trained a Mask RCNN network for instance segmentation of apples. I am able to load the weights and generate predictions for my test images. The masks being generated seem to be in the correct location, but the mask itself ha... | How to generate accurate masks for an image from Mask R-CNN prediction in PyTorch? | I have trained a Mask RCNN network for instance segmentation of apples. I am able to load the weights and generate predictions for my test images. The masks being generated seem to be in the correct location, but the mask itself has no real form.. it just looks like a bunch of pixels
Training is done based on the data... | [
"The prediction from the Mask R-CNN has the following structure:\n\nDuring inference, the model requires only the input tensors, and returns the post-processed predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as follows:\n\nboxes (FloatTensor[N, 4]): the predicted boxes in [... | [
1,
0
] | [] | [] | [
"computer_vision",
"machine_learning",
"python",
"pytorch",
"torchvision"
] | stackoverflow_0061051335_computer_vision_machine_learning_python_pytorch_torchvision.txt |
Q:
How can I scrape "Net Worth" from YieldWatch?
I would to scrape a website as per following:
Go to Yieldwatch
Enter 0xF54274757Bf717B1ab52bA0d3a7CbF635f856a0d into the Address textbox and click the binoculars
Scrape the text under "Net worth"
I am using Selenium in Python to try and do it and here is my attempt ... | How can I scrape "Net Worth" from YieldWatch? | I would to scrape a website as per following:
Go to Yieldwatch
Enter 0xF54274757Bf717B1ab52bA0d3a7CbF635f856a0d into the Address textbox and click the binoculars
Scrape the text under "Net worth"
I am using Selenium in Python to try and do it and here is my attempt so far:
from selenium.webdriver import Safari # pi... | [
"You don't really need the heavy guns of selenium. You can get all the data from the API endpoint.\nHere's how:\nimport requests\n\nwallet = \"0xF54274757Bf717B1ab52bA0d3a7CbF635f856a0d\"\nendpoint = f\"https://www.yieldwatch.net/api/all/{wallet}?platforms=beefy,pancake,hyperjump,auto,mdex\"\n\nwallet_data = reques... | [
4,
0,
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0067313341_python_selenium_web_scraping.txt |
Q:
Non-blocking launching of concurrent coroutines in Python
I want to execute tasks asynchronously and concurrently. If task1 is running when task2 arrives, task2 is started right away, without waiting for task2 to complete. Also, I would like to avoid callbacks with the help of coroutines.
Here's a concurrent solut... | Non-blocking launching of concurrent coroutines in Python | I want to execute tasks asynchronously and concurrently. If task1 is running when task2 arrives, task2 is started right away, without waiting for task2 to complete. Also, I would like to avoid callbacks with the help of coroutines.
Here's a concurrent solution with callbacks:
def fibonacci(n):
if n <= 1:
re... | [
"loop.run_forever() will indeed run forever, even if there are no tasks inside. Good news is that you don't need this function. In order to wait for your computations to complete, use asyncio.gather:\nclass FibonacciCalculatorAsync:\n\n def __init__(self):\n self.pool = ThreadPoolExecutor(max_workers=2)\n... | [
1,
1,
1
] | [] | [] | [
"coroutine",
"python",
"python_asyncio"
] | stackoverflow_0054255352_coroutine_python_python_asyncio.txt |
Q:
Python: Undefined variable in nested function when variable exists in parent function?
Edit: I realize this isn't a nested function, instead I'm calling a function within a function!
I am pulling data from 5 different endpoints (endpoint_a through endpoint_e) and each endpoint has its own function get_endpoint_ su... | Python: Undefined variable in nested function when variable exists in parent function? | Edit: I realize this isn't a nested function, instead I'm calling a function within a function!
I am pulling data from 5 different endpoints (endpoint_a through endpoint_e) and each endpoint has its own function get_endpoint_ such as below:
def get_endpoint_a() -> pd.dataFrame:
"""
Return data from API endpoint... | [
"As pointed out in a comment, this isnt a nested function. However, to fix your problem you just need to add querystring as an argument to your function and pass it in each time:\ndef _get_all_data(response, querystring):\n\"\"\"\nReturn the results of the get request.\n\nLoops over api response and appends results... | [
1
] | [] | [] | [
"api",
"function",
"python"
] | stackoverflow_0074210755_api_function_python.txt |
Q:
Upgrading Python version to 3.9 on macOS now gives “variable not defined” error for some file-reading code
I just upgraded from Python 3.7 to 3.9.14 and it now gives a variable not defined error. The same code works fine locally and remotely where Python 3.9.2 is installed but now locally it gives an error in Pyth... | Upgrading Python version to 3.9 on macOS now gives “variable not defined” error for some file-reading code | I just upgraded from Python 3.7 to 3.9.14 and it now gives a variable not defined error. The same code works fine locally and remotely where Python 3.9.2 is installed but now locally it gives an error in Python 3.9.14 version. Below is the code:
def check(url):
result = None
product = Product(url, user_agents)
... | [
"You must be on OS-X. On that OS, Python changed across this versions the default method to spawn sub-processes - that also explains why it \"works on Python 3.9 remotely\": the remote deploy must be on a Linux or other Unix than MacOS -\nBear with me:\nthe default child-process creation method used to be \"fork\" ... | [
7
] | [] | [] | [
"python",
"python_3.9",
"python_3.x"
] | stackoverflow_0074210613_python_python_3.9_python_3.x.txt |
Q:
Do not decode utf8 in pymongo
from pymongo import MongoClient
mongo = MongoClient('mongodb://admin:pass@127.0.0.1:27017/web_cache?authSource=admin')['web_cache']['pages']
for x in mongo.find({"status" : 1},{ "_id": 0, "url": 1, "effective_url": 1, "content" : 1, "Content-Type" : 1 }):
print(x['content'])
b... | Do not decode utf8 in pymongo | from pymongo import MongoClient
mongo = MongoClient('mongodb://admin:pass@127.0.0.1:27017/web_cache?authSource=admin')['web_cache']['pages']
for x in mongo.find({"status" : 1},{ "_id": 0, "url": 1, "effective_url": 1, "content" : 1, "Content-Type" : 1 }):
print(x['content'])
break
get error:
bson.errors.Invali... | [
"You could try to implement MongoClient as below:\nmongo = MongoClient('mongodb://admin:pass@127.0.0.1:27017/web_cache?authSource=admin', unicode_decode_error_handler='ignore') ....\n\nAdding that unicode_decode_error_handler='ignore' statement in MongoClient.\nIf the error continue, you must upload pymongo version... | [
0
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0069872506_mongodb_pymongo_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.