content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
how to set a relative box size in toga python
I'm making an app with Beeware and toga using python and I need a box to be half size of its parent.
Does toga have relative size units like CSS? How do I use them?
I thought to use the parent box size as a reference but the Box object has no size-related attributes (a... | how to set a relative box size in toga python | I'm making an app with Beeware and toga using python and I need a box to be half size of its parent.
Does toga have relative size units like CSS? How do I use them?
I thought to use the parent box size as a reference but the Box object has no size-related attributes (at least not documented).
| [
"If you add two children with equal flex values, then they will each be half the size of the parent:\nparent = Box(style=Pack(direction=\"column\"))\nchild1 = Box(style=Pack(flex=1))\nchild2 = Box(style=Pack(flex=1))\nparent.add(child1, child2)\n\n"
] | [
1
] | [] | [] | [
"beeware",
"python",
"units_of_measurement"
] | stackoverflow_0074573735_beeware_python_units_of_measurement.txt |
Q:
Does keras.backend.clear_session() deletes sessions in a process or globally?
I create up to 100 keras models in separated script an save them localy with model.save().
For Training them, I use multiprocessing.pool. In those processes I load each model separately. Because of occuring Memory Errors I used keras.bac... | Does keras.backend.clear_session() deletes sessions in a process or globally? | I create up to 100 keras models in separated script an save them localy with model.save().
For Training them, I use multiprocessing.pool. In those processes I load each model separately. Because of occuring Memory Errors I used keras.backend.clear_session(). This seems to work but I have also read that it deletes the w... | [
"I faced similar kind of issue but I am not running models in parallel but alternatively i;e; either of the models (in different folders but same model file names) will run. \nWhen I run the models directly without clear_session it was conflicting with the previously loaded model and cannot switch to other model. A... | [
3,
0
] | [] | [] | [
"keras",
"multiprocessing",
"python",
"tensorflow"
] | stackoverflow_0050823233_keras_multiprocessing_python_tensorflow.txt |
Q:
Changing the labelling of the numbers in the plot
I want to create IDL-like plots in python. I have come close to doing so by changing some of the details in the matplotlibrc file in the matplotlib directory. The following is what I have changed my matplotlibrc file to look like from the standard matplotlibrc file... | Changing the labelling of the numbers in the plot | I want to create IDL-like plots in python. I have come close to doing so by changing some of the details in the matplotlibrc file in the matplotlib directory. The following is what I have changed my matplotlibrc file to look like from the standard matplotlibrc file:
### MATPLOTLIBRC FORMAT
backend : tkagg
#... | [
"You need to include the line \ntext.latex.preamble : \\usepackage{sfmath}\n\nin your .matplotlibrc file. This tells latex to use sans-serif fonts for math-text, which is what it uses for tick labels.\n",
"Try to download this TTF font which is a replicate of the IDL's default Hershey font https://github.com/yang... | [
1,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0033643100_matplotlib_python.txt |
Q:
How to get the common index of two pandas dataframes?
I have two pandas DataFrames df1 and df2 and I want to transform them in order that they keep values only for the index that are common to the 2 dataframes.
df1
values 1
0
28/11/2000 -0.055276
29/11/200... | How to get the common index of two pandas dataframes? | I have two pandas DataFrames df1 and df2 and I want to transform them in order that they keep values only for the index that are common to the 2 dataframes.
df1
values 1
0
28/11/2000 -0.055276
29/11/2000 0.027427
30/11/2000 0.066009
01/12/20... | [
"You can use Index.intersection + DataFrame.loc:\nidx = df1.index.intersection(df2.index)\nprint (idx)\nIndex(['28/11/2000', '29/11/2000', '30/11/2000'], dtype='object')\n\nAlternative solution with numpy.intersect1d:\nidx = np.intersect1d(df1.index, df2.index)\nprint (idx)\n['28/11/2000' '29/11/2000' '30/11/2000']... | [
35,
8,
8,
4,
2,
2,
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0048170867_dataframe_pandas_python.txt |
Q:
Django how do you AutoComplete a ForeignKey Input field using Crispy Forms
Looking for any assistance as i just can't seem to get this.
I have a 'category' field that has approx 4000 categories in it, sourced from my table "Category". When a user inputs their details they choose from the category field. This works... | Django how do you AutoComplete a ForeignKey Input field using Crispy Forms | Looking for any assistance as i just can't seem to get this.
I have a 'category' field that has approx 4000 categories in it, sourced from my table "Category". When a user inputs their details they choose from the category field. This works fine as a drop down list but takes ages to scroll. I'd rather have the field as... | [
"Try changing your import:\nimport autocomplete_light.shortcuts as al\n\nal.register\n\nThis has changed in version 2.2:\n\n2.2.0rc1\n\n PENDING BREAK WARNING, Django >= 1.9.\n\n The good old ``import autocomplete_light`` API support will be dropped with\n Django 1.9. All imports have moved to ``autocomple... | [
0
] | [] | [] | [
"autocomplete",
"django",
"django_autocomplete_light",
"django_crispy_forms",
"python"
] | stackoverflow_0074302824_autocomplete_django_django_autocomplete_light_django_crispy_forms_python.txt |
Q:
Is using an 'anonymous' threading.Lock() always an error?
I'm trying to make sense of some code and I see this function below
def get_batch(
self,
) -> Union[Tuple[List[int], torch.Tensor], Tuple[None, None]]:
"""
Return an inference batch
"""
with threading.Lock():
indices: List[int] =... | Is using an 'anonymous' threading.Lock() always an error? | I'm trying to make sense of some code and I see this function below
def get_batch(
self,
) -> Union[Tuple[List[int], torch.Tensor], Tuple[None, None]]:
"""
Return an inference batch
"""
with threading.Lock():
indices: List[int] = []
for _ in range(self.batch_size):
try:
... | [
"Yes, @Homer512's comment nailed it. Each activation of the function creates a new Lock object, and there's no way for those objects to be shared between threads. Nothing is accomplished by locking a Lock that cannot be locked by any other thread. It's effectively a no-op.\n"
] | [
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0074589199_multithreading_python.txt |
Q:
Create a land mask from latitude and longitude arrays
Given latitude and longitude arrays, I'm tryin to genereate a land_mask, an array of the same size that tells whether a coordinate is land or not.
lon=np.random.uniform(0,150,size=[1000,1000])
lat=np.random.uniform(-90,90,size=[1000,1000])
from global_land_mas... | Create a land mask from latitude and longitude arrays | Given latitude and longitude arrays, I'm tryin to genereate a land_mask, an array of the same size that tells whether a coordinate is land or not.
lon=np.random.uniform(0,150,size=[1000,1000])
lat=np.random.uniform(-90,90,size=[1000,1000])
from global_land_mask import globe
land_mask=globe.is_land(lat,lon)
This is a ... | [
"so it seems globe.is_land(y,x) doesn't take a masked array. An equitable solution would be to use a coord outside your domain (if possible). So:\nlon[lon==327.67] = 170\nlat[lat==327.67] = -90\n\nfrom global_land_mask import globe\nland_mask=globe.is_land(lat,lon)\n\nmasked = np.where((lat==-90)|(lon==170), False,... | [
2
] | [] | [] | [
"arrays",
"cartopy",
"numpy",
"python"
] | stackoverflow_0074593424_arrays_cartopy_numpy_python.txt |
Q:
How can I change the value of a row with indexing?
I've scraped the crypto.com website to get the current prices of crypto coins in DataFrame form, it worked perfectly with pandas, but the 'Prices' values are mixed.
here's the output:
Name Price 24H CHANGE
0 ... | How can I change the value of a row with indexing? | I've scraped the crypto.com website to get the current prices of crypto coins in DataFrame form, it worked perfectly with pandas, but the 'Prices' values are mixed.
here's the output:
Name Price 24H CHANGE
0 BBitcoinBTC 16.678,36$16.678,36+0,32% +0,32%... | [
"if youre regex expression is good, this would work\ndf['Price']= df['Price'].apply(lambda x: pattern.search(x).group(1))\n\n",
"can you try this:\ndf['price_v2']=df['Price'].apply(lambda x: '$' + x.split('$')[1])\n\n'''\n0 $16.678,36+0,32%\n1 $1.230,40\n2 $1,02\n3 $315,... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074593208_dataframe_pandas_python.txt |
Q:
PyGIWarning: Gtk and Rsvg were imported without specifying a version first. Use gi.require_version
$ python -c 'from gi.repository import Gtk'
-c:1: PyGIWarning: Gtk was imported without specifying a version first. Use gi.require_version('Gtk', '3.0') before import to ensure that the right version gets loaded.
wha... | PyGIWarning: Gtk and Rsvg were imported without specifying a version first. Use gi.require_version | $ python -c 'from gi.repository import Gtk'
-c:1: PyGIWarning: Gtk was imported without specifying a version first. Use gi.require_version('Gtk', '3.0') before import to ensure that the right version gets loaded.
what should i do?
| [
"You got a warning because you are importing gtk wihtouht specifing the version. This is because gtk has several version so you should declare which want to use.\nIn order to do so you can open a python terminal (type python on your commandline) and execute the following code:\nimport gi\ngi.require_version('Gtk', ... | [
5,
1,
0
] | [] | [] | [
"centos",
"gtk",
"linux",
"python",
"tryton"
] | stackoverflow_0063631072_centos_gtk_linux_python_tryton.txt |
Q:
for loop on lists and keep common items
I wish to iterate through a list and only retain in it those items that also appear in two other lists.
For example:
list1 = [1, 2, 3, "a", 4, 5, 6, 7, 8, 9]
list2 = [2, 5, "a", 8, 4]
list3 = [4, 6, "a", 5]
for item in list1:
if item not in list2 and item not in list3:
... | for loop on lists and keep common items | I wish to iterate through a list and only retain in it those items that also appear in two other lists.
For example:
list1 = [1, 2, 3, "a", 4, 5, 6, 7, 8, 9]
list2 = [2, 5, "a", 8, 4]
list3 = [4, 6, "a", 5]
for item in list1:
if item not in list2 and item not in list3:
list1.remove(item)
print(list1)
I expe... | [
"here is another way of doing it:\nlist1 = [1, 2, 3, \"a\", 4, 5, 6, 7, 8, 9]\nlist2 = [2, 5, \"a\", 8, 4]\nlist3 = [4, 6, \"a\", 5]\n\nlist4 = []\n\nfor item in list1:\n if item in list2 and item in list3:\n list4.append(item)\n\nprint(list4)\n\n\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074593641_python.txt |
Q:
Get correlation per groupby/apply in Python Polars
I have a pandas DataFrame df:
d = {'era': ["a", "a", "b","b","c", "c"], 'feature1': [3, 4, 5, 6, 7, 8], 'feature2': [7, 8, 9, 10, 11, 12], 'target': [1, 2, 3, 4, 5 ,6]}
df = pd.DataFrame(data=d)
And I want to apply a correlation between the feature_cols = ['featu... | Get correlation per groupby/apply in Python Polars | I have a pandas DataFrame df:
d = {'era': ["a", "a", "b","b","c", "c"], 'feature1': [3, 4, 5, 6, 7, 8], 'feature2': [7, 8, 9, 10, 11, 12], 'target': [1, 2, 3, 4, 5 ,6]}
df = pd.DataFrame(data=d)
And I want to apply a correlation between the feature_cols = ['feature1', 'feature2'] and the TARGET_COL = 'target' for each... | [
"Here's the polars equivalent of that code. You can do this by combining groupby() and agg().\nimport polars as pl\n\nd = {'era': [\"a\", \"a\", \"b\",\"b\",\"c\", \"c\"], 'feature1': [3, 4, 5, 6, 7, 8], 'feature2': [7, 8, 9, 10, 11, 12], 'target': [1, 2, 3, 4, 5 ,6]}\ndf = pl.DataFrame(d)\nfeature_cols = ['feature... | [
1
] | [] | [] | [
"group_by",
"pandas",
"pandas_apply",
"python",
"python_polars"
] | stackoverflow_0074593723_group_by_pandas_pandas_apply_python_python_polars.txt |
Q:
Is It Possible To Upgrade The Tkinter Library In Python?
I really want to know is it possible to upgrade the tkinter library in python because currently i am working on a project named Translator where text of any language will be converted to a text of any other language and vice versa same as our google translat... | Is It Possible To Upgrade The Tkinter Library In Python? | I really want to know is it possible to upgrade the tkinter library in python because currently i am working on a project named Translator where text of any language will be converted to a text of any other language and vice versa same as our google translator. So the problem I am facing is that whenever I want to writ... | [
"Each version of Python comes with corresponding versions of the Python-coded tkinter and C-coded _tkinter modules. (Tkinter imports _tkinter.) One cannot upgrade tkinter except by upgrading Python.\nThat said, the tkinter that comes with current versions of Python (3.10+) potentially display all unicode characte... | [
0
] | [] | [] | [
"python",
"python_idle",
"tkinter"
] | stackoverflow_0074587775_python_python_idle_tkinter.txt |
Q:
Iterate a JSONfield corresponding to an object
The view receives an user request and then returns the corresponding object on the 'ControleProdutos' model db.
views.py
def relatorio_produtos(request):
if request.method == 'POST':
prod_json = ControleProduto.objects.get(pk = request.POST.get('periodo'))... | Iterate a JSONfield corresponding to an object | The view receives an user request and then returns the corresponding object on the 'ControleProdutos' model db.
views.py
def relatorio_produtos(request):
if request.method == 'POST':
prod_json = ControleProduto.objects.get(pk = request.POST.get('periodo'))
return render(request, 'selecao/historico-p... | [
"Django probably stores the JOSNField, produtos, in a varchar or nvarchar field in your database.\nWhether or not that's true, you probably could solve this issue in the get_data method in ControleProduto.\nAn example of this would be:\ndef get_data(self):\n return{\n 'periodo': self.periodo,\n 'pr... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074593683_django_python.txt |
Q:
Pygame-2.1.3.dev8 release not working with moviepy
I tried installing pygame with pip install pygame --pre but that release(Pygame-2.1.3.dev8) of pygame seems to not be compatible with the moviepy library.
Does anyone know if there is some kind of workaround to get this to work?
Error:
Traceback (most recent call ... | Pygame-2.1.3.dev8 release not working with moviepy | I tried installing pygame with pip install pygame --pre but that release(Pygame-2.1.3.dev8) of pygame seems to not be compatible with the moviepy library.
Does anyone know if there is some kind of workaround to get this to work?
Error:
Traceback (most recent call last):
File "C:\Users\oscar\OneDrive\Skrivbord\Auto-to... | [
"Unfortunately, Pygame has not been ported to Python 3.11. I would downgrade to 3.10 and try that instead. There aren't many critical features added in 3.11 that I think you should be able to live without. I doubt you'll need tomllib, for instance.\n"
] | [
0
] | [] | [] | [
"moviepy",
"pygame",
"python",
"python_3.11"
] | stackoverflow_0074593879_moviepy_pygame_python_python_3.11.txt |
Q:
Why doesn't my program properly read from my text file?
I made a text file with a list of usernames and passwords. My program (in a tkinter page) is supposed to check whether the username and password exists in the file, and then if it doesn't it makes a label that says 'username or password incorrect'. However, e... | Why doesn't my program properly read from my text file? | I made a text file with a list of usernames and passwords. My program (in a tkinter page) is supposed to check whether the username and password exists in the file, and then if it doesn't it makes a label that says 'username or password incorrect'. However, even when the username and password clealy exists in the text ... | [
"It looks like you first need to read the file, and only then check for the occurrence of the desired one.\nwith open('AccountDatabase.txt', 'r') as f:\n file_logins = f.read()\n if loginUsernameE.get() + '.' + loginPasswordE.get() not in file_logins:\n login_incorrect()\n print('incorrect')\n\n... | [
1,
0
] | [] | [] | [
"database",
"python",
"text_files",
"tkinter",
"txt"
] | stackoverflow_0074593227_database_python_text_files_tkinter_txt.txt |
Q:
Converting the output of pickle.dumps() into a string and back?
In my Python program, I have a list with some objects from a custom class:
# Some example program, not the actual code.
class SomeClass:
def __init__(self):
import random
import os
self.thing = random.randint(5,15)
... | Converting the output of pickle.dumps() into a string and back? | In my Python program, I have a list with some objects from a custom class:
# Some example program, not the actual code.
class SomeClass:
def __init__(self):
import random
import os
self.thing = random.randint(5,15)
self.thing2 = str(os.urandom(16))
self.thing3 = random.randin... | [
"The usual way to \"stringify\" binary data is to base64-encode it:\n>>> import pickle\n>>> import base64\n>>> L = list(range(5))\n>>> ps = pickle.dumps(L)\n>>> ps\nb'\\x80\\x04\\x95\\x0f\\x00\\x00\\x00\\x00\\x00\\x00\\x00]\\x94(K\\x00K\\x01K\\x02K\\x03K\\x04e.'\n>>> s = base64.b64encode(ps).decode('ascii')\n>>> s\... | [
2
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0074593860_pickle_python.txt |
Q:
python ndarray multiply columns
I have a dataframe with two columns that are json.
So for example,
df = A B C D
1. 2. {b:1,c:2,d:{r:1,t:{y:0}}} {v:9}
I want to flatten it entirely, so every value in the json will be in a seperate columns, and the name will be the full path. So her... | python ndarray multiply columns | I have a dataframe with two columns that are json.
So for example,
df = A B C D
1. 2. {b:1,c:2,d:{r:1,t:{y:0}}} {v:9}
I want to flatten it entirely, so every value in the json will be in a seperate columns, and the name will be the full path. So here the value 0 will be in the column:
... | [
"If your dataframe contains only nested dictionaries (no lists), you can try:\ndef get_values(df):\n def _parse(val, current_path):\n if isinstance(val, dict):\n for k, v in val.items():\n yield from _parse(v, current_path + [k])\n else:\n yield \"_\".join(map(s... | [
1
] | [] | [] | [
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0074593846_dataframe_json_pandas_python.txt |
Q:
How do I connect categorical scatter points with a vertical line?
I have data in dataframe about different assets - let's say A,B,C,D.
What I would like to do is create a chart that looks something like this:
These assets are at a maximum of price n (let's say in our case 3.5), the dotted line and dotted circle s... | How do I connect categorical scatter points with a vertical line? | I have data in dataframe about different assets - let's say A,B,C,D.
What I would like to do is create a chart that looks something like this:
These assets are at a maximum of price n (let's say in our case 3.5), the dotted line and dotted circle show the historic minimum. Furthermore, it is possible to also display a... | [
"You can draw an open scatter plot using facecolor='none'. And setting facecolor=None will get the default with the face color equal to the main color.\nWith plt.vlines() you can draw vertical lines between the minima and the maxima.\nfrom matplotlib import pyplot as plt\nimport pandas as pd\n\ndf = pd.DataFrame({... | [
2
] | [] | [] | [
"matplotlib",
"pandas",
"python",
"scatter_plot"
] | stackoverflow_0074593695_matplotlib_pandas_python_scatter_plot.txt |
Q:
How to split a list into sublists with specific range for each sublist?
I want to split a list into sublist with specific 'if statement' for each sublist.
For examle:
input:
a = [1, 2, 7.9, 3, 4, 3.7, 5, 6, 2.2, 7, 8, 1.2, 5.7]
output:
b = [[1, 1.2, 2], [2.2, 3, 3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]
Values should b... | How to split a list into sublists with specific range for each sublist? | I want to split a list into sublist with specific 'if statement' for each sublist.
For examle:
input:
a = [1, 2, 7.9, 3, 4, 3.7, 5, 6, 2.2, 7, 8, 1.2, 5.7]
output:
b = [[1, 1.2, 2], [2.2, 3, 3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]
Values should be grouped by certain range. here it is between (1:2); (2.1:4); (4.1:6); (6.1:... | [
"You seem to want to divide your data into buckets of width dx. Assuming this, your expected output would be:\n[[1, 1.2, 2], [2.2, 3], [3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]\n\nFirst, let's sort the input numbers:\nnumbers = sorted(a)\n\nNow, we'll iterate over this sorted list, and append to a bucket list as long as ... | [
1,
0
] | [] | [] | [
"arrays",
"loops",
"python",
"sorting"
] | stackoverflow_0074593812_arrays_loops_python_sorting.txt |
Q:
Pass build inputs from Jenkins to a Python script
I wrote this simple Jenkinsfile to execute a Python script.
The Jenkins job is supposed to take the value of the Jenkins build parameter and inject it to the python script, then execute the python script.
Here is the Jenkinsfile
pipeline{
agent any
parameters {
... | Pass build inputs from Jenkins to a Python script | I wrote this simple Jenkinsfile to execute a Python script.
The Jenkins job is supposed to take the value of the Jenkins build parameter and inject it to the python script, then execute the python script.
Here is the Jenkinsfile
pipeline{
agent any
parameters {
string description: 'write the week number', name: 'We... | [
"You need your python script to be able to parse command line arguments or named command line arguments.\nIf your script is using command line argument you can pass parameters as follow:\nstages{\n stage(\"Pass Week Number&execute script\"){\n steps{\n sh('python3 statistics.py ' + params.Week_... | [
0
] | [] | [] | [
"groovy",
"jenkins",
"python"
] | stackoverflow_0074548804_groovy_jenkins_python.txt |
Q:
AttributeError: 'Tensor' object has no attribute '_keras_history'
I looked for all the "'Tensor' object has no attribute ***" but none seems related to Keras (except for TensorFlow: AttributeError: 'Tensor' object has no attribute 'log10' which didn't help)...
I am making a sort of GAN (Generative Adversarial Netw... | AttributeError: 'Tensor' object has no attribute '_keras_history' | I looked for all the "'Tensor' object has no attribute ***" but none seems related to Keras (except for TensorFlow: AttributeError: 'Tensor' object has no attribute 'log10' which didn't help)...
I am making a sort of GAN (Generative Adversarial Networks). Here you can find the structure.
Layer (type) ... | [
"My problem was using '+' instead of 'Add' on keras\n",
"Since the error comes directly from here:\nTraceback (most recent call last):\n File \"C:\\Users\\Asmaa\\Documents\\BillyValuation\\GFD.py\", line 88, in <module>\nGAN = make_gan(inputSentence, G, F, D)\n File \"C:\\Users\\Asmaa\\Documents\\BillyValuation... | [
23,
13,
4,
1,
0,
0
] | [] | [] | [
"attributeerror",
"keras",
"python"
] | stackoverflow_0044889187_attributeerror_keras_python.txt |
Q:
I'm not sure what I'm doing wrong on this program
Define a Course base class with attributes number and title. Define a print_info() method that displays the course number and title.
Also define a derived class OfferedCourse with the additional attributes instructor_name, term, and class_time.
Ex: If the input is:... | I'm not sure what I'm doing wrong on this program | Define a Course base class with attributes number and title. Define a print_info() method that displays the course number and title.
Also define a derived class OfferedCourse with the additional attributes instructor_name, term, and class_time.
Ex: If the input is:
ECE287
Digital Systems Design
ECE387
Embedded Systems ... | [
"The thing is with the def __init__(self): method in the Course class. Here you are telling python that the class Course does not receive anything else than itself. If you want to be able to pass those arguments to init, but keep the default values, you can provide a default value inside init\ndef __init__(self, nu... | [
0,
0
] | [] | [] | [
"derived_class",
"inheritance",
"python"
] | stackoverflow_0074593913_derived_class_inheritance_python.txt |
Q:
Why does it say IndexError: list index out of range?
I am a python newbie. I am in the phase of testing my code but I am quite confused why sometimes this works and sometimes it does not. As per my understanding the random.randint(0,13) this means that random numbers from 0 to 12 which is the number of my cards li... | Why does it say IndexError: list index out of range? | I am a python newbie. I am in the phase of testing my code but I am quite confused why sometimes this works and sometimes it does not. As per my understanding the random.randint(0,13) this means that random numbers from 0 to 12 which is the number of my cards list.
Error im geting:
Traceback (most recent call last):
... | [
"Seems you have an incorrect assumption.\nA quick test gave me the following output:\n>>> from random import randint\n>>> randint(0,13)\n3\n>>> randint(0,13)\n1\n>>> randint(0,13)\n10\n>>> randint(0,13)\n2\n>>> randint(0,13)\n12\n>>> randint(0,13)\n12\n>>> randint(0,13)\n3\n>>> randint(0,13)\n12\n>>> randint(0,13)\... | [
0,
0,
0
] | [
"There are 12 elements in your list, you are trying to check for the 13th element when it should be computer_hand.append(cards[rand1 - 2]) since all indexes of elements start at 0. So there are actually 0,1,2,3,4,5,6,7,8,9,10,11 elements. Therefore, there should only be a maximum of index 11.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074593962_python.txt |
Q:
How can I play audio with playsound and type in an entry box at the same time in tkinter?
I want to type something in the user_text entry box while the play_audio function is running
I tried the following code:
from tkinter import *
from playsound import playsound
root = Tk()
def play_audio():
playsound('aud... | How can I play audio with playsound and type in an entry box at the same time in tkinter? | I want to type something in the user_text entry box while the play_audio function is running
I tried the following code:
from tkinter import *
from playsound import playsound
root = Tk()
def play_audio():
playsound('audio.mp3')
play_audio_button = Button(root, text='Play audio', command=play_audio)
user_text =... | [
"playsound can run sound in the background, you should use threads if you need to loop the sound or something more than just running a single sound file.\ndef play_audio():\n playsound('audio.mp3', block=False)\n\nif you want to loop the sound you don't need multiprocessing, the threading module is perfectly usa... | [
0
] | [] | [] | [
"multiprocessing",
"playsound",
"python",
"tkinter"
] | stackoverflow_0074593915_multiprocessing_playsound_python_tkinter.txt |
Q:
How to use Boto to self-terminate instance its running on?
I need to terminate an instance from an AutoScalingGroup as the policies ASG has are leaving the scaled out instances running longer than desired. I need to terminate said instance after its done running a python process.
The code already uses Boto to acce... | How to use Boto to self-terminate instance its running on? | I need to terminate an instance from an AutoScalingGroup as the policies ASG has are leaving the scaled out instances running longer than desired. I need to terminate said instance after its done running a python process.
The code already uses Boto to access other AWS services, so I'm looking to leverage Boto to self-t... | [
"An instance can be removed from an Auto Scaling Group by using detach_instances():\n\nRemoves one or more instances from the specified Auto Scaling group.\nAfter the instances are detached, you can manage them independent of the Auto Scaling group.\nIf you do not specify the option to decrement the desired capacit... | [
0,
0
] | [] | [] | [
"amazon_ec2",
"amazon_web_services",
"boto",
"python"
] | stackoverflow_0052749959_amazon_ec2_amazon_web_services_boto_python.txt |
Q:
PyTorch vectorized sum different from looped sum
I am using torch 1.7.1 and I noticed that vectorized sums are different from sums in a loop if the indices are repeated. For example:
import torch
indices = torch.LongTensor([0,1,2,1])
values = torch.FloatTensor([1,1,2,2])
result = torch.FloatTensor([0,0,0])
loope... | PyTorch vectorized sum different from looped sum | I am using torch 1.7.1 and I noticed that vectorized sums are different from sums in a loop if the indices are repeated. For example:
import torch
indices = torch.LongTensor([0,1,2,1])
values = torch.FloatTensor([1,1,2,2])
result = torch.FloatTensor([0,0,0])
looped_result = torch.zeros_like(result)
for i in range(in... | [
"The issue here is that you're indexing result multiple times at the same index, which is bound to fail for this inplace operation. Instead what you'd need to use is index_add or index_add_, e.g. (as a continuation of your snippet):\n>>> result_ia = torch.zeros_like(result)\n>>> result_ia.index_add_(0, indices, val... | [
1
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074593825_python_pytorch.txt |
Q:
NLTK download SSL: Certificate verify failed
I get the following error when trying to install Punkt for nltk:
nltk.download('punkt')
[nltk_data] Error loading Punkt: <urlopen error [SSL:
[nltk_data] CERTIFICATE_VERIFY_FAILED] certificate verify failed
[nltk_data] (_ssl.c:590)>
False
A:
TLDR: Here ... | NLTK download SSL: Certificate verify failed | I get the following error when trying to install Punkt for nltk:
nltk.download('punkt')
[nltk_data] Error loading Punkt: <urlopen error [SSL:
[nltk_data] CERTIFICATE_VERIFY_FAILED] certificate verify failed
[nltk_data] (_ssl.c:590)>
False
| [
"TLDR: Here is a better solution: https://github.com/gunthercox/ChatterBot/issues/930#issuecomment-322111087\nNote that when you run nltk.download(), a window will pop up and let you select which packages to download (Download is not automatically started right away).\nTo complement the accepted answer, the followi... | [
160,
59,
36,
27,
26,
7,
7,
4,
3,
2,
2,
1,
1,
0,
0
] | [
"For me, the solution was much simpler: I was still connected to my corporate network/VPN which blocks certain types of downloads. Switching the network made the SSL error disappear.\n"
] | [
-1
] | [
"nltk",
"python",
"ssl_certificate"
] | stackoverflow_0038916452_nltk_python_ssl_certificate.txt |
Q:
HTML wont work when I send a message with CKEditor
Right now I'm trying to send bulk messages in an app made with Python. Now, when I do it, the message that it's supposed to be formatted with HTML won't renderize.
emails = [c for c in view_contactos]
if add.validate_on_submit(): #validamos datos
subje... | HTML wont work when I send a message with CKEditor | Right now I'm trying to send bulk messages in an app made with Python. Now, when I do it, the message that it's supposed to be formatted with HTML won't renderize.
emails = [c for c in view_contactos]
if add.validate_on_submit(): #validamos datos
subject = add.title.data
body_message = add.body.data... | [
"In the line em.set_content(body_message) I had to write \", subtype=\"html\" after the body_message \nem.set_content(body_message, subtype=\"html\")\n"
] | [
0
] | [] | [] | [
"bulk_mail",
"email",
"flask",
"gmail",
"python"
] | stackoverflow_0074594039_bulk_mail_email_flask_gmail_python.txt |
Q:
Is there a way to use pylast to get the top tracks?
I need to use the pylast module and last.fm api to get the top tracks (https://www.last.fm/api/show/chart.getTopTracks) but I can't find how to do this in python.
API_KEY = "my key"
API_SECRET = "my secret"
network = pylast.LastFMNetwork(api_key = API_KEY)
prin... | Is there a way to use pylast to get the top tracks? | I need to use the pylast module and last.fm api to get the top tracks (https://www.last.fm/api/show/chart.getTopTracks) but I can't find how to do this in python.
API_KEY = "my key"
API_SECRET = "my secret"
network = pylast.LastFMNetwork(api_key = API_KEY)
print(network.chart_get_top_tracks())
But the chart_get_top_... | [
"You're looking for network.get_top_tracks(), not network.chart_get_top_tracks():\nimport pylast\n\nAPI_KEY = \"TODO\"\n\nnetwork = pylast.LastFMNetwork(api_key=API_KEY)\ntracks = network.get_top_tracks()\n\nfor track in tracks[:10]:\n print(track.item)\n\nOutputs:\nTaylor Swift - Anti-Hero\nDrake - Rich Flex\nT... | [
0
] | [] | [] | [
"api",
"last.fm",
"pylast",
"python",
"spotify"
] | stackoverflow_0074320861_api_last.fm_pylast_python_spotify.txt |
Q:
Error when using include('admin.site.urls'): Passing a 3-tuple to include() is not supported
I'm fairly new to Python and I am using a video tutorial on Lynda to help me build the frameworks for a Social WebApp. I'm trying to run the server from the cmd using python manage.py runserver from the cmd, however, I kee... | Error when using include('admin.site.urls'): Passing a 3-tuple to include() is not supported | I'm fairly new to Python and I am using a video tutorial on Lynda to help me build the frameworks for a Social WebApp. I'm trying to run the server from the cmd using python manage.py runserver from the cmd, however, I keep running into this error message.
CMD PROMPT ERROR
Traceback (most recent call last):
File "C:\U... | [
"In Django 2.0 you can no longer use include(admin.site.urls) (release notes). Just use admin.site.urls instead.\nfrom django.contrib import admin\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n ...\n]\n\n"
] | [
12
] | [
"As from Django version 2.0, the documentation clears this:\nWhen to use include()\nYou should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.\n",
"Including another URLconf :\n\nImport the include() function : from django.urls import include, path\nAdd a U... | [
-1,
-1
] | [
"django",
"django_2.0",
"python",
"valueerror"
] | stackoverflow_0048203313_django_django_2.0_python_valueerror.txt |
Q:
Problem with monthly data on yfinance for Python
I am having a problem downloading monthly data for any ticker (or list of tickers). The dates in the index of the result show more than just the beginning of the month.
Example :
import yfinance as yf
y_params = {
'tickers': 'AAPL',
'start': '2020-01-01',
... | Problem with monthly data on yfinance for Python | I am having a problem downloading monthly data for any ticker (or list of tickers). The dates in the index of the result show more than just the beginning of the month.
Example :
import yfinance as yf
y_params = {
'tickers': 'AAPL',
'start': '2020-01-01',
'end': '2022-11-01',
'interval': '1mo'
}
data = ... | [
"Yahoo Finance generate a special record each time there is a split or a dividend payment.\nIn your data, we see a NaN every 3 months. That's a dividend entry. Other NaN are probably splits.\nYou can't see the amounts because you only look at one column ('Adj Close').\nI can't provide more details because last time... | [
0,
0
] | [] | [] | [
"python",
"yfinance"
] | stackoverflow_0074586281_python_yfinance.txt |
Q:
How to solve Local path is not registered within uploads in the request in PyCharm 2022.2.1 (Professional Edition)?
I want to set up a Django project with docker-compose and PyCharm on my PC with Ubuntu 22.04 OS. Using PyCharm 2022.2.1 (Professional) I get the following error
How to solve Local path is not regi... | How to solve Local path is not registered within uploads in the request in PyCharm 2022.2.1 (Professional Edition)? | I want to set up a Django project with docker-compose and PyCharm on my PC with Ubuntu 22.04 OS. Using PyCharm 2022.2.1 (Professional) I get the following error
How to solve Local path is not registered within uploads in the request
I added a Python interpreter from Settings > project > Python interpreter and then a... | [
"This bug was reported as PY-55396 on the JetBrains bug tracker.\nThe bug was solved in PyCharm 2022.2.2, the solution is to upgrade to that version or downgrade to PyCharm 2021.3.\n"
] | [
1
] | [] | [] | [
"django",
"docker_compose",
"interpreter",
"pycharm",
"python"
] | stackoverflow_0074221022_django_docker_compose_interpreter_pycharm_python.txt |
Q:
Transpose Columns in Python
Let´s say I have the following table:
Produced by the following python Code
import pandas as pd
data = [["Car","Sport","Wheel", 4],
["Car", "Sport","engine HP", 65],
["Car", "Sport","windows", 5],
["Car","Van","Wheel", 4],
["Car", "Van","engine HP",... | Transpose Columns in Python | Let´s say I have the following table:
Produced by the following python Code
import pandas as pd
data = [["Car","Sport","Wheel", 4],
["Car", "Sport","engine HP", 65],
["Car", "Sport","windows", 5],
["Car","Van","Wheel", 4],
["Car", "Van","engine HP", 85],
["Car", "Van","win... | [
"You can try the built-in transpose method provided by pandas.\nYou can have a look about pandas.DataFrame.transpose\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074594043_pandas_python.txt |
Q:
Python Find columns of second dataframe with matching index to first datframe
I have two dataframes.
Input data
# First df mainly consists data provided by the user
fdf = pd.DataFrame(columns=['user_data'],data=[10,14,1],index=['alpha','beta','gamma'])
user_data
alpha 10
beta 14
gamma 1
# Second... | Python Find columns of second dataframe with matching index to first datframe | I have two dataframes.
Input data
# First df mainly consists data provided by the user
fdf = pd.DataFrame(columns=['user_data'],data=[10,14,1],index=['alpha','beta','gamma'])
user_data
alpha 10
beta 14
gamma 1
# Second df is basically a default data consisting kind of analysis I can run based on the ... | [
"Get the indices provided by the use from your second table. Then subset the columns where all the arguments are equal to 1.\nsdf.loc[fdf.index].eq(1).all(0).loc[lambda x:x].index\n\nIndex(['ABG_analysis'], dtype='object')\n\n",
"Assuming you want to identify the analyses for which no required data is missing. Yo... | [
1,
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074594034_dataframe_numpy_pandas_python.txt |
Q:
Is it possible to get the bounding boxes for each word with Python?
I know that
pdftotext -bbox foobar.pdf
creates a HTML file which contains content like
<word xMin="301.703800" yMin="104.483700" xMax="309.697000" yMax="115.283700">is</word>
<word xMin="313.046200" yMin="104.483700" xMax="318.374200" yMax="115.2... | Is it possible to get the bounding boxes for each word with Python? | I know that
pdftotext -bbox foobar.pdf
creates a HTML file which contains content like
<word xMin="301.703800" yMin="104.483700" xMax="309.697000" yMax="115.283700">is</word>
<word xMin="313.046200" yMin="104.483700" xMax="318.374200" yMax="115.283700">a</word>
<word xMin="321.603400" yMin="104.483700" xMax="365.50900... | [
"disclaimer: I am the author of borb, the package used in this answer.\nYou will need to do some kind of processing in order to get bounding boxes on a word-level. The problem is that a PDF (worst case scenario) only contains rendering instructions, and not structure-information.\nPut simply, your PDF might contain... | [
1
] | [] | [] | [
"pdf",
"python"
] | stackoverflow_0045082427_pdf_python.txt |
Q:
Tkinter Entry.insert() changes type from int to str
I need to do a simple gui for accepting user input for further processing. It's my first time when I'm using tkinter and I've encountered a strange problem. Namely Entry.insert() changes type from int to str. Moreover first it was working alright, but then I was ... | Tkinter Entry.insert() changes type from int to str | I need to do a simple gui for accepting user input for further processing. It's my first time when I'm using tkinter and I've encountered a strange problem. Namely Entry.insert() changes type from int to str. Moreover first it was working alright, but then I was trying to implement something and I did couple of strong ... | [
"\nNamely Entry.insert() changes type from int to str... it's type is changed from int to str. I have no idea why it is happening.\n\nYes, this is how the Entry widget has always worked. The get method always returns a string, and the insert method converts all non-string arguments into strings before inserting the... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074594124_python_tkinter.txt |
Q:
Upload any file type to S3 using Lambda
I'm trying to upload files to S3 using API Gateway and Lambda, all the processes work fine until I arrive at the Lambda, my lambda looks like this:
import base64
import boto3
import os
s3_client = boto3.client('s3')
bucket_name = os.environ['S3_BUCKET_NAME']
def lambda_han... | Upload any file type to S3 using Lambda | I'm trying to upload files to S3 using API Gateway and Lambda, all the processes work fine until I arrive at the Lambda, my lambda looks like this:
import base64
import boto3
import os
s3_client = boto3.client('s3')
bucket_name = os.environ['S3_BUCKET_NAME']
def lambda_handler(event, context):
contend_decode = b... | [
"The Error And A Bunch Of Computer Science\nSo I still think that John Rotenstein's answer is objectively correct, ie the problem is that you can't decode event['body'] into bytes, because its a string in the form of bytes that have non-ascii characters, and that's why it is throwing an error.\nIf you look at event... | [
3,
1
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"aws_lambda",
"python"
] | stackoverflow_0074592604_amazon_s3_amazon_web_services_aws_lambda_python.txt |
Q:
How to get the relative position of a tkinter canvas after it got scaled and dragged around?
The canvas c is the basis of a kind of CAD modelling software I'm working on. The methods for transforming it work (bound to mouse button 2).
In another function I want to add/edit items on the canvas so I need the new rel... | How to get the relative position of a tkinter canvas after it got scaled and dragged around? | The canvas c is the basis of a kind of CAD modelling software I'm working on. The methods for transforming it work (bound to mouse button 2).
In another function I want to add/edit items on the canvas so I need the new relative position to the canvas.
Context:
That should be (0,0) in the end:
enter image description he... | [
"In a comment you wrote:\n\nTo clarify my end goal more: I want to add an object to the model (on the grid) where the mouse pointer is.\n\nTo do that you need to pass the x/y coordinate from the event through the canvasx and canvasy methods.\nFor example, if you want to draw a circle under the mouse pointer when yo... | [
0
] | [] | [] | [
"python",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0074592864_python_tkinter_tkinter_canvas.txt |
Q:
Find, delete and add text into pdf file in Python
I have a pdf file, it is necessary to delete certain text in it. Then add new text below to the existing one.
I'm trying to use the PyMuPDF library - fitz. Open the file, set the text to search, but I did not find how to delete it and add new text.
Please could you... | Find, delete and add text into pdf file in Python | I have a pdf file, it is necessary to delete certain text in it. Then add new text below to the existing one.
I'm trying to use the PyMuPDF library - fitz. Open the file, set the text to search, but I did not find how to delete it and add new text.
Please could you help me how to delete the found text and add to the ex... | [
"The library doesn't officially support adding/deleting text of a pdf document. However, from a recorded issue there is a workaround this. You can see the answer here from the author of the library on how you can get around this using a Text Modification method.\nIt also worries me that the documentation for the li... | [
0,
0
] | [] | [] | [
"pdf",
"python",
"python_3.x"
] | stackoverflow_0062793843_pdf_python_python_3.x.txt |
Q:
How to count the number of list elements embedded in a datafrane column?
I have a dataframe that looks like the below (inclusive of the brackets and quotes):
ID
Interests
2131
['music','art','travel']
3213
[]
3132
['martial arts']
3232
['martial arts']
The desired output I am trying to get is:
ID
Interests
... | How to count the number of list elements embedded in a datafrane column? | I have a dataframe that looks like the below (inclusive of the brackets and quotes):
ID
Interests
2131
['music','art','travel']
3213
[]
3132
['martial arts']
3232
['martial arts']
The desired output I am trying to get is:
ID
Interests
2131
3
3213
0
3132
1
3232
1
I've tried using
from... | [
"If you have lists (['music','art','travel']):\ndf['Interests'] = df['Interests'].str.len()\n\nIf you have strings (\"['music','art','travel']\"):\nfrom ast import literal_eval\n\ndf['Interests'] = df['Interests'].apply(literal_eval).str.len()\n\nOr, if you know that there are no quoted commas:\ndf['Interests'] = d... | [
2,
0
] | [] | [] | [
"dataframe",
"list",
"numpy",
"pandas",
"python"
] | stackoverflow_0074594185_dataframe_list_numpy_pandas_python.txt |
Q:
Nonzero for integers
My problem is as follows. I am generating a random bitstring of size n, and need to iterate over the indices for which the random bit is 1. For example, if my random bitstring ends up being 00101, I want to retrieve [2, 4] (on which I will iterate over). The goal is to do so in the fastest way... | Nonzero for integers | My problem is as follows. I am generating a random bitstring of size n, and need to iterate over the indices for which the random bit is 1. For example, if my random bitstring ends up being 00101, I want to retrieve [2, 4] (on which I will iterate over). The goal is to do so in the fastest way possible with Python/NumP... | [
"A minor optimisation to your code would be to use the new style random interface and generate bools rather than 64bit integers\nrng = np.random.default_rng()\n\ndef original(n):\n bitstring = rng.integers(2, size=n, dtype=bool)\n return np.nonzero(bitstring)[0]\n\nthis causes it to take ~24 µs on my laptop, ... | [
1,
1,
1,
0
] | [] | [] | [
"bitstring",
"numpy",
"python",
"random"
] | stackoverflow_0074557590_bitstring_numpy_python_random.txt |
Q:
How to read a CSV file in Pandas with quote characters?
I have a csv file dataset that looks like this:
dataset header
Date,"TTF_1M_15m","Own Trades (Sell)","Own Trades (Buy)"
2022-01-03 09:00:00,"68.54485294117647","",""
2022-01-03 09:15:00,"66.46498579545455","",""
2022-01-03 09:30:00,"69.53991935483872","",""
.... | How to read a CSV file in Pandas with quote characters? | I have a csv file dataset that looks like this:
dataset header
Date,"TTF_1M_15m","Own Trades (Sell)","Own Trades (Buy)"
2022-01-03 09:00:00,"68.54485294117647","",""
2022-01-03 09:15:00,"66.46498579545455","",""
2022-01-03 09:30:00,"69.53991935483872","",""
.......
I'm having trouble reading this into pandas due to th... | [
"You can try using,\ndf = pd.read_csv('APE_Data_Export_15min_2022.csv', sep=',', engine='python').replace('\"','', regex=True)\n\nOutput:\n\nOUTPUT with actual data:\n\n"
] | [
0
] | [] | [] | [
"csv",
"export_to_csv",
"pandas",
"python"
] | stackoverflow_0074594243_csv_export_to_csv_pandas_python.txt |
Q:
Docker image url validation for django
I want to get docker image URL from the user but URLs can't be acceptable with models.URLField() in django.For example, this URL: hub.something.com/nginx:1.21, got an error.How can fix it?
A:
Try this out:
from django.core.validators import URLValidator
from django.utils.de... | Docker image url validation for django | I want to get docker image URL from the user but URLs can't be acceptable with models.URLField() in django.For example, this URL: hub.something.com/nginx:1.21, got an error.How can fix it?
| [
"Try this out:\nfrom django.core.validators import URLValidator\nfrom django.utils.deconstruct import deconstructible\nfrom django.db import models\n\n# I suggest to move this class to validators.py outside of this app folder \n# so it can be easily accessible by all models\n@deconstructible\nclass DockerHubURLVali... | [
2,
0
] | [] | [] | [
"django",
"docker",
"docker_image",
"python",
"url"
] | stackoverflow_0074593617_django_docker_docker_image_python_url.txt |
Q:
Quotation Marks in Python while Reading a CSV File
I am a total newbie in Python I must admit. I have a CSV file and now I have to write the values in a specific column in a sorted list, there are same values that repeats itself I also need to get rid of those.
So I have a column called reason and the index is as ... | Quotation Marks in Python while Reading a CSV File | I am a total newbie in Python I must admit. I have a CSV file and now I have to write the values in a specific column in a sorted list, there are same values that repeats itself I also need to get rid of those.
So I have a column called reason and the index is as follows;
allow, school, 'business', education, school et... | [
"The sort order is not what we desire.\n\nbecause business has already ‘\n\nTo solve, simply edit the .CSV file, removing unwanted punctuation.\n"
] | [
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074594329_csv_pandas_python.txt |
Q:
Print out the index of the value that satisfy the list's condition
I am having trouble figuring out how to come up with the correct code for this particular problem that involving list. So the question is:
We have n fruit baskets, with some apples and oranges in them. We want to select the basket that have the mos... | Print out the index of the value that satisfy the list's condition | I am having trouble figuring out how to come up with the correct code for this particular problem that involving list. So the question is:
We have n fruit baskets, with some apples and oranges in them. We want to select the basket that have the most apples, but if there are several baskets with the same amount (biggest... | [
"Your problem is in this section:\n if a[num] == app:\n if b[num] < oran:\n idx = a.index(a[num])\n elif b[num] == oran:\n idx = b.index(oran)\n\nWhen you find the max number of ranges with if b[num] == oran, you set idx to the index of the first occurance of oran in b, not nu... | [
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074594143_list_python.txt |
Q:
Breaking items in a list into lists in Python3
I'm trying to make something that goes over my folders and find duplicates. That said, files cant have identical names, so the first part I made is to go over the folder and append a list of folders. Then I want to break the items in the list into lists and compare ea... | Breaking items in a list into lists in Python3 | I'm trying to make something that goes over my folders and find duplicates. That said, files cant have identical names, so the first part I made is to go over the folder and append a list of folders. Then I want to break the items in the list into lists and compare each other and find high similarities. I'm quite stuck... | [
"First of all, I would recommend you to use the library pathlib, since os is a bit outdated for file exploring.\nHere's how you can do what you want:\nfrom pathlib import Path\n\nfolder_path = Path(input(\"Where you want to look?\"))\nfolder_content = [file_or_dir for file_or_dir in folder_path.iterdir() if file_or... | [
0
] | [] | [] | [
"dictionary",
"list",
"python",
"python_3.x"
] | stackoverflow_0074594331_dictionary_list_python_python_3.x.txt |
Q:
Applying Jaro-Winkler distance to two dataframes
I have two dataframes of unequal length and would like to compare the similarity of strings in df2 with df1. Is it possible to apply Jaro-Winkler distance method to calculate the string similarity on two dataframes through map/lambda function.
df1
Behavioral disorde... | Applying Jaro-Winkler distance to two dataframes | I have two dataframes of unequal length and would like to compare the similarity of strings in df2 with df1. Is it possible to apply Jaro-Winkler distance method to calculate the string similarity on two dataframes through map/lambda function.
df1
Behavioral disorders
Behçet disease
AV-Block
df2
Behavioral disorder
Be... | [
"Assuming you want the max score and that the original columns in the input are \"name\":\n# pip install jaro-winkler\n# https://pypi.org/project/jaro-winkler/\nfrom jaro import jaro_winkler_metric as jw\n\npd.DataFrame([[n2, *max([(n1, jw(n1, n2)) for n1 in df1['name']],\n lambda x: x[1])]\n... | [
0
] | [] | [] | [
"jaro_winkler",
"pandas",
"python"
] | stackoverflow_0074594265_jaro_winkler_pandas_python.txt |
Q:
no output in vs code using python logging module
I'm on Windows 10 using VS Code 1.73.1 and am retrofitting my program with the Python logging module. My program is generally functioning. The main thing I did is change all the print statements to logger.debug and I know the variable formatting needs to be changed ... | no output in vs code using python logging module | I'm on Windows 10 using VS Code 1.73.1 and am retrofitting my program with the Python logging module. My program is generally functioning. The main thing I did is change all the print statements to logger.debug and I know the variable formatting needs to be changed from {} to %s. I also added the encoding flag to my fi... | [
"After using a different logger example, I realized the problem was the Level setting in the first example I used had \"INFO\" and not \"DEBUG\" so nothing was showing up. Oops...\nimport logging\n\nlogger = logging.getLogger('simple_example')\nlogger.setLevel(logging.DEBUG)\nconsole = logging.StreamHandler()\ncons... | [
0
] | [] | [] | [
"logging",
"python",
"python_logging",
"visual_studio_code"
] | stackoverflow_0074585126_logging_python_python_logging_visual_studio_code.txt |
Q:
Python: OCR - For loop is very slow
I have here some lines of code from the beginning of my OCR program. I can see with the Time() function that these few lines take 90% of the time of a run. Unfortunately, I have no more idea how to develop these lines more efficiently in terms of time. What would be your approac... | Python: OCR - For loop is very slow | I have here some lines of code from the beginning of my OCR program. I can see with the Time() function that these few lines take 90% of the time of a run. Unfortunately, I have no more idea how to develop these lines more efficiently in terms of time. What would be your approaches to speed up this process?
for page_nu... | [
"You're saying that .image_to_string() consumes most of the CPU cycles.\nYup. That's not surprising, it's a hard problem we're asking it to solve.\nDelve into what that function is doing,\nif you want to shave off some seconds of CPU time.\nBut you're probably better off consulting the fine documentation.\nDependin... | [
0
] | [] | [] | [
"ocr",
"python",
"python_tesseract"
] | stackoverflow_0074594275_ocr_python_python_tesseract.txt |
Q:
How can I use fillna for a specific value?
I already know how to use fillna() but it fills every empty value with the same indicated value. In this case, I want to fill each empty value with different values, should I use the row number or how can it be done?
Failed try:
I want it to be
bmw 320i 2
... | How can I use fillna for a specific value? | I already know how to use fillna() but it fills every empty value with the same indicated value. In this case, I want to fill each empty value with different values, should I use the row number or how can it be done?
Failed try:
I want it to be
bmw 320i 2
plymouth reliant 1
honda civic ... | [
"Since the condition is not mentioned, the best solution I can provide is to use mask.\nIt replaces values where the condition is True.\n",
"\nI want it to be bmw 320i 2 plymouth reliant 1 honda civic 3\n\nYou can fill the NaN in the first column with values from a series like this:\ndf = pd.DataFrame([[np.nan, \... | [
0,
0
] | [] | [] | [
"categories",
"fillna",
"function",
"pandas",
"python"
] | stackoverflow_0074594059_categories_fillna_function_pandas_python.txt |
Q:
How do I get a value based of the combinations of check buttons that are checked in tkinter?
I am making an application that creates a password based on the requirements of the password needed. The requirements are picked through check buttons, so if a check button is on, then the password should contain those val... | How do I get a value based of the combinations of check buttons that are checked in tkinter? | I am making an application that creates a password based on the requirements of the password needed. The requirements are picked through check buttons, so if a check button is on, then the password should contain those values, if the check button is off then the password should not contain that value. All of the check ... | [
"Here's a general idea, in pseudocode that you can modify. The general idea is to use the value of the checkboxes to make a \"pool\" of characters to choose from inside your generation function.\n\nget the value of the checkboxes and assign them to obviously named variables.\n\nIf no checkboxes are present, do som... | [
0,
0
] | [] | [] | [
"if_statement",
"python",
"python_3.x",
"tkinter",
"tkinter_button"
] | stackoverflow_0074594081_if_statement_python_python_3.x_tkinter_tkinter_button.txt |
Q:
Matplotlib conditional scatterplot colors
I'm trying to change the colors of the points in a scatterplot to red based on the condition x > 0. Here's what I have:
x = np.random.rand(100,1)
y = np.random.rand(100,1)
plt.scatter(x, y, c=['r' if x > 0 else 'b' for v in x])
I get the following error:
ValueError: The ... | Matplotlib conditional scatterplot colors | I'm trying to change the colors of the points in a scatterplot to red based on the condition x > 0. Here's what I have:
x = np.random.rand(100,1)
y = np.random.rand(100,1)
plt.scatter(x, y, c=['r' if x > 0 else 'b' for v in x])
I get the following error:
ValueError: The truth value of an array with more than one elem... | [
"There is a mistake in the comprehesion list in the first code block. Try the following:\nplt.scatter(x, y, c=['r' if v > 0 else 'b' for v in x])\n\nHowever, you will see all the values in red as the function np.random.rand() returns positive values (between 0 and 1). To confirm that it is working you can use this ... | [
1
] | [] | [] | [
"matplotlib",
"python",
"scatter_plot"
] | stackoverflow_0074594484_matplotlib_python_scatter_plot.txt |
Q:
How to fix errors that involve Selenium
I am trying to make a Facebook marketplace scraper. I am using Microsoft Edge and every time I run the code, it gives me a few errors that I do not know how to fix. This is all I have so far, and it is supposed to print the year of a car and the name of it.
Ex: 2009 Honda Ac... | How to fix errors that involve Selenium | I am trying to make a Facebook marketplace scraper. I am using Microsoft Edge and every time I run the code, it gives me a few errors that I do not know how to fix. This is all I have so far, and it is supposed to print the year of a car and the name of it.
Ex: 2009 Honda Accord
from selenium import webdriver
from sele... | [
"It tells you what the error is:\n\nselenium.common.exceptions.NoSuchElementException: Message: no such\nelement: Unable to locate element: {\"method\":\"css\nselector\",\"selector\":\".x1i10hfl xjbqb8w x6umtig x1b1mbwd xaqea5y\nxav7gou x9f619 x1ypdohk xt0psk2 xe8uvvx xdj266r x11i5rnm xat24cr\nx1mh8g0r xexx8yu x4ua... | [
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074594496_python_selenium_web_scraping.txt |
Q:
Logging printout of an executed python file within another file and printing out the result in terminal simultaneously
I have two Python files (main.py and main_test.py). The file main_test.py is executed within main.py. When I do not use a log file this is what gets printed out:
Main file: 17:41:18
Executed file:... | Logging printout of an executed python file within another file and printing out the result in terminal simultaneously | I have two Python files (main.py and main_test.py). The file main_test.py is executed within main.py. When I do not use a log file this is what gets printed out:
Main file: 17:41:18
Executed file: 17:41:18
Executed file: 17:41:19
Executed file: 17:41:20
When I use a log file and execute main.py>log, then I get the fol... | [] | [] | [
"When you run a script like this:\npython main.py>log\n\nThe shell redirects output from the script to a file called log. However, if the script launches other scripts in their own subshell (which is what os.system() does), the output of that does not get captured.\nWhat is surprising about your example is that you... | [
-1
] | [
"python"
] | stackoverflow_0074594425_python.txt |
Q:
Saving a dataframe after for loop
I run for loop on a dataframe. like below
for row in df["findings"]:
GPT2_model = TransformerSummarizer(transformer_type="GPT2",transformer_model_key="gpt2-medium")
full = ''.join(GPT2_model(row, min_length=60))
In this loop I extract one row at a time and then the GPT2_mo... | Saving a dataframe after for loop | I run for loop on a dataframe. like below
for row in df["findings"]:
GPT2_model = TransformerSummarizer(transformer_type="GPT2",transformer_model_key="gpt2-medium")
full = ''.join(GPT2_model(row, min_length=60))
In this loop I extract one row at a time and then the GPT2_model model process and returns that row.... | [
"Try not using a for loop, cause the advantage of using pandas is exactly to avoid the for loops\nin your place I would try :\nGPT2_model = TransformerSummarizer(transformer_type=\"GPT2\",transformer_model_key=\"gpt2-medium\")\ndf[\"new_column\"] = ''.join((df[\"findings\"].apply(GPT2_model), min_length=60)) \n\n"
... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074591640_pandas_python.txt |
Q:
Python Programming: syntax error question
Im completing a python course for school and found the following code. Ive submitted the code, btw I am a finance major very limited knowledge on coding, and I consitently get an error I do not understand.enter image description here
In []:
tuition_increase = 0.03
tuition ... | Python Programming: syntax error question | Im completing a python course for school and found the following code. Ive submitted the code, btw I am a finance major very limited knowledge on coding, and I consitently get an error I do not understand.enter image description here
In []:
tuition_increase = 0.03
tuition = 8000
years = 5
print('{:10}{}'.format('tuitio... | [
"It should work perfectly fine, if you remove the first line of code.\n"
] | [
0
] | [] | [] | [
"error_handling",
"python",
"syntax"
] | stackoverflow_0074594578_error_handling_python_syntax.txt |
Q:
Pandas Rows MODE, AVERAGE Python
I have a pandas dataframe with a list of products in rows, and the columns are the sales of current month, current month - 1, current month -2 and current month - 3
for all rows I want to add a new column with MODE(most frequent number in row), average, and number off months with ... | Pandas Rows MODE, AVERAGE Python | I have a pandas dataframe with a list of products in rows, and the columns are the sales of current month, current month - 1, current month -2 and current month - 3
for all rows I want to add a new column with MODE(most frequent number in row), average, and number off months with sales more than zero and get something... | [
"Here is a solution on a toy pandas.DataFrame, albeit there might be some codes that are more efficient.\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame({'MES-1':[1,2,3,4],'MES-2':[2,2,3,-2],'MES-3':[-1,2,-3,-1]})\n\nmodes, sup0, avg = [],[],[]\nfor line in range(df.shape[0]):\n series = pd.Series(... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"statistics"
] | stackoverflow_0074594511_dataframe_pandas_python_statistics.txt |
Q:
Why when I try to search for a product, nothing comes up?
I've created an ecommerce website using Django, though the search results aren't coming up when I try to search for a product. For example, when I try to search for part of a product title, like throat spray, nothing comes up even though there is a throat s... | Why when I try to search for a product, nothing comes up? | I've created an ecommerce website using Django, though the search results aren't coming up when I try to search for a product. For example, when I try to search for part of a product title, like throat spray, nothing comes up even though there is a throat spray in the database.
I tried using the Post and Get methods th... | [
"You're passing a variable named product to the template...\nreturn render(request, 'epharmacyweb/search.html', {'searched': searched, 'product': products})\n\n... but then the template tries to access a variable named products.\n{% for product in products %}\n\nYou have a variable name mismatch. Change 'product':... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074594528_django_python.txt |
Q:
How can I get the most common headers at this moment?
I am using the Python requests library to scrape, but I am pasting headers in the code:
headers_list = [
{'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'},
{'... | How can I get the most common headers at this moment? | I am using the Python requests library to scrape, but I am pasting headers in the code:
headers_list = [
{'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'},
{'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:1... | [
"You could use the browser inspection. With that you could have a complete details of request, not only the headers\nYou only need to open the web in your favorite browser, inspect it, in network tab choose one of the first request and right click and get what you need from the request\n\n\nAdvice\nSometimes the he... | [
0
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074586905_python_web_scraping.txt |
Q:
how do i use list comprehensions to print a list of all possible dimensions of a cuboid in python?
You are given three integers x,y and z representing the dimensions of a cuboid along with an integer n. Print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum of i+j+k is not equal to n... | how do i use list comprehensions to print a list of all possible dimensions of a cuboid in python? | You are given three integers x,y and z representing the dimensions of a cuboid along with an integer n. Print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum of i+j+k is not equal to n. Here,0<=i<=x; 0<=j<=y;0<=k<=z. Please use list comprehensions rather than multiple loops, as a learnin... | [
"Try it online!\nx, y, z, n = 2, 3, 4, 5\nprint([(i, j, k) for i in range(x + 1) for j in range(y + 1)\n for k in range(z + 1) if i + j + k != n])\n\nOutput:\n[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 4), (0, 3, 0),... | [
1,
0,
0,
0
] | [
"if name == 'main':\nx=int(input())\ny=int(input())\nz=int(input())\nn=int(input())\nans[]\nfor i in range(x+1):\n for j in range(y+1):\n for k in range(z+1):\n\n\n if(i+j+k)!=n:\n ans.append([i,j,k])\n\nprint(ans)\n\n"
] | [
-1
] | [
"list",
"python"
] | stackoverflow_0070055982_list_python.txt |
Q:
Selenium - How to open a browser with the driver once it's been closed
I have a Start button which once pressed, will navigate to a URL. The button then turns into a Stop button which will close the browser. Once the Stop button is pressed, it turns back into a Start button which I want to open the browser again. ... | Selenium - How to open a browser with the driver once it's been closed | I have a Start button which once pressed, will navigate to a URL. The button then turns into a Stop button which will close the browser. Once the Stop button is pressed, it turns back into a Start button which I want to open the browser again. The problem is that I'm getting the error once the driver has been closed an... | [
"So after changing the driver into an array of drivers, I also had to change driver[instance].close() to driver[instance].quit() and it stopped freezing!\nThank you for the suggestion @AbiSaran!\n"
] | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074577902_python_selenium.txt |
Q:
How to insert image in HTML in python script?
I am writing a htmlfunction in python as below:
def html(function):
htmlfile = open(function.name+".html", "w")
htmlfile.write("<html>\n")
# statement for title
# statement for header
htmlfile.write('<img src = '+function.name+'.png alt ="cfg">\n') ... | How to insert image in HTML in python script? | I am writing a htmlfunction in python as below:
def html(function):
htmlfile = open(function.name+".html", "w")
htmlfile.write("<html>\n")
# statement for title
# statement for header
htmlfile.write('<img src = '+function.name+'.png alt ="cfg">\n')
htmlfile.write("</html>\n")
htmlfile.close... | [
"You can implement it as below:\nfrom robot.api import logger\n\nimg = \"example.jpg\"\nstrImg = '\"{}\"'.format(img)\n\nimg_tag = \"<img src=\" + strImg + \">\"\nlogger.info(img_tag, html=True)\n\n",
"Try this. I think this works. The image does get inserted to HTML.\ndef html(function):\n htmlfile = open(fun... | [
2,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0031194637_html_python.txt |
Q:
How can I get rid of the lxml download error?
Then i download lxml with command pip install lxml in visual studio code i get this mistake:
Collecting lxml
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Installing collected packages: lxml
DEPRECATION: lxml is being installed us... | How can I get rid of the lxml download error? | Then i download lxml with command pip install lxml in visual studio code i get this mistake:
Collecting lxml
Using cached lxml-4.9.1.tar.gz (3.4 MB)
Preparing metadata (setup.py) ... done
Installing collected packages: lxml
DEPRECATION: lxml is being installed using the legacy 'setup.py install' method, because i... | [
"Did you see this part of the error message:\nerror: Microsoft Visual C++ 14.0 or greater is required. Get it with \"Microsoft C++ Build Tools\": https://visualstudio.microsoft.com/visual-cpp-build-tools/\n\nYou need the Visual C++ compiler to build this package on your computer.\n"
] | [
1
] | [] | [] | [
"lxml",
"python",
"python_3.x"
] | stackoverflow_0074594649_lxml_python_python_3.x.txt |
Q:
Cannot install Python secrets package
I have few dependencies in a project listed in the requirements.txt file,
requests==2.18.4
secrets==1.0.2
PyYAML==3.12
I wanted to installed them and called the command inside the virtualenv,
$ pip install -r bin/requirements.txt
I get the message provided below,
Collecti... | Cannot install Python secrets package | I have few dependencies in a project listed in the requirements.txt file,
requests==2.18.4
secrets==1.0.2
PyYAML==3.12
I wanted to installed them and called the command inside the virtualenv,
$ pip install -r bin/requirements.txt
I get the message provided below,
Collecting requests==2.18.4 (from -r bin/requiremen... | [
"While there is a secrets package, it’s very old (2012), has only one release, a broken website, and no info. It doesn’t appear to install on Python 2.7 or 3.7.\nYou may instead be trying to use the secrets standard library that’s built-in to Python 3.6+. It’s not a package, so you don’t need to install it or add i... | [
6,
1,
0,
0
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0054966977_python_virtualenv.txt |
Q:
How to make a function that changes initialized coordinates
I'm struggling with making a function that changes the value of the coordinates if the parameters appropriate.
That's what I made:
class Move:
def __init__(self, x, y):
self.x = x
self.y = y
move = Move(5, 5)
def obstacle(axis, value... | How to make a function that changes initialized coordinates | I'm struggling with making a function that changes the value of the coordinates if the parameters appropriate.
That's what I made:
class Move:
def __init__(self, x, y):
self.x = x
self.y = y
move = Move(5, 5)
def obstacle(axis, value, plus):
if plus is True:
if axis == value:
... | [
"What the program is currently doing is running obstacle(), going inside the \"if plus is false\" block and changing the axis value from 5 to 4, and that's it.\nTo print: x=4, y=5 you can:\n\nInstead of the axis value change the move.x value\nOr print the axis value instead of move.x\n\n",
"Here is the code rewri... | [
0,
0,
0
] | [] | [] | [
"class",
"constructor",
"coordinates",
"function",
"python"
] | stackoverflow_0074594613_class_constructor_coordinates_function_python.txt |
Q:
With list of tuples corresponding to a list of int values, create list corresponding to sum of each value in the list (python)
I have a huge list of sublists, each sublist consisting of a tuple and a list of 4 integers.
I want to create a list of unique tuples that adds each integer values of the list (keeping the... | With list of tuples corresponding to a list of int values, create list corresponding to sum of each value in the list (python) | I have a huge list of sublists, each sublist consisting of a tuple and a list of 4 integers.
I want to create a list of unique tuples that adds each integer values of the list (keeping the four integers in the list separate).
Short Example:
[[(30, 40), [4, 7, 7, 1]],[(30, 40), [2, 9, 3, 4]],[(30, 40), [6, 5, 10, 0]],[(... | [
"You can create a dictionary where keys are the first tuples and values are lists of sublists. In second step sum the values at each index:\nlst = [\n [(30, 40), [4, 7, 7, 1]],\n [(30, 40), [2, 9, 3, 4]],\n [(30, 40), [6, 5, 10, 0]],\n [(20, 40), [4, 0, 4, 0]],\n [(20, 40), [3, 4, 14, 5]],\n [(20,... | [
1,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"tuples",
"unique"
] | stackoverflow_0074594645_dictionary_list_python_tuples_unique.txt |
Q:
How can I better check for a pair using a data set of card numbers and their suits?
I have recently taken it upon my self to create a program that plays DJ Wild the poker game. I haven't ran into many bumps but I am not very familiar with time complexity which I know that many programs can run into. This is making... | How can I better check for a pair using a data set of card numbers and their suits? | I have recently taken it upon my self to create a program that plays DJ Wild the poker game. I haven't ran into many bumps but I am not very familiar with time complexity which I know that many programs can run into. This is making me cautious about how many and how long my if statements are. Thus a question occurred, ... | [
"\ninitialize boolean to false\nloop the hands0 array\ncheck value of array\nif its true set your boolean to true and break your for loop\nthen you can check against your boolean\n\n"
] | [
0
] | [] | [] | [
"if_statement",
"python",
"simplify",
"time_complexity"
] | stackoverflow_0074594730_if_statement_python_simplify_time_complexity.txt |
Q:
How to add a surcharge to fine calculator in Python?
I am trying to create a fine amount calculator, but I don't know how to add a surcharge to the calculations.
For each fine amount in the code, I need to add a victims surcharge that varies depending on fine amount. If the fine amount is between $0 and $99 surcha... | How to add a surcharge to fine calculator in Python? | I am trying to create a fine amount calculator, but I don't know how to add a surcharge to the calculations.
For each fine amount in the code, I need to add a victims surcharge that varies depending on fine amount. If the fine amount is between $0 and $99 surcharge is $40, between $100 and $200 surcharge is $50, $201 a... | [
"You can add a function to do that based on the fine value:\ndef ask_limit():\n limit = float(input (\"What was the speed limit? \"))\n return limit\n\ndef ask_speed():\n speed = float(input (\"What was your clocked speed? \"))\n return speed\n\ndef findfine(speed, limit):\n if speed > 35 + limit :\n... | [
0
] | [] | [] | [
"function",
"if_statement",
"python",
"python_3.x"
] | stackoverflow_0074594737_function_if_statement_python_python_3.x.txt |
Q:
Drawing line plot for a histogram
I'm trying to reproduce this chart using Altair as much as I can.
https://fivethirtyeight.com/wp-content/uploads/2014/04/hickey-bechdel-11.png?w=575
I'm stuck at getting the black line dividing pass/fail. This is similar to this Altair example: https://altair-viz.github.io/gallery... | Drawing line plot for a histogram | I'm trying to reproduce this chart using Altair as much as I can.
https://fivethirtyeight.com/wp-content/uploads/2014/04/hickey-bechdel-11.png?w=575
I'm stuck at getting the black line dividing pass/fail. This is similar to this Altair example: https://altair-viz.github.io/gallery/step_chart.html.
However: in the 538 v... | [
"One - rather hacky - way to make the step chart cover the beginning of the first until the end of the last bin is to control the bin positions manually (using the rank of the ordered bins).\nThis way we can add two lines: one with 'step-after' and another one with step-before shifted by one bin. From here on, the ... | [
0
] | [] | [] | [
"altair",
"histogram",
"line",
"python",
"vega_lite"
] | stackoverflow_0057878892_altair_histogram_line_python_vega_lite.txt |
Q:
Detect passive or active sentence from text
Using the Python package spaCy, how can one detect whether a sentence uses a passive or active voice? For example, the following sentences should be detected as using a passive and active voice respectively:
passive_sentence = "John was accused of committing crimes by Da... | Detect passive or active sentence from text | Using the Python package spaCy, how can one detect whether a sentence uses a passive or active voice? For example, the following sentences should be detected as using a passive and active voice respectively:
passive_sentence = "John was accused of committing crimes by David"
# passive voice "John was accused"
active_s... | [
"There is no easy solution for this. If you're looking for something simple, accuracy might take a hit. There is a wealth of info about NLP detecting passive and active voice in a text, proprietary algorithms being the most accurate, but they come at a cost.\nWhat you're looking for, if it's for a custom hobby proj... | [
0,
0
] | [] | [] | [
"nlp",
"python",
"spacy"
] | stackoverflow_0074528441_nlp_python_spacy.txt |
Q:
OOP Tkinter how to pass a value to a function
I'm rewriting my program in OOP and I'm faced with the problem that I can't turn to graphInA and graphInB in the calBut function. How can I implement this?
import customtkinter as CTtk
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import Style
... | OOP Tkinter how to pass a value to a function | I'm rewriting my program in OOP and I'm faced with the problem that I can't turn to graphInA and graphInB in the calBut function. How can I implement this?
import customtkinter as CTtk
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import Style
class App(CTtk.CTk):
def __init__(self):
... | [
"You have two options. You can bind the variables you want as instance variables on self (i.e. the application object)\nself.graphInA = CTtk.CTkEntry(width=50)\n# Then later ...\nif len(self.graphInA.get()) > 0:\n ...\n\nor you can write a lambda that explicitly closes around the variables you want.\ndef calBut(se... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074594753_python_tkinter.txt |
Q:
Pandas: IndexingError: Unalignable boolean Series provided as indexer
I'm trying to run what I think is simple code to eliminate any columns with all NaNs, but can't get this to work (axis = 1 works just fine when eliminating rows):
import pandas as pd
import numpy as np
df = pd.DataFrame({'a':[1,2,np.nan,np.nan]... | Pandas: IndexingError: Unalignable boolean Series provided as indexer | I'm trying to run what I think is simple code to eliminate any columns with all NaNs, but can't get this to work (axis = 1 works just fine when eliminating rows):
import pandas as pd
import numpy as np
df = pd.DataFrame({'a':[1,2,np.nan,np.nan], 'b':[4,np.nan,6,np.nan], 'c':[np.nan, 8,9,np.nan], 'd':[np.nan,np.nan,np.... | [
"You need loc, because filter by columns:\nprint (df.notnull().any(axis = 0))\na True\nb True\nc True\nd False\ndtype: bool\n\ndf = df.loc[:, df.notnull().any(axis = 0)]\nprint (df)\n\n a b c\n0 1.0 4.0 NaN\n1 2.0 NaN 8.0\n2 NaN 6.0 9.0\n3 NaN NaN NaN\n\nOr filter columns and th... | [
34,
5,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0045352909_pandas_python.txt |
Q:
Can I establish a reference variable that will then let me assign a new value?
I'm writing a script interpreter in Python using Sly. While figuring out how to best write assignment interpretation, I found myself unable to quite understand how to handle the left-hand side being different sorts of values. The script... | Can I establish a reference variable that will then let me assign a new value? | I'm writing a script interpreter in Python using Sly. While figuring out how to best write assignment interpretation, I found myself unable to quite understand how to handle the left-hand side being different sorts of values. The scripting language I'm using, the left-hand side could be a variable or a field on an obje... | [
"All of your assignment operations can be reduced to \"set selector S of container C to value V\". While Python doesn't let you create a reference value C[S], it certainly lets you pass around the tuple (C, S); that works because Python containers dictionaries, lists, etc.) are effectively reference values.\n(In th... | [
1
] | [] | [] | [
"interpreter",
"python",
"sly"
] | stackoverflow_0074594595_interpreter_python_sly.txt |
Q:
Converting a pandas dataframe into a torch Dataset
I have a pandas dataframe with the following structure:
path
sentence
speech
input_values
labels
audio1.mp3
This is the first audio
[[0.0, 0.0, 0.0, ..., 0.0, 0.0]]
[[0.00005, ..., 0.0003]]
[23, 4, 6, 11, ..., 12
audio2.mp3
This is the second audio
[[0.0, 0.0, ... | Converting a pandas dataframe into a torch Dataset | I have a pandas dataframe with the following structure:
path
sentence
speech
input_values
labels
audio1.mp3
This is the first audio
[[0.0, 0.0, 0.0, ..., 0.0, 0.0]]
[[0.00005, ..., 0.0003]]
[23, 4, 6, 11, ..., 12
audio2.mp3
This is the second audio
[[0.0, 0.0, 0.0, ..., 0.0, 0.0]]
[[0.000044, ..., 0.00033]]
[... | [
"Depends on how you will use your labels column.\nI don't know how your your trainer use these data but I suggest to define your own Dataset class (https://pytorch.org/tutorials/beginner/basics/data_tutorial.html#creating-a-custom-dataset-for-your-files)\nclass CustomDataset(Dataset):\n def __init__(self, datafr... | [
0
] | [] | [] | [
"pandas",
"python",
"pytorch",
"torchaudio",
"transformer_model"
] | stackoverflow_0069724009_pandas_python_pytorch_torchaudio_transformer_model.txt |
Q:
How to save data to user models when using a resume parser in django
I am working on a website whereby users will be uploading resumes and a resume parser script will be run to get skills and save the skills to the profile of the user. I have managed to obtain the skills before saving the form but I cant save the ... | How to save data to user models when using a resume parser in django | I am working on a website whereby users will be uploading resumes and a resume parser script will be run to get skills and save the skills to the profile of the user. I have managed to obtain the skills before saving the form but I cant save the extracted skills now. Anyone who can help with this issue will be highly a... | [
"The cause of your error is when you cycle through the files submitted in your resume form, you are trying to save the resume field (remember, resume = file_form.cleaned_data['resume'] ). Presumably you want to be saving a Profile object\nIn all those lines where you add things to resume from your parsed resume fi... | [
1
] | [] | [] | [
"django",
"python",
"temporary_files"
] | stackoverflow_0074594399_django_python_temporary_files.txt |
Q:
Python error: the following arguments are required :
I am not familiar with Python, trying to build some DNN. So when I tried to parse some arguments I got this error in main.
usage: main.py [-h] [-j N] [--resume PATH] [--epochs N] [--start-epoch N] [-b N] [--lr LR]
[--weight-decay W] [-e] [--print-... | Python error: the following arguments are required : | I am not familiar with Python, trying to build some DNN. So when I tried to parse some arguments I got this error in main.
usage: main.py [-h] [-j N] [--resume PATH] [--epochs N] [--start-epoch N] [-b N] [--lr LR]
[--weight-decay W] [-e] [--print-freq N]
DIR
main.py: error: the following a... | [
"As DIR doesn't have a default value, you need to supply one when running the program. The easiest way to do this is via a command line interface. Consult the documentation of the library you are using for further hints on that.\n"
] | [
0
] | [] | [] | [
"argparse",
"conv_neural_network",
"deep_learning",
"python"
] | stackoverflow_0074594831_argparse_conv_neural_network_deep_learning_python.txt |
Q:
How to extract element from HTML code in Python
I'm trying to webscrape multiple webpages of similar HTML code. I can already get the HTML of each page and I can manually find the part of the code's string where the information I need is placed - I just don't know how to properly extract it. I believe my problem ... | How to extract element from HTML code in Python | I'm trying to webscrape multiple webpages of similar HTML code. I can already get the HTML of each page and I can manually find the part of the code's string where the information I need is placed - I just don't know how to properly extract it. I believe my problem might be solved with REGEX, actually, but I don't kno... | [
"You can use beautifulsoup to find the correct tag and json module to parse the values:\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\n\nresp = requests.get(\n \"https://statusinvest.com.br/fundos-imobiliarios/knri11\",\n headers={\"User-Agent\": \"Mozilla/5.0\"},\n)\nsoup = BeautifulSoup(resp.... | [
1,
0
] | [] | [] | [
"html",
"python",
"web_scraping"
] | stackoverflow_0074594806_html_python_web_scraping.txt |
Q:
Expand sin(acot(...)) in sympy?
Is there a way to expand the trigonometric function of an inverse trigonometric function? I have a long-expression f that contains many such subexpressions, e.g.:
sin(0.5 acot(x))**2
cos(0.5 acot(x))**2
sin(acot(x))
These expressions can be rewritten without trigonometric function... | Expand sin(acot(...)) in sympy? | Is there a way to expand the trigonometric function of an inverse trigonometric function? I have a long-expression f that contains many such subexpressions, e.g.:
sin(0.5 acot(x))**2
cos(0.5 acot(x))**2
sin(acot(x))
These expressions can be rewritten without trigonometric functions, e.g.:
1/2 - 1/2 * x / sp.sqrt(x**... | [
"There are various ways to do this. Some examples:\nIn [1]: sin(acot(x))\nOut[1]: \n 1 \n───────────────\n ________\n ╱ 1 \nx⋅ ╱ 1 + ── \n ╱ 2 \n ╲╱ x \n\nIn [2]: sin(acot(x)/2)**2\nOut[2]: \n 2⎛acot(x)⎞\nsin ⎜───────⎟\n ⎝ 2 ⎠\n\nIn [3]: e = sin(acot(x)/2)*... | [
2
] | [] | [] | [
"python",
"sympy",
"trigonometry"
] | stackoverflow_0074594679_python_sympy_trigonometry.txt |
Q:
Adding an XML element within an existing document with Python
Hello this is my first post, if something is not clear, please say so!
I have this xml file from which I have to extract all the names found between the square brackets of eanch transc tag (the one inside newsFrom) and then put them in a new tag called ... | Adding an XML element within an existing document with Python | Hello this is my first post, if something is not clear, please say so!
I have this xml file from which I have to extract all the names found between the square brackets of eanch transc tag (the one inside newsFrom) and then put them in a new tag called person under it. Obviously if there are two names I need two separa... | [
"In this case, it's easier to use lxml rather than ElementTree, because of lxml's better support for xpath.\nSo try this:\nfrom lxml import etree\nimport re\n\ntree=etree.parse('1649.xml')\n\n#find all <trasnc> elements\ntrs = root.xpath(\".//transc\")\nfor t in trs:\n #use regex to find the data between \"[\" a... | [
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0074594523_python_xml.txt |
Q:
Why am i getting an error when i import a moduel
Im following a postgresql tutorial and in the video he does
from . import models
then when i try it i can an error
i did exactly what he did in the video and i get this error
from . import models
ImportError: attempted relative import with no known parent packa... | Why am i getting an error when i import a moduel | Im following a postgresql tutorial and in the video he does
from . import models
then when i try it i can an error
i did exactly what he did in the video and i get this error
from . import models
ImportError: attempted relative import with no known parent package
does anyone know why?
| [
"The ImportError message is stating that Python expected a module to import models from, but didn't find it. Are you working from the same directory that the instructor is working from?\nI'm not familiar with the tutorial, but given the import, it seems you're also learning Django. If so, are you sure you have Djan... | [
0
] | [] | [] | [
"fastapi",
"postgresql",
"python",
"sql",
"uvicorn"
] | stackoverflow_0074594722_fastapi_postgresql_python_sql_uvicorn.txt |
Q:
Save the data in CSV after every update
Hi I have some data I want to save it in dataframe after every update. but It always override my previous data. is there any method to keep my previous data save and add new to it.
df = pd.DataFrame(columns=['Entry','Middle','Exit'])
def function():
entry_value = 178.184... | Save the data in CSV after every update | Hi I have some data I want to save it in dataframe after every update. but It always override my previous data. is there any method to keep my previous data save and add new to it.
df = pd.DataFrame(columns=['Entry','Middle','Exit'])
def function():
entry_value = 178.184 # data comming from server
middle_value ... | [
"You can use concat function (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html)\nfor example:\nimport pandas as pd\n\ndf = pd.DataFrame(columns=['Entry','Middle','Exit'])\ndef function():\n global df\n entry_value = 178.184 # data comming from server\n middle_value = 14.121 # d... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074594554_dataframe_pandas_python_python_3.x.txt |
Q:
Python change every n-th pixel of an image on x and y axis to a different color
As the title says, I have to take an image and write code that colors in every n-th pixel on x axis and every n-th pixel on y axis.
I tried using coloring every pixel manually but it will take too much time because image is 500x500 an... | Python change every n-th pixel of an image on x and y axis to a different color | As the title says, I have to take an image and write code that colors in every n-th pixel on x axis and every n-th pixel on y axis.
I tried using coloring every pixel manually but it will take too much time because image is 500x500 and it will take eternity to change every pixel based on its number on x and y axis.
| [
"I think (@PranavHosangadi) and (@Mike L) are correct.\nI don't see how it is possible without a loop. But you can use the loop in this way by skipping the pixels and not iterate over each position.\nThis is an example to change the value at a location by skipping 2 rows and 2 columns.\nimport numpy as np\n\nimg = ... | [
0
] | [] | [] | [
"jupyter",
"jupyter_notebook",
"python",
"python_3.x"
] | stackoverflow_0074594351_jupyter_jupyter_notebook_python_python_3.x.txt |
Q:
Python 2D self-avoiding random walk
I want to make a self-avoiding 2D random walk in python. Imagine it like the dot is on the square grid and it can only go up, down, left or right but it cannot land twice on the same point. I have an idea how to do it, but my programming skills aren't very good (I'm a beginner)... | Python 2D self-avoiding random walk | I want to make a self-avoiding 2D random walk in python. Imagine it like the dot is on the square grid and it can only go up, down, left or right but it cannot land twice on the same point. I have an idea how to do it, but my programming skills aren't very good (I'm a beginner) and the code doesn't work.
The end produ... | [
"Hard to know where you are going with this, here is a basic working example;\nThis is invalid as they don't exist;\n\nplt.style.use(['science', 'notebook', 'dark background'])\n\n\nPossible values are;\n\n['Solarize_Light2', '_classic_test_patch', '_mpl-gallery',\n'_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_bac... | [
0
] | [] | [] | [
"python",
"random_walk"
] | stackoverflow_0074594765_python_random_walk.txt |
Q:
Show protocols of packets captured and saved in a .pcap with scapy on python
I am capturing live air WiFi traffic and saving only the headers of the packets captures in a .pcap file.
Is it possible to find out what protocols have been used on the whole capture? If yes, how can I keep track of the number of packets... | Show protocols of packets captured and saved in a .pcap with scapy on python | I am capturing live air WiFi traffic and saving only the headers of the packets captures in a .pcap file.
Is it possible to find out what protocols have been used on the whole capture? If yes, how can I keep track of the number of packets under every protocol found?
I've found a lot of info on injecting packets with Sc... | [
"Currently, Scapy does not support very many protocols, so it's great for some tasks, but not others. Using pyshark instead (a Python wrapper for Wireshark), there are many more supported protocols.\n\nUsing Scapy:\nfrom scapy.all import *\n\ndef process_with_scapy(fileName):\n protocol_count = {}\n\n pcap_da... | [
0
] | [] | [] | [
"analysis",
"pcap",
"protocols",
"python",
"scapy"
] | stackoverflow_0020088735_analysis_pcap_protocols_python_scapy.txt |
Q:
how to change the date format in every first element of a sublist
I have a nested list like this: datelist = [["2019/04/12", 7.0], ["2019/02/09", 7.3], ["2018/08/14", 6.1]]
I need to change the date format from yyyy/mm/dd/ to yyyy.mm.dd and then return the list as it is.
So the result should be [["12.04.2019", 7.0... | how to change the date format in every first element of a sublist | I have a nested list like this: datelist = [["2019/04/12", 7.0], ["2019/02/09", 7.3], ["2018/08/14", 6.1]]
I need to change the date format from yyyy/mm/dd/ to yyyy.mm.dd and then return the list as it is.
So the result should be [["12.04.2019", 7.0], ["09.02.2019", 7.3], ["14.08.2018", 6.1]].
I'm a beginner, so I'm re... | [
"It's simple:\ndatelist = [[datetime.datetime.strptime(str(i[0]), \"%Y/%m/%d\").strftime('%d.%m.%Y'), i[1]] for i in mylist]\n\nWhen iterating throughout your list, you get back a list, knowing the position of your elements in the list helps, thus using i[0] for the first element (datetime), and i[1] for the second... | [
0,
0
] | [] | [] | [
"datetime",
"function",
"nested_lists",
"python"
] | stackoverflow_0074595039_datetime_function_nested_lists_python.txt |
Q:
Get size of a file before downloading in Python
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?
import urllib
impor... | Get size of a file before downloading in Python | I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?
import urllib
import re
url = "http://www.someurl.com"
# Download the ... | [
"I have reproduced what you are seeing:\nimport urllib, os\nlink = \"http://python.org\"\nprint \"opening url:\", link\nsite = urllib.urlopen(link)\nmeta = site.info()\nprint \"Content-Length:\", meta.getheaders(\"Content-Length\")[0]\n\nf = open(\"out.txt\", \"r\")\nprint \"File on disk:\",len(f.read())\nf.close()... | [
39,
28,
12,
7,
6,
5,
3,
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0000005909_python_urllib.txt |
Q:
Plotly: Remove legend title using template
Even after passing 'title':None inside layout.legend in the template, the chart still shows a legend title, whereas it should change the default setting to no legend title.
If I manually pass it though with fig.update_layout(), it then removes the title.
Why is this happ... | Plotly: Remove legend title using template | Even after passing 'title':None inside layout.legend in the template, the chart still shows a legend title, whereas it should change the default setting to no legend title.
If I manually pass it though with fig.update_layout(), it then removes the title.
Why is this happening and how do I change the default setting to... | [
"I was certain that the following would do the trick:\n'title': {'text': None}\n\nBut to my surprise, the text 'variable' still pops up. An empty string '' doesn't work, and neither does 'title': {'text': False}.\nAnd I find this very interesting, since you're able to edit all other attributes of the legend title e... | [
2,
2,
0,
0
] | [] | [] | [
"data_visualization",
"plotly",
"plotly_python",
"python"
] | stackoverflow_0067622972_data_visualization_plotly_plotly_python_python.txt |
Q:
Element-wise multiplication of matrices in Tensorflow : how to avoid for loop
I want to do the following multiplication in tensorflow (TF 2.10), but I'm not sure how to.
I have an image tensor a, which is of shape 224x224x3 and a tensor b, which is of shape 224x224xf. I want to multiply (element-wise) a by each 2D... | Element-wise multiplication of matrices in Tensorflow : how to avoid for loop | I want to do the following multiplication in tensorflow (TF 2.10), but I'm not sure how to.
I have an image tensor a, which is of shape 224x224x3 and a tensor b, which is of shape 224x224xf. I want to multiply (element-wise) a by each 2D matrix of b sliced by f to get a matrix c of shape 224x224xf.
So for example, the ... | [
"You could multiply each channel of a with b and then sum:\nX = a[:,:,0:1] * b + a[:,:,1:2] * b + a[:,:,2:3] * b\n\nThe shape of X is (224, 224, f) and it will give the same results as your multiplications:\n(X[:, :, 0] == tf.reduce_sum(a * b[:, :, 0][:, :, None], axis=-1)).numpy().all()\n\nOutput:\nTrue\n\nThe fol... | [
3,
1
] | [] | [] | [
"matrix_multiplication",
"python",
"tensorflow"
] | stackoverflow_0074592109_matrix_multiplication_python_tensorflow.txt |
Q:
Filling NaN on conditions
I have the following input data:
df = pd.DataFrame({"ID" : [1, 1, 1, 2, 2, 2, 2],
"length" : [0.7, 0.7, 0.7, 0.8, 0.6, 0.6, 0.7],
"height" : [7, 9, np.nan, 4, 8, np.nan, 5]})
df
ID length height
0 1 0.7 7
1 1 0.7 9
2 1 0.7 ... | Filling NaN on conditions | I have the following input data:
df = pd.DataFrame({"ID" : [1, 1, 1, 2, 2, 2, 2],
"length" : [0.7, 0.7, 0.7, 0.8, 0.6, 0.6, 0.7],
"height" : [7, 9, np.nan, 4, 8, np.nan, 5]})
df
ID length height
0 1 0.7 7
1 1 0.7 9
2 1 0.7 np.nan
3 2 0.8 4
4 2... | [
"You could try with sort_value then we use groupby find the last\n#last will find the last not NaN value\n\ndf.height.fillna(df.sort_values(['length','height']).groupby(['ID'])['height'].transform('last'),inplace=True)\ndf\nOut[296]: \n ID length height\n0 1 0.7 7.0\n1 1 0.7 9.0\n2 1 0... | [
2
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074595035_numpy_pandas_python.txt |
Q:
Why does python replace every object of a column, when only referring to one, if all lines are identical?
When trying to change one value in a matrix, python will change all items of that column with the desired value, despite the fact I am only trying to change one. But this only happens when all rows are identic... | Why does python replace every object of a column, when only referring to one, if all lines are identical? | When trying to change one value in a matrix, python will change all items of that column with the desired value, despite the fact I am only trying to change one. But this only happens when all rows are identical.
Example:
def print_matrix(matrix: list[list], dlm: str) -> None:
for row in matrix:
for col i... | [
"The reason is when you write test_matrix.append(one_row) you are appending actually [0,1,2,3] 5 times to test_matrix, essentially, i.e the list will look like [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]. Here each list element is a list with [0,1,2,3] references to the same [0,1,2,3]. Wh... | [
0
] | [] | [] | [
"list",
"matrix",
"python"
] | stackoverflow_0074595031_list_matrix_python.txt |
Q:
Python read dict values from lists?
In python I have:
my_dict = dict({'98:1E:19:7E:8F:30': ['SAGEMCOM BROADBAND SAS', '22'], '98:1E:19:7E:8F:32': ['SAGEMCOM BROADBAND SAS1']})
and would like to generate a list of all values, so I tried:
[[sub_val for sub_val in val] for val in my_dict.values()]
But this gives me... | Python read dict values from lists? | In python I have:
my_dict = dict({'98:1E:19:7E:8F:30': ['SAGEMCOM BROADBAND SAS', '22'], '98:1E:19:7E:8F:32': ['SAGEMCOM BROADBAND SAS1']})
and would like to generate a list of all values, so I tried:
[[sub_val for sub_val in val] for val in my_dict.values()]
But this gives me:
[['SAGEMCOM BROADBAND SAS', '22'], ['S... | [
"You can use an additional for clause in the list comprehension to iterate through the sub-lists:\n[value for values in my_dict.values() for value in values]\n\n"
] | [
1
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074595083_list_python_python_3.x.txt |
Q:
Calculating Pearson correlation and significance in Python
I am looking for a function that takes as input two lists, and returns the Pearson correlation, and the significance of the correlation.
A:
You can have a look at scipy.stats:
from pydoc import help
from scipy.stats.stats import pearsonr
help(pearsonr)
... | Calculating Pearson correlation and significance in Python | I am looking for a function that takes as input two lists, and returns the Pearson correlation, and the significance of the correlation.
| [
"You can have a look at scipy.stats:\nfrom pydoc import help\nfrom scipy.stats.stats import pearsonr\nhelp(pearsonr)\n\n>>>\nHelp on function pearsonr in module scipy.stats.stats:\n\npearsonr(x, y)\n Calculates a Pearson correlation coefficient and the p-value for testing\n non-correlation.\n\n The Pearson correlat... | [
213,
120,
60,
39,
31,
28,
11,
11,
7,
6,
5,
3,
3,
3,
1,
1,
0,
0
] | [
"def pearson(x,y):\n n=len(x)\n vals=range(n)\n\n sumx=sum([float(x[i]) for i in vals])\n sumy=sum([float(y[i]) for i in vals])\n\n sumxSq=sum([x[i]**2.0 for i in vals])\n sumySq=sum([y[i]**2.0 for i in vals])\n\n pSum=sum([x[i]*y[i] for i in vals])\n # Calculating Pearson correlation\n num=pSum-(sumx*sumy... | [
-1
] | [
"numpy",
"python",
"scipy",
"statistics"
] | stackoverflow_0003949226_numpy_python_scipy_statistics.txt |
Q:
Display PDF in django
I need to display a pdf file in a browser, but I cannot find the solution to take the PDF for the folder media, the PDF file was save in my database, but I cannot show.
my urls.py:
urlpatterns = [
path('uploadfile/', views.uploadFile, name="uploadFile"),
path('verPDF/<idtermsCondition... | Display PDF in django | I need to display a pdf file in a browser, but I cannot find the solution to take the PDF for the folder media, the PDF file was save in my database, but I cannot show.
my urls.py:
urlpatterns = [
path('uploadfile/', views.uploadFile, name="uploadFile"),
path('verPDF/<idtermsCondition>', views.verPDF, name='ver... | [
"It should be user.is_authenticated not user.is_authenticated() in verPDF view and also I'd recommend you to change <idtermsCondition> to <int:idtermsCondition> as by default (if nothing is given) it is considered as string.\nurls.py\nurlpatterns = [\n path('uploadfile/', views.uploadFile, name=\"uploadFile\"),\... | [
3,
2
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_urls",
"python"
] | stackoverflow_0074587558_django_django_forms_django_templates_django_urls_python.txt |
Q:
How to find the best minimal distance path between list of words and their indices?
Here's an example data I have,
word_indices = [
('bus', 554, 1),
('bus', 719, 1),
('bus', 808, 1),
('accessibility', 572, 2),
('accessibility', 724, 2),
('accessibility', 809, 2),
('ada', 725, 3),
('ada', 810, 3),
('access... | How to find the best minimal distance path between list of words and their indices? | Here's an example data I have,
word_indices = [
('bus', 554, 1),
('bus', 719, 1),
('bus', 808, 1),
('accessibility', 572, 2),
('accessibility', 724, 2),
('accessibility', 809, 2),
('ada', 725, 3),
('ada', 810, 3),
('accessible', 695, 4),
('accessible', 707, 4),
('accessible', 726, 4),
('accessible', 811, 4)... | [
"from collections import defaultdict\nimport heapq\n\ndef dijkstra(word_indices):\n groups = defaultdict(list)\n for word, group_index, group in word_indices:\n groups[group].append((word, group_index))\n start, stop = min(groups), max(groups)\n # queue contains distance, path, where path is a tu... | [
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074594885_python_python_3.x.txt |
Q:
It is saying that mean, and median when chosen, is not defined?
def average(vals, method):
if method == mean:
mean == (sum(a)/len(a))
print('The mean is', str(mean))
if method == median:
median == (len(a)-1)//2
print('The median is', str(median))
average((-1,0,1,1,1,2,3), mean)
I... | It is saying that mean, and median when chosen, is not defined? | def average(vals, method):
if method == mean:
mean == (sum(a)/len(a))
print('The mean is', str(mean))
if method == median:
median == (len(a)-1)//2
print('The median is', str(median))
average((-1,0,1,1,1,2,3), mean)
I dont understand what needs fixing, can anyone help?
| [
"Here is some fixed code:\ndef average(vals, method):\n if method == 'mean':\n mean = (sum(a)/len(a))\n print('The mean is', mean)\n if method == 'median':\n midpoint = (len(a)-1)//2\n median = vals[midpoint]\n print('The median is', median)\n\naverage((-1,0,1,1,1,2,3), 'mean')\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074595056_python.txt |
Q:
Assign number to python from range
I'm looking at a data set of scores.
I want to know the probability of each score based on the bin the score falls in using pd.cut
How can I take a value and assign it a probability based on the outputted table?
Code as follows
import pandas as pd
data = pd.DataFrame({'scores':[... | Assign number to python from range | I'm looking at a data set of scores.
I want to know the probability of each score based on the bin the score falls in using pd.cut
How can I take a value and assign it a probability based on the outputted table?
Code as follows
import pandas as pd
data = pd.DataFrame({'scores':[168.0, 44.0, 352.0, 128.0, 268.0, 228.0,... | [
"Your frequencyTable is a table where the first column is an Interval and the third column is the percentage. So to get what you want, you iterate over the table, looking for the item where the input value (v=265) is in the Interval of that row, and if it is, you take the value in the third column. So something l... | [
0
] | [] | [] | [
"pandas",
"python",
"statistics"
] | stackoverflow_0074594997_pandas_python_statistics.txt |
Q:
IndexError: tuple index out of range when creating PySpark DataFrame
I want to create test data in a pyspark dataframe but I always get the same "tuple index out of range" error. I do not get this error when reading a csv. Would appreciate any thoughts on why I'm getting this error.
The first thing I tried was cre... | IndexError: tuple index out of range when creating PySpark DataFrame | I want to create test data in a pyspark dataframe but I always get the same "tuple index out of range" error. I do not get this error when reading a csv. Would appreciate any thoughts on why I'm getting this error.
The first thing I tried was create a pandas dataframe and convert it to a pyspark dataframe:
columns = ["... | [
"After doing some reading I checked https://pyreadiness.org/3.11 and it looks like the latest version of python is not supported by pyspark. I was able to resolve this problem by downgrading to python 3.9\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074579273_dataframe_pandas_pyspark_python.txt |
Q:
How to fix pydev debugger error in Pycharm?
Yesterday I updated my python, this caused my debugger to not function properly.
I keep getting the following error in output:
-------------------------------------------------------------------------------
pydev debugger: CRITICAL WARNING: This version of python seems t... | How to fix pydev debugger error in Pycharm? | Yesterday I updated my python, this caused my debugger to not function properly.
I keep getting the following error in output:
-------------------------------------------------------------------------------
pydev debugger: CRITICAL WARNING: This version of python seems to be incorrectly compiled (internal generated fil... | [
"So it seems that there is a bug in Pycharm current version and What helped me fix it is to download the EAP version 2022.3. I did not receive anymore errors.\n"
] | [
0
] | [] | [] | [
"debugging",
"pycharm",
"python"
] | stackoverflow_0074583310_debugging_pycharm_python.txt |
Q:
How can resources be provided in PyQt6 (which has no pyrcc)?
The documentation for PyQt6 states that
Support for Qt’s resource system has been removed (i.e. there is no pyrcc6).
In light of this, how should one provide resources for a PyQt6 application?
A:
There has been some discussion on the PyQt mailing lis... | How can resources be provided in PyQt6 (which has no pyrcc)? | The documentation for PyQt6 states that
Support for Qt’s resource system has been removed (i.e. there is no pyrcc6).
In light of this, how should one provide resources for a PyQt6 application?
| [
"There has been some discussion on the PyQt mailing list when this was found out.\nThe maintainer is not interested in maintaining pyrcc anymore as he believes that it doesn't provide any major benefit considering that python already uses multiple files anyway.\nThe easiest solution is probably to use the static me... | [
9,
6,
1,
0,
0
] | [] | [] | [
"pyqt",
"pyqt6",
"pyrcc",
"python",
"resources"
] | stackoverflow_0066099225_pyqt_pyqt6_pyrcc_python_resources.txt |
Q:
How do I use the debug console in VSCode?
I really like the debug console feature in VScode, it makes it a lot easier for me to do Python writing. How do I get it to stay on? Is it possible to write launch.json so that the code runs without closing the run afterwards?
I can use 'time.sleep()' to continue this cons... | How do I use the debug console in VSCode? | I really like the debug console feature in VScode, it makes it a lot easier for me to do Python writing. How do I get it to stay on? Is it possible to write launch.json so that the code runs without closing the run afterwards?
I can use 'time.sleep()' to continue this console on.
Can I edit the'launch.json'?
What are o... | [
"It's not possible to keep the debug console open after the script ends, because the memory is released back to the operating system.\nEdit: as @nigh_anxiety mentioned, setting a breakpoint at the end of the script is probably a more elegant solution.\n\nOld Answer:\nInstead, you could wait for user input before ex... | [
0,
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074567962_python_visual_studio_code.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.