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:
Find the possible states to make the result of the Bitwise OR answer
For example if you have a1 | a2 = 0011 so the possible states for a1 and a2 are => result = [ (0000,0011) , (0001,0010) , (0001,0011) ]
and a1 < a2.
Our numbers are not necessarily 4-bit, they can be more.
I mean, you have the answer of Bitwise O... | Find the possible states to make the result of the Bitwise OR answer | For example if you have a1 | a2 = 0011 so the possible states for a1 and a2 are => result = [ (0000,0011) , (0001,0010) , (0001,0011) ]
and a1 < a2.
Our numbers are not necessarily 4-bit, they can be more.
I mean, you have the answer of Bitwise OR and you are looking for all possible states for a2, a1 (in binary).
Coul... | [
"If I understand you right, the following itertools-based solution should work:\nfrom itertools import product\n\ndef or_factors(bits):\n bit_pairs = [[('0','0')] if i == '0' else [('0','1'),('1','0'),('1','1')] for i in bits]\n num_pairs = product(*bit_pairs)\n factors = []\n for pair in num_pairs:\n ... | [
1,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0074239800_math_python.txt |
Q:
Pandas dataframe total row
I have a dataframe, something like:
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c 2 1.62
3 d 9 1.41
4 e 3 0.58
and I would like to add a 'total' row to the end of dataframe:
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c ... | Pandas dataframe total row | I have a dataframe, something like:
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c 2 1.62
3 d 9 1.41
4 e 3 0.58
and I would like to add a 'total' row to the end of dataframe:
foo bar qux
0 a 1 3.14
1 b 3 2.72
2 c 2 1.62
3 d 9 1.41
4 ... | [
"Update June 2022\npd.append is now deprecated. You could use pd.concat instead but it's probably easier to use df.loc['Total'] = df.sum(numeric_only=True), as Kevin Zhu commented. Or, better still, don't modify the data frame in place and keep your data separate from your summary statistics!\n\nAppend a totals row... | [
82,
72,
50,
24,
9,
6,
5,
5,
3,
2,
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0021752399_pandas_python.txt |
Q:
PIP: Installing only the dependencies
I have a script that creates a virtualenv, installs distribute and pip in it and then optionally clones a git repo.
Now I have the project I will be working on, installed. But its dependencies are not installed. How can I make pip install all the dependencies as if I have issu... | PIP: Installing only the dependencies | I have a script that creates a virtualenv, installs distribute and pip in it and then optionally clones a git repo.
Now I have the project I will be working on, installed. But its dependencies are not installed. How can I make pip install all the dependencies as if I have issued a pip install MyApp?
EDIT: Appareantly m... | [
"If your dependencies are defined in the setup.py file, you can first dump them to an external file using:\npython setup.py egg_info\n\nThis will list all your dependencies in YOUR_PROJECT.egg-info/requires.txt file. Then you can install them using pip:\npip install -r *.egg-info/requires.txt\n\nto delete what you ... | [
25,
15,
4,
1,
1
] | [] | [] | [
"distribute",
"pip",
"python",
"virtualenv"
] | stackoverflow_0002317410_distribute_pip_python_virtualenv.txt |
Q:
How can I update my data automatically in Kivy?
I have a code block in my class
def datas(self):
source = requests.get("http://150.150.150.150/tek.json").json()
return source
My program uses this data and this data is updated in that server everyday at 12:05 AM.
When i run app at 12:... | How can I update my data automatically in Kivy? | I have a code block in my class
def datas(self):
source = requests.get("http://150.150.150.150/tek.json").json()
return source
My program uses this data and this data is updated in that server everyday at 12:05 AM.
When i run app at 12:00 and if i wait untill 12:10 the datas is not update... | [
"I think in this case what could be helpful is an asyncio library. It would the While True loop to run every 10 seconds without freezing the whole program.\nHere is an example:\nhttps://github.com/kivy/kivy/blob/master/examples/async/asyncio_basic.py?fbclid=IwAR0Ae1UhdZL57ytHdVzpXYiPUnxE1c5si6RWnYQjo5l_N-Wm3MTNbGJD... | [
0,
0
] | [] | [] | [
"kivy",
"kivy_language",
"kivymd",
"python",
"python_3.x"
] | stackoverflow_0074191357_kivy_kivy_language_kivymd_python_python_3.x.txt |
Q:
How do I create new lists dynamically and add these multiple lists inside a parent list as a value in a dictionary?
I need to create a Panda Data frame for Pokémon's using a dictionary which needs to contain the attribute name (Ex: such as "height" of Chameleon and Charmander) as the key and the respective value (... | How do I create new lists dynamically and add these multiple lists inside a parent list as a value in a dictionary? | I need to create a Panda Data frame for Pokémon's using a dictionary which needs to contain the attribute name (Ex: such as "height" of Chameleon and Charmander) as the key and the respective value (Ex: Height value of Chameleon and Charmander as 11 and 6) as the value.
To start with, my code needs to have multiple lis... | [
"One way to make each entry in the type array a list by using a list comprehension as follows:\nimport requests\nimport json\nimport pandas as pd\n\npokemons = [\"bulbasaur\" ,\"charmeleon\",\"charmander\"]\nname, height, weight, types_l = [],[],[],[]\n\n\nfor pokemon in pokemons:\n res = requests.get(f\"https://... | [
0,
0
] | [] | [] | [
"api",
"python"
] | stackoverflow_0074240463_api_python.txt |
Q:
Script to extract links from page and check the domain
I'm trying to write a script that iterates through a list of web pages, extracts the links from each page and checks each link to see if the are in a given set of domains. I have the script set up to write two files - pages with links in the given domains are ... | Script to extract links from page and check the domain | I'm trying to write a script that iterates through a list of web pages, extracts the links from each page and checks each link to see if the are in a given set of domains. I have the script set up to write two files - pages with links in the given domains are written to one file while the rest are written to the other.... | [
"There are some very basic problems with your code:\n\nif invalid == None is missing a : at the end, but should also be if invalid is None:\nnot all <a> elements will have an href, so you need to deal with those, or your script will fail.\nthe regex has some issues (you probably don't want to repeat that first URL ... | [
0
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074240507_python_web_scraping.txt |
Q:
Accessing Tasks with Graph API
I am currently trying to access my microsoft task from a python application by using the following code:
client = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential=client_secret)
# First, try to lookup an access token in cache
token_result = client... | Accessing Tasks with Graph API | I am currently trying to access my microsoft task from a python application by using the following code:
client = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential=client_secret)
# First, try to lookup an access token in cache
token_result = client.acquire_token_silent(scope, account... | [
"Application permissions are not supported for To Do Tasks requests at this moment, you need delegated permissions: https://learn.microsoft.com/en-us/graph/api/todo-list-lists?view=graph-rest-beta&tabs=http\n"
] | [
0
] | [] | [] | [
"microsoft_graph_api",
"python"
] | stackoverflow_0074239992_microsoft_graph_api_python.txt |
Q:
Make a list of lists from another by making successive subtractions of their rows
In my program I get a list that contains an indefinite number of lists, each of these having 4 elements.
Example:
List=[[70,70,70,70],[1,1,1,1],[2,2,2,2],[4,4,4,4]]
I would like by means of a function to be able to subtract the valu... | Make a list of lists from another by making successive subtractions of their rows | In my program I get a list that contains an indefinite number of lists, each of these having 4 elements.
Example:
List=[[70,70,70,70],[1,1,1,1],[2,2,2,2],[4,4,4,4]]
I would like by means of a function to be able to subtract the values and have the result instead.
Resulting:
Result_List=[[70,70,70,70],[69,69,69,69],[67... | [
"You can use the following code:\nList = [[70,70,70,70],[1,1,1,1],[2,2,2,2],[4,4,4,4]]\nresult = [List[0]] # add the first element since it doesn't change\n\nfor sub_list in List[1:]: # for each element omitting the first one\n result.append(\n [\n # subtract the current element of List (iterat... | [
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074240549_list_python.txt |
Q:
CSV forgetting some columns when added to ArcGIS Pro
In the first photo []. I have all the columns I have desired (which the example I will talking about is Project Scope) in an Excel CSV file. When I go to add the the CSV into ArcPro (second photo) ArcGIS Pro drops the Project Scope column for some reason and it ... | CSV forgetting some columns when added to ArcGIS Pro | In the first photo []. I have all the columns I have desired (which the example I will talking about is Project Scope) in an Excel CSV file. When I go to add the the CSV into ArcPro (second photo) ArcGIS Pro drops the Project Scope column for some reason and it should be in between the Project Phase column and the Cons... | [
"Project scope has line breaks within. I bet that is causing problems. Look at the actual csv file you are trying to load in a text editor.\n"
] | [
0
] | [] | [] | [
"arcgis",
"csv",
"list",
"pandas",
"python"
] | stackoverflow_0074240683_arcgis_csv_list_pandas_python.txt |
Q:
How to manually adjust index in dbf python package?
I am looking for a way to manually adjust the index when walking through dbf files using Ethan Furman's dbf package for Python. My current issue is the program that generated the original files had a bad habit of adding a row at the end of the file with all space... | How to manually adjust index in dbf python package? | I am looking for a way to manually adjust the index when walking through dbf files using Ethan Furman's dbf package for Python. My current issue is the program that generated the original files had a bad habit of adding a row at the end of the file with all spaces for every entry.
I am trying to find a way to detect th... | [
"There is nothing built in to dbf as empty records are unusual. A bit of custom code should solve the problem, though:\ndef is_empty_rec(rec):\n # 'empty' means all fields are blank/False/0\n return any(bool(fld) for fld in rec)\n\ndef last_nonempty_index(table):\n # 'table' can also be a list\n i = le... | [
0
] | [] | [] | [
"database",
"dbf",
"indexing",
"python"
] | stackoverflow_0074237126_database_dbf_indexing_python.txt |
Q:
How to access widget class id from different class in kivy
Am trying to figure out how to make button in ScreenTwo class access a function found in ScreenOne class
This is hot-reload main.kv :
from kivymd.app import MDApp
from kaki.app import App
from kivy.factory import Factory
from kivy.uix.widget import Widget... | How to access widget class id from different class in kivy | Am trying to figure out how to make button in ScreenTwo class access a function found in ScreenOne class
This is hot-reload main.kv :
from kivymd.app import MDApp
from kaki.app import App
from kivy.factory import Factory
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager, Screen
import... | [
"To access the properties of ScreenOne from within ScreenTwo, you can use:\nself.manager.get_screen('screen_one').<property_name>\n"
] | [
0
] | [] | [] | [
"kivy",
"kivy_language",
"kivymd",
"python"
] | stackoverflow_0074168671_kivy_kivy_language_kivymd_python.txt |
Q:
plt.imshow() not working in pycharm due to matplotlib not having a framework
import cv2
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import Image
Image(filename='test2.png')
# Returns numpy 2D array
cb_img = cv2.imread("test2.png")
# Print size of image:
print("Image size is: ", cb_im... | plt.imshow() not working in pycharm due to matplotlib not having a framework | import cv2
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import Image
Image(filename='test2.png')
# Returns numpy 2D array
cb_img = cv2.imread("test2.png")
# Print size of image:
print("Image size is: ", cb_img.shape)
# Print data type of image:
print("Data type of image is: ", cb_img.dty... | [
"I've had this same issue. The only solution I found was to downgrade matplotlib to 3.5.3. Here's how to do this: https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html#packages-tool-window\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pycharm",
"python"
] | stackoverflow_0074048023_matplotlib_pycharm_python.txt |
Q:
Python pickling and unpickling numpy array?
I have the following dilemma. I am trying to pickle and then unpickle a numpy array that represents an image.
Executing this code:
a1 = np.zeros((1080, 1920, 3), dtype=np.uint8)
print(sys.getsizeof(a1), a1.shape)
a2 = pickle.dumps(a1)
print(sys.getsizeof(a2), type(a2))
... | Python pickling and unpickling numpy array? | I have the following dilemma. I am trying to pickle and then unpickle a numpy array that represents an image.
Executing this code:
a1 = np.zeros((1080, 1920, 3), dtype=np.uint8)
print(sys.getsizeof(a1), a1.shape)
a2 = pickle.dumps(a1)
print(sys.getsizeof(a2), type(a2))
a3 = pickle.loads(a2)
print(sys.getsizeof(a3), a... | [
"From the sys.getsizeof docs:\n\nReturn the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.\n\nEmphasis mine. Basically there's no guarantee that sys.g... | [
0,
0,
0
] | [] | [] | [
"numpy",
"pickle",
"python",
"serialization"
] | stackoverflow_0074228918_numpy_pickle_python_serialization.txt |
Q:
Discord.py Button responses interaction failed after 3 min
The button doesn't respond if no one has clicked it in 3 minutes.
I saw that it was something with timeout but I don't know where to place it.
My code:
#Tickets
class Menu(discord.ui.View):
def __init__(self):
super().__init__()
self.va... | Discord.py Button responses interaction failed after 3 min | The button doesn't respond if no one has clicked it in 3 minutes.
I saw that it was something with timeout but I don't know where to place it.
My code:
#Tickets
class Menu(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label=" Ticket", style=discor... | [
"You can set the timeout value like this:\nclass Menu(discord.ui.View):\n def __init__(self):\n super().__init__(timeout=180) # Timeout value in seconds\n self.value = None\n\nIf you set it to None, it will never time out, until you restart your bot.\nIf you want the view to persist between bot res... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074240607_discord_discord.py_python.txt |
Q:
Unable to access public url from Google Cloud Platform
I am trying to access a public url from the Google Cloud Platform. But each time, I am getting connection timeout error. That URL is very well opening in my browsers and on different network as well. I am using Python to make a POST request to this URL and loc... | Unable to access public url from Google Cloud Platform | I am trying to access a public url from the Google Cloud Platform. But each time, I am getting connection timeout error. That URL is very well opening in my browsers and on different network as well. I am using Python to make a POST request to this URL and locally it is working fine. I don't know if need to set some se... | [
"as mentioned here How to access websites that have ip block on GCP\nBy default, a Cloud Run service connects to external endpoints on the internet using a dynamic IP address pool.Which is problematic if you want to access an external website that requires connections originating from a static IP address, such as a... | [
0
] | [] | [] | [
"google_app_engine",
"google_cloud_platform",
"python",
"web_services"
] | stackoverflow_0052329155_google_app_engine_google_cloud_platform_python_web_services.txt |
Q:
How do I add a vector into a specific row of a matrix?
I have a matrix and I want to add a vector into the fourth row of the matrix. I am using vstack but I am having trouble figuring out how to input it as the fourth row. If I input the new vector as either the first or second argument, it will add the vector as ... | How do I add a vector into a specific row of a matrix? | I have a matrix and I want to add a vector into the fourth row of the matrix. I am using vstack but I am having trouble figuring out how to input it as the fourth row. If I input the new vector as either the first or second argument, it will add the vector as the first or last row of them matrix. Here is my example:
A... | [
"I think this should do it. Likely read the docs to get clarification, but this seemed to work.\nB = np.vstack([A, (10,3,5,3,6)])\n\nfor some reason the order mattered, of course I did not read enough to give more.\n"
] | [
2
] | [] | [] | [
"matrix",
"numpy",
"python",
"vstack"
] | stackoverflow_0074240635_matrix_numpy_python_vstack.txt |
Q:
How to serve response in django then down the server
I need a advice
I want create a path in django for example /stop-server
When somebody send a request to /stop-server server return a response and then become killed
What's your proposal?.........
A:
You can use the os module to kill the process.
import os
d... | How to serve response in django then down the server | I need a advice
I want create a path in django for example /stop-server
When somebody send a request to /stop-server server return a response and then become killed
What's your proposal?.........
| [
"You can use the os module to kill the process.\nimport os\n\ndef stop_server(request):\n os.kill(os.getpid(), 9)\n\nYou can send a response before killing the process.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074240826_django_python.txt |
Q:
Generating Custom JSON format output from pandas dataframe
I have a pandas Dataframe like this.
The dataframe data
date aid x_axis y_axis z_axis
0 2018-12-01 9.0 -0.71 8.75 5.23
1 2018-12-03 3.0 -0.55 10.13 1.15
2 2018-12-03 4.0 -1.84 4.56 5.74
3 2018-12-0... | Generating Custom JSON format output from pandas dataframe | I have a pandas Dataframe like this.
The dataframe data
date aid x_axis y_axis z_axis
0 2018-12-01 9.0 -0.71 8.75 5.23
1 2018-12-03 3.0 -0.55 10.13 1.15
2 2018-12-03 4.0 -1.84 4.56 5.74
3 2018-12-03 5.0 -1.49 4.11 7.03
4 2018-12-03 7.0 -0.40 ... | [
"Try:\nout = []\nfor d, g in df.groupby(\"date\"):\n out.append(\n {\n \"date\": d,\n }\n )\n for _, row in g.iterrows():\n out[-1][str(int(row[\"aid\"]))] = {\n \"mean\": {\n \"x_axis\": row[\"x_axis\"],\n \"y_axis\": row[\"y_axis\"]... | [
2
] | [] | [] | [
"dataframe",
"group_by",
"json",
"pandas",
"python"
] | stackoverflow_0074240716_dataframe_group_by_json_pandas_python.txt |
Q:
Colab automatically create directory
I am trying to implement a code on the CIFAR10 dataset. For each image of the dataset, I am to see if it is correctly classified or not and I want to save two images, for each of the images of the dataset.
One image is the original image and the other is the saliency map of tha... | Colab automatically create directory | I am trying to implement a code on the CIFAR10 dataset. For each image of the dataset, I am to see if it is correctly classified or not and I want to save two images, for each of the images of the dataset.
One image is the original image and the other is the saliency map of that image. For each image I want the structu... | [
"Use pathlib, like this:\nfrom pathlib import Path\n\nPath(baseLink).mkdir(parents=True, exist_ok=True)\n\nAnd please, snake_case. baseLink -> base_link, originalImage -> original_image, etc.\n"
] | [
2
] | [] | [] | [
"google_colaboratory",
"jupyter_notebook",
"python"
] | stackoverflow_0074240862_google_colaboratory_jupyter_notebook_python.txt |
Q:
VoiceState always returning None as 'channel' value
I'm messing around creating a discord bot, but the VoiceState objetcs that I get always have the channel value to None.
intents = discord.Intents(messages=True, voice_states=True)
client = discord.Client(intents=intents)
@client.event
async def on_voice_state_up... | VoiceState always returning None as 'channel' value | I'm messing around creating a discord bot, but the VoiceState objetcs that I get always have the channel value to None.
intents = discord.Intents(messages=True, voice_states=True)
client = discord.Client(intents=intents)
@client.event
async def on_voice_state_update(member, before, after):
print("Channel event", mem... | [
"To see the channels of a guild, you also need to enable the guilds intent, like this:\nintents = discord.Intents(messages=True, voice_states=True, guilds=True)\n\nHere is a list of all intents: https://discordpy.readthedocs.io/en/latest/api.html?highlight=intents#discord.Intents\nHope this helps.\n"
] | [
0
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0074239801_bots_discord_discord.py_python.txt |
Q:
Convert portion of Pandas dataframe into alternate layout
I have a dataframe in the following format:
Category
Date
Count
Comment
Blue
10/24
7
None
Red
10/25
10
None
Green
10/23
5
None
Red
10/24
2
None
Blue
10/23
3
None
Red
10/26
11
None
Green
10/26
3
None
I want to take the data out of that dataframe and... | Convert portion of Pandas dataframe into alternate layout | I have a dataframe in the following format:
Category
Date
Count
Comment
Blue
10/24
7
None
Red
10/25
10
None
Green
10/23
5
None
Red
10/24
2
None
Blue
10/23
3
None
Red
10/26
11
None
Green
10/26
3
None
I want to take the data out of that dataframe and convert it to a dataframe like this:
Catego... | [
"You want a pivot table:\ndf = pd.DataFrame(\n {\n 'Category': ['blue', 'red', 'green', 'red', 'blue', 'red', 'green'],\n 'Date': ['10/24', '10/25', '10/23', '10/24', '10/23', '10/26', '10/26'],\n 'Count': [7,10,5,2,3,11,3]\n }\n)\n\ndf.pivot(index='Category', values='Count', columns='Dat... | [
2,
1
] | [] | [] | [
"jinja2",
"pandas",
"python"
] | stackoverflow_0074240531_jinja2_pandas_python.txt |
Q:
Convert OpenCV video to Streamlit video in-memory
I have a list of image frames frames that I would like to be able to display in Streamlit application: st.video(frames_converted).
Challenges:
Streamlit takes HTML5 and video requires H264 encoding
Want to complete all processing in-memory (as opposed to the much ... | Convert OpenCV video to Streamlit video in-memory | I have a list of image frames frames that I would like to be able to display in Streamlit application: st.video(frames_converted).
Challenges:
Streamlit takes HTML5 and video requires H264 encoding
Want to complete all processing in-memory (as opposed to the much more common saving to temporary file
Current attempt:
... | [
"We may encode an \"in memory\" MP4 video using PyAV as described in my following answer - the video is stored in BytesIO object.\nWe may pass the BytesIO object as input to Streamlit (or convert the BytesIO object to bytes array and use the array as input).\n\nCode sample:\nimport numpy as np\nimport cv2 # OpenCV... | [
2
] | [] | [] | [
"opencv",
"python",
"streamlit"
] | stackoverflow_0074238426_opencv_python_streamlit.txt |
Q:
How to get POST body in ESP8266 micropython server
I am trying to create a simple Micropython project where when the microcontroller first turns on, if it is unsuccessful at connecting to wifi, it will begin to host an Access Point. When connected to the access point, the device serves a simple webpage that allows... | How to get POST body in ESP8266 micropython server | I am trying to create a simple Micropython project where when the microcontroller first turns on, if it is unsuccessful at connecting to wifi, it will begin to host an Access Point. When connected to the access point, the device serves a simple webpage that allows to user to enter their SSID and Passphrase, which are t... | [
"Once you have the client request in your buffer, you need to parse it to find the various pieces you're looking for. There are modules out there (like microdot on GitHub) that will do this for you with MicroPython. Or you can roll your own.\nIf you choose to do your own, it'll look something like this:\n def pa... | [
1
] | [] | [] | [
"esp8266",
"micropython",
"python"
] | stackoverflow_0073979557_esp8266_micropython_python.txt |
Q:
Does this parallel generator have problems in its implementations?
I'm new to multiprocessing and I'm trying to define a parallel generator to solve my problem; but I have some questions:
is mp.get_context('spawn') the most adequate for the job, provided that it will run on a node that has Red Hat 8.4 as OS, abou... | Does this parallel generator have problems in its implementations? | I'm new to multiprocessing and I'm trying to define a parallel generator to solve my problem; but I have some questions:
is mp.get_context('spawn') the most adequate for the job, provided that it will run on a node that has Red Hat 8.4 as OS, about 20 CPUs and 2 GPUs?
am I sure that the spawned processes will be close... | [
"Designing your own process pool may not be a good idea, instead you should rely on the existing implementation which should work just fine:\nfrom multiprocessing import Pool, Semaphore\nfrom time import sleep\nfrom random import random\n\n\ndef work(i: int):\n sleep(1 + random())\n print(f\"Processed value {... | [
0
] | [] | [] | [
"generator",
"python",
"python_multiprocessing"
] | stackoverflow_0074238975_generator_python_python_multiprocessing.txt |
Q:
How to get pod names from inside and the pods names form another namespace in Kuberentes?
Assume I am running a Javascript server in a Pod in Kubernetes. How can I get the name of that pod or its ID?
Similarly, if I am running a Python server in namespace A, how can I get the names resp. other IDs of all pods in n... | How to get pod names from inside and the pods names form another namespace in Kuberentes? | Assume I am running a Javascript server in a Pod in Kubernetes. How can I get the name of that pod or its ID?
Similarly, if I am running a Python server in namespace A, how can I get the names resp. other IDs of all pods in namespace B?
| [
"You can get the name of the pod as seen inside the Kubernetes Cluster by checking the HOSTNAME variable inside the pod.\nRef: https://kubernetes.io/docs/concepts/containers/container-environment/\nFor your second question, you can always run kubectl inside a container running in the cluster. Check this question:\n... | [
0
] | [] | [] | [
"javascript",
"kubernetes",
"kubernetes_pod",
"python"
] | stackoverflow_0074240863_javascript_kubernetes_kubernetes_pod_python.txt |
Q:
Finding the distance between 2 points fails
I'm cycling through points in a geodataframe by index in such away where I am comparing index 0 and 1, then 1 and 2, then 3 and 4 etc... The purpose is to compare the 2 points. if the points are occupying the same location pass, else draw a line between the 2 points and ... | Finding the distance between 2 points fails | I'm cycling through points in a geodataframe by index in such away where I am comparing index 0 and 1, then 1 and 2, then 3 and 4 etc... The purpose is to compare the 2 points. if the points are occupying the same location pass, else draw a line between the 2 points and summarize some stats. I figured if I compared the... | [
"Instead of looping through each pair of points, do this once:\ndist_to_next_point = track_pts.distance(track_pts.shift()).dropna()\n\n"
] | [
0
] | [] | [] | [
"geopandas",
"python"
] | stackoverflow_0074240500_geopandas_python.txt |
Q:
How to use recursion for "for" loops
My code is meant to find the longest path in a matrix, where each value is greater than the one previous. However, I've been instructed to not use for loops at all, which is difficult because I have 3, with 2 of them being involved in a nested loop. Is there any way I could onl... | How to use recursion for "for" loops | My code is meant to find the longest path in a matrix, where each value is greater than the one previous. However, I've been instructed to not use for loops at all, which is difficult because I have 3, with 2 of them being involved in a nested loop. Is there any way I could only user recursion to solve this?
def pat... | [
"Recursion is about a base case and an iterative case. In your situation, think of the smallest matrix you can - an empty matrix. That is your base case. Your function should return a path length of 0 if it is empty.\nThe iterative case is a bit more difficult, and usually where things become confusing. The key goa... | [
0
] | [
"Recursion is just a function that keeps calling itself until it reaches a condition that disallows it from continuing.\nHere's an example that's themed toward your needs.\n\"\"\" Emulation Of:\nfor row in range (len(matrix)):\n for col in range (len(matrix[0])):\n print(matrix[row][col])\n\"\"\"\n\nmatri... | [
-1
] | [
"for_loop",
"matrix",
"memoization",
"python",
"recursion"
] | stackoverflow_0074239550_for_loop_matrix_memoization_python_recursion.txt |
Q:
How to do a loop with multiprocessing
I want a number to go up in the background while waiting for user input but my code doesn't work anyone know why or how to fix
import multiprocessing as mp
num = 0
def add():
global num
while True:
num += 1
def ask():
global num
x = input("Input:")
print(x)
pri... | How to do a loop with multiprocessing | I want a number to go up in the background while waiting for user input but my code doesn't work anyone know why or how to fix
import multiprocessing as mp
num = 0
def add():
global num
while True:
num += 1
def ask():
global num
x = input("Input:")
print(x)
print(num)
if __name__ == "__main__":
p2 = m... | [
"The target argument of the mp.Process initializer is a reference to a function that will be called within a new process. But you are calling ask and add and passing their return values, which are None, as the target arguments. This is clearly a problem.\nThe other two problems you have are:\n\nYou can only call th... | [
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0074225074_multiprocessing_python.txt |
Q:
Is there a way to assign a rank to three values and then create a new column that takes the minimum value between those 3 values?
In my one sheet excel file that i created thru my SQL, I have 3 columns that represent letter ratings. The rating values may differ between ratings 1, 2, and 3, but they can still be ra... | Is there a way to assign a rank to three values and then create a new column that takes the minimum value between those 3 values? | In my one sheet excel file that i created thru my SQL, I have 3 columns that represent letter ratings. The rating values may differ between ratings 1, 2, and 3, but they can still be ranked with the same value.
I am trying to create a new column in my excel file that can take these 3 letter ratings and pull the minimum... | [
"Given your dataframe as:\ndf = pd.DataFrame(\n {\"Rating_1\": [\"A+\", \"AA\", \"Aa\"],\n \"Rating_2\": [\"B+\", \"BB\", \"Bb\"],\n \"Rating_3\": [\"Fa\", \"Fb\", \"Fc\"]}\n)\n\nYou can create a mapping dictionary (instead of lists) like this:\nmapping = {\n \"A+\": 3, \"AA\": 3, \"Aa\": 3,\n \"B+... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"sql"
] | stackoverflow_0074239340_dataframe_pandas_python_sql.txt |
Q:
How do i make this if-then statement work
I am currently learning python and i cant seen to figure out how to get a if - then statement for a dice to work (randomint).
I tried
if roll_dice < 10:
print ("dang, you got a low roll, try again")
else:
roll_dice > 10
print ("nice! you got a high roll")
roll_dice... | How do i make this if-then statement work | I am currently learning python and i cant seen to figure out how to get a if - then statement for a dice to work (randomint).
I tried
if roll_dice < 10:
print ("dang, you got a low roll, try again")
else:
roll_dice > 10
print ("nice! you got a high roll")
roll_dice = 10
print ("10!")
It says "ValueError: don... | [
"Maybe you want it to work this way:\nif roll_dice < 10:\n print (\"dang, you got a low roll, try again\")\nelif roll_dice > 10:\n print (\"nice! you got a high roll\")\nelse:\n print (\"10!\")\n\nor\nif roll_dice < 10:\n print (\"dang, you got a low roll, try again\")\nelif roll_dice > 10:\n print (\"nice! yo... | [
2,
2,
1,
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074240611_if_statement_python.txt |
Q:
Django: could not convert string to float: ''
I am trying to write a function to display all items in cart, but it keeps showing this error could not convert string to float: " and i cannot tell where the problem is coming from? i have tried chaging the float(...) method to int(...). what the possible error?
def... | Django: could not convert string to float: '' | I am trying to write a function to display all items in cart, but it keeps showing this error could not convert string to float: " and i cannot tell where the problem is coming from? i have tried chaging the float(...) method to int(...). what the possible error?
def cart_view(request):
cart_total_amount = 0
... | [
"It looks like you are getting an empty string '' when trying to convert item['price'] into a float.\n>>> float('')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: could not convert string to float: ''\n\nMake sure that item['price'] has a valid value before converting it t... | [
2
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0074240899_django_django_views_python.txt |
Q:
How to extract numbers (along with comparison adjectives or ranges)
I am working on two NLP projects in Python, and both have a similar task to extract numerical values and comparison operators from sentences, like the following:
"... greater than $10 ... ",
"... weight not more than 200lbs ...",
"... height in 5-... | How to extract numbers (along with comparison adjectives or ranges) | I am working on two NLP projects in Python, and both have a similar task to extract numerical values and comparison operators from sentences, like the following:
"... greater than $10 ... ",
"... weight not more than 200lbs ...",
"... height in 5-7 feets ...",
"... faster than 30 seconds ... "
I found two different ap... | [
"I would probably approach this as a chunking task and use nltk's part of speech tagger combined with its regular expression chunker. This will allow you to define a regular expression based on the part of speech of the words in your sentences instead of on the words themselves. For a given sentence, you can do t... | [
31,
0
] | [] | [] | [
"nlp",
"nltk",
"python",
"regex",
"spacy"
] | stackoverflow_0045126071_nlp_nltk_python_regex_spacy.txt |
Q:
PYsimpleGUI: not possible to repeat an event using radio button
I developed a pack app that can run 3 functions depending on the user's choice:
It is pretty simple:
For each option, we have another window to upload the required files an run the routine as follows:
However, if I choose option A, once I ran the sc... | PYsimpleGUI: not possible to repeat an event using radio button | I developed a pack app that can run 3 functions depending on the user's choice:
It is pretty simple:
For each option, we have another window to upload the required files an run the routine as follows:
However, if I choose option A, once I ran the script I can't run A again, I need to close and open the application ag... | [
"There're something wrong.\n\nwindow_appx will be shown when method read called\n\nif close button clicked, then window destroyed, and method read will always return (None, None), so you cannot find window any more.\nif \"Generate File\" clicked, focus still kept at the same window_appx window, but the code back to... | [
0,
0
] | [] | [] | [
"pysimplegui",
"python"
] | stackoverflow_0074212209_pysimplegui_python.txt |
Q:
bash: pip: command not found
I downloaded pip and ran python setup.py install and everything worked just fine. The very next step in the tutorial is to run pip install <lib you want> but before it even tries to find anything online I get an error "bash: pip: command not found".
This is on Mac OS X, which I'm new t... | bash: pip: command not found | I downloaded pip and ran python setup.py install and everything worked just fine. The very next step in the tutorial is to run pip install <lib you want> but before it even tries to find anything online I get an error "bash: pip: command not found".
This is on Mac OS X, which I'm new to, so I'm assuming there's some ki... | [
"Why not just do sudo easy_install pip or if this is for python 2.6 sudo easy_install-2.6 pip?\nThis installs pip using the default python package installer system and saves you the hassle of manual set-up all at the same time.\nThis will allow you to then run the pip command for python package installation as it w... | [
569,
458,
325,
62,
46,
40,
34,
28,
23,
20,
17,
15,
14,
9,
8,
7,
7,
6,
5,
4,
4,
4,
4,
4,
2,
2,
2,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"macos",
"pip",
"python",
"python_2.6"
] | stackoverflow_0009780717_macos_pip_python_python_2.6.txt |
Q:
with FastAPI, is it possible to have default path parameters?
my question is, how can i get a default value for the path parameter to work?
for the following endpoint:
from FastAPI import Path as fPath
@app.get("/users/{code}")
async def get_user(code: str = fPath("hellomotto", regex=r'hello.*')):
return {"co... | with FastAPI, is it possible to have default path parameters? | my question is, how can i get a default value for the path parameter to work?
for the following endpoint:
from FastAPI import Path as fPath
@app.get("/users/{code}")
async def get_user(code: str = fPath("hellomotto", regex=r'hello.*')):
return {"code": code}
now, if i visit localhost:666/users/helloworld it will... | [
"localhost:666/users/ matches with /users/ only, but it will never match /users/{something}. That's why FastAPI is returning 404.\nHowever, getting a user by default in that way, doesn't sound to me like a good API design. Usually, a GET /something/ will return a list of something, instead of a specific default ele... | [
1
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0073927805_fastapi_python.txt |
Q:
Scrapping with request_HTML
I am trying to scrape this website down below: https://www.kayak-polo.info/kphistorique.php?Group=CE&lang=en
down below is my code. I am trying to actually get the text inside the caption element (as shown on the screenshot). However I believe I cannot find the tag because it has no cl... | Scrapping with request_HTML | I am trying to scrape this website down below: https://www.kayak-polo.info/kphistorique.php?Group=CE&lang=en
down below is my code. I am trying to actually get the text inside the caption element (as shown on the screenshot). However I believe I cannot find the tag because it has no closing tag and that's why I think ... | [
"Here is one possible solution:\nfrom time import time\nfrom typing import Generator\nfrom requests_html import HTMLSession\nfrom requests_html import HTMLResponse\n\n\ndef get_competition_types(html: HTMLResponse) -> Generator[None, None, str]:\n return (i.attrs.get('value') for i in html.html.find('select[name... | [
0
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074236412_python_web_scraping.txt |
Q:
\Git\git-bash.exe hangs sometimes on python or python3 input() function -- \Git\bin\bash.exe doesn't. Why does this happen?
I am not asking for a substitute for git bash -- please read the entire post before answering. Thank you!
My original goal was to be able to run any python script or python program DIRECTLY f... | \Git\git-bash.exe hangs sometimes on python or python3 input() function -- \Git\bin\bash.exe doesn't. Why does this happen? | I am not asking for a substitute for git bash -- please read the entire post before answering. Thank you!
My original goal was to be able to run any python script or python program DIRECTLY from the gitbash CLI with a command like python myProgram.py or python3 myScript.py. I didn't want to have to enter any python int... | [
"I would reccomend using WSL: https://learn.microsoft.com/en-us/windows/wsl/install, I have used it for years without any problems. Hope this helps!\n"
] | [
0
] | [] | [] | [
"git_bash",
"python",
"tabby",
"windows",
"windows_terminal"
] | stackoverflow_0074241165_git_bash_python_tabby_windows_windows_terminal.txt |
Q:
How to create an A* algorithm in lists using python?
I'm trying to create an A* algorithm in Python. The matter of fact is that I don't understand anything on all the websites I'm searching, and this is why I ask on stack overflow. Here is my list :
[
['X', '_', '_', '_', 'O', 'O', '_', '_', 'O', '_', '_', '_', ... | How to create an A* algorithm in lists using python? | I'm trying to create an A* algorithm in Python. The matter of fact is that I don't understand anything on all the websites I'm searching, and this is why I ask on stack overflow. Here is my list :
[
['X', '_', '_', '_', 'O', 'O', '_', '_', 'O', '_', '_', '_', 'O'],
['_', '_', 'O', '_', '_', 'O', 'O', 'O', 'O', '_'... | [
"This is not A*(star) solution but only explanation for code in question.\n\nYou return only True/False so you can't see path.\nYou should return something like True,[path] and False,[] or False,None to get path.\nAnd first you shouldn't check _ but you should run rest of code.\nAnd in recursion you should check ev... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074235281_python.txt |
Q:
Django {% extends 'base.html' %} {% block content %} {% load static %} does not work, nothing works actually
I have a html template i want to code in django.
For now i need to take the header and footer parts and make images, css and js into static files.
I tried to do it but it does not quite work, can anyone hel... | Django {% extends 'base.html' %} {% block content %} {% load static %} does not work, nothing works actually | I have a html template i want to code in django.
For now i need to take the header and footer parts and make images, css and js into static files.
I tried to do it but it does not quite work, can anyone help me with it? I would greatly appreciate if someone can fix my mistakes and send me the file
{% extends 'base.html... | [
"Try changing the HTML file to base.html.js or make sure that the template directory is configured correctly in settings.py\nfor reference\nTEMPLATES = [\n'DIRS' = [os.path.join(base_directory, 'template_directory')]\n\n]\n",
"Hi ai ohto for {% load static %} read this Django documentation:\ndocumentation\nor in ... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074239750_django_python.txt |
Q:
How to find and replace a part of a value in json file in python by taking a result as an argument?
The output of the function I run is in format int. I should replace the number in json file
"x":{..},
"y":{..},
"z":{
... | How to find and replace a part of a value in json file in python by taking a result as an argument? | The output of the function I run is in format int. I should replace the number in json file
"x":{..},
"y":{..},
"z":{
"zz":{
"test1": "2010-11",
"test2": "somestri... | [
"What the question is asking for is a 5 step process:\n\ncreate a (properly formed) dict.\ncreate a function that returns something.\ncall the function.\nchange the value of a specific key.\nwrite the new json string.\n\nThis is code that will do such:\nimport json\n\ndef some_function():\n return 'hello world'\... | [
1,
1,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074240638_json_python.txt |
Q:
Print variable 'string value' instead of value
lst = [1,2]
x = lst
print(x) #this will print the value of x, which is [1,2]
Is there anyway that I can print 'lst' as a string, isntead of the value [1,2] ?
I do need this a I am creating a dynamic python dictionary where python dict key is a dynamic 'string' , in ... | Print variable 'string value' instead of value | lst = [1,2]
x = lst
print(x) #this will print the value of x, which is [1,2]
Is there anyway that I can print 'lst' as a string, isntead of the value [1,2] ?
I do need this a I am creating a dynamic python dictionary where python dict key is a dynamic 'string' , in my case I should have dict[lst] where lst is the key... | [
"so, I found a python library called varname, in which it has a function of \"nameof()\" and this function returns the object name, not value.\n!pip install varname\nfrom varname import nameof \n\nlst = [1,2]\nx = nameof(lst) \nprint(x) #this will print the string 'lst'\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"dynamic",
"python",
"variables"
] | stackoverflow_0074167189_dictionary_dynamic_python_variables.txt |
Q:
Convert string of list of JSON which is separated by '\n' to list of JSON(data from mixpanel) in python
The data I retrieved from Mixpanel has the format:
"{"event":"info1xxxxx","Id":"0001"}
{"event":"info2xxxxx","Id":"0002"}
{"event":"info3xxxxx","Id":"0003"}
{"event":"info3xxxxx","Id":"0003","other_key":"valu... | Convert string of list of JSON which is separated by '\n' to list of JSON(data from mixpanel) in python | The data I retrieved from Mixpanel has the format:
"{"event":"info1xxxxx","Id":"0001"}
{"event":"info2xxxxx","Id":"0002"}
{"event":"info3xxxxx","Id":"0003"}
{"event":"info3xxxxx","Id":"0003","other_key":"value"}..."
It's a string of list of JSON which are separated by '\n'. And each JSON may have a different struct... | [
"You can try str.splitlines:\nimport json\n\ns = \"\"\"\\\n{\"event\":\"info1xxxxx\",\"Id\":\"0001\"}\n{\"event\":\"info2xxxxx\",\"Id\":\"0002\"}\n{\"event\":\"info3xxxxx\",\"Id\":\"0003\"}\n{\"event\":\"info3xxxxx\",\"Id\":\"0003\",\"other_key\":\"value\"}\"\"\"\n\n\nlst = json.loads(f\"[{', '.join(s.splitlines())... | [
1,
1
] | [] | [] | [
"json",
"mixpanel",
"python"
] | stackoverflow_0074241203_json_mixpanel_python.txt |
Q:
How to fix postgres error; time zone displacement out of range?
CurrentTimeStamp (timestamp with time zone not null) column's Date-Time Records in BOOKS postgres db table are stored in the format:
2022-10-29 00:00:00+00
There's a java API which fetches records from this table, using the CurrentTimeStamp column,
... | How to fix postgres error; time zone displacement out of range? | CurrentTimeStamp (timestamp with time zone not null) column's Date-Time Records in BOOKS postgres db table are stored in the format:
2022-10-29 00:00:00+00
There's a java API which fetches records from this table, using the CurrentTimeStamp column,
Prior to that, there's a python API which provides a timestamp in the... | [
"The part after \"+\" is not milliseconds though, is it. That is how you represent the tine-zone. Which can't be an offset of 45 hours.\n"
] | [
1
] | [] | [] | [
"java",
"pgadmin_4",
"postgresql",
"python"
] | stackoverflow_0074240284_java_pgadmin_4_postgresql_python.txt |
Q:
How to parse the log data which is in form of nested [key=value] format using python pandas
I have huge Sensor log data which is in form of [key=value] pair I need to parse the data column wise
i found this code for my problem
import pandas as pd
lines = []
with open('/path/to/test.txt', 'r') as infile:
for l... | How to parse the log data which is in form of nested [key=value] format using python pandas | I have huge Sensor log data which is in form of [key=value] pair I need to parse the data column wise
i found this code for my problem
import pandas as pd
lines = []
with open('/path/to/test.txt', 'r') as infile:
for line in infile:
if "," not in line:
continue
else:
lines.a... | [
"I've downloaded as csv.\nSince your file has multiple tables on one sheet, I've limited to 100 rows, you can remove that parameter.\nraw = pd.read_csv(\n \"logdata - Sheet1.csv\", # filename \n skiprows=1, # skip the first row\n nrows=100, # use 100 rows, remove in your example\n usecols=[0], # onl... | [
0
] | [] | [] | [
"data_science",
"dictionary",
"pandas",
"parsing",
"python"
] | stackoverflow_0074238871_data_science_dictionary_pandas_parsing_python.txt |
Q:
How to print line number specific element inside complex child elements using python
Example of my XML1 consists of format of Equal element :
<Operator>
<Equal>
<Data>A1</Data>
<Data>2</Data>
</Equal>
<Equal>
<Integer>A2</Integer>
<Data>2</Data>
</Equal>
<Equal>
... | How to print line number specific element inside complex child elements using python | Example of my XML1 consists of format of Equal element :
<Operator>
<Equal>
<Data>A1</Data>
<Data>2</Data>
</Equal>
<Equal>
<Integer>A2</Integer>
<Data>2</Data>
</Equal>
<Equal>
<Integer>A3</Integer>
<Integer>2</Integer>
</Equal>
</Operator>
And t... | [
"The code is taking only the first Equal found so it fails when there are 2 or more\nfor service in doc.xpath('//Sub_Function_1//Data[Label and .//Equal[(*[1][self::Data] and *[2][self::Data]) or *[1][self::Integer]]]'):\n eqs = service.xpath('.//Equal[(*[1][self::Data] and *[2][self::Data]) or *[1][self::Integ... | [
0
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0074240953_lxml_python_xml.txt |
Q:
asdict() inside .format() in a Python class
How can I use asdict() method inside .format() in oder to unpack the class attributes.
So that instead of this:
from dataclasses import dataclass, asdict
@dataclass
class InfoMessage():
training_type: str
duration: float
distance: float
message = 'Traini... | asdict() inside .format() in a Python class | How can I use asdict() method inside .format() in oder to unpack the class attributes.
So that instead of this:
from dataclasses import dataclass, asdict
@dataclass
class InfoMessage():
training_type: str
duration: float
distance: float
message = 'Training type: {}; Duration: {:.3f} ч.; Distance: {:.3f... | [
"asdict should be called on an instance of a class - self, in this case. Additionally, you don't need the dict's keys, you need its values, which you can spread using the * operator:\ndef get_message(self) -> str:\n return self.message.format(*asdict(self).values())\n # Here --------------------^\n\n",
"You... | [
2,
0
] | [] | [] | [
"class",
"dictionary",
"python"
] | stackoverflow_0070890819_class_dictionary_python.txt |
Q:
python: beautiful soup extracting info
I am using beautiful soup to parse HTML as follows:
html_content2 ="""
<h3 style="cear: both;">
<abbr title="European Union">EU</abbr>Investment</h3>
<div class="conditions">
<p>bla bla bla
</p>
</div>
<p style="margin-bottom: 0;">
<span class="amount">66000 €</span>
</p>"""
... | python: beautiful soup extracting info | I am using beautiful soup to parse HTML as follows:
html_content2 ="""
<h3 style="cear: both;">
<abbr title="European Union">EU</abbr>Investment</h3>
<div class="conditions">
<p>bla bla bla
</p>
</div>
<p style="margin-bottom: 0;">
<span class="amount">66000 €</span>
</p>"""
I would like to extract the amount of money... | [
"Use lambda tag: tag.name == \"h3\" and \"Investment\" in tag.text:\nfrom bs4 import BeautifulSoup\n\nhtml_content = \"\"\"\n<h3 style=\"cear: both;\">\n<abbr title=\"European Union\">EU</abbr>Investment</h3>\n<div class=\"conditions\">\n<p>bla bla bla\n</p>\n</div>\n<p style=\"margin-bottom: 0;\">\n<span class=\"a... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074240934_beautifulsoup_python.txt |
Q:
Is there a way to call a function to make a dice roll?
creating a tuple that holds the values 1 through 6. Roll the dice by calling a function and display the random roll. For this example, let’s assume that the random roll is (2, 1, 5, 1, 5).
The following message will be displayed:
Rolling the dice... (2, 1, 5, ... | Is there a way to call a function to make a dice roll? | creating a tuple that holds the values 1 through 6. Roll the dice by calling a function and display the random roll. For this example, let’s assume that the random roll is (2, 1, 5, 1, 5).
The following message will be displayed:
Rolling the dice... (2, 1, 5, 1, 5)
then from the random add implementing a counter functi... | [] | [] | [
"You may want to check out https://stackoverflow.com/help/how-to-ask, as this question isn't very clear and doesn't isolate the issue, but I believe I understand what you are asking.\nimport random\n#this should have a more intuitive name like potential_results\nroll_number = [1,2,3,4,5,6]\n#It looks like you need ... | [
-1
] | [
"python",
"user_defined_functions"
] | stackoverflow_0074241192_python_user_defined_functions.txt |
Q:
Django - Form not populating in models but no error in console
I'm creating a Django application and am having a bit of difficulty with creating 'activities' via the frontend. (CRUD application)
Previously, I had issues related to the ForeignKey for the host; which I was using the extended AllAuth models (named ... | Django - Form not populating in models but no error in console | I'm creating a Django application and am having a bit of difficulty with creating 'activities' via the frontend. (CRUD application)
Previously, I had issues related to the ForeignKey for the host; which I was using the extended AllAuth models (named UserProfile) and the errors for this do appear to have been resolved... | [
"Make sure you have added the forms action in your HTML and assigned it to the create_activity function URL in urls.py.\nFor example, in your new_listing.html:\n<form method=\"post\" action=\"{% url '**yourFunctionUrl**' %}\">\n {% csrf_token %}\n\n {{ form.as_p }}\n\n</form>\n\nAnd in urls.py:\nfrom django.urls... | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0074239270_django_django_models_django_views_python.txt |
Q:
Save data to hdf5 (e.g. from pandas df) with structure copied from another hdf5-file
I have astronomical data in columns, that look something like this
M200c, M200m, dec, ra
19.4, 20.4, 1.33, 4.68
...
I need to save my data in hdf5 format, so it can be fed into a script. I know the structure, that the hdf5 file... | Save data to hdf5 (e.g. from pandas df) with structure copied from another hdf5-file | I have astronomical data in columns, that look something like this
M200c, M200m, dec, ra
19.4, 20.4, 1.33, 4.68
...
I need to save my data in hdf5 format, so it can be fed into a script. I know the structure, that the hdf5 file should have, from an example that is provided, it delivers this structure:
import nexusfo... | [
"Yes, as you discovered, pandas uses predefined schemas when wrting HDF5 data and doesn't give you much control. I answered a similar question a few days ago. You can get close with the following pandas options: key='NXroot', format='table', data_columns=True. However, you won't be able to mimic the schema exactly.... | [
1
] | [] | [] | [
"data_structures",
"dataframe",
"hdf5",
"pandas",
"python"
] | stackoverflow_0074237288_data_structures_dataframe_hdf5_pandas_python.txt |
Q:
Python Selenium problems with passing login information to user/password form
So, the last 3 hours or so I have tried to get Selenium to work without success. I managed to make it work with requests and Beautifulsoup, but apparently site uses javascript to load data after login so I cannot scrape the data I want a... | Python Selenium problems with passing login information to user/password form | So, the last 3 hours or so I have tried to get Selenium to work without success. I managed to make it work with requests and Beautifulsoup, but apparently site uses javascript to load data after login so I cannot scrape the data I want after successful login.
Below is the script I am trying to work with.
``
import time... | [
"this occurs because there is an iframe in the page code. It is necessary to switch to the iframe and then search for the element, follow the code with the correction.\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n\ndriver = webdriver.Chrome(executable_path= \"chromedriver.exe\")\n... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074240268_python_selenium.txt |
Q:
AssertionError: returned during python unittest and properties
I was taking a python test and am unclear on something that appeared in the test. The test used test driven development, so we were given a file with unittest assertions calling into a module we needed to create. So, I'm unable to change how the cal... | AssertionError: returned during python unittest and properties | I was taking a python test and am unclear on something that appeared in the test. The test used test driven development, so we were given a file with unittest assertions calling into a module we needed to create. So, I'm unable to change how the calls are made in the test file.
Here is the basics of the two files tha... | [
"\nNote that the test_yahtzee.py file doesn't use an instance of Roll and instead looks like the unittest module must bind the <Class.fun> method (i.e., Roll(...).up_best) to something it can call ... again I can't change this file.\n\nI'm not sure what you mean by \"the test_yahtzee.py file doesn't use an instance... | [
0
] | [] | [] | [
"properties",
"python",
"python_3.x",
"unit_testing"
] | stackoverflow_0073993258_properties_python_python_3.x_unit_testing.txt |
Q:
Django App on Heroku using psycopg2 - unable to run locally - can't detect module
Been trying to implement a django app with postgresql database on heroku, with psycopg2 as the backend.
(Based on the research I've done, psycopg3 looks like it's not really built for that purpose)
My app works, without issue runnin... | Django App on Heroku using psycopg2 - unable to run locally - can't detect module | Been trying to implement a django app with postgresql database on heroku, with psycopg2 as the backend.
(Based on the research I've done, psycopg3 looks like it's not really built for that purpose)
My app works, without issue running inside heroku/heroku console, and connects to db fine.
But running locally (python ... | [
"So... It worked upon downgrading back to Python 3.10. Shoulda tried that earlier lol\n"
] | [
1
] | [] | [] | [
"django",
"heroku",
"heroku_postgres",
"psycopg2",
"python"
] | stackoverflow_0074238815_django_heroku_heroku_postgres_psycopg2_python.txt |
Q:
Appending the content of old csv into new csv
I created a function and the idea is that if the "main" file (transactions_ledger.csv) doesn't exist I need to create it and append the new file (user input- which file) to it.
The code is working BUT the new file has an additional row in between with no contents.
note... | Appending the content of old csv into new csv | I created a function and the idea is that if the "main" file (transactions_ledger.csv) doesn't exist I need to create it and append the new file (user input- which file) to it.
The code is working BUT the new file has an additional row in between with no contents.
note: I can not use pandas
In advance thank you for hel... | [
"I found a solution. I need to specify inside the writer_obj = csv.writer(new_file,delimiter=\",\") the following:\nlineterminator = \"\\n\"\n"
] | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074241252_csv_python.txt |
Q:
Pandas: Filtering timeseries data from two dataframes
I am trying to write a program which involves monitoring the electric power consumption in watts for a house. I have two sets of dataframes. The first one (df_appliances) contains multiple columns of appliances with their wattage recorded after every 10 mins li... | Pandas: Filtering timeseries data from two dataframes | I am trying to write a program which involves monitoring the electric power consumption in watts for a house. I have two sets of dataframes. The first one (df_appliances) contains multiple columns of appliances with their wattage recorded after every 10 mins like so:
Timestamp Dishwasher TV Desktop_PC Wash... | [
"One way would be to merge and then filter based on your criterium.\ndf = df_appliances.merge(df_total, left_on=\"Timestamp\", right_on=\"DATETIME\")\n\nprint(df[(df.Total_Watts >= 4000) | (df.Total_Watts.shift(-1) >= 4000) | (df.Total_Watts.shift(-2) >= 4000)])\n\nEdit:\ndf.Timestamp = pd.to_datetime(df.Timestamp)... | [
0
] | [] | [] | [
"dataframe",
"filter",
"pandas",
"python",
"time_series"
] | stackoverflow_0074240708_dataframe_filter_pandas_python_time_series.txt |
Q:
Error When Trying To Read Int From Txt File Python
Im trying to do a highscore system for my python game using a txt file and writing and reading the highscore from/to it.
When i try the code under i get this error message:
ValueError: invalid literal for int() with base 10: '\x003'
highscorefileR = open(r"highsco... | Error When Trying To Read Int From Txt File Python | Im trying to do a highscore system for my python game using a txt file and writing and reading the highscore from/to it.
When i try the code under i get this error message:
ValueError: invalid literal for int() with base 10: '\x003'
highscorefileR = open(r"highscore.txt","r+")
score = int(score)
highscore = highscor... | [
"If it's a plain text file, you shouldn't need all that complication. Just:\nwith open(r\"highscore.txt\",\"r\") as highscorefileR:\n highscore = int(highscorefileR.read())\n\nif score > highscore:\n with open(r\"highscore.txt\",\"w\") as highscorefileW:\n highscorefileW.write(f'{score}\\n')\n\n",
"I... | [
0,
0
] | [] | [] | [
"file",
"file_read",
"file_writing",
"python",
"valueerror"
] | stackoverflow_0074241182_file_file_read_file_writing_python_valueerror.txt |
Q:
Understanding weird boolean 2d-array indexing behavior in numpy
Why does this work:
a = np.random.rand(10, 20)
x_range = np.arange(10)
y_range = np.arange(20)
a_tmp = a[x_range<5,:]
b = a_tmp[:, np.in1d(y_range, [3,4,8])]
and this does not:
a = np.random.rand(10,20)
x_range = np.arange(10)
y_range = np.arange(20... | Understanding weird boolean 2d-array indexing behavior in numpy | Why does this work:
a = np.random.rand(10, 20)
x_range = np.arange(10)
y_range = np.arange(20)
a_tmp = a[x_range<5,:]
b = a_tmp[:, np.in1d(y_range, [3,4,8])]
and this does not:
a = np.random.rand(10,20)
x_range = np.arange(10)
y_range = np.arange(20)
b = a[x_range<5, np.in1d(y_range,[3,4,8])]
| [
"The Numpy reference documentation's page on indexing contains the answers, but requires a bit of careful reading.\nThe answer here is that indexing with booleans is equivalent to indexing with integer arrays obtained by first transforming the boolean arrays with np.nonzero. Therefore, with boolean arrays m1, m2\na... | [
26,
7,
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007820809_numpy_python.txt |
Q:
python how do I add a score on the same object 3 times in a row?
I have a problem adding scores to an object with a for loop.
what I'm trying to achieve is this:
enter test num: 1
enter test score: 58
enter test num: 2
etc...
and then print out the three test numbers and the average, but I can't seem to get it to ... | python how do I add a score on the same object 3 times in a row? | I have a problem adding scores to an object with a for loop.
what I'm trying to achieve is this:
enter test num: 1
enter test score: 58
enter test num: 2
etc...
and then print out the three test numbers and the average, but I can't seem to get it to set the test num nor the score.
this is the error I get after tring to... | [
"Issue is you are trying to run setTestScore function without instantiating the class. Either make it a staticmethod or call it from an object\n for s in classList:\n for i in range(len(classList)):\n test = int(input(\"enter test number: \"))\n score = int(input(\"enter test score: ... | [
1,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074241261_python_python_3.x.txt |
Q:
how do i make an array of arrays using for loops to input elements to the array
grades=[]
ClassGrade=[]
NumStudents=int(input(" How Many Students Do You Have ? "))
for i in range(0,2,1):
prompt=("Input student "+str(i)+"'s grades ")
for i in range(0,2,1):
grade=float(input(prompt))
grades... | how do i make an array of arrays using for loops to input elements to the array | grades=[]
ClassGrade=[]
NumStudents=int(input(" How Many Students Do You Have ? "))
for i in range(0,2,1):
prompt=("Input student "+str(i)+"'s grades ")
for i in range(0,2,1):
grade=float(input(prompt))
grades.append(grade)
ClassGrade.append(grades)
print(ClassGrade)
when start inputtin... | [
"You should declare the array inside the for loop, or you will add all the grades to the same list:\nyou need to move grades=[] from here:\ngrades=[] <---\nClassGrade=[]\n\nto:\nfor i in range(0,2,1):\n grades=[] <---\n prompt=(\"Input student \"+str(i)+\"'s grades \")\n\n"
] | [
0
] | [] | [] | [
"append",
"arrayofarrays",
"arrays",
"for_loop",
"python"
] | stackoverflow_0074241280_append_arrayofarrays_arrays_for_loop_python.txt |
Q:
How to achieve two function signatures for `for loop unzip`
Following snippet gives my intention of unzipping t1, t2, t3 or t1, t2 depending upon the task. I know such if-else on for statement doesn't exist but I am wondering is there a workaround for this. Any help or clarification questions are welcome.
def func... | How to achieve two function signatures for `for loop unzip` | Following snippet gives my intention of unzipping t1, t2, t3 or t1, t2 depending upon the task. I know such if-else on for statement doesn't exist but I am wondering is there a workaround for this. Any help or clarification questions are welcome.
def func(task, t1, t2, t3):
if task == 'abc': # t3=None for this cas... | [
"Use itertools.repeat() to provide a default third list for zip() that produces a continuous stream of a default value.\ndef func(task, a1, a2, a3 = None):\n if a3 is None:\n a3 = itertools.repeat(None)\n for t1, t2, t3 in zip(a1, a2, a3):\n // do someting\n\n",
"Not clear what the problem is ... | [
2,
2
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074241311_for_loop_python.txt |
Q:
How to display Legend with seaborn.kdeplot
I have been trying add the Legend to my code below.
It should have worked when I add the "Label". But it just won't show, not sure what I did wrong.
Packages Used
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.sta... | How to display Legend with seaborn.kdeplot | I have been trying add the Legend to my code below.
It should have worked when I add the "Label". But it just won't show, not sure what I did wrong.
Packages Used
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats as stats
from scipy.stats import kruskal
from... | [
"You simply need to call the .legend() method of your Axes object. The plotting functions of seaborn return the reference to the Axes directly which is handy. See the documentation of sns.kdeplot\nax = sns.kdeplot(...)\nax.legend(loc=\"upper right\")\n\n",
"import pandas as pd\nimport numpy as np\nimport matplotl... | [
2,
0
] | [] | [] | [
"legend",
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0069688499_legend_matplotlib_python_seaborn.txt |
Q:
Is divmod() faster than using the % and // operators?
I remember from assembly that integer division instructions yield both the quotient and remainder. So, in python will the built-in divmod() function be better performance-wise than using the % and // operators (suppose of course one needs both the quotient and ... | Is divmod() faster than using the % and // operators? | I remember from assembly that integer division instructions yield both the quotient and remainder. So, in python will the built-in divmod() function be better performance-wise than using the % and // operators (suppose of course one needs both the quotient and the remainder)?
q, r = divmod(n, d)
q, r = (n // d, n % d)
... | [
"To measure is to know (all timings on a Macbook Pro 2.8Ghz i7):\n>>> import sys, timeit\n>>> sys.version_info\nsys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)\n>>> timeit.timeit('divmod(n, d)', 'n, d = 42, 7')\n0.1473848819732666\n>>> timeit.timeit('n // d, n % d', 'n, d = 42, 7')\n0.1... | [
60,
25,
0
] | [] | [] | [
"division",
"divmod",
"modulo",
"performance",
"python"
] | stackoverflow_0030079879_division_divmod_modulo_performance_python.txt |
Q:
I cannot get pyqt5 to run under anaconda python
I cannot get pyqt5 to run under anaconda python. The following is an error message I get when I run a script shown below:
Traceback (most recent call last
File [full path to the python script], line 9, in <module>
from PyQt5.QtCore import QT_VERSION_STR
ImportError... | I cannot get pyqt5 to run under anaconda python | I cannot get pyqt5 to run under anaconda python. The following is an error message I get when I run a script shown below:
Traceback (most recent call last
File [full path to the python script], line 9, in <module>
from PyQt5.QtCore import QT_VERSION_STR
ImportError: DLL load failed while importing QtCore: The specifi... | [
"I had a similar problem with PyQt - after upgrading to spyder 5.2.2 neither anaconda nor spyder would open at all - no splash screen etc or anything - it didn't even try to start the programs. Trying to start from the prompt, \"anaconda-navigator\" and \"sypder\" both returned:\n(base) C:\\Users\\Geography Chair>s... | [
2
] | [] | [] | [
"anaconda",
"dllimport",
"pyqt5",
"python"
] | stackoverflow_0063674900_anaconda_dllimport_pyqt5_python.txt |
Q:
How to change certain letters in a word list (words contain in text file) with python
I have a word list contains in a text file; below I show an example:
place
lime
nest
land
I want to get an other file with the content below:
pl@ce
lim3
n3st
l@nd
This mean that:
the letter a must be transform in in the char @... | How to change certain letters in a word list (words contain in text file) with python | I have a word list contains in a text file; below I show an example:
place
lime
nest
land
I want to get an other file with the content below:
pl@ce
lim3
n3st
l@nd
This mean that:
the letter a must be transform in in the char @ but in a word must be only 1 change so apart becomes ap@rt and not @p@rt.
the letter e mus... | [
"Split input string into individual words, replace first instance of 'a' with '@' in each word. Append edited words to output string.\ninput = 'place lime nest land'\noutput = ''\n\ninput = input.split(' ')\n\nfor i in input:\n i = i.replace('a', '@', 1)\n i = i.replace('e', '3', 1)\n output += i + ' '\n\n... | [
1,
1,
0,
0
] | [
"this may be a rough first draft and some assumptions were made but here is a shot at a function. Could be cleaned up alot. Good luck\ndef updt_text(s):\n # assumptions, string of text is seperated by spaces and there are no odd characters\n words = s.split()\n newwords = []\n \n dictChanges = {\n ... | [
-2
] | [
"python",
"python_3.x",
"text_files"
] | stackoverflow_0074240883_python_python_3.x_text_files.txt |
Q:
ImportError in python: cannot import from a partially initialized module.. in python
I have python 3.10 code running from some time, and now, it started getting me errors while importing the libraries, without any modification in the code.
For example, from this line:
from azure.keyvault.secrets import SecretClie... | ImportError in python: cannot import from a partially initialized module.. in python | I have python 3.10 code running from some time, and now, it started getting me errors while importing the libraries, without any modification in the code.
For example, from this line:
from azure.keyvault.secrets import SecretClient
I get this error;
from azure.keyvault.secrets import SecretClient
ImportError: can... | [
"azure-keyvault is deprecated.\nPlease uninstall azure-keyvault and use pip install azure-keyvault-secrets.\n(I work in MS in the SDK team)\n"
] | [
0
] | [] | [] | [
"azure_keyvault",
"python"
] | stackoverflow_0074212331_azure_keyvault_python.txt |
Q:
How to override `Model.__init__` and respect `.using(db)` in Django?
I have the following code:
print(f"current database: {self.db}\ninfusate from database: {infusate._state.db}\ntracer from database: {tracer._state.db}")
FCirc.objects.using(self.db).get_or_create(
serum_sample=sample,
tracer=tracer,
e... | How to override `Model.__init__` and respect `.using(db)` in Django? | I have the following code:
print(f"current database: {self.db}\ninfusate from database: {infusate._state.db}\ntracer from database: {tracer._state.db}")
FCirc.objects.using(self.db).get_or_create(
serum_sample=sample,
tracer=tracer,
element=label.element,
)
That is producing the following output and except... | [
"I figured it out! Another developer had added calls to full_clean (which I have a separate question about) in derived classes of the QuerySet class for a few of the models. E.g.:\nclass TracerQuerySet(models.QuerySet):\n ...\n\nclass Tracer(MaintainedModel):\n objects = TracerQuerySet().as_manager()\n .... | [
0
] | [] | [] | [
"database",
"django",
"orm",
"python",
"using"
] | stackoverflow_0074241257_database_django_orm_python_using.txt |
Q:
Python - Printing numbers with spacing format
Let's say I have an array of numbers where
list = [(4, 3, 7, 23),(17, 4021, 4, 92)]
and I want to print the numbers out in such a way so that the output looks somewhat like this:
[ 4 | 3 | 7 | 23 ]
[ 17 | 4021 | 4 | 92 ]
Where the numbers are as ce... | Python - Printing numbers with spacing format | Let's say I have an array of numbers where
list = [(4, 3, 7, 23),(17, 4021, 4, 92)]
and I want to print the numbers out in such a way so that the output looks somewhat like this:
[ 4 | 3 | 7 | 23 ]
[ 17 | 4021 | 4 | 92 ]
Where the numbers are as centered as possible and that there is enough space i... | [
"str.center can make things easier.\nfor i in list:\n print '[ ' + ' | '.join([str(j).center(4) for j in i]) + ' ]'\n\nOutput:\n[ 4 | 3 | 7 | 23 ]\n[ 17 | 4021 | 4 | 92 ]\n\nIn case you need an alternative solution, you can use str.format: \nfor i in list:\n print '[ ' + ' | '.join([\"{:^4}\... | [
4,
3,
0,
0
] | [] | [] | [
"format",
"list",
"number_formatting",
"python",
"string"
] | stackoverflow_0039130914_format_list_number_formatting_python_string.txt |
Q:
Structuring of .py project using sqlalchemy
I've written a 'simple' python project in my spare time to get myself familiar with the language, but now I want to take it up a level. This includes storing data to a database for persistance. However, I'm having a hard-time to figure out the structuring of my project. ... | Structuring of .py project using sqlalchemy | I've written a 'simple' python project in my spare time to get myself familiar with the language, but now I want to take it up a level. This includes storing data to a database for persistance. However, I'm having a hard-time to figure out the structuring of my project. My first attempt locked me out through circular d... | [
"For me the most intuitive structure for sqlalchemy is having a db module that creates the engine, base and sessions. I create modules per functionality group, mainly for naming, with classes (tables) which often also provide save() functions for 'fire and forget' mutations. These modules form a component that have... | [
0
] | [] | [] | [
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0074239889_python_sqlalchemy_sqlite.txt |
Q:
Remove substring and all characters before from pyspark column
I have a pyspark object column in a dataframe (df) like this:
| 'A' |
-------------------------
| field 1 - order - one |
| field 2 - sell |
| order |
| sell |
I'd like to remove the first occu... | Remove substring and all characters before from pyspark column | I have a pyspark object column in a dataframe (df) like this:
| 'A' |
-------------------------
| field 1 - order - one |
| field 2 - sell |
| order |
| sell |
I'd like to remove the first occurence of '- ' and all characters before using regex_replace or what... | [
"this should work\nfrom pyspark.sql import functions as F\n\ndf = spark.createDataFrame(\n [\n (\"field 1 - order\", \"None\"),\n (\"field 2 - sell\", \"None\"),\n (\"order\", \"None\"),\n (\"sell\", \"None\"),\n ],\n [\"A\", \"B\"],\n)\ndf.show()\n\ndf = (\n df\n .withCol... | [
1,
0
] | [] | [] | [
"pyspark",
"python"
] | stackoverflow_0074239317_pyspark_python.txt |
Q:
I want to create a new column with ages according to birth dates but I'm not able to
I have a df with date of birth and I want to add another column with age. I want to understand what the problem is with this iteration I made. Why does this code put the age of the last user on every line instead of putting the ag... | I want to create a new column with ages according to birth dates but I'm not able to | I have a df with date of birth and I want to add another column with age. I want to understand what the problem is with this iteration I made. Why does this code put the age of the last user on every line instead of putting the age of each user?
import pandas as pd
import datetime as dt
df = pd.DataFrame(['9/26/1987 1... | [
"when using Pandas your last resort should be to use loops: vectorization is the purpose of the module. That being said:\nI'm going to assume your dob column is already in a datetime format. if not just call something like:\ndf['dob'] = pd.to_datetime(df['dob'])\n\nThen get today's date from the datetime module a... | [
0
] | [] | [] | [
"dataframe",
"for_loop",
"pandas",
"python",
"python_datetime"
] | stackoverflow_0074241677_dataframe_for_loop_pandas_python_python_datetime.txt |
Q:
An accurate progress bar for loading files and transforming data using Vaex and Pandas
I am looking for the method to include a progress bar to see the remaining time for loading a file with Vaex (big data files) or transform big data with Panda. I have checked this thread https://stackoverflow.com/questions/31606... | An accurate progress bar for loading files and transforming data using Vaex and Pandas | I am looking for the method to include a progress bar to see the remaining time for loading a file with Vaex (big data files) or transform big data with Panda. I have checked this thread https://stackoverflow.com/questions/3160699/python-progress-bar, but unfortunately, all the progress bar codes are absolutely inaccur... | [
"i use these two progress bar variants that do not require imports and one can embed into the code quite easily.\nsimple progress bar:\nimport time\n\n\nn = 25\nfor i in range(n):\n time.sleep(0.1)\n progress = int(i / n * 50)\n print(f'running {i+1} of {n} {progress*\".\"}', end='\\r', flush=True)\n\n\nmo... | [
0
] | [] | [] | [
"progress_bar",
"python",
"vaex"
] | stackoverflow_0074241225_progress_bar_python_vaex.txt |
Q:
when I apply median filter to image, it turns purple. why?
I have a image.I added salt & pepper noise to this image. After that I applied 2D median filter to remove noise from image. But after this process, the image converted purple.
And here is my codes.
M=3;
N=3;
modifyA=np.pad(image, [(math.floor(M/2),math.f... | when I apply median filter to image, it turns purple. why? | I have a image.I added salt & pepper noise to this image. After that I applied 2D median filter to remove noise from image. But after this process, the image converted purple.
And here is my codes.
M=3;
N=3;
modifyA=np.pad(image, [(math.floor(M/2),math.floor(N/2))])
B = np.zeros([(image.shape[0]),(image.shape[1])]) ... | [
"As @gre_gor wrote in their comment, imshow is using a pseudocolor. More specifically, it is using the common colormap viridis by default if the image is not RGB(A).\nTake a look at the documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.imshow.html\nTo display a grayscale version of your ima... | [
0
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0074241505_image_processing_python.txt |
Q:
Apache Beam – issue with Deduplicate function
I have an issue with apache_beam.transforms.deduplicate.Deduplicate transformation. Please, look on a code sample below:
with beam.Pipeline() as pipeline:
(
pipeline
# | 'Load' >> beam.Create(['a', 'b', 'b']) ## <- works fine
... | Apache Beam – issue with Deduplicate function | I have an issue with apache_beam.transforms.deduplicate.Deduplicate transformation. Please, look on a code sample below:
with beam.Pipeline() as pipeline:
(
pipeline
# | 'Load' >> beam.Create(['a', 'b', 'b']) ## <- works fine
| 'Load' >> beam.io.ReadFromText('./input.txt'... | [
"I hope it can help.\nIndeed I tested your code and it doesn't works, maybe I am wrong but I think the Deduplicate PTransform seems to be more adapted for jobs with windowing logics (processing time and event time).\nIt works with beam.Create (even if it's a bounded source) but not with ReadFromText because a type ... | [
1
] | [] | [] | [
"apache_beam",
"apache_beam_io",
"python"
] | stackoverflow_0074221065_apache_beam_apache_beam_io_python.txt |
Q:
Python: Azure Function Key Vault reference for certificates?
Similar to this question, I have a Python Azure Function where I want to load a certificate from a Key Vault Reference. Referencing the secret returns a string that looks like this: "MIIcGA...z62QICB9A=". I'm trying to load this into an azure.identity Ce... | Python: Azure Function Key Vault reference for certificates? | Similar to this question, I have a Python Azure Function where I want to load a certificate from a Key Vault Reference. Referencing the secret returns a string that looks like this: "MIIcGA...z62QICB9A=". I'm trying to load this into an azure.identity CertificateCredential object and can't figure out how to construct t... | [
"After fighting with this all day, I discovered the answer here\nBase64-decode the string that comes from keyvault and set it as the certificate_data bytes.\npkcs12_bytes = base64.b64decode(cert64) \ncert_cred = CertificateCredential(\"72f...guid\", \"eff...guid\", certificate_data = base64.b64decode(cert64))\n\n... | [
1
] | [] | [] | [
"azure_functions",
"azure_keyvault",
"python"
] | stackoverflow_0074239136_azure_functions_azure_keyvault_python.txt |
Q:
Loop Through Two Dataframe Columns to Create Key-Value Pairs For Value Dictionaries Nested Inside A Dictionary Nested Inside Another Dictonary
I want to create a metadata variable based on my input dataset's columns using dictionaries. Specifically, I want the metadata variable to have exactly this structure and ... | Loop Through Two Dataframe Columns to Create Key-Value Pairs For Value Dictionaries Nested Inside A Dictionary Nested Inside Another Dictonary | I want to create a metadata variable based on my input dataset's columns using dictionaries. Specifically, I want the metadata variable to have exactly this structure and values:
metadata = {
'fields': {
'id': {'type': 'categorical'},
'name': {'type': 'categorical'},
'category_id': {'type':... | [
"You can convert your 0 column into an array of dicts, using replace to replace 'object' with 'categorical' (and any others you might need)) and then applying a function to return a dict with type as the key and that value. You can then zip that to the index column and convert to a dict of fields. Finally you can a... | [
1
] | [] | [] | [
"dictionary",
"for_loop",
"key_value",
"nested",
"python"
] | stackoverflow_0074241450_dictionary_for_loop_key_value_nested_python.txt |
Q:
How to conditionally filter a Pandas dataframe
I have a Pandas dataframe that looks like this:
import pandas as pd
df = pd.DataFrame({
'city': ['New York','New York','New York','Los Angeles','Los Angeles','Houston','Houston','Houston'],
'airport': ['LGA', 'EWR', 'JFK', 'LAX', 'BUR', 'IAH', 'HOU', 'EFD'],
'distanc... | How to conditionally filter a Pandas dataframe | I have a Pandas dataframe that looks like this:
import pandas as pd
df = pd.DataFrame({
'city': ['New York','New York','New York','Los Angeles','Los Angeles','Houston','Houston','Houston'],
'airport': ['LGA', 'EWR', 'JFK', 'LAX', 'BUR', 'IAH', 'HOU', 'EFD'],
'distance': [38, 50, 32, 8, 50, 90, 78, 120]
}
df
city ... | [
"So in your case do with drop_duplicates then combine_first\nout = df.sort_values('distance').drop_duplicates('city').combine_first(df.loc[df['distance']<40])\nOut[228]: \n city airport distance\n0 NewYork LGA 38\n2 NewYork JFK 32\n3 LosAngeles LAX 8\n6 Housto... | [
4,
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074240730_pandas_python.txt |
Q:
Count occurence of True or False for a range of rows in Pandas
I am using a similar question on SO, except that I need to limit the range of rows in the Pandas dataframe Count occurrences of False or True in a column in pandas
So using this example, I would like to count the number of False occurrences in rows tha... | Count occurence of True or False for a range of rows in Pandas | I am using a similar question on SO, except that I need to limit the range of rows in the Pandas dataframe Count occurrences of False or True in a column in pandas
So using this example, I would like to count the number of False occurrences in rows that start with values between 50000 and 80000.
I would need to first s... | [
"I will assume the data you presented is in a variable called \"df\".\nimport pandas as pd\n# 0\ndf = pd.DataFrame() \n\n# 1\ndf = df[(df['patient_id'] >= 50000) & (df['patient_id'] <= 50000)]\n\n# 2 retrieves a series object\ndf['has_cancer'].value_counts()\n\n# 3 retrieving the actual number\ndf[~df['has_cancer']... | [
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074241886_numpy_pandas_python.txt |
Q:
How do I use an input to print a class definition?
I am trying to code something basic in python just for fun and I encountered an issue,
# Employee is a class with the initialization being self, name, status
e1 = Employee("Tom, Lincoln", "Present")
e2 = Employee("Sam, Bradley", "Absent")
print(e1.status)
# prin... | How do I use an input to print a class definition? | I am trying to code something basic in python just for fun and I encountered an issue,
# Employee is a class with the initialization being self, name, status
e1 = Employee("Tom, Lincoln", "Present")
e2 = Employee("Sam, Bradley", "Absent")
print(e1.status)
# printing e1 status will make "Present" or "Absent"
while Tr... | [
"If you want to map names to values, you don't want separate variables. You want a dictionary.\nRather than\ne1 = Employee(\"Tom, Lincoln\", \"Present\")\ne2 = Employee(\"Sam, Bradley\", \"Absent\")\n\nConsider\nemployees = {\n 'e1': Employee(\"Tom, Lincoln\", \"Present\"),\n 'e2': Employee(\"Sam, Bradley\", ... | [
3,
0
] | [] | [] | [
"class",
"input",
"python"
] | stackoverflow_0074241900_class_input_python.txt |
Q:
How do I make a struct point in python?
I'm making a Tetris clone in Pygame based on https://www.youtube.com/watch?v=zH_omFPqMO4 and I need to know how to turn
struct Point
{int x,y;} a[4],b[4];
into Python from C++.
A:
So the C++ code, struct point {int x, y} a[4], b[4] creates a new structure which is a data ... | How do I make a struct point in python? | I'm making a Tetris clone in Pygame based on https://www.youtube.com/watch?v=zH_omFPqMO4 and I need to know how to turn
struct Point
{int x,y;} a[4],b[4];
into Python from C++.
| [
"So the C++ code, struct point {int x, y} a[4], b[4] creates a new structure which is a data type with two ints x and y. The a[4] and b[4] are two created arrays of type point and each of size 4.\nTo replicate a structure in python we could use a class\nExample:\nclass Point:\n def __init__(self, x, y):\n ... | [
0,
0
] | [] | [] | [
"c++",
"python",
"tetris"
] | stackoverflow_0074092062_c++_python_tetris.txt |
Q:
Best way to notify to phone from Python / JS script?
I am currently writing a script to notify me on my phone when a certain product goes on sale (no, I am not a scalper; I am buying a laptop for personal use, and they only currently go on sale for 60-15 minutes at a time in my country). However, I got a bit stuck... | Best way to notify to phone from Python / JS script? | I am currently writing a script to notify me on my phone when a certain product goes on sale (no, I am not a scalper; I am buying a laptop for personal use, and they only currently go on sale for 60-15 minutes at a time in my country). However, I got a bit stuck when deciding on what API/service to use for notifying. S... | [
"\nPushbullet\nhttps://www.pushbullet.com/\n\nTelegram bot\nBut user need to subscribe or join the bot channel, then develope a function to grab chat ID for distributing your messages.\n\n\n"
] | [
0
] | [] | [] | [
"api",
"javascript",
"push_notification",
"python",
"sms"
] | stackoverflow_0067358384_api_javascript_push_notification_python_sms.txt |
Q:
Is possible to eliminate a column of a list of lists if some value is present
I am having a problem with list of lists. I want to know if there is a way to eliminate a column if some value is present
Example:
List = [[1, 4, 1, 1, 1, 4, 1],
[2, 2, 2, 4, 2, 2, 2],
[3, 3, 3, 3, 3, 3, 3]]
if the numbe... | Is possible to eliminate a column of a list of lists if some value is present | I am having a problem with list of lists. I want to know if there is a way to eliminate a column if some value is present
Example:
List = [[1, 4, 1, 1, 1, 4, 1],
[2, 2, 2, 4, 2, 2, 2],
[3, 3, 3, 3, 3, 3, 3]]
if the number 4 is present in the list of lists eliminate that column giving for result:
Result... | [
"Try:\nlst = [[1, 4, 1, 1, 1, 4, 1], \n [2, 2, 2, 4, 2, 2, 2], \n [3, 3, 3, 3, 3, 3, 3]]\n\nout = list(\n map(\n list,\n zip(\n *(\n [0] * len(lst) if any(v == 4 for v in c) else c\n for c in zip(*lst)\n )\n ),\n )\n)\nprint(... | [
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074241874_list_python.txt |
Q:
Use ENV Variables as flags for python script in dockerfile? (Boolean Flags)
Lets say I have the following python script
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--host", required=True)
parser.add_argument("--enabled", default=False, action="store_true")
args = parser.parse_args()
p... | Use ENV Variables as flags for python script in dockerfile? (Boolean Flags) | Lets say I have the following python script
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--host", required=True)
parser.add_argument("--enabled", default=False, action="store_true")
args = parser.parse_args()
print("host: " + args.host)
print("enabled: " + str(args.enabled))
$ python3 test... | [
"For exactly the reasons you're showing here, I'd suggest modifying your script to be able to accept command-line options from environment variables. If you add a line\nparser.set_defaults(\n host=os.environ.get('MY_HOST'),\n enabled=(os.environ.get('MY_ENABLED') == 'true')\n)\n\nthen you can use docker run -e o... | [
1
] | [] | [] | [
"docker",
"dockerfile",
"python"
] | stackoverflow_0074241211_docker_dockerfile_python.txt |
Q:
Drupal 8/9 how do I allow specific sub-folder to execute python scripts?
I have a Drupal 9.x site running in the web-root directory (public_html/). I need to run some python scripts (currently in public_html/python/) and show the output in an iframe called in a Drupal twig template. Permissions on the python files... | Drupal 8/9 how do I allow specific sub-folder to execute python scripts? | I have a Drupal 9.x site running in the web-root directory (public_html/). I need to run some python scripts (currently in public_html/python/) and show the output in an iframe called in a Drupal twig template. Permissions on the python files are 755 but when I load the page that calls the iframe, it shows the python c... | [
"you should use php exec\nhttps://www.php.net/manual/en/function.exec.php\nI recommend to you, to put the python scripts in another directory\nFor example create a directory called /home/pythonScripts\n$ mkdir /home/pythonScripts\n$ touch /home/pythonScripts/hola.py\n$ echo \"print (\\\"Python\\\")\" > hola.py\n$ c... | [
0
] | [] | [] | [
"drupal_8",
"python"
] | stackoverflow_0074230599_drupal_8_python.txt |
Q:
How to fix wmctrl Cannot open display when Python open subprocess
This is my program, and it works very well.
import subprocess
result = subprocess.check_output("wmctrl -l",shell=True,stderr=subprocess.STDOUT)
result = result.decode('UTF-8')
print(result)
Output:
0x03800003 -1 name-PC Desktop
0x03e00037 0 name... | How to fix wmctrl Cannot open display when Python open subprocess | This is my program, and it works very well.
import subprocess
result = subprocess.check_output("wmctrl -l",shell=True,stderr=subprocess.STDOUT)
result = result.decode('UTF-8')
print(result)
Output:
0x03800003 -1 name-PC Desktop
0x03e00037 0 name-PC How to fix wmctrl Cannot open display when Python open subprocess -... | [
"I have find solution myself. The key is to use two commands:\nos.system(\"xhost local:root &>/dev/null\")\n\nallow root opening X windows.\nAnd \n subprocess.check_output([command], shell=True, stderr=subprocess.STDOUT).decode('UTF-8')\ncommand = \"env DISPLAY=:0 XAUTHORITY=/home/ourname/.Xauthority \"+\"wmctrl -l... | [
1,
0,
0
] | [] | [] | [
"linux",
"python",
"subprocess",
"wmctrl"
] | stackoverflow_0055383162_linux_python_subprocess_wmctrl.txt |
Q:
Figuring out how to format the receipt part of my pizza function (Attached is the current output I have)
This is my current output that I have
Your order:
[['S', 'ONION', 'BACON', 'HAM', 'MUSHROOM'], ['L', 'BACON', 'CHICKEN', 'SAUSAGE', 'GROUND BEEF']]
7.99
8.49
11.99
Tax: $2.79
Total: $24.27
Here I want to form... | Figuring out how to format the receipt part of my pizza function (Attached is the current output I have) | This is my current output that I have
Your order:
[['S', 'ONION', 'BACON', 'HAM', 'MUSHROOM'], ['L', 'BACON', 'CHICKEN', 'SAUSAGE', 'GROUND BEEF']]
7.99
8.49
11.99
Tax: $2.79
Total: $24.27
Here I want to format it so the first list is a receipt for its own pizza so it would be like this:
pizza 1: S ... | [
"Does this work for you?\ndef generateReceipt(order):\n basePrices = {'S': 7.99, 'M': 9.99, 'L': 11.99, 'XL': 13.99}\n extraToppingPrices = {'S': 0.5, 'M': 0.75, 'L': 1.0, 'XL': 1.25}\n total = 0.0\n for (i, pizza) in enumerate(order):\n total += basePrices[pizza[0]]\n print(f'pizza {i+1}:... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074242015_python.txt |
Q:
JSON iteration with different format Python
I have a JSON feed i need to collect data from but I am running into some issues with iterating and parsing the API data.
The function below collects what I need but some horses get scratched (dont race) and the format of their JSON is different to horses who's status is... | JSON iteration with different format Python | I have a JSON feed i need to collect data from but I am running into some issues with iterating and parsing the API data.
The function below collects what I need but some horses get scratched (dont race) and the format of their JSON is different to horses who's status is "Starter".
def race_data():
for race_key in... | [
"Use a for loop to iterate through the prices, and check the betType key to see if it's either FixedWin or FixedPlace, that way the ordering of the different prices doesn't matter.\nAlso since the race_key and the race event are always the same you should define them at the top of the function so your implementatio... | [
0
] | [] | [] | [
"iteration",
"json",
"python"
] | stackoverflow_0074242034_iteration_json_python.txt |
Q:
Way to simplify enum?
Is there a better way to initialize all this boilerplate?
class Type(Enum):
Null=auto()
Bool=auto()
Int=auto()
Float=auto()
Decimal=auto()
String=auto()
Bytes=auto()
Date=auto()
Time=auto()
Datetime=auto()
Timestamp=auto()
Interval=auto()
St... | Way to simplify enum? | Is there a better way to initialize all this boilerplate?
class Type(Enum):
Null=auto()
Bool=auto()
Int=auto()
Float=auto()
Decimal=auto()
String=auto()
Bytes=auto()
Date=auto()
Time=auto()
Datetime=auto()
Timestamp=auto()
Interval=auto()
Struct=auto()
Array=auto(... | [
"I can't speak for Pylance, but if you want auto implementations, you can just pass your list of types directly to the Enum function.\nType = Enum('Type', ['Null','Bool','Int','Float','Decimal','String','Bytes',\n 'Date','Time','Datetime','Timestamp','Interval','Struct',\n 'A... | [
4
] | [] | [] | [
"enums",
"python",
"python_3.x"
] | stackoverflow_0074242076_enums_python_python_3.x.txt |
Q:
Python function doesn't return list[int] - solved
I'm still a beginner with just a few months experience in programming. I'm writing a program to roll dice in a few modes. I'm having a problem with my Selective mode.
Code:
from os import system
from platform import system as operating_system
from random import ran... | Python function doesn't return list[int] - solved | I'm still a beginner with just a few months experience in programming. I'm writing a program to roll dice in a few modes. I'm having a problem with my Selective mode.
Code:
from os import system
from platform import system as operating_system
from random import randint, randrange
from textwrap import dedent
from time i... | [
"There is a logic problem in your function number_inclusion, at the bottom of the loop:\n if str(temp_input).upper() == \"REMOVE\":\n print(f\"Saved numbers are:\\n{included_numbers}\")\n try:\n temp_remove: int = int(input(\n \"Which would you like to remove?\\n\"))\n ... | [
1
] | [] | [] | [
"function",
"list",
"python",
"python_3.10",
"return"
] | stackoverflow_0074241659_function_list_python_python_3.10_return.txt |
Q:
Python splitting string by length without cutting words
I am trying to split a string in multiple lines. Here is an example of the string:
Here the line that have to be under 120 chars and cut at the point in the string where the last word is under 120 chars because this part have to be in the second line and it a... | Python splitting string by length without cutting words | I am trying to split a string in multiple lines. Here is an example of the string:
Here the line that have to be under 120 chars and cut at the point in the string where the last word is under 120 chars because this part have to be in the second line and it also needs to be seperated such as the string part before and ... | [
"Using textwrap.wrap:\n>>> text = \"Here the line that have to be under 120 chars and cut at the point in the string where the last word is under 120 chars because this part have to be in the second line and it also needs to be seperated such as the string part before and this has to be in the third line with the e... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074242067_python.txt |
Q:
How to use Python regex pattern matching with re.findall(pattern, string)?
I need to match to the strings "Johnson" and "Jackson", but not the string "Jason." Using Python, I need to use the function findall in the RegEx library.
I tried:
a = "Jackson, Johnson, Jason"
b = re.findall("J*\w{2}*son", a)
and it did n... | How to use Python regex pattern matching with re.findall(pattern, string)? | I need to match to the strings "Johnson" and "Jackson", but not the string "Jason." Using Python, I need to use the function findall in the RegEx library.
I tried:
a = "Jackson, Johnson, Jason"
b = re.findall("J*\w{2}*son", a)
and it did not work! If there is anyone that can help, i would very much appreciate it!
| [
"findall only works with a string as input not a list.\nYou probably want to use map and re.match or re.search for example:\nAlso your regex has multiple repeat symbols in it and needs some tuning, this one seems to work J\\w{3}son\nimport re\na = [\"Jackson\", \"Johnson\", \"Jason\"]\nc = list(map(lambda x: re.sea... | [
2
] | [] | [] | [
"findall",
"pattern_matching",
"python",
"python_3.x",
"regex"
] | stackoverflow_0074242147_findall_pattern_matching_python_python_3.x_regex.txt |
Q:
pySimpleGUI two filebrowser events were reversed
Why the sg.filebrowser were reversed on my code? when I select CUSID file then then event is SPlist and when I select SPlist file then it is cusid event...
import PySimpleGUI as sg
sg.theme('SystemDefaultForReal')
layout = [
[sg.FileBrowse('CUSID',... | pySimpleGUI two filebrowser events were reversed | Why the sg.filebrowser were reversed on my code? when I select CUSID file then then event is SPlist and when I select SPlist file then it is cusid event...
import PySimpleGUI as sg
sg.theme('SystemDefaultForReal')
layout = [
[sg.FileBrowse('CUSID',size = (15,2),file_types =('Excel File', '*.xlsx'), ke... | [
"\nThe FileBrowse, FolderBrowse, FileSaveAs , FilesSaveAs, CalendarButton, ColorChooserButton buttons all fill-in values into another element located on the window. The target can be a Text Element or an InputText Element or the button itself. The location of the element is specified by the target variable in the f... | [
0
] | [] | [] | [
"pysimplegui",
"python",
"python_3.x"
] | stackoverflow_0074241753_pysimplegui_python_python_3.x.txt |
Q:
Tell f2py to skip a function
I am using f2py to compile a Fortran library such that I can import it in python so that I can easily create unit tests. However, one of the functions in the module uses an allocatable array to read a matrix from a file (the size of the matrix is not know until it is read). Unfortunate... | Tell f2py to skip a function | I am using f2py to compile a Fortran library such that I can import it in python so that I can easily create unit tests. However, one of the functions in the module uses an allocatable array to read a matrix from a file (the size of the matrix is not know until it is read). Unfortunately, f2py does not support allocata... | [
"In the f2py docs here it says that you can skip a function by doing this: \n f2py -h <filename.pyf> <options> <fortran files> \\\n [[ only: <fortran functions> : ] \\\n [ skip: <fortran functions> : ]]... \\\n [<fortran files> ...]\n\nwhere skip:\"\" can be used to sk... | [
3,
0
] | [] | [] | [
"f2py",
"fortran",
"python",
"unit_testing"
] | stackoverflow_0054603252_f2py_fortran_python_unit_testing.txt |
Q:
Problème with async function
i have a function that check every 30 second if a streamer is on live. it work with a while true whith if inside and a time.sleep(30) at the end of the while.
stream = request_twitch_stream("can't show", "can't show", "can't show") #return all the information about a live (view, title,... | Problème with async function | i have a function that check every 30 second if a streamer is on live. it work with a while true whith if inside and a time.sleep(30) at the end of the while.
stream = request_twitch_stream("can't show", "can't show", "can't show") #return all the information about a live (view, title, streamer_ame etc)
embed_on=d... | [
"You can reorganize your function check_stream as follows. All of your code before and after this function can remain the same.\ndef check_stream():\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n prev = True\n while True:\n if request_twitch_stream_bool(\"can't show\", \"can'... | [
0
] | [] | [] | [
"async_await",
"asynchronous",
"discord.py",
"python",
"python_asyncio"
] | stackoverflow_0074224259_async_await_asynchronous_discord.py_python_python_asyncio.txt |
Q:
Match all the characters in a regular expression untill an specific sequence or characters in order
I want to match this text:
<SERIES>
<OWNER-CIK>0000003521
<SERIES-ID>S000020958
<SERIES-NAME>Alger Small Cap Focus Fund
<CLASS-CONTRACT>
<CLASS-CONTRACT-ID>C000059340
<CLASS-CO... | Match all the characters in a regular expression untill an specific sequence or characters in order | I want to match this text:
<SERIES>
<OWNER-CIK>0000003521
<SERIES-ID>S000020958
<SERIES-NAME>Alger Small Cap Focus Fund
<CLASS-CONTRACT>
<CLASS-CONTRACT-ID>C000059340
<CLASS-CONTRACT-NAME>Alger Small Cap Focus Fund Class I
<CLASS-CONTRACT-TICKER-SYMBOL>AOFIX
</CLASS-CO... | [
"Just use .*? between the end anchors. You'll need re.S so the . matches newlines. The ? makes it the shortest match, in case the ending anchor appears multiple times.\nSo the full string would be\nr\"<SERIES>.*?</SERIES>\"\n\n",
"This should work. It uses a lookahead so it knows when to stop.\nimpo... | [
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074242291_python_regex.txt |
Q:
Merge PPTX python
I’m trying to merge multiple PowerPoint presentations at once and have had no luck doing it and keeping formatting. Only way I found was aspose cloud and while it works well it’s very slow. I’m looking to do it with pptx-Python and keep formatting. Thanks
I tried with the standard merge code I fo... | Merge PPTX python | I’m trying to merge multiple PowerPoint presentations at once and have had no luck doing it and keeping formatting. Only way I found was aspose cloud and while it works well it’s very slow. I’m looking to do it with pptx-Python and keep formatting. Thanks
I tried with the standard merge code I found online but it loses... | [
"You could try something like...\nfrom pptx import Presentation\nimport os\nimport glob\nimport copy\n\nimgDict = {}\n\n\npres = glob.glob(\"*.pptx\")\nprs1 = Presentation(pres[0])\nfor presentation in pres[1:]:\n pres = Presentation(presentation)\n for slide in pres.slides:\n sl = prs1.slides.add_slid... | [
0
] | [] | [] | [
"merge",
"powerpoint",
"python",
"python_3.x",
"python_pptx"
] | stackoverflow_0074242031_merge_powerpoint_python_python_3.x_python_pptx.txt |
Q:
autovivify non-sequential array/list in Python like Perl
In perl I can have what I think are called sparse arrays.
my @a;
$a[4321] = "blah";
and it just does what I want. I don't know how to do this in Python without an error IndexError: list assignment index out of range. What is the (simplest) way to do this in... | autovivify non-sequential array/list in Python like Perl | In perl I can have what I think are called sparse arrays.
my @a;
$a[4321] = "blah";
and it just does what I want. I don't know how to do this in Python without an error IndexError: list assignment index out of range. What is the (simplest) way to do this in Python?
| [
"That array is not sparse. It has 4322 elements.\nIn Python, the following would create a similar construct:\na = [ None for i in range( 4321 ) ] + [ \"blah\" ]\n\nIf you want to set an element of an array that might be beyond the end of an existing array, @OmnipotentEntity proposed this function.\ndef set_at( xs, ... | [
1
] | [] | [] | [
"arrays",
"list",
"perl",
"python"
] | stackoverflow_0074241969_arrays_list_perl_python.txt |
Q:
Accessing a specific class attribute within an index?
I made a basic Python RPG game , and I'm attempting to recreate it with object-oriented programming. My goal is to have each battle scene capable of importing a character class object with a given amount of health and a list of attacks it can use, and an enemy ... | Accessing a specific class attribute within an index? | I made a basic Python RPG game , and I'm attempting to recreate it with object-oriented programming. My goal is to have each battle scene capable of importing a character class object with a given amount of health and a list of attacks it can use, and an enemy object with health and a list of attacks it can use as well... | [
"So first, you're attacklist variable attached to the player_class object contains objects, not integers. (Note, change the name of the Class class to something else. It's not good practice to use names one keystroke off of a keyword! Maybe RPGClass? Makes it a little more distinguishable.)\n# Wrong, returns an ... | [
0
] | [] | [] | [
"game_development",
"python",
"python_3.x"
] | stackoverflow_0074242225_game_development_python_python_3.x.txt |
Q:
In Pytorch, how do you multiply a (b, c, h, w) size tensor with a tensor of size (c)
I have to normalize a tensor of size size (b, c, h, w) with two tensors of size (c) which represent the respective mean and standard deviation.
I cannot manage to figure out how to multiply a tensor of shape, let say torch.Size([1... | In Pytorch, how do you multiply a (b, c, h, w) size tensor with a tensor of size (c) | I have to normalize a tensor of size size (b, c, h, w) with two tensors of size (c) which represent the respective mean and standard deviation.
I cannot manage to figure out how to multiply a tensor of shape, let say torch.Size([1, 3, 128, 128]) with a tensor of shape torch.Size([3]).
What I want to accomplish is: take... | [
"img * mean.reshape(1,3,1,1)\n\nWill reshape the mean tensor so that torch can understand which dimensions you are trying to multiply together.\nEdit for details:\nTorch reads tensor sizes from lowest to highest dimension, so it can infer some of the higher dimensions (e.g. img * mean.reshape(3,1,1) also works in y... | [
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074242409_python_pytorch.txt |
Q:
run python script multiple times with different files from differents directories
I tried to execute a python script multiple times but with different CSV Files from different directories but I know how to do it with just one directory...
Here is the tree structure:
Directory_1
|
|---> FileA
|---> FileB
.....
... | run python script multiple times with different files from differents directories | I tried to execute a python script multiple times but with different CSV Files from different directories but I know how to do it with just one directory...
Here is the tree structure:
Directory_1
|
|---> FileA
|---> FileB
.....
Directory_2
|
|---> File2_A
|---> File2_B
.....
My code:
import os
import sys
di... | [
"Provided the files will be sorted in both directories and match pair by pair based on order, you can just zip them together, iterating on both directories at once. You can also filter only the CSV's for iteration.\nimport os\n\ndirectory1_path = \"CSV_Files/FileX_CSV/\"\ndirectory2_path = \"CSV_Files/File2_X_CSV/\... | [
0
] | [] | [] | [
"csv",
"directory",
"exec",
"path",
"python"
] | stackoverflow_0074242102_csv_directory_exec_path_python.txt |
Q:
Print docstring with default --help function
I have a code that looks like:
#!/usr/bin/env python
'''Plot multiple DOS/PDOS in a single plot
run python dplot.py -h for more usage
'''
import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
parser = argparse.ArgumentParser()
# parser.add_arg... | Print docstring with default --help function | I have a code that looks like:
#!/usr/bin/env python
'''Plot multiple DOS/PDOS in a single plot
run python dplot.py -h for more usage
'''
import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
parser = argparse.ArgumentParser()
# parser.add_argument('--dos', help='Plot the dos', required=True)... | [
"Initialize argparse.ArgumentParser with more information:\nargparse.ArgumentParser(\n description='description')\n\nSo putting your doc-string in the description should do the trick. Check the documentation for more info.\n",
"You can get the local module docstring with __doc__ If you use that as the descrip... | [
2,
2
] | [] | [] | [
"docstring",
"python"
] | stackoverflow_0074242407_docstring_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.