content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to get number of specific words from a string
Please I need to write a program in python3 that return the number of word in a string that has letter that repeat only n time successive.
Expl if n=2 "first loop ddd" the code must return 1 [Loop contains 2 o] [d is repeated 3 times in ddd so it wan't be counted]... | How to get number of specific words from a string | Please I need to write a program in python3 that return the number of word in a string that has letter that repeat only n time successive.
Expl if n=2 "first loop ddd" the code must return 1 [Loop contains 2 o] [d is repeated 3 times in ddd so it wan't be counted].
I wrote a long code but i did not get a result.
... | [
"You could create a words list by splitting the sentence by whitespace, and then searching each word (after removing any punctuation etc..) for occurrences of repeated letters. I've kept a set of words found, so that the same word isn't counted multiple times if it has repeats of more than one letter, but if you d... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074539415_python.txt |
Q:
Flask WTForms how to prevent duplicate form submission
I'm new to Flask.
Forms.py:
class NoteForm(FlaskForm):
note = fields.TextAreaField("Note")
add_note = fields.SubmitField("Add Note")
router.py:
add_note_form = forms.NoteForm()
template:
<div class="form-group">
{{ add_note_form.add_note}}
</div>
... | Flask WTForms how to prevent duplicate form submission | I'm new to Flask.
Forms.py:
class NoteForm(FlaskForm):
note = fields.TextAreaField("Note")
add_note = fields.SubmitField("Add Note")
router.py:
add_note_form = forms.NoteForm()
template:
<div class="form-group">
{{ add_note_form.add_note}}
</div>
Now if I click the add note button multiple times in a very ... | [
"One way to do this is to disable the submit button after form is submitted\nonClick=\"this.form.submit(); this.disabled=true; this.value='Saving…'; \"\n\nAnother way would be to give you record an id and check for duplicate in the backend.\n"
] | [
1
] | [] | [] | [
"flask",
"flask_wtforms",
"python",
"python_3.x",
"wtforms"
] | stackoverflow_0074539465_flask_flask_wtforms_python_python_3.x_wtforms.txt |
Q:
Create new column using multiple groupby's in Pandas
I have a dataset where I would like to:
group by location and box and take a count of the box
Data
ID location type box status
aa NY no box55 hey
aa NY no box55 hi
aa NY yes ... | Create new column using multiple groupby's in Pandas | I have a dataset where I would like to:
group by location and box and take a count of the box
Data
ID location type box status
aa NY no box55 hey
aa NY no box55 hi
aa NY yes box66 hello
aa NY yes box66 ... | [
"Try:\ndf = df.groupby([\"location\", \"box\"], as_index=False).agg(\n **{\"box count\": (\"box\", \"size\")}\n)\nprint(df)\n\nPrints:\n location box box count\n0 CA box11 4\n1 CA box86 3\n2 CA box99 3\n3 NY box55 2\n4 NY box66 ... | [
1
] | [] | [] | [
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074540009_group_by_numpy_pandas_python.txt |
Q:
How to calculate 1st and 3rd quartiles?
I have DataFrame:
time_diff avg_trips
0 0.450000 1.0
1 0.483333 1.0
2 0.500000 1.0
3 0.516667 1.0
4 0.533333 2.0
I want to get 1st quartile, 3rd quartile and median for the column time_diff. To obtain median, I use np.median(df["time_diff"].va... | How to calculate 1st and 3rd quartiles? | I have DataFrame:
time_diff avg_trips
0 0.450000 1.0
1 0.483333 1.0
2 0.500000 1.0
3 0.516667 1.0
4 0.533333 2.0
I want to get 1st quartile, 3rd quartile and median for the column time_diff. To obtain median, I use np.median(df["time_diff"].values).
How can I calculate quartiles?
| [
"By using pandas:\ndf.time_diff.quantile([0.25,0.5,0.75])\n\n\nOut[793]: \n0.25 0.483333\n0.50 0.500000\n0.75 0.516667\nName: time_diff, dtype: float64\n\n",
"You can use np.percentile to calculate quartiles (including the median):\n>>> np.percentile(df.time_diff, 25) # Q1\n0.48333300000000001\n\n>>> np... | [
91,
82,
26,
26,
13,
6,
4,
4,
2,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"python_2.7"
] | stackoverflow_0045926230_numpy_pandas_python_python_2.7.txt |
Q:
ValueError: invalid literal for int() with base 10: 'quit'
I keep getting this errror message:
ValueError: invalid literal for int() with base 10
Here is my code snippet
age = {}
while age != 'quit':
age = input('what is your age?')
age = int(age)
if age >= 18:
print("You're old en... | ValueError: invalid literal for int() with base 10: 'quit' | I keep getting this errror message:
ValueError: invalid literal for int() with base 10
Here is my code snippet
age = {}
while age != 'quit':
age = input('what is your age?')
age = int(age)
if age >= 18:
print("You're old enough to vote.")
else:
print("You're not old enou... | [
"One of the approach (may not be optimal) is to break the loop once you encounter ValueError. Logic can be similar to this\nwhile age != 'quit':\n age = input()\n try:\n age = int(age)\n if age >= 18:\n print(\"You're old enough to vote.\")\n else:\n print(\"You're n... | [
0
] | [] | [] | [
"python",
"user_input"
] | stackoverflow_0074540042_python_user_input.txt |
Q:
How to check whether tensor values in a different tensor pytorch?
I have 2 tensors of unequal size
a = torch.tensor([[1,2], [2,3],[3,4]])
b = torch.tensor([[4,5],[2,3]])
I want a boolean array of whether each value exists in the other tensor without iterating. something like
a in b
and the result should be
[Fals... | How to check whether tensor values in a different tensor pytorch? | I have 2 tensors of unequal size
a = torch.tensor([[1,2], [2,3],[3,4]])
b = torch.tensor([[4,5],[2,3]])
I want a boolean array of whether each value exists in the other tensor without iterating. something like
a in b
and the result should be
[False, True, False]
as only the value of a[1] is in b
| [
"I think it's impossible without using at least some type of iteration. The most succinct way I can manage is using list comprehension:\n[True if i in b else False for i in a]\n\nChecks for elements in b that are in a and gives [False, True, False]. Can also be reversed to get elements a in b [False, True].\n",
"... | [
2,
2,
1,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"pytorch",
"torch"
] | stackoverflow_0066036375_python_python_3.x_pytorch_torch.txt |
Q:
NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:access.pyodbc
I want to import a dataframe into a access database but I got an error NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:access.pyodbc
from sqlalchemy import create_engine
import urllib
import pyodbc
conec = (r"Driver={Microsoft Acces... | NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:access.pyodbc | I want to import a dataframe into a access database but I got an error NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:access.pyodbc
from sqlalchemy import create_engine
import urllib
import pyodbc
conec = (r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
r"DBQ=C:\Users\redim\Desktop\18_marzo\L... | [
"For some reason this only works in Jupyter notebooks, not in PyCharm which I was having the same problems for quite some time in both until I upgraded SQLalchemy\nI use conda install with most of my libraries:\nconda update sqlalchemy\n\nBut if you are using pip, then below is command:\npip install --upgrade sqlal... | [
0
] | [] | [] | [
"python",
"sqlalchemy",
"sqlalchemy_access"
] | stackoverflow_0066858168_python_sqlalchemy_sqlalchemy_access.txt |
Q:
Error passing wav file to IPython.display
I am new to Python but I am studying it as programming language for DSP. I recorded a wav file, and have been trying to play it back using IPython.display.Audio:
import IPython.display
from scipy.io import wavfile
rate, s = wavfile.read('h.wav')
IPython.display.Audio(s, r... | Error passing wav file to IPython.display | I am new to Python but I am studying it as programming language for DSP. I recorded a wav file, and have been trying to play it back using IPython.display.Audio:
import IPython.display
from scipy.io import wavfile
rate, s = wavfile.read('h.wav')
IPython.display.Audio(s, rate=rate)
But this gives the following error:
... | [
"That's not a very useful error message, it took a bit of debugging to figure out what was going on! It is caused by the \"shape\" of the matrix returned from wavfile being the wrong way around.\nThe docs for IPython.display.Audio say it expects a:\n\nNumpy 2d array containing waveforms for each channel. Shape=(NC... | [
8,
0
] | [] | [] | [
"jupyter_notebook",
"python",
"scipy",
"wav"
] | stackoverflow_0057137050_jupyter_notebook_python_scipy_wav.txt |
Q:
Tricky Multiple Groupings and Transformations using Pandas
I have a dataset where I would like to:
group by location and box and take distinct count of the box
create column headers with the values in the status column and include its count based on the box
Data
ID location type box status
a... | Tricky Multiple Groupings and Transformations using Pandas | I have a dataset where I would like to:
group by location and box and take distinct count of the box
create column headers with the values in the status column and include its count based on the box
Data
ID location type box status
aa NY no box55 hey
aa NY no ... | [
"Try making two dataframes: first with .groupby(), second with pd.crosstab. Then just pd.concat them:\ndf1 = df.groupby([\"location\", \"box\"]).agg(**{\"box count\": (\"box\", \"size\")})\ndf2 = pd.crosstab([df[\"location\"], df[\"box\"]], df[\"status\"])\n\ndf_out = pd.concat([df1, df2], axis=1)\nprint(df_out.res... | [
1
] | [] | [] | [
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074539860_group_by_numpy_pandas_python.txt |
Q:
Sort short_names in reverse alphabetic order
I dont understand what I am doing wrong:
Sort short_names in reverse alphabetic order. Sample output from given program:
['Tod', 'Sam', 'Joe', 'Jan', 'Ann']
My code:
short_names = ['Jan', 'Sam', 'Ann', 'Joe', 'Tod']
short_names.sort()
print(short_names)
A:
sort f... | Sort short_names in reverse alphabetic order | I dont understand what I am doing wrong:
Sort short_names in reverse alphabetic order. Sample output from given program:
['Tod', 'Sam', 'Joe', 'Jan', 'Ann']
My code:
short_names = ['Jan', 'Sam', 'Ann', 'Joe', 'Tod']
short_names.sort()
print(short_names)
| [
"sort function has a reverse option:\nshort_names.sort(reverse=True)\n\n",
"As always, first have a look at the documentation for list.sort:\n\nsort(*, key=None, reverse=None)\nThis method sorts the list in place, using only < comparisons between items.\nreverse is a boolean value. If set to True, then the list e... | [
1,
0,
0
] | [
"I'm doing this lab right now, and this is what your code should look like for the zybook, based on the methods we have learned.\nuser_input = input()\nshort_names = user_input.split()\nshort_names.sort()\nshort_names.reverse()\nprint(short_names)\n\n"
] | [
-1
] | [
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0045049758_python_python_2.7_python_3.x.txt |
Q:
How can a function access variables that are not defined inside the function?
I recently started studying Python and I came across an example that I did not understand:
def teste():
print(a, b)
a = 5
b = 4
teste() # Outputs '5 4'
What is happening here? Is teste() able to access a and b because those va... | How can a function access variables that are not defined inside the function? | I recently started studying Python and I came across an example that I did not understand:
def teste():
print(a, b)
a = 5
b = 4
teste() # Outputs '5 4'
What is happening here? Is teste() able to access a and b because those variables are globals?
| [
"Short answer, yes. a and b are global variables in that sense.\nLong answer, as long as you keep the variable names on the right side of an assignment or just pass them to a function within a function, they'll act as global variables.\nWhat's happening is that Python will first look in the local scope of that func... | [
1
] | [] | [] | [
"global_variables",
"python",
"python_3.x",
"scope"
] | stackoverflow_0074540137_global_variables_python_python_3.x_scope.txt |
Q:
Change Typo Column Values with Right Word based on Columns in Other Dataframe
I have two dataframe, the first one is location ,
location = pd.DataFrame({'city': ['RIYADH','SEOUL','BUSAN','TOKYO','OSAKA'],
'country': ['Saudi Arabia','South Korea','South Korea','Japan','Japan']})
the other one i... | Change Typo Column Values with Right Word based on Columns in Other Dataframe | I have two dataframe, the first one is location ,
location = pd.DataFrame({'city': ['RIYADH','SEOUL','BUSAN','TOKYO','OSAKA'],
'country': ['Saudi Arabia','South Korea','South Korea','Japan','Japan']})
the other one is customer,
customer = pd.DataFrame({'id': [1001,2002,3003,4004,5005,6006,7007,8008... | [
"A possible solution, based on RapidFuzz:\nfrom rapidfuzz import process\n\nout = (customer.assign(\n aux = customer['city']\n .map(lambda x: \n process.extractOne(x, location['city']+'*'+location['country'])[0])))\n\nout[['aux1', 'aux2']] = out['aux'].str.split(r'\\*', expand=True)\nout['city'] = out.... | [
2
] | [] | [] | [
"dataframe",
"fuzzy_comparison",
"pandas",
"python",
"similarity"
] | stackoverflow_0074540077_dataframe_fuzzy_comparison_pandas_python_similarity.txt |
Q:
Python asyncio listener loop doesn't run using idle main loop
I have a "listener" loop that constantly watches for items to process from an asyncio queue. This loop runs in a part of the application that is not using asyncio, so I've been trying to set up a passive asyncio main loop that the listener can be transf... | Python asyncio listener loop doesn't run using idle main loop | I have a "listener" loop that constantly watches for items to process from an asyncio queue. This loop runs in a part of the application that is not using asyncio, so I've been trying to set up a passive asyncio main loop that the listener can be transferred to as needed. The listener is started and stopped as needed p... | [
"You never start the newly created loop. I adjusted to call main (although here it does nothing I assume the original code is more complex). All changes are in start_IO. Tested with python 3.10 (I think there was some change in the past regarding threads and async)\nimport asyncio\nimport threading\nfrom asyncio.qu... | [
2
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074538362_python_python_asyncio.txt |
Q:
Time zone offset change history dataset by date and city parameter
I am searching for Rest API that will allow me to get all Time zone offset changes of city between dates.
Is there any API like this (not free) ?
For example:
Get --> Headers:
City
From date
To date
Rome
2001-01-01 00:00:01.000
2020-01-01 00:00:0... | Time zone offset change history dataset by date and city parameter | I am searching for Rest API that will allow me to get all Time zone offset changes of city between dates.
Is there any API like this (not free) ?
For example:
Get --> Headers:
City
From date
To date
Rome
2001-01-01 00:00:01.000
2020-01-01 00:00:01.000
Response:
Timestamp
Time zone offset
2001-01-01 ... | [
"Azure Maps API.\nOne call for Search --> Get Search Address- returns Coordinates (latitude and longitude).\nAnother call for Timezone --> Get Timezone By Coordinates - returns times zones (historical, current, future).\n"
] | [
0
] | [] | [] | [
"api",
"python",
"rest"
] | stackoverflow_0074376595_api_python_rest.txt |
Q:
How to get absolute path of root directory from anywhere within the directory in python
Let's say I have the following directory
model_folder
|
|
------- model_modules
| |
| ---- __init__.py
| |
| ---- foo.py
| |
| ---- bar.py
|
|
------- researc... | How to get absolute path of root directory from anywhere within the directory in python | Let's say I have the following directory
model_folder
|
|
------- model_modules
| |
| ---- __init__.py
| |
| ---- foo.py
| |
| ---- bar.py
|
|
------- research
| |
| ----- training.ipynb
| |
| ----- eda.ipyn... | [
"sys.path[0] contain your root directory (the directory where the program is located). You can use that to add your sub-directories.\nimport sys\nsys.path.append( sys.path[0] + \"/model_modules\")\nimport foo\n\nand for cases where foo.py may exist elsewhere:\nimport sys\nsys.path.insert( 1, sys.path[0] + \"/model_... | [
0
] | [] | [] | [
"directory",
"python"
] | stackoverflow_0074539909_directory_python.txt |
Q:
Speed of loading files with asyncio
I'm writing a piece of code that needs to compare a python set to many other sets and retain the names of the files which have a minimum intersection length. I currently have a synchronous version but was wondering if it could benefit from async/await. I wanted to start by compa... | Speed of loading files with asyncio | I'm writing a piece of code that needs to compare a python set to many other sets and retain the names of the files which have a minimum intersection length. I currently have a synchronous version but was wondering if it could benefit from async/await. I wanted to start by comparing the loading of sets. I wrote a simpl... | [
"Asyncio doesn’t help in this case because your workload is basically disk-IO bound and CPU bound.\nCPU bound workload cannot be sped up by Asyncio.\nDisk-IO bound workload could benefit from async operation if but the disk operation is very slow and your program can do other things during that time. This may not ... | [
1,
0
] | [] | [] | [
"async_await",
"asynchronous",
"python",
"python_asyncio"
] | stackoverflow_0074537864_async_await_asynchronous_python_python_asyncio.txt |
Q:
How does async.queue synchronization works?
I have to build an application where my computer receives information from different serial ports.
My plan is to use one thread per port to read the data and another common to all to parse and save. Communication between threads is done through a async.queue but I have a... | How does async.queue synchronization works? | I have to build an application where my computer receives information from different serial ports.
My plan is to use one thread per port to read the data and another common to all to parse and save. Communication between threads is done through a async.queue but I have a problem with my implementation.
I have made a si... | [
"Your basic idea of using one thread per serial port is a possible approach. However, in your test program, the main thread does nothing but write the data to a file. It does not share execution with a second Task, so there is no need for asyncio. If your real program is indeed that simple, you don't need asynci... | [
0,
0
] | [] | [] | [
"multithreading",
"python",
"python_asyncio"
] | stackoverflow_0074508546_multithreading_python_python_asyncio.txt |
Q:
unexpected output from the init value and from the main function
I am trying to do the binary tree inversion in Python. I did in the following way.
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
print(self.left)
print(self.right)
... | unexpected output from the init value and from the main function | I am trying to do the binary tree inversion in Python. I did in the following way.
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
print(self.left)
print(self.right)
def PrintTree ( self ) :
if self.left :
self.l... | [
"add this to PrintTree function:\nprint (self.data) #Missing\n\nAnd also remove prints on init\n"
] | [
0
] | [] | [] | [
"algorithm",
"data_structures",
"init",
"python"
] | stackoverflow_0074540317_algorithm_data_structures_init_python.txt |
Q:
Overwrite a value in a pandas dataframe column based on a calculation function applied to it
From the following DataFrame:
worktime = 1440
person = [11,22,33,44,55]
begin_date = '2019-10-01'
shift= [1,2,3,1,2]
pause = [90,0,85,70,0]
occu = [60,0,40,20,0]
time_u = [50,40,80,20,0]
time_a = [84.5,0.0,10.5,47.7,0.0]
t... | Overwrite a value in a pandas dataframe column based on a calculation function applied to it | From the following DataFrame:
worktime = 1440
person = [11,22,33,44,55]
begin_date = '2019-10-01'
shift= [1,2,3,1,2]
pause = [90,0,85,70,0]
occu = [60,0,40,20,0]
time_u = [50,40,80,20,0]
time_a = [84.5,0.0,10.5,47.7,0.0]
time_p = 0
time_q = [35.9,69.1,0.0,0.0,84.4]
df = pd.DataFrame({'date':pd.date_range(begin_date, p... | [
"You can simply apply the relationships you have supplied sequentially. Or are you looking for something else? By the way, you put an extra space at the end of 'time_p'\ndf['time_u'] = df['worktime'] - df['pause'] - df['occu'] - df['time_u']\ndf['time_a'] = df['time_u'] - df['time_a']\ndf['time_p'] = df['time_a'] -... | [
0
] | [] | [] | [
"dataframe",
"function",
"overwrite",
"pandas",
"python"
] | stackoverflow_0074540220_dataframe_function_overwrite_pandas_python.txt |
Q:
Getting "IndexError: list index out of range" and not sure why
Beginner python programmer here. I understand what an "IndexError: list index out of range" error means, but in my case I'm not sure why I'm getting it. I have a script which goes to this webpage (https://www.basketball-reference.com/players/v/valanjo0... | Getting "IndexError: list index out of range" and not sure why | Beginner python programmer here. I understand what an "IndexError: list index out of range" error means, but in my case I'm not sure why I'm getting it. I have a script which goes to this webpage (https://www.basketball-reference.com/players/v/valanjo01/gamelog/2022) and in the "2021-22 Regular Season" table, goes thro... | [
"The append() method appends/add an element to the end of the list.\nIn your code you can remove the index before the append method.\n\n\nteam_game_number_element = []\nteam_game_number = []\n\nfor index in range(82):\n y = str(index + 1)\n team_game_number_element.append('some text')\n team_game_number.ap... | [
1
] | [] | [] | [
"indexing",
"python",
"selenium"
] | stackoverflow_0074540368_indexing_python_selenium.txt |
Q:
Splitting a string into multiple string using re.split()
I have a string that I am trying to split into 2 strings using Regex to form a list. Below is the string:
Input: 'TLSD_IBPDEq.'
Output: ['', '']
Expected Output: ['TLSD_IBPD', 'Eq.']
Below is what I have tried but is not working
pattern = r"\S*Eq[\.,]"
l = r... | Splitting a string into multiple string using re.split() | I have a string that I am trying to split into 2 strings using Regex to form a list. Below is the string:
Input: 'TLSD_IBPDEq.'
Output: ['', '']
Expected Output: ['TLSD_IBPD', 'Eq.']
Below is what I have tried but is not working
pattern = r"\S*Eq[\.,]"
l = re.split(pattern,"TLSD_IBPDEq.")
print(l) => ['', '']
| [
"If I understand, then you can apply the answer from this question. If you need to use a regex to solve this, then use a capture group and remove the last (empty) element, like this:\npattern = r\"(Eq\\.)$\"\nl = re.split(pattern, \"TLSD_IBPDEq.\")[:-1]\nprint(l) # => ['TLSD_IBPD', 'Eq.']\n\n",
"You can do it wi... | [
1,
1
] | [] | [] | [
"python",
"regex",
"split"
] | stackoverflow_0074540445_python_regex_split.txt |
Q:
How to have a new list for every input
I am trying to edit the input entered for each day. I have created an input_sales_day function that contains a number of products to enter for a day, an input_sales function that takes the number of products and days as parameters, where I think the problem lies, and a final ... | How to have a new list for every input | I am trying to edit the input entered for each day. I have created an input_sales_day function that contains a number of products to enter for a day, an input_sales function that takes the number of products and days as parameters, where I think the problem lies, and a final function that just prints. I've tried using ... | [
"All you need to do is make p a local variable of the input_sales_day function. If you do this, then p will be reset on every invokation. Like this:\ndef input_sales_day(nbp):\n p = []\n for i in range(nbp):\n np = input(\"Product Name: \")\n qv = input(\"quantity sold : \")\n p.append('{... | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0074540525_python.txt |
Q:
Unable to sleep execution within an api subscription callback
I am making an api subscription to fetch real time live data from one of the api providers,
However i only want to pull the data every few seconds (eg 5 seconds).
I am using the below code snippet, however am unable to implement the sleep or delay effec... | Unable to sleep execution within an api subscription callback | I am making an api subscription to fetch real time live data from one of the api providers,
However i only want to pull the data every few seconds (eg 5 seconds).
I am using the below code snippet, however am unable to implement the sleep or delay effectively.
Can you please help to guide why the api is not adhering to... | [
"Assuming api_ABC_connection is calling callback function asynchronously, you can try and add the lock. Try this, it may work:\nlock = multiprocessing.Lock()\n\ndef on_ticks(ticks):\n print('###################')\n print(datetime.now())\n lock.acquire()\n time.sleep(5)\n lock.release()\n fetch_tim... | [
1
] | [] | [] | [
"api",
"callback",
"pandas",
"python",
"sleep"
] | stackoverflow_0074442477_api_callback_pandas_python_sleep.txt |
Q:
Asyncio: cancelling tasks and starting new ones when a signal flag is raised
My program is supposed to read data forever from provider classes stored in PROVIDERS, defined in the config. Every second, it should check whether the config has changed and if so, stop all tasks, reload the config and and create new tas... | Asyncio: cancelling tasks and starting new ones when a signal flag is raised | My program is supposed to read data forever from provider classes stored in PROVIDERS, defined in the config. Every second, it should check whether the config has changed and if so, stop all tasks, reload the config and and create new tasks.
The below code raises CancelledError because I'm cancelling my tasks. Should I... | [
"If you are on Python 3.11, your pattern maps directly to using asyncio.TaskGroup, the \"successor\" to asyncio.gather, which makes use of the new \"exception Groups\". By default, if any task in the group raises an exception, all tasks in the group are cancelled:\nI played around this snippet in the ipython conso... | [
2,
0
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074517438_python_python_asyncio.txt |
Q:
concurrent.futures captures all exceptions
I have coded myself into an interesting situation that I don't know how to get out of.
I have a number of functions I am running in a number of parallel threads, but when an exception is thrown within one of the threads the code continues on with no notification
with ... | concurrent.futures captures all exceptions | I have coded myself into an interesting situation that I don't know how to get out of.
I have a number of functions I am running in a number of parallel threads, but when an exception is thrown within one of the threads the code continues on with no notification
with concurrent.futures.ThreadPoolExecutor() as execu... | [
"Exceptions are captured by the future object:\n for future in concurrent.futures.as_completed(futureHost):\n if future.exception() is not None:\n print(f'ERROR: {future}: {future.exception()}')\n continue\n\n"
] | [
0
] | [] | [] | [
"concurrent.futures",
"error_handling",
"exception",
"python"
] | stackoverflow_0074188604_concurrent.futures_error_handling_exception_python.txt |
Q:
How to measure distance between camera and an object?
I'm an OpenCV beginner, just wondering which way would be the best to measure
the distance between the camera to an object in a given video.
Every tutorial I encountered before tutor by using camera calibration first and then undistorting the camera lens. But i... | How to measure distance between camera and an object? | I'm an OpenCV beginner, just wondering which way would be the best to measure
the distance between the camera to an object in a given video.
Every tutorial I encountered before tutor by using camera calibration first and then undistorting the camera lens. But in this case I don't use my own camera, so is it necessary f... | [
"Usually, one does measure the distance between a single camera and an object with prior knowledge of the object. It could be the dimensions of a planar pattern or the 3D positions of edges that can easily be detected automatically using image analysis.\nThe computation of the position of the object with respect to... | [
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074097066_opencv_python.txt |
Q:
Exception has occurred: TimeoutError exception: no description
I am specifically using python version 3.10 to run a websocket (or any long asyncio process) for a specified period of time which is covered in the python docs. The .wait_for() method looks like the correct solution.
I run this code (from the docs):
im... | Exception has occurred: TimeoutError exception: no description | I am specifically using python version 3.10 to run a websocket (or any long asyncio process) for a specified period of time which is covered in the python docs. The .wait_for() method looks like the correct solution.
I run this code (from the docs):
import asyncio
async def eternity():
# Sleep for one hour
awa... | [
"You can remove the TimeoutError so it can jump down to the print('timeout') or can use this example to output the error\nexcept Exception as exc:\n print(f'The exception: {exc!r}')\n\n",
"There are a number of TimeoutErrors in Python.\nReplace except TimeoutError with except asyncio.TimeoutError and you’ll be... | [
1,
0
] | [] | [] | [
"python",
"python_asyncio",
"timeout",
"timeouterror",
"websocket"
] | stackoverflow_0074510354_python_python_asyncio_timeout_timeouterror_websocket.txt |
Q:
ERROR: Could not build wheels for spacy, which is required to install pyproject.toml-based projects
Hi Guys, I am trying to install spacy model == 2.3.5 but I am getting this error, please help me!
A:
Try using python 3.6-3.9 instead, where there are binary wheels for pip install to use instead of having to comp... | ERROR: Could not build wheels for spacy, which is required to install pyproject.toml-based projects |
Hi Guys, I am trying to install spacy model == 2.3.5 but I am getting this error, please help me!
| [
"Try using python 3.6-3.9 instead, where there are binary wheels for pip install to use instead of having to compile from source.\n(This is a conflict with python 3.10 and some generated .cpp files in the source package. Python 3.10 wasn't released yet when this version was published.)\n",
"I had the similar erro... | [
4,
1,
0
] | [] | [] | [
"nlp",
"python",
"spacy"
] | stackoverflow_0071512301_nlp_python_spacy.txt |
Q:
Is there a faster optimization algorithm than SLSQP for my problem?
I have a medium sized optimization problem that I have used scipy optimize with the SLSQP method to solve. I am wondering if there is a faster algorithm?
Here is my code:
from scipy.optimize import minimize, Bounds
import pandas as pd
import numpy... | Is there a faster optimization algorithm than SLSQP for my problem? | I have a medium sized optimization problem that I have used scipy optimize with the SLSQP method to solve. I am wondering if there is a faster algorithm?
Here is my code:
from scipy.optimize import minimize, Bounds
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(500,5),columns=['pred','var1','v... | [
"After setting a random seed by np.random.seed(1) at the top of your code snippet in order to reproduce the results, we can time your code snippet:\nIn [15]: def foo1():\n ...: sol = minimize(\n ...: fun=obj,\n ...: x0=df['weights'],\n ...: method='SLSQP',\n ...: b... | [
1
] | [] | [] | [
"optimization",
"python",
"scipy_optimize"
] | stackoverflow_0074540008_optimization_python_scipy_optimize.txt |
Q:
Python - Random.sample from a range with excluded values (array)
I am currently using the random.sample function to extract individuals from a population.
ex:
n = range(1,1501)
result = random.sample(n, 500)
print(result)
in this example I draw 500 persons among 1500. So far, so good..
Now, I want to go further an... | Python - Random.sample from a range with excluded values (array) | I am currently using the random.sample function to extract individuals from a population.
ex:
n = range(1,1501)
result = random.sample(n, 500)
print(result)
in this example I draw 500 persons among 1500. So far, so good..
Now, I want to go further and launch a search with a list of exclude people.
exclude = [122,506,11... | [
"exclude = {122, 506, 1100, 56, 76, 1301}\nresult = random.sample([k for k in range(1, 1501) if k not in exclude], 500)\n\n# check\nassert set(result).isdisjoint(exclude)\n\nMarginally faster (but a bit more convoluted for my taste):\nresult = random.sample(list(set(range(1, 1501)).difference(exclude)), 500)\n\n",
... | [
1,
1
] | [] | [] | [
"python",
"random"
] | stackoverflow_0074540504_python_random.txt |
Q:
How can you retrieve webpages based on URLs and convert each to a beautifulsoup object
So I am scraping a website I was able to get all the information thanks to Andrej Kesely, I was also able to syntheses URLs that downloaded the first 50 pages, however now I want to retrieve the webpages based on the URLs and co... | How can you retrieve webpages based on URLs and convert each to a beautifulsoup object | So I am scraping a website I was able to get all the information thanks to Andrej Kesely, I was also able to syntheses URLs that downloaded the first 50 pages, however now I want to retrieve the webpages based on the URLs and convert them into a beautifulsoup and I also want to retrieve all the information and the URL(... | [
"To iterate over multiple pages you can do:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://jammer.ie/used-cars?page={}&per-page=12\"\n\nall_data = []\n\nfor page in range(1, 3): # <-- increase number of pages here\n soup = BeautifulSoup(requests.get(url.format(page)).t... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074540562_beautifulsoup_python_web_scraping.txt |
Q:
djongo + mongodb, Array Data Insert Problem
I have a problem.
Stack: Django-Rest-Framework + Djongo + Mongodb.
Problem: Insert error array data
//models.py
from django.db import models
from djongo import models as djongoModels
class House(models.Model):
house_id = models.CharField(max_length=256)
class ... | djongo + mongodb, Array Data Insert Problem | I have a problem.
Stack: Django-Rest-Framework + Djongo + Mongodb.
Problem: Insert error array data
//models.py
from django.db import models
from djongo import models as djongoModels
class House(models.Model):
house_id = models.CharField(max_length=256)
class Meta:
abstract = True
class Users(models... | [
"[Self Solved]\nIt's problem with between a model and a value.\n//ArrayField: Only available {key:value} \n//models.py\nclass House(models.Model):\n house_id = models.CharField(max_length=256)\n\nclass Users(models.Model):\n ...\n house = djongoModels.ArrayField(\n model_container=House\n )\n\n//... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"djongo",
"mongodb",
"python"
] | stackoverflow_0074168540_django_django_rest_framework_djongo_mongodb_python.txt |
Q:
Basic Python Issue / removing whitespace
I am struggling in a python undergraduate class that should have had fewer modules: for a grade, I have a code that reads a formatted file and "prints" a table. The problem is, the last entry of the table has a trailing space at the end. My print statement is
for time in mo... | Basic Python Issue / removing whitespace | I am struggling in a python undergraduate class that should have had fewer modules: for a grade, I have a code that reads a formatted file and "prints" a table. The problem is, the last entry of the table has a trailing space at the end. My print statement is
for time in movieTiming[m]:
pr... | [
"Instead of multiple calls to print, create a single space-delimited string with ' '.join and print that.\nprint(' '.join(movieTiming[m]))\n\nAs you've noted, printing a space between list elements is different from printing a space after each element. While you can play around with list indices to figure out whic... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074540601_python.txt |
Q:
Checking if the window is working Python3
How can I make a health check of a window by hwnd? Simply put, I need to handle an error if it happens.
The mistake in question:
I assume this can be done with Win32 libraries, but my searches haven't led to anything.
A:
Use SendMessageTimeout() to send the HWND a benig... | Checking if the window is working Python3 | How can I make a health check of a window by hwnd? Simply put, I need to handle an error if it happens.
The mistake in question:
I assume this can be done with Win32 libraries, but my searches haven't led to anything.
| [
"Use SendMessageTimeout() to send the HWND a benign message, like WM_NULL. You can specify whether the function should fail if a timeout elapses, or even fail immediately if the window's thread is hung (not processing messages).\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"win32gui",
"winapi"
] | stackoverflow_0074538813_python_python_3.x_win32gui_winapi.txt |
Q:
Populating nested dictionary by iterating over dataframe not producing desired result
I have a dataframe with double timestamped data (effective date and termination date), and I want to produce a nested dictionary (and ultimately a new dataframe) for each entity represented in the data that counts the active inst... | Populating nested dictionary by iterating over dataframe not producing desired result | I have a dataframe with double timestamped data (effective date and termination date), and I want to produce a nested dictionary (and ultimately a new dataframe) for each entity represented in the data that counts the active instances of the data over time. For example, if a field becomes active in 1980, I want the val... | [
"I figured it out. My first issue was failing to make copies of the company sub-dictionary for each separate year. For more information on this, see this post\nMy second issues was figuring out how to utilize my previous iteration output values\nfor yr in timeseries:\n if yr == 1969:\n for row in df.value... | [
0
] | [] | [] | [
"dictionary",
"pandas",
"python",
"time_series"
] | stackoverflow_0074539632_dictionary_pandas_python_time_series.txt |
Q:
Signers are being required to sign tabs meant for other recipients
I am integrating docusign into an app using the python SDK with the flow as follows:
1.) generate an envelope with multiple documents each with its own tabs
2.) The envelope has 3 recipients( 2 signers with routing order and 1 cc)
3.) In each docum... | Signers are being required to sign tabs meant for other recipients | I am integrating docusign into an app using the python SDK with the flow as follows:
1.) generate an envelope with multiple documents each with its own tabs
2.) The envelope has 3 recipients( 2 signers with routing order and 1 cc)
3.) In each document there are 2 tabs groups for each signer in the envelope.
4.) Once th... | [
"You use this /222c/ and /333d/ as your anchor strings for both recipients it seems to me.\nThese are strings to be looked up in your document and be used to anchor the tabs, but since you use them for both signers, they'll get the same tabs, twice, once for each.\nYou can either have different strings for differe... | [
1
] | [] | [] | [
"docusignapi",
"python"
] | stackoverflow_0074540588_docusignapi_python.txt |
Q:
ERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based projects
Error while installing manimce, I have been trying to install manimce library on windows subsystem for linux and after running
pip install manimce
Collecting manimce
Downloading manimce-0.1.1.post2-py3-none-any.... | ERROR: Could not build wheels for pycairo, which is required to install pyproject.toml-based projects | Error while installing manimce, I have been trying to install manimce library on windows subsystem for linux and after running
pip install manimce
Collecting manimce
Downloading manimce-0.1.1.post2-py3-none-any.whl (249 kB)
|████████████████████████████████| 249 kB 257 kB/s
Collecting Pillow
Using cached Pillo... | [
"apt-get install sox ffmpeg libcairo2 libcairo2-dev\napt-get install texlive-full\npip3 install manimlib # or pip install manimlib\n\nThen:\npip3 install manimce # or pip install manimce\n\nAnd everything works.\n",
"I had the same error, for a different package however. I solved the issue with:\napt install li... | [
7,
3,
1,
1,
0,
0
] | [] | [] | [
"manim",
"pycairo",
"python",
"ubuntu",
"windows_subsystem_for_linux"
] | stackoverflow_0070508775_manim_pycairo_python_ubuntu_windows_subsystem_for_linux.txt |
Q:
Disable a charfield in DJANGO when I'm creating a new User
I'm trying to do a crud in Django, it's about jefe and encargados. When I am logged in as an administrator, it has to allow me to create a encargados, but not a manager, but if I log in as a manager, it has to allow me to create a new encargados. For the j... | Disable a charfield in DJANGO when I'm creating a new User | I'm trying to do a crud in Django, it's about jefe and encargados. When I am logged in as an administrator, it has to allow me to create a encargados, but not a manager, but if I log in as a manager, it has to allow me to create a new encargados. For the jefe I am using a table called users and for the admin I am using... | [
"In your view, you need to get the user so you can pass it to the form via kwargs. Add the following method to your view\ndef get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs['user'] = self.request.user\n return kwargs\n\nNow in your form you can test against the user when you initiali... | [
1
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0074540370_django_html_python.txt |
Q:
How to assign list of teams to a list of users randomly in python
For example:
Team
User
USA
Mark
England
Sean
India
Sri
assigning users to different teams randomly
A:
You could use shuffle to shuffle a user list;
from random import shuffle
teams = ['USA', 'England', 'India']
users = ['Mark', 'Sean', 'Sri']... | How to assign list of teams to a list of users randomly in python | For example:
Team
User
USA
Mark
England
Sean
India
Sri
assigning users to different teams randomly
| [
"You could use shuffle to shuffle a user list;\nfrom random import shuffle\nteams = ['USA', 'England', 'India']\nusers = ['Mark', 'Sean', 'Sri']\nshuffle(users)\nprint([(t,u) for t,u in zip(teams, users)])\n\nTo assign multiple teams to a player, you can use iter() to ensure there are no duplicates\nfrom random imp... | [
1,
1,
1
] | [] | [] | [
"function",
"numpy",
"pandas",
"python",
"random"
] | stackoverflow_0074540633_function_numpy_pandas_python_random.txt |
Q:
Both codes work(caesar cipher): but one code rearranges the output
Beginner python programmer here. Before I knew about using .index(), i used a work around. Whilst it did work something peculiar happened. The output string was re-arranged and i don't know why.
Here is my code:
alphabet = ['a', 'b', 'c', 'd', 'e',... | Both codes work(caesar cipher): but one code rearranges the output | Beginner python programmer here. Before I knew about using .index(), i used a work around. Whilst it did work something peculiar happened. The output string was re-arranged and i don't know why.
Here is my code:
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', '... | [
"Your first code prints the word with the letters rearranged in alphabetical order (before using the cipher). You go through the alphabet in your enumerate, a-z, and you look for each letter in your word. For example, if your word was 'ba', with a shift of one, it should output 'cb' - but it outputs 'bc'. It is bec... | [
0
] | [] | [] | [
"caesar_cipher",
"python",
"python_3.x"
] | stackoverflow_0074540620_caesar_cipher_python_python_3.x.txt |
Q:
Group and take count by expanding values in column Pandas
I wish to groupby and then create column headers with the values in a specific column and list their counts.
Data
location box type
ny box11 hey
ny box11 hey
ny box13 hello
ny box13 hello
ny ... | Group and take count by expanding values in column Pandas | I wish to groupby and then create column headers with the values in a specific column and list their counts.
Data
location box type
ny box11 hey
ny box11 hey
ny box13 hello
ny box13 hello
ny box13 hello
ca box5 hi
ca box... | [
"No need box\ndf1 = pd.crosstab(df[\"location\"], df[\"type\"])\nOut[271]: \ntype hello hey hi\nlocation \nca 1 0 1\nny 3 2 0\n\n"
] | [
3
] | [] | [] | [
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074540717_group_by_numpy_pandas_python.txt |
Q:
vscode python URLError:
# requirements
import pandas as pd
from urllib.request import Request, urlopen
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
ua = UserAgent()
ua.ie
req = Request(df["URL"][0], headers={"User-Agent" : ua.ie})
html = urlopen(req).read()
soup_tmp = Beautifu... | vscode python URLError: | # requirements
import pandas as pd
from urllib.request import Request, urlopen
from fake_useragent import UserAgent
from bs4 import BeautifulSoup
ua = UserAgent()
ua.ie
req = Request(df["URL"][0], headers={"User-Agent" : ua.ie})
html = urlopen(req).read()
soup_tmp = BeautifulSoup(html, "html.parser")
sou... | [
"Obviously, the problem is df[\"URL\"][0] in the line:\nreq = Request(df[\"URL\"][0], headers={\"User-Agent\" : ua.ie})\n\nAt the same time, you didn't provide the url you used. I used Google to test that it worked well:\nurl='https://www.google.com'\nreq = Request(url, headers={\"User-Agent\" : ua.ie})\n\nYou need... | [
0
] | [] | [] | [
"error_handling",
"python",
"visual_studio_code"
] | stackoverflow_0074529323_error_handling_python_visual_studio_code.txt |
Q:
error: command '/usr/bin/clang' failed with exit code 1
I download a not commonly-used software package in github in Mac M1. I am trying to compile and install myself according to the instruction.
I have encountered the following problem saying "command/usr/bin/clang with exits error 1". I did install xcode in my ... | error: command '/usr/bin/clang' failed with exit code 1 | I download a not commonly-used software package in github in Mac M1. I am trying to compile and install myself according to the instruction.
I have encountered the following problem saying "command/usr/bin/clang with exits error 1". I did install xcode in my mac. Because the built-in gcc version is 4.2, I upgrade the v... | [
"The follow steps worked!\n\nupgrade pip and related components by:\n\npython -m pip install --upgrade pip\npip install –upgrade wheel \npip install –upgrade setuptools\n\n\ninstall openssl\n\nbrew install openssl re2\n\n\nreinstall your package with some environment to be set\n\nLDFLAGS=\"-L$(/opt/homebrew/bin/bre... | [
0
] | [] | [] | [
"clang",
"gcc",
"macos",
"python"
] | stackoverflow_0071671666_clang_gcc_macos_python.txt |
Q:
Remove weights from networkx graph
I have a weighted Networkx graph G. I first want to make some operation on G with weights (which is why I just don't read the input and set weights=None) and then remove them from G afterwards. What is the most straightforward way to make it unweighted?
I could just do:
G = nx.fr... | Remove weights from networkx graph | I have a weighted Networkx graph G. I first want to make some operation on G with weights (which is why I just don't read the input and set weights=None) and then remove them from G afterwards. What is the most straightforward way to make it unweighted?
I could just do:
G = nx.from_scipy_sparse_array(nx.to_scipy_sparse... | [
"It is possible to access the data structure of the networkx graphs directly and remove any unwanted attributes.\nAt the end, what you can do is define a function that loops over the dictionaries and remove the \"weight\" attribute.\ndef drop_weights(G):\n '''Drop the weights from a networkx weighted graph.'''\n... | [
0
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0072045825_networkx_python.txt |
Q:
Pandas - improve performance when grouping and applying custom function
I have a dataframe like this. My data size is approximately over 100,000 rows.
Category
val1
val2
val3
val4
A
1
2
3
4
A
4
3
2
1
B
1
2
3
4
B
3
4
1
2
B
1
5
3
1
I'd like to group with Category column at first, and calculate with my own met... | Pandas - improve performance when grouping and applying custom function | I have a dataframe like this. My data size is approximately over 100,000 rows.
Category
val1
val2
val3
val4
A
1
2
3
4
A
4
3
2
1
B
1
2
3
4
B
3
4
1
2
B
1
5
3
1
I'd like to group with Category column at first, and calculate with my own method in each group.
Custom method returns a float value cal.
The ... | [
"Here are some things you could try:\n\nReduce the number of rows, by removing elements with invalid values, prior to applying the group by (if possible).\nReduce the data frame's memory footprint, by shrinking its columns data types.\nUse numba, to generate an optimized machine code version of my_cal function.\n\n... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074539837_pandas_python.txt |
Q:
Edit attribute in script string with AST
I'm unfamiliar with the AST module and would appreciate any insight. If, for example, I have a string that contains a valid python script such as
import sys #Just any module
class SomeClass:
def __init__(self):
self.x = 10
self.b = 15
def a_func(self... | Edit attribute in script string with AST | I'm unfamiliar with the AST module and would appreciate any insight. If, for example, I have a string that contains a valid python script such as
import sys #Just any module
class SomeClass:
def __init__(self):
self.x = 10
self.b = 15
def a_func(self):
print(self.x)
I would like to be a... | [
"You can start by using ast.dump to get an idea of the AST structure of the code you're dealing with:\nimport ast\n\ncode='self.x = 10'\nprint(ast.dump(ast.parse(code), indent=2))\n\nThis outputs:\nModule(\n body=[\n Assign(\n targets=[\n Attribute(\n value=Name(id='self', ctx=Load()),\n ... | [
1
] | [] | [] | [
"abstract_syntax_tree",
"metaprogramming",
"python"
] | stackoverflow_0074540739_abstract_syntax_tree_metaprogramming_python.txt |
Q:
(Python) How to run tasks concurrently (and independently) without using asyncio gather?
I have a pool of tasks in a list and each of those tasks take a different amount of time to complete. To mimick this I'll use this piece of code:
tasks = [asyncio.create_task(asyncio.sleep(i)) for i in range(10)]
If I use the ... | (Python) How to run tasks concurrently (and independently) without using asyncio gather? | I have a pool of tasks in a list and each of those tasks take a different amount of time to complete. To mimick this I'll use this piece of code:
tasks = [asyncio.create_task(asyncio.sleep(i)) for i in range(10)]
If I use the asyncio gather API like this: await asyncio.gather(*tasks), then this statement blocks the eve... | [
"asyncio.gather() waits for the tasks to finish. If you don’t want to wait, just don’t call asyncio.gather().\nThe tasks will kick off even if you don’t call gather(), as long as your event loop keeps running.\nTo keep an event loop running, call loop.run_forever() as your entry point, or call asyncio.run(coro()) ... | [
1
] | [] | [] | [
"python",
"python_3.x",
"python_asyncio",
"threadpool"
] | stackoverflow_0074477978_python_python_3.x_python_asyncio_threadpool.txt |
Q:
how to print object data with user input
userInput = input("Enter Name: ")
class person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
People = [
person('Josh',23,'Consultant'),
person('Maya',25,'Accountant'),
person('Dan',32,'Social W... | how to print object data with user input | userInput = input("Enter Name: ")
class person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
People = [
person('Josh',23,'Consultant'),
person('Maya',25,'Accountant'),
person('Dan',32,'Social Worker'),
person('Keon',38,'Biomaterials De... | [
"The slow method is to iterate over the list and find a match.\ndef find_person(people, name):\n for person in people:\n if person.name == name:\n return person\n raise ValueError(\"No matching person found\")\n\nThis is O(n) in the size of the list, which will cause problems if your list of... | [
0
] | [] | [] | [
"class",
"input",
"object",
"python",
"python_3.x"
] | stackoverflow_0074540836_class_input_object_python_python_3.x.txt |
Q:
How to merge/concat dataframe and dummies without duplicate columns
I have a dataframe, with pair of columns containing categorical data (they are the same, differing only by the amount of values for their categories); and I've made two sets of dummies for those two columns, viz:
dummies1 = pd.get_dummies(df.loc[d... | How to merge/concat dataframe and dummies without duplicate columns | I have a dataframe, with pair of columns containing categorical data (they are the same, differing only by the amount of values for their categories); and I've made two sets of dummies for those two columns, viz:
dummies1 = pd.get_dummies(df.loc[df['col1'].isin(columns_valuecounts_top3.index)], columns=['col1', 'col2']... | [
"If you want only the dummy value, you can pass only that column into pd.get_dummies.\ndummies1 = pd.get_dummies(df.loc[df['col1'].isin(columns_valuecounts_top3.index), 'col1']) \ndummies2 = pd.get_dummies(df.loc[df['col2'].isin(columns_valuecounts_top3.index), 'col2'])\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"dummy_variable",
"pandas",
"python"
] | stackoverflow_0074540000_dataframe_dummy_variable_pandas_python.txt |
Q:
Whats wrong with this code for checking age?
I want to know if inputed date of birth is over 18 or under.
def is_under_18(birth):
now = date.today()
return (
now.year - birth.year < 18
or now.year - birth.year == 18 and (
now.month < birth.month
or now.month == birth.month and now.day <= b... | Whats wrong with this code for checking age? | I want to know if inputed date of birth is over 18 or under.
def is_under_18(birth):
now = date.today()
return (
now.year - birth.year < 18
or now.year - birth.year == 18 and (
now.month < birth.month
or now.month == birth.month and now.day <= birth.day
)
)
And then:
year = int(input("Year... | [
"Your original code doesn't seem to have a problem with the dates you mention, but does have a bug as Nov 22, 2004 is \"Under 18\" and today's date is Nov 22, 2022 (18th birthday). Use now.day < birth.day instead.\nBut if you compute the birthday required to be 18 by replacing today's year with 18 less, then direc... | [
0
] | [] | [] | [
"date",
"python",
"python_3.x"
] | stackoverflow_0074540811_date_python_python_3.x.txt |
Q:
Issue using GEKKO solve in Python: getting different result using same code in two different .py files
The libraries used are pandas to read an excel file and gekko to solve an equation.
Both .py files use the same code and the same excel file.
The difference between them is one has an extra for cycle to get value... | Issue using GEKKO solve in Python: getting different result using same code in two different .py files | The libraries used are pandas to read an excel file and gekko to solve an equation.
Both .py files use the same code and the same excel file.
The difference between them is one has an extra for cycle to get values from several sheets and the other is only able to read one sheet at a time.
The results they produce from ... | [
"Gekko uses solvers that iterate to find a solution. However, the same outputs can be expected with the same inputs and equations. Here is an example that returns True and True to verify that the solutions are the same.\nfrom gekko import GEKKO\n\nm1 = GEKKO()\nx1,y1 = m1.Array(m1.Var,2)\nm1.Equations([3*x1+2*y1==1... | [
0
] | [] | [] | [
"gekko",
"pandas",
"python"
] | stackoverflow_0074540273_gekko_pandas_python.txt |
Q:
Cannot find the table tag in the website to scrap information using Beautiful soup
I am trying to obtain the values of this columns (Year, Mom Dy, Hr, Mn, Sec) from the following [website https://www.ngdc.noaa.gov/hazel/view/hazards/tsunami/event-data?maxYear=2022&minYear=2010&country=USA] but I am new using Beaut... | Cannot find the table tag in the website to scrap information using Beautiful soup | I am trying to obtain the values of this columns (Year, Mom Dy, Hr, Mn, Sec) from the following [website https://www.ngdc.noaa.gov/hazel/view/hazards/tsunami/event-data?maxYear=2022&minYear=2010&country=USA] but I am new using Beautiful soup and I cannot find the table tag in the inspection to obtain the information.
T... | [
"Data comes from an API you can call. You can optionally create a date index and sort on that as well after generating a DataFrame from the returned json.\nimport requests\nimport pandas as pd\n\ndf = pd.DataFrame(requests.get('https://www.ngdc.noaa.gov/hazel/hazard-service/api/v1/tsunamis/events?++maxYear=2022&min... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_beautifultable",
"web_scraping"
] | stackoverflow_0074540242_beautifulsoup_python_python_beautifultable_web_scraping.txt |
Q:
How to timeout an async test in pytest with fixture?
I am testing an async function that might get deadlocked. I tried to add a fixture to limit the function to only run for 5 seconds before raising a failure, but it hasn't worked so far.
Setup:
pipenv --python==3.6
pipenv install pytest==4.4.1
pipenv install pyte... | How to timeout an async test in pytest with fixture? | I am testing an async function that might get deadlocked. I tried to add a fixture to limit the function to only run for 5 seconds before raising a failure, but it hasn't worked so far.
Setup:
pipenv --python==3.6
pipenv install pytest==4.4.1
pipenv install pytest-asyncio==0.10.0
Code:
import asyncio
import pytest
@p... | [
"Convenient way to limit function (or block of code) with timeout is to use async-timeout module. You can use it inside your test function or, for example, create a decorator. Unlike with fixture it'll allow to specify concrete time for each test:\nimport asyncio\nimport pytest\nfrom async_timeout import timeout\n\... | [
8,
2,
0
] | [] | [] | [
"pytest",
"pytest_asyncio",
"python",
"python_asyncio"
] | stackoverflow_0055684737_pytest_pytest_asyncio_python_python_asyncio.txt |
Q:
Read data from Quip Spreadsheet with Python
I need to make a tool with Python which needs to read data from a given Quip. I have read the Quip Api documentation but I can't find anything code related.
Does anyone have a source of inspiration for this implementation?
I tried 2 different implementation from various ... | Read data from Quip Spreadsheet with Python | I need to make a tool with Python which needs to read data from a given Quip. I have read the Quip Api documentation but I can't find anything code related.
Does anyone have a source of inspiration for this implementation?
I tried 2 different implementation from various sources but they are not working:
1.
import quip
... | [
"In the latest version, Quip has put the thread ID in the url as well\nso for example: https://<your enterprise quip host>/<thread_id>/<your spreadsheet name>\nSo for exporting a spreadsheet to lets say a dataframe following would be helper code\nimport quipclient\nimport pandas as pd\nimport lxml\n\nACCESS_TOKEN =... | [
0
] | [] | [] | [
"python",
"quip",
"spreadsheet",
"thread_id",
"token"
] | stackoverflow_0073449477_python_quip_spreadsheet_thread_id_token.txt |
Q:
populating form with data from session; django
I'm wondering how to fill my form with data that i have stored in my session.
my model:
models.py
class Order(models.Model):
order_by = ForeignKey(User, on_delete=DO_NOTHING)
order_status = ForeignKey(OrderStatus, on_delete=DO_NOTHING)
created = DateTimeFi... | populating form with data from session; django | I'm wondering how to fill my form with data that i have stored in my session.
my model:
models.py
class Order(models.Model):
order_by = ForeignKey(User, on_delete=DO_NOTHING)
order_status = ForeignKey(OrderStatus, on_delete=DO_NOTHING)
created = DateTimeField(default=datetime.now)
address_street = CharF... | [
"To populate a form from multiple data sources, you can simply merge those data sources, and use the new data.\n# request.POST is immutable by default. \n# .copy() will make a new, mutable copy. \ndata = request.POST.copy()\ndata['cart'] = request.sessions.get('cart')\n\nform = AddAdditionalDataForm(data)\n\nTwo mo... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074534204_django_python.txt |
Q:
how to select rows with a certain pattern
I'm stuck in a problem, because I can't find any solution to deal with it, I have the following sample:
data = [['John', 6, 'A'], ['Paul', 6, 'D'],
['Juli', 9, 'D'], ['Geeta', 4, 'A'],
['Jay', 6, 'D'], ['Sara', 6, 'A'],
['Mario', 3, 'D'], ['Peter', ... | how to select rows with a certain pattern | I'm stuck in a problem, because I can't find any solution to deal with it, I have the following sample:
data = [['John', 6, 'A'], ['Paul', 6, 'D'],
['Juli', 9, 'D'], ['Geeta', 4, 'A'],
['Jay', 6, 'D'], ['Sara', 6, 'A'],
['Mario', 3, 'D'], ['Peter', 6, 'A'],
['Jin', 6, 'D'], ['Carl', 6, '... | [
"You need to use:\n# is the row label A?\nm1 = df['Label'].eq('A')\n# id the next row label D?\nm2 = df['Label'].shift(-1).eq('D')\n# create a mask combining both conditions\nmask = m1&m2\n\n# select the matching rows and the next one (boolean OR)\ndf[mask|mask.shift()]\n\noutput:\n Name Number Label\n0 John ... | [
3,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0072435732_pandas_python.txt |
Q:
Garbage collection in python module
I am using a very simple ctypes module:
% cat acme/__init__.py
from acme import lowlevel
and
% cat acme/lowlevel.py
import logging
_lib = cdll.LoadLibrary("libacme.so.0")
def _func(name, restype, argtypes):
func = getattr(_lib, name)
func.restype = restype
func.argt... | Garbage collection in python module | I am using a very simple ctypes module:
% cat acme/__init__.py
from acme import lowlevel
and
% cat acme/lowlevel.py
import logging
_lib = cdll.LoadLibrary("libacme.so.0")
def _func(name, restype, argtypes):
func = getattr(_lib, name)
func.restype = restype
func.argtypes = argtypes
return func
def py_l... | [
"If you don't reassign PY_LOG_FUNC and it doesn't go out of scope it won't change.\nYour fix works.\nHere's an alternative. Decorate the Python function with the C callback signature. the decorator is the same as coding py_log_func = LOGFUNC(py_log_func) so it redefines the Python function name as the C callback ... | [
1
] | [] | [] | [
"callback",
"ctypes",
"python"
] | stackoverflow_0074517129_callback_ctypes_python.txt |
Q:
Vscode: always running the same python file when pressing the run button
By default the run button always runs the file you're currently viewing, and it's annoying because most of the time I don't want that: I'll be editing another file and then want to run my main.py file, so instead I have to go in the main file... | Vscode: always running the same python file when pressing the run button | By default the run button always runs the file you're currently viewing, and it's annoying because most of the time I don't want that: I'll be editing another file and then want to run my main.py file, so instead I have to go in the main file and then execute it. How can I change this?
I tried looking online but couldn... | [
"Create a launch.json file in the Run and Debug panel, and then replace the configuration \"program\": \"${file}\", with \"program\": \"./main.py\",.\n\nFile structure\npytest11\n|-.venv\n|-.vscode\n| |-launch.json\n|-demo.py\n|-main.py\n\nlaunch.json\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n ... | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074534084_python_visual_studio_code.txt |
Q:
Function equivalent of Excel's SUMIFS()
I have a sales table with columns item, week, and sales. I wanted to create a week to date sales column (wtd sales) that is a weekly roll-up of sales per item.
I have no idea how to create this in Python.
I'm stuck at groupby(), which probably is not the answer. Can anyone h... | Function equivalent of Excel's SUMIFS() | I have a sales table with columns item, week, and sales. I wanted to create a week to date sales column (wtd sales) that is a weekly roll-up of sales per item.
I have no idea how to create this in Python.
I'm stuck at groupby(), which probably is not the answer. Can anyone help?
output_df['wtd sales'] = input_df.group... | [
"As I stated in my comment, you are looking for cumsum():\nimport pandas as pd\n\ndf = pd.DataFrame({\n 'items': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],\n 'weeks': [1, 2, 3, 4, 1, 2, 3, 4],\n 'sales': [100, 101, 102, 130, 10, 11, 12, 13]\n})\n\ndf.groupby(['items'])['sales'].cumsum()\n\nWhich results in... | [
0
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0074540921_excel_python.txt |
Q:
my flowaverage function wont produce an output
Part 3 – Create the Functions to Analyse a Packet
the flowaverage function wont produce an output please help - Python
.
For you to know if a packet is involved in malicious activity or not you must first identify characteristics of malicious traffic and then find a w... | my flowaverage function wont produce an output | Part 3 – Create the Functions to Analyse a Packet
the flowaverage function wont produce an output please help - Python
.
For you to know if a packet is involved in malicious activity or not you must first identify characteristics of malicious traffic and then find a way to represent this in python. For this assignment ... | [
"It looks to me like you are returning early from your for loop, instead of iterating over all the packets. To get the average of the packet lengths, you could do something like this:\ndef flowAverage(pkt_list):\n payloads = []\n large_packets = []\n for pkt in pkt_list:\n payloads.append(getPayload... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074540972_python.txt |
Q:
Selenium. NoSuchElementException
can someone be able to understand what the problem of this code is?I understand that the question is not new, but what I found just didn't help me, but maybe I was looking badly
wd = webdriver.Chrome('chromedriver',options=chrome_options)
wd.get('https://www.uniprot.org/uniprot... | Selenium. NoSuchElementException | can someone be able to understand what the problem of this code is?I understand that the question is not new, but what I found just didn't help me, but maybe I was looking badly
wd = webdriver.Chrome('chromedriver',options=chrome_options)
wd.get('https://www.uniprot.org/uniprotkb/Q14050/entry')
sleep(15)
Mo... | [
"I am assuming you are trying the get the value '63,616', for that you can use any one of the below locators:\nCSS_SELECTOR:\n driver.find_element(By.CSS_SELECTOR, \".sequence-container li:nth-of-type(2) .decorated-list-item__content\").text\n\nXPATH:\ndriver.find_element(By.XPATH, \".//section[@class='sequence-con... | [
0
] | [] | [] | [
"html",
"html_parsing",
"python",
"selenium"
] | stackoverflow_0074538790_html_html_parsing_python_selenium.txt |
Q:
Condense dataset pandas
I wish to condense my dataset. Essentially it is a groupby.
Data
id box status
aa box11 hey
aa box11 hey
aa box11 hey
aa box11 hey
aa box5 hello
aa box5 hello
aa box5 hello
aa box5 hello
aa box5 hello
bb box8 no
bb box8 no
Desired
id box st... | Condense dataset pandas | I wish to condense my dataset. Essentially it is a groupby.
Data
id box status
aa box11 hey
aa box11 hey
aa box11 hey
aa box11 hey
aa box5 hello
aa box5 hello
aa box5 hello
aa box5 hello
aa box5 hello
bb box8 no
bb box8 no
Desired
id box status
aa box11 hey
aa box5... | [
"DataFrame.drop_duplicates()\nIf you want to be careful and exclude \"id\" you can use the subset keyword:\ndf1 = df.drop_duplicates(subset = ['box', 'status'])\n\nEDIT:\nTo clarify, drop_duplicates() will only drop rows if the full row is duplicated. Subset just tells it which rows to consider. If you had a row w... | [
1
] | [] | [] | [
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074541010_group_by_numpy_pandas_python.txt |
Q:
double quoted elements in csv cant read with pandas
I have an input file where every value is stored as a string.
It is inside a csv file with each entry inside double quotes.
Example file:
"column1","column2", "column3", "column4", "column5", "column6"
"AM", "07", "1", "SD", "SD", "CR"
"AM", "08", "1,2,3", "PR,SD... | double quoted elements in csv cant read with pandas | I have an input file where every value is stored as a string.
It is inside a csv file with each entry inside double quotes.
Example file:
"column1","column2", "column3", "column4", "column5", "column6"
"AM", "07", "1", "SD", "SD", "CR"
"AM", "08", "1,2,3", "PR,SD,SD", "PR,SD,SD", "PR,SD,SD"
"AM", "01", "2", "SD", "SD",... | [
"This will work. It falls back to the python parser (as you have non-regular separators, e.g. they are comma and sometimes space). If you only have commas it would use the c-parser and be much faster.\nIn [1]: import csv\n\nIn [2]: !cat test.csv\n\"column1\",\"column2\", \"column3\", \"column4\", \"column5\", \"col... | [
27,
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0026595819_csv_pandas_python.txt |
Q:
WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages)
Whenever I install a pip library in Python, I get a series of warnings. For example :
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages)
WARN... | WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages) | Whenever I install a pip library in Python, I get a series of warnings. For example :
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages)
WARNING... | [
"the warning below:\n\ncan fix as follows.\ngo to the lib\\site-packages folder, then look for folders starting with ~ like what you see in the picture below\n\nand mentioned in that warning, then remove them\nthis can be fixed this warning and no longer appears\n",
"I solved this error by heading over to...\n[ S... | [
29,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0070998452_pip_python.txt |
Q:
how to fix rows getting "None" when using .apply function in pandas dataframe?
Im working on a large dataset of 7GB were i need to use BERT AI algorithm for text classification,
i used a random dataset i found on kaggle as an alternative example to minimise the process time and to apply a function i created (for f... | how to fix rows getting "None" when using .apply function in pandas dataframe? | Im working on a large dataset of 7GB were i need to use BERT AI algorithm for text classification,
i used a random dataset i found on kaggle as an alternative example to minimise the process time and to apply a function i created (for future use on the original dataset) to clean the text by removing punctuations and le... | [
"Usually this happens when one forgets to add a return statement to their apply function, which in this case is your clean_text.\nAs a side-note, you can simply do .apply(clean_text) without the lambda function.\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"series",
"string"
] | stackoverflow_0074540423_dataframe_pandas_python_series_string.txt |
Q:
SQLAlchemy doesn't correctly create in-memory database
Making an API using FastAPI and SQLAlchemy I'm experiencing strange behaviour when database (SQLite) is in-memory which doesn't occur when stored as file.
Model:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, St... | SQLAlchemy doesn't correctly create in-memory database | Making an API using FastAPI and SQLAlchemy I'm experiencing strange behaviour when database (SQLite) is in-memory which doesn't occur when stored as file.
Model:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class Thing(Base):
__ta... | [
"The docs explain this in the following https://docs.sqlalchemy.org/en/14/dialects/sqlite.html#using-a-memory-database-in-multiple-threads\n\nTo use a :memory: database in a multithreaded scenario, the same connection object must be shared among threads, since the database exists only within the scope of that conne... | [
2
] | [] | [] | [
"fastapi",
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0074536228_fastapi_python_sqlalchemy_sqlite.txt |
Q:
Check if module exists, if not install it
I want to check if a module exists, if it doesn't I want to install it.
How should I do this?
So far I have this code which correctly prints f if the module doesn't exist.
try:
import keyring
except ImportError:
print 'f'
A:
import pip
def import_or_install(pack... | Check if module exists, if not install it | I want to check if a module exists, if it doesn't I want to install it.
How should I do this?
So far I have this code which correctly prints f if the module doesn't exist.
try:
import keyring
except ImportError:
print 'f'
| [
"import pip\n\ndef import_or_install(package):\n try:\n __import__(package)\n except ImportError:\n pip.main(['install', package]) \n\nThis code simply attempt to import a package, where package is of type str, and if it is unable to, calls pip and attempt to install it from there.\n",
"... | [
47,
20,
11,
9,
2,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0004527554_import_module_python.txt |
Q:
How to pass a list between two functions?
I have a list that's been modified in one function, and I want it to go to another function in order to be read and modified further.
def get_cards_player():
deck = Deck()
deck.shuffle()
player1 = []
player2 = []
you_won = False #if u won, var is true, ... | How to pass a list between two functions? | I have a list that's been modified in one function, and I want it to go to another function in order to be read and modified further.
def get_cards_player():
deck = Deck()
deck.shuffle()
player1 = []
player2 = []
you_won = False #if u won, var is true, if u lose, var is false
for i in range(5):... | [
"calc_winner should take these lists as parameters. I purposely changed the names to highlight that parameters don't have to have the same name in different functions.\nget_cards_player already creates and returns the lists, so no need to change. Again, to show the different ways you can do this, I'm remembering th... | [
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074541154_list_python.txt |
Q:
Using """ text here"""" isn't printing items on a new line
I've tried to google an answer and I probably just don't know the right thing to look for, so I'm not finding anything. Sorry if this is a newbish question, I'm still fairly new to python. Thank you in advance for your help!
I'm defining a group of charact... | Using """ text here"""" isn't printing items on a new line | I've tried to google an answer and I probably just don't know the right thing to look for, so I'm not finding anything. Sorry if this is a newbish question, I'm still fairly new to python. Thank you in advance for your help!
I'm defining a group of characters forming the words Thank You using """, but when I call it, i... | [
"Try resizing your window.\nwhen the terminal is to small, it will word wrap and have the characters that don't fit on the next line, thus making your output all jumbled and weird.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074540824_python.txt |
Q:
Why does it not need to use the "self" parameter like in Python to define Class in C++?
I am a beginner of C++ with Python background. I have some ambiguity about the process of obtaining instance attributes in Python classes and C++ classes.
As follows, I list two classes that have the same function in Python and... | Why does it not need to use the "self" parameter like in Python to define Class in C++? | I am a beginner of C++ with Python background. I have some ambiguity about the process of obtaining instance attributes in Python classes and C++ classes.
As follows, I list two classes that have the same function in Python and C++ respectively.
My problem is that I am used to using self parameters to distinguish class... | [
"c++ just doesn't write \"self\" explicitly, maybe you need to learn about the keyword \"this\".\n"
] | [
0
] | [] | [] | [
"c++",
"instance_variables",
"oop",
"python",
"self"
] | stackoverflow_0074541205_c++_instance_variables_oop_python_self.txt |
Q:
How would I force user input to be only 1 and 0 in my code
So im trying to force the user to give me purely an input between 1 and 0 and I managed to do so for the most part but it'll only work if all three inputs are above that and my code only gives me and input for a
def AND(a, b):
return a and b
def OR(a,... | How would I force user input to be only 1 and 0 in my code | So im trying to force the user to give me purely an input between 1 and 0 and I managed to do so for the most part but it'll only work if all three inputs are above that and my code only gives me and input for a
def AND(a, b):
return a and b
def OR(a, b):
return a and b
def NOR(a, b):
return a an... | [
"You can use a while loop to keep asking for a valid input until it gets one. Use a for loop to iterate through the names and store input values in a dict to avoid duplicate code:\nvalues = {}\nfor name in 'a', 'b', 'c':\n while True:\n try:\n value = input(f'for {name}, 1 or 0: ')\n ... | [
0,
0,
0,
-3
] | [] | [] | [
"function",
"if_statement",
"input",
"loops",
"python"
] | stackoverflow_0074540891_function_if_statement_input_loops_python.txt |
Q:
calling a method inside a class from a different file
I am trying to implement python classes and objects in my application code. Currently, I have a file that includes all the frequently used functions. I import them in another file.
funcs.py
class name1():
def func1(x):
return x
def func2(y... | calling a method inside a class from a different file | I am trying to implement python classes and objects in my application code. Currently, I have a file that includes all the frequently used functions. I import them in another file.
funcs.py
class name1():
def func1(x):
return x
def func2(y):
return y
....
file1.py
from funcs import fun... | [
"If you want to call a method within a class, first you have to instantiate an object of that class, and then call the method in reference to the object. Below is not an ideal implementation but it's just for example. \nexample.py\nclass MyClass:\n def my_method(self):\n print('something')\n\nobject1 = My... | [
1
] | [] | [] | [
"class",
"methods",
"oop",
"python"
] | stackoverflow_0074541145_class_methods_oop_python.txt |
Q:
Is there a way to specify a range of valid values for a function argument with type hinting in python?
I am a big fan of the type hinting in python, however I am curious if there is a way to specify a valid range of values for a given parameter using type hinting.
What I had in mind is something like
from typing i... | Is there a way to specify a range of valid values for a function argument with type hinting in python? | I am a big fan of the type hinting in python, however I am curious if there is a way to specify a valid range of values for a given parameter using type hinting.
What I had in mind is something like
from typing import *
def function(
number: Union[float, int],
fraction: Float[0.0, 1.0] = 0.5 # give a h... | [
"Python 3.9 introduced typing.Annotated:\nIn [75]: from typing import *\n\nIn [76]: from dataclasses import dataclass\n\nIn [77]: @dataclass\n ...: class ValueRange:\n ...: min: float\n ...: max: float\n ...:\n\nIn [78]: def function(\n ...: number: Union[float, int],\n ...: ... | [
11,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0066451253_python_python_3.x.txt |
Q:
Replicate plotly plot as connected scatter plot
I want to plot a graph for one API, which has different versions in it throughout the years, with commits on the y axis.
My current graph looks something like this:
I want to connect all the scatter plot dots together, with the version name on top of it.
My desired ... | Replicate plotly plot as connected scatter plot | I want to plot a graph for one API, which has different versions in it throughout the years, with commits on the y axis.
My current graph looks something like this:
I want to connect all the scatter plot dots together, with the version name on top of it.
My desired output is something like the line in the graph.
My d... | [
"To realize your question, use the graph object to create a graph with markers, line segments, and annotations. The function required for a line graph is to create a staircase-like graph, so you set the shape of the line. Next, a color scale is applied to the markers of the scatter plot in order to color-code the m... | [
1
] | [] | [] | [
"pandas",
"plotly",
"python"
] | stackoverflow_0074540093_pandas_plotly_python.txt |
Q:
Iterating over a dictionary (follow up to previous question)
Hello i am new to python and i am building a small program that returns false if a string is an isogram (words with no repeating letters consecutive or non-consecutive), and false otherwise.
It also ignores letter case.
So far i have initilised an empty ... | Iterating over a dictionary (follow up to previous question) | Hello i am new to python and i am building a small program that returns false if a string is an isogram (words with no repeating letters consecutive or non-consecutive), and false otherwise.
It also ignores letter case.
So far i have initilised an empty dictionary which will store key value pairs containing the letter ... | [
"First and foremost welcome to Python! I took a look and it seems like the issue is occurring in your second code section, the for-loop over the dictionary values.\nAdding a print statement within the loop may help debugging these sorts of things in the future, i.e.\nfor values in dict:\n print(values)\n if ... | [
1
] | [] | [] | [
"dictionary",
"for_loop",
"if_statement",
"python"
] | stackoverflow_0074471431_dictionary_for_loop_if_statement_python.txt |
Q:
Filling 0 with previous value at index
I have a df:
1 2 3 4 5 6 7 8 9 10
A 10 0 0 15 0 21 45 0 0 7
I am trying fill index A values with the current value if the next value is 0 so that the df would look like this:
1 2 3 4 5 6 7 8 9... | Filling 0 with previous value at index | I have a df:
1 2 3 4 5 6 7 8 9 10
A 10 0 0 15 0 21 45 0 0 7
I am trying fill index A values with the current value if the next value is 0 so that the df would look like this:
1 2 3 4 5 6 7 8 9 10
A 10 10 10 15 15 21 4... | [
"If you want to use your method, you need to work with Series on both sides:\ndf.loc['A'] = df.loc['A'].replace(to_replace=0, method='ffill')\n\nAlternatively, you can mask the 0 with NaNs, and ffill the data on axis=1:\ndf.mask(df.eq(0)).ffill(axis=1)\n\noutput:\n 1 2 3 4 5 6 7 8 ... | [
3,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0070592685_pandas_python.txt |
Q:
prime number machine and if not working tkinter
I am building a machine that can recognize prime numbers individually and show the result to the user,But there is a problem that I showed in the text below
>>12
>>12,is a not prime number
>>7
>>7,is a not prime number
Which prime number and which composite number c... | prime number machine and if not working tkinter | I am building a machine that can recognize prime numbers individually and show the result to the user,But there is a problem that I showed in the text below
>>12
>>12,is a not prime number
>>7
>>7,is a not prime number
Which prime number and which composite number can be converted into composite numbers
my codes:
from... | [
"Try this:\nnum = 3\nflag = False\n\nif num > 1:\n # check for factors\n for i in range(2, num):\n if (num % i) == 0:\n flag = True\n break\n\nif flag:\n print(f\"{num} is not a prime number\")\nelse:\n print(f\"{num} is a prime number\")\n\n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074538009_python_tkinter.txt |
Q:
Install pip for new python version
I installed Python3.11 which is located usr/local/bin/python3, which came without pip. The old Python3.10 was located in usr/bin/python3.
I tried to install pip with sudo apt-install python3-pip, but it seems to be attached to the old Python3.10. If I check pip --version, the out... | Install pip for new python version | I installed Python3.11 which is located usr/local/bin/python3, which came without pip. The old Python3.10 was located in usr/bin/python3.
I tried to install pip with sudo apt-install python3-pip, but it seems to be attached to the old Python3.10. If I check pip --version, the output will be this:
pip 22.0.2 from /usr/l... | [
"Maybe you need pyenv:\n\nWhat pyenv does...\n\nLets you change the global Python version on a per-user basis.\nProvides support for per-project Python versions.\nAllows you to override the Python version with an environment variable.\nSearches for commands from multiple versions of Python at a time. This may be he... | [
1,
0
] | [] | [] | [
"linux",
"pip",
"python",
"ubuntu"
] | stackoverflow_0074541264_linux_pip_python_ubuntu.txt |
Q:
Auto __repr__ method
I want to have simple representation of any class, like { property = value }, is there auto __repr__?
A:
Simplest way:
def __repr__(self):
return str(self.__dict__)
A:
Yes, you can make a class "AutoRepr" and let all other classes extend it:
>>> class AutoRepr(object):
... def __re... | Auto __repr__ method | I want to have simple representation of any class, like { property = value }, is there auto __repr__?
| [
"Simplest way:\ndef __repr__(self):\n return str(self.__dict__)\n\n",
"Yes, you can make a class \"AutoRepr\" and let all other classes extend it:\n>>> class AutoRepr(object):\n... def __repr__(self):\n... items = (\"%s = %r\" % (k, v) for k, v in self.__dict__.items())\n... return \"<%s: {... | [
33,
14,
7,
5,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000750908_python.txt |
Q:
Append column to a dataframe using list comprehension format
I would like to append a column of zeros to a dataframe if the column in question is not already inside the dataframe.
If the dataframe looks like this:
df = pd.DataFrame({'a':[0,1,0], 'c':[1,1,1]})
----------------------------------------------
a ... | Append column to a dataframe using list comprehension format | I would like to append a column of zeros to a dataframe if the column in question is not already inside the dataframe.
If the dataframe looks like this:
df = pd.DataFrame({'a':[0,1,0], 'c':[1,1,1]})
----------------------------------------------
a c
0 0 1
1 1 1
2 0 1
And the complete list of column ... | [
"A list comprehension would produce a list. You don't want a list, you want to add columns to your dataframe. List comprehensions should not be used for side effects, ever.\nYou can however, produce the columns you want to add as a list and use advanced indexing to assign all the columns at the same time:\ndf[[col ... | [
1
] | [] | [] | [
"append",
"dataframe",
"list_comprehension",
"pandas",
"python"
] | stackoverflow_0074541208_append_dataframe_list_comprehension_pandas_python.txt |
Q:
Is there a way in python to detect if a domain does not exist or error?
i want to ask whether or not if it's possible to detect a website that isn't available or a website can't be reach in python?
And there is also a site where it says "The site can't be reached", and when checking the network it says status "(F... | Is there a way in python to detect if a domain does not exist or error? | i want to ask whether or not if it's possible to detect a website that isn't available or a website can't be reach in python?
And there is also a site where it says "The site can't be reached", and when checking the network it says status "(Failed)"
To detect a site i used this code.
import requests
exist=[]
for b ... | [
"In general, if requests.get() throws a ConnectionError exception, then the hostname does not exist, or is unreachable, or is not serving a website.\nOtherwise if requests.get() does not throw an exception (regardless of the specific http return code), then a website does exist at that address.\n",
"import reques... | [
0,
0
] | [] | [] | [
"jupyter_notebook",
"python",
"python_requests"
] | stackoverflow_0074541297_jupyter_notebook_python_python_requests.txt |
Q:
Assign value to column and reset after nth row
I have a pandas dataframe that looks like this...
index
my_column
0
1
2
3
4
5
6
What I need to do is conditionally assign values to 'my_column' depending on the index. The first three rows should have the values 'dog', 'cat', 'bird'. Then, the next three rows... | Assign value to column and reset after nth row | I have a pandas dataframe that looks like this...
index
my_column
0
1
2
3
4
5
6
What I need to do is conditionally assign values to 'my_column' depending on the index. The first three rows should have the values 'dog', 'cat', 'bird'. Then, the next three rows should also have 'dog', 'cat'... | [
"Several problems:\n\nYour if syntax is incorrect, you are missing colons and proper indentation\nYou are breaking out of your loop, terminating it early instead of using an if, elif, else structure\nYou are trying to update your dataframe while iterating over it.\n\nSee this question about why you shouldn't update... | [
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074541372_pandas_python.txt |
Q:
Is there a way to pause my if statement without pausing my entire script in pygame?
Pretty simple, I just want to make a damage system in pygame and i want invincibility frames (aka a delay) so that you don't just die instantly.
For reference here's the if statement
if pygame.Rect.colliderect(player_rect, baddude_... | Is there a way to pause my if statement without pausing my entire script in pygame? | Pretty simple, I just want to make a damage system in pygame and i want invincibility frames (aka a delay) so that you don't just die instantly.
For reference here's the if statement
if pygame.Rect.colliderect(player_rect, baddude_rect):
print('hit')
time.sleep(0.5)
if you need the entire script i will post it... | [
"One way of doing this is to use the millisecond timer provided by pygame.time.get_ticks(). This returns the number of milliseconds since PyGame started. It's handy for doing time calculations.\nSo, reading through the comments, you want the player to be invulnerable for some time (0.5 seconds) after taking a hit... | [
3
] | [] | [] | [
"pause",
"pygame",
"python"
] | stackoverflow_0074540691_pause_pygame_python.txt |
Q:
How to filter row dataframe based on value of another dataframe
How to get filter based data rows from Genre column coming from another dataframe?
I have a movies dataframe as follows:
Movie_Name
Genre
Rating
Halloween
Crime, Horror, Thriller
6.5
Nope
Horror, Mystery, Sci-Fi
6.9
The Midnight Club
Drama, Horror... | How to filter row dataframe based on value of another dataframe | How to get filter based data rows from Genre column coming from another dataframe?
I have a movies dataframe as follows:
Movie_Name
Genre
Rating
Halloween
Crime, Horror, Thriller
6.5
Nope
Horror, Mystery, Sci-Fi
6.9
The Midnight Club
Drama, Horror, Mystery
6.7
The Northman
Action, Adventure, Drama
7.1
P... | [
"try this:\npattern = user['Genre'].str.replace(', ', '|')[0]\nresult = movies.query('Genre.str.contains(@pattern)')\nprint(result)\n\n",
"The example use a for loop to get a list for each user on df2\nimport pandas as pd\ndf=pd.read_csv(\"db1.csv\",header=[0]) # movies\ndf2=pd.read_csv(\"db2.csv\",header=[0]) # ... | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074541262_pandas_python.txt |
Q:
How to convert Clipboard Image BMP to PNG using Pillow package without saving and then loading
I would like to convert an image obtained from the Windows Clipboard to PNG format without having to save and then reload.
As per the code below, I am saving the clipboard image and then reloading it.
Is there a way to ... | How to convert Clipboard Image BMP to PNG using Pillow package without saving and then loading | I would like to convert an image obtained from the Windows Clipboard to PNG format without having to save and then reload.
As per the code below, I am saving the clipboard image and then reloading it.
Is there a way to convert the image to PNG format without those extra steps, such that the
PIL.BmpImagePlugin.DibIma... | [
"As per some help from Seon's comment, this got me on the right track, and fulfilled my requirements. \nAs per Seon:\n\n\"the idea is to save the image to an in-memory BytesIO object, and reload it from there. We're still saving and loading, but not to disk.\"\n\nWhich is exactly what I wanted.\nHere is the code I ... | [
0
] | [] | [] | [
"bmp",
"clipboard",
"png",
"python",
"python_imaging_library"
] | stackoverflow_0074520589_bmp_clipboard_png_python_python_imaging_library.txt |
Q:
Efficient Method to interpolate between 2 pandas date objects?
I am trying to create a table that shows the months that a category of people is available, using an excel table like this one:
Table
I know that I can interpolate using the following method:
import pandas as pd
data = pd.read_csv('Dataset.csv')
final ... | Efficient Method to interpolate between 2 pandas date objects? | I am trying to create a table that shows the months that a category of people is available, using an excel table like this one:
Table
I know that I can interpolate using the following method:
import pandas as pd
data = pd.read_csv('Dataset.csv')
final = pd.DataFrame()
for index,row in data.iterrows():
start = row['... | [
"Take a look at this answer, which seems to be doing the same thing you want: https://stackoverflow.com/a/61930008/11542834\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074541432_pandas_python.txt |
Q:
Combine bar chart and highlight when using Pandas Styler on the same column
Is there a way to combine bar styler and highlight styler in Pandas' DataFrame?
For example, I want to red highlight a NaN value, but if it is not NaN, green bar is shown.
Score
79 --> green bar
84 --> green bar
nan --> red highlight
... | Combine bar chart and highlight when using Pandas Styler on the same column | Is there a way to combine bar styler and highlight styler in Pandas' DataFrame?
For example, I want to red highlight a NaN value, but if it is not NaN, green bar is shown.
Score
79 --> green bar
84 --> green bar
nan --> red highlight
Currently, I can only use highlight_null or apply_map to highlight the NaN valu... | [
"Finally, I can combine it by calling the bar function first, and then followed by applymap\ndef style_zero(v, props=''):\n return props if v == 0 or v == np.nan else None\n\ndf.style.bar(color='#5fba7d').applymap(style_zero, props='background-color:pink;color:red')\n\nMaybe, it will help someone who have the sa... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"pandas_styles",
"python"
] | stackoverflow_0074541618_dataframe_pandas_pandas_styles_python.txt |
Q:
Python printing list of items
Below is my function and output. I want to remove the \n present in the output.
def printInventory():
fh = open("stock.txt","r")
print('Current Inventory')
print('-----------------')
L=fh.readlines()
print("List of all Stock Items")
for i in L:
L=i.s... | Python printing list of items | Below is my function and output. I want to remove the \n present in the output.
def printInventory():
fh = open("stock.txt","r")
print('Current Inventory')
print('-----------------')
L=fh.readlines()
print("List of all Stock Items")
for i in L:
L=i.split(",")
print(L)
CHOICE ... | [
"You can use the .strip() function to remove the new line character\nFor instance:\nout = ['APPLE', '100\\n']\nout[1] = out[1].strip('\\n')\nprint(out) # ['APPLE', '100']\n\nIf you have a list of values, you can just loop through and apply the same logic to each item in the list\n",
"Since you are reading each li... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074531582_python.txt |
Q:
Pandas Multiindex columns slice: use combination of all and pesice selet
Input: hierarchical headered dataframe (multiindex columns).
Ask: select combination of specific column(s) [level0, level1] and broadcast [level0, :]
Example:
import numpy as np
import pandas as pd
index=pd.MultiIndex.from_product([["A", "B"... | Pandas Multiindex columns slice: use combination of all and pesice selet | Input: hierarchical headered dataframe (multiindex columns).
Ask: select combination of specific column(s) [level0, level1] and broadcast [level0, :]
Example:
import numpy as np
import pandas as pd
index=pd.MultiIndex.from_product([["A", "B"], ["x", "y", "z"]])
df = pd.DataFrame(np.random.randn(8,6), columns=index)
T... | [
"Your list comprehension should work:\ncols = [ent for ent in df if ent == ('A','y') or ent[0] == 'B']\ndf.loc[:, cols]\n A B\n y x y z\n0 0.069915 2.563734 1.034784 0.659189\n1 -0.240847 1.924626 1.241827 0.973155\n2 -1.091353 -1.003005 1.648075 -1.162863\n... | [
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074540899_dataframe_numpy_pandas_python.txt |
Q:
AttributeError: 'DatetimeProperties' object has no attribute 'day_name'
I am using pandas day_name() function but its giving attribute error as below:
s = pd.Series(pd.date_range(start='2018-01-01', freq='D', periods=3))
s
0 2018-01-01
1 2018-01-02
2 2018-01-03
dtype: datetime64[ns]
s.dt.day_name()
-----... | AttributeError: 'DatetimeProperties' object has no attribute 'day_name' | I am using pandas day_name() function but its giving attribute error as below:
s = pd.Series(pd.date_range(start='2018-01-01', freq='D', periods=3))
s
0 2018-01-01
1 2018-01-02
2 2018-01-03
dtype: datetime64[ns]
s.dt.day_name()
---------------------------------------------------------------------------
Attrib... | [
"\nWorked for me when I tried in my iPython notebook.\n"
] | [
0
] | [] | [] | [
"datetime",
"pandas",
"python",
"weekday"
] | stackoverflow_0074537161_datetime_pandas_python_weekday.txt |
Q:
PyQt6 how to get black menu bar in Mac OS Dark Mode
I'm developing an app with PyQt6 for Mac OS. When using Dark Mode in the Mac OS settings it applies to all widgets etc in my app however for some reason the menubar does not turn black like it does for most other apps e.g. Google Chrome when running Mac OS in Dar... | PyQt6 how to get black menu bar in Mac OS Dark Mode | I'm developing an app with PyQt6 for Mac OS. When using Dark Mode in the Mac OS settings it applies to all widgets etc in my app however for some reason the menubar does not turn black like it does for most other apps e.g. Google Chrome when running Mac OS in Dark Mode. I've noticed that the Finder app also does not ge... | [
"I solved it. Seems one only gets a black menu bar when running in full screen, which I was not doing.\n"
] | [
0
] | [] | [] | [
"macos",
"pyqt6",
"python",
"qt6"
] | stackoverflow_0074541742_macos_pyqt6_python_qt6.txt |
Q:
How to store user input in a variable in django python
So i want to take the user input and compare it to data present in the sqlite3 db, and if matches I'd like to print that whole row, using django orm.
models.py
from django.db import models
class Inventory(models.Model):
item_bc = models.CharField(max_leng... | How to store user input in a variable in django python | So i want to take the user input and compare it to data present in the sqlite3 db, and if matches I'd like to print that whole row, using django orm.
models.py
from django.db import models
class Inventory(models.Model):
item_bc = models.CharField(max_length=100)
item_details = models.CharField(max_length=100)... | [
"html\n<form action=\"search\" method=\"post\">\n BARCODE: <input type=\"text\" name=\"barcode\">\n <br>\n <br>\n <input type=\"submit\">\n</form>\n\nin view.py you can fetch searched input like this and filter.\ndef search(request):\n search_input = request.POST['barcode']\n data = ModelName.obje... | [
0
] | [] | [] | [
"database",
"django",
"orm",
"python",
"user_input"
] | stackoverflow_0074541719_database_django_orm_python_user_input.txt |
Q:
My ball keeps leaving a trail. I did use blitz and update() but it is not working
.import pygame
from sys import exit
pygame.init()
widthscreen = 1440 #middle 720
heightscreen = 790 #middle 395
w_surface = 800
h_surface = 500
midalignX_lg = (widthscreen-w_surface)/2
midalignY_lg = (heightscreen-h_surface)/2
scr... | My ball keeps leaving a trail. I did use blitz and update() but it is not working | .import pygame
from sys import exit
pygame.init()
widthscreen = 1440 #middle 720
heightscreen = 790 #middle 395
w_surface = 800
h_surface = 500
midalignX_lg = (widthscreen-w_surface)/2
midalignY_lg = (heightscreen-h_surface)/2
screen = pygame.display.set_mode((widthscreen,heightscreen))
pygame.display.set_caption(... | [
"The problem is that you have one surface that you continually blit a yellow square on.\nThe program doesn't know to remove the previously drawn square.\nWhat you can do is just redraw the surface on every loop which is fine given that your program is relatively simple.\nwhile True:\n #elements & update\n\n #... | [
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074541645_pygame_python.txt |
Q:
How to get all pixels in mask in C++
In python, we can use such code to fetch all pixels under mask:
src_img = cv2.imread("xxx")
mask = src_img > 50
fetch = src_img[mask]
what we get is a ndarray including all pixels matching condition mask. How to implement the same function using C++opencv ?
I've found that cop... | How to get all pixels in mask in C++ | In python, we can use such code to fetch all pixels under mask:
src_img = cv2.imread("xxx")
mask = src_img > 50
fetch = src_img[mask]
what we get is a ndarray including all pixels matching condition mask. How to implement the same function using C++opencv ?
I've found that copyTo can select pixels under specified mask... | [
"This is not that straightforward in C++ (as expected). That operation breaks down in further, smaller operations. One way to achieve a std::vector with the same pixel values above your threshold is this, I'm using this test image:\n// Read the input image:\nstd::string imageName = \"D://opencvImages//grayDog.png\"... | [
2,
1
] | [] | [] | [
"c++",
"opencv",
"python"
] | stackoverflow_0074527114_c++_opencv_python.txt |
Q:
Random motion of a person generated with forward and backwards steps with proper iterations
My instructions:
-A person walks a random amount of steps forward, and then a different random number of steps backwards.
-The random steps are anywhere between 2 and 20
-The number of steps forward is always greater than t... | Random motion of a person generated with forward and backwards steps with proper iterations | My instructions:
-A person walks a random amount of steps forward, and then a different random number of steps backwards.
-The random steps are anywhere between 2 and 20
-The number of steps forward is always greater than the number of steps backwards
-That motion of forward / backward random steps repeats itself again... | [
"First of all, why do you need \"infinite\" loop if you know the total number of steps in advance? We can replace it with for loop that runs the exact number of steps.\nWhile inside the loop we want to keep track of several things:\n\ncurrent direction (boolean - true if moving forward)\ntotal displacement (number ... | [
0
] | [] | [] | [
"iteration",
"loops",
"python"
] | stackoverflow_0074540770_iteration_loops_python.txt |
Q:
Time out waiting for launcher to connect in VS code
I did python debugging in VS code.
The following is the launch.json file:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?... | Time out waiting for launcher to connect in VS code | I did python debugging in VS code.
The following is the launch.json file:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations... | [
"Its very simple. Open the launch.json file and add the following into it:\n{\n \"name\": \"Python: Debug Console\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"${file}\",\n \"console\": \"internalConsole\"\n}\n\nThen save and exit it. Whatever you do, DO NOT clear the text already in t... | [
2,
0
] | [] | [] | [
"connection_timeout",
"python",
"vscode_debugger"
] | stackoverflow_0071920044_connection_timeout_python_vscode_debugger.txt |
Q:
Splitting data frame values at a specific word
I have a column of string values:
df[V1]
Could you please speak a little bit more slowly
Could you please speak a little bit more slowly
Could you please speak a little bit more slowly
Could you please speak a little bit more slowly
I tried to use the following code ... | Splitting data frame values at a specific word | I have a column of string values:
df[V1]
Could you please speak a little bit more slowly
Could you please speak a little bit more slowly
Could you please speak a little bit more slowly
Could you please speak a little bit more slowly
I tried to use the following code but it also includes the word I want to split after:... | [
"Using the regex that bobble bubble provided to answer my own question:\nfac_list = []\n\nfor fac in list:\n test_fac = ' '.join(fac)\n y = re.findall(r'^.*\\bspeak\\b|\\S.* ', test_fac)\n fac_list.append(y)\nprint(fac_list)\n\n"
] | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074541542_python_regex.txt |
Q:
if input type by user is not defined how to add
import random
def roll_dice():
dice_drawing = {
1:(
"_________",
"| 1 |",
"| * |",
"----------"
),
2:(
"__________",
"| 2 |",
"| * * ... | if input type by user is not defined how to add | import random
def roll_dice():
dice_drawing = {
1:(
"_________",
"| 1 |",
"| * |",
"----------"
),
2:(
"__________",
"| 2 |",
"| * * |",
"-----------"
),
3:(... | [] | [] | [
"is this you are finding ?\nwhile True:\n roll = input('Roll the dice Yes/No: ')\n if roll.lower() == 'yes':\n \n ##\n ## do your stuff here \n ##\n\n elif roll.lower() =='no':\n break\n else :\n print('enter yes or no') \n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074541867_python.txt |
Q:
ruamel.yaml dump contains "..."
I need to sort the contents of a YAML file, and I'm learning ruamel.yaml to do this.
Given this file example.yml:
---
- job:
name: this is the job name
And this Python program:
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML() # defaults to round-trip
# Read YAML file
... | ruamel.yaml dump contains "..." | I need to sort the contents of a YAML file, and I'm learning ruamel.yaml to do this.
Given this file example.yml:
---
- job:
name: this is the job name
And this Python program:
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML() # defaults to round-trip
# Read YAML file
with open('example.yml', 'r') as f:
... | [
"It's a YAML boundary marker.\nIt's not entirely clear what exactly you are hoping to produce here. If you don't specifically want a YAML document on output, probably just print the thing. I'm guessing you are in the middle of debugging something, because this seems unrelated to the actual task you claim to be work... | [
2
] | [] | [] | [
"python",
"ruamel.yaml",
"yaml"
] | stackoverflow_0074541169_python_ruamel.yaml_yaml.txt |
Q:
compare two dictionaries key by key
I have two python dictionaries like below :
d1 ={'k1':{'a':100}, 'k2':{'b':200}, 'k3':{'b':300}, 'k4':{'c':400}}
d2 ={'k1':{'a':101}, 'k2':{'b':200}, 'k3':{'b':302}, 'k4':{'c':399}}
I want to compare same keys and find out the difference like below:
{'k1':{'diff':1}, 'k2':{'dif... | compare two dictionaries key by key | I have two python dictionaries like below :
d1 ={'k1':{'a':100}, 'k2':{'b':200}, 'k3':{'b':300}, 'k4':{'c':400}}
d2 ={'k1':{'a':101}, 'k2':{'b':200}, 'k3':{'b':302}, 'k4':{'c':399}}
I want to compare same keys and find out the difference like below:
{'k1':{'diff':1}, 'k2':{'diff':0}, 'k3':{'diff':2}, 'k4':{'diff':1}}
... | [
"source:\nd1 = {'k1': {'a': 100}, 'k2': {'b': 200}, 'k3': {'b': 300}, 'k4': {'c': 400}}\nd2 = {'k1': {'a': 101}, 'k2': {'b': 200}, 'k3': {'b': 302}, 'k4': {'c': 399}}\n\nd3 = {}\nfor k in d1:\n d_tmp = {\n \"diff\": abs(list(d1[k].values())[0] - list(d2[k].values())[0])\n }\n d3[k] = d_tmp\n\nprint(... | [
1,
0
] | [] | [] | [
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0074541901_dictionary_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.