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:
Algorithm to find all duplicate sequences of tokens in a long string
Let's say I have a really long string consists of 10^6 tokens (for simplicity, token is a space-separated word, so this string is splitted to list of tokens)
now I need to find all possible duplicated sequences and the start of the duplication lo... | Algorithm to find all duplicate sequences of tokens in a long string | Let's say I have a really long string consists of 10^6 tokens (for simplicity, token is a space-separated word, so this string is splitted to list of tokens)
now I need to find all possible duplicated sequences and the start of the duplication locations in the string.
For example:
(The brackets are not really in the st... | [
"You wish to identify repeated bi-grams.\nOptionally construct a dictionary for converting str to int, if desired.\nIterate over the document,\ngenerating a bi-gram for current position,\nthen advance to next position.\nStore these in a bigram_to_index_list dict in memory,\nor perhaps in an out-of-core file or data... | [
0,
0
] | [] | [] | [
"algorithm",
"python",
"suffix_tree",
"trie"
] | stackoverflow_0074198696_algorithm_python_suffix_tree_trie.txt |
Q:
Dataframe: index values difference calculation
For a Python dataframe (based on some criteria) I am able to select the index value (a date) (='first date') as well as the index value (a date) corresponding to the very last row ('last date').
I would like to calculate explicitly the difference (in days) between 'f... | Dataframe: index values difference calculation | For a Python dataframe (based on some criteria) I am able to select the index value (a date) (='first date') as well as the index value (a date) corresponding to the very last row ('last date').
I would like to calculate explicitly the difference (in days) between 'first date' and 'last date' (should be = 3 (number o... | [
"You forgot to set the type of the 'date' column. Currently, it is a string but you want it to be a datetime instance instead.\ndf1 = pd.DataFrame({\"date\": ['2021-3-22', '2021-3-23', '2021-3-24', '2021-3-25', '2021-3-26'],\n\"x\": ['nan', 1, 'nan', 'nan', 'nan' ]})\n\ndf1['date'] = pd.to_datetime(df1['date'])\n\n... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074278207_dataframe_pandas_python.txt |
Q:
Python raises a NameError when using a type hint in arguments of class method
Take a look at this code:
class Test:
def __eq__(self, rhs: Test):
# ...
pass
The code fails with the following output:
Traceback (most recent call last):
File "test.py", line 1, in <module>
class Test:
File ... | Python raises a NameError when using a type hint in arguments of class method | Take a look at this code:
class Test:
def __eq__(self, rhs: Test):
# ...
pass
The code fails with the following output:
Traceback (most recent call last):
File "test.py", line 1, in <module>
class Test:
File "test.py", line 2, in Test
def __eq__(self, rhs: Test):
NameError: name 'Test' ... | [
"Because Test is not defined yet, you will need to do a forward declaration like this:\nclass Test:\n def __eq__(self, rhs: \"Test\"):\n # ...\n pass\n\n"
] | [
0
] | [] | [] | [
"python",
"type_hinting"
] | stackoverflow_0074278320_python_type_hinting.txt |
Q:
How to show plotly graphic on PyQt5 Application
I try to show the plotly graph in one of application's window.
But this graph does not scale when the window changes.
How can I fix it?
Here is begin of class Main Window
class MainWindow(QWidget, From_Main):
def __init__(self):
super(MainWindow, self)._... | How to show plotly graphic on PyQt5 Application | I try to show the plotly graph in one of application's window.
But this graph does not scale when the window changes.
How can I fix it?
Here is begin of class Main Window
class MainWindow(QWidget, From_Main):
def __init__(self):
super(MainWindow, self).__init__()
QWidget.__init__(self)
sel... | [
"You already have a layout, you cannot set a new one; instead, you need to add the view to it.\nGo to Designer, select the parent widget in which you want to add the browser, if it already has an existing layout to which you can add the view, then scroll down to the end of the property editor and get its layoutName... | [
1
] | [] | [] | [
"plotly",
"pyqt5",
"python"
] | stackoverflow_0074278200_plotly_pyqt5_python.txt |
Q:
Why do I get a ChunkedEncodingError in Python when using requests module?
I try to query this API https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi
with these params ?db=mesh&id=68016019
So the whole URL is https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=mesh&id=68016019
When executing this in... | Why do I get a ChunkedEncodingError in Python when using requests module? | I try to query this API https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi
with these params ?db=mesh&id=68016019
So the whole URL is https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=mesh&id=68016019
When executing this in Postman everything's fine and the output is as expected:
1: Survival Analysis
... | [
"If you are occasionally getting a ChunkedEncodingError, you can implement some retry logic in that case:\nSomething like this would retry a given URL 3 times (with a 1 second pause between each retry):\nimport requests\nimport time\n\narticle_id=68016019\n\nfor attempt in range(3):\n try:\n res = request... | [
1
] | [] | [] | [
"pubmed",
"python",
"python_requests"
] | stackoverflow_0074275924_pubmed_python_python_requests.txt |
Q:
How to call python user-defined function in main( )?
I create some functions and how to call them in main( )? It throws NameError: name 'list_A' is not defined
def main():
output_item_statistics(list_A, list_B, fh_out)
def output_item_statistics(list_A, list_B, fh_out):
number = 0
for a, b in zi... | How to call python user-defined function in main( )? | I create some functions and how to call them in main( )? It throws NameError: name 'list_A' is not defined
def main():
output_item_statistics(list_A, list_B, fh_out)
def output_item_statistics(list_A, list_B, fh_out):
number = 0
for a, b in zip(list_A, list_B):
number = number + 1
... | [
"It feels like your files are not in the same directory. Here's a sample:\nMain Folder\n β Python File `main()`\n β Folder\n β Second File `output_item_statistics)`\n\nIf there's such a case in your system then try importing the folder:\nimport folder_name.file_name as file_name\n\nThen you need to cal... | [
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074278362_function_python.txt |
Q:
Cannot create graphics instruction outside the main Kivy thread
I'm trying to create a small GUI with kivy. by clicking on the button named button it should launch the popup on another thread with a progress bar that evolves after 3 seconds. But kivy gives me an error saying "Cannot create graphics instruction out... | Cannot create graphics instruction outside the main Kivy thread | I'm trying to create a small GUI with kivy. by clicking on the button named button it should launch the popup on another thread with a progress bar that evolves after 3 seconds. But kivy gives me an error saying "Cannot create graphics instruction outside the main Kivy thread"
how to solve this problem?
from kivy.app ... | [
"Im a bit late but i just solve the same problem by changing the 2.1.0 kivy version to the 2.0.0 version.\n",
"I cannot replicate your error, but the general rule is don't do GUI operations on threads other than the main thread. Here is a modified version of your Thebutton class that does that:\nclass Thebutton(B... | [
1,
0
] | [] | [] | [
"kivy",
"python"
] | stackoverflow_0071885469_kivy_python.txt |
Q:
Problem getting data from callback(data):
I am still struggling with using data from the callback function, I wrote a class and trying to get the data from the callback function associated with the class, any help would be much appreciated. Do I need to use multi threading or there is an easy way to use it ? When ... | Problem getting data from callback(data): | I am still struggling with using data from the callback function, I wrote a class and trying to get the data from the callback function associated with the class, any help would be much appreciated. Do I need to use multi threading or there is an easy way to use it ? When I am calling the class the publisher initialize... | [
"I resolved this issue,\n\nCreate another function out of the class say name use_data(args)\nCall use_data in main function and you are good to go.\n\nOne of the common problem is use of spin command,they block the main thread from exiting until ROS invokes a shutdown - via a Ctrl + C.\ndef use_data(args):\n\n i... | [
0
] | [] | [] | [
"callback",
"python",
"ros"
] | stackoverflow_0074270404_callback_python_ros.txt |
Q:
Drawing staircases in a loop but not getting correct results
I am trying to draw 7 staircases with a loop but I have missed something and not sure why it's not working. It draws the first staircase and then goes completely off track and doesn't put the pen back down and I'm not sure why.
#Draw stairs 7 times
from ... | Drawing staircases in a loop but not getting correct results | I am trying to draw 7 staircases with a loop but I have missed something and not sure why it's not working. It draws the first staircase and then goes completely off track and doesn't put the pen back down and I'm not sure why.
#Draw stairs 7 times
from turtle import*
#Stair repeat
for i in range (3):
forward (25)... | [
"A couple things seem amiss:\n\nThe body of the for i in range(7): loop doesn't make sense. It never does any movement when the pen is down, so the turtle draws nothing.\nThe for i in range (3): loop doesn't make sense either if you want to draw 7 stairs. What do you need to do 3 times here?\n\nBeyond that, avoid f... | [
0
] | [] | [] | [
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074276779_python_python_turtle_turtle_graphics.txt |
Q:
Problem obtaining residual data in a nuclei segmentation program
I'm trying to get a mask over image cores like this so I can count them later.
For this, I am performing different steps in Colab:
Color processing
Segmentation using K-means
Find contours to detect those cells
Here is the code:
import sys
import... | Problem obtaining residual data in a nuclei segmentation program | I'm trying to get a mask over image cores like this so I can count them later.
For this, I am performing different steps in Colab:
Color processing
Segmentation using K-means
Find contours to detect those cells
Here is the code:
import sys
import os
import cv2
import copy
import numpy as np
#Load images (600x600x3... | [
"Shape of nuclie is circular while shape of other features is irregular. Thus other features will have more variation in second direction. PCA or eigen values can be used to measure priciple directions of variations. If the magnitude of variation is more in one direction, then it is not nuclei.\nimport numpy.linalg... | [
0
] | [] | [] | [
"image_segmentation",
"k_means",
"python"
] | stackoverflow_0074266115_image_segmentation_k_means_python.txt |
Q:
Pandas: parse .csv string type number with dot as thousand separator to int instead of float
It's a .csv with items and prices. The latter already come rounded (without decimal) but if the price is more than 999, then I have to deal with the thousand separator.
item, price
foo, 12
bar,678
baz, 1.200
`df.dtype` re... | Pandas: parse .csv string type number with dot as thousand separator to int instead of float | It's a .csv with items and prices. The latter already come rounded (without decimal) but if the price is more than 999, then I have to deal with the thousand separator.
item, price
foo, 12
bar,678
baz, 1.200
`df.dtype` returns:
item object
price float64
If I try to convert to int it truncates the numbe... | [
"As mentioned by @BigBen there's a pd.read_csv parameter called thousands used to indicate the thousand separator. There's also a decimal parameter which may be useful too.\n"
] | [
1
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074277279_csv_pandas_python.txt |
Q:
how can we add blank spaces between a number of integer which is then converted from a string?
I am trying to make a program which takes in value from an api an I have coded it to reduce it to 1 single value. But then it is returning me 5 different values. But after even accepting that too, I am facing a problem i... | how can we add blank spaces between a number of integer which is then converted from a string? | I am trying to make a program which takes in value from an api an I have coded it to reduce it to 1 single value. But then it is returning me 5 different values. But after even accepting that too, I am facing a problem in which I am not able to convert the data extracted from the API in integer form.
So this is my code... | [
"Since the digit number of each numerical value is different (it has two or three digits), it is best to keep the values in a string having space between them, and whenever you want to have it as integer, then remove the space and change it to integer.\nstring_tds = string_tds.replace(\"ppm\", \" \")\nstring_tds = ... | [
0
] | [] | [] | [
"api",
"integer",
"python"
] | stackoverflow_0074278152_api_integer_python.txt |
Q:
How to extract data from list with RegExp OR in Python3?
I have the following list
['Amount', 'amount', 'Line Total', 'lineTotal', 'AMOUNT DUE']
and I'm trying to extract 'Amount', 'amount', 'Line Total', 'lineTotal' but not 'AMOUNT DUE' field from that list.
Here is how I do that:
>>> lst = ['Amount', 'amount', ... | How to extract data from list with RegExp OR in Python3? | I have the following list
['Amount', 'amount', 'Line Total', 'lineTotal', 'AMOUNT DUE']
and I'm trying to extract 'Amount', 'amount', 'Line Total', 'lineTotal' but not 'AMOUNT DUE' field from that list.
Here is how I do that:
>>> lst = ['Amount', 'amount', 'Line Total', 'lineTotal', 'AMOUNT DUE']
>>> import re
>>> r =... | [
"Try (regex101):\nimport re\n\nlst = [\"Amount\", \"amount\", \"Line Total\", \"lineTotal\", \"AMOUNT DUE\"]\nr = re.compile(r\"(?=line|amount$).*\", flags=re.IGNORECASE)\n\nlst = list(filter(r.match, lst))\nprint(lst)\n\nPrints:\n['Amount', 'amount', 'Line Total', 'lineTotal']\n\n"
] | [
0
] | [] | [] | [
"list",
"python",
"regex"
] | stackoverflow_0074277875_list_python_regex.txt |
Q:
xpath selenium locating next sibling - any element
The URL is enter link description here
Is there any way in selenium XPath to get value the element just the element which following sibling of located element
//span[contains(text(),"by")]//following-sibling::a
in this code I want to take the next element because ... | xpath selenium locating next sibling - any element | The URL is enter link description here
Is there any way in selenium XPath to get value the element just the element which following sibling of located element
//span[contains(text(),"by")]//following-sibling::a
in this code I want to take the next element because sometimes it is not an anchor tag but span
For getting v... | [
"The following XPath will give exactly what you need:\n\"//span[text()='by ']/following-sibling::*[1]\"\n\nThere are several points to be improved in your initial XPath:\n\n//span[contains(text(),\"by\")] matches more than 16 relevant elements.\n/following-sibling::* selects All the following siblings, of any tag n... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"xpath"
] | stackoverflow_0074275057_python_selenium_selenium_webdriver_xpath.txt |
Q:
Class Method Unreachable
In the code is a class Company wherein is an employe_base, *which contains employee objects . With the function print_self_employees, I try to modify a list employees and print it.
class Company():
def __init__(self, name, minimum_hiring_grades, required_work_experience_years,employee_... | Class Method Unreachable | In the code is a class Company wherein is an employe_base, *which contains employee objects . With the function print_self_employees, I try to modify a list employees and print it.
class Company():
def __init__(self, name, minimum_hiring_grades, required_work_experience_years,employee_leaves, employee_bonus_percent... | [
"You need to be calling the print function rather than referencing it. Try:\nE.print_self_employees()\n\n"
] | [
1
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074278382_class_python.txt |
Q:
Create new a DataFrame from itself with its transpose
I am trying to create a new DataFrame with its transpose:
It's look like a matrix multiplication of its transpose, M x M^T
Groups
Area g1 g2 g3 g4
a1 1 0 0 0
a2 0 0 0 1
a3 0 0 0 0
a4 0 0 1 0
a5 ... | Create new a DataFrame from itself with its transpose | I am trying to create a new DataFrame with its transpose:
It's look like a matrix multiplication of its transpose, M x M^T
Groups
Area g1 g2 g3 g4
a1 1 0 0 0
a2 0 0 0 1
a3 0 0 0 0
a4 0 0 1 0
a5 1 0 0 0
a6 0 0 1 0
its transpose
... | [
"I got it.\nimport numpy as np\n\narr1 =np.array([[1, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 0 , 0],\n [0, 0 , 1, 0],\n [1, 0, 0, 0],\n [0, 0, 1, 0]\n ])\n\narr2 =arr1.T\nnp.dot(arr1, arr2)\n\noutput:\narray([[1, 0, 0, 0, 1, 0],\n [0, 1, 0, 0, 0, 0],\n ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074271775_pandas_python.txt |
Q:
Python doesn't want to run function asynchronous
I just want to run async function like really async, but it blocks main thread for 5 seconds
import asyncio
async def sideTask():
await asyncio.sleep(5) # this will pause main thread for no reason
print("doing side job")
global test
test = 0
# main work... | Python doesn't want to run function asynchronous | I just want to run async function like really async, but it blocks main thread for 5 seconds
import asyncio
async def sideTask():
await asyncio.sleep(5) # this will pause main thread for no reason
print("doing side job")
global test
test = 0
# main work
while True:
test += 1
time.sleep(1)
if t... | [
"What are you trying to achieve by running sideTask() in the loop?\nIf you're trying to see output of \"doing side job\" while asyncio.sleep(5) is executing, you should simply put \"doing side job\" before asyncio.sleep(5)\nasyncio.sleep() is not pausing the main thread, you are just doing sleep function which serv... | [
0
] | [] | [] | [
"asynchronous",
"python"
] | stackoverflow_0074277664_asynchronous_python.txt |
Q:
How to filter isnull False value in Django-filters?
I want to only filter category which has channels__livestream__isnull=False. The Queryset is working fine with this paremter but the Django-filters getting error TypeError: 'FilterSetMetaclass' object is not iterable.
filters.py
class CategoryFilterSet(django_fil... | How to filter isnull False value in Django-filters? | I want to only filter category which has channels__livestream__isnull=False. The Queryset is working fine with this paremter but the Django-filters getting error TypeError: 'FilterSetMetaclass' object is not iterable.
filters.py
class CategoryFilterSet(django_filters.FilterSet):
has_live_stream = django_filters.Bo... | [
"According to the docs for django-rest-framework (https://www.django-rest-framework.org/api-guide/filtering/#overriding-the-initial-queryset) it looks like you should be setting filterset_class instead of filterset_fields in your views.py:\nclass CategoryList(generics.ListAPIView):\n authentication_classes = []\... | [
0
] | [] | [] | [
"django",
"django_filter",
"django_rest_framework",
"python"
] | stackoverflow_0074277718_django_django_filter_django_rest_framework_python.txt |
Q:
Filter dataframe by multiple criteria in Python (pandas)
I am having a problem filtering my dataframe by multiple criteria. I have no problem filtering by one criteria (string).
I have an excel sheet with around 15 columns. First, I filtered my dataframe by specific column, let's say by column2, column4, column5, ... | Filter dataframe by multiple criteria in Python (pandas) | I am having a problem filtering my dataframe by multiple criteria. I have no problem filtering by one criteria (string).
I have an excel sheet with around 15 columns. First, I filtered my dataframe by specific column, let's say by column2, column4, column5, and column11, by using the following code:
df_name_filtered_co... | [
"You have to use the and and or conditions wisely. Here you can use something like the following\ndf_srm_final = df_name_filtered_columns[(((df_name_filtered_columns[\"column2\"] == \"city1\") |\n (df_name_filtered_columns[\"column2\"] == \"city4\") ) \n ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074278311_pandas_python.txt |
Q:
How to get multiple return values from a threaded function
Have called an external function which returns multiple values.
def get_name(full_name):
# you code
return first_name, last_name
In simple function call, I can get the results.
from names import get_name
first, last= get_name(full_name)
But I need... | How to get multiple return values from a threaded function | Have called an external function which returns multiple values.
def get_name(full_name):
# you code
return first_name, last_name
In simple function call, I can get the results.
from names import get_name
first, last= get_name(full_name)
But I need to use threading for the call to get the result values for the ... | [
"You should use a queue for retrieve data from threads, here you have an example using a wrapper to store values from the functions into a queue:\nimport threading\nimport queue\n\nmy_queue = queue.Queue()\n\ndef storeInQueue(f):\n def wrapper(*args):\n my_queue.put(f(*args))\n return wrapper\n\n\n@storeInQueu... | [
10,
0
] | [] | [] | [
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0050290226_multiprocessing_multithreading_python.txt |
Q:
How to concatenate multiple csv file with one common column
I have multiple csv files with different columns and one common EMP_ID column. I want to merge all the files and get one file with all the columns and header from different files. I tried the following code and I get the EMP_ID column multiple times.
file... | How to concatenate multiple csv file with one common column | I have multiple csv files with different columns and one common EMP_ID column. I want to merge all the files and get one file with all the columns and header from different files. I tried the following code and I get the EMP_ID column multiple times.
file 1 :
EMP_ID
EMP_name
EMP_Service
33
a
6
44
b
3
12
c
1... | [
"Set your index as the column you want to join on~\ndfs = [df1, df2, df3]\n\ndfs = [x.set_index('EMP_ID') for x in dfs]\n\ndf = pd.concat(dfs, axis=1).reset_index()\n\nprint(df)\n\nOutput:\n EMP_ID EMP_name EMP_Service EMP_age EMP_dept\n0 33 a 6 30 xyz\n1 44 b ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074278352_pandas_python.txt |
Q:
python selenium find element is slow
<body>
<tbody id="data-table">
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
... | python selenium find element is slow | <body>
<tbody id="data-table">
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
... | [
"If you're just looking for the text in each td tag you could do:\nmain_table = driver.find_element(By.XPATH, '//*[@id=\"data-table\"]/tr/td')\nfor xin main_table:\n print(x.text)\n\n",
"Identify the table element and get the outerHtml of the table element first, Then use pandas to read the html\nmain_table = d... | [
0,
0
] | [] | [] | [
"driver",
"google_chrome",
"performance",
"python",
"selenium"
] | stackoverflow_0074278423_driver_google_chrome_performance_python_selenium.txt |
Q:
Pynput: Count keypresses
I want to write a program which counts, how often a key is pressed on my keyboard (e.g. per day). I can use Pynput to recognize a certain keypress, but I'm struggling with the counting part. Here's what I got so far:
from pynput.keyboard import Key, Listener
i = 0
def on_press(key, pressed... | Pynput: Count keypresses | I want to write a program which counts, how often a key is pressed on my keyboard (e.g. per day). I can use Pynput to recognize a certain keypress, but I'm struggling with the counting part. Here's what I got so far:
from pynput.keyboard import Key, Listener
i = 0
def on_press(key, pressed):
print('{0} pressed'.for... | [
"I'm trying to figure this exact problem out myself. To answer what the error wants, it wants you to define the parameter \"pressed\" in your arguments passed to on_press.\nex.\n def on_press(key, pressed=0):\n print('{0} pressed'.format(\n key))\n if pressed({0}):\n i = i + 1... | [
1,
0
] | [] | [] | [
"pynput",
"python"
] | stackoverflow_0063670700_pynput_python.txt |
Q:
Python pandas get previous values row
I created this dataframe with python pandas:
import numpy as np
import pandas as pd
my_df = pd.DataFrame(
{'ColumnA':['Value A', '', 'Value B', '', '', 'Value C',''],
'ColumnB':['', '', '', '', '', '', '']})
The dataframe is presented below:
ColumnA | ColumnB
0 ... | Python pandas get previous values row | I created this dataframe with python pandas:
import numpy as np
import pandas as pd
my_df = pd.DataFrame(
{'ColumnA':['Value A', '', 'Value B', '', '', 'Value C',''],
'ColumnB':['', '', '', '', '', '', '']})
The dataframe is presented below:
ColumnA | ColumnB
0 Value A |
1 |
2 Value B |
... | [
"Using real NaN values instead of empty strings makes many things easier...\nimport pandas as pd\nimport numpy as np\n\ndata = {'ColumnA':['Value A', '', 'Value B', '', '', 'Value C',''],\n 'ColumnB':['', '', '', '', '', '', '']}\ndf = pd.DataFrame(data)\n\n# Fix your null values:\ndf = df.replace('', np.nan... | [
1
] | [] | [] | [
"multiple_conditions",
"pandas",
"python"
] | stackoverflow_0074278518_multiple_conditions_pandas_python.txt |
Q:
Scrape data from a paginated website which was blocking the request when i use beautifulsoup, selenium
I want to scrape data from this site "https://www.findhelp.org/care/support-network--san-francisco-ca?postal=94105" . I Tried using selenium, beautifulsoup but cant able to scrape the data because the site was bl... | Scrape data from a paginated website which was blocking the request when i use beautifulsoup, selenium | I want to scrape data from this site "https://www.findhelp.org/care/support-network--san-francisco-ca?postal=94105" . I Tried using selenium, beautifulsoup but cant able to scrape the data because the site was blocking scrapers. I want to find a way to scrape the data in this site.
Any solution for this problem will be... | [
"I was able to get into the site by passing this user agent in the header.\nMozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246\n\n"
] | [
0
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074278576_python_web_scraping.txt |
Q:
How can I solve OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'rectangle'?
I study on a instance segmentation model. I complede training part. BUt in the inference part; i faced with an error as I showed below. I converted boxes[i][0] to the int(boxes[i][0]) but it gives also error. Are there any idea to... | How can I solve OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'rectangle'? | I study on a instance segmentation model. I complede training part. BUt in the inference part; i faced with an error as I showed below. I converted boxes[i][0] to the int(boxes[i][0]) but it gives also error. Are there any idea to help?
def get_prediction(img_path, confidence):
img = Image.open(img_path)
t... | [
"cv::rectangle has two overloads, where the first takes two cv::Points and the second takes a cv::Rect.\nBoth are tuples in Python, where the elements are integers.\nCreating a tuple for pt argument like the following may work.\npt1 = tuple([int(j) for j in boxes[i][0]])\npt2 = tuple([int(j) for j in boxes[i][1]])\... | [
0
] | [] | [] | [
"mask_rcnn",
"opencv",
"python"
] | stackoverflow_0074277921_mask_rcnn_opencv_python.txt |
Q:
I need to do two columns web scraption with python
<div class="content">
<div class="container">
<div class="row pt-2">
<div class="col pe-1">
<div class="grid-cell p-2">
<a href="united-states_florida/company/met-west-commercial-lender/tom-mchugh-975">
Tom Mchugh
</a>
</div>
</div>
<div ... | I need to do two columns web scraption with python | <div class="content">
<div class="container">
<div class="row pt-2">
<div class="col pe-1">
<div class="grid-cell p-2">
<a href="united-states_florida/company/met-west-commercial-lender/tom-mchugh-975">
Tom Mchugh
</a>
</div>
</div>
<div class="col ps-1">
<div class="grid-cell p-2">
... | [
"There might be different approaches. Here is an elegant one.\ny = df.Name.values\ndf = pd.DataFrame({'A' : y[::2], 'B' : y[1::2]})\n\n"
] | [
1
] | [] | [] | [
"html",
"jupyter_lab",
"jupyter_notebook",
"python",
"web_scraping"
] | stackoverflow_0074278564_html_jupyter_lab_jupyter_notebook_python_web_scraping.txt |
Q:
My pycharm version does not support "match" statements
I am using PyCharm for making an app and I used the statement "match" . It shows the current version does not support match statements, I tried updating.
I updated python but PyCharm shows that it is on the latest version.
I updated Python to 3.11.0 (before it... | My pycharm version does not support "match" statements | I am using PyCharm for making an app and I used the statement "match" . It shows the current version does not support match statements, I tried updating.
I updated python but PyCharm shows that it is on the latest version.
I updated Python to 3.11.0 (before it was 3.9)
| [
"I guess you didn't configure the new python interpreter in PyCharm. In this case you should try to change the interpreter to the new version of python you installed i.e. Python 3.11.0. You can change it in the status bar of PyCharm.\nRefer Change the Python interpreter using the Python Interpreter selectorο»Ώ for mo... | [
2
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0074277906_pycharm_python.txt |
Q:
How to increment filename from inside for loop in python?
I have eighteen folders in a directory, each of them has four images from a specific region of four larger images that have been cropped into eighteen smaller pieces. I want to remake the four original images and for that I made a code that goes through all... | How to increment filename from inside for loop in python? | I have eighteen folders in a directory, each of them has four images from a specific region of four larger images that have been cropped into eighteen smaller pieces. I want to remake the four original images and for that I made a code that goes through all the folders in the directory taking the first image from each ... | [
"Try this. Added extra variable j that controls the count. Follow comments to change as per you need.\nfrom PIL import Image\nfrom natsort import natsorted\nimport os\n\nimage_path = \"heat_map/\"\nw1 = 2560\nh1 = 2048\ndir_list = natsorted(os.listdir(image_path))\nfor im in range(4):\n output_image = Image.new(... | [
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0074278653_python_python_imaging_library.txt |
Q:
Python Executable not Running in Terminal
I created a python script in VS Code that runs perfectly fine.
I am trying to turn it into an executable for ease of access and use.
I have a macbook air m1 and everything should be up to date.
I installed pyinstaller with pip install pyinstaller.
When I run pyinstall #fil... | Python Executable not Running in Terminal | I created a python script in VS Code that runs perfectly fine.
I am trying to turn it into an executable for ease of access and use.
I have a macbook air m1 and everything should be up to date.
I installed pyinstaller with pip install pyinstaller.
When I run pyinstall #filename I get everything to run fine including th... | [
"This is 5 step the process that i use (which works for windows):\nCan you verify that steps 1 & 2 are done correctly ? And also that you have done the ios version of the windows commands.,,\n\nAdd Python to Windows Path:\nAn easy way to add Python to the path is by downloading a recent version of Python, and then ... | [
0
] | [
"for my personal reference I use Anaconda + Jupyter notebook for developing. Then I usually save the jupyter notebook where the code resides as a python script as .py. After that I can use this executable python script into anything as I need. run is from task scheduler, I can run it manually, from the shell, or an... | [
-1
] | [
"pyinstaller",
"python",
"python_3.x"
] | stackoverflow_0074277756_pyinstaller_python_python_3.x.txt |
Q:
Django Manager Chaining
I was wondering if it was possible (and, if so, how) to chain together multiple managers to produce a query set that is affected by both of the individual managers. I'll explain the specific example that I'm working on:
I have multiple abstract model classes that I use to provide small, sp... | Django Manager Chaining | I was wondering if it was possible (and, if so, how) to chain together multiple managers to produce a query set that is affected by both of the individual managers. I'll explain the specific example that I'm working on:
I have multiple abstract model classes that I use to provide small, specific functionality to other... | [
"See this snippet on Djangosnippets: http://djangosnippets.org/snippets/734/\nInstead of putting your custom methods in a manager, you subclass the queryset itself. It's very easy and works perfectly. The only issue I've had is with model inheritance, you always have to define the manager in model subclasses (just:... | [
22,
10,
2,
2,
0
] | [] | [] | [
"django",
"django_managers",
"django_models",
"python"
] | stackoverflow_0000809210_django_django_managers_django_models_python.txt |
Q:
Automatically generating Python type annotations?
I'm retrofitting some old Python code to add PyType annotations. I'm doing this mechanically, by adding print statements to the top of each function
def f(a, b):
print("type a:", type(a))
print("type b:", type(b))
and updating accordingly.
Is there anythi... | Automatically generating Python type annotations? | I'm retrofitting some old Python code to add PyType annotations. I'm doing this mechanically, by adding print statements to the top of each function
def f(a, b):
print("type a:", type(a))
print("type b:", type(b))
and updating accordingly.
Is there anything which can help automate this process?
| [
"Sure, there are some projects out there that can help out.\n\nInstagram developed the MonkeyType tool to pick up runtime type information. These are output as stubs files, but you can use the tools included to apply those to your source files as inline annotations, or use the retype project to do the same.\nDropb... | [
36,
0
] | [] | [] | [
"python",
"type_hinting",
"types"
] | stackoverflow_0050416444_python_type_hinting_types.txt |
Q:
return NotImplemented but when printed, I get False
Here is a minimal reproducible example:
class Attribut:
def __init__(
self,
name: str,
other_name: str,
):
self.name: str = name
self.other_name: str = other_name
def __eq__(self, other):
if isi... | return NotImplemented but when printed, I get False | Here is a minimal reproducible example:
class Attribut:
def __init__(
self,
name: str,
other_name: str,
):
self.name: str = name
self.other_name: str = other_name
def __eq__(self, other):
if isinstance(other, Attribut):
return self.name ==... | [
"Overriding hash method allows you to use other methods that would involve sorting a list of your Attribut objects.\nTo test it create a script in which you would create such a list\na = [Attribut(\"lol\", \"a\"), Attribut(\"lol\", \"a\"), Attribut(\"lol\", \"a\")]\n\nand then try to make a set out of it\nset(a)\... | [
2,
2
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074278681_class_python.txt |
Q:
Poetry Upgrade Project from Python 3.10.x to Python 3.11.0
I have a poetry based Django project using Python 3.10.2. I would like to upgrade the project to use Python 3.11.0.
What is the proper way to do that?
Should I nuke poetry.lock then update the pyproject.toml to
[tool.poetry.dependencies]
python = "^3.11"
... | Poetry Upgrade Project from Python 3.10.x to Python 3.11.0 | I have a poetry based Django project using Python 3.10.2. I would like to upgrade the project to use Python 3.11.0.
What is the proper way to do that?
Should I nuke poetry.lock then update the pyproject.toml to
[tool.poetry.dependencies]
python = "^3.11"
The ability to easily upgrade to newer versions of Python seems ... | [
"try:\npoetry env use python3.11.0\nor the full path to that python version\n"
] | [
0
] | [] | [] | [
"python",
"python_poetry",
"upgrade"
] | stackoverflow_0074278322_python_python_poetry_upgrade.txt |
Q:
Passing a Python list in a Redshift SQL query
I am trying to pass a python list into a Redshift SQL query:
test = ['0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d',
'0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb',
'0x60e4d786628fea6478f785a6d7e704777c86a7c6']
l = tuple(test)
params = {'l': l}
The query is ... | Passing a Python list in a Redshift SQL query | I am trying to pass a python list into a Redshift SQL query:
test = ['0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d',
'0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb',
'0x60e4d786628fea6478f785a6d7e704777c86a7c6']
l = tuple(test)
params = {'l': l}
The query is as follows:
conn = aws_utils.Redshift.get_redshift_... | [
"I think you need to specify params keyword in read_sql, because params is not 3rd argument in doc https://pandas.pydata.org/pandas-docs/version/1.4/reference/api/pandas.read_sql.html.\ntest_df = pd.read_sql(query, conn, params=params)\n\n"
] | [
0
] | [] | [] | [
"amazon_redshift",
"python",
"sql"
] | stackoverflow_0074055903_amazon_redshift_python_sql.txt |
Q:
How to limit quantity of lines in a notebook [Odoo 15]
I want to limit the quantity of "Order lines" to 2 products only (When 2 products are loaded, I want the "Add a Product", "Add a section" and "Add a note" buttons to disappear automatically).
I tried to use an @api.constrains but it only validates when I click... | How to limit quantity of lines in a notebook [Odoo 15] | I want to limit the quantity of "Order lines" to 2 products only (When 2 products are loaded, I want the "Add a Product", "Add a section" and "Add a note" buttons to disappear automatically).
I tried to use an @api.constrains but it only validates when I click Save button.
| [
"Solved\n@api.onchange('reservation_line')\ndef _onchange_check_cabanias(self):\n if len(self.reservation_line) > 1:\n raise ValidationError(\"Only one habitation per reserve is allowed\")\n\n",
"try to add readonly = True in relation field to make it cant editable\n"
] | [
1,
0
] | [] | [] | [
"odoo",
"odoo_15",
"python"
] | stackoverflow_0074265465_odoo_odoo_15_python.txt |
Q:
how to get a value that has exactly the name of the class web scraping
I have this web page:
https://tr.uspoloassn.com/erkek-beyaz-polo-yaka-t-shirt-basic-50249146-vr013/
that contains this html:
this code has the sizes in it. you can see that some class has: js-variant and some has js-variant disabled
what i wan... | how to get a value that has exactly the name of the class web scraping | I have this web page:
https://tr.uspoloassn.com/erkek-beyaz-polo-yaka-t-shirt-basic-50249146-vr013/
that contains this html:
this code has the sizes in it. you can see that some class has: js-variant and some has js-variant disabled
what i want is to select the text where the class is js-variant using web scraping.
I ... | [
"There is a space in class like this js-variant and we can use xpath to get exact matches.\nitems = response.xpath(\"//a[@class='js-variant ']\")\n\nfor item in items:\n item_text = item.css(\"::text\").get().strip()\n\n",
"There are two types of sizes which are active and disabled and they are to be diffrentia... | [
0,
0
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074278318_python_web_scraping.txt |
Q:
Using PyMongo with docker-compose generating 'waves' of connections
I'm building a system with docker-compose with an FastAPI api and Mongo as the runtime DB. The basic architecture looks as follows (relevant parts of my docker-compose.yaml -file):
version: "3.4"
services:
api:
build:
context: ./api
... | Using PyMongo with docker-compose generating 'waves' of connections | I'm building a system with docker-compose with an FastAPI api and Mongo as the runtime DB. The basic architecture looks as follows (relevant parts of my docker-compose.yaml -file):
version: "3.4"
services:
api:
build:
context: ./api
ports:
- "5057:5057"
expose:
- "5057"
working_dir:... | [
"Mongodb driver opens a pool of connections and keeps them persisten to reuse on consecutive calls per client.\nwith pymongo.MongoClient(RUNTIME_LOGGING_ENDPOINT) as client:\n\nCreates a new client, opens all connections, then closes all connections when you exit the with block\nMake client a global variable and re... | [
1
] | [] | [] | [
"docker_compose",
"fastapi",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0074277928_docker_compose_fastapi_mongodb_pymongo_python.txt |
Q:
how to use 1 master(page or model.Model) for many catigories(page)?
I want to get something like this:
but I have no idea how to do it in wagtail(1 child cant have more then 1 parent), how 2 fix it? I don't want to have 3 master pages in admin panel.
well, I'm newbie in Wagtail, I know about snippets, but I need ... | how to use 1 master(page or model.Model) for many catigories(page)? | I want to get something like this:
but I have no idea how to do it in wagtail(1 child cant have more then 1 parent), how 2 fix it? I don't want to have 3 master pages in admin panel.
well, I'm newbie in Wagtail, I know about snippets, but I need master page. I know how to do it in Django, but have no idea when using W... | [
"What do the lines in your diagram represent? Are they the class inheritance or the navigation tree? In other words, how is the master page related to products, training and timetable?\nI think rather than diving into the code, it would help to describe what you want your site to do. For example is this a site for... | [
0
] | [] | [] | [
"django",
"python",
"wagtail",
"wagtail_admin"
] | stackoverflow_0074273165_django_python_wagtail_wagtail_admin.txt |
Q:
Make Spacy tokenizer not split on /
How do I modify the English tokenizer to prevent splitting tokens on the '/' character?
For example, the following string should be one token:
import spacy
nlp = spacy.load('en_core_web_md')
doc = nlp("12/AB/568793")
for t in doc:
print(f"[{t.pos_} {t.text}]")
# produces... | Make Spacy tokenizer not split on / | How do I modify the English tokenizer to prevent splitting tokens on the '/' character?
For example, the following string should be one token:
import spacy
nlp = spacy.load('en_core_web_md')
doc = nlp("12/AB/568793")
for t in doc:
print(f"[{t.pos_} {t.text}]")
# produces
#[NUM 12]
#[SYM /]
#[ADJ AB/568793]
| [
"The approach is a variation on removing a rule in the \"Modifying existing rule sets\" from Spacy documentation:\n\nnlp = spacy.load('en_core_web_md')\ninfixes = nlp.Defaults.infixes\nassert(len([x for x in infixes if '/' in x])==1) # there seems to just be one rule that splits on /'s\n# remove that rule; then mo... | [
2,
1
] | [] | [] | [
"nlp",
"python",
"spacy"
] | stackoverflow_0071417026_nlp_python_spacy.txt |
Q:
Python code using Jupyter Notebook deployed on Azure . Issue: The kernel appears to have died. It will restart automatically
All of the script had been running perfectly fine in Jupyter Notebook. But, I am facing an issue "The kernel appears to have died. It will restart automatically" when I deploy python code us... | Python code using Jupyter Notebook deployed on Azure . Issue: The kernel appears to have died. It will restart automatically | All of the script had been running perfectly fine in Jupyter Notebook. But, I am facing an issue "The kernel appears to have died. It will restart automatically" when I deploy python code using Jupyter Notebook on Azure. All parts of the code run fine, except for the last line of the code (where I open an image using O... | [
"\nKernel Restarting\nThe kernel appears to have died. It will restart automatically.\n\nI have got the same issue. I have fixed by reinstalling the necessary packages again. I hope you already done it if not try to reinstall the necessary packages matplotlib, NumPy, TensorFlow & others.\nInstead of using !pip inst... | [
0
] | [] | [] | [
"azure",
"deployment",
"jupyter_notebook",
"opencv",
"python"
] | stackoverflow_0074253129_azure_deployment_jupyter_notebook_opencv_python.txt |
Q:
Multiprocessing event-queue not updating
So I'm writing a program with an event system.
I got a list of events to be handled.
One Process is supposed to push to the handler-list new events.
This part seems to work as I tried to print out the to-handle-list after pushing one event.
It gets longer and longer, while,... | Multiprocessing event-queue not updating | So I'm writing a program with an event system.
I got a list of events to be handled.
One Process is supposed to push to the handler-list new events.
This part seems to work as I tried to print out the to-handle-list after pushing one event.
It gets longer and longer, while, when I print out the to handle list in the ha... | [
"To have a shareable set of deque instances, you could create a special class DequeArray which will hold an internal list of deque instances and expose whatever methods you might need. Then I would turn this into a shareable, managed object. When the manager creates an instance of this class, what is returned is a ... | [
0
] | [] | [] | [
"deque",
"multiprocessing",
"python"
] | stackoverflow_0074272790_deque_multiprocessing_python.txt |
Q:
Calendar Module in Python not working
I tried to use the python calendar module in version 3.5.2 with:
import calendar
yy = 2016
mm = 12
# To ask month and year from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
display=calendar.calendar(yy,mm)
# display the calendar
print(displ... | Calendar Module in Python not working | I tried to use the python calendar module in version 3.5.2 with:
import calendar
yy = 2016
mm = 12
# To ask month and year from the user
# yy = int(input("Enter year: "))
# mm = int(input("Enter month: "))
display=calendar.calendar(yy,mm)
# display the calendar
print(display)
but every time I try to run it, crashe... | [
"From this answer here. You probably calling another file called calendar. Use this to find where that file is: print(calendar) Hope this helps! \nEDIT: also according to the documentation, I think that you are looking for the function monthdatescalendar(year, month) not calendar.month(). please read over the pytho... | [
0
] | [
"You already named a file calendar.py that it is referencing instead of the calendar module.\nhttps://intellipaat.com/community/65020/why-calendar-module-is-not-working-on-python-3\n"
] | [
-1
] | [
"calendar",
"python"
] | stackoverflow_0041366720_calendar_python.txt |
Q:
ValueError: shapes (4,87) and (4,87) not aligned: 87 (dim 1) != 4 (dim 0)
I am trying to implement the logistic regression from scratch with the data shape : x_train[0], len(x_train) be ([0.0, 0.0, 0.93, 0.07], 87) but I am receiving an error. I am sure the error is causing due to mismatch of shape of w but I am u... | ValueError: shapes (4,87) and (4,87) not aligned: 87 (dim 1) != 4 (dim 0) | I am trying to implement the logistic regression from scratch with the data shape : x_train[0], len(x_train) be ([0.0, 0.0, 0.93, 0.07], 87) but I am receiving an error. I am sure the error is causing due to mismatch of shape of w but I am unable to resolve it.
ValueError Traceback (most ... | [
"You really should tell us the dimensions at various points - since you need to know those your self. But I'll try deducing things from the code.\nx_train is a 2d array with shape (m,n):\nm = len(x_train) # x_train.shape[0]\nn = len(x_train[0]) # x_train.shape[1]\nweights = np.zeros((m,1))... | [
1
] | [] | [] | [
"logistic_regression",
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074277476_logistic_regression_numpy_python_python_3.x.txt |
Q:
How can divide a textbook every 400 lines parts with python?
i have 20 files and they all have different number of lines. Mostly 1000+ lines, i want to divide them 400 lines parts with python and save it as a different text files.
How can i do that ? Is split() method useful for this?
A:
get their names with glo... | How can divide a textbook every 400 lines parts with python? | i have 20 files and they all have different number of lines. Mostly 1000+ lines, i want to divide them 400 lines parts with python and save it as a different text files.
How can i do that ? Is split() method useful for this?
| [
"\nget their names with glob.glob()\nturn each file into list with lines as elements by f.readlines()\neach f.readlines() output extend to some common_list\nthen iterate this common_list appending a line (=common_list's element) to a new file\nand count lines, every time it's 400th one create a new file\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074278949_python.txt |
Q:
Git script is running differently when I run it through subprocess.check_output?
When I run this Bash script
#!/bin/bash
cd /srv/http
unset GIT_DIR
git commit -am "design changes"
git push -u origin master
git checkout dev
git merge master
git commit -am "design changes"
git checkout master
through the command ... | Git script is running differently when I run it through subprocess.check_output? | When I run this Bash script
#!/bin/bash
cd /srv/http
unset GIT_DIR
git commit -am "design changes"
git push -u origin master
git checkout dev
git merge master
git commit -am "design changes"
git checkout master
through the command line, I get this output
[master 914422f] design changes
1 file changed, 17 deletions(... | [
"I still don't know why it's happening, but I fixed it by running it by sshing to localhost:\nsubprocess.check_output('ssh localhost \"/srv/http/save-design\"', shell=True)\n\n",
"could it be that you aren't setting the working directory for subprocess.check_output and so git is picking up whatever random working... | [
0,
0
] | [] | [] | [
"bash",
"git",
"python"
] | stackoverflow_0024029954_bash_git_python.txt |
Q:
How to find the max hotspot of a matrix in python
I was given a matrix question on a technical assessment that revolved around the idea of finding the "Max Hotspot".
Areas of connected 1's represent a hotspot, and given a matrix we want to return the max hotspot. Similar to "Number of Islands" or "Word Search.
are... | How to find the max hotspot of a matrix in python | I was given a matrix question on a technical assessment that revolved around the idea of finding the "Max Hotspot".
Areas of connected 1's represent a hotspot, and given a matrix we want to return the max hotspot. Similar to "Number of Islands" or "Word Search.
areamap = [[1, 0, 0, 0],
[1, 1, 1, 0],
... | [
"There are two issues with the code:\n\nevap does not return any result and so count never gets assigned anything other than 0\nYou have an array of integers, but you check its elements against strings (\"0\" and \"1\")\n\nSolving those issues yields the following code, which outputs the result you want\ndef hotSpo... | [
1
] | [] | [] | [
"algorithm",
"arrays",
"depth_first_search",
"matrix",
"python"
] | stackoverflow_0074278815_algorithm_arrays_depth_first_search_matrix_python.txt |
Q:
Lua equivalent to shlex?
Is there a Lua equivalent for python's shlex library?
A:
See also LPeg.
A:
I found a reference to a project called LuaParse:
LuaParse includes Blex, a general purpose pure-Lua lexer, and lparse, a pure-Lua Lua parser, as well as a variety of utility functions and a prototype package m... | Lua equivalent to shlex? | Is there a Lua equivalent for python's shlex library?
| [
"See also LPeg.\n",
"I found a reference to a project called LuaParse:\n\nLuaParse includes Blex, a general purpose pure-Lua lexer, and lparse, a pure-Lua Lua parser, as well as a variety of utility functions and a prototype package management system.\n\nMaybe this will meed your needs.\n",
"If the goal is to p... | [
4,
3,
3,
1,
0
] | [] | [] | [
"command_line_arguments",
"lua",
"parsing",
"python"
] | stackoverflow_0001851940_command_line_arguments_lua_parsing_python.txt |
Q:
Tkinter canvas animation
I'm working with Tkinter and canvas, and I want to make a moving animation. I have a coordinate list:
# coordinates
x = [100, 200, 300, 400]
y = [50, 200, 250, 300]
# starting point
radius = 5
dot = canvas.create_oval(x[0]-radius, y[0]-radius, x[0]+radius, y[0]+radius, fill="red")
Expect... | Tkinter canvas animation | I'm working with Tkinter and canvas, and I want to make a moving animation. I have a coordinate list:
# coordinates
x = [100, 200, 300, 400]
y = [50, 200, 250, 300]
# starting point
radius = 5
dot = canvas.create_oval(x[0]-radius, y[0]-radius, x[0]+radius, y[0]+radius, fill="red")
Expected output would be the animati... | [
"You could do it with a combination of canvas.coords(dot, ...), as @acw1668 suggests (+1), and tkinter's after() method:\nimport tkinter as tk\nfrom itertools import cycle\n\nRADIUS = 5\nDELAY = 1000 # milliseconds\nWIDTH, HEIGHT = 500, 500\n\ncoordinates = [(100, 50), (200, 200), (300, 250), (400, 300)]\n\ndef mo... | [
0
] | [] | [] | [
"python",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0074269304_python_tkinter_tkinter_canvas.txt |
Q:
`setup.py develop` works but `pip install -e` doesn't - TypeError: 'module' object is not callable
Setuptools deprecated develop in favor of -e, yet former works for me while latter gives
TypeError: 'module' object is not callable
for MyClass() that comes from from my_pkg import MyClass, with __init__.py being
fr... | `setup.py develop` works but `pip install -e` doesn't - TypeError: 'module' object is not callable | Setuptools deprecated develop in favor of -e, yet former works for me while latter gives
TypeError: 'module' object is not callable
for MyClass() that comes from from my_pkg import MyClass, with __init__.py being
from .myclass import MyClass
All I found is a bunch of closed and stale issues that point to this issue.
... | [] | [] | [
"pip uninstall not working with editable dependencies, had to remove manually from site-packages.\n"
] | [
-1
] | [
"anaconda",
"pip",
"pytest",
"python",
"setuptools"
] | stackoverflow_0074277838_anaconda_pip_pytest_python_setuptools.txt |
Q:
mod_wsgi flask app not seeing jinja2 to import?
I have a test script, test_wsgi.py. See below. This is working. I can hit https://opencalaccess.org/test_wsgi and I get a good result, so I think that mod_wsgi is properly set up.
But when I access my main script, I get a 500.
Here is the bit in my conf:
WSGI... | mod_wsgi flask app not seeing jinja2 to import? | I have a test script, test_wsgi.py. See below. This is working. I can hit https://opencalaccess.org/test_wsgi and I get a good result, so I think that mod_wsgi is properly set up.
But when I access my main script, I get a 500.
Here is the bit in my conf:
WSGIScriptAlias /test_wsgi /var/www/opencalaccess_org/tes... | [
"The SyntaxError on def get(self, key: str) -> bytes: would be because mod_wsgi is attempting to run your script with a Python version before type annotations were added (probably 2.7, but could be anything below 3.5).\nThe mod_wsgi docs say that Python scripts run through WSGIDaemonProcess need to be of the same v... | [
0,
0
] | [] | [] | [
"mod_wsgi",
"python",
"virtualenv"
] | stackoverflow_0074101368_mod_wsgi_python_virtualenv.txt |
Q:
Opening Python script mode on a MacBook
I have a MacBook air and have tried opening Python in terminal but when I open it, it opens Python interactive mode. Does anyone know how to open Python script mode please.
Iβve tried typing in things such as Python or Python 3 like safari suggests but that didnβt work.
A:... | Opening Python script mode on a MacBook | I have a MacBook air and have tried opening Python in terminal but when I open it, it opens Python interactive mode. Does anyone know how to open Python script mode please.
Iβve tried typing in things such as Python or Python 3 like safari suggests but that didnβt work.
| [
"There is no 'script mode'. You can create a Python script using TextEdit or another editor, save it as myfile.py, and then run it with python myfile.py.\n",
"for running what you are calling 'script version' of python you should choose a python file to run and make sure is written in the same or in a compatible ... | [
0,
0,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0074278705_macos_python.txt |
Q:
Loading shapefile with altair, getting only gibberish
I'm trying to create a cloropleth map using Italian provinces. I downloaded the shapefiles from here, when I load the .shp file into mapshaper everything works, but when I try to load the file using altair on my computer I obtain a nonsensical plot. What AM I d... | Loading shapefile with altair, getting only gibberish | I'm trying to create a cloropleth map using Italian provinces. I downloaded the shapefiles from here, when I load the .shp file into mapshaper everything works, but when I try to load the file using altair on my computer I obtain a nonsensical plot. What AM I doing wrong? I followed some tutorials and I should be doing... | [
"This is all down to the CRS of the data. Projecting GeoDataFrame to epsg:4286 first resolves the issue. (This code requires download code to be run before plotting code)\nplot\nimport altair as alt\ngdf = gdfs[\"ProvCM01012022_g_WGS84.shp\"].to_crs(\"epsg:4286\")\n\nalt.Chart(gdf).mark_geoshape(\n fill='lightg... | [
2
] | [] | [] | [
"altair",
"geometry",
"geopandas",
"python",
"python_3.x"
] | stackoverflow_0074219191_altair_geometry_geopandas_python_python_3.x.txt |
Q:
Generate all possible combinations of characters, of every length, from an array using Python
I want to generate all possible combinations of letters from array ["a", "b", "c"]
I've seen programs that should have generated all combinations but I got [('a', 'b'), ('a', 'c'), ('b', 'c')] which is wrong because its m... | Generate all possible combinations of characters, of every length, from an array using Python | I want to generate all possible combinations of letters from array ["a", "b", "c"]
I've seen programs that should have generated all combinations but I got [('a', 'b'), ('a', 'c'), ('b', 'c')] which is wrong because its missing ('b', 'a'), ('b', 'b') ('c', 'a'), ('c', 'b'). Does anyone have any idea for how to generate... | [
"from itertools import product\n\ntext = 'abc'\n\nall_product = sum((list(product(text,repeat=i)) for i in range(len(text)+1)),[])\nprint(all_product)\n\nWhat you are looking for is product from the built-in packages. You need to increase the repeat parameter from 0 to the length of the input text, that's why I add... | [
0
] | [] | [] | [
"combinations",
"python"
] | stackoverflow_0074279079_combinations_python.txt |
Q:
FileNotFoundError: [Errno 2] No such file or directory Pandas
I am trying to read my excel file with pd.read_excel in python.
But Δ± am get this error message = FileNotFoundError: [Errno 2] No such file or directory
I put my excel file same place with my python file.
pic1 pic2
A:
You can use full path this way to... | FileNotFoundError: [Errno 2] No such file or directory Pandas | I am trying to read my excel file with pd.read_excel in python.
But Δ± am get this error message = FileNotFoundError: [Errno 2] No such file or directory
I put my excel file same place with my python file.
pic1 pic2
| [
"You can use full path this way to read the excel file. And also add r prefix before the file path so backslash will be treated as literal character\npd.read_excel(r\"C:\\Users\\selman\\PycharmProjects\\selman_learning\\bisiklet_fiyatlari.xlsx\")\n\n",
"import pandas as pd\npath = 'absolute_path/records.xlsx' #eg... | [
3,
1,
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0071176986_pandas_python.txt |
Q:
Remove \n from specific lines Python
I have a function where I am converting pdf files to text files. It's all working fine, except I have to clean up the paragraphs where there are bullet points by removing \n from the end of each string line that starts with the word bullet_point. I want to replace \n with "end_... | Remove \n from specific lines Python | I have a function where I am converting pdf files to text files. It's all working fine, except I have to clean up the paragraphs where there are bullet points by removing \n from the end of each string line that starts with the word bullet_point. I want to replace \n with "end_bullet". Then I want to join the lines tha... | [
"I managed to find a solution, so I'm posting it, as it might help someone:\nfor i in range(len(jpgFiles)):\n Text1 = pytesseract.image_to_string(Image.open(destination_jpg + jpgFiles[i]),\n config=\"tessdata_dir_config --psm 6 --oem 1\")\\\n .replace('\\n\\n... | [
0
] | [] | [] | [
"carriage_return",
"character_replacement",
"python"
] | stackoverflow_0074193582_carriage_return_character_replacement_python.txt |
Q:
pyannotate apply says "No files need to be modified." even if functions are not annotated
I have been using pytest https://github.com/kensho-technologies/pytest-annotate and have been following the process of:
pip install pytest-annotate
# Generate annotations by running your pytest tests as usual:
pytest --annot... | pyannotate apply says "No files need to be modified." even if functions are not annotated | I have been using pytest https://github.com/kensho-technologies/pytest-annotate and have been following the process of:
pip install pytest-annotate
# Generate annotations by running your pytest tests as usual:
pytest --annotate-output=./annotations.json
# Apply those annotations using pyannotate:
pyannotate --type-in... | [
"I am aware of 2 possible reasons you get this error.\nPossible Issues\n\nThe function without type hints is not actually called by the tests. (pyannotate, and monkeytype for that matter, only generate type-hints for the code that was executed, not for all the code.)\nYou are not applying the type-hints to a Python... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0067035617_python.txt |
Q:
Flask SQLAlchemy: TypeError: 'Flask' object is not iterable
I am attempting to create a Flask app where users can register / login and have their own page (following a tutorial on YT) - I am quite new to this and am struggling to understand the error message that I am receiving.
Error Message:
Traceback (most rece... | Flask SQLAlchemy: TypeError: 'Flask' object is not iterable | I am attempting to create a Flask app where users can register / login and have their own page (following a tutorial on YT) - I am quite new to this and am struggling to understand the error message that I am receiving.
Error Message:
Traceback (most recent call last):
File "C:\Users\mmacp\PycharmProjects\cfg_project... | [
"I have solved this by adding a piece of code to the create_app() function in the init.py file:\ndef create_app():\n app = Flask(__name__)\n app.config['SECRET_KEY'] = 'kdxhfds iefhsdbf'\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///databse.db'\n db.init_app(app)\n\n ***with app.app_context():... | [
1
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"python"
] | stackoverflow_0074278688_flask_flask_sqlalchemy_python.txt |
Q:
How can I count occurrences of words specified in an array in Python?
I am working on a small program in which the user enters text and I would like to check how many times the given words occur in the given input.
# Read user input
print("Input your code: \n")
user_input = sys.stdin.read()
print(user_input)
For... | How can I count occurrences of words specified in an array in Python? | I am working on a small program in which the user enters text and I would like to check how many times the given words occur in the given input.
# Read user input
print("Input your code: \n")
user_input = sys.stdin.read()
print(user_input)
For example, the text that I input in a program is:
a=1
b=3
if (a == 1):
p... | [
"I think the best option is to use the tokenize built-in module of python:\n# Let's say this is tokens.py\nimport sys\nfrom collections import Counter\nfrom io import BytesIO\nfrom tokenize import tokenize\n\n# Get input from stdin\ncode_text = sys.stdin.read()\n\n# Tokenize the input as python code\ntokens = token... | [
3
] | [] | [] | [
"arrays",
"python",
"user_input"
] | stackoverflow_0074278889_arrays_python_user_input.txt |
Q:
What does "aggregated" mean in this context? aggregated=False? (Python)
Looking over assignments and practice we were working with Linked Lists and we were provided with the following code :
`
class LinkedList:
class ListNode:
def __init__(self, data=None):
self.next = None
self... | What does "aggregated" mean in this context? aggregated=False? (Python) | Looking over assignments and practice we were working with Linked Lists and we were provided with the following code :
`
class LinkedList:
class ListNode:
def __init__(self, data=None):
self.next = None
self.prev = None
self.data = data
def __init__(self):
sel... | [
"aggregated is an argument of the function that you can pass when calling the function. E.g. you could call the function like this:\nlist = LinkedList()\nlist.charCount(True)\n\nIn this case, the value of the aggregated argument that you passed is True.\nThe =False part in the function declaration means that you do... | [
0
] | [] | [] | [
"linked_list",
"python"
] | stackoverflow_0074279115_linked_list_python.txt |
Q:
Verifying AzureAD access token with Django-REST-framework
Before anything I would like to warn you about my extremely limited knowledge on the subject.
Now that you've been warned, what I need to ask is how can I verify and azureAD access token with Django/django-rest-framework.
I have a app that I need to sign in... | Verifying AzureAD access token with Django-REST-framework | Before anything I would like to warn you about my extremely limited knowledge on the subject.
Now that you've been warned, what I need to ask is how can I verify and azureAD access token with Django/django-rest-framework.
I have a app that I need to sign in to with azureAD, which means I need to get an access token fro... | [
"Ok, so I owe this to my past self.\nWhat I did is got the authorization from the headers of the request, sliced it so it's the token only and used the used the microsoft keys url, audience and jwt package to decode it, here is the code:\nurl = \"https://login.microsoftonline.com/5c9b264f-33ad-4093-bb65-8d14aaec9f6... | [
0
] | [] | [] | [
"azure_active_directory",
"django",
"django_rest_auth",
"django_rest_framework",
"python"
] | stackoverflow_0073319757_azure_active_directory_django_django_rest_auth_django_rest_framework_python.txt |
Q:
Is there any way to manipulate an image using a color curve in python?
I have a series of tif images and was wondering if there is a possibility to write something in python (using maybe scikit-image or OpenCV) to apply a color curve. The data I have looks like the following, where we have a list of x, y, x, y... ... | Is there any way to manipulate an image using a color curve in python? | I have a series of tif images and was wondering if there is a possibility to write something in python (using maybe scikit-image or OpenCV) to apply a color curve. The data I have looks like the following, where we have a list of x, y, x, y... data like so: (0, 0, 32, 22, 64, 56, 128, 128, 192, 196, 255, 255).
| [
"With the new information you provided I think that the following code should do the trick. lut_in is the vector of input gray levels and lut_out the desired output level. Here it's applied for all 3 channels (like in photoshop). The only thing you need is the interpolation to have a LUT (look up table) of 256 elem... | [
2,
1,
1
] | [] | [] | [
"opencv",
"python",
"scikit_image"
] | stackoverflow_0059851952_opencv_python_scikit_image.txt |
Q:
Do we need to manually cache schema registry?
We are currently using Protocol Buffers as serialization mechanism for kafak message. We are going to move to Avro. We tested Avro Confluent consumer with Schema Registry and according to those tests, Avro consumer is little bit slow compare to protobuff consumer.
My q... | Do we need to manually cache schema registry? | We are currently using Protocol Buffers as serialization mechanism for kafak message. We are going to move to Avro. We tested Avro Confluent consumer with Schema Registry and according to those tests, Avro consumer is little bit slow compare to protobuff consumer.
My question is do we need to manually cash schemas or P... | [
"I had the same problem some time ago, there is additional latency when you're moving from Google protobuf, which is really fast, to something like Avro + Schema Registry. \nYou definitely have the option to cache the schemas manually. However, most decent kafka clients that talk to SchemaRegistry should already do... | [
1,
0
] | [] | [] | [
"apache_kafka",
"avro",
"confluent_platform",
"confluent_schema_registry",
"python"
] | stackoverflow_0050168243_apache_kafka_avro_confluent_platform_confluent_schema_registry_python.txt |
Q:
NoReverseMatch at / - not understanding reason
I am trying to create a 'edit settings/ view profile page' drop down item in my navbar. The functionality was working prior to being called from the drop down which now throws the NoReverseMatch error as shown below:
Reverse for 'show_profile_page' with arguments '(''... | NoReverseMatch at / - not understanding reason | I am trying to create a 'edit settings/ view profile page' drop down item in my navbar. The functionality was working prior to being called from the drop down which now throws the NoReverseMatch error as shown below:
Reverse for 'show_profile_page' with arguments '('',)' not found. 1 pattern(s) tried: ['subs/(?P[0-9]+)... | [
"Without the forms.py i cant give you a code example, but I suspect if you created a Profile object in your Admin panel it would solve the issue. If you aren't sure how to register your Profile model in the Admin panel then a simple example can be found in the docs here:\nhttps://docs.djangoproject.com/en/4.1/ref/c... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074277605_django_python.txt |
Q:
SSLError: max retries exceeded with url error? How to fix this?
I am attempting to scrape text off of websites, and I am using the requests module to do so.
With the given code (Facebook as an example here)
requests.get('http://facebook.com')
I receive back the following error:
SSLError: HTTPSConnectionPool(host=... | SSLError: max retries exceeded with url error? How to fix this? | I am attempting to scrape text off of websites, and I am using the requests module to do so.
With the given code (Facebook as an example here)
requests.get('http://facebook.com')
I receive back the following error:
SSLError: HTTPSConnectionPool(host='facebook.com', port=443): Max retries exceeded with url: / (Caused b... | [
"You can try this way\nimport requests\nfrom urllib3.exceptions import InsecureRequestWarning\nfrom urllib3 import disable_warnings\n\ndisable_warnings(InsecureRequestWarning)\n\npage = requests.get('http://facebook.com', verify=False)\n\nprint(page.content)\n\n",
"The problem probably stems from an overly aggres... | [
4,
0
] | [] | [] | [
"certifi",
"python",
"ssl",
"ssl_certificate"
] | stackoverflow_0072188582_certifi_python_ssl_ssl_certificate.txt |
Q:
Method is not appending to list like other similar methods
I'm a beginner at pyhton. i'm working on a poker game. currently i'm stuck at dealing every player two cards. dealing the flop, turn and river work fine but dealing the player cards doesn't work. I don't understand why it doesn't work. Any solutions, expla... | Method is not appending to list like other similar methods | I'm a beginner at pyhton. i'm working on a poker game. currently i'm stuck at dealing every player two cards. dealing the flop, turn and river work fine but dealing the player cards doesn't work. I don't understand why it doesn't work. Any solutions, explanation, other approaches advice are appreciated. Link to my gith... | [
"In the code you use for testing, by doing the following:\na = player('a')\nyou do not assign player('a') from list_of_players to variable a, but create another player with name \"a\". That is why you cannot see its cards. But it will work properly, when you do it like this:\na = list_of_players[0]\na.show_hand(\"a... | [
1
] | [] | [] | [
"class",
"game_development",
"poker",
"python"
] | stackoverflow_0074274660_class_game_development_poker_python.txt |
Q:
What is this hexadecimal in the utf16 format?
print(bytes('ba', 'utf-16'))
Result :
b'\xff\xfeb\x00a\x00'
I understand utf-16 means every character will take 16 bits means 00000000 00000000 in binary and i understand there are 16 bits here x00a means x00 = 00000000 and a = 01000001 so both gives x00a it is clear... | What is this hexadecimal in the utf16 format? | print(bytes('ba', 'utf-16'))
Result :
b'\xff\xfeb\x00a\x00'
I understand utf-16 means every character will take 16 bits means 00000000 00000000 in binary and i understand there are 16 bits here x00a means x00 = 00000000 and a = 01000001 so both gives x00a it is clear to my mind like this but here is the confusion:
\x... | [
"I think you are misinterpreting the printout.\nYou have 3 16-bit words:\n\nFFFE: This is the byte-order mark required in UTF-16 (Byte order mark - Wikipedia).\n00, followed by the 8-bit encoding of 'b' (that is shown as the character 'b' instead of using an \\x escape sequence): This is the 16-bit representation o... | [
1,
1,
1
] | [] | [] | [
"encoding",
"endianness",
"python",
"utf_16"
] | stackoverflow_0074278473_encoding_endianness_python_utf_16.txt |
Q:
Python Pandas Result of dataframe groupby agg to dict to be easily used outside of pandas
I have a dataframe that I'm grouping as seen below:
df_sums = df.groupby(["Product", "Year", "Month"]).agg({"Quantity": "sum"})
When I check the result in the console, it prints this data exactly as I want, with clear divisio... | Python Pandas Result of dataframe groupby agg to dict to be easily used outside of pandas | I have a dataframe that I'm grouping as seen below:
df_sums = df.groupby(["Product", "Year", "Month"]).agg({"Quantity": "sum"})
When I check the result in the console, it prints this data exactly as I want, with clear division / grouping, example below:
Product Year Month Quantity
product1 ... | [
"When you're using the .to_dict() function on a Pandas dataframe with multiple columns, the key will be a tuple of the values of all the other columns, with the last column being the value of the key. That dictionary is nestled in another one with the column itself.\nSo the original output is in the format of:\n>>>... | [
1
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074279160_dataframe_dictionary_pandas_python.txt |
Q:
How to remove element from list if part of it appears in another list in python
So let's say I have
list_1 = ["ABC_123,Hello,World", "DEF_456,Hello,World"]
list_2 = ["ABC_123,Something,Else", "KOR_729,Something,Else"]
What I want to do is remove the elements from list_1 that contain the same first part of the str... | How to remove element from list if part of it appears in another list in python | So let's say I have
list_1 = ["ABC_123,Hello,World", "DEF_456,Hello,World"]
list_2 = ["ABC_123,Something,Else", "KOR_729,Something,Else"]
What I want to do is remove the elements from list_1 that contain the same first part of the string as in list_2, in this case "ABC_123".
The expected output would be
list_3 = ["DEF... | [
"Alright so after some trying I was able to get it to work.\nHere is a solution:\nlist_1 = [\"ABC_123,Hello,World\",\"DEF_456,Hello,World\"]\nlist_2 = [\"ABC_123,Something,Else\",\"KOR_729,Something,Else\"]\n\nlist_2_prefix = set([x.split(sep=\",\")[0] for x in list_2])\nlist_3 = [x for x in list_1 if x.split(sep=\... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074278842_python_python_3.x.txt |
Q:
How can I combine 2 lists in a specific order?
This is an example for 3 elements
List_A = ['abc', 'def', 'ghi']
List_B = ['123', '456', '789']
for i in [List_A[0], List_B[0]]:
for j in [List_A[1], List_B[1]]:
for k in [List_A[2], List_B[2]]:
print(i+j+k)
Following this result:
abcdefghi
a... | How can I combine 2 lists in a specific order? | This is an example for 3 elements
List_A = ['abc', 'def', 'ghi']
List_B = ['123', '456', '789']
for i in [List_A[0], List_B[0]]:
for j in [List_A[1], List_B[1]]:
for k in [List_A[2], List_B[2]]:
print(i+j+k)
Following this result:
abcdefghi
abcdef789
abc456ghi
abc456789
123defghi
123def789... | [
"Do you want something like?\nimport itertools\nprint([\"\".join(i) for i in itertools.product(*zip(a, b))])\n\nwhich gives\n['abcdefghi',\n 'abcdef789',\n 'abc456ghi',\n 'abc456789',\n '123defghi',\n '123def789',\n '123456ghi',\n '123456789']\n\n"
] | [
3
] | [] | [] | [
"combinatorics",
"python"
] | stackoverflow_0074279307_combinatorics_python.txt |
Q:
Loop to test range of variables and find the best ones in Pyhton
First of all thank you for this amazing space to learn from you all, I have the following question. I created a code that imports data from several APIs and it performs various statistical operations around the data. And it returns 1 result number, w... | Loop to test range of variables and find the best ones in Pyhton | First of all thank you for this amazing space to learn from you all, I have the following question. I created a code that imports data from several APIs and it performs various statistical operations around the data. And it returns 1 result number, which is helpful to see if the model is correct.
The code is built arou... | [
"Extracting the maximal result from a loop\nbest_result = None\nfor variable_1 in range(-4, 4, 1):\n result = my_code()\n if best_result is None or best_result > result:\n best_result = result\n\nIterating over decimals (numpy solution)\nimport numpy as np\n\nbest_result = None\nfor variable_1 in np.ar... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074279127_python.txt |
Q:
pandas data frame transform INT64 columns to boolean
Some column in dataframe df, df.column, is stored as datatype int64.
The values are all 1s or 0s.
Is there a way to replace these values with boolean values?
A:
df['column_name'] = df['column_name'].astype('bool')
For example:
import pandas as pd
import num... | pandas data frame transform INT64 columns to boolean | Some column in dataframe df, df.column, is stored as datatype int64.
The values are all 1s or 0s.
Is there a way to replace these values with boolean values?
| [
"df['column_name'] = df['column_name'].astype('bool')\n\nFor example:\nimport pandas as pd\nimport numpy as np\ndf = pd.DataFrame(np.random.random_integers(0,1,size=5), \n columns=['foo'])\nprint(df)\n# foo\n# 0 0\n# 1 1\n# 2 0\n# 3 1\n# 4 1\n\ndf['foo'] = df['foo'].astype('bool')... | [
69,
2,
0
] | [] | [] | [
"boolean",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0018748171_boolean_dataframe_numpy_pandas_python.txt |
Q:
how can i add text to my popup label from another class function with kivy
I want to display the color name that i found at { closest_colour(requested_colour) } function
in popup window.
In practice application supposed to ask for file from your computer (only specific image types) then ask for mouse input while d... | how can i add text to my popup label from another class function with kivy | I want to display the color name that i found at { closest_colour(requested_colour) } function
in popup window.
In practice application supposed to ask for file from your computer (only specific image types) then ask for mouse input while displaying image that you choose.Finally opens popup window to display color of p... | [
"Okay, the structure of what you're trying to do is a little confusing, the class LoadDialog(FloatLayout) looks like it's being called just to make the connection between the two classes, is that it?\nBut from the looks of it, you are trying to pass the text from variable\n\nanswer\n\nthat is returned when you call... | [
0
] | [] | [] | [
"kivy",
"opencv",
"popup",
"python"
] | stackoverflow_0074277363_kivy_opencv_popup_python.txt |
Q:
Move substring to front of string
I have a field "Numbers" that can have a value such as:
"01-02-03-04-Zero"
I want to change the substring "Zero" to "00" and move it to the front of the string, so that the result is:
"00-01-02-03-04"
Not all rows contain this "Zero" substring so I only want to perform this on fie... | Move substring to front of string | I have a field "Numbers" that can have a value such as:
"01-02-03-04-Zero"
I want to change the substring "Zero" to "00" and move it to the front of the string, so that the result is:
"00-01-02-03-04"
Not all rows contain this "Zero" substring so I only want to perform this on fields that do.
| [
"You can use regex. In this approach you can replace Zero with 00 if exist.\nimport re\n\ndef change_Zero(st):\n # If we find '-Zero', we replace all strings with '00' that add to the first part. \n # with '\\1' access to first part\n return re.sub(r\"(.*)(-Zero)\", r\"00-\\1\", st) \n\nprint(change_Zero(\... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"substring"
] | stackoverflow_0074279314_pandas_python_substring.txt |
Q:
How do I predict the value based on the curve?
I have two matrices (100,6). one of them contains PSNR values for different bitrates and the other one contains corresponding bitrates. if I plot the diagram of one row, we will have the following diagram based on the following data.
660256 1522800 2481600 3533650 44... | How do I predict the value based on the curve? | I have two matrices (100,6). one of them contains PSNR values for different bitrates and the other one contains corresponding bitrates. if I plot the diagram of one row, we will have the following diagram based on the following data.
660256 1522800 2481600 3533650 4432290 5469300
38.3587 41.0925 42.3772 43.4243 44.158... | [
"If linear interpolation is good enough, you can use interp1d\nimport scipy \n\nlinear_PSNR_model = scipy.interpolate.interp1d(x_values, PSNR_values)\n\nThen, you can use linear_PSNR_model as a function like this\nlinear_PSNR_model(1000000)\n"
] | [
2
] | [] | [] | [
"curve_fitting",
"python"
] | stackoverflow_0074279319_curve_fitting_python.txt |
Q:
Is there a way I can make this more elegant? I cant figure out any other way to write this
comboList = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
#duplicate values wont be entered into these test lists to begin with so idc about that
testList1 = [0,1,2]
testList2 = [1,2,4,7]
testList3 = [0,... | Is there a way I can make this more elegant? I cant figure out any other way to write this | comboList = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
#duplicate values wont be entered into these test lists to begin with so idc about that
testList1 = [0,1,2]
testList2 = [1,2,4,7]
testList3 = [0,2,3,6,5,69,4,6,1]
testList4 = [2,1,3] #this needs to return false
def testfunc(mainList, sublis... | [
"You could break down the logic into separate functions which are shorter and more readable, like this:\ndef has_n_items(iterable, n):\n \"\"\" Check whether an iterable has at least n items \"\"\"\n for i, _ in enumerate(iterable, 1):\n if i == n:\n return True\n return False\n\ndef has_... | [
0
] | [
"As well as improving your function you could simplify the test to avoid repeats:\ncomboList = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]\n#duplicate values wont be entered into these test lists to begin with so idc about that\n\ntestlists = {'test1': [0,1,2], 'test2': [1,2,4,7], 'test3': [0,... | [
-1,
-1,
-2
] | [
"list",
"loops",
"optimization",
"performance",
"python"
] | stackoverflow_0074279119_list_loops_optimization_performance_python.txt |
Q:
Additional data in dependency injection
I have a code like the below:
class ISaver(abc.ABC):
@abstractmethod
def save(self, text):
pass
class FileSaver(ISaver):
def __init__(self, filepath):
self.filepath = filepath # <----- This part is important, please remember it
def save(sel... | Additional data in dependency injection | I have a code like the below:
class ISaver(abc.ABC):
@abstractmethod
def save(self, text):
pass
class FileSaver(ISaver):
def __init__(self, filepath):
self.filepath = filepath # <----- This part is important, please remember it
def save(self, text):
with open(self.filepath, 'w... | [
"Can you have a filepath setter and call that from within Scraper1? Although this is no longer follows the DI pattern; the filepath is a dependency of Scraper1, so it should be injected in to it.\nfrom dependency_injector import containers, providers\nimport abc\n\nclass ISaver(abc.ABC):\n @abc.abstractmethod\n ... | [
0
] | [] | [] | [
"dependency_injection",
"python",
"python_3.x"
] | stackoverflow_0073846095_dependency_injection_python_python_3.x.txt |
Q:
multiprocessing not using all cores while running simple script in jupyter notebook
I am a trying to understand why not all the cores are being used, I have an I7 with 6 cores and 12 logical processors.
I am trying to calculate a diversity index on a large dataframe(1,2mln rows and a subsets of the dataframe which... | multiprocessing not using all cores while running simple script in jupyter notebook | I am a trying to understand why not all the cores are being used, I have an I7 with 6 cores and 12 logical processors.
I am trying to calculate a diversity index on a large dataframe(1,2mln rows and a subsets of the dataframe which is 1/3 of the rows).
So far I have tried to only run it on the subset. I think that the ... | [
"I haven't used Pools before, but the map function takes an iterable so I would expect it to pass jobs to the pool one by one. If this is the case, the workers will be spending most of their time marshalling data. I would try setting chunksize to something like len(df) // core_count. This should minimise any marsha... | [
1
] | [] | [] | [
"jupyter_notebook",
"multiprocessing",
"performance",
"python"
] | stackoverflow_0074272521_jupyter_notebook_multiprocessing_performance_python.txt |
Q:
Replacing duplicate values in distinct columns
I have the following dataframe:
Year-Week Case Team Case Info
2022-42 540 Finance OTHER
2022-42 540 IT ACCEPTED
2022-42 480 Sales OTHER
2022-42 480 Finance CHECK CASE
2022-42 480 IT OTHER
202... | Replacing duplicate values in distinct columns | I have the following dataframe:
Year-Week Case Team Case Info
2022-42 540 Finance OTHER
2022-42 540 IT ACCEPTED
2022-42 480 Sales OTHER
2022-42 480 Finance CHECK CASE
2022-42 480 IT OTHER
2022-42 465 IT OTHER
2022-42 465 ... | [
"Not exactly, the most efficient way but this method chaining should work buddy\ndf.groupby('Case')['Case Info'].apply(lambda x : x.replace('OTHER',np.nan).bfill().ffill()) # This should return your wanted series\n\n"
] | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074279627_pandas_python.txt |
Q:
Limit the number of repetitive consecutive characters in a string
I'm preprocessing tweets and need to set the maximum limit of the number of consecutive occurrences of "@USER" to 3 times. For example, a tweet like this:
this tweet contains hate speech @USER@USER@USER@USER@USER about a target group @USER@USER
af... | Limit the number of repetitive consecutive characters in a string | I'm preprocessing tweets and need to set the maximum limit of the number of consecutive occurrences of "@USER" to 3 times. For example, a tweet like this:
this tweet contains hate speech @USER@USER@USER@USER@USER about a target group @USER@USER
after processing, should look like this:
this tweet contains hate speech... | [
"You can just use re to replace 4 or more occurrences of @USER with three:\ntweet = \"this tweet contains hate speech @USER@USER@USER@USER@USER about a target group @USER@USER\"\nre.sub(r'(@USER){4,}', r'@USER@USER@USER', tweet)\n\n",
"Regular expressions.\n>>> import re\n\n>>> re.sub(rf'({k}){{4,}}', k*3, tweets... | [
1,
1
] | [] | [] | [
"data_preprocessing",
"nlp",
"python"
] | stackoverflow_0074279532_data_preprocessing_nlp_python.txt |
Q:
Why won't chatterbot python learn from our convos?
I'm using ChatterBot in python and it enters the data into the Sqlite database but doesn't actually match it...
For example it says its adding a reply but then I can never get it to repeat it.
If I say What is your name... and it doesn't know then I reply "it's m... | Why won't chatterbot python learn from our convos? | I'm using ChatterBot in python and it enters the data into the Sqlite database but doesn't actually match it...
For example it says its adding a reply but then I can never get it to repeat it.
If I say What is your name... and it doesn't know then I reply "it's mia" it never says its name is mia.
It can't even get bas... | [] | [] | [
"Turned out it was the version of chatterbot I was using it was buggy. I fixed issue by using stable version 1.0.0\n"
] | [
-1
] | [
"artificial_intelligence",
"chatbot",
"chatterbot",
"machine_learning",
"python"
] | stackoverflow_0074257667_artificial_intelligence_chatbot_chatterbot_machine_learning_python.txt |
Q:
With df.replace able to replace pd.NaT with any value but np.nan/None
With df.replace able to replace pd.NaT with any value but np.nan/None
Note: I have to do multiple data transformations where I'd be using fillna('') which wont work on NaT and I don't want chained replace as it's bit expensive on massive datafra... | With df.replace able to replace pd.NaT with any value but np.nan/None | With df.replace able to replace pd.NaT with any value but np.nan/None
Note: I have to do multiple data transformations where I'd be using fillna('') which wont work on NaT and I don't want chained replace as it's bit expensive on massive dataframes.
I have a df (provided after dtype info)
ID ... | [
"pandas has some issues with types overall and that is why those pd.NaT and 'pd.NA' are for.\nHere is an example of the issue when using the columns with bool type. After creating a DataFrame where one column bool_type holds only boolean values will be type 'bool' while another column boot_with_none containing boo... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074279136_pandas_python.txt |
Q:
pandas - create sparse matrix for collaborative filtering
I have a pandas dataframe like this:
user_id
music_id
rating
A
a
5
B
a
3
and I would like to create a sparse matrix from it, putting music_id as column and user_id as a row like this:
->
a
b
A
5
B
3
what would be the way to achieve it by using panda... | pandas - create sparse matrix for collaborative filtering | I have a pandas dataframe like this:
user_id
music_id
rating
A
a
5
B
a
3
and I would like to create a sparse matrix from it, putting music_id as column and user_id as a row like this:
->
a
b
A
5
B
3
what would be the way to achieve it by using pandas or numpy for this task?
| [
"If we suppose you have the following dataset as describe in your question:\nd = {'user_id':['A','B'],'music_id':['a','a'],'rating':[5,3]}\ndf = pd.DataFrame(d)\n\nThen you can do:\ndf.set_index(['user_id','music_id']).unstack(level=-1).rating\n\nor, equivalently:\npd.pivot_table(df,values='rating',index='user_id',... | [
1
] | [] | [] | [
"matrix",
"numpy",
"pandas",
"python",
"sparse_matrix"
] | stackoverflow_0074279328_matrix_numpy_pandas_python_sparse_matrix.txt |
Q:
Merge multiple csv files into one
I have roughly 20 csv files (all with headers) that I would like to merge all of them into 1 csv file.
Looking online, one way I found was to use the terminal command:
cat *.csv > file.csv
This worked just fine, but the problem is, as all the csv file comes with the headers, thos... | Merge multiple csv files into one | I have roughly 20 csv files (all with headers) that I would like to merge all of them into 1 csv file.
Looking online, one way I found was to use the terminal command:
cat *.csv > file.csv
This worked just fine, but the problem is, as all the csv file comes with the headers, those also get placed into the csv file.
Is... | [
"You can do this with awk:\nawk '(NR == 1) || (FNR > 1)' *.csv > file.csv\n\nFNR refers to the record number (typically the line number) in the current file and NR refers to the total record number. So the first line of the first file is accepted and the first lines of the subsequent files are ignored.\nThis does a... | [
1,
1,
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0068557745_csv_python.txt |
Q:
Telebot (pyTelegramBotAPI): how to wait for a single reply and stop the bot
I'm trying to implement a function in Python that would just send a message via telegram bot, wait for a single reply, stop the bot and return the reply.
The following code works correctly, but only once: on the second call telebot receive... | Telebot (pyTelegramBotAPI): how to wait for a single reply and stop the bot | I'm trying to implement a function in Python that would just send a message via telegram bot, wait for a single reply, stop the bot and return the reply.
The following code works correctly, but only once: on the second call telebot receives the same reply. Tried reading the docs (especially about polling), but got more... | [
"You can use use types.ForceReply(selective=False) and check if the message user sent is replied to the message. Here is some code that may help:\nfrom telebot import *\nbot = TeleBot('TOKEN')\n@bot.message_handler(func=lambda _: True)\ndef send_msg(message):\n msg_id = message.message_id\n msg = bot.send_mes... | [
0
] | [] | [] | [
"py_telegram_bot_api",
"python",
"telebot"
] | stackoverflow_0074274576_py_telegram_bot_api_python_telebot.txt |
Q:
Django: ImportError: cannot import name 'User'
I'm new to django and I'm facing some difficulties in creating a user from the AbstractBaseUser model. Now I'm starting wondering if my user model is not being build in the right way. This is my User model
from django.db import models
from django.contrib.auth.models i... | Django: ImportError: cannot import name 'User' | I'm new to django and I'm facing some difficulties in creating a user from the AbstractBaseUser model. Now I'm starting wondering if my user model is not being build in the right way. This is my User model
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
class User(AbstractBaseUser)... | [
"You didn't import from right package.\nUse:\nfrom user_profile.models import User\n\n",
"I solved this by importing\nfrom django.contrib.auth.models import User\n\n",
"I solved this by importing\nfrom django.contrib.auth.models import AbstractBaseUser\n\nCheck the right spell of the package\n",
"I had a make... | [
8,
8,
0,
0
] | [
"Make sure you import User and not user\n'' from django.contrib.auth.models import User\n"
] | [
-2
] | [
"django",
"django_models",
"django_users",
"model",
"python"
] | stackoverflow_0039559635_django_django_models_django_users_model_python.txt |
Q:
How can I retun a list of absolute paths?
The following code returns a list of file-names in a given directory:
def get_files(dir_path_str):
onlyfiles = next(os.walk(dir_path_str))[2]
return onlyfiles
How can I make it return absolute file paths with minimal modification and preserve the behavior of the f... | How can I retun a list of absolute paths? | The following code returns a list of file-names in a given directory:
def get_files(dir_path_str):
onlyfiles = next(os.walk(dir_path_str))[2]
return onlyfiles
How can I make it return absolute file paths with minimal modification and preserve the behavior of the function?
| [
"The easiest way to do this is with pathlib\nMake your input directory a Path object, use .iterdir() to get all the files/folders inside that directory, use .absolute() to make them absolute and .is_file() to check that they're files:\nfrom pathlib import Path\n\n\ndef get_files(inp_path_str):\n directory = Path... | [
1,
0
] | [] | [] | [
"absolute_path",
"python"
] | stackoverflow_0074279679_absolute_path_python.txt |
Q:
Add formatting, surrounding box to Altair vertical line tooltip label?
I am new to Altair, and am attempting to plot a monthly time-series variable, and have a vertical line tooltip display the date and corresponding y-value.
The code I have (warning, probably a bit ugly) gets me most of the way there:
import alta... | Add formatting, surrounding box to Altair vertical line tooltip label? | I am new to Altair, and am attempting to plot a monthly time-series variable, and have a vertical line tooltip display the date and corresponding y-value.
The code I have (warning, probably a bit ugly) gets me most of the way there:
import altair as alt
import datetime as dt
import numpy as np
import pandas as pd
# cr... | [
"Update: I figured both out.\nThe solutions to both 1 and 2 are in the code below.\nFor 1: instead of trying to add a box around the text manually, I instead added tooltips to the selectors object and dropped the text_x and text_y entirely.\nFor 2: I used transform_calculate to create new fields for x_label and y_l... | [
0
] | [] | [] | [
"altair",
"python"
] | stackoverflow_0074278407_altair_python.txt |
Q:
Center number of pages Discord Bot
I'm currently having a problem to center the number of pages between the navigation buttons
he ends up being like this
But whenever I change pages, It goes to the direction I click the navigation button
I use the pycord lib for the navigation buttons, the code looks like this:
... | Center number of pages Discord Bot | I'm currently having a problem to center the number of pages between the navigation buttons
he ends up being like this
But whenever I change pages, It goes to the direction I click the navigation button
I use the pycord lib for the navigation buttons, the code looks like this:
@commands.slash_command()
async ... | [
"I arrived at the solution, instantiating the buttons directly in the function\n@commands.slash_command()\nasync def help(self, ctx: discord.ApplicationContext):\n \"\"\"\n Mostrar a pΓ‘gina de ajuda.\n \"\"\"\n paginator = pages.Paginator(\n pages=self.pages,\n use_default_buttons=False,\n... | [
0
] | [] | [] | [
"button",
"pycord",
"python",
"uibutton"
] | stackoverflow_0074278917_button_pycord_python_uibutton.txt |
Q:
Python firestore collection query order by document_id
We can order a collection query by documentId in javascript,
.orderBy(firebase.firestore.FieldPath.documentId())
How is this done in python, cannot seem to find a similar object (field_path.document_id) in the python SDK reference.
A:
It can be done this way... | Python firestore collection query order by document_id | We can order a collection query by documentId in javascript,
.orderBy(firebase.firestore.FieldPath.documentId())
How is this done in python, cannot seem to find a similar object (field_path.document_id) in the python SDK reference.
| [
"It can be done this way\nfrom google.cloud.firestore_v1.field_path import FieldPath\n.order_by(FieldPath.document_id())\n\nIt is found in the code here\n"
] | [
0
] | [] | [] | [
"google_cloud_firestore",
"python"
] | stackoverflow_0074278645_google_cloud_firestore_python.txt |
Q:
Can anyone pls help me how to resolve this issue?
classes.py
from flask_wtf import Form
from wtforms import TextField, IntegerField, SubmitField
class CreateTask(Form):
title = TextField('Task Title')
shortdesc = TextField('Short Description')
priority = IntegerField('Priority')
create = SubmitFie... | Can anyone pls help me how to resolve this issue? | classes.py
from flask_wtf import Form
from wtforms import TextField, IntegerField, SubmitField
class CreateTask(Form):
title = TextField('Task Title')
shortdesc = TextField('Short Description')
priority = IntegerField('Priority')
create = SubmitField('Create')
class DeleteTask(Form):
key = TextFie... | [
"The error is coming from your run.py file, but the main issue is from classes.py.\nIn the first line of your main() function:\ndef main():\n\n # create form\n\n cform = CreateTask(prefix='cform')\n\nYou create a variable cform from the CreateTask object.\nThen, further in your main() function, you have this ... | [
1
] | [] | [] | [
"flask",
"flask_wtforms",
"python"
] | stackoverflow_0074279666_flask_flask_wtforms_python.txt |
Q:
how to merge two dictonaries in python with union of values if the keys do exist in both
how to merge two dictonaries in python with union of values if the keys do exist in both. Each dictionary has values as list.
I have three dictionaries:
d1 = {"KEY1": [1, 2, 3]}
d2 = {"KEY1": [2, 3, 4]}
d3 = {"KEY2": ... | how to merge two dictonaries in python with union of values if the keys do exist in both | how to merge two dictonaries in python with union of values if the keys do exist in both. Each dictionary has values as list.
I have three dictionaries:
d1 = {"KEY1": [1, 2, 3]}
d2 = {"KEY1": [2, 3, 4]}
d3 = {"KEY2": [1, 2, 3]}
how could I merge then so if:
merge(d1,d2) --> {"KEY1": [1, 2, 3, 4]}
merge(... | [
"define a merge function (here as lambda function):\nmerge = lambda x,y: {v:list(set(x.get(v, []) + y.get(v, []))) for v in x.keys() | y.keys()}\n\noutput:\n merge(d1,d3)\n {'KEY2': [1, 2, 3], 'KEY1': [1, 2, 3]}\n\n merge(d1,d2)\n {'KEY1': [1, 2, 3, 4]}\n\n",
"For such a specific kind of dictionary me... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074279798_python.txt |
Q:
How to find data-id content in webscraping (python)
Im trying to extract all Product Names, Product Codes, Prices, and Specs from a website, but there's no classes I can use to dig deeper into the html tree, so I have to use data-type and data-id, and all the tr and td info inside of it. However, if I now search f... | How to find data-id content in webscraping (python) | Im trying to extract all Product Names, Product Codes, Prices, and Specs from a website, but there's no classes I can use to dig deeper into the html tree, so I have to use data-type and data-id, and all the tr and td info inside of it. However, if I now search for data-id, it only shows me the names, but not actually ... | [
".find_all('tr', attrs=('data-id')) is not the correct way to use find; if you want rows that have a data-id attribute, you can use select with CSS selectors, and if you want value of the data-id attribute, you can use .get:\nfor row in WholeDoc.select('div[data-type=\"Photobook\"] tbody tr[data-id]'): \n print(... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074261711_beautifulsoup_python_python_requests_web_scraping.txt |
Q:
Django Unit Testing - How to load once a DB for multiple tests.py files?
I have a folder named "test" in my Django project.
Inside this folder I have multiple files named "test_xyz.py".
My goal: loading the DB only once and share it across all test*.py files.
What I currently do:
class OneTestCase(APITestCase):
... | Django Unit Testing - How to load once a DB for multiple tests.py files? | I have a folder named "test" in my Django project.
Inside this folder I have multiple files named "test_xyz.py".
My goal: loading the DB only once and share it across all test*.py files.
What I currently do:
class OneTestCase(APITestCase):
@classmethod
def setUpTestData(cls):
'''
Init database
... | [
"A pytest fixture with scope=\"session\"?\n"
] | [
0
] | [] | [] | [
"django",
"pytest",
"pytest_django",
"python"
] | stackoverflow_0074279660_django_pytest_pytest_django_python.txt |
Q:
Excel File not generating in python selenium
I m trying to Scrap bunch of url .Output is right excel file not generating to store all the scrape data
for i in range(len(df)):
driver.get(f"{df.loc[i, 'URL']}")
f_name = driver.find_elements(by=By.XPATH, value="//a[@href]")
for elem in f_name:
url... | Excel File not generating in python selenium | I m trying to Scrap bunch of url .Output is right excel file not generating to store all the scrape data
for i in range(len(df)):
driver.get(f"{df.loc[i, 'URL']}")
f_name = driver.find_elements(by=By.XPATH, value="//a[@href]")
for elem in f_name:
urls = print(elem.get_attribute("href"))
df.loc[i,ur... | [] | [] | [
"import xlsxwriter\nworkbook = xlsxwriter.Workbook('hello.xlsx')\nworksheet = workbook.add_worksheet()\nworksheet.write('A1', 'Hello world')\nworkbook.close()\n"
] | [
-1
] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074274708_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
pydantic Settings: TypeError: cannot pickle '_thread.lock' object
I am facing an issue with pydantic.BaseSettings and prometheus_client.Summary.
The snippet below throws an Exception when trying to be executed:
from prometheus_client import Summary
from pydantic import BaseSettings
class Settings(BaseSettings):
... | pydantic Settings: TypeError: cannot pickle '_thread.lock' object | I am facing an issue with pydantic.BaseSettings and prometheus_client.Summary.
The snippet below throws an Exception when trying to be executed:
from prometheus_client import Summary
from pydantic import BaseSettings
class Settings(BaseSettings):
app_name: str = 'any_app_name'
any_boolean: bool = False
any... | [
"Looks like you want to create Custom Data Type\n",
"Easiest for me was to use an automatically excluded attribute:\nfrom typing import ClassVar\nclass Settings(BaseSettings):\n any_summary: ClassVar[Summary] = Summary('my_summary','My Summary')\n\n"
] | [
2,
0
] | [] | [] | [
"prometheus",
"pydantic",
"python"
] | stackoverflow_0066419620_prometheus_pydantic_python.txt |
Q:
How to pass authentication pop up in selenium?
I'm trying to load a web page that requires authentication using Python script with Selenium.
options = webdriver.ChromeOptions()
prefs = {'download.default_directory': r"download.default_directory=" + download_folder,
"download.prompt_for_download": False, '... | How to pass authentication pop up in selenium? | I'm trying to load a web page that requires authentication using Python script with Selenium.
options = webdriver.ChromeOptions()
prefs = {'download.default_directory': r"download.default_directory=" + download_folder,
"download.prompt_for_download": False, 'profile.default_content_setting_values.automatic_dow... | [
"After many hours wasted, it turns out that it is a known issue with chromedriver:\nhttps://bugs.chromium.org/p/chromedriver/issues/detail?id=1917&q=authentication&colspec=ID%20Status%20Pri%20Owner%20Summary\nI switched to using Firefox instead and it works from there.\n",
"In case you mean html basic authentific... | [
1,
1,
1,
0,
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0049292221_python_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
How to create a ts object with a specific chosen time in python?
I am trying to translate this code from R to python, but I cannot create the time objects I want to work with. Here is an example of what I did in R.
## Subset to one observation per week on Mondays at 8:00pm for 2007, 2008 and 2009
house070809weekl... | How to create a ts object with a specific chosen time in python? | I am trying to translate this code from R to python, but I cannot create the time objects I want to work with. Here is an example of what I did in R.
## Subset to one observation per week on Mondays at 8:00pm for 2007, 2008 and 2009
house070809weekly <- filter(MultiYear1, weekdays == "monday" & hour == 20 & minute == ... | [
"I need to make a forecast of three ts.\nH1W = data[(data['Weekday'] == 0)]\nH1WH = H1W[(H1W['Hour'] == 20)]\nH1WHM = H1WH[(H1WH['Minute'] == 1)]\n\nbyMonth1 = H1WHM.resample(\"M\").fillna(method= \"pad\")\nbyWeek1 = H1WHM.resample(\"W\").fillna(method= \"pad\")\nbyDay1 = H1WHM.resample(\"D\").fillna(method= \"pad\... | [
0
] | [] | [] | [
"datetime",
"python",
"r",
"time_series"
] | stackoverflow_0074277341_datetime_python_r_time_series.txt |
Q:
How to keep original index of a DataFrame after groupby 2 columns?
Is there any way I can retain the original index of my large dataframe after I perform a groupby? The reason I need to this is because I need to do an inner merge back to my original df (after my groupby) to regain those lost columns. And the index... | How to keep original index of a DataFrame after groupby 2 columns? | Is there any way I can retain the original index of my large dataframe after I perform a groupby? The reason I need to this is because I need to do an inner merge back to my original df (after my groupby) to regain those lost columns. And the index value is the only 'unique' column to perform the merge back into. Does ... | [
"You can elevate your index to a column via reset_index. Then aggregate your index to a tuple via agg, together with your count aggregation.\nBelow is a minimal example.\nimport pandas as pd, numpy as np\n\ndf = pd.DataFrame(np.random.randint(0, 4, (50, 5)),\n index=np.random.randint(0, 4, 50))\n\n... | [
18,
12,
0,
0
] | [] | [] | [
"dataframe",
"indexing",
"pandas",
"pandas_groupby",
"python"
] | stackoverflow_0049216357_dataframe_indexing_pandas_pandas_groupby_python.txt |
Q:
NameError: name 'anekdot' is not defined. Did you mean: 'anekdots'?
Good afternoon, trying to output a random list item from this code
global anekdot
def randanek():
anekdot = random.choice(anekdots)
randanek()
textaneka = anekdot
but for some reason the program doesn't see my variable and i see this error... | NameError: name 'anekdot' is not defined. Did you mean: 'anekdots'? | Good afternoon, trying to output a random list item from this code
global anekdot
def randanek():
anekdot = random.choice(anekdots)
randanek()
textaneka = anekdot
but for some reason the program doesn't see my variable and i see this error
Traceback (most recent call last):
File "", line 44, in <module>
... | [
"The reason you're getting an error is of how python is interpreting your code. You say you want anekdot to be a global, but don't give it a value. You think the compiler will figure out that anekdot is assigned a value within the function, but it is hitting an error before that because it sees texaneka = anekdot a... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074279885_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.