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:
Check if combination appears in lists in another dataframe?
I have two large dataframes something like this:
df1:
A time
0 [a, b, c] 122
1 [a, d, e] 45
2 [b, c, e] 64
df2:
Origin Destination
0 a b
1 b c
2 b e
3 d ... | Check if combination appears in lists in another dataframe? | I have two large dataframes something like this:
df1:
A time
0 [a, b, c] 122
1 [a, d, e] 45
2 [b, c, e] 64
df2:
Origin Destination
0 a b
1 b c
2 b e
3 d e
Now I want to compare the two, so that the code chec... | [
"I din't find an elegant way, but you could try something like this :\n# data first\ndf1 = pd.DataFrame({\"A\": [['a', 'b', 'c'], ['a', 'd', 'e'], ['b', 'c', 'e']],\n \"time\": [122, 45, 64]})\ndf2 = pd.DataFrame({\"Origin\": ['a', 'b', 'b', 'd'],\n \"Destination\": ['b', 'c', ... | [
0
] | [] | [] | [
"combinations",
"compare",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074376848_combinations_compare_dataframe_pandas_python.txt |
Q:
Python reload app on Azure App Configuration change
For a Python Flask application I am using envconsul to read config from Consul KV store and inject it as environment variables into the app and watch for updates.
I am planning migration to Azure and considering switching to Azure App Configuration. Since there i... | Python reload app on Azure App Configuration change | For a Python Flask application I am using envconsul to read config from Consul KV store and inject it as environment variables into the app and watch for updates.
I am planning migration to Azure and considering switching to Azure App Configuration. Since there is nothing like envconsul (is there?) I will probably use ... | [
"You are recommended to use the Python Provider library to access Azure App Configuration. The Python provider library uses the Python SDK under the cover but is designed to make it easier to use. Once data is loaded, you can access App Configuration just like a dictionary. It also offers other features like config... | [
0
] | [] | [] | [
"azure",
"azure_app_configuration",
"python"
] | stackoverflow_0074377880_azure_azure_app_configuration_python.txt |
Q:
Multiline f-string in Python """ """ turning other code lines into strings outside of what i am looking for
I am trying to e-mail an attachment and am formatting the content of my e-mail message.
For some reason when i do:
variable = f"""
email content formatting line 1
email content formatting line 2
email conten... | Multiline f-string in Python """ """ turning other code lines into strings outside of what i am looking for | I am trying to e-mail an attachment and am formatting the content of my e-mail message.
For some reason when i do:
variable = f"""
email content formatting line 1
email content formatting line 2
email content formatting line 3
"""
The lines inside the """ """ don't all turn to string...and the rest of my code below bec... | [
"It seems you are trying to use a Python docstring with f-strings. This answer here covers fairly well how \"Docstrings in Python must be regular string literals.\"\nMaking multi-line f-strings is covered here and here, as well as other places.\n"
] | [
1
] | [] | [] | [
"email",
"f_string",
"pandas",
"python"
] | stackoverflow_0074375950_email_f_string_pandas_python.txt |
Q:
How to generate negative random value in python
I am starting to learn python, I tried to generate random values by passing in a negative and positive number. Let say -1, 1.
How should I do this in python?
A:
Use random.uniform(a, b)
>>> import random
>>> random.uniform(-1, 1)
0.4779007751444888
>>> random.uni... | How to generate negative random value in python | I am starting to learn python, I tried to generate random values by passing in a negative and positive number. Let say -1, 1.
How should I do this in python?
| [
"Use random.uniform(a, b)\n>>> import random\n>>> random.uniform(-1, 1)\n0.4779007751444888\n>>> random.uniform(-1, 1)\n-0.10028581710574902\n\n",
"import random\n\ndef r(minimum, maximum):\n return minimum + (maximum - minimum) * random.random()\n\nprint r(-1, 1)\n\nEDIT: @San4ez's random.uniform(-1, 1) is th... | [
31,
5,
4,
4,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0010579518_python_random.txt |
Q:
How to scrap data from post request
I am new here and did't find anything related to post request scrapping.
website- https://intake.steerhealth.io/doctor-search/ae44936d8c986da0787e50a4b4e9ede602
I am tring to scrap all the doctors name and address from this website and don't know how to start.
so far I have trie... | How to scrap data from post request | I am new here and did't find anything related to post request scrapping.
website- https://intake.steerhealth.io/doctor-search/ae44936d8c986da0787e50a4b4e9ede602
I am tring to scrap all the doctors name and address from this website and don't know how to start.
so far I have tried the below tricks but did not receive an... | [
"You're on the right track, you just need to specify the correct headers and payload:\nimport requests\nimport pandas as pd\nfrom tqdm import tqdm ## if using Jupyter notebook, do: from tqdm.notebook import tqdm\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\nheaders = {\... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074377072_beautifulsoup_python_web_scraping.txt |
Q:
Replacing value related to a specific date in df?
I have a df like as follows
Date Flow
0 1981-01-01 103.432860
1 1981-01-02 102.982800
2 1981-01-03 102.121150
3 1981-01-04 100.92662
... ....
xx 2020-12-31 150.123
I need to replace the value of flow for every 1st ... | Replacing value related to a specific date in df? | I have a df like as follows
Date Flow
0 1981-01-01 103.432860
1 1981-01-02 102.982800
2 1981-01-03 102.121150
3 1981-01-04 100.92662
... ....
xx 2020-12-31 150.123
I need to replace the value of flow for every 1st of january as 0.00
df['month'] = df['Date'].dt.month_na... | [
"Use an int rather than a string\nAs MattDMo pointed out, the reason you code is failing is because you are filtering by df[\"dom\"] == \"01\" instead of df[\"dom\"] == 0. Because the dom is expressed in integers rather than strings, it is failing to match any columns.\nA suggestion\nRather than looping through ea... | [
0
] | [] | [] | [
"dataframe",
"datetime",
"python",
"replace",
"time"
] | stackoverflow_0074378348_dataframe_datetime_python_replace_time.txt |
Q:
Correlate two DataFrames based on a key, and a timespan
I work in medicine and I am trying to identify events that happen within a time span after an event. For example if a patient is admitted to the hospital, I want to be able to find out what changes happened within a time span. So say from the time they were ... | Correlate two DataFrames based on a key, and a timespan | I work in medicine and I am trying to identify events that happen within a time span after an event. For example if a patient is admitted to the hospital, I want to be able to find out what changes happened within a time span. So say from the time they were discharged, and before their follow up visit.
I have two Data... | [
"This might be a little faster.\nimport pandas as pd\nimport numpy as np\n\n#loading data\ndf_discharge = pd.DataFrame({'Person': {0: 'P000001', 1: 'P000002', 2: 'P000003', 3: 'P000004'}, 'DischargeDate': {0: '2022-03-18 10:03', 1: '2022-03-18 11:18', 2: '2022-03-18 11:21', 3: '2022-03-19 22:03'}, 'FollowUpVisitDat... | [
0
] | [] | [] | [
"dataframe",
"filtering",
"pandas",
"python",
"timespan"
] | stackoverflow_0074378101_dataframe_filtering_pandas_python_timespan.txt |
Q:
Startin with Python by Tony Gaddis
I have exam in python about some weeks and our professor gave us some tasks to prepare for the exam. One of the tasks I found very difficult and I thought I solved it, but seems like I used the wrong code. I checked youtube for similar codes where I can use the tasks, but couldn'... | Startin with Python by Tony Gaddis | I have exam in python about some weeks and our professor gave us some tasks to prepare for the exam. One of the tasks I found very difficult and I thought I solved it, but seems like I used the wrong code. I checked youtube for similar codes where I can use the tasks, but couldn't fully understand it. I just wonder how... | [
"you can do a for loop that iterates over years and updates the price\nvalue = 1000.0\ndepreciation_list = [0.2, 0.14, 0.13, 0.12, 0.11, 0.10]\n\nprint(f\"Value new: {value}\")\n\nfor year, depreciation in enumerate(depreciation_list):\n new_value = value - value * depreciation \n print(f\"Value after year {y... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074378447_python.txt |
Q:
TypeError when instantiating a deque and then popping
I'm trying to understand why I am getting this TypeError when instantiating my deque. I am solving the "Number of Islands" problem
def bfs(r,c):
q = collections.deque((r,c))
while q:
r_curr, c_curr = q.popleft()
for dr, dc in dirs:
... | TypeError when instantiating a deque and then popping | I'm trying to understand why I am getting this TypeError when instantiating my deque. I am solving the "Number of Islands" problem
def bfs(r,c):
q = collections.deque((r,c))
while q:
r_curr, c_curr = q.popleft()
for dr, dc in dirs:
r_next, c_next = r_curr + dr, c_curr + dc
... | [
"deque takes an iterable, using the elements to form itself. So deque((r, c)) gives you the deque equivalent of (r, c). You want this to be a deque with one item: (r, c), not two items: r and c, so you must use deque(((r, c),)).\n",
"You are getting the error when poplefting from deque not when instantiating it. ... | [
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074378433_python_python_3.x.txt |
Q:
python match case part of a string
I want to know if I can use match cases within Python to match within a string - that is, if a string contains the match case. Example:
mystring = "xmas holidays"
match mystring:
case "holidays":
return true
case "workday":
return false
I can s... | python match case part of a string | I want to know if I can use match cases within Python to match within a string - that is, if a string contains the match case. Example:
mystring = "xmas holidays"
match mystring:
case "holidays":
return true
case "workday":
return false
I can see why it wouldn't, since this could pot... | [
"In match statement, strings are compared using == operator which means that case patterns must be exactly equal to the match expression(mystring in this case) .\nIn order to solve this problem you can create a custom class which inherit from str and overrides the __eq__ method. This method should delegate to __con... | [
1,
0
] | [] | [] | [
"match",
"python",
"python_3.10"
] | stackoverflow_0074378015_match_python_python_3.10.txt |
Q:
Nested validation with the flask-restful RequestParser
Using the flask-restful micro-framework, I am having trouble constructing a RequestParser that will validate nested resources. Assuming an expected JSON resource format of the form:
{
'a_list': [
{
'obj1': 1,
'obj2': 2,
... | Nested validation with the flask-restful RequestParser | Using the flask-restful micro-framework, I am having trouble constructing a RequestParser that will validate nested resources. Assuming an expected JSON resource format of the form:
{
'a_list': [
{
'obj1': 1,
'obj2': 2,
'obj3': 3
},
{
'obj1': ... | [
"I have had success by creating RequestParser instances for the nested objects. Parse the root object first as you normally would, then use the results to feed into the parsers for the nested objects. \nThe trick is the location argument of the add_argument method and the req argument of the parse_args method. They... | [
31,
10,
5,
4,
3,
0,
0,
0
] | [] | [] | [
"flask",
"flask_restful",
"python",
"rest"
] | stackoverflow_0019234737_flask_flask_restful_python_rest.txt |
Q:
How to save screenshot to folder using python?
I am attempting to use a Haar Cascade for object detection, and I need to take screenshots of an object across ~1000 images. Is there a way that I can screenshot a certain part of an image and have it automatically saved to a specific folder using Python?
A:
You can... | How to save screenshot to folder using python? | I am attempting to use a Haar Cascade for object detection, and I need to take screenshots of an object across ~1000 images. Is there a way that I can screenshot a certain part of an image and have it automatically saved to a specific folder using Python?
| [
"You can use pyautogui for that. If you don't have it already installed on your machine, first you'll have to pip install it:\npip install pyautogui\n\nAfter you install pyautogui, you can take screenshots using the code as follows:\n\nimport os\nimport pyautogui\n\nsave_screenshot_folder = './'\n\n# Call pyautogui... | [
1
] | [] | [] | [
"haar_classifier",
"python",
"screen_capture",
"screenshot"
] | stackoverflow_0074378464_haar_classifier_python_screen_capture_screenshot.txt |
Q:
Fast way to remove a few items from a list/queue
This is a follow up to a similar question which asked the best way to write
for item in somelist:
if determine(item):
code_to_remove_item
and it seems the consensus was on something like
somelist[:] = [x for x in somelist if not determine(x)]
However,... | Fast way to remove a few items from a list/queue | This is a follow up to a similar question which asked the best way to write
for item in somelist:
if determine(item):
code_to_remove_item
and it seems the consensus was on something like
somelist[:] = [x for x in somelist if not determine(x)]
However, I think if you are only removing a few items, most of... | [
"The list comprehension is the asymptotically optimal solution:\nsomelist = [x for x in somelist if not determine(x)]\n\nIt only makes one pass over the list, so runs in O(n) time. Since you need to call determine() on each object, any algorithm will require at least O(n) operations. The list comprehension does h... | [
23,
3,
3,
3,
2,
0
] | [
" import collections\n list1=collections.deque(list1)\n for i in list2:\n try:\n list1.remove(i)\n except:\n pass\n\nINSTEAD OF CHECKING IF ELEMENT IS THERE. USING TRY EXCEPT.\nI GUESS THIS FASTER\n"
] | [
-1
] | [
"list",
"optimization",
"python",
"queue",
"time_complexity"
] | stackoverflow_0005745881_list_optimization_python_queue_time_complexity.txt |
Q:
Matplolib and Arcade compute shaders: conflict for the default main context
I'm trying to adapt a big radiative transfert code written in python to use the GPU capacities, as I perform a lot of times the same computation which can be done in parallel. I'm a newbie when it comes to shaders, but found this, which se... | Matplolib and Arcade compute shaders: conflict for the default main context | I'm trying to adapt a big radiative transfert code written in python to use the GPU capacities, as I perform a lot of times the same computation which can be done in parallel. I'm a newbie when it comes to shaders, but found this, which seems to offer what I want. It uses the Arcade python module, and runs fine, as is,... | [
"After a lot of searching around and waiting for a miracle below this post, I think I found a better way of doing what I'm trying to do.\nFirst of all, I found the modernGL python module that seems more adequate for my purpose because it is not a game engine, and focuses on shaders.\nThen, using their compute shade... | [
1
] | [] | [] | [
"arcade",
"compute_shader",
"matplotlib",
"python"
] | stackoverflow_0074317757_arcade_compute_shader_matplotlib_python.txt |
Q:
how i make this function fit for every variable
i got this function but it only fit variable a and i want it fit for every variable without change the function every time.
def count_input_a(numbers_of_letters):
global a
if numbers_of_letters == 0:
a = 13
else:
a = int(a)
I want one fun... | how i make this function fit for every variable | i got this function but it only fit variable a and i want it fit for every variable without change the function every time.
def count_input_a(numbers_of_letters):
global a
if numbers_of_letters == 0:
a = 13
else:
a = int(a)
I want one function that fit for multipale variable.
| [
"This is exactly why using global to return a value is bad -- it ties the function to a particular variable in the caller's namespace, which both makes the function less flexible and creates the possibility of confusing bugs if the function changes the caller's state in unexpected ways.\nInstead, take the value as ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074378630_python.txt |
Q:
Generate Random Coordinates in United States?
I want to generate a random set of latitude and longitude coordinates in the US (including Hawaii and Alaska). I tried using a shapefile from the National Weather Service (https://www.weather.gov/gis/USstates ) but it was generating points in the middle of the ocean. W... | Generate Random Coordinates in United States? | I want to generate a random set of latitude and longitude coordinates in the US (including Hawaii and Alaska). I tried using a shapefile from the National Weather Service (https://www.weather.gov/gis/USstates ) but it was generating points in the middle of the ocean. What is the best way of doing this? I thought about ... | [
"This one requires geopandas but it's a quick and standard solution for sampling within odd shapes (called Monte Carlo Sampling ). Most of the comments below question outline the same concept.\nSolution\n# grab shape within which to sample\nurl = \"https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_nation_20... | [
3
] | [] | [] | [
"coordinates",
"geocoding",
"python",
"shapefile"
] | stackoverflow_0074378025_coordinates_geocoding_python_shapefile.txt |
Q:
from_tensor_slices returns ValueError when passing two numpy arrays as arguments
I've got two numpy arrays: images_ar (data) and categorical_y_ar (labels).
Both consist of dtype('uint8').
Shape of categorical_y_ar is (978, 126).
Shape of images_ar is (978, 224, 224, 3)
When trying to build a dataset with:
dataset... | from_tensor_slices returns ValueError when passing two numpy arrays as arguments | I've got two numpy arrays: images_ar (data) and categorical_y_ar (labels).
Both consist of dtype('uint8').
Shape of categorical_y_ar is (978, 126).
Shape of images_ar is (978, 224, 224, 3)
When trying to build a dataset with:
dataset = tf.data.Dataset.from_tensor_slices(images_ar, categorical_y_ar)
I get the followin... | [
"Try to pass the data as a set or list not as a single entity to the tf.data.Dataset.from_tensor_slice(), as shown below\nx_train = np.random.randn(978, 224, 224, 3)\ny_train = np.random.randint(0,127, size=(978, 127))\n\ndataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n\nprint(next(iter(dataset.ta... | [
0
] | [] | [] | [
"numpy",
"python",
"tensorflow"
] | stackoverflow_0074378577_numpy_python_tensorflow.txt |
Q:
How can I check if a combination of 2 columns appears in lists in a column of another dataframe?
I have two large dataframes something like this:
df1:
A time
0 [a, b, c] 122
1 [a, d, e] 45
2 [b, c, e] 64
df2:
Origin Destination
0 a b
1 b c
2... | How can I check if a combination of 2 columns appears in lists in a column of another dataframe? | I have two large dataframes something like this:
df1:
A time
0 [a, b, c] 122
1 [a, d, e] 45
2 [b, c, e] 64
df2:
Origin Destination
0 a b
1 b c
2 b e
3 d e
Now I want to compare the two, so that the code chec... | [
"ar = []\nfor i, row in df1.iterrows():\n temp = row['A']\n df_temp = (df2.loc[(df2['Origin'].isin(temp)) & (df2['Destination'].isin(temp))]).copy()\n if df_temp.shape[0]>0:\n df_temp['A'] = [row['A']]* df_temp.shape[0]\n df_temp.loc[:,'time'] = [row['time']] * df_temp.shape[0]\n ar.ap... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074377622_dataframe_pandas_python.txt |
Q:
How to join in pandas one to many?
I have two tables. First table is df_1, down below:
job_function
job_area
title
General Management
Human Resources
manager
Learning / Training
IT / Computers / Electronics
personnel
And second table is df_2, down below:
job_function
job_area
id
title
General Management
Huma... | How to join in pandas one to many? | I have two tables. First table is df_1, down below:
job_function
job_area
title
General Management
Human Resources
manager
Learning / Training
IT / Computers / Electronics
personnel
And second table is df_2, down below:
job_function
job_area
id
title
General Management
Human Resources
12312312
man... | [
"I think this is what you want to do (both CSVs I use are identical to what you have in your question):\nimport pandas as pd\n\ndf_1 = pd.read_csv('document1.csv')\ndf_2 = pd.read_csv('document2.csv')\n\nkey_cols = ['job_function', 'job_area', 'title']\nmerged_df = pd.merge(df_1, df_2, how='left', left_on=key_cols... | [
1
] | [] | [] | [
"merge",
"pandas",
"python"
] | stackoverflow_0074378426_merge_pandas_python.txt |
Q:
Pandas - diagonal / shift
Looking for advice please.
In my DF below, I would like to subract the 'difference' column value (red square), from the value in 'trailing sl' column (blue square), but shifted to lag .shift(1).
So the new values would be:
1.08778 - 0.00115
1.08663 - 0.00077
1.08586 - 0.00059
etc
I've tr... | Pandas - diagonal / shift | Looking for advice please.
In my DF below, I would like to subract the 'difference' column value (red square), from the value in 'trailing sl' column (blue square), but shifted to lag .shift(1).
So the new values would be:
1.08778 - 0.00115
1.08663 - 0.00077
1.08586 - 0.00059
etc
I've tried .loc with a .shift value, b... | [
"Use Series.notna:\nm = df['difference'].notna()\ndf.loc[m, 'trailing_sl'] = df.trailing_sl.shift() - df['difference']\n\nOr:\ndf['trailing_sl'] = df.trailing_sl.shift().sub(df['difference']).fillna(df['trailing_sl'])\n\n",
"FWIW, my answer was to make a cumulative sum series of the 'difference' column, and then ... | [
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074371891_pandas_python.txt |
Q:
How to change sawtooth function so it raises from 0.15 to 0.18 instead of -1 to 1
I would like to change the y axis so the wave raises from 0.15 and the peak is at 0.18. Instead of -1 to 1
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 3, 500)
plt.plot(t, signal.sawt... | How to change sawtooth function so it raises from 0.15 to 0.18 instead of -1 to 1 | I would like to change the y axis so the wave raises from 0.15 and the peak is at 0.18. Instead of -1 to 1
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 3, 500)
plt.plot(t, signal.sawtooth(np.pi * 4 * t))
plt.show()
| [
"You could do the following:\nfrom scipy import signal\nimport numpy as np\nimport matplotlib.pyplot as plt\n\na = .15\nb = .18\nt = np.linspace(0, 3, 500)\n\ny = (b+a)/2 + ((b-a)/2) * signal.sawtooth(np.pi * 4 * t)\n\nplt.plot(t, y)\nplt.show()\n\n"
] | [
0
] | [] | [] | [
"python",
"scipy",
"signals"
] | stackoverflow_0074378731_python_scipy_signals.txt |
Q:
Upload local file to Telegram channel
I have a goal to do python script for checking new videos at yt channel then download and upload as audio to tg channel.
I've done first part with checking/downloading/converting (youtube_dl library) and don't see how to do upload part. (there are telegram-upload, python-teleg... | Upload local file to Telegram channel | I have a goal to do python script for checking new videos at yt channel then download and upload as audio to tg channel.
I've done first part with checking/downloading/converting (youtube_dl library) and don't see how to do upload part. (there are telegram-upload, python-telegram-bot, telethon libraries but i don't get... | [
"python-telegram-bot is a library that provides a wrapper for the Telegram Bot API. telethon and telegram-upload instead use the Telegram API (also called MTProto), which controls user (and also Bot accounts).\nIf you want to use a bot to send files to the channel, you'll have to create a bot and make it an admin i... | [
2,
0
] | [] | [] | [
"python",
"telegram",
"telegram_upload",
"upload"
] | stackoverflow_0072675357_python_telegram_telegram_upload_upload.txt |
Q:
Discord bot in python- message not sending
Below is the current code. I'm kinda new to python, but my previous bot with virtually the same code ran perfectly fine, so i don't understand why it's not running. The bot will turn on and show as "online" in Discord, but won't send the message.
import os
import discord... | Discord bot in python- message not sending | Below is the current code. I'm kinda new to python, but my previous bot with virtually the same code ran perfectly fine, so i don't understand why it's not running. The bot will turn on and show as "online" in Discord, but won't send the message.
import os
import discord
from dotenv import load_dotenv
load_dotenv()
T... | [
"on_message here is not decorated with @client.event hence you just define a function and never call it. Add the decorator to make a listener out of it\n@client.event\nasync def on_message(message):\n ...\n\n",
"For your code to work you need to add a decorator to every method.\nimport os\n\nimport discord\nfr... | [
0,
0
] | [] | [] | [
"bots",
"discord",
"python"
] | stackoverflow_0074377975_bots_discord_python.txt |
Q:
Count occurences of values inside a list stored in a dictionary in python
I have a dictionary like this:
dict = {
key1: [1, 5, 65, 78, 4],
key2: [1, 5, 3, 90],
key3: [1, 5, 785, 908, 65, 3]
}
Goal to achieve:
I want to count the occurrences of all the single values inside the lists in my whole dic... | Count occurences of values inside a list stored in a dictionary in python | I have a dictionary like this:
dict = {
key1: [1, 5, 65, 78, 4],
key2: [1, 5, 3, 90],
key3: [1, 5, 785, 908, 65, 3]
}
Goal to achieve:
I want to count the occurrences of all the single values inside the lists in my whole dictionary. Something like this:
count = {
1:3,
5:3,
3:2,
4:1,
... | [
"You can use chain.from_iterable to flatten three lists. You can use collection.Counter to count each value and at the end use the length of dict for computing the percentage.\nfrom itertools import chain\nfrom collections import Counter\n\ndct = {\n 'key1': [1, 5, 65, 78, 4],\n 'key2': [1, 5, 3, 90],\n ... | [
1
] | [] | [] | [
"dictionary",
"key_value",
"list",
"python",
"python_3.x"
] | stackoverflow_0074378823_dictionary_key_value_list_python_python_3.x.txt |
Q:
Optimization: Apply function to all values in a pandas dataframe
I have a data frame of words that looks like this:
I built a function called get_freq(word) that takes a string and returns a list with the word and its frequency in a certain corpus (iWeb Corpus). This corpus is in another data frame called df_freq... | Optimization: Apply function to all values in a pandas dataframe | I have a data frame of words that looks like this:
I built a function called get_freq(word) that takes a string and returns a list with the word and its frequency in a certain corpus (iWeb Corpus). This corpus is in another data frame called df_freq
def get_freq(word):
word_freq=[]
for i in range(len(df_freq)):
... | [
"This is what DataFrame.applymap is for:\ndf = df.applymap(get_freq)\n\nHowever, because this operation probably can't be vectorized, it's going to take some time any way you go about it.\n"
] | [
0
] | [] | [] | [
"optimization",
"pandas",
"python"
] | stackoverflow_0074378846_optimization_pandas_python.txt |
Q:
Activating venv and conda environment at the same time
I am a beginner and was "playing around" with environments a bit. I came across a situation where it seemed that I had two environments activated:
I create a directory, create an environment with venv, activate it and then also conda activate a conda environme... | Activating venv and conda environment at the same time | I am a beginner and was "playing around" with environments a bit. I came across a situation where it seemed that I had two environments activated:
I create a directory, create an environment with venv, activate it and then also conda activate a conda environment which I created before. These are the commands:
mkdir dum... | [
"No, it does not mean they are both activated. Only one can have priority in the PATH, which is what I’d consider the simplest definition of what “activated” means, functionally. The indicators in the PS1 string (i.e., the shell’s prompt string) are not robustly managed. The two environment managers are simply una... | [
4,
0
] | [] | [] | [
"conda",
"environment",
"python",
"python_venv",
"virtual_environment"
] | stackoverflow_0072455487_conda_environment_python_python_venv_virtual_environment.txt |
Q:
How can i merge a bidimensional list using new lines "\n"?
I have the output of a maze solver as a bidimensional array and want to give it the format of a real maze, this is my nested for loop that merges the array:
for renglon in solucion:
solucionCompleta = "\n".join(''.join(l) for l in solucion)
... | How can i merge a bidimensional list using new lines "\n"? | I have the output of a maze solver as a bidimensional array and want to give it the format of a real maze, this is my nested for loop that merges the array:
for renglon in solucion:
solucionCompleta = "\n".join(''.join(l) for l in solucion)
for elemento in renglon:
mediaSalida = ... | [
"Sorry if I misunderstood but if you want to see the maze printing the string give you a visualisation\nprint('#####X#\\n#####*#\\n####**#\\n####*##\\n*****##\\nR######')\n\n\n#####X#\n#####*#\n####**#\n####*##\n*****##\nR######\n\n"
] | [
0
] | [] | [] | [
"arraylist",
"python"
] | stackoverflow_0074378692_arraylist_python.txt |
Q:
How to compare strings within a list-of-lists?
I have the following list
lst =[['A', 'BA'], ['B', 'CB'], ['C', 'AC'], ['D', 'ED']].
I want to check if the first element in a given list is found in the second element of the previous list. If that is the case then take the second element of the list and add it to th... | How to compare strings within a list-of-lists? | I have the following list
lst =[['A', 'BA'], ['B', 'CB'], ['C', 'AC'], ['D', 'ED']].
I want to check if the first element in a given list is found in the second element of the previous list. If that is the case then take the second element of the list and add it to the second element in the previous list.
Eg.
'B' is fo... | [
"It is unclear whether the following code can cover all test cases.\n# -*- coding:utf-8 -*-\nlst = [['A', 'BA'], ['B', 'CB'], ['C', 'AC'], ['D', 'ED']]\n# lst_map = dict(lst)\nlst_map = {i[0]: i[1] for i in lst}\nfor k, v in lst_map.items():\n for c in v:\n if c != k:\n lst_map[k] += lst_map.ge... | [
2
] | [] | [] | [
"enumerate",
"list",
"python"
] | stackoverflow_0074378554_enumerate_list_python.txt |
Q:
If Dataframe column A is X check if column B values are in list
I want to be able to create an error flag in a sperate column.
I am not sure how to check conditions between two different DF columns.
Example DF
Category Item Flag
0 Fruit Apple
1 Fruit Apple
2 Fruit Beef
3 Fr... | If Dataframe column A is X check if column B values are in list | I want to be able to create an error flag in a sperate column.
I am not sure how to check conditions between two different DF columns.
Example DF
Category Item Flag
0 Fruit Apple
1 Fruit Apple
2 Fruit Beef
3 Fruit Kiwi
4 Fruit Orange
What I want to achive:
fruits ... | [
"Using np.where()\ndf[\"Flag\"] = np.where(df[\"Category\"].eq(\"Fruit\") & df[\"Item\"].isin(fruits), \"OK\", \"Error\")\n\n",
"This would do the trick for just fruits, creating a new df.\nYou can loop through all Categories, and combine the dataframes if you want one dataframe.\ntemp_df = df[df['Category'] == \... | [
2,
1,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074378700_pandas_python.txt |
Q:
'django-admin' is not recognized as an internal or external command, operable program or batch file. Windows10
I tried starting my own project in Django but I keep getting "'django-admin' is not recognized as an internal or external command, operable program or batch file."
C:\>cd C:\Users\Gamer Grill\Desktop
C:\... | 'django-admin' is not recognized as an internal or external command, operable program or batch file. Windows10 | I tried starting my own project in Django but I keep getting "'django-admin' is not recognized as an internal or external command, operable program or batch file."
C:\>cd C:\Users\Gamer Grill\Desktop
C:\Users\Gamer Grill\Desktop>mkdir django-practise
C:\Users\Gamer Grill\Desktop>cd django-practise
C:\Users\Gamer Gri... | [
"Probably the easiest thing you can do is uninstall Python and when you install it again make sure the \"add Python to Path\" option is selected before you click install. After that go ahead and do your thing.\n",
"For me, the way to do it is to\nIf you have installed django before with pip install django, you mi... | [
0,
0
] | [
"At the time of writing, Python 3.7 is the latest version. Open the command prompt and check that the Python version matches the version:\n...\\> py --version\n\nNow you can verify your Django installation by executing in the command prompt:\n...\\> django-admin --version\n\nIf you still have problems executing the... | [
-2,
-4
] | [
"django",
"python"
] | stackoverflow_0061543737_django_python.txt |
Q:
Python Date Conversion reading January date as a November Date
152008
2008-01-05 00:00:00
152008
2008-01-05 00:00:00
162008
2008-01-06 00:00:00
162008
2008-01-06 00:00:00
162008
2008-01-06 00:00:00
162008
2008-01-06 00:00:00
1122008
2008-11-02 00:00:00
1122008
2008-11-02 00:00:00
1122008
2008-11-02 00:00:00
112200... | Python Date Conversion reading January date as a November Date | 152008
2008-01-05 00:00:00
152008
2008-01-05 00:00:00
162008
2008-01-06 00:00:00
162008
2008-01-06 00:00:00
162008
2008-01-06 00:00:00
162008
2008-01-06 00:00:00
1122008
2008-11-02 00:00:00
1122008
2008-11-02 00:00:00
1122008
2008-11-02 00:00:00
1122008
2008-11-02 00:00:00
1132008
2008-11-03 00:00:00
1132008
2008-11-03... | [
"you need to zero pad the numbers for the month and or day. see the documentation for %m and %d\nsee docs here\nnote the change from 1132008 in your code to '01132008'\nfrom datetime import datetime\ndatetime.strftime(datetime.strptime('01132008',\"%m%d%Y\").date(),\"%Y/%m/%d\")\n\nreturns '2008/01/13'\nor changing... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074378799_python.txt |
Q:
Counting occurrence of item in csv file
I need to produce the number of occurrences of a word in a csv file. The output needs to list each word and the number of times it appears in the file. So if the file looks like:
house, red, knife, red, car, house, Red
the output would be:
house 2
red 2
knife 1
car 1
Red 1
I... | Counting occurrence of item in csv file | I need to produce the number of occurrences of a word in a csv file. The output needs to list each word and the number of times it appears in the file. So if the file looks like:
house, red, knife, red, car, house, Red
the output would be:
house 2
red 2
knife 1
car 1
Red 1
I've tried creating a dictionary and increment... | [
"cat count.csv \nhouse,red,knife,red,car,house,Red\n\nimport csv\n\nwith open('count.csv') as csv_file:\n ct_dict = {}\n c_reader = csv.reader(csv_file)\... | [
0
] | [] | [] | [
"csv",
"file",
"python"
] | stackoverflow_0074377311_csv_file_python.txt |
Q:
Python multiprocessing - sharing large dataset
I'm trying to speed up a CPU-bound Python script (on Windows11). Threats in Python do not seem to run on a different cpu(core) so the only option I have is multiprocessing.
I have a big dictionary data structure (11GB memory footprint after loading from file) that I a... | Python multiprocessing - sharing large dataset | I'm trying to speed up a CPU-bound Python script (on Windows11). Threats in Python do not seem to run on a different cpu(core) so the only option I have is multiprocessing.
I have a big dictionary data structure (11GB memory footprint after loading from file) that I am checking calculated values on if they are in that ... | [
"you can use a multiprocessing.Manager.dict for this, it's the fastest IPC you can use to do the check between processes in python, and for the memory size, just make it smaller by changing all values to None, on my pc it can do 33k member checks every second ... about 400 times slower than a normal dictionary.\nma... | [
2
] | [] | [] | [
"dictionary",
"large_data",
"multiprocessing",
"python",
"python_3.x"
] | stackoverflow_0074375196_dictionary_large_data_multiprocessing_python_python_3.x.txt |
Q:
Binary search tree - why does it not work without the "return" statement
When I want to search for a name which is in the tree, without the return statement I only get None but why?
See code comment #<----
class Tree:
def __init__(self, data):
self.data = data
self.left = None
self.righ... | Binary search tree - why does it not work without the "return" statement | When I want to search for a name which is in the tree, without the return statement I only get None but why?
See code comment #<----
class Tree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def child(self, data):
if self.data == data:
... | [
"Without return, you ignore the result of the subtree search and fall through to the end of the method, at which point you return None implicitly.\nYou also need to return False when the appropriate subtree is empty, not set the subtree reference to False.\ndef search(self, elem):\n if self.data == elem:\n ... | [
1
] | [] | [] | [
"binary_search_tree",
"python"
] | stackoverflow_0074379015_binary_search_tree_python.txt |
Q:
Why modal window does not shown? Library discord.py
i tried to do my first modal window in python, i am doing this in my cog with discord.py, but i don't understand, why it doesn't works?
When i typing $test command, bot gives nothing. No errors and no answers.
This is my cog code:
from discord.ext import comm... | Why modal window does not shown? Library discord.py | i tried to do my first modal window in python, i am doing this in my cog with discord.py, but i don't understand, why it doesn't works?
When i typing $test command, bot gives nothing. No errors and no answers.
This is my cog code:
from discord.ext import commands
import discord
class ModalTest(discord.... | [
"You can only send modals as a response to interactions (which are triggered by application commands), not regular message commands.\nYour test command is annotated with @commands.command(), so it's a message command. The parameter is incorrectly named (& type-annotated) as discord.Interaction while it's actually c... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074372564_discord.py_python.txt |
Q:
Pyqt5 Don't know where to pass instance variable from button
So I have 2 group boxes, left one has 2 buttons, fruits and vegetables. Right group box is empty and should add to it items after pressing a button. I wrote button class so it stores items, what I can't seem to understand is how do I pass item list, or r... | Pyqt5 Don't know where to pass instance variable from button | So I have 2 group boxes, left one has 2 buttons, fruits and vegetables. Right group box is empty and should add to it items after pressing a button. I wrote button class so it stores items, what I can't seem to understand is how do I pass item list, or rather where should I pass it. So I want to press a button(ex. frui... | [
"One of the solutions is to add a callback manager method to mainWindow and make mousePressEvent trigger it. You can centralize there all callback reactions. Additionally, before adding new widgets to the layout on the right you need to delete the existing ones.\n\nimport sys\nfrom PyQt5.QtCore import Qt\nfrom PyQt... | [
1
] | [] | [] | [
"pyqt5",
"python"
] | stackoverflow_0074375041_pyqt5_python.txt |
Q:
Delete object in array within another array while checking for valid index
The task is to delete an object from an array within another array (a touple if i'm correct). To bugproof i would need to check whether the index is actually valid. This means ranges from 0 to 4 (so input should be greater 0 smaller 4) and ... | Delete object in array within another array while checking for valid index | The task is to delete an object from an array within another array (a touple if i'm correct). To bugproof i would need to check whether the index is actually valid. This means ranges from 0 to 4 (so input should be greater 0 smaller 4) and obviously not be a string or float of any kind.
I have tried to do that with my ... | [
"Here is a version of the valuecheck() function that should do what you want:\ndef valuecheck(checker):\n while True:\n try:\n checker = int(checker)\n if checker > 0 and checker < 4:\n return checker\n checker = input(\"Value must be between 1 and 3, try ag... | [
1,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074378793_python_python_3.x.txt |
Q:
TypeError: setup() missing 2 required positional arguments: 'ctx' and 'message'
I'm having this problem where my error output says that I am missing 2 positional arguments but they are defined.
if you didnt understand, this is a Cog :)
btw, if you see any problems with my sqlite, please notify me because i am kind... | TypeError: setup() missing 2 required positional arguments: 'ctx' and 'message' | I'm having this problem where my error output says that I am missing 2 positional arguments but they are defined.
if you didnt understand, this is a Cog :)
btw, if you see any problems with my sqlite, please notify me because i am kind of new to sqlite
this is my code:
import discord
from discord.ext import commands
im... | [
"\nasync def setup(bot, ctx, message):\n\nThe setup method for cogs only takes bot as the argument, nothing else. You can't just add random arguments to functions and expect the library to be able to pass those arguments in.\nAlso - setup is called when you load a cog. At that point there is no ctx, and there is no... | [
0
] | [
"tbh I am not sure what you are trying to do there, but you dont need to pass bot in the command method if that is the code you use. The error is caused because the bot expects the parameters \"ctx\" and \"message\" in the discord command. This should work:\nasync def setup(self, ctx):\n\n"
] | [
-1
] | [
"discord.py",
"python",
"typeerror"
] | stackoverflow_0074378681_discord.py_python_typeerror.txt |
Q:
Why is pandas compare not working when comparing two dataframes?
I am creating two dataframes, that I set equal to eachother based on an index field. So each frame has the same indices on both sides and I sort them as well. I want to return the differences between these fields, so as to catch any of the rows that... | Why is pandas compare not working when comparing two dataframes? | I am creating two dataframes, that I set equal to eachother based on an index field. So each frame has the same indices on both sides and I sort them as well. I want to return the differences between these fields, so as to catch any of the rows that have 'updated' since the last run. But I am getting a weird result.
... | [
"If you look at the below code:\n\nIt's working.\nCan you please share both of your dfs so that we can assist you better.\n",
"I solved it and will post this in case someone else gets stuck. Apparently Nulls were being interpreted as 'None' when read into the dataframe. But the other dataframe actually had the ... | [
0,
0
] | [] | [] | [
"compare",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074378910_compare_dataframe_pandas_python.txt |
Q:
How can I get a df that is exactly like the .txt imput? (file has " " separator)
I have a TXT file that looks like this:
DBSH
(NFr) O (NTo) Nc C (Vmn (Vmx Bctrl (Qini) T A (Extr
121 D 0950 1050 121 -10. C
(G O E (U) UOp (Sht ) M
1 2 2 -5. S
2 1 0 -10. S
FBAN
(NFr... | How can I get a df that is exactly like the .txt imput? (file has " " separator) | I have a TXT file that looks like this:
DBSH
(NFr) O (NTo) Nc C (Vmn (Vmx Bctrl (Qini) T A (Extr
121 D 0950 1050 121 -10. C
(G O E (U) UOp (Sht ) M
1 2 2 -5. S
2 1 0 -10. S
FBAN
(NFr) O (NTo) Nc C (Vmn (Vmx Bctrl (Qini) T A (Extr
125 D 0950 1050 125 ... | [
"Once you find the \"largest_colummn\"(which should be largest row), go through each line and change the delimiter to a comma. Add as many comas until you get the number of correct columns for each line. I am guessing the space delimiter could make things complicated. You can add Nan when adding comas or change th... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074378986_dataframe_pandas_python.txt |
Q:
Checking probability of the if statement in Python more efficiently
I have multiple variables to pass in if, elif and else statement. Assuming 3 variables a, b, and c. Those are simply list that contains numbers. But I need to define if, elif and else statement for each probability of the variables.
For example:
... | Checking probability of the if statement in Python more efficiently | I have multiple variables to pass in if, elif and else statement. Assuming 3 variables a, b, and c. Those are simply list that contains numbers. But I need to define if, elif and else statement for each probability of the variables.
For example:
if one of the variables >0 do something with this variable but pass the o... | [
"More simplar way?\na=[1,0,1,1,1,0,0,0,1]\nb=[1,0,0,1,0,1,1,0,1]\nc=[1,0,0,0,1,0,1,1,1]\n\na1 = ['working' if int(el)>0 else 'not working' for el in a]\nb1 = ['working' if int(el)>0 else 'not working' for el in b]\nc1= ['working' if int(el)>0 else 'not working' for el in c]\n\nfor f, b,i,x,y,z in zip(a, b,c,a1,b1,c... | [
1,
1
] | [] | [] | [
"if_statement",
"python",
"python_3.x"
] | stackoverflow_0074378466_if_statement_python_python_3.x.txt |
Q:
Finding local time zone using Python
I want to find my local time zone and then return the time zone name (cet, est etc.) using Python and my location so that I can just find it without entering any additional information except for the location of my pc (which I want to find using GPS and not manually adding it)
... | Finding local time zone using Python | I want to find my local time zone and then return the time zone name (cet, est etc.) using Python and my location so that I can just find it without entering any additional information except for the location of my pc (which I want to find using GPS and not manually adding it)
import say
import datetime
def timezone()... | [
"You can use the time module to get your local timezone:\nimport time\nprint(time.tzname)\n\nThis gets you a tuple like ('CET', 'CEST').\n",
"borrowing from this answer to the linked Q&A, you can also do\nfrom datetime import datetime\n\ndt_local = datetime.now().astimezone()\n\nprint(dt_local.isoformat(timespec=... | [
1,
0
] | [] | [] | [
"datetime",
"python",
"python_datetime",
"timezone"
] | stackoverflow_0074378432_datetime_python_python_datetime_timezone.txt |
Q:
Can I parse the content of a Jupyter Notebook cells in a script?
Is it possible to extract the content of a Jupyter notebook input cell programatically? Be that raw cell / code / Markdown, does not matter really. I was thinking of tools like nbconvert or papermill but could not find exactly what I am looking for..... | Can I parse the content of a Jupyter Notebook cells in a script? | Is it possible to extract the content of a Jupyter notebook input cell programatically? Be that raw cell / code / Markdown, does not matter really. I was thinking of tools like nbconvert or papermill but could not find exactly what I am looking for... I would like to write a script which will essentially parse a notebo... | [
"The Jupyter ecosystem includes nbformat for this this task.\nThe intro at the top of here will probably help you see how nbformat is the tool you seek. Importantly, the abstractions of the notebook & cells & types of cells is all baked in so that you don't have to worry about json parsing really.\nI have several e... | [
1
] | [] | [] | [
"jupyter",
"jupyter_notebook",
"nbconvert",
"papermill",
"python"
] | stackoverflow_0074368984_jupyter_jupyter_notebook_nbconvert_papermill_python.txt |
Q:
Add objects from a class to class list and extract them
I have a class:
class AlchemicalElement:
def __init__(self, name: str):
self.name = name
I then create a class that will be used to store the AlchemicalElement objects:
class AlchemicalStorage:
def __init__(self):
self.storage_list ... | Add objects from a class to class list and extract them | I have a class:
class AlchemicalElement:
def __init__(self, name: str):
self.name = name
I then create a class that will be used to store the AlchemicalElement objects:
class AlchemicalStorage:
def __init__(self):
self.storage_list = []
I don't understand how to write this function:
def extr... | [
"Assuming this is what you're starting with\nclass AlchemicalElement:\n\n def __init__(self, name: str):\n self.name = name\n\n\nclass AlchemicalStorage:\n\n def __init__(self):\n self.storage_list = []\n\n def add(self, element: AlchemicalElement):\n if isinstance(element, AlchemicalE... | [
0
] | [] | [] | [
"list",
"oop",
"python"
] | stackoverflow_0074378690_list_oop_python.txt |
Q:
ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import)
I'm upgrading an application from Django 1.11.25 (Python 2.6) to Django 3.1.3 (Python 3.8.5) and, when I run manage.py makemigrations, I receive this messasge:
File "/home/eduardo/projdevs/upgrade-i... | ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import) | I'm upgrading an application from Django 1.11.25 (Python 2.6) to Django 3.1.3 (Python 3.8.5) and, when I run manage.py makemigrations, I receive this messasge:
File "/home/eduardo/projdevs/upgrade-intra/corporate/models/section.py", line 9, in <module>
from authentication.models import get_sentinel**
ImportError: ... | [
"For future readers, this can also happen if you name a python file the same name as a dependency your project uses.\nFor example:\nI cannot have a file named retrying.py that is using the retrying package.\nAssuming I had the retrying package in my project, I could not have a file called retrying.py with the below... | [
168,
29,
6,
5,
3,
1,
0
] | [] | [] | [
"circular_dependency",
"django",
"importerror",
"python",
"python_module"
] | stackoverflow_0064807163_circular_dependency_django_importerror_python_python_module.txt |
Q:
Comparing columns with at least some values are the same Python
I have a dataframe with several rows and I need to assign a number (new column) according to the values of the other columns:
If all values in the different columns are the same the new value would be 5,
if at least 4 values are the same it would be ... | Comparing columns with at least some values are the same Python | I have a dataframe with several rows and I need to assign a number (new column) according to the values of the other columns:
If all values in the different columns are the same the new value would be 5,
if at least 4 values are the same it would be 4,
if at least 3 values are the same, 3
and so on until all are diffe... | [
"You can make use of collections.Counter to count how many items are equal. I come up with this way:\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter\n\ndata = [\n [1,1,1,1,1],\n [2,3,2,2,2],\n [2,2,3,4,1],\n [4,4,1,1,1],\n [2,1,2,3,5],\n [1,2,3,4,5]\n]\ndf = pd.DataFrame(... | [
0,
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074378495_dataframe_python.txt |
Q:
How to access SDL Surface pixel data in pySDL
I am making a 3d renderer in python, I am using pySDL for the display as pygame didn't seem to have fast enough pixel writes. I need to access pixels as an array and it seems like this shouldn't be too hard in SDL, according to the docs the pixel data can be accessed d... | How to access SDL Surface pixel data in pySDL | I am making a 3d renderer in python, I am using pySDL for the display as pygame didn't seem to have fast enough pixel writes. I need to access pixels as an array and it seems like this shouldn't be too hard in SDL, according to the docs the pixel data can be accessed directly, but here is the problem, its a null pointe... | [
"Take this example\nfrom sdl2 import *;\nimport sys;\nimport ctypes;\n\nSDL_Init(SDL_INIT_VIDEO);\nwin = SDL_CreateWindow(b\"test\",\n SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\n 640, 480, 0);\nsurf = SDL_GetWindowSurface(win);\n\n# get pointer to pixels as uint32[]\nu32_pixels = ctypes.cast(s... | [
1
] | [] | [] | [
"pysdl2",
"python",
"sdl",
"void_pointers"
] | stackoverflow_0074378930_pysdl2_python_sdl_void_pointers.txt |
Q:
Flask Simple Question About Printing Strings with newline
For Example, I am using the following code.
@app.route('/test', methods=['GET', 'POST'])
def test():
if request.method == 'POST':
test = request.form['test']
print(test)
print('\nprinted')
If I send the post request with a value... | Flask Simple Question About Printing Strings with newline | For Example, I am using the following code.
@app.route('/test', methods=['GET', 'POST'])
def test():
if request.method == 'POST':
test = request.form['test']
print(test)
print('\nprinted')
If I send the post request with a value containing newline '\n' the print method will not print the co... | [
"I believe it's due to the way the input field value is handled. So it escapes the escape character, because it wants to keep the format of the input as exact as possible.\nSo the true values of your varaible is test = \\\\nhello\nYou can fix this like so:\ntest.replace(\"\\\\n\", \"\\n\") # \"\\\\nhello\" -> \"\\n... | [
0,
0
] | [] | [] | [
"flask",
"python",
"python_3.x"
] | stackoverflow_0074378581_flask_python_python_3.x.txt |
Q:
Sending MIDI file using Python to MAX MSP or Ableton
I have a Python code that outputs a MIDI file and I'm trying to send this automatically to Ableton (preferably) or MAX MSP so I can do further processing. Until now I've tried many suggested solutions but none of them has worked, and here's a summary of what I'v... | Sending MIDI file using Python to MAX MSP or Ableton | I have a Python code that outputs a MIDI file and I'm trying to send this automatically to Ableton (preferably) or MAX MSP so I can do further processing. Until now I've tried many suggested solutions but none of them has worked, and here's a summary of what I've done:
In MAX MSP, I created a udpreceive PORT object an... | [
"I think the UDP/OSC protocols are overcomplicating the situation more than they're helping. If you don't want to or don't need to interact with Max, you could just automate the midi file importing process through python or with an additional scripting language.\nWithin Live's user menu, the Create dropdown menu ha... | [
0
] | [] | [] | [
"ableton_live",
"osc",
"python",
"udp"
] | stackoverflow_0073260192_ableton_live_osc_python_udp.txt |
Q:
raise AssertionError("Torch not compiled with CUDA enabled")
I Try to install Pytorch on my Windows 10 system.
I wanna Use a anaconda env.
i followed the instruction 'https://pytorch.org/' stable 1.12.1 && Conda && Python && cuda 11.6
(conda install pytorch torchvision torchaudio cudatoolkit=11.6 -c pytorch -c con... | raise AssertionError("Torch not compiled with CUDA enabled") | I Try to install Pytorch on my Windows 10 system.
I wanna Use a anaconda env.
i followed the instruction 'https://pytorch.org/' stable 1.12.1 && Conda && Python && cuda 11.6
(conda install pytorch torchvision torchaudio cudatoolkit=11.6 -c pytorch -c conda-forge)
Before I installed conda 11.6, when i enter nvcc --versi... | [] | [] | [
"In my case i try to change the environment so i create new environment using conda then i download pytorch again from pytorch.org the compatible version for my GPU and then i tap the cmd of training and it works. hope it helps you\n"
] | [
-1
] | [
"anaconda",
"gpu",
"python",
"pytorch"
] | stackoverflow_0074058265_anaconda_gpu_python_pytorch.txt |
Q:
Cowardly refusing to install hooks with `core.hooksPath` set
i tried to run this command but it always show this error, i can't fix it with anyway. Help me, please!
(venv)<...>pre-commit install
[ERROR] Cowardly refusing to install hooks with core.hooksPath set.
hint: git config --unset-all core.hooksPath
A:
Run... | Cowardly refusing to install hooks with `core.hooksPath` set | i tried to run this command but it always show this error, i can't fix it with anyway. Help me, please!
(venv)<...>pre-commit install
[ERROR] Cowardly refusing to install hooks with core.hooksPath set.
hint: git config --unset-all core.hooksPath
| [
"\nRun:\ngit config --unset-all core.hooksPath\n\n\nIf the global core.hooksPath is not empty, run:\ngit config --global --unset-all core.hooksPath\n\nBut of course, it's global so be careful.\nWhy pre-commit is nonfunctional with global hooks? see issue\n\n\n",
"You are getting the above error because of setting... | [
6,
0,
0
] | [] | [] | [
"git",
"pre_commit",
"pre_commit.com",
"python"
] | stackoverflow_0067793193_git_pre_commit_pre_commit.com_python.txt |
Q:
Video of geometrical shapes in matplotlib
I have position data of three circles and I want to make an animation of these moving circles. I have seen a lot of animations of functions, but I can't get to work animations of geometric shapes. Here is some code I wrote to create plots of the three circles in time varyi... | Video of geometrical shapes in matplotlib | I have position data of three circles and I want to make an animation of these moving circles. I have seen a lot of animations of functions, but I can't get to work animations of geometric shapes. Here is some code I wrote to create plots of the three circles in time varying positions.
import matplotlib.pyplot as plt
i... | [
"You need to call animate function.\n(There are other ways. Depending on how you render the plot, you can loop yourself, and update the data. But for this kind of animation, animate is better).\n# Let start with import. Btw, you should include those in your question.\n# The \"minimal reproducible example\" is an ex... | [
1
] | [] | [] | [
"animation",
"matplotlib",
"python"
] | stackoverflow_0074378668_animation_matplotlib_python.txt |
Q:
getting angle with known coordinates
I have an object on my canvas and I want to make an arrow pointing on it. I already have an image of arrow, that is pointing up, and I need to know the angle I must rotate it by to make it point on that image. The arrow is always at position (0, 0), but the position of the seco... | getting angle with known coordinates | I have an object on my canvas and I want to make an arrow pointing on it. I already have an image of arrow, that is pointing up, and I need to know the angle I must rotate it by to make it point on that image. The arrow is always at position (0, 0), but the position of the second picture can change.
I know I can count... | [
"The angle is 90 - arctan(Y/X). You probably want to use math.atan2(y,x), and remember that returns radians, not degrees. If you want degrees, it's\nangle = 90 - math.atan2(y,x) * 180 / math.pi\n\n"
] | [
0
] | [] | [] | [
"python",
"trigonometry"
] | stackoverflow_0074379200_python_trigonometry.txt |
Q:
python dataframe unique values
I dont have experience with dataframes and i stuck in the following problem:
There is a table looking like that:
enter image description here
parent account account number account name code
0 parent 1 123122 account1 1
1 parent 1 456222 account2 1
2 parent 1 ... | python dataframe unique values | I dont have experience with dataframes and i stuck in the following problem:
There is a table looking like that:
enter image description here
parent account account number account name code
0 parent 1 123122 account1 1
1 parent 1 456222 account2 1
2 parent 1 456334 account3 1
3 parent ... | [
"First obtain a list of parent accounts such that they have more than 1 distinct code\ncondition = df.groupby('parent account').code.nunique() > 1\n\nparent_list = list( condition.index[condition.values] )\n\nThen apply the filter on your data\ndf[ df['parent acount'].isin(parent_list) ]\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"datatable",
"list",
"pandas",
"python"
] | stackoverflow_0074379569_dataframe_datatable_list_pandas_python.txt |
Q:
How to use a string with backslashes in Python
I want to maintain a variable with a string which contains backslashes and don't want to alter that. When I try to use the string, it gets extra backslashes as escape characters. I tried with 'r' ( raw ) modifier - but it didn't help.
Python 2.7.3 (default, Feb 27 201... | How to use a string with backslashes in Python | I want to maintain a variable with a string which contains backslashes and don't want to alter that. When I try to use the string, it gets extra backslashes as escape characters. I tried with 'r' ( raw ) modifier - but it didn't help.
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
[GCC 4.6.3] on linux2
Type "help", "cop... | [
"Your string is not altered. Use the print statement to print the actual variable contents.\nIn the second example, you just print the whole list, not the items present inside the list.\n>>> s = r'\\abc'\n>>> print s\n\\abc\n>>> value = [r'\"\\1\"', r'\"\\\\1\"', r'\"\\\\\\1\"' ]\n>>> for val in value:\n pr... | [
0,
0,
0
] | [] | [] | [
"backslash",
"python",
"python_2.7"
] | stackoverflow_0028554767_backslash_python_python_2.7.txt |
Q:
Aligning text in rows of Pyplot legend at multiple points, without using monospace font
I am trying to create a neat legend in Pyplot. So far I have this:
fig = plt.figure()
ax = plt.gca()
marker_size = [20.0, 40.0, 60.0, 100.0, 150.0]
marker_color = ['black', 'red',... | Aligning text in rows of Pyplot legend at multiple points, without using monospace font | I am trying to create a neat legend in Pyplot. So far I have this:
fig = plt.figure()
ax = plt.gca()
marker_size = [20.0, 40.0, 60.0, 100.0, 150.0]
marker_color = ['black', 'red', 'pink', 'white', 'yellow']
... | [
"You could replace the spaces by '\\u2007', a space that is as wide as a digit.\nIn most fonts, a space character is much narrower than a digit. Except for monospaced fonts, which don't look as nice, each letter has its own width. The character width can even be different depending on which letter goes before and a... | [
3,
2
] | [] | [] | [
"latex",
"matplotlib",
"python"
] | stackoverflow_0074378923_latex_matplotlib_python.txt |
Q:
Flipping variable length subvectors inside a numpy array efficiently
I have a problem that requires me to re-order elements in subvectors within a long vector in a specific way such that the first element of the subvector remains in place, and the remaining elements are flipped.
For example:
vector = [0, 1, 2, 3, ... | Flipping variable length subvectors inside a numpy array efficiently | I have a problem that requires me to re-order elements in subvectors within a long vector in a specific way such that the first element of the subvector remains in place, and the remaining elements are flipped.
For example:
vector = [0, 1, 2, 3, 4, 5, 6, 7] and the subvectors have length 3 and 5, then the flipped versi... | [
"My solution to this in the end was to determine the unique lengths of the subvectors and create 2D arrays that are groups of these, where the 2D array is nSubVectors long, and has zeros at locations where the subvectors have different lengths to the current length.\nFrom there, the entire 2D array can be flipped f... | [
1
] | [] | [] | [
"numpy",
"optimization",
"python",
"vector",
"vectorization"
] | stackoverflow_0074147140_numpy_optimization_python_vector_vectorization.txt |
Q:
spacy matcher pattern IN + REGEX Tag
My goal is to match with spacy the sentences that contain one of the following words:
['studium','abschluss','ausbildung']
I can solve the problem with this line:
pattern = [{"LOWER": {'IN':['studium','abschluss', 'ausbildung']}}]
My problem is that in German there is a vast u... | spacy matcher pattern IN + REGEX Tag | My goal is to match with spacy the sentences that contain one of the following words:
['studium','abschluss','ausbildung']
I can solve the problem with this line:
pattern = [{"LOWER": {'IN':['studium','abschluss', 'ausbildung']}}]
My problem is that in German there is a vast use of composed words like Hochschulstudium... | [
"You can use the REGEX operator:\nimport re\nl = ['abschluss', 'ausbildung']\npattern = [{'LOWER': {'REGEX':fr'^(?:{\"|\".join(map(re.escape, l))}|[^\\W\\d_]*studium)$'}}]\n\nNote:\n\nmap(re.escape, l) - escapes the items in the l list\n\"|\".join(...) - joins the words as alternatives (word1|word2|wordN)\n^(?:...|... | [
2
] | [] | [] | [
"nlp",
"nltk",
"python",
"regex",
"spacy"
] | stackoverflow_0074379471_nlp_nltk_python_regex_spacy.txt |
Q:
How can I rotate column titles in pyplot.table?
I'm creating a table in matplotlib, but the table headers are long strings, and the table values are numbers with only a few digits. This leaves me with two bad options: either my table is much wider than necessary, or my headers overlap. To fix this, I'd like to rot... | How can I rotate column titles in pyplot.table? | I'm creating a table in matplotlib, but the table headers are long strings, and the table values are numbers with only a few digits. This leaves me with two bad options: either my table is much wider than necessary, or my headers overlap. To fix this, I'd like to rotate the table headings (possibly up to 90 degrees). I... | [
"I figured it out. It's not pretty, but it works. I added two annotations for each column - the text, and a line to separate it from the next column header. I had to define some parameters that apply to the table and the fancy labels (width, height, col_width), and some parameters to make the fancy labels line up c... | [
3,
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0035003603_matplotlib_python.txt |
Q:
How can I write filtered results from a JSON file to a CSV file in Python?
I am trying to make a program that can save the results of a filtered JSON file as a CSV. Right now my function only saves the keys of the JSON to the CSV file.
Ideally I want the function to take two arguments: column (key) it is searching... | How can I write filtered results from a JSON file to a CSV file in Python? | I am trying to make a program that can save the results of a filtered JSON file as a CSV. Right now my function only saves the keys of the JSON to the CSV file.
Ideally I want the function to take two arguments: column (key) it is searching in; and the item (value) it is searching for.
This is my current function:
def ... | [
"def save_csv(key, value):\n with open('db.json') as json_file:\n info = json.load(json_file)\n test = info['data']\n with open('test.csv', 'w', newline='') as csv_file:\n csv_writer = csv.writer(csv_file)\n for n,v in enumerate(test):\n if not n:\n ... | [
0
] | [] | [] | [
"csv",
"json",
"python"
] | stackoverflow_0074379142_csv_json_python.txt |
Q:
Refining/condensing my python code for rock paper scissors (I just started learning)
### Import specification function required - for some reason if I do just "import random"
from random import randint
moves = ["rock", "paper", "scissors"]
### While pretty much is used so we can play over and over.
while True:
... | Refining/condensing my python code for rock paper scissors (I just started learning) | ### Import specification function required - for some reason if I do just "import random"
from random import randint
moves = ["rock", "paper", "scissors"]
### While pretty much is used so we can play over and over.
while True:
computer = moves[randint(0,2)]
player = input("Choose rock, paper or scissors, or '... | [
"You can eliminate most of your code and achieve the same result:\nAt its core, rock/paper/scissors is a 1/3 chance of each of win, loss, or tie. Therefore, requesting the user's input and then returning a randomly chosen outcome will give the same results.\nimport random as r\ninput(\"Enter rock, paper, or scissor... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074379372_python.txt |
Q:
get function in route FastApi
Is it possible to pass a function to a route so that it is then called?
i tried to do this but it doesn't work:
app = FastAPI()
class GetFunction(BaseModel):
function: Callable
def hello():
return print("Hello world")
@app.post("/datalore")
def datalore(function: GetFunctio... | get function in route FastApi | Is it possible to pass a function to a route so that it is then called?
i tried to do this but it doesn't work:
app = FastAPI()
class GetFunction(BaseModel):
function: Callable
def hello():
return print("Hello world")
@app.post("/datalore")
def datalore(function: GetFunction):
function()
| [
"The simpliest way to do that is just get dictionary of functions you would like to call\napp = FastAPI()\n\ndef hello():\n print(\"Hello!\")\n\n@app.post(\"/datalore\")\ndef datalore(function: str):\n func_dict = {\"hello\": hello}\n func_to_call = func_dict[function]\n return func_to_call()\n\n"
] | [
2
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0074379522_fastapi_python.txt |
Q:
Shelve module: What's the point of 'writeback' variable?
Take a look at the code snippet below
Python 3.10.1 (main, Dec 10 2021, 10:36:36) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from shelve import DbfilenameShelf as db
>>> x = db("te... | Shelve module: What's the point of 'writeback' variable? | Take a look at the code snippet below
Python 3.10.1 (main, Dec 10 2021, 10:36:36) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from shelve import DbfilenameShelf as db
>>> x = db("test") ## create a new Shelf object of type DbfilenameShelf
>>> ... | [
"You seem to have misinterpreted the meaning of writeback.\nWriteback is a method of caching in which the latest data is initially written only to the cache and is written back to secondary storage only periodically or when some condition is satisfied. It is in contrast to write-through method in which data is writ... | [
0
] | [] | [] | [
"python",
"python_3.x",
"shelve"
] | stackoverflow_0070873522_python_python_3.x_shelve.txt |
Q:
Create conditional dataframe column using content of a different column as input on f-string inside np.where
I have a dataframe like this (simplified):
| | amount | other_amt | rule_id |
|---:|:--------|:----------|---------:|
| 0 | 2 | 0 | 101 |
| 1 | 20 | 0.5 | 102 |
| ... | Create conditional dataframe column using content of a different column as input on f-string inside np.where | I have a dataframe like this (simplified):
| | amount | other_amt | rule_id |
|---:|:--------|:----------|---------:|
| 0 | 2 | 0 | 101 |
| 1 | 20 | 0.5 | 102 |
| 2 | 300 | 0 | 0 |
| 3 | 50 | 1 | 101 |
I then have a set of functions that ... | [
"You can use a dictionary to look up the rules:\ndef rule_101(df):\n return df['amount'] / 2\n\ndef rule_102(df):\n return df['other_amt']\n\nruleset = {\n 0: lambda k: 0,\n 101: rule_101,\n 102: rule_102\n}\n\ndef rules(row):\n return ruleset[row['rule_id']](row)\n\ndf['new_col'] = df.apply(rul... | [
1
] | [] | [] | [
"dataframe",
"keyerror",
"numpy",
"pandas",
"python"
] | stackoverflow_0074379752_dataframe_keyerror_numpy_pandas_python.txt |
Q:
Make a row-wise Conditional Column
I got this dataframe:
Df = pd.DataFrame({'TIPOIDPRESTADOR': ['CC', 'NI', 'CE', 'RS'],
'Levels': [0, 1, np.nan, np.nan]
})
| TIPOIDPRESTADOR | Levels |
| -------- | -------- |
| CC | 0 |
| NI ... | Make a row-wise Conditional Column | I got this dataframe:
Df = pd.DataFrame({'TIPOIDPRESTADOR': ['CC', 'NI', 'CE', 'RS'],
'Levels': [0, 1, np.nan, np.nan]
})
| TIPOIDPRESTADOR | Levels |
| -------- | -------- |
| CC | 0 |
| NI | 1 |
| CE ... | [
"You were performing operations on TIPOIDPRESTADOR column rather than on Levels (assume those were typos, otherwise you wouldn't have got your result) and when using np.where() in a loop you probably have filled all NaN values in the first iteration and there has become nothing to update afterwards.\nTry this:\nfor... | [
0
] | [] | [] | [
"loops",
"pandas",
"python"
] | stackoverflow_0074379028_loops_pandas_python.txt |
Q:
What is the right way to mimic interface in Python with AbstractClass and type hinting
I need to write an abstract class which will act like an driver to "something external".
# ./base.py
import typing as t
from abc import ABC, abstractmethod
class DefaultClass: pass
MyType = t.TypeVar("MyType", bound=DefaultCla... | What is the right way to mimic interface in Python with AbstractClass and type hinting | I need to write an abstract class which will act like an driver to "something external".
# ./base.py
import typing as t
from abc import ABC, abstractmethod
class DefaultClass: pass
MyType = t.TypeVar("MyType", bound=DefaultClass)
class Driver(ABC):
def __init__(self, return_class: t.Type[MyType]):
self.... | [
"You did not give enough context to provide an unambiguous recommendation, but I'll give it a shot.\nIf that \"something external\" being driven by your Driver subclasses indeed always inherits from the same base class, there is no need for typing.Protocol here since we have nominal subtyping to guide us.\nI agree ... | [
1
] | [] | [] | [
"abstract_class",
"python",
"python_3.x",
"type_hinting"
] | stackoverflow_0074377778_abstract_class_python_python_3.x_type_hinting.txt |
Q:
Split a List into several Lists based on sum of List in python
This is my code:
list_ = [30.3125, 13.75, 12.1875, 30.625, 18.125, 58.75, 38.125, 33.125, 55.3125, 28.75, 60.3125, 31.5625, 59.0625]
total = 150.0
new_list = []
while sum(list_) > total:
new_list.append(list_[-1:])
list_ = list_[:-1]
new_list... | Split a List into several Lists based on sum of List in python | This is my code:
list_ = [30.3125, 13.75, 12.1875, 30.625, 18.125, 58.75, 38.125, 33.125, 55.3125, 28.75, 60.3125, 31.5625, 59.0625]
total = 150.0
new_list = []
while sum(list_) > total:
new_list.append(list_[-1:])
list_ = list_[:-1]
new_list.reverse()
print(list_)
>>> [30.3125, 13.75, 12.1875, 30.625, 18.12... | [
"How about putting them in a dictionary?\nlist_ = [30.3125, 13.75, 12.1875, 30.625, 18.125, 58.75, 38.125, 33.125, 55.3125, 28.75, 60.3125, 31.5625, 59.0625]\ntotal = 150.0\n\ndict_ = {}\n\nsum_ = 0\ni = 0\n\nfor item in list_: \n # When sum + item > total reset sum and go to next key\n sum_ += item\n i... | [
2,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0045546541_python_python_3.x.txt |
Q:
Split one CSV file into multiple new CSV files based on the value of one column
I want to split one big CSV file into multiple new CSV files.
There is a column SYMBOL I want the new CSV files on that name.
There are around 200 symbols.
List of columns in the big CSV file are:
INSTRUMENT
SYMBOL
EXPIRY_DT
STRIKE_PR... | Split one CSV file into multiple new CSV files based on the value of one column | I want to split one big CSV file into multiple new CSV files.
There is a column SYMBOL I want the new CSV files on that name.
There are around 200 symbols.
List of columns in the big CSV file are:
INSTRUMENT
SYMBOL
EXPIRY_DT
STRIKE_PR
OPTION_TYP
OPEN
HIGH
LOW
CLOSE
SETTLE_PR
CONTRACTS
VAL_INLAKH
OPEN_INT
CHG_IN_OI
TIM... | [
"First, make a unique list of all the symbols, and iterate through the list using the variable in the code you already have + something else to handle the storage of the data... something like this. Just make sure the data is not that big that can cause a MemoryError reading all of the files from the zip.\nimport g... | [
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074379496_csv_python.txt |
Q:
Converting String to dates in pyspark
I have a String in the format of "MMM-YY" (ie) "jun-22","Jan-22" etc.
I want to convert it into Date with 01st Day of Month in the following format.
Jan-22 --> 01-Jan-22
Feb-21 --> 01-Feb-21
I have tried a few ways but couldn't get to the solution.
Can someone please advise o... | Converting String to dates in pyspark | I have a String in the format of "MMM-YY" (ie) "jun-22","Jan-22" etc.
I want to convert it into Date with 01st Day of Month in the following format.
Jan-22 --> 01-Jan-22
Feb-21 --> 01-Feb-21
I have tried a few ways but couldn't get to the solution.
Can someone please advise on what is the quickest and most efficient w... | [
"Thanks for the help. I was able to add \"01-\" at the beginning of the date string and converting it into a date.\n"
] | [
0
] | [] | [] | [
"date",
"pyspark",
"python"
] | stackoverflow_0074343555_date_pyspark_python.txt |
Q:
How do I replace nan values of specific rows to a random number using pandas or numpy
I have a dataset in which few values are null. I want to change them to either 4 or 5 randomly in specific rows. How do I do that?
data.replace(np.nan, np.random.randint(4,5))
I tried this and every nan value changed to only 4 a... | How do I replace nan values of specific rows to a random number using pandas or numpy | I have a dataset in which few values are null. I want to change them to either 4 or 5 randomly in specific rows. How do I do that?
data.replace(np.nan, np.random.randint(4,5))
I tried this and every nan value changed to only 4 and not 4 and 5 randomly. Also I dont know how to replace nan values for only specific rows ... | [
"Use loc and select by index and isna. Change np.random.randint(4,5) to (4,6) to get both four and fives.\nimport pandas as pd\nimport numpy as np\n\ndata = {\n 'A': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n 'B': [0, np.nan, 1, 2.0, 2, np.nan, 3, 2.0, 7, np.nan]}\ndf = pd.DataFrame(data)\n# A B\n# 1 0.0\n# 2 Na... | [
0
] | [] | [] | [
"fillna",
"nan",
"numpy",
"pandas",
"python"
] | stackoverflow_0074379219_fillna_nan_numpy_pandas_python.txt |
Q:
TKINTER get the position of LABEL in TEXT FRAME
I have a TEXT Widget as a FRAME und add LABELS to it. Any way to get the position of the LABEL by clicking it?
Not coordinates but rather position.
Example:
These are 15 different LABELS and I need the position of the LABEL 'different at position 4'.
Result:
4 after ... | TKINTER get the position of LABEL in TEXT FRAME | I have a TEXT Widget as a FRAME und add LABELS to it. Any way to get the position of the LABEL by clicking it?
Not coordinates but rather position.
Example:
These are 15 different LABELS and I need the position of the LABEL 'different at position 4'.
Result:
4 after clicking 'different' LABEL
import tkinter as tk
from ... | [
"If you want an index you'll need the function called by the click to return the index number. This can be attached with a function closure as shown below, or with functools.partial if you're more comfortable with that.\nI've shown the index incrementing by line. It could be incremented for each label or whatever... | [
0
] | [] | [] | [
"frame",
"python",
"tkinter",
"window"
] | stackoverflow_0074366578_frame_python_tkinter_window.txt |
Q:
Failed convert .caffemodel to .mlmodel
While trying convert caffemodel to mlmodel i cant run my converter-script.py
this is my converter-script.py file :
import coremltools
caffe_model = ('oxford102.caffemodel', 'deploy.prototxt')
labels = 'flower-labels.txt'
models = coremltools.converters.caffe.converts(
caff... | Failed convert .caffemodel to .mlmodel | While trying convert caffemodel to mlmodel i cant run my converter-script.py
this is my converter-script.py file :
import coremltools
caffe_model = ('oxford102.caffemodel', 'deploy.prototxt')
labels = 'flower-labels.txt'
models = coremltools.converters.caffe.converts(
caffe_model,
class_labels = labels,
image_... | [
"Use python3 instead of creating and running from a python27 venv.\npython3 convert-script.py\n\nworked for me\n",
"So the problem here is about coremltools. The most recent version of it works with python 3 and you're doing conversion on python 2.7\nThe easiest way to solve your problem is to downgrade your core... | [
0,
0
] | [] | [] | [
"mlmodel",
"python",
"python_2.7",
"virtualenv"
] | stackoverflow_0067084584_mlmodel_python_python_2.7_virtualenv.txt |
Q:
TypeError: Text reading control character must be a single unicode character or None
Using numpy.loadtxt with numpy==1.23.4 is throwing a TypeError when loading from a file with multiple characters in the delimiter:
from io import StringIO
import numpy as np
csv_file = StringIO("""1||2
3||4
5||6
""")
print(np.lo... | TypeError: Text reading control character must be a single unicode character or None | Using numpy.loadtxt with numpy==1.23.4 is throwing a TypeError when loading from a file with multiple characters in the delimiter:
from io import StringIO
import numpy as np
csv_file = StringIO("""1||2
3||4
5||6
""")
print(np.loadtxt(csv_file, delimiter="||"))
Traceback (most recent call last):
File "/home/hayesal... | [
"loadtxt appears to have been rewritten between 1.22 and 1.23.\nOne fix would be to replace np.loadtxt with np.genfromtxt:\nfrom io import StringIO\nimport numpy as np\n\ncsv_file = StringIO(\"\"\"1||2\n3||4\n5||6\n\"\"\")\n\nprint(np.genfromtxt(csv_file, delimiter=\"||\"))\n\n"
] | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074379966_numpy_python.txt |
Q:
compare integer to value in list in python
I'm trying to compare a value in list to a integer. can someone help how to do that
list = [1]
if list == number:
print(number)
I want some thing like above, how to do
A:
list = ["1","20","300","4000","50000"]
temp = int(list[x])
if temp == number:
print(number... | compare integer to value in list in python | I'm trying to compare a value in list to a integer. can someone help how to do that
list = [1]
if list == number:
print(number)
I want some thing like above, how to do
| [
"list = [\"1\",\"20\",\"300\",\"4000\",\"50000\"]\ntemp = int(list[x])\nif temp == number:\n print(number)\n\n#x = 1 to list# (number of values in list)\n\nBe warned, if the string in the list isn't an integer (when removing \"quotes\"), it will throw an error\n",
"if you have only one element in your list you... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074379799_list_python.txt |
Q:
Decision Tree in python with sklearn change sklearn to use c4.5
My question is can we choose what Decision Tree algorithm to use in sklearn?
In user guide of sklearn, it mentions optimised version of the CART algorithm is used.
Can we change to other algorithms such as C4.5?
A:
According to scikit-learn document... | Decision Tree in python with sklearn change sklearn to use c4.5 | My question is can we choose what Decision Tree algorithm to use in sklearn?
In user guide of sklearn, it mentions optimised version of the CART algorithm is used.
Can we change to other algorithms such as C4.5?
| [
"According to scikit-learn documentation, they use an optimized version of the CART algorithm; however, the scikit-learn implementation does not support categorical variables.\nCredit: https://scikit-learn.org/stable/modules/tree.html#tree-algorithms-id3-c4-5-c5-0-and-cart\n"
] | [
0
] | [] | [] | [
"decision_tree",
"python",
"scikit_learn"
] | stackoverflow_0066627436_decision_tree_python_scikit_learn.txt |
Q:
Pygame object moves to all sides except downwards
I'm learning to develop a pygame using a book with an example. So basically I'm using a code from the book, the only thing I swapped was an element, which in my case is a robot.
In a word, I am supposed to make the robot move left, right, down and up - and it doe... | Pygame object moves to all sides except downwards | I'm learning to develop a pygame using a book with an example. So basically I'm using a code from the book, the only thing I swapped was an element, which in my case is a robot.
In a word, I am supposed to make the robot move left, right, down and up - and it does move to all the sides but won't move downwards. Again... | [
"In the _check_keydown_events there is the following line:\nelif event_key == pygame.K_DOWN:\n\nHowever, the event_keyvariable doesn't exist. It should be event.key, as you want to get the attribute from the event variable.\n"
] | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074374439_pygame_python.txt |
Q:
Python-Redmine on a project without issues
I have a Redmine project that is a container for subprojects. This top level project does not have issues (Issue tracking is not enabled in the project settings).
I am trying to figure out a way for the Python api to detect this. Right now, when my code (which is scanning... | Python-Redmine on a project without issues | I have a Redmine project that is a container for subprojects. This top level project does not have issues (Issue tracking is not enabled in the project settings).
I am trying to figure out a way for the Python api to detect this. Right now, when my code (which is scanning for issue counts) is going through the projects... | [
"How about\ntry:\n # code assuming issues are enabled\nexcept redminelib.exceptions.ForbiddenError:\n # code to execute for projects where issues are disabled\n\n",
"The list of enabled modules for a project can be fetched from the projects API. With your existing code, you can use e.g.\nredmine = Redmine('... | [
0,
0
] | [] | [] | [
"python",
"redmine"
] | stackoverflow_0074364666_python_redmine.txt |
Q:
Unable to download attachments from outlook using Python || Python 3.10
I am trying to download an attachment from outlook with a specific Subject line. It shows finished, but no attachment is getting downloaded. Below attached is my code, kindly help if I am missing something.
# import libraries
import win32com.c... | Unable to download attachments from outlook using Python || Python 3.10 | I am trying to download an attachment from outlook with a specific Subject line. It shows finished, but no attachment is getting downloaded. Below attached is my code, kindly help if I am missing something.
# import libraries
import win32com.client
import re
import datetime
import pathlib2 as pathlib
# set up connect... | [
"First, you need to make sure that a valid file path is passed to the SaveAsFile method of the Attachment class:\nattachment.SaveASFile(pathlib.path + 'C:\\\\Users\\\\UserTest\\\\Desktop\\\\Folder\\\\Subject Line\\\\Nov' + attachment_name)\n\nMake sure the folder exists on the disk and the file name doesn't contain... | [
0,
0
] | [] | [] | [
"email_attachments",
"office_automation",
"outlook",
"python",
"win32com"
] | stackoverflow_0074356466_email_attachments_office_automation_outlook_python_win32com.txt |
Q:
Groupby sum and count on multiple columns in python
I have a pandas dataframe that looks like this
ID country month revenue profit ebit
234 USA 201409 10 5 3
344 USA 201409 9 7 2
532 UK 201410 20 10 5
129 Canada 201411 15 ... | Groupby sum and count on multiple columns in python | I have a pandas dataframe that looks like this
ID country month revenue profit ebit
234 USA 201409 10 5 3
344 USA 201409 9 7 2
532 UK 201410 20 10 5
129 Canada 201411 15 10 5
I want to group by ID, country, month an... | [
"It can be done using pivot_table this way:\n>>> df1=pd.pivot_table(df, index=['country','month'],values=['revenue','profit','ebit'],aggfunc=np.sum)\n>>> df1 \n ebit profit revenue\ncountry month \nCanada 201411 5 10 15\nUK 201410 5 10 20\n... | [
27,
17,
6,
1
] | [] | [] | [
"pandas",
"pandas_groupby",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0048768650_pandas_pandas_groupby_python_python_2.7_python_3.x.txt |
Q:
Detecting the volume/overlap region in image registration for OCT data
I am working on image registration of OCT data. I would like to locate the regions/area in my targeted registered image, where image registration has actually occurred from the source images. I am working in Python. Can anyone please tell me wh... | Detecting the volume/overlap region in image registration for OCT data | I am working on image registration of OCT data. I would like to locate the regions/area in my targeted registered image, where image registration has actually occurred from the source images. I am working in Python. Can anyone please tell me what are the available techniques?
Any suggestions on how to proceed with the ... | [
"Image differentiation technique can be used to identify the registered area in the images by comparing it with base images. In this way, the different areas will be recognized.\n"
] | [
0
] | [] | [] | [
"image",
"image_processing",
"pycharm",
"python",
"registration"
] | stackoverflow_0065575001_image_image_processing_pycharm_python_registration.txt |
Q:
Jetson AGX Xavier python3 matplotlib 3.3.4 installation error
I want to use yolov5 at my Jetson AGX Xavier developer kit and I have to upgrade matplotlib to version 3.3.4 highest version that python3.6 support. I'm using python version 3.6.9(default of Jetson AGX Xavier) and python3.6 support matplotlib version 3.... | Jetson AGX Xavier python3 matplotlib 3.3.4 installation error | I want to use yolov5 at my Jetson AGX Xavier developer kit and I have to upgrade matplotlib to version 3.3.4 highest version that python3.6 support. I'm using python version 3.6.9(default of Jetson AGX Xavier) and python3.6 support matplotlib version 3.3.4. But I CANNOT upgrade that over 2.1.1(and this version is defau... | [
"I solved this problem!!!!\nThis line was added to bashrc and the problem was solved.\n\nexport OPENBLAS_CORETYPE=ARMV8 python3\n\n",
"It seems that your python packages have broken, There can be two ways to install matplotlib\nWay-1: Try to install matplotlib in venv\nWay-2: Uninstall python and then reinstall p... | [
1,
0,
0
] | [] | [] | [
"jetson_xavier",
"matplotlib",
"nvidia_jetson",
"python",
"python_3.x"
] | stackoverflow_0071000696_jetson_xavier_matplotlib_nvidia_jetson_python_python_3.x.txt |
Q:
django-filter AssertionError: Cannot filter a query once a slice has been taken
I'm using Django-filter ,I want to slice the rows ,just want the first 75 row:
def hist_view_render(request):
all_obj = RunStats.objects.all().order_by('-create_dttm')[:75]
hist_filter = RunStatsFilter(request.GET, queryset=al... | django-filter AssertionError: Cannot filter a query once a slice has been taken | I'm using Django-filter ,I want to slice the rows ,just want the first 75 row:
def hist_view_render(request):
all_obj = RunStats.objects.all().order_by('-create_dttm')[:75]
hist_filter = RunStatsFilter(request.GET, queryset=all_obj)
paginator= Paginator(hist_filter.qs, 15)
page = request.GET.get('page'... | [
"The issue occurs when the paginator slices the queryset to get the object list for the page. You can pass a list to the paginator instead so that the slice does not raise the error\nall_obj = RunStats.objects.all().order_by('-create_dttm')\nhist_filter = RunStatsFilter(request.GET, queryset=all_obj)\npaginator = ... | [
1
] | [] | [] | [
"django",
"django_filter",
"django_queryset",
"django_views",
"python"
] | stackoverflow_0074379963_django_django_filter_django_queryset_django_views_python.txt |
Q:
Nested generator vs nested list comprehension inside generator
I have 2 generators. One has a nested generator, and the other has a nested list comprehension.
// list of variables
variables = []
nestedGen = (x for x in (y for y in variables))
nestedList = (x for x in [y for y in variables])
Both generators can b... | Nested generator vs nested list comprehension inside generator | I have 2 generators. One has a nested generator, and the other has a nested list comprehension.
// list of variables
variables = []
nestedGen = (x for x in (y for y in variables))
nestedList = (x for x in [y for y in variables])
Both generators can be simplified to remove nesting, but are they identical in terms of f... | [
"There's a difference if variables gets modified.\nReassigning variables won't do anything, because both versions retrieve variables up front. The first for target in a genexp is evaluated immediately, unlike the rest of the genexp. For nestedList, that means evaluating the list comprehension immediately. For neste... | [
0,
0
] | [] | [] | [
"generator",
"list_comprehension",
"python"
] | stackoverflow_0074379974_generator_list_comprehension_python.txt |
Q:
Is there a way to access what help() prints and set it to a variable?
For example I am using pymeasure and would like to create a way for a user to check weather the device they want to use is accessible in pymeasure. rather than accessing the docstring i want to access the list of packages in the module that help... | Is there a way to access what help() prints and set it to a variable? | For example I am using pymeasure and would like to create a way for a user to check weather the device they want to use is accessible in pymeasure. rather than accessing the docstring i want to access the list of packages in the module that help prints. to do this i want do:
print(help("pymeasure.instruments"))
which o... | [
"Reading through the source code of the help() function, it looks like it uses pkgutil.iter_modules() to find the modules which are part of pymeasure.instruments, and generate that help file.\nHere's how to get all of the submodules of a module.\nimport pkgutil\nmodule = pymeasure.instruments\nprint([pkg.name for p... | [
0
] | [] | [] | [
"nonetype",
"python",
"python_3.x",
"return_type",
"types"
] | stackoverflow_0074379759_nonetype_python_python_3.x_return_type_types.txt |
Q:
Python Black for Atom not formatting on Apple M1 chip
I have a pretty simple file I'm trying to reformat, itsadate.py, and when I run the command black itsadate.py from a terminal I get the following error
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/black/__i... | Python Black for Atom not formatting on Apple M1 chip | I have a pretty simple file I'm trying to reformat, itsadate.py, and when I run the command black itsadate.py from a terminal I get the following error
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/black/__init__.cpython-310-darwin.so, 0x0002
): tried: '/Library/Fra... | [
"I've solve this problem. Here is my solution, maybe it helps someone.\nI've migrated from Mac Intel to Mac M1, and I've migrated all my projects.\nI've used black library in prehook.\nThe problem was in Intel .venv/ and incorrect paths to intel lib. Commit prehook has tried to use M1 libraries:\nImportError: dlope... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0071429418_python.txt |
Q:
I would like to append different values to a dictionary with multiple keys
I have my array with data referring to different subjects divided in 3 different groups
A = ([12, 13, 15], [13, 16, 18], [15, 15, 17])
I want to append these to 3 different arrays, but I don't want to do it "manually" since I should use thi... | I would like to append different values to a dictionary with multiple keys | I have my array with data referring to different subjects divided in 3 different groups
A = ([12, 13, 15], [13, 16, 18], [15, 15, 17])
I want to append these to 3 different arrays, but I don't want to do it "manually" since I should use this code for bigger set of data.
So, I was looking for a way to create as many arr... | [
"I'mahdi had already suggested dict-comprehension to build the correct list in first place. In addition, you can use enumerate to iterate all elements a with index i of the tuple A:\ngroups = {\n f\"group{i+1}\": a\n for i, a in enumerate(A)\n}\n\nAs Rolf of Saxony pointed out, enumerate has an optional start... | [
1,
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074379933_dictionary_list_python.txt |
Q:
pyautogui does not work with python3.10, but works well with python3.8 on ubuntu20.04
On a machine with Ubuntu20.04 (description Ubuntu 20.04.4 LTS, Codename: focal) and python3.8.11 I've installed pyautogui, and it works well. But on a machine with Ubuntu22.04 (description Ubuntu 22.04 LTS, Codename: jammy) and p... | pyautogui does not work with python3.10, but works well with python3.8 on ubuntu20.04 | On a machine with Ubuntu20.04 (description Ubuntu 20.04.4 LTS, Codename: focal) and python3.8.11 I've installed pyautogui, and it works well. But on a machine with Ubuntu22.04 (description Ubuntu 22.04 LTS, Codename: jammy) and python3.10.4 pyautogui does not work, because pyautogui.position() does not show the correct... | [
"I am also searching for a solution to this issue and this is what I have found.\n\nTry restarting your system after installing pyautogui.\nTry using just one monitor.\n\nThanks,\nRahul\n"
] | [
0
] | [] | [] | [
"pyautogui",
"python",
"ubuntu_20.04"
] | stackoverflow_0073171220_pyautogui_python_ubuntu_20.04.txt |
Q:
BeautifulSoup Python .text method doesn't return proper text
I'm trying to scrape soccer results from a website. I get the results with the html and when I try to remove them with .text I get strange output. I use the parent method to get the parent HTML element for the whole score.
The scraper script:
res... | BeautifulSoup Python .text method doesn't return proper text | I'm trying to scrape soccer results from a website. I get the results with the html and when I try to remove them with .text I get strange output. I use the parent method to get the parent HTML element for the whole score.
The scraper script:
response = requests.get(url)
html_soup = BeautifulSoup(respon... | [
"To get rid of the blank space, I recommend you do something like this:\nfor result in results:\n chosen_team_results.append(''.join(str(result.parent.text).split()))\nprint(chosen_team_results)\n\n",
"You can add a .strip() method to the string/text so it displays only the text without the \\r\\n\\t\\t\\t (li... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0057180239_beautifulsoup_html_python.txt |
Q:
How to check if a word is in a list that is in another function?
To put it simply, I was given a .txt file with a list of words in it, then asked to read it in python and store it in a list with a function. So far, no problem. I wrote something that looks like this:
def load_lexicon():
with open("lexicon.txt"... | How to check if a word is in a list that is in another function? | To put it simply, I was given a .txt file with a list of words in it, then asked to read it in python and store it in a list with a function. So far, no problem. I wrote something that looks like this:
def load_lexicon():
with open("lexicon.txt", "r") as f:
content_list = f.read().splitlines()
lex... | [
"First you open the file and read the contents as content_list then you make another file handle called lexique. So you never actually do anything with the file contents. Additionally as @quamrana mentions you would need to either iterate through each word on each line or use extends to add them to your list otherw... | [
0,
0
] | [] | [] | [
"function",
"list",
"python",
"python_3.x"
] | stackoverflow_0074375491_function_list_python_python_3.x.txt |
Q:
If heapq.heapify(list) is O(N) and list.sort() is O(NlogN) then why isn't the default sort algorithm heapify?
If I have a list and need to sort it, is there a good reason to use list.sort() over heapq.heapify(list), given that heapify is O(N) (link) and .sort() is O(NlogN)?
Why isn't the default sort algorithm hea... | If heapq.heapify(list) is O(N) and list.sort() is O(NlogN) then why isn't the default sort algorithm heapify? | If I have a list and need to sort it, is there a good reason to use list.sort() over heapq.heapify(list), given that heapify is O(N) (link) and .sort() is O(NlogN)?
Why isn't the default sort algorithm heapify if heapify is faster?
| [
"as guys have said in the comment section, \"heapify\" rearranges elements of the list to form a heap-oriented binary tree. complete binary trees can be represented using arrays or in other words, any array which is fully filled with comparable values can be logically viewed as a complete binary tree.\nby definitio... | [
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074379603_python_sorting.txt |
Q:
how to add space after every word and separate digits from word?
here is my string
text = 'EffectsRelaxed96% VotedHappy79% VotedEuphoric67% Voted'
I tried this:
add_space_after_word = re.sub(r"(\w)([A-Z])", r"\1 \2", text)
>>>'Effects Relaxed96% Voted Happy79% Voted Euphoric67% Voted'
seperate_digites_from_words... | how to add space after every word and separate digits from word? | here is my string
text = 'EffectsRelaxed96% VotedHappy79% VotedEuphoric67% Voted'
I tried this:
add_space_after_word = re.sub(r"(\w)([A-Z])", r"\1 \2", text)
>>>'Effects Relaxed96% Voted Happy79% Voted Euphoric67% Voted'
seperate_digites_from_words = 'Effects Relaxed96% Voted Happy79% Voted Euphoric67% Voted'
re.sub(... | [
"You can use\nimport re\ntext = 'EffectsRelaxed96% VotedHappy79% VotedEuphoric67% Voted'\nprint( re.sub(r'([a-z])([A-Z0-9])', r'\\1 \\2', text).replace(\"Effects\", \"Effects:\").replace(\"Voted\", \"Voted,\").rstrip(',') )\n# => Effects: Relaxed 96% Voted, Happy 79% Voted, Euphoric 67% Voted\n\nSee the Python code... | [
2
] | [] | [] | [
"python",
"python_3.x",
"python_re",
"regex"
] | stackoverflow_0074379968_python_python_3.x_python_re_regex.txt |
Q:
Is there a way to randomly generate groups of numbers so that each number is repeated the same amount of times but only in any given group once?
Sorry for the long title, but I'm not sure how to shorten it. I'm trying to program an object that targets other objects. Each object is assigned an integer id starting f... | Is there a way to randomly generate groups of numbers so that each number is repeated the same amount of times but only in any given group once? | Sorry for the long title, but I'm not sure how to shorten it. I'm trying to program an object that targets other objects. Each object is assigned an integer id starting from 0, and that's all that's really relavent here. I can access objects by id, so I jsut need to get the numbers. Each object should target the same a... | [
"Randomized via index as opposed to actual parameter, while it isn't the most random it might still count.\n# import library\nimport random\n\n# input parameters\nrange_ = 9\nrepeats = 4\n\n# rotate array elements\ndef rotate(input, n):\n return input[n:] + input[:n]\n\n# shifts for shuffleing, as they are all d... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074354875_python.txt |
Q:
PackageNotInstalledError: Package is not installed in prefix
conda update conda >> successful
conda update anaconda >> gives me error saying package is not installed in prefix.
I have single installation of Python distribution on my system. How do I solve this issue?
(base) C:\Users\asukumari>conda info
active e... | PackageNotInstalledError: Package is not installed in prefix | conda update conda >> successful
conda update anaconda >> gives me error saying package is not installed in prefix.
I have single installation of Python distribution on my system. How do I solve this issue?
(base) C:\Users\asukumari>conda info
active environment : base
active env location : C:\Users\asukumari\AppDat... | [
"Usually this error, \"PackageNotInstalledError: Package is not installed in prefix.\" is because your custom environment doesn't have the conda infrastructure. Instead, it is in your base only. To update the base environment:\nconda update --name base conda\n\nTo see what version you have installed:\nconda list --... | [
72,
22,
6,
4,
3,
3,
1,
0,
0
] | [
"This works for me:\nsource active <your python env>\n\n"
] | [
-5
] | [
"anaconda",
"conda",
"python",
"python_3.x",
"windows"
] | stackoverflow_0051712693_anaconda_conda_python_python_3.x_windows.txt |
Q:
ImportError: No module named jinja2
Using google-app-engine tutorial, I got the following error stack message:
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 239, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandle... | ImportError: No module named jinja2 | Using google-app-engine tutorial, I got the following error stack message:
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 239, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files (x86)\Google\... | [
"In order to use Jinja locally, you need to install it locally\neasy_install Jinja2\n\nor \npip install Jinja2\n\n",
"Need to restart application in AEL.\nThe application in Google App Engine Launcher must be restarted for new library calls to be taken into account.\nI was mislead by the fact all other changes do... | [
32,
7,
5,
4,
0,
0,
0,
0
] | [] | [] | [
"google_app_engine",
"python",
"python_2.7"
] | stackoverflow_0018944345_google_app_engine_python_python_2.7.txt |
Q:
Why is junk data appearing in my Python's subprocess stdout?
I'm writing a Python app that runs a command on an AWS remote docker container, and saves the output to a file. The command that is being run remotely is generating binary data (a database dump).
The app works great if I start the download and don't touc... | Why is junk data appearing in my Python's subprocess stdout? | I'm writing a Python app that runs a command on an AWS remote docker container, and saves the output to a file. The command that is being run remotely is generating binary data (a database dump).
The app works great if I start the download and don't touch anything. The issue I'm having is that if I start the download, ... | [
"When you don't specify what subprocess should do with stdin, it gets inherited from the parent process, letting the child see your enter keys, scroll-wheel data, etc.\nA typical noninteractive process won't do \"local echo\" of input back to output; but you're using --interactive here, so the behavior is not surpr... | [
1
] | [] | [] | [
"npyscreen",
"python",
"python_curses",
"subprocess"
] | stackoverflow_0074378607_npyscreen_python_python_curses_subprocess.txt |
Q:
how to integrate a composite function using scipy
I have two functions defined as integrals where the lower and upper limits are (0-1) and (0-10), respectively. I found out the scipy library and was trying to use it for this purpose. Below I am showing my functions.
f(x) = (p*x) dx
g(x) = alpha*(ln(f(x))) dx
I a... | how to integrate a composite function using scipy | I have two functions defined as integrals where the lower and upper limits are (0-1) and (0-10), respectively. I found out the scipy library and was trying to use it for this purpose. Below I am showing my functions.
f(x) = (p*x) dx
g(x) = alpha*(ln(f(x))) dx
I am trying to calculate the value of function g(x), but I... | [
"The problem is in secondMethod. Right now you're passing the function firstIntegral itself (functions are first class objects in Python). You need to call the function, i.e. put parentheses after its name and pass in any arguments it needs.\nFor example, you could change your secondMethod to this:\ndef secondMetho... | [
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0074380172_python_scipy.txt |
Q:
How turn data into bar chart?
I'm struggling with how to turn the result of my code into a bar chart.
Code:
Result:
tried unsuccessfully add data to a dataframe
A:
May be you can use matplotlib.pyplot and from that import plt. To create a bar chart use plt.bar function.
| How turn data into bar chart? | I'm struggling with how to turn the result of my code into a bar chart.
Code:
Result:
tried unsuccessfully add data to a dataframe
| [
"May be you can use matplotlib.pyplot and from that import plt. To create a bar chart use plt.bar function.\n"
] | [
0
] | [] | [] | [
"graph",
"hierarchical_clustering",
"python"
] | stackoverflow_0074380288_graph_hierarchical_clustering_python.txt |
Q:
Adding Up str input
Im getting an error saying I cant multiply sequences by non-int of type(str) which is confusing me because all I wanted to do is multiply the 2 str(input)'s together, I tried finding resources on the internet and nothing to be seen.
length = str(input("Enter length (cm): "))
width = str(input("... | Adding Up str input | Im getting an error saying I cant multiply sequences by non-int of type(str) which is confusing me because all I wanted to do is multiply the 2 str(input)'s together, I tried finding resources on the internet and nothing to be seen.
length = str(input("Enter length (cm): "))
width = str(input("Enter the width (cm):"))
... | [
"What you did wrong is that you are trying to multiply strings and not integers, when getting input, stored value is a string. You need integers for this task so convert input to int with simple int(input()).\nHere is the code that you need to use:\ndef main():\n try:\n length = int(input(\"Enter the leng... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074380281_python.txt |
Q:
How to list time series data
I have data with timestamps. I want to list the data in chronologically, but for each "id" separately. So, put timestamps in ascending order for id=2. When the last id=2 entry is reached, start listing id=3 entries,etc.
Data:
df
timestamp id value
2022-10-10 00:00 2 221... | How to list time series data | I have data with timestamps. I want to list the data in chronologically, but for each "id" separately. So, put timestamps in ascending order for id=2. When the last id=2 entry is reached, start listing id=3 entries,etc.
Data:
df
timestamp id value
2022-10-10 00:00 2 221
2022-10-10 00:00 3 189
2022... | [
"you can achieve this using groupby and sort_values.\ndf = df.groupby(['id'])\nsorted_df = df.apply(lambda x: x.sort_values(ascending=False))\n\nIf you are only interested in the top values, you can play around with .head() functions as well.\nGood luck!\n"
] | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074379796_dataframe_pandas_python.txt |
Q:
How to ensure that the timezone is entered in the ISO UTC format within the request body?
I am using pydantic within FastAPI and I need to ensure that the timestamp is always entered in the UTC ISO format such as 2015-09-01T16:09:00:000Z.
from typing import Optional
from fastapi import FastAPI
from pydantic import... | How to ensure that the timezone is entered in the ISO UTC format within the request body? | I am using pydantic within FastAPI and I need to ensure that the timestamp is always entered in the UTC ISO format such as 2015-09-01T16:09:00:000Z.
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel, Field
from datetime import datetime
app = FastAPI()
measurements = [
{
... | [
"Import re\nimport re\n\nDeclare the regular expression\ntimestamp_regex = r'[0-9]{4}-[0-9]{2}-[0-9]{2}T([0-9]{2}:){3}[0-9]{3}Z'\n\nCheck the parameter (note that this assumes m is a valid dictionary)\n@app.post(\"/measurements\")\nasync def create_measurement(m: MeasurementIn, response: Response):\n if bool(re.ma... | [
1
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0074379605_fastapi_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.