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:
Do something specific if python scripts exits because of error
My script sometimes errors which is fine, but I have to manually restart the script.
Anyone knows how to make it so that it actually works infinitely even if it crashed 50 times, currently what I have only works for 1 crash.
try:
while True:
... | Do something specific if python scripts exits because of error | My script sometimes errors which is fine, but I have to manually restart the script.
Anyone knows how to make it so that it actually works infinitely even if it crashed 50 times, currently what I have only works for 1 crash.
try:
while True:
do_main_logic()
except:
continue
I have tried many scripts,... | [
"Wrap only do_main_logic() in a try-except block, not the full loop.\nwhile True:\n try:\n do_main_logic()\n except:\n pass\n\nCaveat: Catching bare exceptions is frowned upon for good reason. It would be better if you could specify the type(s) of exceptions you expect. To cite the Programming R... | [
3
] | [
"You want to do it forever ?\nJust add a while :)\nwhile True:\n try:\n while True:\n do_main_logic()\n\n\n except:\n continue\n\n"
] | [
-2
] | [
"automation",
"loops",
"python"
] | stackoverflow_0074381966_automation_loops_python.txt |
Q:
Does Python have a .pdbinit file (similar to .gdbinit file)?
With gdb there is a .gdbinit[1] file that you can put lots of things that are important/necessary for more complex debugging sessions.
For example my recent Python debugging session required:
numerous breakpoints
numerous display expressions (similar to... | Does Python have a .pdbinit file (similar to .gdbinit file)? | With gdb there is a .gdbinit[1] file that you can put lots of things that are important/necessary for more complex debugging sessions.
For example my recent Python debugging session required:
numerous breakpoints
numerous display expressions (similar to watch expressions in gdb)
and I would like to have conditional br... | [
"I think the closest file to .gdbinit is .pdbrc. This is where one can store aliases to make debugging more convenient. However, one can write arbitrary code in this file that can be used to extend the pdb debugger.\nMost of the tutorials about this file cover aliases in detail, but you may be able to find a way to... | [
2
] | [] | [] | [
"pdb",
"python"
] | stackoverflow_0074381737_pdb_python.txt |
Q:
Merge 2 lists into dataframe and pivot based on string slice of index
I have two lists in Python, cohorts and pct_error_avgs:
['FGLMC 1.5 2020',
'FGLMC 1.5 2021',
'FNCI 1.5 2020',
'FNCI 1.5 2021',
'FNCL 1.5 2020',
'FNCL 1.5 2021',
'G2SF 1.5 2021',
'FGLMC 2.5 2016',
'FGLMC 2.5 2019',
'FGLMC 2.5 2020',
'FG... | Merge 2 lists into dataframe and pivot based on string slice of index | I have two lists in Python, cohorts and pct_error_avgs:
['FGLMC 1.5 2020',
'FGLMC 1.5 2021',
'FNCI 1.5 2020',
'FNCI 1.5 2021',
'FNCL 1.5 2020',
'FNCL 1.5 2021',
'G2SF 1.5 2021',
'FGLMC 2.5 2016',
'FGLMC 2.5 2019',
'FGLMC 2.5 2020',
'FGLMC 2.5 2021',
'FGLMC 2.5 2013',
'FNCI 2.5 2016',
'FNCI 2.5 2017',
'FNC... | [
"You can extract the year from your index by first resetting the index to be a normal column. Then use string split to get the year and put that in it's own column. Then remove the year from the string column and then use the pivot function.\nlr_pct_errors = lr_pct_errors.reset_index()\nlr_pct_errors['year'] = lr_p... | [
3
] | [] | [] | [
"colormap",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074381732_colormap_dataframe_pandas_python.txt |
Q:
Logic to convert flat JSON to nested JSON
I have a flat JSON where keys represent different levels.
For example:
data = {
"name": "John",
"age": 30,
"address:city": "New-York",
"address:street": "5th avenue",
"address:number": 10,
}
As you can see keys contains : which is the separat... | Logic to convert flat JSON to nested JSON | I have a flat JSON where keys represent different levels.
For example:
data = {
"name": "John",
"age": 30,
"address:city": "New-York",
"address:street": "5th avenue",
"address:number": 10,
}
As you can see keys contains : which is the separator for the level.
I would like to convert it to... | [
"I think an easy approach would be to create a method that maps this JSON to an object, and then convert the object to another object with attributes such as in the \"wanted\" one, and then you can simply convert the result object to JSON that will have \"wanted\" structure\n",
"A recursive approach that supports... | [
1,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"json",
"python"
] | stackoverflow_0074380421_algorithm_json_python.txt |
Q:
Create new column detailing the "i"th occurence of a value in another column
I am attempting to create a new column in a data frame ("occurence") as seen below that details how many times a particular id has already been seen. I understand that Counter (if turned into a list) or value_counts() will count the total... | Create new column detailing the "i"th occurence of a value in another column | I am attempting to create a new column in a data frame ("occurence") as seen below that details how many times a particular id has already been seen. I understand that Counter (if turned into a list) or value_counts() will count the total number of occurences. But I am trying to structure my dataframe as follows:
id ... | [
"A possible solution:\ndf['occurrence'] = df.groupby('id').transform('cumcount')+1\n\nOutput:\n id occurence\n0 123456 1\n1 987641 1\n2 123456 2\n3 987641 2\n4 123456 3\n5 123456 4\n6 212212 1\n\n"
] | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074381935_pandas_python.txt |
Q:
How to compare two columns in different pandas dataframes, store the differences in a 3rd dataframe
I need to compare two df1 (blue) and df2 (orange), store only the rows of df2 (orange) that are not in df1 in a separate data frame, and then add that to df1 while assigning function 6 and sector 20 for the employee... | How to compare two columns in different pandas dataframes, store the differences in a 3rd dataframe | I need to compare two df1 (blue) and df2 (orange), store only the rows of df2 (orange) that are not in df1 in a separate data frame, and then add that to df1 while assigning function 6 and sector 20 for the employees that were not present in df1 (blue)
I know how to find the differences between the data frames and sto... | [
"This has been answered in pandas get rows which are NOT in other dataframe\nStore it as a merge and simply select the rows that do not share common values.\n~ negates the expression, select all that are NOT IN instead of IN.\ncommon = df1.merge(df2,on=['ID','Name'])\ndf = df2[(~df2['ID'].isin(common['ID']))&(~df2[... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074381858_pandas_python.txt |
Q:
Spacing of two printed shapes side by side individually
So I have to print dual diamonds side by side with the user input as half of the rows in the diamond. However, my middle rows of both diamonds are touching each other. There needs to be a space between both shapes so theyre two unconnected diamonds, and Im un... | Spacing of two printed shapes side by side individually | So I have to print dual diamonds side by side with the user input as half of the rows in the diamond. However, my middle rows of both diamonds are touching each other. There needs to be a space between both shapes so theyre two unconnected diamonds, and Im unsure of how to do it without botching the whole code up.
rows... | [
"Think of the output as being on checkerboard paper. Each character is either a space or an asterisk. The printing process is either \"this is a gap\" or \"this is a diamond\".\nThe following arrangement is desired:\ngap + stars + gap + gap + stars\nYou currently have:\ngap + asterisks\nAll you need to do is to pas... | [
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074381839_loops_python.txt |
Q:
SEGMENTATION FAULT when running inference on tflite_runtime converted model
I am trying to convert and run a small keras model with tflite_runtime. Converting to tflite works and running inference with tf.lite also works well, however when using the interpreter from tflite_runtime.interpreter I get "segmentation f... | SEGMENTATION FAULT when running inference on tflite_runtime converted model | I am trying to convert and run a small keras model with tflite_runtime. Converting to tflite works and running inference with tf.lite also works well, however when using the interpreter from tflite_runtime.interpreter I get "segmentation fault: 11" and no other error messages. Any ideas on how to solve? I need this to ... | [
"Simply read from the website TFLite-Interpreter you need to create a correct target method.\nSample: I create a test and simple convert it to the TFLite by model.save and read its input/output for proving the save and recalling works.\nimport os\nfrom os.path import exists\n\nimport tensorflow as tf\nimport tflite... | [
0,
0
] | [] | [] | [
"keras",
"python",
"tensorflow",
"tflite"
] | stackoverflow_0074012227_keras_python_tensorflow_tflite.txt |
Q:
Writerow coma separates the items I pass to him don't know why
I have la list: final_data = ['0.0267166', '0.0534331', '0.0801497', '0.106866', ...]
I'm trying to write this data into .csv file with csv module from python (no pandas allowed)
so I'm using this code from documentation
with open('final_data.csv', 'w+... | Writerow coma separates the items I pass to him don't know why | I have la list: final_data = ['0.0267166', '0.0534331', '0.0801497', '0.106866', ...]
I'm trying to write this data into .csv file with csv module from python (no pandas allowed)
so I'm using this code from documentation
with open('final_data.csv', 'w+', newline='') as f:
f = open('final_data.csv', "w+")
writer... | [
"Try this:\nimport csv\n\nfinal_data = ['0.0267166', '0.0534331', '0.0801497', '0.106866']\nfinal_data = [[e] for e in final_data]\n\nwith open(r'path_to_your_outputCsv.csv', 'w', newline=\"\\n\") as f:\n wr = csv.writer(f)\n wr.writerow(['final_data'])\n wr.writerows(final_data)\n\n# Output (.csv) :\nfina... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074382055_python.txt |
Q:
Why is the bind not triggering when i press the left or right key? Tkinter
When I press the right or left key, the bind in move_ball doesn't get triggered.
Is this something to do with the OOP side or the Tkinter side?
Can .bind be anywhere in the code or does it need to be in the same class?
Any help?
This is to ... | Why is the bind not triggering when i press the left or right key? Tkinter | When I press the right or left key, the bind in move_ball doesn't get triggered.
Is this something to do with the OOP side or the Tkinter side?
Can .bind be anywhere in the code or does it need to be in the same class?
Any help?
This is to allow me to post because apparently I don't have enough details.
from tkinter im... | [
"The issue is that a canvas widget by default does not get the keyboard focus, so it will not see any keyboard events. You can give it the keyboard focus by calling focus_set on the widget.\nclass Game():\n def __init__(self, window):\n ...\n self.canvas = Canvas(window, width = 600, height = 400, ... | [
1
] | [] | [] | [
"class",
"oop",
"python",
"tkinter"
] | stackoverflow_0074381779_class_oop_python_tkinter.txt |
Q:
How to center x/y labels on the visible axes spine, not the plot area
My plot has ylim(0,0.08), but I am only displaying up to 0.06. The problem is, my ylabel is centered on a spine that is 0.08, instead of 0.06. Is there a way to have the label centered only on the visible spine?
A:
The y label gets positioned ... | How to center x/y labels on the visible axes spine, not the plot area | My plot has ylim(0,0.08), but I am only displaying up to 0.06. The problem is, my ylabel is centered on a spine that is 0.08, instead of 0.06. Is there a way to have the label centered only on the visible spine?
| [
"The y label gets positioned in \"axes coordinates\" relative to the main plot area (0 at the bottom, 1 at the top, so 0.5 to have it centered).\nYou can recalculate the position proportional to the ylim and the extreme y ticks.\nThe following example uses sns.despine(trim=True) to cut the y-axis. A maximum y-tick ... | [
2
] | [
"import matplotlib.pyplot as plt #3.5\nimport numpy as np\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 5))\n\nax1.set_yticks(np.linspace(0, 0.08, 9))\nax1.set_ylim(0, 0.08)\nax1.set_ylabel('Fraction', loc='center')\n\nax2.set_yticks(np.linspace(0, 0.06, 7))\nax2.set_ylim(0, 0.06)\nax2.set_ylabel('Fraction',... | [
-1
] | [
"axis_labels",
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0074381373_axis_labels_matplotlib_python_seaborn.txt |
Q:
matching regex for custom params in URI
I am building a web framework and REGEX is really hostile today.
I do not like the django way of formatting custom params with angle brackets
url/<param>/... or
<str:token>/
I would prefer the way js and other programs handle this
name/:token/:another_param
After trying fo... | matching regex for custom params in URI | I am building a web framework and REGEX is really hostile today.
I do not like the django way of formatting custom params with angle brackets
url/<param>/... or
<str:token>/
I would prefer the way js and other programs handle this
name/:token/:another_param
After trying for 45 minutes I am giving up. I would like to ... | [
"You don't want to match :: and apparently also not :/\nWhat you can do is use a single negative lookahead to assert that those 2 strings do not occur.\n^(?![/\\w:]*:[:/])[/\\w:]*$\n\nExplanation\n\n^ Start of string\n(?![/\\w:]*:[:/]) Negative lookahead, assert not :: or :/ to the right\n[/\\w:]* Optionally repeat... | [
1
] | [] | [] | [
"html",
"javascript",
"python",
"regex",
"web"
] | stackoverflow_0074377131_html_javascript_python_regex_web.txt |
Q:
Why wont this part of my code make a tempfile?
I just made a account here so sorry in advance
I am trying to make a tool that will give me some information about my discord account etc, put it into a file, zip it up and send it to a discord webhook.
The zip file gets sent to the webhook with no errors, and everyth... | Why wont this part of my code make a tempfile? | I just made a account here so sorry in advance
I am trying to make a tool that will give me some information about my discord account etc, put it into a file, zip it up and send it to a discord webhook.
The zip file gets sent to the webhook with no errors, and everything except the discord part is in the file. Here is ... | [
"Take a look at Python's tempfile module. Here is a quick example that is similar to your example, but with a few layers of complexity removed for illustrative purposes. You can remove the seek() and .read() and put in whatever you would like to do with the temp file or the data written to it.\nCode\nimport tempfil... | [
0
] | [] | [] | [
"discord",
"python",
"temporary_files",
"webhooks"
] | stackoverflow_0074382069_discord_python_temporary_files_webhooks.txt |
Q:
How would I add a space character to ascii_lowercase
So im making a code that'll encrypt a character or word per se. Im done with that so far but would like to include a space character and continue on with an extra word to encrypt. "Congratulations you won"<<<
from random import shuffle
from string import ascii_l... | How would I add a space character to ascii_lowercase | So im making a code that'll encrypt a character or word per se. Im done with that so far but would like to include a space character and continue on with an extra word to encrypt. "Congratulations you won"<<<
from random import shuffle
from string import ascii_lowercase
array=[0]*26
for i in range(26):
array[i]=i
... | [
"Use + to concatenate strings.\nlet = ascii_lowercase + \" \"\n\nThen replace ord(get[i]) - 97 with the value of let.index(get[i]), since that formula only works for lowercase letters.\nYou also need to increase the length of array to 27, to add a place for the encrypted spaces.\nfrom random import shuffle\nfrom st... | [
0
] | [] | [] | [
"append",
"ascii",
"encryption",
"python"
] | stackoverflow_0074382163_append_ascii_encryption_python.txt |
Q:
TypeError: argument must be sequence while using Pillow
The goal is to overlay pfp on top of template, and then place the string description underneath pfp. When I run the code, I get the error TypeError: argument must be sequence.
def edit(template, pfp, description):
x = (template.size[0] - image.size[0])/2
... | TypeError: argument must be sequence while using Pillow | The goal is to overlay pfp on top of template, and then place the string description underneath pfp. When I run the code, I get the error TypeError: argument must be sequence.
def edit(template, pfp, description):
x = (template.size[0] - image.size[0])/2
y = (template.size[1] - image.size[1])/2
Image.Image.... | [
"Try putting your x, y coordinates inside a tuple:\ndraw.text((x,y)), \"Text\")\n\n"
] | [
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0074381965_python_python_imaging_library.txt |
Q:
How to run a cmd with "start" using subprocess in Python
I am trying to start a program called drive snapshot via python script, however I cannot make it work with subprocess.
If below cmd is used directly in command line, it works just fine:
start pathtoprogram pathtoimage E: -vq
However, in python, when I am tr... | How to run a cmd with "start" using subprocess in Python | I am trying to start a program called drive snapshot via python script, however I cannot make it work with subprocess.
If below cmd is used directly in command line, it works just fine:
start pathtoprogram pathtoimage E: -vq
However, in python, when I am trying to use:
subprocess.run("start pathtoprogram pathtoimage E... | [
"Set the shell param to True when invoking the subprocess.run() method.\nsubprocess.run(\"start pathtoprogram pathtoimage E: -vq\", shell=True)\n\n"
] | [
0
] | [
"try this:\nfrom subprocess import Popen as po\ncmd = ['pathtoprogram', 'pathtoimage', 'E:', '-vq']\nmy_process = po(cmd) #start the process\nmy_process.wait() #wait for the process to finish\nprint('process has finished')\n\nor this:\nfrom subprocess import Popen as po\ncmd = ['pathtoprogram', 'pathtoimage', 'E:',... | [
-1
] | [
"cmd",
"python",
"subprocess",
"windows"
] | stackoverflow_0071469284_cmd_python_subprocess_windows.txt |
Q:
Space between Menus in Tkinter Menu
I have the below tkinter menubar. It all works great, accept the menus within it are all bunched up close together.
Can anyone please tell me if there's a way to add left and right padding between the menus.
I don't mean the separator in the menu items, but padding between the t... | Space between Menus in Tkinter Menu | I have the below tkinter menubar. It all works great, accept the menus within it are all bunched up close together.
Can anyone please tell me if there's a way to add left and right padding between the menus.
I don't mean the separator in the menu items, but padding between the top menus in the menubar, such as between ... | [
"Generally speaking, no, you don't have control over this. There are no options to modify the space between items on a menubar. On Windows and OSX menus are handled by the OS and tkinter has very little control over them. For unix-based systems, it might be possible to dig into the tk source code and see how the me... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074381327_python_tkinter.txt |
Q:
How to solve CDK CLI version mismatch
I'm getting following error:
This CDK CLI is not compatible with the CDK library used by your application. Please upgrade the CLI to the latest version.
(Cloud assembly schema version mismatch: Maximum schema version supported is 8.0.0, but found 9.0.0)
after issuing cdk dif... | How to solve CDK CLI version mismatch | I'm getting following error:
This CDK CLI is not compatible with the CDK library used by your application. Please upgrade the CLI to the latest version.
(Cloud assembly schema version mismatch: Maximum schema version supported is 8.0.0, but found 9.0.0)
after issuing cdk diff command.
I did run npm install -g aws-cdk... | [
"I encountered this issue with a typescript package, after upgrading the cdk in package.json. As Maciej noted upgrading did not seem to work. I am installing the cdk cli with npm, and an uninstall followed by an install fixed the issue.\nnpm -g uninstall aws-cdk\nnpm -g install aws-cdk\n\n",
"So I've fixed it, b... | [
31,
5,
3,
2,
0,
0,
0,
0
] | [] | [] | [
"aws_cdk",
"python"
] | stackoverflow_0066565550_aws_cdk_python.txt |
Q:
How can I know the numbers of colours in plt.quiver from matplotlib
I have written a code in matplotlib pyplot
import matplotlib.pyplot as plt
plt.quiver(x,y,u,v, colour)
Here the color is a list of float numbers. My question is how can I know which number represents blue/green etc.
I tried 500 it seems purple, i... | How can I know the numbers of colours in plt.quiver from matplotlib | I have written a code in matplotlib pyplot
import matplotlib.pyplot as plt
plt.quiver(x,y,u,v, colour)
Here the color is a list of float numbers. My question is how can I know which number represents blue/green etc.
I tried 500 it seems purple, it needs green/blue/yellow, ..etc
I tried random numbers but it was not u... | [
"You can execute help(plt.quiver) to quickly read its documentation.\nWhen you call plt.quiver(x,y,u,v, colour), matplotlib uses a colormap to assing a color to each value of colour. You can change the colormap with the cmap option. In the following example I'll map the magnitude of the vector field to a colormap:\... | [
0
] | [] | [] | [
"colors",
"matplotlib",
"plot",
"python",
"scatter_plot"
] | stackoverflow_0074382035_colors_matplotlib_plot_python_scatter_plot.txt |
Q:
Trying to fake and rotating user agents
I am trying to fake user agents as well as rotate them in Python.
I found a tutorial online about how to do this with Scrapy using scrapy-useragents package.
I scrape the webpage, https://www.whatsmyua.info/, in order to check my user agent to see if it is different then min... | Trying to fake and rotating user agents | I am trying to fake user agents as well as rotate them in Python.
I found a tutorial online about how to do this with Scrapy using scrapy-useragents package.
I scrape the webpage, https://www.whatsmyua.info/, in order to check my user agent to see if it is different then mine and if it rotates. Is it different then my... | [
"Here you can find an API returning the most common user-agents as JSON :\nhttp://51.158.74.109/useragents/?format=json\nI have used this tool which will keep your list of user-agents always updated with most recent and most used user-agents : https://pypi.org/project/shadow-useragent/\n from shadow_useragent i... | [
5,
1,
0
] | [] | [] | [
"python",
"scrapy",
"scrapy_splash",
"splash_js_render",
"user_agent"
] | stackoverflow_0056082653_python_scrapy_scrapy_splash_splash_js_render_user_agent.txt |
Q:
How to plot prediction map in SVC algorithm
Currently I am testing an SVC model, and I'd like to create decision maps like those shown in books or in link https://scikit-learn.org/stable/modules/svm.html:
Example of what I have in mind:
But I have no idea, how it's done or if theres a function for this.
I've trie... | How to plot prediction map in SVC algorithm | Currently I am testing an SVC model, and I'd like to create decision maps like those shown in books or in link https://scikit-learn.org/stable/modules/svm.html:
Example of what I have in mind:
But I have no idea, how it's done or if theres a function for this.
I've tried looking on google but found nothing.
Thanks for... | [
"use matplotlib. test make_blobs data and try to add more style\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use(\"ggplot\")\nfrom sklearn.datasets import make_blobs\nX, y = make_blobs(n_samples=40, centers=2, random_state=42, cluster_std=1.25)\nplt.scatter(X[:, 0], X[:,... | [
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0074381713_python_scikit_learn.txt |
Q:
SMTP and Variable
I am very new in Python.
While developing SMTP program with smtplib lib, some unexpected thing happended.
When I send the e-mail, the f-string does not work.
Could you tell me what is the problem?
`
import pickle
import smtplib
from smtplib import*
from email.mine.text import MINETEXT
def email... | SMTP and Variable | I am very new in Python.
While developing SMTP program with smtplib lib, some unexpected thing happended.
When I send the e-mail, the f-string does not work.
Could you tell me what is the problem?
`
import pickle
import smtplib
from smtplib import*
from email.mine.text import MINETEXT
def email():
with open ("tem... | [
"I'm not that familiar with python, but a few points that immediately stood out to me:\n\nAre you sure that your imports are correct? I'm guessing\nemail.mine.text should be email.mime.text, and MINETEXT should be\nMIMETEXT.\nIt would help if you could share some sample contents of the text file you're using. Does ... | [
0
] | [] | [] | [
"binary",
"pickle",
"python",
"python_3.x",
"smtp"
] | stackoverflow_0074348428_binary_pickle_python_python_3.x_smtp.txt |
Q:
Python - Factory functions with different arguments
I have logic in my application that requires me to create different variations of one specific class. These variations differ only by class properties.
If variation == "A", then some class properties need to be set to zero and others filled with the provided inpu... | Python - Factory functions with different arguments | I have logic in my application that requires me to create different variations of one specific class. These variations differ only by class properties.
If variation == "A", then some class properties need to be set to zero and others filled with the provided input, else if variation == "B", some other properties are ze... | [
"You can use typing.TypedDict to provide a more specifically typed dict that knows what type of value each specific key maps to.\nfrom typing import TypedDict, Callable\n\nclass FactoryType(TypedDict):\n one: Callable[[str], str]\n two: Callable[[str, str], str]\n three: Callable[[str, str, str], str]\n\n\... | [
0,
0
] | [] | [] | [
"factory",
"python",
"type_hinting",
"types"
] | stackoverflow_0074382168_factory_python_type_hinting_types.txt |
Q:
random float numbers and their mean and standart deviation
how to get a list of 1000 random float numbers without dublicates and find their mean value in python?
import random
rnd_number=random.random()
def a():
l=[]
m=1
for i in range(1000):
l.append(rnd_number)
ret... | random float numbers and their mean and standart deviation | how to get a list of 1000 random float numbers without dublicates and find their mean value in python?
import random
rnd_number=random.random()
def a():
l=[]
m=1
for i in range(1000):
l.append(rnd_number)
return l
for i in l:
m=m+i
return m... | [
"If you want to have distinct random numbers, you have to draw number on every loop iteration. To avoid duplicates you can use set, which stores unique values.\nimport random\n\ndef a():\n mySet = set()\n while len(mySet) < 1000:\n mySet.add(random.random())\n return mySet\n\nprint(a())\n\n",
"Hop... | [
0,
0,
0
] | [] | [] | [
"mean",
"numbers",
"python"
] | stackoverflow_0074381866_mean_numbers_python.txt |
Q:
running async code within a function which contains blocking code
import asyncio
import time
def blocking_function():
print("Blocking function called")
time.sleep(5)
print("Blocking function finished")
async def concurrent_function():
for x in range(10):
print(x)
await asyncio.sle... | running async code within a function which contains blocking code | import asyncio
import time
def blocking_function():
print("Blocking function called")
time.sleep(5)
print("Blocking function finished")
async def concurrent_function():
for x in range(10):
print(x)
await asyncio.sleep(1)
async def main():
print("Main function called")
loop ... | [
"just create an event loop in the second thread and run the async function there.\nimport asyncio\nimport time\n\nasync def blocking_function():\n for x in range(4):\n print(\"Blocking function called\")\n time.sleep(1)\n print(\"Blocking function finished\")\n print(\"Async code runn... | [
1
] | [] | [] | [
"asynchronous",
"python",
"python_asyncio"
] | stackoverflow_0074382205_asynchronous_python_python_asyncio.txt |
Q:
A server that handles clients in the background while you can still type in commands
I have been trying to make a server where multiple people can connect but i keep getting stuck on one problem. Allowing the server to listen to a client while the server host is still able to type in commands.
running = True
whil... | A server that handles clients in the background while you can still type in commands | I have been trying to make a server where multiple people can connect but i keep getting stuck on one problem. Allowing the server to listen to a client while the server host is still able to type in commands.
running = True
while running:
command = input('>> ') # Allow for inputs but still connect new users (ex, ... | [
"you could create a ClientHandler or create two methods. smth like this:\ndef connecting_users():\n # accept connections\n thread = threading.Thread(target=server_commands,)\n thread.start()\n while True:\n conn, addr = server.accept()\n # do your stuff\n\ndef server_commands():\n w... | [
0
] | [] | [] | [
"multithreading",
"python",
"sockets"
] | stackoverflow_0074382188_multithreading_python_sockets.txt |
Q:
Django Postgres Exclusion Constraint with ManyToManyField
I would like to use Django Exclusion Constraint with ManyToManyField. Unfortunatelly, so far my efforts were futile.
This is my appointment model:
from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import... | Django Postgres Exclusion Constraint with ManyToManyField | I would like to use Django Exclusion Constraint with ManyToManyField. Unfortunatelly, so far my efforts were futile.
This is my appointment model:
from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import DateTimeRangeField, RangeOperators
class Appointment:
pati... | [
"The problem here is that the constraint must be made on the Appointment model's table, however because patients is a M2M field, there is no column as the error message says. The relationship is based on an intermediate table which holds the foreign key.\nThe upshot is that you can't do exactly what you want to do ... | [
0
] | [] | [] | [
"django",
"exclusion_constraint",
"postgresql",
"python"
] | stackoverflow_0066700970_django_exclusion_constraint_postgresql_python.txt |
Q:
Why do I have a space between button 1 and button2?
I set up a grid system with a top frame and a bottom frame. The top frame has buttons on the east side and they should be uniform with each other but I seem to have messed up somewhere because there is a gap between button 1 and button 2. Any feedback would be gr... | Why do I have a space between button 1 and button2? | I set up a grid system with a top frame and a bottom frame. The top frame has buttons on the east side and they should be uniform with each other but I seem to have messed up somewhere because there is a gap between button 1 and button 2. Any feedback would be great. I am trying to geta head start on my final project f... | [
"@jasonharper\nrowspan is exactly what I needed thank you\ntabControl.grid(column=0,row=0, rowspan=8, sticky='nesw')\n\n"
] | [
0
] | [] | [] | [
"oop",
"python",
"tkinter",
"tkinter_layout"
] | stackoverflow_0073942237_oop_python_tkinter_tkinter_layout.txt |
Q:
Get value of dictionaries into separate lists
I am trying to get array by first key.
The names of the keys are always the same and the number of elements is the same.
[{'a': 1, 'b':41, 'c':324}, {'a': 1, 'b':12, 'c':65}, {'a': 2, 'b':36, 'c':12}]
expected output:
[{'b':41, 'c':324}, {'b':12, 'c':65}]
[{'b':36, 'c... | Get value of dictionaries into separate lists | I am trying to get array by first key.
The names of the keys are always the same and the number of elements is the same.
[{'a': 1, 'b':41, 'c':324}, {'a': 1, 'b':12, 'c':65}, {'a': 2, 'b':36, 'c':12}]
expected output:
[{'b':41, 'c':324}, {'b':12, 'c':65}]
[{'b':36, 'c':12}]
| [
"Make a new dictionary that uses the values of the a keys as its keys.\nnewdict = {}\n\nfor d in data:\n newdict.setdefault(d['a'], []).append({'b': d['b'], 'c': d['c']})\n\nresult = list(new_dict.values())\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074382161_python.txt |
Q:
python and sql: issue reading a sql file
I'm trying to read a sql file but it keeps giving me the error:
UnicodeError: UTF-16 stream does not start with BOM
I've created a fxn to read sql files specifically:
import pandas as pd
import pyodbc as db
import os
import codecs
def sql_reader_single(qry_file, server_na... | python and sql: issue reading a sql file | I'm trying to read a sql file but it keeps giving me the error:
UnicodeError: UTF-16 stream does not start with BOM
I've created a fxn to read sql files specifically:
import pandas as pd
import pyodbc as db
import os
import codecs
def sql_reader_single(qry_file, server_name, database, encoding='utf16'):
server = ... | [
"Try to read the file as UTF-8. \n",
"I used errors='ignore' with the utf-8 encoding to prevent missing hex codes from preventing processing.\ndef get_text(file_name):\n with open(file_name, 'r', encoding='utf-8', errors='ignore') as f:\n text = f.read()\n return text\n\n"
] | [
1,
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0048997213_python_sql.txt |
Q:
How to use Amazon SES with dynamic credentials?
I'm using Django/Python and I want to use multiple Amazon SES credentials on same server.
I found boto3 to consume Amazon APIs but it requires to set the credentials using a file or environment variables. Which is I can't (or it's hard to) change it in the runtime.
H... | How to use Amazon SES with dynamic credentials? | I'm using Django/Python and I want to use multiple Amazon SES credentials on same server.
I found boto3 to consume Amazon APIs but it requires to set the credentials using a file or environment variables. Which is I can't (or it's hard to) change it in the runtime.
How can I set the credentials dynamically on runtime?
... | [
"There is several ways actually to do it:\nThe ways that you also wanted to is almost correct.\nI would advice either setting it up in the boto3.client or using the session and everything should work as expected.\nExample:\nimport boto3\n\nclient = boto3.client(\n 's3',\n aws_access_key_id=ACCESS_KEY,\n aw... | [
1
] | [] | [] | [
"amazon_ses",
"amazon_web_services",
"boto3",
"django",
"python"
] | stackoverflow_0074016958_amazon_ses_amazon_web_services_boto3_django_python.txt |
Q:
How to run a Python Script in Excel's Power Query
I'm looking for a way to execute a python script in Excel's Power Query just like we have in Power Bi. Have you tried this? Is it possible to add that from the advanced editor? I can't find documentation on that. thanks!
A:
Looked for the same answer. It seems th... | How to run a Python Script in Excel's Power Query | I'm looking for a way to execute a python script in Excel's Power Query just like we have in Power Bi. Have you tried this? Is it possible to add that from the advanced editor? I can't find documentation on that. thanks!
| [
"Looked for the same answer. It seems there is no option to run Python in Excel's Power Query.\nAs per this list it really only is available in Power BI.\nList of options\nIn the meantime, I am planning to use xlwings to run Python scripts in excel books after I've run Power Query queries. Definitely not ideal.\n"
... | [
0
] | [] | [] | [
"excel",
"powerquery",
"python"
] | stackoverflow_0062365319_excel_powerquery_python.txt |
Q:
How do I make the check boxes stay checked?
How do I make the checkboxes stay ticked? I want it to save to a local database. Here is where I gave up:
import sqlite3
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
from sqlite3 import *
import json
box = Tk()
box.geomet... | How do I make the check boxes stay checked? | How do I make the checkboxes stay ticked? I want it to save to a local database. Here is where I gave up:
import sqlite3
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
from sqlite3 import *
import json
box = Tk()
box.geometry('600x450')
box.title('November Assesment Study... | [
"You could also use a local file. Would be a different approach, but then there is no need to install mysql first.\nBut you were right. You need to store the state of the checkbox somewhere.\ncheckbox1 = True\n\nf = open(\"file.txt\", \"a\") # \"a\" will append to the end of the file.\nf.write(\"checkbox1=\" + str(... | [
0
] | [] | [] | [
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0074382390_python_python_3.x_tkinter.txt |
Q:
How to make one input that is given to 2 Scripts and how to run a script in a script Python
So I want to make an input into a script1. Script1 then continues do to stuff with the input and then at a certain elif statement after checking some cases script1 calls a script2 which continues to check something with the... | How to make one input that is given to 2 Scripts and how to run a script in a script Python | So I want to make an input into a script1. Script1 then continues do to stuff with the input and then at a certain elif statement after checking some cases script1 calls a script2 which continues to check something with the input that i gave to script1. After checking something script2 calls itself again and again unti... | [
"It would be something like that:\nscript1:\nfrom script2 import *\n\ninput = input(\"your input\")\n\ndef your_verifications(input):\n if your_condition:\n // thing you want to do\n elif another_condition:\n // where you want to call script 2\n script2_verifications(input)\n\n\nyour_veri... | [
1
] | [] | [] | [
"call",
"python",
"subprocess"
] | stackoverflow_0074382301_call_python_subprocess.txt |
Q:
Is there a way to search for a specific value in columns using wildcards for columns? - sql server
I just started using SQL server for my dissertation and I have almost 20 columns named Ingredient, Ingredient1 etc that contain an ingredient each. Now, some recipes have the same ingredient, but in different columns... | Is there a way to search for a specific value in columns using wildcards for columns? - sql server | I just started using SQL server for my dissertation and I have almost 20 columns named Ingredient, Ingredient1 etc that contain an ingredient each. Now, some recipes have the same ingredient, but in different columns. Is there a way to get a table with all recipes containing a specific ingredient from the table without... | [
"Please try the following methods to search across multiple columns.\nSQL\n-- DDL and sample data population, start\nDECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, Ingredient VARCHAR(20), Ingredient1 CHAR(2), Ingredient2 VARCHAR(20));\nINSERT @tbl (Ingredient, Ingredient1, Ingredient2) VALUES\n('Miami', 'FL', '33... | [
0
] | [] | [] | [
"columnsorting",
"database",
"python",
"sql",
"sql_server"
] | stackoverflow_0074381465_columnsorting_database_python_sql_sql_server.txt |
Q:
why isn't living_room() function running
I am creating a game with three different rooms with three different functions. The game needs to be started in the living room but the living room function will not run it only will start in the attic() function. Another problem I am having is having the other functions be... | why isn't living_room() function running | I am creating a game with three different rooms with three different functions. The game needs to be started in the living room but the living room function will not run it only will start in the attic() function. Another problem I am having is having the other functions being called to change the room that the player ... | [
"the reason your game isn't starting in the living room is because in def start() you have set the Location = \"attic\".\nChange that to Location = \"living_room\" and it will call def living_room(). As Code_Apprentice says, the Location variable in def start() will not be \"seen\" in any other functions, it is onl... | [
1,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074382263_function_python.txt |
Q:
Extract div with Beautiful Soup
I am trying extract all news headlines from this link with Beautiful Soup. The headlines are located in a div that looks like this..
<div class="container__headline __headline" data-editable="headline">
2022 midterm election results
</div>
So far I have this..
headlines = s... | Extract div with Beautiful Soup | I am trying extract all news headlines from this link with Beautiful Soup. The headlines are located in a div that looks like this..
<div class="container__headline __headline" data-editable="headline">
2022 midterm election results
</div>
So far I have this..
headlines = soup.find('body').find_all('div',{"cla... | [
"Searched url is populated dynamically by JavaScript.So you can apply an automation tool something like selenium with bs4\nExample:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nimport time\nfrom bs4 import BeautifulSoup\n\ns=Ser... | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074381956_beautifulsoup_html_python_web_scraping.txt |
Q:
How to convert csv to json
I have the following csv file:
Topic,Characteristics,Total
Population and dwellings,Population-2016,183314
Population and dwellings,Population-2011,175779
Population and dwellings,Population percentage change,4.3
Age characteristics,0 to 14 years,30670
Age characteristics,0 to 4 years,92... | How to convert csv to json | I have the following csv file:
Topic,Characteristics,Total
Population and dwellings,Population-2016,183314
Population and dwellings,Population-2011,175779
Population and dwellings,Population percentage change,4.3
Age characteristics,0 to 14 years,30670
Age characteristics,0 to 4 years,9275
Age characteristics,5 to 9 ye... | [
"You can use csv module to read the file and dict.setdefault to group elements:\nimport csv\n\nout = {}\nwith open(\"your_file.csv\", \"r\") as f_in:\n reader = csv.reader(f_in)\n next(reader) # skip headers\n for topic, characteristics, total in reader:\n out.setdefault(topic, {})[characteristics]... | [
3,
1
] | [] | [] | [
"csv",
"dictionary",
"json",
"python",
"python_3.x"
] | stackoverflow_0074382431_csv_dictionary_json_python_python_3.x.txt |
Q:
Removing certain strings from text with a specific format
What I'm trying to do is remove certain date strings that randomly popup in the text I'm using, the format is like this: 14 Sept 2021 but the day, month and year is dynamic so it can change.
What I have tried is:
def clean_up_answer(answer):
dat... | Removing certain strings from text with a specific format | What I'm trying to do is remove certain date strings that randomly popup in the text I'm using, the format is like this: 14 Sept 2021 but the day, month and year is dynamic so it can change.
What I have tried is:
def clean_up_answer(answer):
date_pattern = re.search("(\d{2}[.]+\d{4}[.]+\d{4})", answer)
... | [
"Following up on what furas said you need to accommodate the month text in your script.\nYou also don't need to check if the pattern you want to replace is in the string. re.sub() will not make any replacements in your string if it cannot find the pattern to match in the string.\nimport re\n\ndef clean_up_answer(an... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0073978276_python_regex.txt |
Q:
Socket server and client on the same time
I want to know if it’s possible de make a server and client in the same time using sockets
The goal is to do a bidirectional file transfer from client to server and from server to client using python socket
Any one have an idea ?
A:
You still only need a Server and a Cli... | Socket server and client on the same time | I want to know if it’s possible de make a server and client in the same time using sockets
The goal is to do a bidirectional file transfer from client to server and from server to client using python socket
Any one have an idea ?
| [
"You still only need a Server and a Client.\nThe server is also able to read and process data that the client is sending.\n",
"Sockets are bidirectional and server can await clients for long time, you can connect by client when need it and then disconnect. But if you want to start socket server only when you tran... | [
0,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0074382420_python_sockets.txt |
Q:
Open (flattened) png images stored in a .parquet file format
I have instructions for a file format which contains .png images as
Each parquet file contains tens of thousands of 137x236 grayscale images.Each row in the parquet files contains an image_id column, and the flattened image
I've opened these using python... | Open (flattened) png images stored in a .parquet file format | I have instructions for a file format which contains .png images as
Each parquet file contains tens of thousands of 137x236 grayscale images.Each row in the parquet files contains an image_id column, and the flattened image
I've opened these using python and can visualise using matplotlib's imshow. Can anyone suggest ... | [
"For a non-flattened data something like this could work:\nimport pyarrow.parquet as pq\n\nindex = 0\ntable = pq.read_table('data.parquet')\nfor img in table['image']:\n b = img['bytes'].as_py()\n with open(f'{index}.png', 'wb') as f:\n f.write(b)\n index+=1\n\nas_py() returns array of bytes\nIn... | [
0
] | [] | [] | [
"numpy",
"parquet",
"python",
"python_3.x"
] | stackoverflow_0059589990_numpy_parquet_python_python_3.x.txt |
Q:
How to get day of the week based on inputed date(Python)
So i wanted the user to enter date and based on that day to get named day of the week, for example today's date is 2022.11.10, so wanted answer would be Thursday.
I know this is wrong, can anybody help?
import datetime
def dayOfTheWeek(day, month, year):
... | How to get day of the week based on inputed date(Python) | So i wanted the user to enter date and based on that day to get named day of the week, for example today's date is 2022.11.10, so wanted answer would be Thursday.
I know this is wrong, can anybody help?
import datetime
def dayOfTheWeek(day, month, year):
date = datetime.date(year, month, day)
weekday = date.w... | [
"Instead of going through the dictionary with for loop, you can simply return the result already converted by dictionary:\nimport datetime\n\ndef dayOfTheWeek(day, month, year):\n date = datetime.date(year, month, day)\n weekday = date.weekday()\n day_dict = { 0 : \"Monday\", 1 : \"Tuesday\", 2 : \"Wednesd... | [
1,
1
] | [] | [] | [
"datetime",
"python",
"time",
"weekday"
] | stackoverflow_0074382378_datetime_python_time_weekday.txt |
Q:
Cannot import HTTPAdapter from requests.adapters when importing clip_retrieval on WSL2 Ubuntu 20.04 Windows 10
As far as I checked all dependencies are installed and are within the ranges (see below), also I tried uninstall-install for the suspect problematic libs (flask, requests). I didn't use venv so far though... | Cannot import HTTPAdapter from requests.adapters when importing clip_retrieval on WSL2 Ubuntu 20.04 Windows 10 | As far as I checked all dependencies are installed and are within the ranges (see below), also I tried uninstall-install for the suspect problematic libs (flask, requests). I didn't use venv so far though if that could be a problem with some of the libs, flask in particular which breaks during importing) and I don't kn... | [
"I managed to fix it and run the whole clip-retrieval notepad example locally and accessing the local tunnel Node.js server from the Internet. That's the code that had to be run from WSL or Windows:\nhttps://colab.research.google.com/github/rom1504/clip-retrieval/blob/master/notebook/clip-retrieval-getting-started.... | [
0
] | [] | [] | [
"flask",
"python",
"python_requests",
"ubuntu_20.04",
"wsl_2"
] | stackoverflow_0074367611_flask_python_python_requests_ubuntu_20.04_wsl_2.txt |
Q:
Average of two rows based on grouped columns
I want to create the mean of the values in two rows, based on values in a third row. In one row I have ID's A, B and C and means have to be created for the values in two rows with the ID A & B, B & C and A & C. Is there a simple way to do this?
My dataset is as the exam... | Average of two rows based on grouped columns | I want to create the mean of the values in two rows, based on values in a third row. In one row I have ID's A, B and C and means have to be created for the values in two rows with the ID A & B, B & C and A & C. Is there a simple way to do this?
My dataset is as the example below:
station group groupA groupB groupC val... | [
"Try:\nfrom itertools import combinations\n\ncolumns = [\"A\", \"B\", \"C\"]\n\ng = df.groupby(\"station\")\nfor c in combinations(columns, 2):\n for _, d in g:\n x = d.loc[d[\"group\"].isin(c), \"value\"].mean()\n df.loc[d.index, f\"mean{c[0]}{c[1]}\"] = x\ndf[\"ALLme\"] = g[\"value\"].transform(\... | [
0,
0
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074381053_group_by_pandas_python.txt |
Q:
How to make a column from pandas dataframe into a list at each ROW?
Currently I have a JSON file that I converted from pandas dataframe that looks like this:
{"My Setting": {
"0": {
"upper limit": "120",
"lower limit": "40",
"ID": "2000333",
"Competitor ID": ... | How to make a column from pandas dataframe into a list at each ROW? | Currently I have a JSON file that I converted from pandas dataframe that looks like this:
{"My Setting": {
"0": {
"upper limit": "120",
"lower limit": "40",
"ID": "2000333",
"Competitor ID": "99123"
},
"1": {
"upper limit": "100",
... | [
"You can make the values as lists after converting the dataframe to dictionary. For example:\ndct = {\n \"My Setting\": {\n \"0\": {\n \"upper limit\": \"120\",\n \"lower limit\": \"40\",\n \"ID\": \"2000333\",\n \"Competitor ID\": \"99123\",\n },\n ... | [
0
] | [] | [] | [
"dataframe",
"json",
"list",
"pandas",
"python"
] | stackoverflow_0074382554_dataframe_json_list_pandas_python.txt |
Q:
Asyncio, adding tasks to a runnin loop
Lets say we have a 12 tasks, we need to runn all of them with one condition: we can have only 3 tasks running simultaneously. So we can start only 3 tasks at the beggining, then wayt until one of them finishes and launch another one. I am using Asyncio with semafore for this ... | Asyncio, adding tasks to a runnin loop | Lets say we have a 12 tasks, we need to runn all of them with one condition: we can have only 3 tasks running simultaneously. So we can start only 3 tasks at the beggining, then wayt until one of them finishes and launch another one. I am using Asyncio with semafore for this purpose in the simple code below.
import asy... | [
"you need to code around a producer-consumer approach, this question has more explanation of it, Using asyncio.Queue for producer-consumer flow , but basically you need to make a queue and have workers pull items from it, in this answer i created 3 workers and have them pull coroutines from queue till the queue is ... | [
0,
0
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074375922_python_python_asyncio.txt |
Q:
Non model field in Django ModelSerializer
class Form(models.Model):
key = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
class Answer(models.Model):
form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name='answers')
answer = models.TextField()
class Answer... | Non model field in Django ModelSerializer | class Form(models.Model):
key = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
class Answer(models.Model):
form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name='answers')
answer = models.TextField()
class AnswerSerializer(serializers.ModelSerializer):
fo... | [
"Have you tried using the SlugRelatedField, but just pretend that the uuid key is the slug? I think it should work for you since that field is also unique.\nUsing \"form\" for the name might be clearer in code, since that is what the key represents. When the serializer is successful it returns the Form object in ... | [
1
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"django_serializer",
"python"
] | stackoverflow_0074380209_django_django_models_django_rest_framework_django_serializer_python.txt |
Q:
python sqlalchemy mysql use parameter as keyword
I am having trouble getting passed parameters in sqlalchemy to act as columns or tables.
For example, I'd like to select whatever column I pass as a parameter
result = connection.execute(
text(
SELECT :selected_column FROM example_table
),
**{'se... | python sqlalchemy mysql use parameter as keyword | I am having trouble getting passed parameters in sqlalchemy to act as columns or tables.
For example, I'd like to select whatever column I pass as a parameter
result = connection.execute(
text(
SELECT :selected_column FROM example_table
),
**{'selected_column': 'col1'}
).fetchall()
But this ends up... | [
"Parameters are treated as if they are literal values. Parameters are not just string-substitution.\nIf you want to make a dynamic query that selects a column named by a Python variable, you have to expand that variable in the query string before that string is passed to the database connector.\nExample:\nmycol = '... | [
0
] | [] | [] | [
"mysql",
"parameters",
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0074382569_mysql_parameters_python_python_3.x_sqlalchemy.txt |
Q:
How to change the naming structure to a CSV in python
I am trying to change the name that is printed out on a CSV file that I am creating from an SQL Query. I would like the file name to look like this yyyyddmm_"name". With the year day month capturing the corresponding date on the day of its creation. At the mome... | How to change the naming structure to a CSV in python | I am trying to change the name that is printed out on a CSV file that I am creating from an SQL Query. I would like the file name to look like this yyyyddmm_"name". With the year day month capturing the corresponding date on the day of its creation. At the moment I am using pandas and datetime, this is not giving me th... | [
"import time\nfile_name = time.strftime(\"%Y%m%d\"+\"_Name\")\nprint(file_name)\n\nfor your case\nimport time\nfile_name = time.strftime(\"%Y%m%d\"+\"_Name\")\nsave_to_path = r'C:\\Users\\MyPC\\Desktop' #this is where your .csv file will be saved\ndf.to_csv(save_to_path+\"\\\\\"+file_name+ \".csv\", index=False)\n\... | [
1
] | [] | [] | [
"datetime",
"export_to_csv",
"pandas",
"python"
] | stackoverflow_0074382614_datetime_export_to_csv_pandas_python.txt |
Q:
How can I download NLTK corpora via `requirements.txt` using `pip install -r requirements.txt`?
One can download NLTK corpora punkt and wordnet via the command line:
python3 -m nltk.downloader punkt wordnet
How can I download NLTK corpora via requirements.txt using pip install -r requirements.txt?
For example one... | How can I download NLTK corpora via `requirements.txt` using `pip install -r requirements.txt`? | One can download NLTK corpora punkt and wordnet via the command line:
python3 -m nltk.downloader punkt wordnet
How can I download NLTK corpora via requirements.txt using pip install -r requirements.txt?
For example one can download spacy models requirements.txt using pip install -r requirements.txt by adding the URL o... | [
"\nHow can I download NLTK corpora via requirements.txt\n\nShort answer: no way.\nThe URL for spacy models points to a Python package (setup.py and all that) so it can be downloaded and installed by pip. There are no such pip-installable packages for NLTK data. nltk.downloader downloads data in its own format.\n",
... | [
4,
2,
0
] | [] | [] | [
"corpus",
"nltk",
"pip",
"python",
"requirements.txt"
] | stackoverflow_0061646185_corpus_nltk_pip_python_requirements.txt.txt |
Q:
Calling getpass() says too many positional arguments when trying to print prompt
I am very new to Python (Only a couple weeks) and I'm trying to make a rock paper scissors game for Replits 100 days of code. My previous game was very simple and worked fine but it wont fly as a template for this lesson so I've start... | Calling getpass() says too many positional arguments when trying to print prompt | I am very new to Python (Only a couple weeks) and I'm trying to make a rock paper scissors game for Replits 100 days of code. My previous game was very simple and worked fine but it wont fly as a template for this lesson so I've started from scratch but I'm having trouble.
from getpass import getpass as hinput
ch1 = hi... | [
"You're using getpass like print. print is sort of special in Python, as it's written to take any number of arguments. You can write functions like that yourself, but it's not the default. And getpass is written to only accept a single string as an argument (and an output stream, but we don't need that for our purp... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074382707_python.txt |
Q:
Change background color in Pandas.DataFrame.plot() within Jupyter Notebook
I am plotting a bar graph from a Pandas DataFrame in Jupyter Notebook and for some reason I am unable to change the grey background of the plot to white.
df = pd.DataFrame({
'Name': ['John', 'Sammy', 'Joe'],
'Age': [45, 38, 90],
... | Change background color in Pandas.DataFrame.plot() within Jupyter Notebook | I am plotting a bar graph from a Pandas DataFrame in Jupyter Notebook and for some reason I am unable to change the grey background of the plot to white.
df = pd.DataFrame({
'Name': ['John', 'Sammy', 'Joe'],
'Age': [45, 38, 90],
'Height(in cm)': [150, 180, 160]
})
# plotting graph
df.plot(x="Name", y=["A... | [
"To change the background outside of the plot, changing the style should be the easiest way:\nplt.style.use('default')\nThe list of styles:\nhttps://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html\nIf you want to change the background inside the plot, you are doing the right things in the wro... | [
1
] | [] | [] | [
"jupyter_notebook",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074381453_jupyter_notebook_matplotlib_pandas_python.txt |
Q:
Retrieving email in PDF signature with asn1crypto
I have a PDF file with the following signature:
I try to explore the PDF file using the following code:
from pdfrw import PdfReader, PdfWriter
from PyPDF2 import PdfFileReader
import subprocess
from endesive import pdf
from pdfreader import PDFDocument
from asn1cr... | Retrieving email in PDF signature with asn1crypto | I have a PDF file with the following signature:
I try to explore the PDF file using the following code:
from pdfrw import PdfReader, PdfWriter
from PyPDF2 import PdfFileReader
import subprocess
from endesive import pdf
from pdfreader import PDFDocument
from asn1crypto import cms
import datetime
pdf_link = 'FDA_Form_1... | [
"\"the email is hidden inside this blob of encoded message. How can I decode it and retrieve the email?\"\nEncoding pdf as python output is not efficient for reading or text parsing, TL;DR\nb'0\\x82\\x05K\\x06\\t*\\x86H\\x86\\xf7\\r\\x01\\x07\\x02\\xa0\\x82\\x05<0\\x82\\x058\\x02\\x01\\x011\\x0f0\\r\\x06\\t*\\x86H\... | [
0
] | [] | [] | [
"asn1crypto",
"python"
] | stackoverflow_0074369340_asn1crypto_python.txt |
Q:
Consider setting $PYTHONHOME to [:] error
I am constantly getting same error when i do python manage.py runserver. There was no such error when i have ubuntu 15.10. This got started when i upgraded my ubuntu to 16.04. This question might look duplicate but i have tried solution provided to this question like i hav... | Consider setting $PYTHONHOME to [:] error | I am constantly getting same error when i do python manage.py runserver. There was no such error when i have ubuntu 15.10. This got started when i upgraded my ubuntu to 16.04. This question might look duplicate but i have tried solution provided to this question like i have applied the command dpkg --configure -a, i ha... | [
"I had something similar. Turns out uninstalling base python removes symlink and for reason, when reinstalling, it doesn't symlink automatically.\nRunning this helps to link python to path\nsudo ln -s /usr/bin/python2.7 /usr/bin/python\n\n"
] | [
0
] | [] | [] | [
"django",
"django_1.9",
"python",
"ubuntu",
"ubuntu_16.04"
] | stackoverflow_0036832071_django_django_1.9_python_ubuntu_ubuntu_16.04.txt |
Q:
Pytest - raise exception in for loop
I try raise exception in pytest when battery run out from device when calculator count 100x times.
class:
class Calculator:
def __init__(self, battery: int = 100, filename=None):
self.battery = battery
self.filename = filename
self.check_battery()
def check_battery... | Pytest - raise exception in for loop | I try raise exception in pytest when battery run out from device when calculator count 100x times.
class:
class Calculator:
def __init__(self, battery: int = 100, filename=None):
self.battery = battery
self.filename = filename
self.check_battery()
def check_battery(self):
if self.battery <= 0:
... | [
"I am not sure that it should looks like that but works:\ndef test_battery_by_calculate_100x_times(calc):\nfor iteration in range(0, 102):\n value = 2\n try:\n calc.add(value, value)\n except NoBatteryError:\n assert True\n\n"
] | [
0
] | [] | [] | [
"pytest",
"python",
"unit_testing"
] | stackoverflow_0074382405_pytest_python_unit_testing.txt |
Q:
Pandas Groupby rolling sum of multiple columns on datetime column
I am trying to get a rolling sum of multiple columns by group, rolling on a datetime column (i.e. over a specified time interval). Rolling of one column seems to be working fine, but when I roll over multiple columns by vectorizing, I am getting une... | Pandas Groupby rolling sum of multiple columns on datetime column | I am trying to get a rolling sum of multiple columns by group, rolling on a datetime column (i.e. over a specified time interval). Rolling of one column seems to be working fine, but when I roll over multiple columns by vectorizing, I am getting unexpected results.
My first attempt:
df = pd.DataFrame({"column1": range(... | [
"I took your original approach and did some changes. Can you check if this is what you wanted?\nReset the index of the original data frame and assign the original index a column name.\ndf = df.reset_index().rename(columns={df.index.name: 'index'})\n\nNow, you have the same original data frame, but it has an additio... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0062608591_pandas_python.txt |
Q:
Using CMake FindPython() with "Development" component when cross-compiling
I have a CMake toolchain file containing the following
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
set(target_triplet "arm-linux-gnueabihf")
set(target_root /srv/chroot/raspbian)
set(CMAKE_C_COMPILER ${target_triplet}-gcc... | Using CMake FindPython() with "Development" component when cross-compiling | I have a CMake toolchain file containing the following
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
set(target_triplet "arm-linux-gnueabihf")
set(target_root /srv/chroot/raspbian)
set(CMAKE_C_COMPILER ${target_triplet}-gcc CACHE FILEPATH "C compiler")
set(CMAKE_CXX_COMPILER ${target_triplet}-g++ CACHE... | [
"Actually, doing\nset(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY)\nfind_package(Python3 COMPONENTS Development.Module REQUIRED)\nset(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)\n\ndoes work for Python 3. Unfortunately if you still need to support Python 2 too, it doesn't work for it because python2.7-config doesn't behave... | [
0
] | [] | [] | [
"cmake",
"cross_compiling",
"python"
] | stackoverflow_0074245522_cmake_cross_compiling_python.txt |
Q:
How to use sumo/tools/randomTrips.py in order to make random trips that do start from starting lanes and end to final lanes
I'm having problems with SUMO's randomTrips.py, although I set a really high fringe factor, I still get vehicle spawns "inside" my network. I want to make trips that start of a starting lane ... | How to use sumo/tools/randomTrips.py in order to make random trips that do start from starting lanes and end to final lanes | I'm having problems with SUMO's randomTrips.py, although I set a really high fringe factor, I still get vehicle spawns "inside" my network. I want to make trips that start of a starting lane and end to a final lane.
Here's how I generated my trips files. I want ~ 1000 vehs, 1 veh spawning every 2 secs at a duration of ... | [
"Now in SUMO version 1.15.0, --fringe-factor accepts value max to make all vehicles depart and arrive at fringe edges.\nhttps://github.com/eclipse/sumo/blob/main/tools/randomTrips.py#L116\n",
"If your network is not too big you can consider listing the probabilities explicitly and use one or two weight files to g... | [
1,
0
] | [] | [] | [
"artificial_intelligence",
"machine_learning",
"python",
"sumo"
] | stackoverflow_0069737964_artificial_intelligence_machine_learning_python_sumo.txt |
Q:
how can I store optimized parameters corresponding to local maximum of a function out of the multiple loops?
I have a 3D array and I want to find the optimal parameters corresponding to a local maximum of 2D array for each iteration of 3rd array as an outer loop there.
Nstep1 = 5
l2= linspace(0.01,2,Nstep1)
EP_opt... | how can I store optimized parameters corresponding to local maximum of a function out of the multiple loops? | I have a 3D array and I want to find the optimal parameters corresponding to a local maximum of 2D array for each iteration of 3rd array as an outer loop there.
Nstep1 = 5
l2= linspace(0.01,2,Nstep1)
EP_opt = zeros(Nstep1)
Nstep = 5
for l in range(Nstep1):
Vp = zeros((Nstep, Nstep))
g1 = linspace(0.1, 0.5, Nste... | [
"Your optimisation doesn't make any sense, because - given your objective function - for every index of l, the best parameters remain the same. Run this:\nimport numpy as np\nfrom scipy.optimize import minimize\n\n\ndef Ep(pr: np.ndarray, l: float) -> float:\n a, b, c, g1, g2 = pr\n return -(a*l + b*g1*g1 - c... | [
0
] | [] | [] | [
"for_loop",
"optimization",
"python",
"scipy",
"scipy_optimize"
] | stackoverflow_0074111975_for_loop_optimization_python_scipy_scipy_optimize.txt |
Q:
How to return a list from a class
How would I get to return a list from the class, right now its just returning the location
class ListNode:
def __init__(self, val=[]):
self.val = val
def __iter__(self):
return iter(self.val)
def file_reader(file_path):
list_of_num = []
with open... | How to return a list from a class | How would I get to return a list from the class, right now its just returning the location
class ListNode:
def __init__(self, val=[]):
self.val = val
def __iter__(self):
return iter(self.val)
def file_reader(file_path):
list_of_num = []
with open(file_path, "rt") as fout:
rea... | [
"The problem is the ListNode class, which doesn't do anything other than wrap a regular list (it also has a potential bug related to the mutable default arg in the constructor that might bite you later), and it doesn't wrap the __str__ method that provides pretty-printing.\nThe easiest way to solve the problem is t... | [
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074382783_class_python.txt |
Q:
improving speed of Python module import
The question of how to speed up importing of Python modules has been asked previously (Speeding up the python "import" loader and Python -- Speed Up Imports?) but without specific examples and has not yielded accepted solutions. I will therefore take up the issue again here,... | improving speed of Python module import | The question of how to speed up importing of Python modules has been asked previously (Speeding up the python "import" loader and Python -- Speed Up Imports?) but without specific examples and has not yielded accepted solutions. I will therefore take up the issue again here, but this time with a specific example.
I ha... | [
"Not an actual answer to the question, but a hint on how to profile the import speed with Python 3.7 and tuna (a small project of mine):\npython3 -X importtime -c \"import scipy\" 2> scipy.log\ntuna scipy.log\n\n\n",
"you could build a simple server/client, the server running continuously making and updating the ... | [
69,
27,
8,
3,
3,
0
] | [] | [] | [
"import",
"module",
"performance",
"python"
] | stackoverflow_0016373510_import_module_performance_python.txt |
Q:
How to populate a df column based on coditions that are number ranges
I would like to populate column df['category'] with numbers 1-52 when values of column df['values'] are less than x
So here values are days and category is weeknumber but not based on date but rather accumulation of days, every 7 days is a new w... | How to populate a df column based on coditions that are number ranges | I would like to populate column df['category'] with numbers 1-52 when values of column df['values'] are less than x
So here values are days and category is weeknumber but not based on date but rather accumulation of days, every 7 days is a new week.
week = range of values from 1-52
range = multiples of 7 so 7, 14, 21, ... | [
"example:\ndf = pd.DataFrame([[20], [52], [400]], columns=['values'])\n\ndf:\n values\n0 20\n1 52\n2 400\n\nuse following code:\ndf.assign(category=df['values'].divmod(7)[0].add(1).clip(upper=52))\n\noutput:\n values category\n0 20 3\n1 52 8\n2 400 52\n\n"
] | [
0
] | [] | [] | [
"conditional_statements",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074382465_conditional_statements_dataframe_numpy_pandas_python.txt |
Q:
Entire Website Nested in One HTML Tag Disrupts Python Web Scraper
I am trying to create a Python WebScraper that takes data from the internet and converts it to a table that I will then export as a .csv file. The sample website I am trying to get this program to work for is: https://asdc.larc.nasa.gov/data/AJAX/O... | Entire Website Nested in One HTML Tag Disrupts Python Web Scraper | I am trying to create a Python WebScraper that takes data from the internet and converts it to a table that I will then export as a .csv file. The sample website I am trying to get this program to work for is: https://asdc.larc.nasa.gov/data/AJAX/O3_1/2018/06/06/AJAX-O3_ALPHA_20180606_R1_F229.ict
I was planning on usi... | [
"While this is not the best project for a beginner, I thought I would highlight the steps required to retrieve the table at the end of the page. This is not too difficult, and avoids the need for regex etc. \nHere are the steps:\n\nCreate your account at https://asdc.larc.nasa.gov/\nLogin to your account and naviga... | [
0
] | [] | [] | [
"html",
"insert",
"python",
"tags",
"web_scraping"
] | stackoverflow_0070469563_html_insert_python_tags_web_scraping.txt |
Q:
How to check if there is a string/s in a list in Python?
I have the following code:
import statistics
import time
def medianextra (numlist=[0], i=2):
Attempt=0
while not i==0:
try:
if not len(numlist)==1:
try:
a = statistics.median(numlist)
... | How to check if there is a string/s in a list in Python? | I have the following code:
import statistics
import time
def medianextra (numlist=[0], i=2):
Attempt=0
while not i==0:
try:
if not len(numlist)==1:
try:
a = statistics.median(numlist)
b = statistics.median_low(numlist)
... | [
"For multiple strings the best option perhaps might be;\ndef check_if_string_in_numlist(*args, numlist):\n for arg in args:\n if arg in numlist:\n return True\n return False\n\nUsage:\nprint(check_if_string_in_numlist('a', 'b', 'c', numlist=['a', 'b', 3, 4, 5, 6, 7, 8, 9, 10])) # multiple st... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074382725_pandas_python.txt |
Q:
Issue with pretty tables in python
I'm currently working on a assignment for school, Im not asking for anyone to solve the problem for me, Im just trying to figure out what it is im doing wrong with pretty tables. Here is the code I have for the table itself
import random
from prettytable import PrettyTable
x = Pr... | Issue with pretty tables in python | I'm currently working on a assignment for school, Im not asking for anyone to solve the problem for me, Im just trying to figure out what it is im doing wrong with pretty tables. Here is the code I have for the table itself
import random
from prettytable import PrettyTable
x = PrettyTable
def generate_bingo_card():
... | [
"I think this is a much more elegant solution; you have added complexity that I don't feel needs to exist; you can always retrofit this to your solution;\nimport prettytable\nimport random\n\ndef create_bingo_card():\n card = {}\n card['B'] = random.sample(range(1, 16), 5)\n card['I'] = random.sample(range... | [
0
] | [] | [] | [
"prettytable",
"python"
] | stackoverflow_0074382840_prettytable_python.txt |
Q:
Using pandas.replace to change all value in a column except one value
Lets say that i have this dataframe below, and i wanted to change all the non 'United-states' native_country to 'Other' can i use pandas.replace to do this? if not what should i do?
age education marital_status occupation race sex... | Using pandas.replace to change all value in a column except one value | Lets say that i have this dataframe below, and i wanted to change all the non 'United-states' native_country to 'Other' can i use pandas.replace to do this? if not what should i do?
age education marital_status occupation race sex native_country
1 37 Non-grad Married Sales Oth... | [
"using mask or loc\n# using mask, when native country is not United-States, makes it other, else\n# leave value as is\n\ndf['native_country'] = df['native_country'].mask(df['native_country'].ne('United-States'),'other')\ndf\n\nOR\n# using loc, updated native country, where its not united-states\ndf.loc[df['native_c... | [
1
] | [] | [] | [
"pandas",
"python",
"replace"
] | stackoverflow_0074382956_pandas_python_replace.txt |
Q:
Allow only one keyword that is not "None" in **kwargs
I would like to explain my problem with an example.
(The example I gave may not make much sense in itself, but I thought it would be better understood this way.)
def animal(*args, **kwargs):
duck = kwargs.get("duck")
lion = kwargs.get("lion")
wolf =... | Allow only one keyword that is not "None" in **kwargs | I would like to explain my problem with an example.
(The example I gave may not make much sense in itself, but I thought it would be better understood this way.)
def animal(*args, **kwargs):
duck = kwargs.get("duck")
lion = kwargs.get("lion")
wolf = kwargs.get("wolf")
# bear, fish, bee etc...
... | [
"As others have commented, you can count the number of non-None values in kwargs, and raise an exception if that number is greater than one.\nx = 0\nfor val in kwargs.values():\n if val is not None:\n x += 1\n if x > 1:\n raise ValueError(\"Too many values present\")\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074382809_python.txt |
Q:
I want to output a 3D graph using Networkx and Matplotlib
Abstract
As a prototype, we were able to output a 2-dimensional graph. The source code is noted below.
I wanted to try outputting this graph in three dimensions, so I started messing around with the existing code, but after much research I was at a loss.
So... | I want to output a 3D graph using Networkx and Matplotlib | Abstract
As a prototype, we were able to output a 2-dimensional graph. The source code is noted below.
I wanted to try outputting this graph in three dimensions, so I started messing around with the existing code, but after much research I was at a loss.
So I decided to post a question on stackoverflow at the risk of b... | [
"If I understand your question correctly, the checkbox \"Normal network visualization\"\ncontrols whether the edges are plotted or not. Is that right?\nIf that's what you want to do, you could use the edge drawing procedure from your code when the checkbox is on:\ndef while_1(event):\n if(chk_bln[0].get() == Tru... | [
3
] | [] | [] | [
"matplotlib",
"networkx",
"python",
"python_3.x"
] | stackoverflow_0074368905_matplotlib_networkx_python_python_3.x.txt |
Q:
Recode over a range in python
I want to recode the numeric values to categories 1 to 4. When the last condition is run it turns all the previous recoded values into 4. How can I recode over a range of values in python?
df2['col1'] = np.where(df2['col1'] < -1.27, 1,df2['col1'].values)
df2['col1'] = np.where( (df2[... | Recode over a range in python | I want to recode the numeric values to categories 1 to 4. When the last condition is run it turns all the previous recoded values into 4. How can I recode over a range of values in python?
df2['col1'] = np.where(df2['col1'] < -1.27, 1,df2['col1'].values)
df2['col1'] = np.where( (df2['col1'] >= -1.27) & (df2['col1'] < ... | [
"Just make sure the last comparison excludes the values you've already assigned.\ndf2[df2['col1'] < -1.27] = 1\ndf2[(df2['col1'] >= -1.27) & (df2['col1'] < -0.74)] = 2\ndf2[(df2['col1'] >= -0.74) & (df2['col1'] < -0.075)] = 3\ndf2[(df2['col1'] >= -0.075) & (df2['col1'] < 1)] = 4\n\nIf your data actually contains po... | [
0
] | [] | [] | [
"numpy",
"python",
"range",
"recode"
] | stackoverflow_0074382958_numpy_python_range_recode.txt |
Q:
Import "google_auth_oauthlib.flow" could not be resolved
In VSCODE using these specifications:
pip 21.3.1 from C:\users\computador\appdata\local\programs\python\python39\lib\site-packages\pip (python 3.9)
I'm using this path for installation:
pip install --upgrade google-api-python-client google-auth-httplib2 goo... | Import "google_auth_oauthlib.flow" could not be resolved | In VSCODE using these specifications:
pip 21.3.1 from C:\users\computador\appdata\local\programs\python\python39\lib\site-packages\pip (python 3.9)
I'm using this path for installation:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
But when I try to add the flow import, it ... | [
"Try pip uninstall google-auth-oauthlib and pip uninstall google-api-python-client google-auth-httplib2 google-auth-oauthlib then reinstall it with pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib\n",
"Directly run pip install google-api-python-client google-auth-httplib2 google-auth... | [
3,
0
] | [] | [] | [
"google_api_python_client",
"google_oauth",
"pip",
"python",
"visual_studio_code"
] | stackoverflow_0069993244_google_api_python_client_google_oauth_pip_python_visual_studio_code.txt |
Q:
Deleting DataFrame row in Pandas based on column value
I have the following DataFrame:
daysago line_race rating rw wrating
line_date
2007-03-31 62 11 56 1.000000 56.000000
2007-03-10 83 11 67 1.000000... | Deleting DataFrame row in Pandas based on column value | I have the following DataFrame:
daysago line_race rating rw wrating
line_date
2007-03-31 62 11 56 1.000000 56.000000
2007-03-10 83 11 67 1.000000 67.000000
2007-02-10 111 9 66 1.000000... | [
"If I'm understanding correctly, it should be as simple as:\ndf = df[df.line_race != 0]\n\n",
"But for any future bypassers you could mention that df = df[df.line_race != 0] doesn't do anything when trying to filter for None/missing values.\nDoes work:\ndf = df[df.line_race != 0]\n\nDoesn't do anything:\ndf = df[... | [
1452,
289,
128,
63,
58,
56,
48,
18,
7,
7,
6,
6,
3,
3,
2,
1,
0
] | [
"You can try using this:\ndf.drop(df[df.line_race != 0].index, inplace = True)\n\n.\n"
] | [
-1
] | [
"dataframe",
"delete_row",
"pandas",
"performance",
"python"
] | stackoverflow_0018172851_dataframe_delete_row_pandas_performance_python.txt |
Q:
Join DataFrame based on different values
I have 2 DataFrames:
DF 1:
DF 2:
I want to join them to have this final DataFrame:
I have tried many different JOINs or MERGE but any of them are working.
Can anyone help me to get this please??
Thanks in advance!
I have tried left join and merge
A:
Maybe you can try t... | Join DataFrame based on different values | I have 2 DataFrames:
DF 1:
DF 2:
I want to join them to have this final DataFrame:
I have tried many different JOINs or MERGE but any of them are working.
Can anyone help me to get this please??
Thanks in advance!
I have tried left join and merge
| [
"Maybe you can try this\ndf1.join(df2.set_index('Country'), on='Country')\n\nor you could merge the sub-DataFrame (with just those columns):\ndf2[list('min_transaction_threshold approval_drop_threshold')] # df2 but only with columns min_transaction_threshold approval_drop_threshold\n\ndf1.merge(df2[list('min_trans... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074382972_dataframe_pandas_python.txt |
Q:
(Python) same procss but missing one picture, name "output_y:389_x:150.png"
I'm processing the img, I capture a picture from production line, then extract the part I want from image, cut the img into small pieces, and detect img to text
Quesion: one of the image is disappear, for now I know it called "output_y:3... | (Python) same procss but missing one picture, name "output_y:389_x:150.png" | I'm processing the img, I capture a picture from production line, then extract the part I want from image, cut the img into small pieces, and detect img to text
Quesion: one of the image is disappear, for now I know it called "output_y:389_x:150.png" cause I name them by their (x,y) value in original img
the script
... | [
"Here's a version of your code that makes the loops more consistent. In general, it's a very bad idea to include hard-coded paths in code like this (that is, \"/home/student_DC/desktop/test_11_8\", etc.). If you are going to run this code from the \"test_11_8\" directory, then you can remove that prefix from all ... | [
1
] | [] | [] | [
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074375434_numpy_python_python_3.x.txt |
Q:
Logical Problem with the output of the function
This function works like a checklist. It takes a task name and date in the format yyyy/mm/dd HH:MM:SS, and appends them to a list as a tuple. However, when I print them out there is a problem.
When printing the tuple it look like ("A", 2022/12/08 22:15:56). What I am... | Logical Problem with the output of the function | This function works like a checklist. It takes a task name and date in the format yyyy/mm/dd HH:MM:SS, and appends them to a list as a tuple. However, when I print them out there is a problem.
When printing the tuple it look like ("A", 2022/12/08 22:15:56). What I am actually seeing is something like ('A', datetime.dat... | [
"Your first misunderstanding is what happens when you do this (in the REPL):\n>>> format_time = \"%Y/%m/%d %H:%M:%S\"\n>>> my_tuple = (1, datetime.strptime(\"1919/04/13 12:00:00\", format_time))\n>>> print(my_tuple)\n(1, datetime.datetime(1919, 4, 13, 12, 0))\n\nThis prints these values as they think of themselves.... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074382514_python.txt |
Q:
Pre-commit: Absolutify-imports vs Pylint: E0402: Attempted relative import beyond top-level package
Context
Suppose the folder structure is used:
apples/
src/
__init__.py
apples/
helper.py
__main__.py
__init__.py
tests/
__init__.py
sometes... | Pre-commit: Absolutify-imports vs Pylint: E0402: Attempted relative import beyond top-level package | Context
Suppose the folder structure is used:
apples/
src/
__init__.py
apples/
helper.py
__main__.py
__init__.py
tests/
__init__.py
sometest.py
This structure is analog to the flake8 folder structure, where the GitHub repo name is the same as ... | [
"Looks like a known issue in pylint.\n"
] | [
2
] | [] | [] | [
"pre_commit",
"pylint",
"python",
"python_import"
] | stackoverflow_0074360549_pre_commit_pylint_python_python_import.txt |
Q:
Pyenv in Ubuntu 22.04: ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib?
Moving to Ubuntu 22 with a fresh install (I have Ubuntu 20 in another partition) and the last piece I need to use it for working it to have pyenv running fine.
When trying to pyenv install x.xx.x it fails with this er... | Pyenv in Ubuntu 22.04: ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib? | Moving to Ubuntu 22 with a fresh install (I have Ubuntu 20 in another partition) and the last piece I need to use it for working it to have pyenv running fine.
When trying to pyenv install x.xx.x it fails with this error:
ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib?
I "tried to try" what t... | [
"About the doubt on what <openssl install prefix> is, I'll edit the question clarifying it.\nAbout how to make pyenv install versions successfully, after trying everything I found about the topic that's the only thing that worked for me:\nLDFLAGS=\"-Wl,-rpath,$(brew --prefix openssl)/lib\" \\\nCPPFLAGS=\"-I$(brew -... | [
4,
1,
1,
1,
0,
0
] | [] | [] | [
"openssl",
"pyenv",
"python",
"ubuntu_22.04"
] | stackoverflow_0072842089_openssl_pyenv_python_ubuntu_22.04.txt |
Q:
How can I fix this code so that inputs that start and end with 0 will show the zeros
My code runs fine, for example, if i input 123, i will get 321. However there is a problem when I try the input 01230, it would output 321. I can't seem to figure it out.
edit: it has to be done using integers as data type.
while ... | How can I fix this code so that inputs that start and end with 0 will show the zeros | My code runs fine, for example, if i input 123, i will get 321. However there is a problem when I try the input 01230, it would output 321. I can't seem to figure it out.
edit: it has to be done using integers as data type.
while True:
reverse=0
num=str(input("Enter an integer of at least 2 digits or -1 to quit... | [
"You could just keep your variables as strings. Following is a snippet of code that tweaks your current program.\nwhile True:\n reverse=0\n num=str(input(\"Enter an integer of at least 2 digits or -1 to quit: \"))\n if num == str(-1):\n break\n elif len(num)< 2 or len(num)>11:\n print(\"e... | [
0,
0
] | [] | [] | [
"logic",
"python",
"reverse"
] | stackoverflow_0074382584_logic_python_reverse.txt |
Q:
ModuleNotFoundError and Pyenv and python 3.8.10
I am working under Windows 10, and I have several version of python, but I need to work under Python 3.8.10 (with pyenv shell 3.8.10 check the picture below).
I get this exception when I launch my code:
Exception has occurred: ModuleNotFoundError
No module named 'sta... | ModuleNotFoundError and Pyenv and python 3.8.10 | I am working under Windows 10, and I have several version of python, but I need to work under Python 3.8.10 (with pyenv shell 3.8.10 check the picture below).
I get this exception when I launch my code:
Exception has occurred: ModuleNotFoundError
No module named 'statsmodels'
However, statsmodels has already been insta... | [
"\nHowever, statsmodels has already been installed with pip (under the 3.10.8 MS version). Indeed, it works under 3.10.8 but not under 3.8.10.\n\nDifferent versions of python have different site-packages. When you choose the 3.8.10, python interpreter cannot get the packages that you installed in the 3.10.8's site-... | [
2
] | [] | [] | [
"pyenv",
"python",
"visual_studio_code"
] | stackoverflow_0074374925_pyenv_python_visual_studio_code.txt |
Q:
How to plot the initial figure and update it in the same callback, but in a sequence?
Here is a part of my code for plotting and adding traces to the plot.
I have two chained dropdown menus. With the first one, I can select the CSV file and store it as a Jason dataframe, and accordingly the options for the second ... | How to plot the initial figure and update it in the same callback, but in a sequence? | Here is a part of my code for plotting and adding traces to the plot.
I have two chained dropdown menus. With the first one, I can select the CSV file and store it as a Jason dataframe, and accordingly the options for the second dropdown menu updates based on the column names of the CSV file.
Now, for plotting, I want ... | [
"I think you should add more condition in your callback. Something as below:\n@callback(\n Output('graph3', 'figure'),\n Input('table', 'data'),\n Input('dropdown2', 'value'),\n Input('my_rangeslider', 'value'),\n #prevent_initial_call=True\n)\ndef plot_trajectory(js_df, feature, ranges):\n if fea... | [
0
] | [] | [] | [
"callback",
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074380674_callback_plotly_plotly_dash_python.txt |
Q:
python pandas how to remove after specific string?
I have an data frame like this
details
Pinene 0.16%, Borneol 0.08%, Myrcene 0.12%,Total terpenes content 1.00%, Parents Strains Kandy KushCookie Monster
Pinene 0.18%, Borneol 0.08%, Myrcene 0.2%,Total terpenes content 05.00%, Parents Strains Kan... | python pandas how to remove after specific string? | I have an data frame like this
details
Pinene 0.16%, Borneol 0.08%, Myrcene 0.12%,Total terpenes content 1.00%, Parents Strains Kandy KushCookie Monster
Pinene 0.18%, Borneol 0.08%, Myrcene 0.2%,Total terpenes content 05.00%, Parents Strains Kandy KushCookie Monster
I want to remove everything after... | [
"here is one way to do it\n# using regex extract everything prior to 'Total terpenes content' and until\n# positive lookahead of \",\"\n# and assign back to details column\n\ndf['details']=df['details'].str.extract(r'(.*Total terpenes content.*(?=,))' )\ndf\n\n\n0 Pinene 0.16%, Borneol 0.08%, Myrcene 0.12%,Tot..... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074383253_dataframe_pandas_python_python_3.x.txt |
Q:
updating plotly figure [every several seconds] in jupyter
I'm new to the plotly python package and I've faced with such problem:
There is a pandas dataframe that is updating in a loop and I have to plot data from it with plotly.
At the beginning all df.response values are None and then it starts to fill it. Here i... | updating plotly figure [every several seconds] in jupyter | I'm new to the plotly python package and I've faced with such problem:
There is a pandas dataframe that is updating in a loop and I have to plot data from it with plotly.
At the beginning all df.response values are None and then it starts to fill it. Here is an example:
at the beginning
after it starts to fill
I want p... | [
"\ngiven you want to update as data arrives you need an event / interrupt handling approach\nthis example uses time as the event / interupt, a dash Interval\nsimulates more data by concatenating additional data to dataframe then updates the figure in the callback\n\nimport plotly.graph_objects as go\nimport numpy a... | [
1,
0
] | [] | [] | [
"jupyter_notebook",
"pandas",
"plotly",
"python",
"python_multiprocessing"
] | stackoverflow_0068731086_jupyter_notebook_pandas_plotly_python_python_multiprocessing.txt |
Q:
Pythonic way of handling typing Optional?
I'm parsing dict coming from elsewhere and the value is optional
a: typing.Optional = elsewhere_dict.get(a)
When I want to run any 3d party functions on it, I call
b = foo(a) if a is not None else None and I cant pass None to foo or wrap foo.
Is there a better way to call ... | Pythonic way of handling typing Optional? | I'm parsing dict coming from elsewhere and the value is optional
a: typing.Optional = elsewhere_dict.get(a)
When I want to run any 3d party functions on it, I call
b = foo(a) if a is not None else None and I cant pass None to foo or wrap foo.
Is there a better way to call this, without repeating if a is not None else N... | [
"I don't think there is anything built-in for that, but it is rather trivial to implement call_optional yourself:\ndef call_optional(arg, func):\n if arg is not None:\n return func(arg)\n\n"
] | [
1
] | [] | [] | [
"python",
"python_3.x",
"python_typing"
] | stackoverflow_0074383291_python_python_3.x_python_typing.txt |
Q:
Find the index of the last true occurrence in a column by row
I have the following table format:
id
bool
1
true
2
true
3
false
4
false
5
false
6
true
I'd like it so that I could get another column with the index of the last true occurrence in the bool column by row. If it's true in it's own row then return... | Find the index of the last true occurrence in a column by row | I have the following table format:
id
bool
1
true
2
true
3
false
4
false
5
false
6
true
I'd like it so that I could get another column with the index of the last true occurrence in the bool column by row. If it's true in it's own row then return it's own id. It doesn't sound too hard using a for l... | [
"IIUC, you can mask and ffill:\ndf['new'] = df['id'].where(df['bool']).ffill(downcast='infer')\n\noutput:\n id bool new\n0 1 True 1\n1 2 True 2\n2 3 False 2\n3 4 False 2\n4 5 False 2\n5 6 True 6\n\n",
"In your case do\ndf['new'] = df['id'].mul(df['bool']).cummax(... | [
4,
2,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0071666523_pandas_python.txt |
Q:
How to implement @dataclass to define arithmetic operations in Python?
I'm learning Python on my own and I found a task that requires using a decorator @dataclass to create a class with basic arithmetic operations.
from dataclasses import dataclass
from numbers import Number
@dataclass
class MyClass:
x: float... | How to implement @dataclass to define arithmetic operations in Python? | I'm learning Python on my own and I found a task that requires using a decorator @dataclass to create a class with basic arithmetic operations.
from dataclasses import dataclass
from numbers import Number
@dataclass
class MyClass:
x: float
y: float
def __add__(self, other):
match other:
... | [
"If you're trying to make a complete numeric type, I strongly suggest checking out the implementation of the fractions.Fraction type in the fractions source code. The class was intentionally designed as a model for how you'd overload all the pairs of operators needed to implement a numeric type at the Python layer ... | [
1
] | [] | [] | [
"oop",
"python",
"python_dataclasses",
"structural_pattern_matching"
] | stackoverflow_0074383205_oop_python_python_dataclasses_structural_pattern_matching.txt |
Q:
Tensorflow Estimator training works on CPU, but terminates with NaN on GPU
I'm trying to train a model written in Tf (specifically this one: Depth and Motion Learning). It works just fine on CPU, but when I try to train it on GPU it uses up almost all of its memory no matter what batch size I set, and throws an er... | Tensorflow Estimator training works on CPU, but terminates with NaN on GPU | I'm trying to train a model written in Tf (specifically this one: Depth and Motion Learning). It works just fine on CPU, but when I try to train it on GPU it uses up almost all of its memory no matter what batch size I set, and throws an error (not always the same) that may not because of the memory usage but that was ... | [
"I found that the source of my problems might be this bug for CUDA 10.0. I've yet to find a workaround for that that's suitable for me.\n"
] | [
0
] | [] | [] | [
"machine_learning",
"memory",
"python",
"tensorflow"
] | stackoverflow_0074380886_machine_learning_memory_python_tensorflow.txt |
Q:
How can I find probability of categorical variable?
I have three columns in a dataset that tracks breaches in the USA. These are all discrete categorical variables. The dataset has 9k entries.
'State' tracks where the breach occurred. for example, VA, NY.
'Type of Breach' tracks, type of breach.Hacking, Fraud, etc... | How can I find probability of categorical variable? | I have three columns in a dataset that tracks breaches in the USA. These are all discrete categorical variables. The dataset has 9k entries.
'State' tracks where the breach occurred. for example, VA, NY.
'Type of Breach' tracks, type of breach.Hacking, Fraud, etc.
'Type of Org' tracks the sector of the organization. 'M... | [
"Yes, Nick Odell, that is precisely what I am trying to find.\nLet's say I am org X operating in the MEDICAL sector in VA. I want the macro probability so that we can have comparables. Kind of like earnings comparable to determine stock value.\n"
] | [
0
] | [] | [] | [
"probability",
"python",
"r"
] | stackoverflow_0074369391_probability_python_r.txt |
Q:
How to get the return value of a function in multiprocessing code
This is my python code. I am trying to get the returned value(aa1) from the print_cube()
Is there a way to get the value of aa1 inside the main(). I have to use multiprocessing to call other functions also.
import multiprocessing
def print_cube(n... | How to get the return value of a function in multiprocessing code | This is my python code. I am trying to get the returned value(aa1) from the print_cube()
Is there a way to get the value of aa1 inside the main(). I have to use multiprocessing to call other functions also.
import multiprocessing
def print_cube(num):
aa1 = num * num * num
return aa1
def main():
# crea... | [
"Use multiprocessing.Pool when you want to retrieve return values.\ndef print_cube(num):\n aa1 = num * num * num\n return aa1\n\n\ndef main():\n with Pool(5) as p:\n results = p.map(print_cube, range(10, 15))\n print(results)\n\n\nif __name__ == \"__main__\":\n main()\n\n",
"You can use Queu... | [
2,
0
] | [] | [] | [
"python",
"python_multiprocessing"
] | stackoverflow_0066104063_python_python_multiprocessing.txt |
Q:
PIP Install Cannot Find Header File - How to Locate?
I'm trying to pip install a library that needs access to an external header files (i.e. SDL). I know this because I get the following error:
fatal error C1083: Cannot open include file: 'SDL_version.h': No such file or directory
The installation guide says to s... | PIP Install Cannot Find Header File - How to Locate? | I'm trying to pip install a library that needs access to an external header files (i.e. SDL). I know this because I get the following error:
fatal error C1083: Cannot open include file: 'SDL_version.h': No such file or directory
The installation guide says to set SDL_ROOT to the root of the library's directory --- i.e... | [
"I figured it out. I had to define the variable locally in PowerShell...\nSet-Variable -Name \"SDL_ROOT\" -Value \"C:\\\\Program Files\\\\Python311\\\\external_lib\\\\SDL2-2.24.2\"\n\nand THEN, only after the variables were defined locally could I do a pip install.\npip install ffpyplayer \n\n"
] | [
0
] | [] | [] | [
"pip",
"pycharm",
"python",
"python_3.x",
"sdl"
] | stackoverflow_0074379695_pip_pycharm_python_python_3.x_sdl.txt |
Q:
class and defining __str__
This is the exercise:
Write the special method __str__() for CarRecord.
Sample output with input: 2009 'ABC321'
Year: 2009, VIN: ABC321
The following code is what I have came up with, but I'm receiving an error:
TYPEERROR: __str__ returned non-string
I can't figure out where I went wrong... | class and defining __str__ | This is the exercise:
Write the special method __str__() for CarRecord.
Sample output with input: 2009 'ABC321'
Year: 2009, VIN: ABC321
The following code is what I have came up with, but I'm receiving an error:
TYPEERROR: __str__ returned non-string
I can't figure out where I went wrong.
class CarRecord:
def __ini... | [
"You're returning a tuple using all those commas. You should also be using self, rather than my_car, while inside the class. Try like this:\n def __str__(self):\n return f\"Year: {self.year_made}, VIN: {self.car_vin}\"\n\nThe f before the string tells Python to replace any code in braces inside the string... | [
4,
0,
0,
0
] | [] | [] | [
"class",
"python",
"string"
] | stackoverflow_0066748766_class_python_string.txt |
Q:
background color for row with multiple boxes
I want to set background color for whole row, here is what I did now:
import PySimpleGUI as sg
layout = [
[sg.Column(
[
[sg.pin(sg.Text('Values', background_color='lightblue', font=('Helvitica 13 bold'))),
sg.pin(sg.T("$",font=('He... | background color for row with multiple boxes | I want to set background color for whole row, here is what I did now:
import PySimpleGUI as sg
layout = [
[sg.Column(
[
[sg.pin(sg.Text('Values', background_color='lightblue', font=('Helvitica 13 bold'))),
sg.pin(sg.T("$",font=('Helvitica 13 bold'), background_color='lightblue')),... | [
"There's no option for the background color of sg.pin, try to define one for it.\nimport PySimpleGUI as sg\n\ndef pin(elem, vertical_alignment=None, expand_x=None, expand_y=None):\n return sg.Column([[elem, sg.Column([[]], pad=(0,0))]], pad=(0, 0), vertical_alignment=vertical_alignment, expand_x=expand_x, expand... | [
0
] | [] | [] | [
"pysimplegui",
"python"
] | stackoverflow_0074381263_pysimplegui_python.txt |
Q:
Out of range float values are not JSON compliant: nan, Django Rest Framework with Json Serialization Exception
I work with rest_framework to implement a django API. The table Order from my database has nan fields, and Nan generates the error Out of range float values are not JSON compliant: nan.
How to ensure that... | Out of range float values are not JSON compliant: nan, Django Rest Framework with Json Serialization Exception | I work with rest_framework to implement a django API. The table Order from my database has nan fields, and Nan generates the error Out of range float values are not JSON compliant: nan.
How to ensure that serializing Nan to JSON works.
#serializers.py
from rest_framework import serializers
from api.models import Order... | [
"JSON don't suport NaN values\nYou can correct the model data with the following command replacing NaN with None\nfrom django.db.models import Q\nimport math\nimport decimal\n\nMyModel.objects.filter(Q(field_name=math.nan) | Q(field_name=decimal.Decimal(\"NaN\"))).update(field_name=None)\n\nOr adding a method that ... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_serializer",
"json",
"python"
] | stackoverflow_0072058987_django_django_rest_framework_django_serializer_json_python.txt |
Q:
getting the return value of a function used in multiprocess
Say I have the below code, a function that does something, which is initiated in a Process, and returns a value.
from multiprocessing import Process
def my_func(arg):
return 'Hello, ' + arg
p1 = Process(target=my_func, args=('John',)
p1.start()
p1.j... | getting the return value of a function used in multiprocess | Say I have the below code, a function that does something, which is initiated in a Process, and returns a value.
from multiprocessing import Process
def my_func(arg):
return 'Hello, ' + arg
p1 = Process(target=my_func, args=('John',)
p1.start()
p1.join()
How do I get the return value of the function?
| [
"Answer\nfrom multiprocessing import Process, Queue\n\nQ = Queue()\n\ndef my_func(arg):\n Q.put('Hello, ' + arg)\n\np1 = Process(target=my_func, args=('John',))\np1.start()\nprint(Q.get())\np1.join()\n\n",
"You can pass Queue of multiprocessing to my_func() as shown below:\nfrom multiprocessing import Process,... | [
15,
0
] | [] | [] | [
"python",
"python_multiprocessing"
] | stackoverflow_0054615502_python_python_multiprocessing.txt |
Q:
Jupyter notebook setup in VS Code was working fine; now get "Running cells with 'Python 3.9.12 64-bit' requires ipykernel package."
I have a python project (folder) that I'm working on in VS Code (in Windows) and it uses Jupyter notebook. The project uses a virtual env. It was working fine a few days ago. Today wh... | Jupyter notebook setup in VS Code was working fine; now get "Running cells with 'Python 3.9.12 64-bit' requires ipykernel package." | I have a python project (folder) that I'm working on in VS Code (in Windows) and it uses Jupyter notebook. The project uses a virtual env. It was working fine a few days ago. Today when I open up one of the .ipynb files in the project, I see:
Running cells with 'Python 3.9.12 64-bit' requires ipykernel package.
Run th... | [
"Here's my attempt at an explanation of the solution. I'm sure someone understands this better and can explain it better (please do and I will pick your answer as the solution!):\nVS Code uses one python interpreter for .py files and terminal and a different python interpreter for Jupyter notebook (.ipynb) files. T... | [
0
] | [] | [] | [
"jupyter_notebook",
"python",
"visual_studio_code"
] | stackoverflow_0074369471_jupyter_notebook_python_visual_studio_code.txt |
Q:
Skipping through all elifs to the end and activating the last statements
I am making a very creative tetris clone for a project with a friend and we have custom sprites for every shape (including the rotations) and we made a wall of else if statements for the rotations. It's supposed to work like this: It calls a ... | Skipping through all elifs to the end and activating the last statements | I am making a very creative tetris clone for a project with a friend and we have custom sprites for every shape (including the rotations) and we made a wall of else if statements for the rotations. It's supposed to work like this: It calls a random shape out of list of the main 7 shapes and every time the user presses ... | [
"I think the indentation is wrong here. Maybe try putting the last else-statement one tab further?\n",
"Please use elif instead of the else: if formulation to get away from the bewildering indentation - here's how it should look:\ndef sprite_right():\n global tetris\n tetris.hideturtle()\n if (tetris.sha... | [
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074383379_python_python_3.x.txt |
Q:
Display value that corresponds to a specific date in python
I just started to play around in python and need some help. Let's assume I have a table that looks like this
Date
Values
Values_2
22/01/01
1
11
22/01/02
2
12
22/01/03
2
13
I would like to display the number from column Values_2 that corresponds with ... | Display value that corresponds to a specific date in python | I just started to play around in python and need some help. Let's assume I have a table that looks like this
Date
Values
Values_2
22/01/01
1
11
22/01/02
2
12
22/01/03
2
13
I would like to display the number from column Values_2 that corresponds with the latest date. So the answer would be 13.
I've tried... | [
"import pandas as pd\ndf = pd.DataFrame({'date': ['1/1/2022', '1/2/2022', '1/3/2022'],\n 'value': [1, 2, 2], \n 'value_2': [11, 12, 13]})\ndf['date'] = pd.to_datetime(df['date'])\ndf[df[\"date\"]==df[\"date\"].max()]['value_2']\n\nUpdate:\nIf you want to calculate the mean value,... | [
0
] | [] | [] | [
"python",
"python_datetime"
] | stackoverflow_0074383446_python_python_datetime.txt |
Q:
How to incorporate an ANOVA into a "for loop" in python?
I am attempting to run an ANOVA on a number of variables from a list. However, I am having trouble letting indicating that the variable (variable 'lst) inside the ANOVA formula actually refers to a list.
Here is what I attempted:
lst = ['Item1', 'Item2']
fo... | How to incorporate an ANOVA into a "for loop" in python? | I am attempting to run an ANOVA on a number of variables from a list. However, I am having trouble letting indicating that the variable (variable 'lst) inside the ANOVA formula actually refers to a list.
Here is what I attempted:
lst = ['Item1', 'Item2']
for item in lst:
mod = ols('lst ~ Group', data= DF).fit()
... | [
"If you want to accces the correspondig item in the for loop you have to format the string, using the format() method.\nFor example:\nlst = ['Item1', 'Item2']\n\nfor item in lst:\n mod = ols('{} ~ Group'.format(item), data= DF).fit()\n aov_table = sm.stats.anova_lm(mod, typ=2)\n print(aov_table)\n\nThe for... | [
1,
0
] | [] | [] | [
"for_loop",
"python",
"python_3.x"
] | stackoverflow_0057013615_for_loop_python_python_3.x.txt |
Q:
Program paused while thread is being executed
I have a program that should start a web server (as the thread), and then display it in a CEF Browser (not a thread). But when I start it, it just waits for the thread to stop executing, which it will never do, since its an infinite loop.
print("Server started http://%... | Program paused while thread is being executed | I have a program that should start a web server (as the thread), and then display it in a CEF Browser (not a thread). But when I start it, it just waits for the thread to stop executing, which it will never do, since its an infinite loop.
print("Server started http://%s:%s" % (hostName, serverPort))
webServerThread = t... | [
"When you run webServerThread.join() immediately after webServerThread.start(), your app still have a run flow like a single-thread application. Move webServerThread.join() to the end.\nprint(\"Server started http://%s:%s\" % (hostName, serverPort))\nwebServerThread = threading.Thread(target=os.system, args = (\"py... | [
0
] | [] | [] | [
"chromium_embedded",
"python",
"python_3.x",
"python_multithreading",
"webserver"
] | stackoverflow_0074379253_chromium_embedded_python_python_3.x_python_multithreading_webserver.txt |
Q:
Change Logdir of Ray RLlib Training instead of ~/ray_results
I'm using Ray & RLlib to train RL agents on an Ubuntu system. Tensorboard is used to monitor the training progress by pointing it to ~/ray_results where all the log files for all runs are stored. Ray Tune is not being used.
For example, on starting a new... | Change Logdir of Ray RLlib Training instead of ~/ray_results | I'm using Ray & RLlib to train RL agents on an Ubuntu system. Tensorboard is used to monitor the training progress by pointing it to ~/ray_results where all the log files for all runs are stored. Ray Tune is not being used.
For example, on starting a new Ray/RLlib training run, a new directory will be created at
~/ray... | [
"\nIs it possible to configure Ray/RLlib to change the output directory of the log files from ~/ray_results to another location?\n\nThere is currently no way to configure this using RLib CLI tool (rllib).\nIf you're okay with Python API, then, as described in documentation, local_dir parameter of tune.run is respon... | [
5,
5,
0
] | [] | [] | [
"python",
"ray",
"ray_tune",
"reinforcement_learning",
"rllib"
] | stackoverflow_0062241261_python_ray_ray_tune_reinforcement_learning_rllib.txt |
Q:
How to render Javascript/dynamic content with aiohttp?
I would like to know if it is possible to render Javascript content from a website with the module aiohttp in an asynchronous way.
I know it works with static content or API endpoints, but I don´t know how to handle asynchronously dynamic content.
Thank you i... | How to render Javascript/dynamic content with aiohttp? | I would like to know if it is possible to render Javascript content from a website with the module aiohttp in an asynchronous way.
I know it works with static content or API endpoints, but I don´t know how to handle asynchronously dynamic content.
Thank you in advanced.
| [
"You could use requests-html, which is like the requests library but with JavaScript rendering, CSS selectors, XPath selectors, and async support.\n"
] | [
0
] | [] | [] | [
"aiohttp",
"asynchronous",
"python",
"python_asyncio"
] | stackoverflow_0071503198_aiohttp_asynchronous_python_python_asyncio.txt |
Q:
Heroku compiled slug size is too large but can't find large files
I'm trying to build a Python app (using streamlit) and getting
Compiled slug size: 664M is too large (max is 500M).
However, when I run
heroku run bash -a pitchcast
$ du -ha --max-depth 1 /app
the only thing that shows up is
4.0K /app
Where are... | Heroku compiled slug size is too large but can't find large files | I'm trying to build a Python app (using streamlit) and getting
Compiled slug size: 664M is too large (max is 500M).
However, when I run
heroku run bash -a pitchcast
$ du -ha --max-depth 1 /app
the only thing that shows up is
4.0K /app
Where are the large files and what can I do to reduce them?
| [
"Answering my own question: it seems like the size was due to the Python libraries, especially tensorflow. Switching from tensorflow to tensorflow-cpu got it under 500M\n"
] | [
0
] | [] | [] | [
"heroku",
"python",
"streamlit"
] | stackoverflow_0074381318_heroku_python_streamlit.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.