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:
Django many to many model get none
I have been dealing with a project for a few days and today I encountered an error. I wanted to write it here as I have no idea how to solve it.
My first model:
from django.db import models
# Create your models here.
class Video(models.Model):
title = models.CharField(max_le... | Django many to many model get none | I have been dealing with a project for a few days and today I encountered an error. I wanted to write it here as I have no idea how to solve it.
My first model:
from django.db import models
# Create your models here.
class Video(models.Model):
title = models.CharField(max_length=100)
video_slug = models.SlugFi... | [
"Im assuming your mistake is you are using an empty Serializer and not including the queryset instance. So something like this will fix your issue:\nqueryset = Video.objects.all()\nserializer_class = VideoSerializer(queryset, many=True)\n\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"orm",
"python"
] | stackoverflow_0074671896_django_django_models_django_rest_framework_orm_python.txt |
Q:
Is there any way to skip number request in telethon?
Every time if my session is invalid i got this output: "Please enter your phone (or bot token): "
Is there anyway to pass it or ignore it?
I tried to edit telethon source code, but im bad at it))
A:
So, for everyone who have the same problem
client = TelegramC... | Is there any way to skip number request in telethon? | Every time if my session is invalid i got this output: "Please enter your phone (or bot token): "
Is there anyway to pass it or ignore it?
I tried to edit telethon source code, but im bad at it))
| [
"So, for everyone who have the same problem\nclient = TelegramClient(f\"session\", api_id, api_hash)\nclient.connect()\nprint(client)\nif client.is_user_authorized():\n print(\"VALID\")\nelse:\n print('NO VALID')\n\nEverything was much easier, than i thought\n"
] | [
0
] | [
"Telethon project implements Telegram API and there is no way to skip it since it's required by protocol.\nAs an option I can advice you to check if authenticating as a bot instead of a normal user can solve your problem depending on your task.\n"
] | [
-1
] | [
"python",
"telethon"
] | stackoverflow_0074671835_python_telethon.txt |
Q:
I'm doing some basic logic function + decimal rounding stuff, and this doesn't seem to work...why?
temperature=int(input("What temperature are you?"))
if temperature>=37 and temperature<50:
print("your temperature is healthy, as it is" , "%.2f" %temperature)
else:
print("You said your temperature was" , ... | I'm doing some basic logic function + decimal rounding stuff, and this doesn't seem to work...why? | temperature=int(input("What temperature are you?"))
if temperature>=37 and temperature<50:
print("your temperature is healthy, as it is" , "%.2f" %temperature)
else:
print("You said your temperature was" , "%.2f" %temperature , "You are unhealthy")
#why is this not working??? when I input the temperature at ... | [
"temperature=int(input(\"What temperature are you?\"))\n\nWhen you pass a string to int(), it must be a whole number. Decimals like 37.8 aren't allowed.\nI think you could just use float() instead of int().\n"
] | [
0
] | [] | [] | [
"decimal",
"logic",
"python",
"variables"
] | stackoverflow_0074672016_decimal_logic_python_variables.txt |
Q:
tensorflow MDA custom loss and ValueError: No gradients provided for any variable
I would like to use the MDA (mean direction accuracy) as a custom loss function for a tensorflow neural network.
I am trying to implement this as described in here:
Custom Mean Directional Accuracy loss function in Keras
def mda(y_tr... | tensorflow MDA custom loss and ValueError: No gradients provided for any variable | I would like to use the MDA (mean direction accuracy) as a custom loss function for a tensorflow neural network.
I am trying to implement this as described in here:
Custom Mean Directional Accuracy loss function in Keras
def mda(y_true, y_pred):
s = K.equal(K.sign(y_true[1:] - y_true[:-1]),
K.sign(... | [
"It looks like the error you're seeing is because the mda() function you've defined doesn't have any differentiable operations. Because of this, TensorFlow doesn't know how to compute the gradients of the function, and it's unable to optimize the weights of your neural network using backpropagation.\nTo fix this, y... | [
1,
1,
0
] | [] | [] | [
"keras",
"loss_function",
"python",
"tensorflow"
] | stackoverflow_0074671602_keras_loss_function_python_tensorflow.txt |
Q:
Cannot get data from request.get_json(force=True)
import requests
import numpy as np
import json
from flask import Flask, request, jsonify
url = 'http://localhost:5000/api'
dat = np.genfromtxt('/home/panos/Manti_Milk/BigData/50_0_50_3.5_3-3.dat')
d1 = dat[:,0]
data = {"w0": d1[0], "w1": d1[1], "w2": d1[2], "w3"... | Cannot get data from request.get_json(force=True) | import requests
import numpy as np
import json
from flask import Flask, request, jsonify
url = 'http://localhost:5000/api'
dat = np.genfromtxt('/home/panos/Manti_Milk/BigData/50_0_50_3.5_3-3.dat')
d1 = dat[:,0]
data = {"w0": d1[0], "w1": d1[1], "w2": d1[2], "w3": d1[3], "w4": d1[4],
"w5": d1[5], "w6": d1[6... | [
"You do not need to decode json data after request.get_json(), it is already the Python dict. So the line dummy = json.loads(jsondata) is unnecessary.\n@app.route('/api',methods=['POST','GET'])\ndef predict():\n jsondata = request.get_json(force=True)\n arr = np.fromiter(jsondata.values(), dtype=float)\n\nEDI... | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074670424_flask_python.txt |
Q:
How can I get my python code to be more efficient?
I've been struggling for the past couple days with getting my python code to be more efficient, while also getting the run time to be with in the given specifications of the problem below ( 3 seconds, for any given input). Was told that linear time may help, but w... | How can I get my python code to be more efficient? | I've been struggling for the past couple days with getting my python code to be more efficient, while also getting the run time to be with in the given specifications of the problem below ( 3 seconds, for any given input). Was told that linear time may help, but was hoping I can get some help on how I'd approach it wit... | [
"It looks like your current approach is to iterate through all possible pairs of elements in the list and calculate the difference between the maximum and minimum element in each pair. This approach will take quadratic time, which might not efficient enough to solve this problem within the given time constraints.\n... | [
1,
0
] | [] | [] | [
"processing_efficiency",
"python"
] | stackoverflow_0074671865_processing_efficiency_python.txt |
Q:
Question on exponential function and random variable
I am trying to understand the following code. Could someone explain what each step essentially means? (especially the 1st, 2nd and 4th line of code)
X = stats.expon(scale=10)
xs = X.rvs(100000)
plt.figure(figsize=(10, 4))
plt.hist(xs, bins=100, color="navy")
plt... | Question on exponential function and random variable | I am trying to understand the following code. Could someone explain what each step essentially means? (especially the 1st, 2nd and 4th line of code)
X = stats.expon(scale=10)
xs = X.rvs(100000)
plt.figure(figsize=(10, 4))
plt.hist(xs, bins=100, color="navy")
plt.xlim(0, 80);
This was a sample code from a data science ... | [
"This code is using the expon() function from the stats module in the Python library scipy to generate random samples from an exponential distribution with a scale parameter of 10. The expon() function returns an object representing the exponential distribution, which can then be used to generate random samples usi... | [
2
] | [] | [] | [
"exponential",
"matplotlib",
"python"
] | stackoverflow_0074672077_exponential_matplotlib_python.txt |
Q:
Return dataframes containing unique column pairs in Pandas?
I am trying to use pandas to select rows based on unique column pairs.
For example with the dataframe below read of of an csv:
col1 col2 col3
0 1 10 [a, b, c, d]
1 1 10 [e, f, g, h]
2 2 11 [a, b, c, d]
3 3 12... | Return dataframes containing unique column pairs in Pandas? | I am trying to use pandas to select rows based on unique column pairs.
For example with the dataframe below read of of an csv:
col1 col2 col3
0 1 10 [a, b, c, d]
1 1 10 [e, f, g, h]
2 2 11 [a, b, c, d]
3 3 12 [i, j, k, l]
4 3 12 [e, f, g, h]
5 5 14 ... | [
"You could try with\ndf_uniq_list = dict([*df.groupby(['col1','col2'])])\ndf_uniq_list[(1,10)]\n col1 col2 col3 \n0 1 10 [a, b, c, d]\n1 1 10 [e, f, g, h]\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"set_comprehension"
] | stackoverflow_0074672035_pandas_python_set_comprehension.txt |
Q:
Use selenium pull the link from an href which is an attribute of a class element that has a random class name?
Here is the element. Be aware I slimmed it down, there is much more in the </div>:
<a class="123abc456def" download="" href="https://www.downloadme.com/1jk43jkls.txt role="menuitem" tabindex="-1"><div></d... | Use selenium pull the link from an href which is an attribute of a class element that has a random class name? | Here is the element. Be aware I slimmed it down, there is much more in the </div>:
<a class="123abc456def" download="" href="https://www.downloadme.com/1jk43jkls.txt role="menuitem" tabindex="-1"><div></div></a>
The class name is a random string of characters so I cant use that as an identifier.
I want to grab the hre... | [
"Figured it out. I used the xpath, searched for an a class element, and then searched for if it contained part of the url. Then I pulled the href link with get_attribute\nlink = driver.find_element(By.XPATH,\"//a[@class and contains(@href, 'downloadme')]\").get_attribute(\"href\")\n\n"
] | [
0
] | [] | [] | [
"class",
"element",
"href",
"python",
"selenium"
] | stackoverflow_0074672012_class_element_href_python_selenium.txt |
Q:
Sorting a List by frequency of occurrence in a list
I have a list of integers(or could be even strings), which I would like to sort by the frequency of occurrences in Python, for instance:
a = [1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]
Here the element 5 appears 4 times in the list, 4 appears 3 times. So the output... | Sorting a List by frequency of occurrence in a list | I have a list of integers(or could be even strings), which I would like to sort by the frequency of occurrences in Python, for instance:
a = [1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5]
Here the element 5 appears 4 times in the list, 4 appears 3 times. So the output sorted list would be :
result = [5, 5, 5, 5, 3, 3, 3, 4,... | [
"from collections import Counter\nprint [item for items, c in Counter(a).most_common() for item in [items] * c]\n# [5, 5, 5, 5, 3, 3, 3, 4, 4, 4, 1, 1, 2]\n\nOr even better (efficient) implementation\nfrom collections import Counter\nfrom itertools import repeat, chain\nprint list(chain.from_iterable(repeat(i, c) f... | [
37,
8,
3,
1,
0,
0,
0
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0023429426_list_python_sorting.txt |
Q:
How to split a row into 2 rows by setting a delimiter?
How can I split this line: Basis of the Consolidated <> Financial Statements by setting <> as a delimiter and create a new row which should not affect other columns?
The data looks like this.
I need to do this in Python code and I tried this but its not workin... | How to split a row into 2 rows by setting a delimiter? | How can I split this line: Basis of the Consolidated <> Financial Statements by setting <> as a delimiter and create a new row which should not affect other columns?
The data looks like this.
I need to do this in Python code and I tried this but its not working:
for i in range(len(df5)):
df5['text'].iloc[i]=st... | [
"To split a row into two rows by a delimiter such as \"<>\" in Python, you can use the split() method of the str class. The split() method splits a string into a list of substrings based on the specified delimiter and returns the resulting list.\n# Define the row\nrow = \"Basis of the Consolidated<>Financial Statem... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074669736_dataframe_pandas_python.txt |
Q:
How to extract a specific text when web scraping for this situation
I need to scrape texts from a website, but could not figure out a way to scrape a specific text for this situation:
<td valign="top" class="testo_normale">
<font face="Geneva">
<i>W. Richard Bowen</i>
<br>
"Water engine... | How to extract a specific text when web scraping for this situation | I need to scrape texts from a website, but could not figure out a way to scrape a specific text for this situation:
<td valign="top" class="testo_normale">
<font face="Geneva">
<i>W. Richard Bowen</i>
<br>
"Water engineering for the promotion of peace"
<br>
"1(2009)1-6"
... | [
"You can apply split() method like:\nfrom bs4 import BeautifulSoup\n\nhtml ='''\n\n<td valign=\"top\" class=\"testo_normale\">\n <font face=\"Geneva\">\n <i>W. Richard Bowen</i>\n <br>\n \"Water engineering for the promotion of peace\" \n <br>\n \"1(2009)1-6\"\n <br>\n ... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074672015_beautifulsoup_python_web_scraping.txt |
Q:
Unable to iterate over nested loop to calculate sum
I am unable find correct logic to find summation. I have binary_values and function as:
binary_values =[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
def f(x):
m = np.matrix([0.5,-0.5, 0.3])
w = m.transpose()
... | Unable to iterate over nested loop to calculate sum | I am unable find correct logic to find summation. I have binary_values and function as:
binary_values =[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
def f(x):
m = np.matrix([0.5,-0.5, 0.3])
w = m.transpose()
Y = np.dot(x,w)
return Y
f(x)
I have to find summat... | [
"The problem you described is because you do:\nfor i in binary _values # Will put the value of i to a inner list item like [0,1,1]\n\nthen you do:\nfor j in i # makes j a value inside the inner list like\n # 0 - first iteration , 1 - second iteration, 1 - third iteration \n\nand then you try to use i as ... | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074671984_numpy_python.txt |
Q:
Getting strange and unexpected output from python while loop
I made a simple while loop to increase a number. And then I made a completely separate if condition to print a statement under certain circumstances. I don't understand why the two are being joined together.....
Write a program whose input is two intege... | Getting strange and unexpected output from python while loop | I made a simple while loop to increase a number. And then I made a completely separate if condition to print a statement under certain circumstances. I don't understand why the two are being joined together.....
Write a program whose input is two integers. Output the first integer
and subsequent increments of 5 as lon... | [
"Your while loop is ensuring firstNum > secondNum by the time it finishes running. Then, you check to see if firstNum > secondNum (which it is), and your print statement gets executed.\n",
"a = int(input())\nb = int(input())\nif b < a:\n print(\"Second integer can't be less than the first.\",end=\"\")\nwhile a... | [
2,
0
] | [] | [] | [
"python",
"while_loop"
] | stackoverflow_0072081945_python_while_loop.txt |
Q:
Sorting a Dataframe with alternating positive and negative values in one column
please help me sort df into df1, in other words, I am trying to sort df by col3 ensuring that the values in col3 alternate from positive to negative:
df (original dataframe)
col1 col2 col3
0 1 -1 -38
1 2 -2 45
2 3... | Sorting a Dataframe with alternating positive and negative values in one column | please help me sort df into df1, in other words, I am trying to sort df by col3 ensuring that the values in col3 alternate from positive to negative:
df (original dataframe)
col1 col2 col3
0 1 -1 -38
1 2 -2 45
2 3 -3 79
3 4 -4 -55
4 5 -5 31
5 6 -6 38
6 7 -7 -45
7 8 -8 -... | [
"One way using pandas.DataFrame.groupby then sort_values with multiple colums:\nkeys = [\"abs\", \"order\", \"sign\"]\n\ns = df[\"col3\"]\n\ndf[\"abs\"] = s.abs()\ndf[\"order\"] = df.groupby([\"abs\", \"col3\"]).cumcount()\n\n# If you want positive to come first\ndf[\"sign\"] = s.lt(0)\n\n# If you want negative to ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074672188_pandas_python.txt |
Q:
pydantic.error_wrappers.ValidationError: 11 validation errors for For Trip type=value_error.missing
Im getting this error with my pydantic schema, but oddly it is generating the object correctly, and sending it to the SQLAlchemy models, then it suddenly throws error for all elements in the model.
response -> id
... | pydantic.error_wrappers.ValidationError: 11 validation errors for For Trip type=value_error.missing | Im getting this error with my pydantic schema, but oddly it is generating the object correctly, and sending it to the SQLAlchemy models, then it suddenly throws error for all elements in the model.
response -> id
field required (type=value_error.missing)
response -> date
field required (type=value_error.missing)
re... | [
"It seems like a bug on the pydantic model, it happened to me as well, and i was not able to fix it, but indeed if you just skip the type check in the route it works fine\n",
"It seems like there is a conflict in your schema and create_trip function. Have you checked whether you are passing the correct param to y... | [
2,
0,
0
] | [] | [] | [
"pydantic",
"python",
"sqlalchemy"
] | stackoverflow_0072476094_pydantic_python_sqlalchemy.txt |
Q:
Pagination in Flask
I'm trying to display 5 record per page. However, I not sure how to configure the li class. For instance, click the 2 and it will redirect to next 5 record on second page and click previous it will redirect from 2 to 1 to first page.
manageSmartphone.html
<div class="clearfix">
... | Pagination in Flask | I'm trying to display 5 record per page. However, I not sure how to configure the li class. For instance, click the 2 and it will redirect to next 5 record on second page and click previous it will redirect from 2 to 1 to first page.
manageSmartphone.html
<div class="clearfix">
<div class="hint-text">Sh... | [
"Implementing pagination can be challenging for several reasons,\nI would suggest you using the paginate() method of the Flask-SQLAlchemy lib\nThis method takes a page parameter and a per_page parameter that you can use to specify the current page and the number of records to display per page\nHere is an example of... | [
1
] | [] | [] | [
"flask",
"html",
"python"
] | stackoverflow_0074666012_flask_html_python.txt |
Q:
Python: Print string in reverse
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
then the output is:
ereht olleH
yeH
I have alrea... | Python: Print string in reverse | Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
then the output is:
ereht olleH
yeH
I have already the code like this. I don't under... | [
"This may work for you:\nword = \"\"\nthe_no_word = ['Done', 'done', 'd']\nwhile word not in the_no_word:\n word = str(input())\n print(word[-1::-1])\n\nYou need to get the user input into word after every loop and check if word is not in the list of the_no_word. Let me know if this is what you were looking f... | [
0,
0,
0,
0
] | [
"string = str(input())\n\nno_words = ['Done','done','d']\nwhile string not in no_words:\n if string in no_words:\n print()\n else:\n print(string[-1::-1])\n string = str(input())\n\n"
] | [
-2
] | [
"performance",
"python",
"python_3.x"
] | stackoverflow_0071360039_performance_python_python_3.x.txt |
Q:
How to remove fractioned Items and add sales to another row
So basically my POS reports don't add up split bills.
If you look at df.Item there are items with fractions (1/2, 1/3, etc). I want to drop those lines but add the sales to the proper row.
Item Outlet1 Outlet2 Outlet3 Outlet4
2 ... | How to remove fractioned Items and add sales to another row | So basically my POS reports don't add up split bills.
If you look at df.Item there are items with fractions (1/2, 1/3, etc). I want to drop those lines but add the sales to the proper row.
Item Outlet1 Outlet2 Outlet3 Outlet4
2 AIR GIN 162.0 NaN 189.0 54.0
3 AIR G... | [
"I'm assuming the data doesn't contain any duplicate items. It looks like it's total sales over a certain period, but just the itemization is messed up.\nIn that case, you can simply remove the fractions with .str.replace(), then group and sum.\ndf['Item'] = df['Item'].str.replace(r'\\s+\\d+/\\d+$', '', regex=True)... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074671929_dataframe_pandas_python.txt |
Q:
Scraping Table Data from Multiple URLS, but first link is repeating
I'm looking to iterate through the URL with "count" as variables between 1 and 65.
Right now, I'm close but really struggling to figure out the last piece. I'm receiving the same table (from variable 1) 65 times, instead of receiving the differen... | Scraping Table Data from Multiple URLS, but first link is repeating | I'm looking to iterate through the URL with "count" as variables between 1 and 65.
Right now, I'm close but really struggling to figure out the last piece. I'm receiving the same table (from variable 1) 65 times, instead of receiving the different tables.
import requests
import pandas as pd
url = 'https://basketball.... | [
"A few errors:\n\nYour URL was templated incorrectly. It remains at .../{count} literally, without substituting or updating from the loop variable.\nIf you want to get page 1 to 65, use range(1, 66)\nUnless you want to export only the last dataframe, you need to concatenate all of them first\n\n# No count here, we ... | [
1
] | [] | [] | [
"dataframe",
"loops",
"pandas",
"python",
"python_requests"
] | stackoverflow_0074672238_dataframe_loops_pandas_python_python_requests.txt |
Q:
Consume a docker container inside Django docker container? Connecting two docker containers
I have a Django container and I want to consume another DL container inside it? For example, I have a Django app that predicting images classes and I want to make the prediction using a docker container and not a python lib... | Consume a docker container inside Django docker container? Connecting two docker containers | I have a Django container and I want to consume another DL container inside it? For example, I have a Django app that predicting images classes and I want to make the prediction using a docker container and not a python library. That Django app will be containerised as well. In production, I will have three docker cont... | [
"The easiest way to do this is to make a network call to the other container. You may find it simplest to wrap the YoloV5 code in a very thin web layer, e.g. using Flask, to create an API. Then call that in your Django container when you need it using requests.\n",
"As suggested by Nick and others, the solution i... | [
0,
0
] | [] | [] | [
"deep_learning",
"django",
"docker",
"docker_compose",
"python"
] | stackoverflow_0074634267_deep_learning_django_docker_docker_compose_python.txt |
Q:
Invalid Shape Error when trying to leverage Keras's VGG16 pretrained model
I am trying to leverage kera's VGG16 model in my own image classification problem. My code is heavily based upon Francois Chollet's example (Chapter 8 of Deep Learning in Python - code).
I have three classes I'm trying to predict. Directory... | Invalid Shape Error when trying to leverage Keras's VGG16 pretrained model | I am trying to leverage kera's VGG16 model in my own image classification problem. My code is heavily based upon Francois Chollet's example (Chapter 8 of Deep Learning in Python - code).
I have three classes I'm trying to predict. Directory structure:
data/
training/
class_1
class_2
class_3
Note: this my... | [
"The categorical_crossentropy loss for 3 classes together with the batch size of 32 dictate the shape of labels (for each bach) to be (32, 3).\nThe labels are currently ordinal: 0, 1, and 2. One can use the SparseCategoricalCrossentropy loss for ordinal labels:\nloss= tf.keras.losses.SparseCategoricalCrossentropy()... | [
0
] | [] | [] | [
"deep_learning",
"keras",
"python",
"vgg_net"
] | stackoverflow_0074667517_deep_learning_keras_python_vgg_net.txt |
Q:
Why is the InverseMelScale torchaudio function so slow?
I am currently exploring and learning machine learning for music/audio generation and I am already failing in the first steps.
My idea is to use image-based learning algorithms on audio.
To do so, I want to convert the audio into a MEL spectrogram and then ap... | Why is the InverseMelScale torchaudio function so slow? | I am currently exploring and learning machine learning for music/audio generation and I am already failing in the first steps.
My idea is to use image-based learning algorithms on audio.
To do so, I want to convert the audio into a MEL spectrogram and then apply the machine learning stuff.
Then, when the model is trai... | [
"Currently, InverseMelScale is implemented as inference using SGD, that is inside of InverseMelScale, loss function is defined and optimizer run.\nThis implementation is not only inefficient, but also no accurate.\nFor the reason this implementation was picked, you can check out https://github.com/pytorch/audio/pul... | [
0
] | [] | [] | [
"gpu",
"python",
"pytorch",
"spectrogram"
] | stackoverflow_0074447735_gpu_python_pytorch_spectrogram.txt |
Q:
How can I get the text in a textbox in customtkinter?
I am building a text editor but I can't save the file because I can't get the text within the textbox. Even thought in the entry widget I can use .get() to get the text.
I tried .get() but it displays an error that it isn't an option.
A:
Customtkinter library... | How can I get the text in a textbox in customtkinter? | I am building a text editor but I can't save the file because I can't get the text within the textbox. Even thought in the entry widget I can use .get() to get the text.
I tried .get() but it displays an error that it isn't an option.
| [
"Customtkinter library is still under-development and it's getting updated consistently.\n.get() function support was added couple of days ago, you can now use it. Make sure your customtkinter library is up-to-date. (pip3 install customtkinter --upgrade)\nExample code:\nfrom pytube import *\nfrom tkinter import *\n... | [
0
] | [] | [] | [
"customtkinter",
"python",
"tkinter"
] | stackoverflow_0074616256_customtkinter_python_tkinter.txt |
Q:
How to read a big tif file in python?
I'm loading a tiff file from http://oceancolor.gsfc.nasa.gov/DOCS/DistFromCoast/
from PIL import Image
im = Image.open('GMT_intermediate_coast_distance_01d.tif')
The data is large (im.size=(36000, 18000) 1.3GB) and conventional conversion doesn't work; i.e, imarray.shape retu... | How to read a big tif file in python? | I'm loading a tiff file from http://oceancolor.gsfc.nasa.gov/DOCS/DistFromCoast/
from PIL import Image
im = Image.open('GMT_intermediate_coast_distance_01d.tif')
The data is large (im.size=(36000, 18000) 1.3GB) and conventional conversion doesn't work; i.e, imarray.shape returns ()
import numpy as np
imarray=np.zero... | [
"May you dont have too much Ram for this image.You'll need at least some more than 1.3GB free memory.\nI don't know what you're doing with the image and you read the entire into your memory but i recommend you to read it bit by bit if its possible to avoid blowing up your computer. \nYou can use Image.getdata() whi... | [
4,
3,
2,
1,
0
] | [] | [] | [
"numpy",
"python",
"python_imaging_library",
"tiff"
] | stackoverflow_0030465635_numpy_python_python_imaging_library_tiff.txt |
Q:
Blinking box when I attempt to execute my code
I am new to programming, and I am working with web scraping YouTube video using pytube. When I execute the code below, I get the boldly lined box. It seems to want some input but I'm not sure what to do next.
When I press 'enter' without typing anything else, I get th... | Blinking box when I attempt to execute my code | I am new to programming, and I am working with web scraping YouTube video using pytube. When I execute the code below, I get the boldly lined box. It seems to want some input but I'm not sure what to do next.
When I press 'enter' without typing anything else, I get the following error message:
https://www.youtube.com/R... | [
"https://www.youtube.com/RJH6_fx9aT8 isn't a valid YouTube URL, but https://www.youtube.com/watch?v=RJH6_fx9aT8 is a valid YouTube URL.\n"
] | [
0
] | [] | [] | [
"python",
"pytube",
"web_scraping",
"youtube"
] | stackoverflow_0074324936_python_pytube_web_scraping_youtube.txt |
Q:
How to make popouts with CTkInput encode
I'm working on password manager and had structure like that:
def popUp(text):
answer = simpledialocusg.askstring("input string", text)
return answer
And it works perfectly, but I want to make popouts looks better with Custom Tkinter. When I made
def popUp(text):
... | How to make popouts with CTkInput encode | I'm working on password manager and had structure like that:
def popUp(text):
answer = simpledialocusg.askstring("input string", text)
return answer
And it works perfectly, but I want to make popouts looks better with Custom Tkinter. When I made
def popUp(text):
answer = customtkinter.CTkInputDialog("inpu... | [
"You should check the wiki page before opening a question here.\nhttps://github.com/TomSchimansky/CustomTkinter/wiki/CTkInputDialog\nThe syntax should be like this:\ndef getInput():\n answer = customtkinter.CTkInputDialog(text = \"input string\")\n print(answer.get_input())\n\nroot = customtkinter.CTk()\n\nbu... | [
0
] | [] | [] | [
"customtkinter",
"python",
"tkinter"
] | stackoverflow_0074641655_customtkinter_python_tkinter.txt |
Q:
How to pin Youtube comments with python automatically
I need to find a way to pin comments in YouTube automatically. I have checked YouTube API v3 documentation but it does not have this feature. Is there any idea?
A:
To initialize the automatic mechanism, you first need to open your web-browser Web Developer To... | How to pin Youtube comments with python automatically | I need to find a way to pin comments in YouTube automatically. I have checked YouTube API v3 documentation but it does not have this feature. Is there any idea?
| [
"To initialize the automatic mechanism, you first need to open your web-browser Web Developer Tools Network tab, then pin an ad hoc comment, you should notice a XHR request to perform_comment_action endpoint. Right-click this request and copy it as cURL. Notice the last field actions in the JSON encoded --data-raw ... | [
0
] | [] | [] | [
"api",
"comments",
"python",
"youtube"
] | stackoverflow_0073444163_api_comments_python_youtube.txt |
Q:
Python - Adding Custom Values Into A Table From Web Scraping
I wrote a basic web scraper that returns values into nested lists like the one below:
results = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
But I want to add 2 custom values when they get pushed into the lists to look like something below:
result... | Python - Adding Custom Values Into A Table From Web Scraping | I wrote a basic web scraper that returns values into nested lists like the one below:
results = [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
But I want to add 2 custom values when they get pushed into the lists to look like something below:
results = [['customvalue1', 'customvalue2', 'a', 'b', 'c'], ['customvalu... | [
"One of the ways to achieve it in the case of python.\nimport datetime\n\n# Define customvalue2\ncustomvalue2 = \"mystring\"\n\nresults = []\n\n# Get current date\ntoday = datetime.datetime.now()\n\n# Loop over the data you want to add to the results list\nfor data in [['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', '... | [
0
] | [] | [] | [
"list",
"nested",
"python",
"web_scraping"
] | stackoverflow_0074672411_list_nested_python_web_scraping.txt |
Q:
"detail": "CSRF Failed: CCSRF token missing." when sending post data from angular 13 to django connected database
i need to send the post data from angular to DRF through angular form but geeting the error
i checked almost all the answers available on the internet but did not found and useful answer.
"detail": "C... | "detail": "CSRF Failed: CCSRF token missing." when sending post data from angular 13 to django connected database | i need to send the post data from angular to DRF through angular form but geeting the error
i checked almost all the answers available on the internet but did not found and useful answer.
"detail": "CSRF Failed: CSRF token missing."
//post logic sources.service.ts
import { Injectable } from '@angular/core';
import { ... | [
"(Partial answer)\nYou get this error message because the CSRF protection is activated by default and you don't send the CSRF token. Someone wrote a good description of what CSRF is here\nOn the first GET request, the server sends you the CSRF token in a cookie, and you have to send it back on every request, as a c... | [
0,
0
] | [
"you need to exempt csrf in views.py\nfrom django.views.decorators.csrf import csrf_exempt\n\nand then\n@csrf_exempt\ndef index(request):\npass\n\n"
] | [
-1
] | [
"angular",
"angular_fullstack",
"csrf",
"django",
"python"
] | stackoverflow_0074598711_angular_angular_fullstack_csrf_django_python.txt |
Q:
multiprocessing vs multithreading vs asyncio
I found that in Python 3.4 there are few different libraries for multiprocessing/threading: multiprocessing vs threading vs asyncio.
But I don't know which one to use or is the "recommended one". Do they do the same thing, or are different? If so, which one is used for ... | multiprocessing vs multithreading vs asyncio | I found that in Python 3.4 there are few different libraries for multiprocessing/threading: multiprocessing vs threading vs asyncio.
But I don't know which one to use or is the "recommended one". Do they do the same thing, or are different? If so, which one is used for what? I want to write a program that uses multicor... | [
"TL;DR\nMaking the Right Choice:\n\nWe have walked through the most popular forms of concurrency. But the question remains - when should choose which one? It really depends on the use cases. From my experience (and reading), I tend to follow this pseudo code:\n\nif io_bound:\n if io_very_slow:\n print(\"U... | [
247,
140,
74,
39,
25,
7,
1,
0,
0
] | [] | [] | [
"multiprocessing",
"multithreading",
"python",
"python_3.x",
"python_asyncio"
] | stackoverflow_0027435284_multiprocessing_multithreading_python_python_3.x_python_asyncio.txt |
Q:
How to filter the unique values
I have 900k rows and 10 unique values. First 100k rows have only one unique value remaining are after 100k rows. I want 100k rows with all the unique values from the 900k rows.
I cant able to find solution for this.
A:
A solution to the problem to this problem:
Use the set() func... | How to filter the unique values | I have 900k rows and 10 unique values. First 100k rows have only one unique value remaining are after 100k rows. I want 100k rows with all the unique values from the 900k rows.
I cant able to find solution for this.
| [
"A solution to the problem to this problem:\n\nUse the set() function to create a set of the unique values in your\ndata. This will remove any duplicates.\n\nUse the random.sample() function to select a random sample of 1 lakh (100000) items from the set of unique values.\n\nUse the random.shuffle() function to shu... | [
0
] | [] | [] | [
"filter",
"pandas",
"python",
"unique",
"unique_values"
] | stackoverflow_0074672464_filter_pandas_python_unique_unique_values.txt |
Q:
Python Pandas equivalent in JavaScript
With this CSV example:
Source,col1,col2,col3
foo,1,2,3
bar,3,4,5
The standard method I use Pandas is this:
Parse CSV
Select columns into a data frame (col1 and col3)
Process the column (e.g. avarage the values of col1 and col3)
Is there a JavaScript library that ... | Python Pandas equivalent in JavaScript | With this CSV example:
Source,col1,col2,col3
foo,1,2,3
bar,3,4,5
The standard method I use Pandas is this:
Parse CSV
Select columns into a data frame (col1 and col3)
Process the column (e.g. avarage the values of col1 and col3)
Is there a JavaScript library that does that like Pandas?
| [
"This wiki will summarize and compare many pandas-like Javascript libraries.\nIn general, you should check out the d3 Javascript library. d3 is very useful \"swiss army knife\" for handling data in Javascript, just like pandas is helpful for Python. You may see d3 used frequently like pandas, even if d3 is not exac... | [
193,
11,
8,
7,
7,
6,
3,
1,
1,
0
] | [] | [] | [
"javascript",
"pandas",
"python"
] | stackoverflow_0030610675_javascript_pandas_python.txt |
Q:
beautiful soup to grab data from table
I had recently asked for help using beautiful soup to grab forex prices from a site. the data was hidden in the span. I was lucky enough to get help from two people who were amazing and helped me work through it. I have since found a different site that i want to scrape from,... | beautiful soup to grab data from table | I had recently asked for help using beautiful soup to grab forex prices from a site. the data was hidden in the span. I was lucky enough to get help from two people who were amazing and helped me work through it. I have since found a different site that i want to scrape from, this time there is no span the text is in t... | [
"You hadn't added headers thus the request was fetching output for robots.\nFull Code\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nimport os\nresult = []\nheaders = {\n 'user-agent':\n 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074672389_beautifulsoup_python.txt |
Q:
CUDA atomicAdd being run too many times
I am trying to initialise a numpy matrix with a preset initial cache size, and then each CUDA thread with run atomicAdd at most once, hopefully as long as the accumulated sum is still within the initial cache size.
The problem here is that when the initial cache size (500) i... | CUDA atomicAdd being run too many times | I am trying to initialise a numpy matrix with a preset initial cache size, and then each CUDA thread with run atomicAdd at most once, hopefully as long as the accumulated sum is still within the initial cache size.
The problem here is that when the initial cache size (500) is smaller than the number of threads (1024), ... | [
"You changed several things, most incorrectly (e.g. you cannot do atomics on a local variable, you are not actually copying any results back to the host, etc.) in between your first and second postings, more than just the one thing I suggested you change.\nIf we start with your first listing, here are the changes I... | [
1
] | [] | [] | [
"cuda",
"python"
] | stackoverflow_0074662945_cuda_python.txt |
Q:
Failed to build ta-lib ERROR: Could not build wheels for ta-lib, which is required to install pyproject.toml-based project
I'm getting below error, while pip installing ta-lib.
I used command :
!pip install ta-lib
Please provide me solution.
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.d... | Failed to build ta-lib ERROR: Could not build wheels for ta-lib, which is required to install pyproject.toml-based project | I'm getting below error, while pip installing ta-lib.
I used command :
!pip install ta-lib
Please provide me solution.
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/
Collecting ta-lib
Using cached TA-Lib-0.4.25.tar.gz (271 kB)
Installing build dependencies ..... | [
"https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib\nin this web download ta-lib.whl and then pip install\ngotch\n"
] | [
0
] | [] | [] | [
"algorithmic_trading",
"artificial_intelligence",
"python",
"technical_indicator"
] | stackoverflow_0074651107_algorithmic_trading_artificial_intelligence_python_technical_indicator.txt |
Q:
I lose leading zeros when copy data from dataframe to openpyxl.workbook
I use openpyxl and pandas to fill row color with specified condition. Everything works fine but in some cells I lose leading zeros (like 0345 -> output 345), I don't want that. How can I get the exact data?
dt = pd.read_excel(file_luu, sheet_n... | I lose leading zeros when copy data from dataframe to openpyxl.workbook | I use openpyxl and pandas to fill row color with specified condition. Everything works fine but in some cells I lose leading zeros (like 0345 -> output 345), I don't want that. How can I get the exact data?
dt = pd.read_excel(file_luu, sheet_name="Sheet1")
dt = pd.DataFrame(dt)
dinhDanh = len(dt.columns) - 1
wb = load_... | [
"To prevent losing leading zeros when writing data to an Excel file with openpyxl and pandas, you can specify that the cell should be formatted as a string by setting the number_format property of the cell to @. This tells Excel that the cell should be treated as a string, and any leading zeros will be preserved.\n... | [
0
] | [] | [] | [
"openpyxl",
"pandas",
"python"
] | stackoverflow_0074672592_openpyxl_pandas_python.txt |
Q:
Python combinations of multiple list of different sizes
Am trying to swap items between multiple lists and I wanted to know if there is any method to generate combinations between multiple list of different size?
For example, I have this 3 lists:
a = [(0, 0), (1, 0), (2, 0)]
b = [(0, 2), (1, 2), (2, 2)]
c = [(0, 3... | Python combinations of multiple list of different sizes | Am trying to swap items between multiple lists and I wanted to know if there is any method to generate combinations between multiple list of different size?
For example, I have this 3 lists:
a = [(0, 0), (1, 0), (2, 0)]
b = [(0, 2), (1, 2), (2, 2)]
c = [(0, 3), (1, 3)]
Expected result:
a : [(0, 3), (0, 2), (0, 0)]
b :... | [
"Try\n\nadding None to your lists so that they all have the same length,\nuse sympy.utilities.iterables.multiset_permutations instead of,\nit.permutations, and\nfinally filter out None values from the output.\n\nThat should generalize in a natural way your approach for lists of equal sizes:\nimport itertools as it\... | [
0
] | [] | [] | [
"combinations",
"list",
"python",
"python_itertools"
] | stackoverflow_0074646518_combinations_list_python_python_itertools.txt |
Q:
How to take a sum (in denominator) for calculating group by weighted average in a dataframe?
I have a data frame that looks like this.
import pandas as pd
import numpy as np
data = [
['A',1,2,3,4],
['A',5,6,7,8],
['A',9,10,11,12],
['B',13,14,15,16],
['B',17,18,19,20],
['B',21,22,23,24],
['B',25,26,2... | How to take a sum (in denominator) for calculating group by weighted average in a dataframe? | I have a data frame that looks like this.
import pandas as pd
import numpy as np
data = [
['A',1,2,3,4],
['A',5,6,7,8],
['A',9,10,11,12],
['B',13,14,15,16],
['B',17,18,19,20],
['B',21,22,23,24],
['B',25,26,27,28],
['C',29,30,31,32],
['C',33,34,35,36],
['C',37,38,39,40],
['D',13,14,15,0],
['D',0... | [
"i edit your code little bit\nn = len(weights)\ndf=df.groupby('Name').agg(lambda g: sum(g*weights[n-len(g):])/sum(weights[n-len(g):]))\n\noutput(df):\n num1 num2 num3 num4\nName \nA 5.9 6.9 7.9 8.9\nB 21.0 22.0 23.0 24.0\nC 33.9 34.9 35.9 36.9\nD 1.3 ... | [
2,
0
] | [] | [] | [
"data_science_experience",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074672338_data_science_experience_dataframe_pandas_python.txt |
Q:
Can't get attribute to work on a method of a class
Putting the "self.budget" attribute on the buy method returns error 'Shopper' object has no attribute 'budget', this alsoo happense when calling the gifts list to append the additional gift bought through the buy method. As such, both the list of gifts is not adju... | Can't get attribute to work on a method of a class | Putting the "self.budget" attribute on the buy method returns error 'Shopper' object has no attribute 'budget', this alsoo happense when calling the gifts list to append the additional gift bought through the buy method. As such, both the list of gifts is not adjusted, the budget remains unchanged and the quantity is n... | [
"It looks like you've named both classes the same thing, and the first definition doesn't have the 'budget' attribute.\n"
] | [
0
] | [] | [] | [
"class",
"inheritance",
"methods",
"oop",
"python"
] | stackoverflow_0074672632_class_inheritance_methods_oop_python.txt |
Q:
How does a for loop inside of an array (square brackets) work?
I need to increase the size of a list using a for loop, and I figured out how to do it, I just don't understand the math and the logic behind it.
from random import randint()
random_values = randint(0,5)
size = 5
list = [ random_values for i in range(... | How does a for loop inside of an array (square brackets) work? | I need to increase the size of a list using a for loop, and I figured out how to do it, I just don't understand the math and the logic behind it.
from random import randint()
random_values = randint(0,5)
size = 5
list = [ random_values for i in range(size)]
This will create a list(array) with 5 random values. I just ... | [
"That's a \"list comprehension\" - a way of writing a for loop that generates a list. The term itself is from way back in the day, and I've never really comprehended why its called a comprehension, but lets just go with it.\nYou start with an iterable on the right side of the for and an expression on the left: [exp... | [
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0074672606_list_comprehension_python.txt |
Q:
Assign value numbers for alphabet in Python
I have alphabets that I want to assign as follows:
lowercase items a-z have value of 1-26
uppercase items A-Z have value of 27-52
What is the shortest way to implement this
[a,B,h,R]
Expected Output:
[1,28,8,44]
How can we go about doing this in Python
Thank you
A:
The... | Assign value numbers for alphabet in Python | I have alphabets that I want to assign as follows:
lowercase items a-z have value of 1-26
uppercase items A-Z have value of 27-52
What is the shortest way to implement this
[a,B,h,R]
Expected Output:
[1,28,8,44]
How can we go about doing this in Python
Thank you
| [
"The python string module is perfect for this.\nfrom string import ascii_letters\nprint([ascii_letters.index(letter) + 1 for letter in [\"a\", \"B\", \"h\", \"R\"]])\n\n",
"I think I recognize an Advent of Code question! I developed the alphabet to score mapping as follows:\nimport string\nfrom collections import... | [
3,
1,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074672541_list_python_python_3.x.txt |
Q:
ERROR:root:can't pickle fasttext_pybind.fasttext objects
I am using gunicorn with multiple workers for my machine learning project. But the problem is when I send a train request only the worker getting the training request gets updated with the latest model after training is done. Here it is worth to mention that... | ERROR:root:can't pickle fasttext_pybind.fasttext objects | I am using gunicorn with multiple workers for my machine learning project. But the problem is when I send a train request only the worker getting the training request gets updated with the latest model after training is done. Here it is worth to mention that, to make the inference faster I have programmed to load the m... | [
"For the sake of completeness I am providing the solution that worked for me. All the approaches I have tried to serialize FastText went in vain. Finally, as @MedetTleukabiluly mentioned in the comment, I managed to share the message of loading the model from the disk with other workers with redis-pubsub. Obviously... | [
0
] | [] | [] | [
"dill",
"fasttext",
"gunicorn",
"multiprocessing",
"python"
] | stackoverflow_0069430747_dill_fasttext_gunicorn_multiprocessing_python.txt |
Q:
Gaurd Node in torrc file
Hello I have some questions related to tor.
How to disable Guard node in torrc file or by using stem
Is there any method in stem where I can specify my Exit Node. I know a method in torrc file but I don't know how to do it in stem or using controler. for example.
I want this because I wa... | Gaurd Node in torrc file | Hello I have some questions related to tor.
How to disable Guard node in torrc file or by using stem
Is there any method in stem where I can specify my Exit Node. I know a method in torrc file but I don't know how to do it in stem or using controler. for example.
I want this because I want my entry node to be change ... | [
"To disable Guard nodes in the torrc file, you can add the following lines:\nUseEntryGuards 0\nNumEntryGuards 0\n\nTo specify an Exit node in the torrc file, you can add the following line:\nExitNodes $fingerprint\n\nwhere $fingerprint is the fingerprint of the Exit node you want to use.\nYou can use the set_option... | [
0
] | [] | [] | [
"python",
"python_3.x",
"stem"
] | stackoverflow_0074672521_python_python_3.x_stem.txt |
Q:
problem password_reset_key_message.txt` - dj-rest-auth
I'm creating a project (an api), but I'm stuck on the next part.
When sending the password reset mail, specifically password_reset_key_message.txt, I can't capture the user's 'key' and 'uid', I want to change the address.
Email delivery work fine, my problem i... | problem password_reset_key_message.txt` - dj-rest-auth | I'm creating a project (an api), but I'm stuck on the next part.
When sending the password reset mail, specifically password_reset_key_message.txt, I can't capture the user's 'key' and 'uid', I want to change the address.
Email delivery work fine, my problem is with password_reset_key_message.txt.
Packages
django==4.0.... | [
"To resolve this issue, I did the following:\n\nIn the settings.py of the main project, add a custom_password_serializer:\n\nconfig/settings.py\n\nREST_AUTH_SERIALIZERS = {\n 'PASSWORD_RESET_SERIALIZER': 'myapp.serializers.CustomPasswordResetSerializer'\n}\n\n\n\nCreate the custom_password_serializer:\n\nconfig... | [
0
] | [] | [] | [
"api",
"dj_rest_auth",
"django_allauth",
"python"
] | stackoverflow_0073476094_api_dj_rest_auth_django_allauth_python.txt |
Q:
python parallel and join threading not working?
I need to run parallel and join threads in the following code:
`
from threading import Thread
import time
def do_stuff(i):
if i == 1:
time.sleep(1)
if i ==2:
time.sleep(2)
if i ==3:
time.sleep(3)
print(i)
time.sleep(1)... | python parallel and join threading not working? | I need to run parallel and join threads in the following code:
`
from threading import Thread
import time
def do_stuff(i):
if i == 1:
time.sleep(1)
if i ==2:
time.sleep(2)
if i ==3:
time.sleep(3)
print(i)
time.sleep(1)
def thread1(i):
worker1 = Thread(target = do_st... | [
"To run threads in parallel, you can use the Thread.start() method, which starts the execution of the thread's target function. The join() method, on the other hand, is used to wait for a thread to complete its execution.\nIn your code, you are starting three threads in the main thread, and then calling join() on e... | [
0
] | [] | [] | [
"python",
"python_multithreading"
] | stackoverflow_0074672671_python_python_multithreading.txt |
Q:
How to test for a reference cycle caused by saved exception?
I'm talking about this problem: https://bugs.python.org/issue36820.
Small summary:
Saving an exception causes a cyclic reference, because the exception's data include a traceback containing the stack frame with the variable where the exception was saved.... | How to test for a reference cycle caused by saved exception? | I'm talking about this problem: https://bugs.python.org/issue36820.
Small summary:
Saving an exception causes a cyclic reference, because the exception's data include a traceback containing the stack frame with the variable where the exception was saved.
try:
1/0
except Exception as e:
ee = e
The code is not b... | [
"Yes, using the gc module, we can check whether there are (new) exceptions that are only referred to by a traceback frame.\nIn practice, iterating gc objects creates an additional referrer (can't use WeakSet as built-in exceptions don't support weakref), so we check that there are two referrers — the frame and the ... | [
2
] | [
"I believe you can use the gc module to do something like this.\nimport gc\n\n# First, enable garbage collection\ngc.enable()\n\n# Save an exception to a variable\nexception = Exception('test exception')\n\n# Check for objects that are no longer being referenced by the program\nif gc.garbage:\n # Print the objects... | [
-1
] | [
"garbage_collection",
"python"
] | stackoverflow_0067157372_garbage_collection_python.txt |
Q:
How can I get the source of chat without using selenium?
So my issue is that, I want to get user's id info from the chat.
The chat area what I'm looking for, looks like this...
<div id="chat_area" class="chat_area" style="will-change: scroll-position;">
<dl class="" user_id="asdf1234"><dt class="user_m"><em class=... | How can I get the source of chat without using selenium? | So my issue is that, I want to get user's id info from the chat.
The chat area what I'm looking for, looks like this...
<div id="chat_area" class="chat_area" style="will-change: scroll-position;">
<dl class="" user_id="asdf1234"><dt class="user_m"><em class="pc"></em> :</dt><dd id="1">blah blah</dd></dl>
<a href="javas... | [
"It looks like you've got two separate problems here. I'd use both the requests and BeautifulSoup libraries to accomplish this.\nUse your browser's developer tools, the network tab, to refresh the page and look for the request which responds with the HTML you want. Use the requests library to emulate this request e... | [
0,
0
] | [] | [] | [
"html",
"python",
"python_requests",
"selenium"
] | stackoverflow_0074672630_html_python_python_requests_selenium.txt |
Q:
How to use the first row as keys in excel for python selenium
I am making auto login tool on selenium, i want it to use row by row to get login information. I used this code to do it but it only uses the 28th row. Is there a way for it to automatically get the data from the first row to the next to the next?
Thank... | How to use the first row as keys in excel for python selenium | I am making auto login tool on selenium, i want it to use row by row to get login information. I used this code to do it but it only uses the 28th row. Is there a way for it to automatically get the data from the first row to the next to the next?
Thank u all!
from selenium import webdriver
from selenium.webdriver.comm... | [
"Do you mean\nfor i in range(2,29): \n\ndoesn't cover the range of rows in the sheet. So you could increase 29 to max that is needed. Or you can use\nSheet1.max_row\n\nto get the max row number (last row in sheet with data) except you need to create the worksheet (ws) object to get that value.\nFrom your code it lo... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"python",
"python_3.x",
"selenium_chromedriver"
] | stackoverflow_0074668602_excel_openpyxl_python_python_3.x_selenium_chromedriver.txt |
Q:
'int' and 'str' mistake
enter image description here
bank_account = None
highest = 0
for account, amount in accounts.items():
if amount > highest: -------------<
bank_account = account
highest = account
print(bank_acount, highest)
TypeError: '>' not supported between... | 'int' and 'str' mistake | enter image description here
bank_account = None
highest = 0
for account, amount in accounts.items():
if amount > highest: -------------<
bank_account = account
highest = account
print(bank_acount, highest)
TypeError: '>' not supported between instances of 'int' and 'str'... | [
"Either 'account' or 'highest' is a string, you need to determine which one and adjust your code.\nIf the string is the string form of a number, i.e. \"1\", you can use int(\"1\") to get the int form.\n",
"I believe you have a typo in the line that says:\n\nhighest = account\n\nLooks like you wanted that line to ... | [
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074672798_python_python_3.x.txt |
Q:
How to tail a log file with timestamps and count occurrences in the last X seconds
I have a log files that I read/stream into Python (it contains timestamp and data) using tail.
I need a way to see if, in the last 10 seconds, how many lines were seen/observed based on a filter (e.g. line contains "error")
I'll be ... | How to tail a log file with timestamps and count occurrences in the last X seconds | I have a log files that I read/stream into Python (it contains timestamp and data) using tail.
I need a way to see if, in the last 10 seconds, how many lines were seen/observed based on a filter (e.g. line contains "error")
I'll be checking every X seconds to see how many lines were present for "error" or "debug" etc..... | [
"This is a quite simple solution that looks at the current timestamp (I hardcoded the timestamp to follow the timestamps from your example but you can use datetime.datetime.now() instead).\nSimply put, the following was done:\n\nI made a file called test.log with the exact contents of that python tails piece of tex... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074444395_python.txt |
Q:
How to graph a mathematical function for "Distance and Speed over Time" in Python?
I'm struggling with some Python homework.
I'm really new to Python, and coding in general. I have really basic knowledge in Python, and somewhat acceptable level in JavaScript.
My issue: I have to make a graph to represent these two... | How to graph a mathematical function for "Distance and Speed over Time" in Python? | I'm struggling with some Python homework.
I'm really new to Python, and coding in general. I have really basic knowledge in Python, and somewhat acceptable level in JavaScript.
My issue: I have to make a graph to represent these two functions:
distance = (x**2/2 - np.cos(5*x) - 7)
speed = (x + 5*np.sin(5*x))
Between ... | [
"It looks like your code is almost there! You have imported all of the necessary libraries, and you have defined your distance and speed functions correctly.\nTo make your code work, you need to specify the range of values that you want to use for the x-axis of your graph. In this case, you want to use the values b... | [
0,
0
] | [] | [] | [
"graph",
"matplotlib",
"numpy",
"pandas",
"python"
] | stackoverflow_0074671475_graph_matplotlib_numpy_pandas_python.txt |
Q:
What does builder do that python code doesn't?
When I use builder, the program outputs information from qr codes to the lower half of the application, but it is necessary to replace the built code with an equivalent python code, immediately information about qr codes ceases to be output
With builder:
`
from kivy.a... | What does builder do that python code doesn't? | When I use builder, the program outputs information from qr codes to the lower half of the application, but it is necessary to replace the built code with an equivalent python code, immediately information about qr codes ceases to be output
With builder:
`
from kivy.app import App
from kivy.uix.boxlayout import BoxLayo... | [
"The kivy language sets up bindings for you that the pure python does not. So your line in the kv:\ntext: ', '.join([str(symbol.data) for symbol in zbarcam.symbols])\n\nsets up binding to zbarcam.symbols so that the text is updated whenever zbarcam.symbols changes.\nAnd in the python code:\ntext=', '.join([str(sym... | [
0
] | [] | [] | [
"barcode",
"kivy",
"kivy_language",
"python",
"qr_code"
] | stackoverflow_0074669847_barcode_kivy_kivy_language_python_qr_code.txt |
Q:
Getting Element Not Interactable Exception after attempting to insert search query into YouTube input field
I'm just beginning to explore Python and automation testing
Wanted to create a quick script that will:
Open a YouTube page
Find the search input field where I will insert my search query
Insert a search que... | Getting Element Not Interactable Exception after attempting to insert search query into YouTube input field | I'm just beginning to explore Python and automation testing
Wanted to create a quick script that will:
Open a YouTube page
Find the search input field where I will insert my search query
Insert a search query into the field
Press on the button to receive search results
Unfortunately Ive bumped into an error:
"seleniu... | [
"Instead of searching the Input field using the absolute xpath you can use the id properties of the element i.e search and similarly to click on the search icon to resolve the error.\nNote:- We will have to specify the input tag along with the id since the page contains couple of element with id as as search\nYour ... | [
0
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0074662142_python_selenium.txt |
Q:
How can I remove all vowels from an inputted string
This doesn't really work
To explain what I did:
I set a vowel variable with a list
Then I used a for loop to iterate through the list and print the letters not in the list
A:
as user @user56700 noted: You did, probably by mistake:
if not letter.lower in vowels:... | How can I remove all vowels from an inputted string | This doesn't really work
To explain what I did:
I set a vowel variable with a list
Then I used a for loop to iterate through the list and print the letters not in the list
| [
"as user @user56700 noted: You did, probably by mistake:\nif not letter.lower in vowels:\n\ninstead:\nif not letter.lower() in vowels:\n\nfirst is method \"itself\", second is call of method.\nP.S.\nalso, as user @user56700 noted, do not screenshot and paste code as image. Just paste and format as code, it is reall... | [
0,
0
] | [
"import re\nvowel = input()\nlst = re.sub(\"[aeiouAEIOU]\",\"\",vowel)\nprint(lst)\n"
] | [
-1
] | [
"list",
"python",
"string"
] | stackoverflow_0074670665_list_python_string.txt |
Q:
How Do I Add Subtitles to a Video in Python
If I have a script.txt which contains all the things said in the video and the video itself then how do I dynamically add subtitles to the video using python.
A:
To add subtitles to a video using python, you can use the moviepy library. Here is an example of how you ca... | How Do I Add Subtitles to a Video in Python | If I have a script.txt which contains all the things said in the video and the video itself then how do I dynamically add subtitles to the video using python.
| [
"To add subtitles to a video using python, you can use the moviepy library. Here is an example of how you can do this:\nfrom moviepy.editor import *\n\n# Open the video\nvideo = VideoFileClip('video.mp4')\n\n# Read the script from the text file\nwith open('script.txt', 'r') as f:\n script = f.read()\n\n# Add the... | [
2
] | [] | [] | [
"python",
"video_subtitles"
] | stackoverflow_0074672952_python_video_subtitles.txt |
Q:
How can we print a list of numbers taken as [1,2,3,4,5] in a column one by one such that the output should be as 1 2 3 4 5
i had written a piece of code expecting the output as
1
2
3
4
5
but i am unable to get that with my code
for num in numlist:
print(num)
print(num,end=' ')
1
1 2
2 3
3 4
4 5
5
for num in numli... | How can we print a list of numbers taken as [1,2,3,4,5] in a column one by one such that the output should be as 1 2 3 4 5 | i had written a piece of code expecting the output as
1
2
3
4
5
but i am unable to get that with my code
for num in numlist:
print(num)
print(num,end=' ')
1
1 2
2 3
3 4
4 5
5
for num in numlist:
print(num)
print(num,end=' ')
1
2
3
4
5
5
can i know when i am executing it separately without indentation i am getting 5 5... | [] | [] | [
"You can use list comprehension to get a list of strings, and then use join to get a string and print it.\nstrlist = [str(x) for x in numlist] \noutstr = \"\\n\".join(strlist) \nprint(outstr) \n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074672938_python.txt |
Q:
An efficient way to search elements in a Json array (dictionary of arrays)
I am writing a script that reads two Json files into dictionaries
The dictionaries are more or less similar, like this
{ "elements":[
{
"element_id":0,
"thedata":{
"this": 5
}
},
{
... | An efficient way to search elements in a Json array (dictionary of arrays) | I am writing a script that reads two Json files into dictionaries
The dictionaries are more or less similar, like this
{ "elements":[
{
"element_id":0,
"thedata":{
"this": 5
}
},
{
"element_id":4,
"thedata":{
"this": 5
}
... | [
"If you need to find multiple elements with a particular element_id in a dictionary, and you want to do it as efficiently as possible, you could use a dictionary to store the elements with a given element_id. Then, when you need to find an element with a particular element_id, you can just look it up in the diction... | [
1,
1
] | [] | [] | [
"dictionary",
"json",
"python"
] | stackoverflow_0074672767_dictionary_json_python.txt |
Q:
big-O-calculator: AttributeError: 'list' object has no attribute 'lower'
I'm trying to calculate the speed of two functions that I have, this one uses quick sort method. I am using this page to download and use the big O calculator, and test the speed using this. But when I try to execute it, it throws me this err... | big-O-calculator: AttributeError: 'list' object has no attribute 'lower' | I'm trying to calculate the speed of two functions that I have, this one uses quick sort method. I am using this page to download and use the big O calculator, and test the speed using this. But when I try to execute it, it throws me this error: AttributeError: 'list' object has no attribute 'lower'. I'm not sure why, ... | [
"Big0 test func parameters:\ndef test(**args):\n functionName [Callable]: a function to call.\n array [str]: \"random\", \"big\", \"sorted\", \"reversed\", \"partial\", \"Ksorted\", \"string\", \"almost_equal\", \"equal\", \"hole\".\n limit [bool] = True: To break before it takes \"forever\" to sort an arr... | [
0
] | [] | [] | [
"big_o",
"python",
"quicksort"
] | stackoverflow_0074672974_big_o_python_quicksort.txt |
Q:
320 Error after IBApi.EClient.placeOrder() in Python & Interactive Brokers
I am trying to place an order through Interactive Brokers' Python API but receive the error:
ERROR 1 320 Error reading request: Unable to parse data.
java.lang.NumberFormatException: For input string:
"1.7976931348623157e+308"
Connecting ... | 320 Error after IBApi.EClient.placeOrder() in Python & Interactive Brokers | I am trying to place an order through Interactive Brokers' Python API but receive the error:
ERROR 1 320 Error reading request: Unable to parse data.
java.lang.NumberFormatException: For input string:
"1.7976931348623157e+308"
Connecting and retrieving data works fine but when submitting an order, one of my parameter... | [
"Using TWS 10.20.1d and API_Version=10.20.01 I find your code works with only a minor change with nextValidOrderId.\nSuggest checking API version, and upgrading if not latest version.\n"
] | [
0
] | [] | [] | [
"interactive_brokers",
"java",
"python"
] | stackoverflow_0074632771_interactive_brokers_java_python.txt |
Q:
Python Pandas - KeyError: 'username' : when username exist its showing key error when I am Trying to slice users data from csv who logged in
I am a beginner in python and working with python pandas.
I have created a program a demo of payment gateway system .
It contains a login page and signup page .
I want to dis... | Python Pandas - KeyError: 'username' : when username exist its showing key error when I am Trying to slice users data from csv who logged in | I am a beginner in python and working with python pandas.
I have created a program a demo of payment gateway system .
It contains a login page and signup page .
I want to display the main page when valid user logs in
after that I want to extract the data of the only valid user
in the form of Data Frame for a Function T... | [
"user = \"Ramesh\"\na = p_csv.query(\"username == @user\")\nprint(a)\n\n username password Name email Phone\n0 Ramesh Ramesh123 Ramesh Chaurasiya rams@gmail.com 1234567890\n\n"
] | [
0
] | [] | [] | [
"csv",
"keyerror",
"pandas",
"python",
"slice"
] | stackoverflow_0074672980_csv_keyerror_pandas_python_slice.txt |
Q:
Python Trouble Parsing a .max translated to OLE File => output unreadable in text format
The following script outputs files unreadable in .txt format. Please advise.
I inspired myself with: https://area.autodesk.com/m/drew.avis/tutorials/writing-and-reading-3ds-max-scene-sidecar-data-in-python
This is to replicate... | Python Trouble Parsing a .max translated to OLE File => output unreadable in text format | The following script outputs files unreadable in .txt format. Please advise.
I inspired myself with: https://area.autodesk.com/m/drew.avis/tutorials/writing-and-reading-3ds-max-scene-sidecar-data-in-python
This is to replicate a macho shark into a mechanical robot.
import olefile
# set this to your file
f = r'C:\MRP\Sh... | [
"Try opening in binary mode instead of text mode\n"
] | [
0
] | [] | [] | [
"3dsmax",
"python"
] | stackoverflow_0074673023_3dsmax_python.txt |
Q:
TypeError: listdir: path should be string, bytes, os.PathLike or None, not Namespace
I am using Python 3.9, PyCharm 2022.
My purpose (Ultimate goal of this question): create a command line application receive 2 parameters:
Path of directory
Extension of files
then get size of files (Per file size, not sum of fil... | TypeError: listdir: path should be string, bytes, os.PathLike or None, not Namespace | I am using Python 3.9, PyCharm 2022.
My purpose (Ultimate goal of this question): create a command line application receive 2 parameters:
Path of directory
Extension of files
then get size of files (Per file size, not sum of files size).
import os
import argparse
from os import listdir
from os.path import isfile, joi... | [
"The os module holds the traditional interface into the file system. It closely follows the Clib interface so you'll see functions like listdir and stat. pathlib is a new object oriented \"pythonic\" interface to the file system. One can argue whether its better, but I use it, so its gotta be, right?\nIt looks like... | [
1,
0,
0
] | [
"Your two command line arguments are being returned as a single object of the argparse.Namespace class, both stored identically in your args1 and (the superfluous) args2 variables.\nInserting the following line after your calls to parse_args() and commenting out the subsequent code would illuminate this a little mo... | [
-1
] | [
"python"
] | stackoverflow_0074672824_python.txt |
Q:
I can't understand what's wrong - Python multiple text replace dictionary
I can't understand what happen. I'm trying to make this script to replace multiple text files using a list of pairs, but only the first pair is working, the others are not processed. Did I make any mistakes in the loops?
replacements = [
... | I can't understand what's wrong - Python multiple text replace dictionary | I can't understand what happen. I'm trying to make this script to replace multiple text files using a list of pairs, but only the first pair is working, the others are not processed. Did I make any mistakes in the loops?
replacements = [
('Dog', 'Cat'),
('Lazy', 'Smart'),
('Fat', 'Slim'),
]
import re
impor... | [
"The double for loop is causing the issue. Reading the file contents only once fixes the issue.\nreplacements = [\n ('Dog', 'Cat'),\n ('Lazy', 'Smart'),\n ('Fat', 'Slim'),\n]\n\nimport re\nimport sys\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2 or len(sys.argv) > 4:\n print(\"Invalid ... | [
0
] | [] | [] | [
"list",
"python",
"replace",
"text"
] | stackoverflow_0074672969_list_python_replace_text.txt |
Q:
Validate if my mini project game can be past through Test_Python.py?
So basically i am creating my version of rock ,paper, scissor game as a python project and i need help running it through by testing or passing it which i forgot how to becuase i took a few days break working on my project and forgot how to test ... | Validate if my mini project game can be past through Test_Python.py? | So basically i am creating my version of rock ,paper, scissor game as a python project and i need help running it through by testing or passing it which i forgot how to becuase i took a few days break working on my project and forgot how to test it and this is my project:
import random
import math
def play():
user... | [
"I believe you're talking about writing unit tests. There are two libraries commonly used for unit testing in Python, the built in unittest library and the third-party pytest.\nI would personally recommend that you use pytest because the syntax is much simpler. Refer to the unittest and pytest docs for further usag... | [
0
] | [] | [] | [
"project",
"python",
"unit_testing"
] | stackoverflow_0074673060_project_python_unit_testing.txt |
Q:
How do I create a magic square matrix using python
A basket is given to you in the shape of a matrix. If the size of the matrix is N x N then the range of number of eggs you can put in each slot of the basket is 1 to N2 . You task is to arrange the eggs in the basket such that the sum of each row, column and the d... | How do I create a magic square matrix using python | A basket is given to you in the shape of a matrix. If the size of the matrix is N x N then the range of number of eggs you can put in each slot of the basket is 1 to N2 . You task is to arrange the eggs in the basket such that the sum of each row, column and the diagonal of the matrix remain same
This code is working o... | [
"def matrix(n): \nm = [[0 for x in range(n)] \n for y in range(n)]\ni = n / 2\nj = n - 1\nnum = 1\nwhile num <= (n * n): \n if i == -1 and j == n:\n j = n - 2\n i = 0\n else:\n if j == n: \n j = 0 \n if i < 0: \n i = n - 1\n if m[int(i)][in... | [
0
] | [] | [] | [
"computer_science",
"magic_square",
"matrix",
"python",
"python_3.x"
] | stackoverflow_0074384748_computer_science_magic_square_matrix_python_python_3.x.txt |
Q:
Get confidence interval from sklearn linear regression in python
I want to get a confidence interval of the result of a linear regression. I'm working with the boston house price dataset.
I've found this question:
How to calculate the 99% confidence interval for the slope in a linear regression model in python?
Ho... | Get confidence interval from sklearn linear regression in python | I want to get a confidence interval of the result of a linear regression. I'm working with the boston house price dataset.
I've found this question:
How to calculate the 99% confidence interval for the slope in a linear regression model in python?
However, this doesn't quite answer my question.
Here is my code:
import ... | [
"I am not sure if there is any in-built function for this purpose, but what I do is create a loop on n no. of times and compare the accuracy of all the models and save the model with highest accuracy with pickle and use reuse it later.\nHere goes the code:\nfor _ in range(30):\nx_train, x_test, y_train, y_test = sk... | [
0,
0
] | [] | [] | [
"linear_regression",
"python",
"scikit_learn"
] | stackoverflow_0061292464_linear_regression_python_scikit_learn.txt |
Q:
cant enter password in twine pypi package upload
PS D:\Python> cd ClockBlock
PS D:\Python\ClockBlock> python3 -m twine upload --repository testpypi dist/*
Uploading distributions to https://test.pypi.org/legacy/
Enter your username: MYNAME
Enter your password:
Desc for img
I cant enter anything in password, can s... | cant enter password in twine pypi package upload | PS D:\Python> cd ClockBlock
PS D:\Python\ClockBlock> python3 -m twine upload --repository testpypi dist/*
Uploading distributions to https://test.pypi.org/legacy/
Enter your username: MYNAME
Enter your password:
Desc for img
I cant enter anything in password, can someone help, i bashed a bunch of keys and it didnt out... | [] | [] | [
"SO.. it just didnt show the password for privacy reasons it underastood what i was typing though\n"
] | [
-1
] | [
"pypi",
"python",
"python_3.x",
"python_packaging",
"twine"
] | stackoverflow_0074672962_pypi_python_python_3.x_python_packaging_twine.txt |
Q:
I want to solve this question but I am finding some difficulty help me to find the solution
Help me to find out the solution of this question
Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her g... | I want to solve this question but I am finding some difficulty help me to find the solution | Help me to find out the solution of this question
Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.
Function Description
average has the following parameters:
int arr: an array of intege... | [
"I think giving you the answer would probably defeat the purpose of the question, but I'll try to reframe the crux of the problem:\nThe height of each plant may be repeated multiple times in the input array, we need to make sure that we only count each height once when computing the total height.\nThere exists a da... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074673111_python.txt |
Q:
How to split a string but keep multiple delimiters with the original chunk
Say my string is
st = 'Walking happened at 8 am breakfast happened at 9am baseball happened at 12 pm lunch happened at 1pm'
I would like to split on 'am' or 'pm', but I want those deliminters to be a part of the original chunk.
So the desi... | How to split a string but keep multiple delimiters with the original chunk | Say my string is
st = 'Walking happened at 8 am breakfast happened at 9am baseball happened at 12 pm lunch happened at 1pm'
I would like to split on 'am' or 'pm', but I want those deliminters to be a part of the original chunk.
So the desired result is
splitlist = ['Walking happened at 8 am',
'breakfast h... | [
"You can use a lookbehind:\nimport re\n\nsplitlist = re.split(r'(?<=[ap]m)\\s+', st)\n\nOutput:\n['Walking happened at 8 am',\n 'breakfast happened at 9am',\n 'baseball happened at 12 pm',\n 'lunch happened at 1pm']\n\nIf you want to ensure having a word boundary or a digit before am/pm (i.e not splitting after wor... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0074673121_python.txt |
Q:
How to extract all timestamps of badminton shot sound in an audio clip using Neural Networks?
I am trying to find the instances in a source audio file taken from a badminton match where a shot was hit by either of the players. For the same purpose, I have marked the timestamps with positive (hit sounds) and negati... | How to extract all timestamps of badminton shot sound in an audio clip using Neural Networks? | I am trying to find the instances in a source audio file taken from a badminton match where a shot was hit by either of the players. For the same purpose, I have marked the timestamps with positive (hit sounds) and negative (no hit sound: commentary/crowd sound etc) labels like so:
shot_timestamps = [0,6.5,8, 11, 18.5,... | [
"To improve the model, some possible solutions are:\n\nAdjust the window size for the snippets you are creating.\nIncrease the number of data points.\nAugment your existing data with additional data.\nTry different architectures, such as convolutional neural networks and recurrent neural networks.\nTry different fe... | [
3,
2,
0,
0,
0,
0,
0
] | [] | [] | [
"audio",
"deep_learning",
"librosa",
"machine_learning",
"python"
] | stackoverflow_0074471111_audio_deep_learning_librosa_machine_learning_python.txt |
Q:
how to avoid a type error when finding the median of a list
I am working on a project to get the mean, median and mode of a list. I have it almost all down but the median function is giving me the following error:
return (list[midIndex]+list[midIndex-1])/2.0
TypeError: list indices must be integers or slices, not... | how to avoid a type error when finding the median of a list | I am working on a project to get the mean, median and mode of a list. I have it almost all down but the median function is giving me the following error:
return (list[midIndex]+list[midIndex-1])/2.0
TypeError: list indices must be integers or slices, not float
def median(list):
if len(list) == 0:
return 0
... | [
"Try this to see that len division by two will result in a float type and can't be used as an index (python error message is clear).\nlist = {1,2,3,4}\nmidIndex = len(list)/2\nprint(f\"midIndex = {midIndex}\")\nprint(type(midIndex))\n\nOutput:\nmidIndex = 2.0\n<class 'float'>\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074673114_python.txt |
Q:
How to run a function periodically with Flask and Celery?
I have a flask app that roughly looks like this:
app = Flask(__name__)
@app.route('/',methods=['POST'])
def foo():
data = json.loads(request.data)
# do some stuff
return "OK"
Now in addition I would like to run a function every ten seconds from t... | How to run a function periodically with Flask and Celery? | I have a flask app that roughly looks like this:
app = Flask(__name__)
@app.route('/',methods=['POST'])
def foo():
data = json.loads(request.data)
# do some stuff
return "OK"
Now in addition I would like to run a function every ten seconds from that script. I don't want to use sleep for that. I have the foll... | [
"Do you have Celery worker and Celery beat running? Scheduled tasks are handled by beat, which queues the task mentioned when appropriate. Worker then actually crunches the numbers and executes your task.\ncelery worker --app myproject--loglevel=info\ncelery beat --app myproject\n\nYour task however looks like it's... | [
11,
5,
4,
0
] | [] | [] | [
"celery",
"flask",
"python"
] | stackoverflow_0028761750_celery_flask_python.txt |
Q:
@ changing to %40
I am using sqlalchemy and creating the url using
url = url.URL(
drivername,
host,
username,
password,
database)
this does not work
url = url.URL(
drivername='mysql+pymysql',
h... | @ changing to %40 | I am using sqlalchemy and creating the url using
url = url.URL(
drivername,
host,
username,
password,
database)
this does not work
url = url.URL(
drivername='mysql+pymysql',
host='abc.com',
... | [
"To avoid encoding of special characters in the password when creating a SQLAlchemy engine URL, you can use the quote() method from the urllib.parse module to encode the password before passing it to the url.URL() method.\nimport sqlalchemy as sa\nfrom urllib.parse import quote\n\n# Create the URL object with the e... | [
0
] | [] | [] | [
"database",
"python",
"python_unicode",
"sqlalchemy",
"unicode"
] | stackoverflow_0074673195_database_python_python_unicode_sqlalchemy_unicode.txt |
Q:
How to implement a numpy equation in the call of a tensorflow layer for a tensorflow model (Cannot convert a symbolic tf.Tensor to a numpy array)
I have this layer class in tensorflow where i want to implement a specific equation in numpy for the return in the call function. I have this following custom layer:
cla... | How to implement a numpy equation in the call of a tensorflow layer for a tensorflow model (Cannot convert a symbolic tf.Tensor to a numpy array) | I have this layer class in tensorflow where i want to implement a specific equation in numpy for the return in the call function. I have this following custom layer:
class PhysicalLayer(keras.layers.Layer):
def __init__(self, units=32):
super(PhysicalLayer, self).__init__()
self.units = units
d... | [
"Use tf.math.reduce_max to get the maximum of a tensor:\n def call(self, inputs):\n rotationSpeedSquare = tf.math.square(rotationSpeed)\n maximumVibration = tf.math.reduce_max(inputs, axis=1, keepdims=True)\n\n stiff = rotationSpeedSquare / maximumVibration\n return tf.matmul(stiff, s... | [
0
] | [] | [] | [
"keras",
"layer",
"python",
"tensorflow"
] | stackoverflow_0074670055_keras_layer_python_tensorflow.txt |
Q:
running a test script for multiple URLs in multiple browsers (local) in selenium python
I have a test script that I want to be run for multiple URLs on multiple browsers (Chrome and Firefox) locally on my machine. Every browser has to open all the URLs for the test script. I have run the test script for multiple U... | running a test script for multiple URLs in multiple browsers (local) in selenium python | I have a test script that I want to be run for multiple URLs on multiple browsers (Chrome and Firefox) locally on my machine. Every browser has to open all the URLs for the test script. I have run the test script for multiple URLs, but I'm confused about how to do it for multiple browsers. I have checked stuff online b... | [
"Create a list with the drivers and then execute your script in the for loop:\ndrivers = [webdriver.Chrome(), webdriver.Firefox()]\n\nfor Driver in drivers:\n def localitems():\n local_storage = Driver.execute_script( \\\n \"var ls = window.localStorage, items = {}; \" \\\n \"for (va... | [
0
] | [] | [] | [
"browser_automation",
"cross_browser",
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074672023_browser_automation_cross_browser_python_selenium_selenium_webdriver.txt |
Q:
List of numbers have same data but different sum
I have two lists of numbers. After comparing them, they are same but there sum is different.
You can get the script here: https://mega.nz/file/dHgHEQQA#9k9s86hgGH_vWrcE8J6ixYdu3GYkfwtw0V0IBvuhd4o
Am I comparing wrong or what is the problem?
A:
Check the length of... | List of numbers have same data but different sum | I have two lists of numbers. After comparing them, they are same but there sum is different.
You can get the script here: https://mega.nz/file/dHgHEQQA#9k9s86hgGH_vWrcE8J6ixYdu3GYkfwtw0V0IBvuhd4o
Am I comparing wrong or what is the problem?
| [
"Check the length of the list. e appears to be having 694 elements and r appears to be having 693 elements. so, zip aggregates only 693 elements. Hence the sum are different.\nprint(len(e), len(r), len([x for x in zip(e, r)]))\n# 694 693 693\n\n"
] | [
0
] | [] | [] | [
"comparison",
"list",
"python"
] | stackoverflow_0074673224_comparison_list_python.txt |
Q:
glue jupyter notebook locally instead of labs?
docker run -itd -p 8888:8888 -p 4040:4040 --name glue_jupyter amazon/aws-glue-libs:glue_libs_2.0.0_image_01 /home/glue_user/jupyter/jupyter_start.sh
results in
i'm able to open 127.0.0.1:8888 and it redirects to jupyter labs
How do i go to jupyter notebook instead?
... | glue jupyter notebook locally instead of labs? | docker run -itd -p 8888:8888 -p 4040:4040 --name glue_jupyter amazon/aws-glue-libs:glue_libs_2.0.0_image_01 /home/glue_user/jupyter/jupyter_start.sh
results in
i'm able to open 127.0.0.1:8888 and it redirects to jupyter labs
How do i go to jupyter notebook instead?
should i bash instead and then jupyter notebook from... | [
"I tried the following command with glue image for 3.0, and it does takes me to the jupyter labs, with a console prompt to choose python/pyspark/etc. notebooks.\ndocker run -it -p 8888:8888 -p 4040:4040 -e DISABLE_SSL=\"true\" --name glue_jupyter amazon/aws-glue-libs:glue_libs_3.0.0_image_01 /home/glue_user/jupyter... | [
0
] | [] | [] | [
"aws_glue",
"docker",
"jupyter_notebook",
"pyspark",
"python"
] | stackoverflow_0074663072_aws_glue_docker_jupyter_notebook_pyspark_python.txt |
Q:
Understanding how the "is" operator works int Python for result from function
For example we have this code.
x = 1
y = 1
print(x is y) # TRUE
print(id(x), id(y))
y = pow(10, 30, 10**30-1) # 1
print(type(y))
print(x, y, x is y) # FALSE
It`s return:
True
140516304938720 140516304938720
<class 'int'>
1 1 False
The... | Understanding how the "is" operator works int Python for result from function | For example we have this code.
x = 1
y = 1
print(x is y) # TRUE
print(id(x), id(y))
y = pow(10, 30, 10**30-1) # 1
print(type(y))
print(x, y, x is y) # FALSE
It`s return:
True
140516304938720 140516304938720
<class 'int'>
1 1 False
The last result is False. Please help me understand why this is happening? Result of f... | [
"The \"is\" operator checks whether two items are the same object.\nIn your example it returns False because x is not the same object as y, even though they have the same content.\nfor example:\nHere the x and y variables have the same content, but they are not the same object!\nx = [\"apple\", \"banana\"]\ny = [\"... | [
0
] | [
"x1 = 5\ny1 = 5\nx2 = 'Hello'\ny2 = 'Hello'\nx3 = [1,2,3]\ny3 = [1,2,3]\nprint(x1 is not y1) # prints False\nprint(x2 is y2) # prints True\nprint(x3 is y3) # prints False\n",
"x = [\"apple\", \"banana\"]\n\ny = [\"apple\", \"banana\"]\nprint(x is y) #False\nprint(x == y) #True\n"
] | [
-1,
-1
] | [
"function",
"literals",
"operators",
"python",
"syntax"
] | stackoverflow_0074509703_function_literals_operators_python_syntax.txt |
Q:
Python Pandas Data frame Pivoting
I have such .txt file:
Field
Value
First
1
Second
alfa
First
23
Second
beta
First
55
Second
omega
I need to read and transform this file to get data like this:
First
Second
1
alfa
23
beta
55
omega
I start with this:
file = './data.txt'
df = pd.read_csv(file, sep='\t',... | Python Pandas Data frame Pivoting | I have such .txt file:
Field
Value
First
1
Second
alfa
First
23
Second
beta
First
55
Second
omega
I need to read and transform this file to get data like this:
First
Second
1
alfa
23
beta
55
omega
I start with this:
file = './data.txt'
df = pd.read_csv(file, sep='\t',header... | [
"The trick is you need to create common keys for the index.\nUsing .assign create a column named CommonKeys which is the cumcount of grouping on the Fields column. Finally chain functions to pivot and clean up the df.\ndf = (\n df.assign(CommonKeys=df.groupby(\"Field\").cumcount())\n .pivot(index=\"CommonKeys... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074671429_pandas_python.txt |
Q:
How to get only the initial NaN values and leading non NaN values from a pandas dataframe?
I have a dataframe where the rows contain NaN values. The df contains original columns namely Heading 1 Heading 2 and Heading 3 and extra columns called Unnamed: 1 Unnamed: 2 and Unnamed: 3 as shown:
Heading 1
Heading 2
Hea... | How to get only the initial NaN values and leading non NaN values from a pandas dataframe? | I have a dataframe where the rows contain NaN values. The df contains original columns namely Heading 1 Heading 2 and Heading 3 and extra columns called Unnamed: 1 Unnamed: 2 and Unnamed: 3 as shown:
Heading 1
Heading 2
Heading 3
Unnamed: 1
Unnamed: 2
Unnamed: 3
NaN
34
24
45
NaN
NaN
NaN
NaN
24
45
11
NaN
NaN... | [
"First\ndivide dataframe (iloc or filter or and so on)\ndf1 = df.iloc[:, :3]\ndf2 = df.iloc[:, 3:]\n\nSecond\ncount initial NaNs in df1 and count notnull in df2\ns1 = df1.apply(lambda x: (x.notnull().cumsum() == 0).sum(), axis=1)\ns2 = df2.notnull().sum(axis=1)\n\nLast\nconcat and make dict\npd.concat([s1, s2], axi... | [
1,
1
] | [] | [] | [
"data_preprocessing",
"dataframe",
"nan",
"pandas",
"python"
] | stackoverflow_0074673249_data_preprocessing_dataframe_nan_pandas_python.txt |
Q:
how can we find length of word in python without using len function?
#No using of Len function
a=len
b=len(a)
print(b)
I want this without Len function
how can we find length of word in python without using len function?
A:
Here is one way to find the length of a word in Python without using the len function:
w... | how can we find length of word in python without using len function? | #No using of Len function
a=len
b=len(a)
print(b)
I want this without Len function
how can we find length of word in python without using len function?
| [
"Here is one way to find the length of a word in Python without using the len function:\nword = \"hello\"\ncount = 0\n\nfor letter in word:\n count += 1\n\nprint(count) # this will print 5, the length of the word\n\nThis works by iterating through each letter in the word and adding 1 to a counter variable for ea... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074673350_python.txt |
Q:
keras save and load model, accuracy drop
Link to colab
https://colab.research.google.com/drive/1u_jRl3uMlxEne667aCxt5Qh8eMlhme8V?usp=sharing
link to training data
https://drive.google.com/file/d/1jcu7ZTnTF2obGb5OM4dD6T_GlU0sMWmL/view?usp=sharing
So i train a model that have 70% and save it into drive and deleted r... | keras save and load model, accuracy drop | Link to colab
https://colab.research.google.com/drive/1u_jRl3uMlxEne667aCxt5Qh8eMlhme8V?usp=sharing
link to training data
https://drive.google.com/file/d/1jcu7ZTnTF2obGb5OM4dD6T_GlU0sMWmL/view?usp=sharing
So i train a model that have 70% and save it into drive and deleted runtime
Then restart runtime and load the model... | [
"I see your question and would like to clarify your understanding of the following:\n\nYour understanding of Model Training\nYour understanding of Training Accuracy and Validation Accuracy\nGeneral rule-of-thumbs regarding model evaluation.\n\n\nWhen training your model, you do not want to have a \"Perfect Model ac... | [
0
] | [] | [] | [
"artificial_intelligence",
"keras",
"machine_learning",
"model",
"python"
] | stackoverflow_0074665262_artificial_intelligence_keras_machine_learning_model_python.txt |
Q:
How do I trick the app into thinking the mouse movement is really me?
I am attempting to get my script to open up a game through steam and then start a world. This all works fine up until the part where I need to navigate the game. I'm assuming that the modules that let you control the mouse just move to points ra... | How do I trick the app into thinking the mouse movement is really me? | I am attempting to get my script to open up a game through steam and then start a world. This all works fine up until the part where I need to navigate the game. I'm assuming that the modules that let you control the mouse just move to points rather than actually moving the mouse which the game doesn't pick up. The gam... | [
"It sounds like the game is not picking up the simulated mouse movements from the modules you are using. One possible solution is to try using the pyautogui module's moveRel() function to move the mouse relative to its current position, rather than using moveTo() to move it to a specific set of coordinates. This ma... | [
0
] | [] | [] | [
"automation",
"mouse",
"pyautogui",
"python"
] | stackoverflow_0074673336_automation_mouse_pyautogui_python.txt |
Q:
This version of ChromeDriver only supports Chrome version 102
I'm using VS Code and Anaconda3.
Currently trying to install ChromeDriver_Binary but, when I try to execute code, I get this error:
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only s... | This version of ChromeDriver only supports Chrome version 102 | I'm using VS Code and Anaconda3.
Currently trying to install ChromeDriver_Binary but, when I try to execute code, I get this error:
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 102
Current browser version is 100.0.4896.12... | [
"One option is to use chromedriver-autoinstaller to do it all at once:\nimport chromedriver_autoinstaller as chromedriver\nchromedriver.install()\n\nAlternatively use chromedriver-binary-auto to find the required version and install the driver:\npip install --upgrade --force-reinstall chromedriver-binary-auto\nimpo... | [
14,
4,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"selenium_chromedriver"
] | stackoverflow_0072111139_python_selenium_chromedriver.txt |
Q:
Can you explain me the output
I was in class section of python programming and I am confused here.
I have learned that super is used to call the method of parent class but here Employee is not a parent of Programmer yet it's called (showing the result of getLanguage method).
What I am missing?
This is the code.
cl... | Can you explain me the output | I was in class section of python programming and I am confused here.
I have learned that super is used to call the method of parent class but here Employee is not a parent of Programmer yet it's called (showing the result of getLanguage method).
What I am missing?
This is the code.
class Employee:
company= "Google"... | [
"You've bumped into one of the reasons why super exists. From the docs, super delegates method calls to a parent or sibling class of type. Python bases class inheritance on a dynamic Method Resolution Order (MRO). When you created a class with multiple inheritance, those two parent classes became siblings. The left... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0074673076_python.txt |
Q:
How to concatenate lists into single merged DataFrame from for loop output?
I'm tring to pull data by using API, I have a list of IDs from csv,and I use for loop to pull request for each ID, the output is in the form of lists, and I tried to convert them into DataFrame, they come out into seperate DataFrames and I... | How to concatenate lists into single merged DataFrame from for loop output? | I'm tring to pull data by using API, I have a list of IDs from csv,and I use for loop to pull request for each ID, the output is in the form of lists, and I tried to convert them into DataFrame, they come out into seperate DataFrames and I'm not able to merge them into one since they are inside of a for loop.
The code ... | [
"You can start by making an empty list/basket, then put in the dataframes collected in every iteration/pull and finally use pandas.concat to make a whole and single dataframe right after the loop.\nTry this :\n# Read ios id from CSV file\ndata = pd.read_csv('File.csv')\n\nios_data= data['ios_id'].tolist()\n\nlist_d... | [
0
] | [] | [] | [
"api",
"dataframe",
"for_loop",
"pandas",
"python"
] | stackoverflow_0074673399_api_dataframe_for_loop_pandas_python.txt |
Q:
How do I use binding to change the position of an arc?
I am having trouble setting the x position of an arc called "pac_man", and then changing it using += with a function called "xChange()".
I have tried multiple things, but I think using a dictionary would suffice. This is because the variable "coord" needs 4 va... | How do I use binding to change the position of an arc? | I am having trouble setting the x position of an arc called "pac_man", and then changing it using += with a function called "xChange()".
I have tried multiple things, but I think using a dictionary would suffice. This is because the variable "coord" needs 4 values to assign shape and position for "pac_man."
#Imports
fr... | [
"See comments in the code:\n#Imports\nfrom tkinter import *\n\n#Functions\ndef move(event):#add event parameter\n pixels = 1 #local variable, amount of pixels to \"move\"\n direction = event.keysym #get keysym from event object\n if direction == 'Right':#if keysym is Left\n cvs.move('packman',+pixel... | [
1
] | [] | [] | [
"python",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0074673409_python_tkinter_tkinter_canvas.txt |
Q:
Name 'X' is not defined [How to fix it]
I attempted to execute the code but the problem shows up as "Name 'X' is not defined" Is X not defined if not how do I define it for the code to run.
`
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =... | Name 'X' is not defined [How to fix it] | I attempted to execute the code but the problem shows up as "Name 'X' is not defined" Is X not defined if not how do I define it for the code to run.
`
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)
todo_check([
... | [
"You are using the train_test_split function:\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\n\n\ntrain_test_split ( X, y ....\n\nBut at no point have you defined X (or y for that matter).\nYou need to provide the function with data.\n\nWhat is X ?\nWhat is y ?\n\nOnc... | [
0
] | [] | [] | [
"google_colaboratory",
"python"
] | stackoverflow_0074673348_google_colaboratory_python.txt |
Q:
How to extract values from a while loop to print in python?
So I could print out the odd numbers. However, the output isn't what i want. It should look like 1+3+5+7 = 16 but I could not make it into a single line.
I couldn't figure out how to extract the values from the while loop as with my method it only gives t... | How to extract values from a while loop to print in python? | So I could print out the odd numbers. However, the output isn't what i want. It should look like 1+3+5+7 = 16 but I could not make it into a single line.
I couldn't figure out how to extract the values from the while loop as with my method it only gives the latest odd number which is 7 while 1,3 and 5 could not be take... | [
"An alternative method would be the use of:\n\nrange() method to generate the list of odd numbers\n.join() method to stitch the odd numbers together (eg. 1+3+5+7)\nf-strings to print odds together with the total = sum(odd_nums)\n\nCode:\nnum = int(input(\"Insert a postive integer:\")) #4\nodd_nums = range(1, num * ... | [
1,
0,
0,
0
] | [] | [] | [
"numbers",
"python",
"while_loop"
] | stackoverflow_0074673156_numbers_python_while_loop.txt |
Q:
How to pad sequences with variable length in more than 1 dimension in pytorch?
Is there any clean way to create a batch of 3D sequences in pytorch? I have 3D sequences with the shape of (sequence_length_lvl1, sequence_length_lvl2, D), the sequences have different values for sequence_length_lvl1 and sequence_length... | How to pad sequences with variable length in more than 1 dimension in pytorch? | Is there any clean way to create a batch of 3D sequences in pytorch? I have 3D sequences with the shape of (sequence_length_lvl1, sequence_length_lvl2, D), the sequences have different values for sequence_length_lvl1 and sequence_length_lvl2 but all of them have the same value for D, and I want to pad these sequences i... | [
"this works with your example, maybe there is a faster way.\ninput1 = [\n [[1, 1, 1], [2, 2, 2], [3, 3, 3]],\n [[4, 4, 4], [5, 5, 5]]\n ]\n\ninput2 = [\n [[1, 1, 1], [2, 2, 2], [3, 3, 3]],\n [[6, 6, 6]],\n [[4, 4, 4], [5, 5, 5]]\n ]\n\nlen_max = max(len(input1), len(input2))\noutput_val = [[], ... | [
0,
0,
0
] | [] | [] | [
"deep_learning",
"lstm",
"python",
"pytorch"
] | stackoverflow_0072488665_deep_learning_lstm_python_pytorch.txt |
Q:
How to create dynamic hierarchy(nested key value dictionary) based on sub data
customer_det = [
{ "Customer": "A",
"country_name": "USA",
"region_name": "North",
"state_name": "Florida",
"subregion_name": "South Atlantic",
"store": "Store1... | How to create dynamic hierarchy(nested key value dictionary) based on sub data | customer_det = [
{ "Customer": "A",
"country_name": "USA",
"region_name": "North",
"state_name": "Florida",
"subregion_name": "South Atlantic",
"store": "Store1"
},
{
"Customer": "A",
"country_name": ... | [] | [] | [
"The question is a bit vague. But to get data from your database, you may first need to query it and then save the results. In python, you can utilize json.dumps() for getting your desired output.\nimport json\n\n# Example data\ndata = [\n {\n 'id': 1,\n 'name': 'John Doe',\n 'age': 30\n ... | [
-1
] | [
"django",
"json",
"python"
] | stackoverflow_0074673511_django_json_python.txt |
Q:
Applying two styler functions simultanesouly to a dataframe
Here is the example script I am working with. I am trying to apply two styler functions to a dataframe at the same time but as you can see, it would only call the colors2 function. What would be the best way to apply two functions at the same time?
import... | Applying two styler functions simultanesouly to a dataframe | Here is the example script I am working with. I am trying to apply two styler functions to a dataframe at the same time but as you can see, it would only call the colors2 function. What would be the best way to apply two functions at the same time?
import pandas as pd
df = pd.DataFrame(data=[[-100,500,400,0,222,222], [... | [
"Chain your applymap commands in the desired order (last one prevails):\n(df.style\n .applymap(colors2, subset=pd.IndexSlice[:, pd.IndexSlice[:, 'b']])\n .applymap(colors, subset=pd.IndexSlice[:, pd.IndexSlice['x','b']])\n )\n\nHere pd.IndexSlice['x','b']] is more restrictive than pd.IndexSlice[:, 'b'] so we us... | [
2
] | [] | [] | [
"dataframe",
"multi_index",
"pandas",
"python"
] | stackoverflow_0074673515_dataframe_multi_index_pandas_python.txt |
Q:
In the same function separating code into y/n from the user and taking steps based on that without if/else?
I made a sample below to help explain. The problem with an if/else clause is that it makes the variables local so i can't assign a returned value under if: when the user enters 'y' and use it across the boun... | In the same function separating code into y/n from the user and taking steps based on that without if/else? | I made a sample below to help explain. The problem with an if/else clause is that it makes the variables local so i can't assign a returned value under if: when the user enters 'y' and use it across the bounds of else:
-See the value return_from_add and the two places I want to use it. I want to obey running my code se... | [
"There is a syntax error in the code. In the second if statement, the 'y_n' variable is compared to the string 'y' using a single equal sign '=' instead of a double equal sign '=='. This will cause a syntax error, as the single equal sign is used to assign a value to a variable, while the double equal sign is used ... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074673507_python_python_3.x.txt |
Q:
How to count len of strings in a list without built-in function?
How can I create a function count_word in order to get the result like this:
x = ['Hello', 'Bye']
print(count_word(x))
# Result must be [5, 3]
without using len(x[index]) or any built-in function?
A:
Since you're not allowed to use built-in func... | How to count len of strings in a list without built-in function? | How can I create a function count_word in order to get the result like this:
x = ['Hello', 'Bye']
print(count_word(x))
# Result must be [5, 3]
without using len(x[index]) or any built-in function?
| [
"Since you're not allowed to use built-in functions, you have to iterate over each string in the list and over all characters of each word as well. Also you have to memorize the current length of each word and reset the counter if the next word is taken. This is done by re-assigning the counter value to 0 (length =... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0060767809_python.txt |
Q:
Accessing a Pandas index like a regular column
I have a Pandas DataFrame with a named index. I want to pass it off to a piece off code that takes a DataFrame, a column name, and some other stuff, and does a bunch of work involving that column. Only in this case the column I want to highlight is the index, but givi... | Accessing a Pandas index like a regular column | I have a Pandas DataFrame with a named index. I want to pass it off to a piece off code that takes a DataFrame, a column name, and some other stuff, and does a bunch of work involving that column. Only in this case the column I want to highlight is the index, but giving the index's label to this piece of code doesn't w... | [
"Index has a special meaning in Pandas. It's used to optimise specific operations and can be used in various methods such as merging / joining data. Therefore, make a choice:\n\nIf it's \"just another column\", use reset_index and treat it as another column.\nIf it's genuinely used for indexing, keep it as an index... | [
23,
13,
6,
0
] | [] | [] | [
"dataframe",
"indexing",
"pandas",
"python",
"series"
] | stackoverflow_0052139506_dataframe_indexing_pandas_python_series.txt |
Q:
List of integers to pairs of tuples
I have a list of integers like this
numbers = [1, 5, 7, 19, 22, 55]
I want to have a function that takes this as input and gives me a list of paired tuples that should contain the numbers as (1,5), (5,7), (7,19) and so on.
Kindly suggest.
I have tried using for loops. Didn't ge... | List of integers to pairs of tuples | I have a list of integers like this
numbers = [1, 5, 7, 19, 22, 55]
I want to have a function that takes this as input and gives me a list of paired tuples that should contain the numbers as (1,5), (5,7), (7,19) and so on.
Kindly suggest.
I have tried using for loops. Didn't get expected output.
| [
"From Python 3.10 you can use itertools.pairwise\nfrom itertools import pairwise\n\nnumbers = [1, 5, 7, 19, 22, 55]\nlist(pairwise(numbers)) # [(1, 5), (5, 7), (7, 19), (19, 22), (22, 55)]\n\n",
"lst = [(numbers[i],numbers[i+1]) for i in range(0,len(numbers)-1)]\n\nThis should do the trick: loop over all elements... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074673571_python.txt |
Q:
I can't print hello world in visual studio code
I created a folder named " Python Trial ", and a folder within it named test and within that folder i created a file named test.py
I installed the python extension and tried to print " Hello World! " however it keeps on giving me this command:
C:/Users/saram/AppData/... | I can't print hello world in visual studio code | I created a folder named " Python Trial ", and a folder within it named test and within that folder i created a file named test.py
I installed the python extension and tried to print " Hello World! " however it keeps on giving me this command:
C:/Users/saram/AppData/Local/Microsoft/WindowsApps/python3.10.exe "c:/Users/... | [
"The error message you're seeing indicates that the interpreter can't find the Python file that you're trying to run. This could be because the path to the interpreter is incorrect, or because the Python interpreter is not installed on your system.\nThe Python extension in VSCode isn't sufficient for running Python... | [
1
] | [] | [] | [
"python",
"terminal",
"visual_studio_code"
] | stackoverflow_0074672914_python_terminal_visual_studio_code.txt |
Q:
python split string on multiple delimeters without regex
I have a string that I need to split on multiple characters without the use of regular expressions. for example, I would need something like the following:
>>>string="hello there[my]friend"
>>>string.split(' []')
['hello','there','my','friend']
is there an... | python split string on multiple delimeters without regex | I have a string that I need to split on multiple characters without the use of regular expressions. for example, I would need something like the following:
>>>string="hello there[my]friend"
>>>string.split(' []')
['hello','there','my','friend']
is there anything in python like this?
| [
"If you need multiple delimiters, re.split is the way to go.\nWithout using a regex, it's not possible unless you write a custom function for it.\nHere's such a function - it might or might not do what you want (consecutive delimiters cause empty elements):\n>>> def multisplit(s, delims):\n... pos = 0\n... ... | [
8,
1,
1,
0
] | [
"re.split is the right tool here.\n>>> string=\"hello there[my]friend\"\n>>> import re\n>>> re.split('[] []', string)\n['hello', 'there', 'my', 'friend']\n\nIn regex, [...] defines a character class. Any characters inside the brackets will match. The way I've spaced the brackets avoids needing to escape them, but t... | [
-3
] | [
"python",
"split",
"string"
] | stackoverflow_0010655850_python_split_string.txt |
Q:
Python multiprocessing.Process can not stop when after connecting the network
When I try to crawl thesis information in multiple threads, I cannot close the process after getting the information:
error
And when I comment the code which function is get the information from network, these processes can end normally.... | Python multiprocessing.Process can not stop when after connecting the network | When I try to crawl thesis information in multiple threads, I cannot close the process after getting the information:
error
And when I comment the code which function is get the information from network, these processes can end normally.
normal
This error is trouble me and I don't have any idea, my network connect is ... | [
"Hi,this is me again,I tried a concurrent implementation of threads,and global variables for threads are much more comfortable than process queue data sharing. By thread it does implement but my main function can't be stopped, previously with processes it was not possible to proceed to the next step when fetching c... | [
0
] | [] | [] | [
"multiprocessing",
"python",
"python_requests",
"queue",
"web_crawler"
] | stackoverflow_0074668048_multiprocessing_python_python_requests_queue_web_crawler.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.