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:
pocketsphinx ERROR: Could not build wheels for pocketsphinx, which is required to install pyproject.toml-based projects
I am having trouble downloading this python module called pocketsphinx,
I've tried everything by downloading it manually, using git and more (I am on windows), I updated pip, and I even tried dow... | pocketsphinx ERROR: Could not build wheels for pocketsphinx, which is required to install pyproject.toml-based projects | I am having trouble downloading this python module called pocketsphinx,
I've tried everything by downloading it manually, using git and more (I am on windows), I updated pip, and I even tried downloading visual studio with the python environment as the error insisted, i updated my python, I even tried updating my lapto... | [
"Ok, i just found the problem. turns out python 3.11 is completely unsupported. meaning you will have to downgrade to 3.10 to use this module\n"
] | [
0
] | [] | [] | [
"module",
"pip",
"pocketsphinx",
"python",
"python_3.x"
] | stackoverflow_0074562577_module_pip_pocketsphinx_python_python_3.x.txt |
Q:
Decorator Factory
The factory accepts a function (lambda) as an input and returns a decorator that will return the result of the function as the first argument. The result of the decorated function is passed. The function that the factory accepts (in the example below, it is a lambda) can only take one positional ... | Decorator Factory | The factory accepts a function (lambda) as an input and returns a decorator that will return the result of the function as the first argument. The result of the decorated function is passed. The function that the factory accepts (in the example below, it is a lambda) can only take one positional parameter.
Example:
@de... | [
"Just nest functions until you reach the required depth, then apply them:\ndef decorator_apply(transform):\n def wrapper(f):\n def wrapped(x, /):\n return f(transform(x))\n return wrapped\n return wrapper\n\n\n@decorator_apply(lambda user_id: user_id + 1)\ndef return_user_id(num: int)... | [
1
] | [] | [] | [
"decorator",
"python",
"python_decorators"
] | stackoverflow_0074562575_decorator_python_python_decorators.txt |
Q:
How do you remove duplicates in a 2d list with the same values but different order
I have a list which contains lists. I am trying to remove any duplicates of lists which may share the same items within the list but in a different order.
for example if I have this
nestedlist=[[1,2,3,4],[4,3,2,1],[1,5,8,7]]
I woul... | How do you remove duplicates in a 2d list with the same values but different order | I have a list which contains lists. I am trying to remove any duplicates of lists which may share the same items within the list but in a different order.
for example if I have this
nestedlist=[[1,2,3,4],[4,3,2,1],[1,5,8,7]]
I would like a function that returns something like:
[[1,2,3,4],[1,5,8,7]]
| [
"Make a set of sets out of the list of lists. Then convert it back to a list of lists:\nsos = {frozenset(l) for l in nestedlist}\nunique_nested = [list(s) for s in sos]\n\nWe need to use frozenset instead of set because sets are mutable therefore not hashable\n",
"Sort the list after acessing sub list and compare... | [
1,
1
] | [] | [] | [
"duplicates",
"python"
] | stackoverflow_0074563000_duplicates_python.txt |
Q:
How do I create a timeseries sliding window tensorflow dataset where some features have different batch sizes than others?
Currently I am able to create a timeseries sliding window batched dataset that contains ordered 'feature sets' like 'inputs', 'targets', 'benchmarks', etc. Originally I had developed my model ... | How do I create a timeseries sliding window tensorflow dataset where some features have different batch sizes than others? | Currently I am able to create a timeseries sliding window batched dataset that contains ordered 'feature sets' like 'inputs', 'targets', 'benchmarks', etc. Originally I had developed my model and dataset wherein the targets would be of the same batch size as all other inputs, however that has proven to be detrimental t... | [
"We can create two sliding windowed dataset and zip them.\ninputs = df[['input_1', 'input_1']].to_numpy()\nlabels = df['target_1'].to_numpy()\n\n\nwindow_size = 10\nstride =1\ndata1 = tf.data.Dataset.from_tensor_slices(inputs).window(window_size, shift=stride, drop_remainder=True).flat_map(lambda x: x.batch(window_... | [
0
] | [] | [] | [
"python",
"tensorflow",
"tensorflow_datasets"
] | stackoverflow_0074552302_python_tensorflow_tensorflow_datasets.txt |
Q:
scrollable dynamically generated popup in kivy
I'm trying to create a scrollable popup window dynamically in kivy (without a kv file). My goal is two things.
Have the popup window scroll if the popup_label has to much text
Make the popup_label text wrap and use its own space without overflowing onto other widget... | scrollable dynamically generated popup in kivy | I'm trying to create a scrollable popup window dynamically in kivy (without a kv file). My goal is two things.
Have the popup window scroll if the popup_label has to much text
Make the popup_label text wrap and use its own space without overflowing onto other widgets if the text is too large.
The problem:
I've been... | [
"The problem is that you are adding the ScrollView to the GridLayout. It should be the opposite. Try changing:\nlayout.add_widget(scrollLayout)\n\nto:\nscrollLayout.add_widget(layout)\n\nand change:\nsetattr(self, \"content\", layout)\n\nto:\nsetattr(self, \"content\", scrollLayout)\n\nor:\nself.content = scrollLay... | [
0
] | [] | [] | [
"kivy",
"kivymd",
"python"
] | stackoverflow_0074556878_kivy_kivymd_python.txt |
Q:
TypeError: Cannot interpret '12.779999999999998' as a data type
I am trying to plot my data on a chart with matplotlib but I keep getting an error that states that 12.7799 cannot be interpreted as a data type. It works when I take out the figure of the predicted gas prices but not when I include it in. I have trie... | TypeError: Cannot interpret '12.779999999999998' as a data type | I am trying to plot my data on a chart with matplotlib but I keep getting an error that states that 12.7799 cannot be interpreted as a data type. It works when I take out the figure of the predicted gas prices but not when I include it in. I have tried to convert it to an int but the error still keeps showing up.
#Comp... | [
"Try this:\ny = np.array([x , y, z]) instead of y = np.array([x ,y], z)\nI checked it on my end and it works ;)\ny = np.array([gp[0], gp[1], gp23]) \n\n"
] | [
2
] | [] | [] | [
"matplotlib",
"python",
"typeerror"
] | stackoverflow_0074562943_matplotlib_python_typeerror.txt |
Q:
Problems in installing jupyter notebook
I have installed jupyter notebook with pip through python and anaconda multiple times but I cannot find it in my start menu or any other location in my computer.
I have also tried using pip download and then pip install. It is successfull i cmd but I still cannot find it in ... | Problems in installing jupyter notebook | I have installed jupyter notebook with pip through python and anaconda multiple times but I cannot find it in my start menu or any other location in my computer.
I have also tried using pip download and then pip install. It is successfull i cmd but I still cannot find it in my gui.
| [
"I think the best way to go about using Jupyter notebooks is to first create a conda environment that has jupyter installed. You can do this with the following line of code,\nconda create -n my_env python jupyter\n\nOptionally, you can even specify a python version as follows,\nconda create -n my_env python=3.7 jup... | [
0
] | [] | [] | [
"jupyter_notebook",
"pip",
"python"
] | stackoverflow_0074560122_jupyter_notebook_pip_python.txt |
Q:
Django authenticate: usage in login vs. register (signup): how do they differ?
I have noticed that the Django authenticate is used in the same way in both the login view and the register view, both return a User object to be used in the login().
In the login view authenticate() uses username and password from the ... | Django authenticate: usage in login vs. register (signup): how do they differ? | I have noticed that the Django authenticate is used in the same way in both the login view and the register view, both return a User object to be used in the login().
In the login view authenticate() uses username and password from the submitted form, then checks on user if the credentials are ok.
if request.method == ... | [
"You do not need to authenticate a user in your register method. It can be as simple as,\nform = CreateUserForm()\nif request.method == 'POST':\n form = CreateUserForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('<urlname>')\ncontext = {'form': form}\nreturn render(reques... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074562369_django_python.txt |
Q:
How can I lower down values to a specific number in a numpy array
Let's say I have an array like this:
[1,5, 2, 6, 6.7, 8, 10]
I want to lower down the numbers that are larger than n.
So for example if n is 6, the array will look like this:
[1,5, 2, 6, 6, 6, 6]
I have tried a solution using numpy.vectorize:
lowe... | How can I lower down values to a specific number in a numpy array | Let's say I have an array like this:
[1,5, 2, 6, 6.7, 8, 10]
I want to lower down the numbers that are larger than n.
So for example if n is 6, the array will look like this:
[1,5, 2, 6, 6, 6, 6]
I have tried a solution using numpy.vectorize:
lower_down = lambda x : min(6,x)
lower_down = numpy.vectorize(lower_down)
... | [
"You could use numpy.minimum (or numpy.maximum) if you want to limit it:\n>>> numpy.minimum(1, [1, 2])\narray([1, 1])\n\n>>> numpy.maximum(2, [1, 2])\narray([2, 2])\n\nIf you need to limit both minimum and maximum, try numpy.clip function:\n>>> np.clip([1, 2, 3, 4], 2, 3)\narray([2, 2, 3, 3])\n\nFrom docs:\nClip (l... | [
3,
3,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074563149_numpy_python.txt |
Q:
Removing a character (number, letter, anything) in a string that is the same as the one that came before or after? (Python)
So, I've seen a lot of answers for removing duplicate characters in strings, but I'm not trying to remove all duplicates - just the ones that are beside each other.
This is probably a lot mor... | Removing a character (number, letter, anything) in a string that is the same as the one that came before or after? (Python) | So, I've seen a lot of answers for removing duplicate characters in strings, but I'm not trying to remove all duplicates - just the ones that are beside each other.
This is probably a lot more simple than what I'm doing, but this is what I've been attempting to do (and failing miserably at)
for j in range(2, len(string... | [
"I would use a regular expression replacement here:\ninp = \"ppmpvvpmmp\"\noutput = re.sub(r'(\\w)\\1', r'\\1', inp)\nprint(output) # pmpvpmp\n\nThe above assumes that a duplicate is limited to a single pair of same letters. If instead you want to reduce 3 or more, then use:\ninp = \"ppmpvvvvvpmmmp\"\noutput = re... | [
0
] | [] | [] | [
"duplicates",
"python"
] | stackoverflow_0074563172_duplicates_python.txt |
Q:
How do I make the program stop only when something specific happens?
I just started coding and i want to write a small program were you have to guess a number. The problem is you basically only have one guess and then it tells you the right number. How do I make the program only stop as soon as the user guessed th... | How do I make the program stop only when something specific happens? | I just started coding and i want to write a small program were you have to guess a number. The problem is you basically only have one guess and then it tells you the right number. How do I make the program only stop as soon as the user guessed the right number?
This is my current code:
import random
a = int(input())
... | [
"I guess you can figure what is happening\nimport random\n\nx = random.randint(1,5)\n\nguessed_right = False\n\nwhile not guessed_right:\n\n a = int(input())\n\n if a > x:\n print(\"you guessed to high\")\n\n elif a < x:\n print(\"you guessed to low\")\n\n elif a == x:\n print(\"you... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074563236_python.txt |
Q:
Values grabbed through one class are not being passed to the inheriting class in PyQT5
I am building a GUI for a hand tracking app using PyQT5.
There are two windows: one 'MainWindow' which displays the camera view, and one called 'Window 2' which holds multiple checkboxes that correspond to actions that can be en... | Values grabbed through one class are not being passed to the inheriting class in PyQT5 | I am building a GUI for a hand tracking app using PyQT5.
There are two windows: one 'MainWindow' which displays the camera view, and one called 'Window 2' which holds multiple checkboxes that correspond to actions that can be enabled/disabled while the program is running.
The code for the two classes is as follows:
cla... | [
"It seems like you are not familiar with Object Oriented Programming.\nvalues = Window2()\nhello = values.returnvalues()\n\nThis block of code actually creates a new object Window2, and its checkboxes are indeed unchecked, which is why you always get [False, False, False].\nThe simplest (but not the best) way to so... | [
0
] | [] | [] | [
"class",
"inheritance",
"pyqt5",
"python"
] | stackoverflow_0074563079_class_inheritance_pyqt5_python.txt |
Q:
Python gTTS several mp3 files issue
I am creating an app based on speech. Everything works fine but I do not want my app to use outside program to open mp3 file. At the moment program can do several commands only if I will use: cmd
def speak(text):
tts = gTTS(text=text, lang='pl')
filename = 'speak.mp3'
t... | Python gTTS several mp3 files issue | I am creating an app based on speech. Everything works fine but I do not want my app to use outside program to open mp3 file. At the moment program can do several commands only if I will use: cmd
def speak(text):
tts = gTTS(text=text, lang='pl')
filename = 'speak.mp3'
tts.save(filename)
cmd = filename ... | [
"Try to see the permissions of the file that has been created. It might have only read permissions.\n",
"When passing in the function, attempt to supply various file names for each of the distinct texts, or use the random.randit() method to set different file names, or use the current time as your file name using... | [
0,
0
] | [] | [] | [
"gtts",
"python"
] | stackoverflow_0061712950_gtts_python.txt |
Q:
Creating a string text from values and indexes that meet condition
Hello Guys I have the following dataset:
# creating dataset
dataset = pd.DataFrame()
dataset['name'] = ['Alex', 'Alex', 'Alex','Alex','Alex',
'Marie', 'Marie', 'Marie','Marie','Marie',
'Luke', 'Luke', 'Luke','L... | Creating a string text from values and indexes that meet condition | Hello Guys I have the following dataset:
# creating dataset
dataset = pd.DataFrame()
dataset['name'] = ['Alex', 'Alex', 'Alex','Alex','Alex',
'Marie', 'Marie', 'Marie','Marie','Marie',
'Luke', 'Luke', 'Luke','Luke','Luke']
dataset['sales'] = [690,451,478,524,750,452,784,523,451,125... | [
"you can use:\nresult_grouped=dataset.groupby(['name']).aggregate({'sales': 'mean'}).reset_index()\nresult_grouped=result_grouped[(result_grouped['sales']>500)]\n\nresult_grouped['text']=result_grouped['name'] + ' with ' + result_grouped['sales'].astype(str)\nlistt=', '.join(result_grouped['text'].to_list())\nfinal... | [
1,
1
] | [] | [] | [
"pandas",
"printing",
"python"
] | stackoverflow_0074562694_pandas_printing_python.txt |
Q:
Floating-point errors in cube root of exact cubic input
I found myself needing to compute the "integer cube root", meaning the cube root of an integer, rounded down to the nearest integer. In Python, we could use the NumPy floating-point cbrt() function:
import numpy as np
def icbrt(x):
return int(np.cbrt(x))
... | Floating-point errors in cube root of exact cubic input | I found myself needing to compute the "integer cube root", meaning the cube root of an integer, rounded down to the nearest integer. In Python, we could use the NumPy floating-point cbrt() function:
import numpy as np
def icbrt(x):
return int(np.cbrt(x))
Though this works most of the time, it fails at certain inpu... | [
"This problem is caused by a bad implementation of cbrt. It is not caused by floating-point arithmetic because floating-point arithmetic is not a barrier to computing the cube root well enough to return an exactly correct result when the exactly correct result is representable in the floating-point format.\nFor exa... | [
2
] | [] | [] | [
"floating_accuracy",
"floating_point",
"integer",
"math",
"python"
] | stackoverflow_0074553553_floating_accuracy_floating_point_integer_math_python.txt |
Q:
How to avoid blank spaces between bars which are plotted next to each other when exporting as SVG from matplotlib?
I am plotting with matplolib a bar chart, where the bars are next to each other without a space in between.
However, when exporting as .svg blank (white) spaces between the bars are visible.
bar chart... | How to avoid blank spaces between bars which are plotted next to each other when exporting as SVG from matplotlib? | I am plotting with matplolib a bar chart, where the bars are next to each other without a space in between.
However, when exporting as .svg blank (white) spaces between the bars are visible.
bar chart with blank spaces between bars when exported as .svg
When exporting to PDF (also as vector graphic) no blank spaces are... | [
"If your bars aren't perfectly aligned to pixel boundaries, the SVG renderer will try to antialias them, resulting in lighter patches between adjacent bars.\nFor example, here are two SVGs that are both 200 pixels wide. The first shows a bar chart with 21 bars. Since the bars are not aligned with pixel boundaries, ... | [
1
] | [] | [] | [
"matplotlib",
"python",
"svg",
"vector_graphics"
] | stackoverflow_0074562936_matplotlib_python_svg_vector_graphics.txt |
Q:
Why does Python think its timezone is UTC, when the system is PDT/PST?
On my Ubuntu Linux system, the system timezone is correctly set to America/Vancouver:
$ file /etc/localtime
/etc/localtime: symbolic link to /usr/share/zoneinfo/America/Vancouver
$ date
Thu 17 Nov 10:31:38 PST 2022
$ date '+%Y-%m-%d %H:%M:%S... | Why does Python think its timezone is UTC, when the system is PDT/PST? | On my Ubuntu Linux system, the system timezone is correctly set to America/Vancouver:
$ file /etc/localtime
/etc/localtime: symbolic link to /usr/share/zoneinfo/America/Vancouver
$ date
Thu 17 Nov 10:31:38 PST 2022
$ date '+%Y-%m-%d %H:%M:%S%z'
2022-11-17 10:32:57-0800
$ date '+%Y-%m-%d %H:%M:%S%Z'
2022-11-17 10:33... | [
"Turns out this was caused by Homebrew/linuxbrew.\nIt had installed its own versions of python as dependencies and poetry has picked up one of those, as you can see from the poetry debug info here.\nI removed Homebrew completely (it's Linux implementation has always felt like a bad idea to me, and this was enough f... | [
0
] | [] | [] | [
"python",
"time",
"timezone"
] | stackoverflow_0074480620_python_time_timezone.txt |
Q:
How to block terminal/console outputs in python
I'm using Python to execute some bash commands. The problem is that the terminal outputs from these bash scripts are spamming my terminal. Is there any way to block the output messages from these scripts? I have tried the step in this answer. But is only blocking the... | How to block terminal/console outputs in python | I'm using Python to execute some bash commands. The problem is that the terminal outputs from these bash scripts are spamming my terminal. Is there any way to block the output messages from these scripts? I have tried the step in this answer. But is only blocking the print calls I make, and it is not blocking the conso... | [
"In Bash you can simply use:\n$ eclipse &>/dev/null\n\nThis catches both stdin and stderr to the redirect point (in bash).\n(here eclipse is my command like)\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074563179_python.txt |
Q:
Match the content of sentence/sequence in python
Suppose we 2 sequence of words
sentence1 = 'Ram is eating'
sentence2 = 'is Ram eating'
sentence3 = 'is Ram playing'
sentence4 = 'movie Ram watching is'
how to get match% of such 2 sequences .
difflib sequenceMatcher matches letter by letter . Any way to find ma... | Match the content of sentence/sequence in python | Suppose we 2 sequence of words
sentence1 = 'Ram is eating'
sentence2 = 'is Ram eating'
sentence3 = 'is Ram playing'
sentence4 = 'movie Ram watching is'
how to get match% of such 2 sequences .
difflib sequenceMatcher matches letter by letter . Any way to find match % in these cases.
match% between sentence1 and sen... | [
"How about converting string to list and find matching percentage.\nsentence1 = 'Ram is eating'\nsentence2 = 'is Ram eating'\n\nsentence1 = sentence1.split()\nsentence2 = sentence2.split()\n\nlongest = max(sentence1, sentence2, key=len)\n\nper = len(set(sentence1) & set(sentence2)) \nresult = per/len(longest)\npr... | [
1
] | [] | [] | [
"difflib",
"nlp",
"python",
"sentence",
"sequence"
] | stackoverflow_0074563252_difflib_nlp_python_sentence_sequence.txt |
Q:
Check if date is within three weeks from other date
I recently made a birthday tracker app, that basically reads name/birthdate info from a CSV file, puts all data in Person objects, and orders them by date in a list, then re-orders the list, so it starts at the current date.
For example, right now the first few i... | Check if date is within three weeks from other date | I recently made a birthday tracker app, that basically reads name/birthdate info from a CSV file, puts all data in Person objects, and orders them by date in a list, then re-orders the list, so it starts at the current date.
For example, right now the first few items in the list have birthdates in late November and Dec... | [
"I would start by writing a function to find the year and date of someone's next birthday. There are two cases:\n\nTheir birthday is this year.\nTheir birthday is next year.\n\ndef next_birthday(birthday_month, birthday_dayofmonth):\n today = datetime.date.today()\n bday_this_year = datetime.date(year=today.y... | [
1
] | [] | [] | [
"date",
"python"
] | stackoverflow_0074562991_date_python.txt |
Q:
Problems with global variable Django
I write a quiz web site. And i need to save answers from users. Some of them have similar username. This is my start function
global new_user_answer
user_group = request.user.groups.values_list()
university = user_group[0][1]
num = Answers.objects.all().count()
new_user_answer ... | Problems with global variable Django | I write a quiz web site. And i need to save answers from users. Some of them have similar username. This is my start function
global new_user_answer
user_group = request.user.groups.values_list()
university = user_group[0][1]
num = Answers.objects.all().count()
new_user_answer = num + 1
new_line = Answers(id=new_user_a... | [
"Probably it has no sense to use a global variable on that way. You could define a session variable instead (a cookie).\nEdit the MIDDLEWARE setting and make sure it contains django.contrib.sessions.middleware.SessionMiddleware.\n#start function\nuser_group = request.user.groups.values_list()\nuniversity = user_gro... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074562839_django_python.txt |
Q:
Scraping Google images with Python3 (requests + BeautifulSoup)
I would like to download bulk images, using Google image search.
My first method; downloading the page source to a file and then opening it with open() works fine, but I would like to be able to fetch image urls by just running the script and changing ... | Scraping Google images with Python3 (requests + BeautifulSoup) | I would like to download bulk images, using Google image search.
My first method; downloading the page source to a file and then opening it with open() works fine, but I would like to be able to fetch image urls by just running the script and changing keywords.
First method: Go to the image search (https://www.google.n... | [
"Just so you're aware:\n# http://www.google.com/robots.txt\n\nUser-agent: *\nDisallow: /search\n\n\n\nI would like to preface my answer by saying that Google heavily relies on scripting. It's very possible that you're getting different results because the page you're requesting via reqeusts doesn't do anything wit... | [
1,
0,
0
] | [] | [] | [
"google_image_search",
"html",
"python",
"web_scraping"
] | stackoverflow_0035439110_google_image_search_html_python_web_scraping.txt |
Q:
PySpark - Create a Temp Tables for each unique item in loop
I hope you will be able to help me.
I have one big table with information about resolved tasks by user. I need to create a random sample where size of sample is equal 10% of total items per user.
I already created a temporary table with information about ... | PySpark - Create a Temp Tables for each unique item in loop | I hope you will be able to help me.
I have one big table with information about resolved tasks by user. I need to create a random sample where size of sample is equal 10% of total items per user.
I already created a temporary table with information about size of sample (Table 1): https://i.stack.imgur.com/7dM97.jpg
And... | [
"I already found a solution to create a dynamic table, but still I have a problem with size of sample:\nfrom pyspark.sql.types import IntegerType\n#df5 - column with Size of Sample\ndf5 = df5.withColumn(\"Size\", df5[\"Size\"].cast(IntegerType()))\n\ndataCollect = df5.collect()\ndf5.show()\nfor row in dataCollect:\... | [
1
] | [] | [] | [
"databricks",
"pyspark",
"python",
"sql"
] | stackoverflow_0074559243_databricks_pyspark_python_sql.txt |
Q:
how to coalesce every element of join pyspark
i have an array of join args (columns):
attrs = ['surname', 'name', 'patronymic', 'birth_date',
'doc_type', 'doc_series','doc_number']
i'm trying to join two tables just like this but i need to coalesce each column for join to behave normally (cause it wont join ... | how to coalesce every element of join pyspark | i have an array of join args (columns):
attrs = ['surname', 'name', 'patronymic', 'birth_date',
'doc_type', 'doc_series','doc_number']
i'm trying to join two tables just like this but i need to coalesce each column for join to behave normally (cause it wont join correctly if there are nulls)
new_df = pre_df.join(... | [
"so i've figured this out:\njoin_attrs = [F.coalesce(pre_df[elem], F.lit('')) == F.coalesce(res_df[elem], F.lit('')) for elem in attrs]\n\nalso this works too, but not sure what's faster:\njoin_attrs = [pre_df[elem].eqNullSafe(res_df[elem]) for elem in attrs]\n\n",
"If you try to union two dataset with the same c... | [
1,
0
] | [] | [] | [
"apache_spark",
"coalesce",
"pyspark",
"python"
] | stackoverflow_0074515958_apache_spark_coalesce_pyspark_python.txt |
Q:
Multidimensional array restructuring like in pandas.stack
Consider the following code to create a dummy dataset
import numpy as np
from scipy.stats import norm
import pandas as pd
np.random.seed(10)
n=3
space= norm(20, 5).rvs(n)
time= norm(10,2).rvs(n)
values = np.kron(space, time).reshape(n,n) + norm(1,1).rvs... | Multidimensional array restructuring like in pandas.stack | Consider the following code to create a dummy dataset
import numpy as np
from scipy.stats import norm
import pandas as pd
np.random.seed(10)
n=3
space= norm(20, 5).rvs(n)
time= norm(10,2).rvs(n)
values = np.kron(space, time).reshape(n,n) + norm(1,1).rvs([n,n])
### Output
array([[267.39784458, 300.81493866, 229.1... | [
"This does not use stack, but maybe it is acceptable for your problem:\nimport numpy as np\nimport pandas as pd\n\nvalues = np.arange(18).reshape(3, 3, 2) # Your values here\nindex = pd.MultiIndex.from_product([space_names, space_names, time_names], names=[\"space1\", \"space2\", \"time\"])\n\ndf = pd.DataFrame({\... | [
2
] | [] | [] | [
"data_wrangling",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074562840_data_wrangling_dataframe_numpy_pandas_python.txt |
Q:
Twitter No such element error python-selenium
After printing the username on the login screen on twitter, I want it to press the login button, but I get a "no such element" error.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Opti... | Twitter No such element error python-selenium | After printing the username on the login screen on twitter, I want it to press the login button, but I get a "no such element" error.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDr... | [
"This code worked for me!\nWith no changes\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.supp... | [
1
] | [] | [] | [
"python",
"selenium",
"twitter"
] | stackoverflow_0074563424_python_selenium_twitter.txt |
Q:
Remove an open file if an error occurs
Is it possible to close and delete while using 'with open()'?
I will occasionally encounter an error while doing calculations/extractions/queries in a routine called 'write_file'.
try:
with open(some_file, 'w') as report:
write_file(report, other_variables)
exce... | Remove an open file if an error occurs | Is it possible to close and delete while using 'with open()'?
I will occasionally encounter an error while doing calculations/extractions/queries in a routine called 'write_file'.
try:
with open(some_file, 'w') as report:
write_file(report, other_variables)
except:
logging.error("Report {} did not com... | [
"If you're comfortable deleting the file after encountering any exception at all, then this will suffice:\nimport os\n\ntry:\n with open(some_file, 'w') as report:\n write_file(report, other_variables)\nexcept:\n logging.error(\"Report {} did not compile\".format(some_file))\n os.remove(some_file)\n... | [
3,
0,
0
] | [] | [] | [
"contextmanager",
"python"
] | stackoverflow_0026855536_contextmanager_python.txt |
Q:
Using GPIOzero play an MP3 sound file whilst a button is held and an alternative MP3 when button is released (Python, Pygame, Raspberry Pi))
So what I am trying to do is have an MP3 playing when a button on my solderless Breadboard is not pressed and a different one playing when the button is held - best popular e... | Using GPIOzero play an MP3 sound file whilst a button is held and an alternative MP3 when button is released (Python, Pygame, Raspberry Pi)) | So what I am trying to do is have an MP3 playing when a button on my solderless Breadboard is not pressed and a different one playing when the button is held - best popular example is the 'Deal or No Deal' phone if the Banker on the other end was just a recorded message. I am using a Raspberry Pi 3B using the GPIO pin... | [
"#Always comment your code like a violent psychopath will be maintaining it and they know where you live ;)\nfrom pygame import mixer #imports Mixer class from the Pygame module to run the sound\nfrom gpiozero import Button #imports the Button element only from GPIOzero\nimport time #imports the time c... | [
0
] | [] | [] | [
"button",
"mp3",
"pygame",
"python",
"raspberry_pi"
] | stackoverflow_0074238538_button_mp3_pygame_python_raspberry_pi.txt |
Q:
Raise an exception using mock when a specific Django model is called
I have a class based view inheriting from FormView with an overridden form_valid() method that I would like to test.
As you can see, form_valid() is required to access the CustomUser model which is wrapped with a try and except.
What I am trying ... | Raise an exception using mock when a specific Django model is called | I have a class based view inheriting from FormView with an overridden form_valid() method that I would like to test.
As you can see, form_valid() is required to access the CustomUser model which is wrapped with a try and except.
What I am trying to do is raise an exception whenever create_user is called, but I am havin... | [
"You need to write the whole test under mock.patch context manager. Otherwise once with statement is finished, mock doesn't work anymore and has no effect. Try this:\ndef test_database_fail(self):\n with patch.object(CustomUserManager, 'create_user') as mock_method:\n mock_method.side_effect = Exception(V... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_testing",
"mocking",
"python"
] | stackoverflow_0074563124_django_django_forms_django_testing_mocking_python.txt |
Q:
SQLAlchemy: Making a subquery of query.from_statement(text(...)) raising AttributeError
I'm building a tool which relies heavily on SQLAlchemy's query builder, but which allows the user to specify literal text of subqueries to join against in cases where the model is insufficient.
However, when I try something lik... | SQLAlchemy: Making a subquery of query.from_statement(text(...)) raising AttributeError | I'm building a tool which relies heavily on SQLAlchemy's query builder, but which allows the user to specify literal text of subqueries to join against in cases where the model is insufficient.
However, when I try something like this:
q = session.query().from_statement(sa.text(subquery_text)).subquery(subquery_name)
.... | [
"I have found a valid syntax:\nq = sa.text(subquery_text).columns(Table.col_a, Table.col_b).alias(subquery_name)\n\nq can then be used as a standard subquery\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0034169993_python_sqlalchemy.txt |
Q:
pygame.display.set_mode() too slow with threading (up to 18 seconds)
I want to use pygame drawing/event handling in its separate thread, while leaving the main thread for all computations.
Here is a minimal working example. Everything works as intended, after initialization the performance is fine. But the self.sc... | pygame.display.set_mode() too slow with threading (up to 18 seconds) | I want to use pygame drawing/event handling in its separate thread, while leaving the main thread for all computations.
Here is a minimal working example. Everything works as intended, after initialization the performance is fine. But the self.screen = pygame.display.set_mode([400, 400]) line takes 18 seconds to execut... | [
"Figured it out. Apparently\nwhile not self.gui_initialized:\n pass\n\nis really bad because it causes a nearly complete freeze on all threads due to GIL.\nSimply adding a time.sleep(0.1) inside the loop fixes the problem.\n"
] | [
0
] | [] | [] | [
"multithreading",
"pygame",
"python"
] | stackoverflow_0074563456_multithreading_pygame_python.txt |
Q:
on message event in cog dosent work (discord.py)
Bot does not even print the messages from the on_message event and i cannot understand why (no errors or something just nothing happens).
@commands.Cog.listener("on_message")
async def on_message(self, message: discord.Message, ctx):
print(message)
... | on message event in cog dosent work (discord.py) | Bot does not even print the messages from the on_message event and i cannot understand why (no errors or something just nothing happens).
@commands.Cog.listener("on_message")
async def on_message(self, message: discord.Message, ctx):
print(message)
if message.author.id == self.bot.user:
... | [
"on_message only takes one argument, being the message. You can't just add random arguments to events and expect it to work. How would the library know what to pass in?\nDocs: https://discordpy.readthedocs.io/en/stable/api.html?highlight=on_message#discord.on_message\nAlso if you don't get any errors you probably d... | [
0
] | [] | [] | [
"discord.py",
"events",
"python"
] | stackoverflow_0074562260_discord.py_events_python.txt |
Q:
Type for function that accepts module containing specific function?
I'm trying to use a more functional syntax, and I've got two modules:
# foo.py
def bar():
# Do something
pass
# baz.py
def baz(qux: ???):
qux.bar()
# Usage:
import foo as Foo
import baz
baz(Foo)
I want baz to accept an argument (qux) ... | Type for function that accepts module containing specific function? | I'm trying to use a more functional syntax, and I've got two modules:
# foo.py
def bar():
# Do something
pass
# baz.py
def baz(qux: ???):
qux.bar()
# Usage:
import foo as Foo
import baz
baz(Foo)
I want baz to accept an argument (qux) which has an an attribute bar which is a callable. This parameter could r... | [
"You can use a Protocol, as mentioned by @jonrsharpe in the comments:\n# baz.py\n\nfrom typing import Protocol\n\n\nclass SupportsBar(Protocol):\n def bar(self) -> None:\n ...\n\n\ndef baz(qux: SupportsBar) -> None:\n qux.bar()\n\n\n# Usage:\nimport foo as Foo\n\nbaz(Foo) # no errors\n\n"
] | [
0
] | [] | [] | [
"python",
"python_typing"
] | stackoverflow_0074483387_python_python_typing.txt |
Q:
Nested Function in Python
What benefit or implications could we get with Python code like this:
class some_class(parent_class):
def doOp(self, x, y):
def add(x, y):
return x + y
return add(x, y)
I found this in an open-source project, doing something useful inside the nested functi... | Nested Function in Python | What benefit or implications could we get with Python code like this:
class some_class(parent_class):
def doOp(self, x, y):
def add(x, y):
return x + y
return add(x, y)
I found this in an open-source project, doing something useful inside the nested function, but doing absolutely nothin... | [
"Normally you do it to make closures:\ndef make_adder(x):\n def add(y):\n return x + y\n return add\n\nplus5 = make_adder(5)\nprint(plus5(12)) # prints 17\n\nInner functions can access variables from the enclosing scope (in this case, the local variable x). If you're not accessing any variables from ... | [
119,
62,
27,
8,
6,
1,
0
] | [] | [] | [
"nested_function",
"python"
] | stackoverflow_0001589058_nested_function_python.txt |
Q:
Selenium webpage not loading properly
I am trying to web scrape university ranking infomation from USNews site. And the problem is when I use selenium to open the webpage, the 'Load More Button' is not working properly. (I think I successfully click it but in the Chrome window opened by webdriver, when I scroll do... | Selenium webpage not loading properly | I am trying to web scrape university ranking infomation from USNews site. And the problem is when I use selenium to open the webpage, the 'Load More Button' is not working properly. (I think I successfully click it but in the Chrome window opened by webdriver, when I scroll down to the button, is says that 'We're sorry... | [
"It is clear that there is an anti scraping control in the specific site. It is always recommended to consult the robots.txt file beforehand and check whether scraping is possible on a certain site or not.\nIn general, this site blocks just the IP (try to go to other pages afterwards, you will see that you will get... | [
0
] | [] | [] | [
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074563125_python_selenium_web_scraping.txt |
Q:
Python function comparing characters in two strings
I would like to write my own Python function (i.e. without using any other non base Python functions) to compare the characters in two strings in the following way.
If the letter in position i of string 1 is the same as the letter in position i of string 2 then ... | Python function comparing characters in two strings | I would like to write my own Python function (i.e. without using any other non base Python functions) to compare the characters in two strings in the following way.
If the letter in position i of string 1 is the same as the letter in position i of string 2 then "Green" is returned
If the letter in position i of strin... | [
"Have you tried using a for loop?\ndef letter_comparison(string1, string2):\n myList = []\n\n if len(string1) != len(string2):\n return\n \n for i in range(len(string1)):\n try:\n l2p = string2[i+1]\n except:\n l2p = None\n try:\n l2m = string2[i-1]\n except:\n l2m = None\n\n ... | [
0,
0
] | [] | [] | [
"compare",
"function",
"python"
] | stackoverflow_0074562852_compare_function_python.txt |
Q:
Extra coefficient in Ridge Regression
I have 9 predictors (Clean df) but when I run the model I get 10 coefficients.
Here is my code:
#Get clean df with only more relevant columns
Clean_indices = wkospi[['Open_sp','Close_sp','Close_jp','Open_eur','High_eur','Open_kos','Close_kos','1 Mo','2 Mo','1 Yr','2 Yr','Open_... | Extra coefficient in Ridge Regression | I have 9 predictors (Clean df) but when I run the model I get 10 coefficients.
Here is my code:
#Get clean df with only more relevant columns
Clean_indices = wkospi[['Open_sp','Close_sp','Close_jp','Open_eur','High_eur','Open_kos','Close_kos','1 Mo','2 Mo','1 Yr','2 Yr','Open_oil','Open_gold']]
Clean_df = wkospi[['Clos... | [
"PolynomialFeatures has include_bias=True by default, which adds a column of all 1s. Note that the first coefficient is exactly zero, because Ridge has killed that term in favor of its own intercept.\n",
"From the top of my head, there are probably 9 weigths for your predictors and one constant as a whole model b... | [
2,
0
] | [] | [] | [
"model",
"python",
"regression",
"scikit_learn"
] | stackoverflow_0074563411_model_python_regression_scikit_learn.txt |
Q:
Dataframe object not callable when working Python script moved from Replit to local TabPy server
I have written a Python script that calls a National Oceanic and Atmospheric Administration (NOAA) endpoint with a zip code and gets a list of weather stations in response. The script then converts the response to a Pa... | Dataframe object not callable when working Python script moved from Replit to local TabPy server | I have written a Python script that calls a National Oceanic and Atmospheric Administration (NOAA) endpoint with a zip code and gets a list of weather stations in response. The script then converts the response to a Pandas dataframe.
I believe I have it working correctly based on this Replit.The dataframe appears to pr... | [
"The solution required two changes:\n\nIn the Tableau Prep interface where stating the function name, I had get_stations_for_zip(), but needed get_stations_for_zip without parenthesis\n\n\n\nIn my script, the get_stations_for_zip function needed to take \"df\" (for dataframe) as an argument. So def get_stations_for... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"tableau_prep",
"tabpy"
] | stackoverflow_0074553651_pandas_python_tableau_prep_tabpy.txt |
Q:
Airflow: How to get the current date of when data is inserted into a BigQuery table?
I am inserting data from a GCS Bucket to BigQuery, and I am unsure how to get the current date of when the data is inserted into a column.
This is my schema:
load_csv = gcs_to_bq.GoogleCloudStorageToBigQueryOperator(
task_id='... | Airflow: How to get the current date of when data is inserted into a BigQuery table? | I am inserting data from a GCS Bucket to BigQuery, and I am unsure how to get the current date of when the data is inserted into a column.
This is my schema:
load_csv = gcs_to_bq.GoogleCloudStorageToBigQueryOperator(
task_id='gcs_to_bq_example',
bucket='cloud-samples-data',
source_objects=['SOURCE-FILE-LOCA... | [
"There might be 2 ways to reach the desired result but not sure of either.\nThe first one is to use default values as described here and add a column to your schema:\nschema_fields=[\n {'name': 'item', 'type': 'STRING', 'mode': 'NULLABLE'},\n {'name': 'date', 'type': 'DATE', 'mode': 'NULLABLE'},\n\n {'name... | [
1
] | [] | [] | [
"airflow",
"directed_acyclic_graphs",
"google_bigquery",
"google_cloud_platform",
"python"
] | stackoverflow_0074561928_airflow_directed_acyclic_graphs_google_bigquery_google_cloud_platform_python.txt |
Q:
Check if user react with an certian emoji with cogs
I have a problem. How can I check which emoji the user reacted with? That did not work for me How do you check if a specific user reacts to a specific message [discord.py]
I want to check if the reaction is β
or β
folder structure
βββ main.py
βββ cogs
β βββ mem... | Check if user react with an certian emoji with cogs | I have a problem. How can I check which emoji the user reacted with? That did not work for me How do you check if a specific user reacts to a specific message [discord.py]
I want to check if the reaction is β
or β
folder structure
βββ main.py
βββ cogs
β βββ member.py
The problem is that I don't get an error message.... | [
"You're using a function called check, and it doesn't exist - like your error is telling you. There's one in your class, but that isn't in the same scope so you can't just call it using its name.\nTo access a method in a class, use self.<name>.\nAlso, you should only pass the check function, not call it.\n(..., che... | [
1,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074485957_discord_discord.py_python.txt |
Q:
discord.py how does hybrid commands work?
I have a problem with my discord.py code for my bot. It is not showing up as a slash command in Discord's chat box. I wanted to rewrite my bot that I have been running for many months with discord.py 1.7.3, so I wanted to introduce slash commands. Now I have the problem th... | discord.py how does hybrid commands work? | I have a problem with my discord.py code for my bot. It is not showing up as a slash command in Discord's chat box. I wanted to rewrite my bot that I have been running for many months with discord.py 1.7.3, so I wanted to introduce slash commands. Now I have the problem that with my code the slash commands are not disp... | [
"Slash commands have to be registered to Discord. This is done through a process called syncing. By calling tree.sync(), you can push your changes to Discord to let them know about your commands. If you never sync, Discord has no idea you have slash commands.\nThe exact same applies for regular slash commands as we... | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074563671_discord_discord.py_python.txt |
Q:
How to load HTML table into Plotly hover...?
I've been trying to implement an HTML table into my graph label, I have one column in my df with the html code but it isn't showing in the right format. Does anyone knows how can I change this?
plotly code
error
if you hover the cursor in the graph you will see somethin... | How to load HTML table into Plotly hover...? | I've been trying to implement an HTML table into my graph label, I have one column in my df with the html code but it isn't showing in the right format. Does anyone knows how can I change this?
plotly code
error
if you hover the cursor in the graph you will see something like:
table border=1 class="dataframe"><thead><t... | [
"Unfortunately, at this time it's impossible to render a table in the way that I intended. They are planning to make a future update where it will be possible.\n"
] | [
0
] | [] | [] | [
"html",
"plotly",
"python"
] | stackoverflow_0074174997_html_plotly_python.txt |
Q:
Sphinx autodoc dies on ImportError of third party package
There's any way to exclude the import part of a module and then document it with sphinx-python?
I have a module that imports another package (other different project) and then the sphinx gives this error:
"""
File "/usr/local/lib/python2.7/dist-packages... | Sphinx autodoc dies on ImportError of third party package | There's any way to exclude the import part of a module and then document it with sphinx-python?
I have a module that imports another package (other different project) and then the sphinx gives this error:
"""
File "/usr/local/lib/python2.7/dist-packages/Sphinx-1.1.3-py2.7.egg/sphinx/ext/autodoc.py", line 321, in im... | [
"You are fixing the issue wrong way. The correct way to fix the issue is to make Sphinx aware of your existing other packages as autodoc functionality must import Python packages to scan the source code. Python packages cannot be imported without all their dependencies resolved and you cannot cherry-pick lines of s... | [
4,
0
] | [] | [] | [
"autodoc",
"python",
"python_sphinx"
] | stackoverflow_0015088792_autodoc_python_python_sphinx.txt |
Q:
Affect groups() to panda column
I have this dataframe and I want to split a column with a regular expression and create new columns in this dataframe :
data = ["a:b-c","d:e-f"]
df = pd.DataFrame(data, columns=['expr'])
>>> df
expr
0 a:b-c
1 d:e-f
And here is what I want :
>>> df
expr one two three
0 a:... | Affect groups() to panda column | I have this dataframe and I want to split a column with a regular expression and create new columns in this dataframe :
data = ["a:b-c","d:e-f"]
df = pd.DataFrame(data, columns=['expr'])
>>> df
expr
0 a:b-c
1 d:e-f
And here is what I want :
>>> df
expr one two three
0 a:b-c a b c
1 d:e-f d e ... | [
"data = [\"a:b-c\",\"d:e-f\"]\ndf = pd.DataFrame(data, columns=['expr'])\ndf\n\n expr\n0 a:b-c\n1 d:e-f\n\ndf['one'], df['two'], df['three'] = df['expr'].str.split(':|-', expand=True)\ndf\n\n expr one two three\n0 a:b-c a b c\n1 d:e-f d e f\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074563702_pandas_python.txt |
Q:
Python class containing a temporary file
I would like to create a Python class which contains a temporary file.
If I use the usual tempfile.TemporaryFile() with a context manager to create a member variable in the constructor, then the context manager will close/delete the temporary file when the constructor exits... | Python class containing a temporary file | I would like to create a Python class which contains a temporary file.
If I use the usual tempfile.TemporaryFile() with a context manager to create a member variable in the constructor, then the context manager will close/delete the temporary file when the constructor exits. This is no good because I want the file to e... | [
"I came up with the following\nclass TemporaryFile:\n def __init__(self, *, data: str):\n self._data = data\n\n def __enter__(self):\n self._file = NamedTemporaryFile()\n self._file.write(data)\n self._file.flush()\n return self\n\n def __exit__(self, exc_type, exc_value, exc_tb):\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074559659_python.txt |
Q:
How to pass variables/functions from javaScript to Python and vice versa?
I am creating a website in HTML, CSS and JavaScript where I require an AI powered chatbot. I have the required python file which consists of the logic for the chatbot (AI, NLTK). Now, in the python file, I have a function named "response()" ... | How to pass variables/functions from javaScript to Python and vice versa? | I am creating a website in HTML, CSS and JavaScript where I require an AI powered chatbot. I have the required python file which consists of the logic for the chatbot (AI, NLTK). Now, in the python file, I have a function named "response()" which takes the user message as an argument and returns the processed response ... | [
"I will put few steps for you to go through but as @Pointy said in the comment, \"Exactly how you do all that is a very large topic for a single Stack Overflow question\", so consider this as a roadmap.\nSide note: I assume you don't want to execute the AI logic in the frontend as this will be heavy on the client.\... | [
0
] | [] | [] | [
"artificial_intelligence",
"javascript",
"nltk",
"python"
] | stackoverflow_0074563585_artificial_intelligence_javascript_nltk_python.txt |
Q:
How to merge similar columns into a single dictionary column in pandas
I am trying to convert a dataframe that has similar naming convention into a single json format column.
Sample Data:
import pandas as pd
df = pd.DataFrame({'id' : 1,
'userName' : 'john',
'productlist0.name' ... | How to merge similar columns into a single dictionary column in pandas | I am trying to convert a dataframe that has similar naming convention into a single json format column.
Sample Data:
import pandas as pd
df = pd.DataFrame({'id' : 1,
'userName' : 'john',
'productlist0.name' : 'shoe',
'productlist0.price' : 45.89,
... | [
"You can do it like:\ndf1 = df.filter(regex=\"^productlist\\d+.\").T\ndf1.index = pd.MultiIndex.from_tuples([(a[0], a[1]) for a in df1.index.str.split(\".\")])\nproduct_values = df1.unstack().droplevel(0, axis=1).to_dict(\"records\")\ndf1 = pd.concat(\n [\n df[[\"id\", \"userName\"]],\n pd.DataFram... | [
1
] | [] | [] | [
"json",
"pandas",
"python"
] | stackoverflow_0074563440_json_pandas_python.txt |
Q:
how to embed fonts in PDFs produced by matplotlib?
I'm using a font called a ttf font called FreeSans on linux with matplotlib. I create my figure as:
from matplotlib import rc
plt.rcParams['ps.useafm'] = True
rc('font',**{'family':'sans-serif','sans-serif':['FreeSans']})
plt.rcParams['pdf.fonttype'] = 42
plt.figu... | how to embed fonts in PDFs produced by matplotlib? | I'm using a font called a ttf font called FreeSans on linux with matplotlib. I create my figure as:
from matplotlib import rc
plt.rcParams['ps.useafm'] = True
rc('font',**{'family':'sans-serif','sans-serif':['FreeSans']})
plt.rcParams['pdf.fonttype'] = 42
plt.figure()
# plot figure...
plt.savefig("myfig.pdf")
When I o... | [
"I have the same problem when producing pdf with matplotlib.\nInteresting if I specify using TrueType in pdf, the font will be embedded:\nmatplotlib.rc('pdf', fonttype=42)\n\n",
"Are you sure that it's not doing it already? From the website:\n\nmatplotlib has excellent text support, including mathematical\n exp... | [
14,
2,
0
] | [] | [] | [
"matplotlib",
"pdf",
"python"
] | stackoverflow_0009054884_matplotlib_pdf_python.txt |
Q:
creating multiple file using os python
Hi folks I am using ros noetic and i have to create 12 file name as x.bag and x ranging upto 12. code is following.
import rospy
import os
for x in range(12):
cmd='rosbag record -o /home/mubashir/catkin_ws/src/germany1_trush/rosbag/x.bag /web_cam --duration 5 '
os.s... | creating multiple file using os python | Hi folks I am using ros noetic and i have to create 12 file name as x.bag and x ranging upto 12. code is following.
import rospy
import os
for x in range(12):
cmd='rosbag record -o /home/mubashir/catkin_ws/src/germany1_trush/rosbag/x.bag /web_cam --duration 5 '
os.system(cmd)
how I get vlaue of x in cmd.
cr... | [
"I'm not sure I understand your question exactly. I think what you want is to run the following command 12 times (from 0 to 11):\nimport rospy\nimport os\nfor x in range(12): \n cmd = f'rosbag record -o /home/mubashir/catkin_ws/src/germany1_trush/rosbag/{x}.bag /web_cam --duration 5'\n os.system(cmd)\n\nYou p... | [
1
] | [] | [] | [
"for_loop",
"linux",
"python"
] | stackoverflow_0074563392_for_loop_linux_python.txt |
Q:
Using "python -m" to call Python script not working
Basically the title. File structure below with code examples.
Relevant project structure:
drf/
ββ backend/
ββ py_client/
β ββ basic.py
ββ venv/
ββ requirements.txt
I know that using "python -m" is best practice for venvs, and I understand that the reason for th... | Using "python -m" to call Python script not working | Basically the title. File structure below with code examples.
Relevant project structure:
drf/
ββ backend/
ββ py_client/
β ββ basic.py
ββ venv/
ββ requirements.txt
I know that using "python -m" is best practice for venvs, and I understand that the reason for this is to use the currently activated Python version, mana... | [
"When you use -m flag you are telling python to read the script as a module, this requires a special file in the folder where your script is with the name __init__.py more info here Why init.py.\nThen you can use -m flag.\nI reproduced you error with the following structure.\nb/\n|--a/\n|--|script.py\n\nSolved addi... | [
1
] | [] | [] | [
"python",
"terminal"
] | stackoverflow_0074562771_python_terminal.txt |
Q:
Pycharm does not display database tables
After updating PyCharm (version 2017.1), PyCharm does not display sqlite3 database tables anymore.
I've tested the connection and it's working.
In sqlite client I can list all tables and make queries.
Someone else has get this problem? And in this case could solve anyway?
... | Pycharm does not display database tables | After updating PyCharm (version 2017.1), PyCharm does not display sqlite3 database tables anymore.
I've tested the connection and it's working.
In sqlite client I can list all tables and make queries.
Someone else has get this problem? And in this case could solve anyway?
| [
"I am using PyCharm Professional v2017.3.\nIn Database pane, click the plus button and add Data Source -> Sqlite (Xerial). Data Sources and Drivers settings will open up where you will see Driver: Sqlite (Xerial). This does not mean drivers are fully installed. Look at the bottom-left of the pain for a message. If ... | [
2,
1,
0,
0
] | [] | [] | [
"django",
"pycharm",
"python",
"sqlite"
] | stackoverflow_0043075420_django_pycharm_python_sqlite.txt |
Q:
Matplotlib PDF export uses wrong font
I want to generate high-quality diagrams for a presentation. Iβm using Pythonβs matplotlib to generate the graphics. Unfortunately, the PDF export seems to ignore my font settings.
I tried setting the font both by passing a FontProperties object to the text drawing functions a... | Matplotlib PDF export uses wrong font | I want to generate high-quality diagrams for a presentation. Iβm using Pythonβs matplotlib to generate the graphics. Unfortunately, the PDF export seems to ignore my font settings.
I tried setting the font both by passing a FontProperties object to the text drawing functions and by setting the option globally. For the ... | [
"Basically, @Jouniβs is the right answer but since I still had some trouble getting it to work, hereβs my final solution:\n#!/usr/bin/env python2.6\n\nimport scipy\nimport matplotlib\nmatplotlib.use('cairo')\nimport matplotlib.pylab as pylab\nimport matplotlib.font_manager as fm\n\nfont = fm.FontProperties(\n ... | [
8,
3,
0,
0
] | [] | [] | [
"cairo",
"macos",
"matplotlib",
"python"
] | stackoverflow_0002797525_cairo_macos_matplotlib_python.txt |
Q:
Use Git commands within Python code
I have been asked to write a script that pulls the latest code from Git, makes a build, and performs some automated unit tests.
I found that there are two built-in Python modules for interacting with Git that are readily available: GitPython and libgit2.
What approach/module sho... | Use Git commands within Python code | I have been asked to write a script that pulls the latest code from Git, makes a build, and performs some automated unit tests.
I found that there are two built-in Python modules for interacting with Git that are readily available: GitPython and libgit2.
What approach/module should I use?
| [
"An easier solution would be to use the Python subprocess module to call git. In your case, this would pull the latest code and build:\nimport subprocess\nsubprocess.call([\"git\", \"pull\"])\nsubprocess.call([\"make\"])\nsubprocess.call([\"make\", \"test\"])\n\nDocs:\n\nsubprocess - Python 2.x\nsubprocess - Python... | [
47,
24,
21,
2,
2,
0
] | [
"If you're on Linux or Mac, why use python at all for this task? Write a shell script.\n#!/bin/sh\nset -e\ngit pull\nmake\n./your_test #change this line to actually launch the thing that does your test\n\n"
] | [
-8
] | [
"git",
"python"
] | stackoverflow_0011113896_git_python.txt |
Q:
Is it possible access a list stored in a dataframe in a vectorized manner?
Considering a dataframe like so:
data = {
'lists': [[0, 1, 2],[3, 4, 5],[6, 7, 8]],
'indexes': [0, 1, 2]
}
df = pd.DataFrame(data=data)
lists indexes
0 [0, 1, 2] 0
1 [3, 4, 5] 1
2 [6, 7, 8] 2
I want... | Is it possible access a list stored in a dataframe in a vectorized manner? | Considering a dataframe like so:
data = {
'lists': [[0, 1, 2],[3, 4, 5],[6, 7, 8]],
'indexes': [0, 1, 2]
}
df = pd.DataFrame(data=data)
lists indexes
0 [0, 1, 2] 0
1 [3, 4, 5] 1
2 [6, 7, 8] 2
I want to create a new column 'extracted_value' which would be the value contained in ... | [
"What you tried was almost ok, you only needed to put it into pd.DataFrame.apply while setting axis argument as 1 to make sure the function is applied on each row:\ndf['extracted_values'] = df.apply(lambda x: x['lists'][x['indexes']], axis=1)\ndf\n\n lists indexes extracted_values\n0 [0, 1, 2] 0 ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"vectorization"
] | stackoverflow_0074563708_dataframe_pandas_python_vectorization.txt |
Q:
Serve directory in Python 3
I've got this basic python3 server but can't figure out how to serve a directory.
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
sel... | Serve directory in Python 3 | I've got this basic python3 server but can't figure out how to serve a directory.
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
s... | [
"if you are using 3.7, you can simply serve up a directory where your html files, eg. index.html is still\npython -m http.server 8080 --bind 127.0.0.1 --directory /path/to/dir\n\nfor the docs\n",
"The simple way\nYou want to extend the functionality of SimpleHTTPRequestHandler, so you subclass it! Check for your ... | [
19,
4,
1,
0
] | [] | [] | [
"python",
"python_3.x",
"server"
] | stackoverflow_0055052811_python_python_3.x_server.txt |
Q:
Extract a number from a txt file
Apologies to all, I am rewriting the question to be clearer than before.
I have text files that are renamed like this: 1.txt, 2.txt, ... etc. (for a total of 195 files).
These text files contain two blocks made like this:
Alpha occ. eigenvalues -- -0.40198 -0.39833 -0.39431 ... | Extract a number from a txt file | Apologies to all, I am rewriting the question to be clearer than before.
I have text files that are renamed like this: 1.txt, 2.txt, ... etc. (for a total of 195 files).
These text files contain two blocks made like this:
Alpha occ. eigenvalues -- -0.40198 -0.39833 -0.39431 -0.38246 -0.38026
Alpha occ. eigenv... | [
"Assuming your data is stored in text.txt file. I only take the last 5 elements of a line.\nwith open('text.txt') as f:\n file_list = f.readlines()\nnew_list = [] \nfor sentence in file_list:\n new_list.append(sentence.replace('\\n', ''))\nlist_number = []\nfor element in new_list:\n list_number.append(ele... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074563187_python.txt |
Q:
Python Requests - Get Server IP
I'm making a small tool that tests CDN performance and would like to check where the response comes from. I thought of getting the host's IP and then using one of the geolocation API's on github to check the country.
I've tried doing so with
import socket
...
raw._fp.fp._sock.getpee... | Python Requests - Get Server IP | I'm making a small tool that tests CDN performance and would like to check where the response comes from. I thought of getting the host's IP and then using one of the geolocation API's on github to check the country.
I've tried doing so with
import socket
...
raw._fp.fp._sock.getpeername()
...however that only works w... | [
"The socket.gethostbyname() function from Python's socket library should solve your problem. You can check it out in the Python docs here.\nHere is an example of how to use it:\nimport socket\nurl=\"cdnjs.cloudflare.com\"\nprint(\"IP:\",socket.gethostbyname(url))\n\nAll you need to do is pass the url to socket.geth... | [
1,
0
] | [] | [] | [
"ip",
"networking",
"python",
"python_requests",
"sockets"
] | stackoverflow_0067459725_ip_networking_python_python_requests_sockets.txt |
Q:
vectorize a function on a 3D numpy array using a specific signature
I'd like to apply a function f(x, y) on a numpy array a of shape (N,M,2), whose last axis (2) contains the variables x and y to give in input to f.
Example.
a = np.array([[[1, 1],
[2, 1],
[3, 1]],
[[1, 2],
[2, 2],
... | vectorize a function on a 3D numpy array using a specific signature | I'd like to apply a function f(x, y) on a numpy array a of shape (N,M,2), whose last axis (2) contains the variables x and y to give in input to f.
Example.
a = np.array([[[1, 1],
[2, 1],
[3, 1]],
[[1, 2],
[2, 2],
[3, 2]],
[[1, 3],
[2, 3],
[3, 3]]])
def f... | [
"With that function, the np.vectorize result will also expect 2 arguments. 'signature' is determined by the function, not by the array(s) you expect to supply.\nIn [184]: f = np.vectorize(function_to_vectorize)\n\nIn [185]: f(1,2)\nOut[185]: array(2)\n\nIn [186]: a = np.array([[[1, 1],\n ...: [2, 1],\n ... | [
1
] | [] | [] | [
"numpy",
"python",
"vectorization"
] | stackoverflow_0074561431_numpy_python_vectorization.txt |
Q:
openpyxl - Check if sheet contains errors
I have workbook and one sheet in the workbook:
wb = openpyxl.load_workbook("path/to/workbook.xlsx")
ws = wb.worksheets[0]
How can I return all cells that contain an error in the spreadsheet?
I know there could be different types of errors (formula error, N/As, data valida... | openpyxl - Check if sheet contains errors | I have workbook and one sheet in the workbook:
wb = openpyxl.load_workbook("path/to/workbook.xlsx")
ws = wb.worksheets[0]
How can I return all cells that contain an error in the spreadsheet?
I know there could be different types of errors (formula error, N/As, data validation error etc...), just trying to see what's p... | [
"It can be so. Reading an excel file, taking only cell values and comparing them with a list of errors.\ntest.xlsx\n\n\nfrom openpyxl import load_workbook\n\nERROR_CODES = ('#NULL!', '#DIV/0!', '#VALUE!', '#REF!', '#NAME?', '#NUM!', '#N/A')\n\nwb = load_workbook('test.xlsx', data_only=True)\nws = wb.active\ncell_er... | [
1
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0074561075_openpyxl_python.txt |
Q:
beautiful soup to grab forex prices
I'm new to using beautiful soup and I have been following tutorials on scraping with it. I am trying to use it to return high and low prices from common forex pairs. Im not sure if it is the sites that I'm trying to get the information rom, but I can find the div tag that I want... | beautiful soup to grab forex prices | I'm new to using beautiful soup and I have been following tutorials on scraping with it. I am trying to use it to return high and low prices from common forex pairs. Im not sure if it is the sites that I'm trying to get the information rom, but I can find the div tag that I want the info from, I believe the text is hid... | [
"Oke, Version 2..\n\nIt seems like OP want to capture the complete table, with date.\nSince this is an HTML table, you'll need to make a custom loop that will map both the headers (th) and rows (tr > td)\n\nsteps the script takes:\n\nFind the table\n\nFor each header, append the data-date to the result object\n\nFi... | [
2,
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074563876_beautifulsoup_python.txt |
Q:
Optimize nested for loops with numpy
Suppose I have the following loop:
N=5
a=np.zeros((N,N))
for i in range(N):
for j in range(N):
for k in range(N):
for l in range(N):
a[i,j]+=np.exp(1j*(2*np.pi/N*i*k+2*np.pi*j*l))
How can I optimize this? I'm out of ideas
A:
import numpy as np
x ... | Optimize nested for loops with numpy | Suppose I have the following loop:
N=5
a=np.zeros((N,N))
for i in range(N):
for j in range(N):
for k in range(N):
for l in range(N):
a[i,j]+=np.exp(1j*(2*np.pi/N*i*k+2*np.pi*j*l))
How can I optimize this? I'm out of ideas
| [
"import numpy as np\n\nx = np.arange(N)\ni = x[:, None, None, None]\nj = x[None, :, None, None]\nk = x[None, None, :, None]\nl = x[None, None, None, :]\n\nout = np.exp(1j*(2*np.pi/N*i*k + 2*np.pi*j*l)).sum(axis=(2, 3))\n\n# >>> np.allclose(a, out)\n# True\n\n"
] | [
3
] | [] | [] | [
"for_loop",
"numpy",
"optimization",
"performance",
"python"
] | stackoverflow_0074563814_for_loop_numpy_optimization_performance_python.txt |
Q:
List of lists to Tree Diagram Print
I have a list of lists that make up a tree, similar to a top level directory with a recursive listing of directories and files. I want to visualize this as a printed tree.
How can a see a list of lists printed as a tree?
Data
tree = [
['Main University'],
['Main Univers... | List of lists to Tree Diagram Print | I have a list of lists that make up a tree, similar to a top level directory with a recursive listing of directories and files. I want to visualize this as a printed tree.
How can a see a list of lists printed as a tree?
Data
tree = [
['Main University'],
['Main University', 'Academic Affairs'],
['Main Un... | [
"if the array is not too large you can convert it to a tree first then print it\n#!/bin/env python3\nfrom collections import OrderedDict\n\ntree = [\n ['Main University'],\n ['Main University', 'Academic Affairs'],\n ['Main University', 'Academic Affairs', 'College of Health Sciences'],\n ['Main Univers... | [
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074553128_python_python_3.x.txt |
Q:
Implement touch using Python?
touch is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.
How would you implement it as a Python function? Try to be cross platform and complete.
(Current Google results ... | Implement touch using Python? | touch is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.
How would you implement it as a Python function? Try to be cross platform and complete.
(Current Google results for "python touch file" are not tha... | [
"Looks like this is new as of Python 3.4 - pathlib.\nfrom pathlib import Path\n\nPath('path/to/file.txt').touch()\n\nThis will create a file.txt at the path.\n--\n\nPath.touch(mode=0o777, exist_ok=True)\nCreate a file at this given path. If mode is given, it is combined with the processβ umask value to determine th... | [
512,
253,
46,
37,
19,
18,
8,
5,
4,
4,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"utility"
] | stackoverflow_0001158076_python_utility.txt |
Q:
Combine Pandas columns into a nested list
I am attempting to combine elements of a dataframe into a nested list. Say I have the following:
df = pd.DataFrame(np.random.randn(100,4), columns=list('abcd'))
df.head(4)
a b c d
0 0.455258 1.135895 0.573383 -0.637943
1 0.262079 -0.3... | Combine Pandas columns into a nested list | I am attempting to combine elements of a dataframe into a nested list. Say I have the following:
df = pd.DataFrame(np.random.randn(100,4), columns=list('abcd'))
df.head(4)
a b c d
0 0.455258 1.135895 0.573383 -0.637943
1 0.262079 -0.397168 -0.980062 -1.600837
2 0.921582 0.767232... | [
"Another possible solution:\ndf['e'] = df.values.tolist()\ndf['e'] = df['e'].map(lambda x: [x])\n\nOutput:\n a b c d \\\n0 -1.594129 1.692562 0.602186 -1.620295 \n1 -0.561567 -0.033658 -1.259215 1.054229 \n2 0.450852 -0.483194 0.126173 0.354781 \n3 2.060968 -0.428400 -... | [
1,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074563854_dataframe_pandas_python.txt |
Q:
Python script on PBS fails with error =>> PBS: job killed: ncpus 37.94 exceeded limit 36 (sum)
I get the error mentioned in the title when I run a python script (using Miniconda) on a PBS scheduler. I think that numpy is doing some multithreading/processing but I can't stop it from doing so. I added these lines to... | Python script on PBS fails with error =>> PBS: job killed: ncpus 37.94 exceeded limit 36 (sum) | I get the error mentioned in the title when I run a python script (using Miniconda) on a PBS scheduler. I think that numpy is doing some multithreading/processing but I can't stop it from doing so. I added these lines to my PBS script:
export MKL_NUM_THREADS=1
export NUMEXPR_NUM_THREADS=1
export OMP_NUM_THREADS=1
expor... | [
"Runtime fix from https://stackoverflow.com/a/57505958/3528321 :\ntry:\n import mkl\n mkl.set_num_threads(1)\nexcept:\n pass\n\n"
] | [
0
] | [] | [] | [
"anaconda",
"multithreading",
"numpy",
"pbs",
"python"
] | stackoverflow_0074429606_anaconda_multithreading_numpy_pbs_python.txt |
Q:
how to filter csv in python
I have a csv file named film.csv the title of each column is as follows (with a couple of example rows):
Year;Length;Title;Subject;Actor;Actress;Director;Popularity;Awards;*Image
1990;111;Tie Me Up! Tie Me Down!;Comedy;Banderas, Antonio;Abril, Victoria;AlmodΓ³var, Pedro;68;No;NicholasCag... | how to filter csv in python | I have a csv file named film.csv the title of each column is as follows (with a couple of example rows):
Year;Length;Title;Subject;Actor;Actress;Director;Popularity;Awards;*Image
1990;111;Tie Me Up! Tie Me Down!;Comedy;Banderas, Antonio;Abril, Victoria;AlmodΓ³var, Pedro;68;No;NicholasCage.png
1991;113;High Heels;Comedy;... | [
"To read and filter the data you can use next example (I'm using award == No, because you don't have movie with award == Yes and other criteria in your example):\nimport csv\nfrom collections import Counter\n\nwith open(\"data.csv\", \"r\") as f_in:\n reader = csv.DictReader(f_in, delimiter=\";\")\n data = li... | [
1,
0
] | [] | [] | [
"csv",
"parsing",
"python"
] | stackoverflow_0074562025_csv_parsing_python.txt |
Q:
Text File Manipulation using For Loop
I have a text file that looks like this:
line1 #commentA
line2
line3 #commentB
line4
line5
line6 #commentC
line7
line8
line9
line10
line11 #commentD
line12
I want to reformat it to look like this:
line1 ... | Text File Manipulation using For Loop | I have a text file that looks like this:
line1 #commentA
line2
line3 #commentB
line4
line5
line6 #commentC
line7
line8
line9
line10
line11 #commentD
line12
I want to reformat it to look like this:
line1 #commentA
line2
line3 #comm... | [
"You can use itertools.groupby:\ntext = \"\"\"\\\nline1 #commentA\nline2\nline3 #commentB\nline4\nline5\nline6 #commentC\nline7\nline8\nline9\nline10\nline11 #commentD\nline12\"\"\"\n\nfrom itertools import groupby\n\nfor _, g in groupby(text.splitlines(), ... | [
1,
0
] | [
"I think you can use lines = f.read().splitlines() instead of f.readlines()\nand in your for loop, you can do something like\nfor l in lines\n tmp = \"\"\n if '#' in l:\n print(tmp)\n tmp = \"\"\n print(l)\n else:\n tmp+=l\n ```\n\n"
] | [
-1
] | [
"file",
"python",
"string",
"text"
] | stackoverflow_0074562233_file_python_string_text.txt |
Q:
In python, how can I jump to a def?
I want to jump from def number1 to def number2.
I tried this:
def number1():
print("from here to ")
number2()
number1()
def blablabla():
print("blablabla")
blablabla()
def number2():
print("here")
number2()
but I received this error:
Traceback (most recent call ... | In python, how can I jump to a def? | I want to jump from def number1 to def number2.
I tried this:
def number1():
print("from here to ")
number2()
number1()
def blablabla():
print("blablabla")
blablabla()
def number2():
print("here")
number2()
but I received this error:
Traceback (most recent call last):
File "C:\Users\i5 9400f\Document... | [
"Python just run your code from top to bottom sequentially so if you try to access to something that is only defined later you won't succeed. What you need to do is to define all the functions first then call them later :\ndef number1():\n print(\"from here to \")\n number2()\n\ndef blablabla():\n print(\"... | [
1,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074564064_function_python.txt |
Q:
How can I fix this "IndentationError: expected an indented block"?
def remove_stopwords(text,nlp,custom_stop_words=None,remove_small_tokens=True,min_len=2):
if custom_stop_words:
nlp.Defaults.stop_words |= custom_stop_words
filtered_sentence =[]
doc = nlp (text)
for token in doc:
... | How can I fix this "IndentationError: expected an indented block"? | def remove_stopwords(text,nlp,custom_stop_words=None,remove_small_tokens=True,min_len=2):
if custom_stop_words:
nlp.Defaults.stop_words |= custom_stop_words
filtered_sentence =[]
doc = nlp (text)
for token in doc:
if token.is_stop == False:
if remove_small_token... | [
"I guess you want to use the ternary operator.\nThe format for it is x if condition else y this is on the same line and without the : after the if else.\nSo your last return statement should be :\nreturn \" \".join(filtered_sentence) if len(filtered_sentence)>0 else None\n\n",
"Your entire code is not properly in... | [
1,
1
] | [] | [] | [
"if_statement",
"nlp",
"python",
"python_3.x",
"topic_modeling"
] | stackoverflow_0074563930_if_statement_nlp_python_python_3.x_topic_modeling.txt |
Q:
how to get raw events from Firebase analytics using api without BigQuery?
I need to extract raw events from Firebase Analytics using python SDK. Actually, we can link a BigQuery to a firebase and access raw events through BigQuery. But it is not clear from the documentation is there any other ways to extract event... | how to get raw events from Firebase analytics using api without BigQuery? | I need to extract raw events from Firebase Analytics using python SDK. Actually, we can link a BigQuery to a firebase and access raw events through BigQuery. But it is not clear from the documentation is there any other ways to extract events without BigQuery?
| [
"There is an Analytics Data API that you can use to run Analytics reports and retrieve data.\nThe Google Analytics Data API gives programmatic access to users by country.\nIn Data API requests, you'll need to identify your Google Analytics 4 (GA4) property by its ID; this ID is different from the Firebase project. ... | [
0,
0
] | [] | [] | [
"api",
"firebase",
"firebase_analytics",
"google_bigquery",
"python"
] | stackoverflow_0073631180_api_firebase_firebase_analytics_google_bigquery_python.txt |
Q:
Removing lines that have strings with same hexadecimal values from a text file
I have a file in1.txt
info="0x0000b573" data="0x7" id="sp. PCU(Si)"
info="0x0000b573" data="0x00000007" id="HI all. SHa"
info="0x00010AC3" data="0x00000003" id="abc_16. PS"
info="0x00010ac3" data="0x00000045" id="hB2_RC/BS (Spr)"
info="... | Removing lines that have strings with same hexadecimal values from a text file | I have a file in1.txt
info="0x0000b573" data="0x7" id="sp. PCU(Si)"
info="0x0000b573" data="0x00000007" id="HI all. SHa"
info="0x00010AC3" data="0x00000003" id="abc_16. PS"
info="0x00010ac3" data="0x00000045" id="hB2_RC/BS (Spr)"
info="0x205" data="0x00000010" id="cgc_15. PK"
info="0x205" data="0x10" id="cgsd_GH/BS (Sc... | [
"You can use regex\nimport re\n\ns = '''info=\"0x0000b573\" data=\"0x7\" id=\"sp. PCU(Si)\"\ninfo=\"0x0000b573\" data=\"0x00000007\" id=\"HI all. SHa\"\ninfo=\"0x00010AC3\" data=\"0x00000003\" id=\"abc_16. PS\"\ninfo=\"0x00010ac3\" data=\"0x00000045\" id=\"hB2_RC/BS (Spr)\"\ninfo=\"0x205\" data=\"0x00000010\" id=\"... | [
1,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074558591_python_python_3.x.txt |
Q:
django restframework how to edit POST form
im working on api that resizes images. I want to upload just one file save it and resize and keep it in another folder.
models.py
from django.db import models
from django.conf import settings
from django_resized import ResizedImageField
from django.contrib.auth import get... | django restframework how to edit POST form | im working on api that resizes images. I want to upload just one file save it and resize and keep it in another folder.
models.py
from django.db import models
from django.conf import settings
from django_resized import ResizedImageField
from django.contrib.auth import get_user_model
User = get_user_model()
class Ima... | [
"In your Meta class of the ImageSerializer there is a fields attribute. It should only contain the files you want to upload.\nfields (\"file\")\n\nnot\nfields (\"file\", \"file1\")\n\nGoing of your intention in the comment I suggest you also add the \"file1\" to the read only fields\nread_only_fields = (\n ... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0074563888_django_django_rest_framework_python.txt |
Q:
Put a XML file inside a Python script?
I'm trying to create a face-detection script using Python's OpenCV using the haar cascade XML file.
My goal is to upload a python file to a website but due to some weird policies, I can only upload the Python file, without the XML...
The question is, is it possible to somehow... | Put a XML file inside a Python script? | I'm trying to create a face-detection script using Python's OpenCV using the haar cascade XML file.
My goal is to upload a python file to a website but due to some weird policies, I can only upload the Python file, without the XML...
The question is, is it possible to somehow put the XML file inside the Python script, ... | [
"xml = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<a>\n <b>Yes, you can embed XML in a string literal in Python.</b>\n</a>\"\"\"\n\n",
"Not answer to title but answer of your description question.\nHaar cascade doesn't support non-file XML strings. Also, if you try to put an XML file to a website and give... | [
2,
0
] | [
"First, copy the contents of the XML file into the python file and assign the whole thing to a string. Then use XML library to create a tree type data structure named root which contains the contents of the XML file. This tree is traversable and you can do what you like with it in your program:\n import xml.et... | [
-2
] | [
"python",
"string",
"xml"
] | stackoverflow_0051431774_python_string_xml.txt |
Q:
Using python bytes with winrt
I'm attempting to use BitmapDecoder from the winrt package with bytes I've read from a file with python.
I can do it if I use winrt to read the bytes from the file:
import os
from winrt.windows.storage import StorageFile, FileAccessMode
from winrt.windows.graphics.imaging import Bit... | Using python bytes with winrt | I'm attempting to use BitmapDecoder from the winrt package with bytes I've read from a file with python.
I can do it if I use winrt to read the bytes from the file:
import os
from winrt.windows.storage import StorageFile, FileAccessMode
from winrt.windows.graphics.imaging import BitmapDecoder
async def process_image... | [
"To use python bytes you do the following. The key was writer.write_bytes is not async and calling writer.store_async().\nasync def process_image(bytes_):\n stream = InMemoryRandomAccessStream()\n writer = DataWriter(stream)\n writer.write_bytes(bytes_)\n writer.store_async()\n stream.seek(0)\n\n ... | [
0
] | [] | [] | [
"python",
"windows",
"windows_runtime"
] | stackoverflow_0074554823_python_windows_windows_runtime.txt |
Q:
Best practice to rename a method parameter in a deployed Python module
Say I maintain a Python module with some method foo():
def foo(BarArg=None, AnotherArg=False):
return True
But now I'm not satisfied with the PascalCase of my argument names, and would like to rename them as such:
def foo(bar_arg=None, anot... | Best practice to rename a method parameter in a deployed Python module | Say I maintain a Python module with some method foo():
def foo(BarArg=None, AnotherArg=False):
return True
But now I'm not satisfied with the PascalCase of my argument names, and would like to rename them as such:
def foo(bar_arg=None, another_arg=False):
...
How can I introduce this change without breaking exi... | [
"You can use a decorator factory to intercept any uses of the incorrect args:\ndef re_arg(kwarg_map):\n def decorator(func):Β \n def wrapped(*args, **kwargs):\n new_kwargs = {}\n for k, v in kwargs.items():\n if k in kwarg_map:\n print(f\"DEPRECATION ... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0074564140_python.txt |
Q:
When multiple symbols and days occur, how to only keep the first occurrence of the day and symbol?
If I have a dataframe of daily data which contain symbols and different dates:
level_0 index date symbol open ... volume_10_day is_downtrending is_downtrending_lookback consolidating_10 consoli... | When multiple symbols and days occur, how to only keep the first occurrence of the day and symbol? | If I have a dataframe of daily data which contain symbols and different dates:
level_0 index date symbol open ... volume_10_day is_downtrending is_downtrending_lookback consolidating_10 consolidating_10_lookback
0 3608 3608 2022-10-26 CIFR 0.8600 ... 3883.2 0 ... | [
"Per the discussion in the comments, this solution works:\ndf_filtered.drop_duplicates(subset=['date'], keep='first', inplace=True)\n\n"
] | [
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074554462_numpy_pandas_python.txt |
Q:
How to split a column into 4 columns based on spaces in python?
I have seen similar questions, but it seems all would not work in Python 3.8. I have a dataframe like
index id
0 0001 01 12537.30 0
1 0001 01 1278.50 1
2 0001 03 53.10 0
where id column should be split into 4 columns, but they are in one column... | How to split a column into 4 columns based on spaces in python? | I have seen similar questions, but it seems all would not work in Python 3.8. I have a dataframe like
index id
0 0001 01 12537.30 0
1 0001 01 1278.50 1
2 0001 03 53.10 0
where id column should be split into 4 columns, but they are in one column now. I need to split it based on space.
I have tried
df2 = df1['id']... | [
"Instead of going through the hassle of splitting the column, the easy path for you would be to create a new Dataframe with read_csv method where the sep argument as spaces or tab (whatever you have there) and skiprows argument as 1 and names=[co1, col2, col3,...].\nHere is an example to further clarify the above ... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0069453110_pandas_python.txt |
Q:
Where can I find a catalogue of error messages for the standard packages in Python?
I am referring to Errors like
ValueError: dictionary update sequence element #0 has length 1; 2 is required
which happen when you
>>> a_dictionary = {}
>>> a_dictionary.update([[1]])
Is there a place where these Errors for standa... | Where can I find a catalogue of error messages for the standard packages in Python? | I am referring to Errors like
ValueError: dictionary update sequence element #0 has length 1; 2 is required
which happen when you
>>> a_dictionary = {}
>>> a_dictionary.update([[1]])
Is there a place where these Errors for standard packages like dictionaries are documented?
An online research didn't yield any results... | [
"I think all errors are subclasses of the Exception class. Thus, the following code will list them for you:\ndef get_all_subclasses(cls):\n all_subclasses = []\n\n for subclass in cls.__subclasses__():\n all_subclasses.append(subclass)\n all_subclasses.extend(get_all_subclasses(subclass))\n\n ... | [
0
] | [] | [] | [
"documentation",
"python"
] | stackoverflow_0074564340_documentation_python.txt |
Q:
Losing information when saving an image as uint8
So I have an image, I'm just testing it with any random Google image, that I saved as "Picture.png". Now I want to normalize that image and save it as an .npy file, so I use the code:
from PIL import Image
import numpy as np
temp = Image.open("Picture.png")
image =... | Losing information when saving an image as uint8 | So I have an image, I'm just testing it with any random Google image, that I saved as "Picture.png". Now I want to normalize that image and save it as an .npy file, so I use the code:
from PIL import Image
import numpy as np
temp = Image.open("Picture.png")
image = np.asarray(temp)
def NormalizeData(data):
return... | [
"you are normalizing the data to be between 0 and 1, then you are converting it to an integer. which will round all numbers to 0.\nyou should just multiply the numbers by 255 before using the astype(np.uint8) so numbers will be between 0 and 255 which is the correct range for unsigned 8 bit integers.\n"
] | [
2
] | [] | [] | [
"numpy",
"python",
"python_imaging_library"
] | stackoverflow_0074564391_numpy_python_python_imaging_library.txt |
Q:
How to create an object with built-in "object()" in Python?
I found there is object() which is a built-in function in Python. *You can find object() in Built-in Functions
And, the documentation says below:
Return a new featureless object. object is a base for all classes. It
has methods that are common to all ins... | How to create an object with built-in "object()" in Python? | I found there is object() which is a built-in function in Python. *You can find object() in Built-in Functions
And, the documentation says below:
Return a new featureless object. object is a base for all classes. It
has methods that are common to all instances of Python classes. This
function does not accept any argum... | [
"To create an object with object, just call it: object(). However, it is never (as noted in the comments, it may be sometimes useful, when you need to have a something but you don't care what it is) used as is. object is just the (implicit in Python 3) base class of all classes. It provides basic features, such as ... | [
2,
0
] | [] | [] | [
"built_in",
"class",
"object",
"python",
"python_3.x"
] | stackoverflow_0074434245_built_in_class_object_python_python_3.x.txt |
Q:
Flask extract value from drop down menu if value is url_for()
I want to be able to serve a static html file (located in static/{platform}/graph.html) within an iframe based on the value ({platform}) selected from a drop down menu. I also want to use the value selected in drop down menu in other places as well.
Rig... | Flask extract value from drop down menu if value is url_for() | I want to be able to serve a static html file (located in static/{platform}/graph.html) within an iframe based on the value ({platform}) selected from a drop down menu. I also want to use the value selected in drop down menu in other places as well.
Right now I have something that works for serving static html file in ... | [
"Adding a submit button that made a POST request to a new _refresh_plot endpoint allowed me to see the URL from the url_for() value from drop down menu value\nviews.py\n@app.route('/_refresh_plot', methods=['POST'])\ndef _refresh_plot():\n pattern = '\\/static\\/([\\w]+)\\/graph\\.html'\n url = request.form.g... | [
0
] | [] | [] | [
"flask",
"html",
"iframe",
"javascript",
"python"
] | stackoverflow_0074452268_flask_html_iframe_javascript_python.txt |
Q:
Pyomo with glpk solver doesn't solve anything
Shouldn't the following result in a number different than zero?
import pyomo.environ as pyo
from pyomo.opt import SolverFactory
m = pyo.ConcreteModel()
m.x = pyo.Var([1,2], domain=pyo.Reals,initialize=0)
m.obj = pyo.Objective(expr = 2*m.x[1] + 3*m.x[2],sense=pyo.minim... | Pyomo with glpk solver doesn't solve anything | Shouldn't the following result in a number different than zero?
import pyomo.environ as pyo
from pyomo.opt import SolverFactory
m = pyo.ConcreteModel()
m.x = pyo.Var([1,2], domain=pyo.Reals,initialize=0)
m.obj = pyo.Objective(expr = 2*m.x[1] + 3*m.x[2],sense=pyo.minimize)
m.c1 = pyo.Constraint(expr = 3*m.x[1] + 4*m.x[... | [
"The problem you have written is unbounded. Try changing the domain of x to NonNegativeReals or put in constraints to do same.\nYou should always check the solver status, which you seem to have skipped over and will state βunboundedβ for this model.\n"
] | [
1
] | [] | [] | [
"pyomo",
"python",
"solver"
] | stackoverflow_0074563966_pyomo_python_solver.txt |
Q:
Capturing output from bash script run using os.system() python
I'm using Python to run a bash script using os.system. The problem is that the bash executable prints so many outputs to the console which is spamming my screen. Is there any way to block all the print calls from such external routines/modules in pytho... | Capturing output from bash script run using os.system() python | I'm using Python to run a bash script using os.system. The problem is that the bash executable prints so many outputs to the console which is spamming my screen. Is there any way to block all the print calls from such external routines/modules in python?
Here is a small toy example showing the problem,
I have a small b... | [
"The os.system() does not provide a way to capture the stdout of the process which is run.\n\nos.system(command)\nExecute the command (a string) in a subshell. This is implemented by\ncalling the Standard C function system(), and has the same\nlimitations. Changes to sys.stdin, etc. are not reflected in the\nenviro... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074564067_python.txt |
Q:
Can we create a history track on Fusion spreadsheet?
I have a Fusion spreasheet on foundry which i want to track it's history whenever a user type something new on it or modify it's content
Can we do something similar?
A:
Assuming your fusion sheet is synced to a dataset, you might be able to achieve this throug... | Can we create a history track on Fusion spreadsheet? | I have a Fusion spreasheet on foundry which i want to track it's history whenever a user type something new on it or modify it's content
Can we do something similar?
| [
"Assuming your fusion sheet is synced to a dataset, you might be able to achieve this through an upstream incremental build as described here.\nSomething like:\nfrom pyspark.sql import functions as F\n\n@incremental(snapshot_inputs=['input_data'])\n@transform(\n input_data=Input(\"/path/to/snapshot/input\"),\n ... | [
0
] | [] | [] | [
"palantir_foundry",
"palantir_foundry_api",
"pyspark",
"python"
] | stackoverflow_0074564224_palantir_foundry_palantir_foundry_api_pyspark_python.txt |
Q:
Why does this for loop loop twice?
This is what I'm trying to accomplish:
list_dic_gen(['One','Two'], [['First','Second']])
is
[{'One': 'First', 'Two': 'Second'}]
As a second example of this, the function call:
list_dic_gen(['Second'], [['One'],['Third Fourth']])
would be expected to return:
[{'Second': 'One'},... | Why does this for loop loop twice? | This is what I'm trying to accomplish:
list_dic_gen(['One','Two'], [['First','Second']])
is
[{'One': 'First', 'Two': 'Second'}]
As a second example of this, the function call:
list_dic_gen(['Second'], [['One'],['Third Fourth']])
would be expected to return:
[{'Second': 'One'}, {'Second': 'Third Fourth'}]
But my cod... | [
"Because there are 2 b's in x and you are appending for both. Append acc after the inner loop.\ndef list_dic_gen(lst,lol):\n acc=[]\n a=0\n for x in lol:\n accd={}\n for b in x:\n accd[lst[a]]=b\n a += len(lst)>1 #you don't need a condition\n acc.append(accd) #append... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074564380_python.txt |
Q:
I'm trying to properly visualise this lambda problem but I'm having a lot of trouble
These 2 lines of code are from an exam paper and I'm trying to figure out how to properly visualise how the variables move about. The output is 8.
f = lambda x, y: lambda z: (x)(y)(z)
print((f)(lambda x: lambda y: x, lambda z: z *... | I'm trying to properly visualise this lambda problem but I'm having a lot of trouble | These 2 lines of code are from an exam paper and I'm trying to figure out how to properly visualise how the variables move about. The output is 8.
f = lambda x, y: lambda z: (x)(y)(z)
print((f)(lambda x: lambda y: x, lambda z: z * 2)(3)(4))
I've tried using online python visualiser websites but I still can't understan... | [
"f can be written as a function as follows:\ndef f(x, y):\n def inner(z):\n return x(y)(z)\n return inner\n\nf takes two functions, x and y. x is a function that accepts another function (y), and returns a third function that accepts an argument z.\nThe print statement calls f with a couple of anonymou... | [
3
] | [] | [] | [
"lambda",
"python",
"python_3.x"
] | stackoverflow_0074563389_lambda_python_python_3.x.txt |
Q:
'numpy.ndarray' object has no attribute 'tick_params' when plotting histograms in 'for' loop but not sure why
I have the following code.
I am trying to loop through columns of a dataframe (newerdf) and plot a histogram for each one.
I am then saving each plot as a .png file on my desktop.
However, the following co... | 'numpy.ndarray' object has no attribute 'tick_params' when plotting histograms in 'for' loop but not sure why | I have the following code.
I am trying to loop through columns of a dataframe (newerdf) and plot a histogram for each one.
I am then saving each plot as a .png file on my desktop.
However, the following code gives me the error: 'numpy.ndarray' object has no attribute 'tick_params'.
I would be so grateful for a helping ... | [
"The DataFrame.hist() function returns, according to its documentation, a matplotlib axes or a numpy array of them, if your dataframe has more then one column.\n\nThis function calls matplotlib.pyplot.hist(), on each series in the DataFrame, resulting in one histogram per column.\n\nThus in this line,\nx = newerdf[... | [
0,
0
] | [] | [] | [
"dataframe",
"histogram",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074564245_dataframe_histogram_jupyter_notebook_pandas_python.txt |
Q:
Rearranging values mixed up in incorrect columns
I'm cleaning a dataframe and have this column Description that I would like to split into 4 separate new columns(Type, Stories, Bedrooms, Bathrooms).
The column contains entries mainly in this format: Type: Detached; Style: 2-Story; 3 Bedrooms; 2 Bathrooms which is ... | Rearranging values mixed up in incorrect columns | I'm cleaning a dataframe and have this column Description that I would like to split into 4 separate new columns(Type, Stories, Bedrooms, Bathrooms).
The column contains entries mainly in this format: Type: Detached; Style: 2-Story; 3 Bedrooms; 2 Bathrooms which is the correct format I want every entry in the column to... | [
"Try using .str accessor,extract, regex, and named capture groups like this:\nregstr = 'Type: (?P<Type>.*); Style: (?P<Style>.*); (?P<Bedrooms>\\d+) Bedrooms; (?P<Bathrooms>\\d+)'\ndf.join(df['Description'].str.extract(regstr))\n\nOutput:\n Date of Sale Price(β¬) Location Year Built Size(sq ft) ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074564102_dataframe_pandas_python.txt |
Q:
Fixing Confusion Matrix plot lines
I am trying to plot a confusion matrix as shown below
cm = confusion_matrix(testY.argmax(axis=1), predictions.argmax(axis=1))
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=lb.classes_)
disp = disp.plot(include_values=True, cmap='viridis', ax=None, xticks_rot... | Fixing Confusion Matrix plot lines | I am trying to plot a confusion matrix as shown below
cm = confusion_matrix(testY.argmax(axis=1), predictions.argmax(axis=1))
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=lb.classes_)
disp = disp.plot(include_values=True, cmap='viridis', ax=None, xticks_rotation='horizontal')
plt.show()
The res... | [
"Turn the grid off\nE.g.,\nimport matplotlib.pyplot as plt\nfig, _ = plt.subplots(nrows=1, figsize=(10,10))\nax = plt.subplot(1, 1, 1)\nax.grid(False)\n\n...\n\ndisp = ConfusionMatrixDisplay(...)\n_ = disp.plot(..., ax=ax, ...)\n\n",
"cm = confusion_matrix(testY.argmax(axis=1), predictions.argmax(axis=1))\n\ndis... | [
5,
2,
0,
0,
0
] | [] | [] | [
"confusion_matrix",
"python",
"scikit_learn"
] | stackoverflow_0063591238_confusion_matrix_python_scikit_learn.txt |
Q:
Python Regular Expression - Get Text starting in the next line after the match was found
I have a question on using regular expressions in Python. This is a part of the text I am analysing.
Amit Jawaharlaz Daryanani, Evercore ISI Institutional Equities, Research Division - Senior MD & Fundamental Research Analyst... | Python Regular Expression - Get Text starting in the next line after the match was found | I have a question on using regular expressions in Python. This is a part of the text I am analysing.
Amit Jawaharlaz Daryanani, Evercore ISI Institutional Equities, Research Division - Senior MD & Fundamental Research Analyst [19]\n I have 2 as well. I guess, first off, on the channel inventory, I was hoping if you ... | [
"You can use a capture group:\n\\bAmit Jawaharlaz Daryanani\\b.*\\n\\s*(.*)\\n\n\nExplanation\n\n\\bAmit Jawaharlaz Daryanani\\b Match the name\n.*\\n Match the rest of the line and a newline\n\\s*(.*)\\n Match optional whitespace chars, and capture a whole line in group 1 followed by matching a newline\n\nSee a re... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074564654_python_regex.txt |
Q:
How to add columns to Pandas DataFrame with minute of the day, month, year using time stamp from other column?
I have a dataframe containing various data, including a column from Linux Timestamp. For further analysis, I need to extract the minutes of each period (hour minute number, day minute number, week minute ... | How to add columns to Pandas DataFrame with minute of the day, month, year using time stamp from other column? | I have a dataframe containing various data, including a column from Linux Timestamp. For further analysis, I need to extract the minutes of each period (hour minute number, day minute number, week minute number, month minute number, year minute number) from the Linux Timestamp column.
I have:
TimeStamp var1 var2
16... | [
"import pandas as pd\n\n# Your dataframe here:\ndf = pd.DataFrame({\n \"Timestamp\": [1659494100, 1659494160, 1659494220, 1659494280, 1659494340],\n \"var1\": [5.22, 4.33, 5.46, 4.33, 6.45],\n \"var2\": [6.34, 7.33, 7.21, 4.51, 5.67]\n})\n\ntimestamps = pd.to_datetime(df[\"Timestamp\"], unit=\"s\")\n\nfreq... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"timestamp"
] | stackoverflow_0074564536_dataframe_pandas_python_timestamp.txt |
Q:
searching values from one dataframe in another dataframe using pandas
I have two datasets, patient data and disease data.
The patient dataset has diseases written in alphanumeric code format which I want to search in the disease dataset to display the disease name.
Patient dataset snapshot
Disease dataset snapshot... | searching values from one dataframe in another dataframe using pandas | I have two datasets, patient data and disease data.
The patient dataset has diseases written in alphanumeric code format which I want to search in the disease dataset to display the disease name.
Patient dataset snapshot
Disease dataset snapshot
I want use groupby function on the ICD column and find out the occurrence... | [
"Assuming that the data you have are in two pandas dataframes called patients and diseases and that the diseases dataset has the column names disease_id and disease_name this could be a solution:\njoined = patients.merge(diseases, left_on='ICD', right_on='disease_id')\n\ntop_5 = joined.disease_name.value_counts().h... | [
0
] | [] | [] | [
"columnsorting",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074564513_columnsorting_dataframe_numpy_pandas_python.txt |
Q:
Finding the median of a list of even numbers
I'm doing a coding challenge where I need to find the min, max, average and median of a list and output two tuples (one of them being squared).
I've managed to output the correct results apart from the median of a list that has odd numbers (e.g. ([7,2,4,5]) should retur... | Finding the median of a list of even numbers | I'm doing a coding challenge where I need to find the min, max, average and median of a list and output two tuples (one of them being squared).
I've managed to output the correct results apart from the median of a list that has odd numbers (e.g. ([7,2,4,5]) should return [(2, 4.5, 4.5, 7), (4, 23.5, 20.5, 49)].
Instead... | [
"If usage of python standard library is not prohibited by the rules of your contest I would go with\nfrom statistics import median\nmedian(l)\n\n"
] | [
1
] | [] | [] | [
"list",
"python",
"statistics"
] | stackoverflow_0074564696_list_python_statistics.txt |
Q:
Converting indices in marching cubes to original x,y,z space - visualizing isosurface 3d skimage
I want to draw a volume in x1,x2,x3-space. The volume is an isocurve found by the marching cubes algorithm in skimage. The function generating the volume is pdf_grid = f(x1,x2,x3) and
I want to draw the volume where p... | Converting indices in marching cubes to original x,y,z space - visualizing isosurface 3d skimage | I want to draw a volume in x1,x2,x3-space. The volume is an isocurve found by the marching cubes algorithm in skimage. The function generating the volume is pdf_grid = f(x1,x2,x3) and
I want to draw the volume where pdf = 60% max(pdf).
My issue is that the marching cubes algorithm generates vertices and faces, but how... | [
"This is probably way too late of an answer to help OP, but in case anyone else comes across this post looking for a solution to this problem, the issue stems from the marching cubes algorithm outputting the relevant vertices in array space. This space is defined by the number of elements per dimension of the mesh ... | [
0
] | [] | [] | [
"isosurface",
"marching_cubes",
"python",
"scikit_image"
] | stackoverflow_0070834443_isosurface_marching_cubes_python_scikit_image.txt |
Q:
Python- Return true if all statements are true
I have a method and I want it to return true if all 3 statements are true. In case any of them is false the method should return false.
def check_valid(self, a, b):
statement1 = self.x == 0
statement2 = self.y == a
statment3 = self.z = b
... | Python- Return true if all statements are true | I have a method and I want it to return true if all 3 statements are true. In case any of them is false the method should return false.
def check_valid(self, a, b):
statement1 = self.x == 0
statement2 = self.y == a
statment3 = self.z = b
return statement1 ^ statement2 ^ statement3
I ... | [
"This way would be a better approach and much more readable:\ndef check_valid(self, a, b):\n if not self.x == 0: return False\n if not self.y == a: return False\n if not self.z == b: return False\n return True\n\n\n"
] | [
2
] | [] | [] | [
"boolean",
"boolean_logic",
"boolean_operations",
"python",
"xor"
] | stackoverflow_0074564703_boolean_boolean_logic_boolean_operations_python_xor.txt |
Q:
How to split a list into pairs in all possible ways
I have a list (say 6 elements for simplicity)
L = [0, 1, 2, 3, 4, 5]
and I want to chunk it into pairs in ALL possible ways. I show some configurations:
[(0, 1), (2, 3), (4, 5)]
[(0, 1), (2, 4), (3, 5)]
[(0, 1), (2, 5), (3, 4)]
and so on.
Here (a, b) = (b, a) ... | How to split a list into pairs in all possible ways | I have a list (say 6 elements for simplicity)
L = [0, 1, 2, 3, 4, 5]
and I want to chunk it into pairs in ALL possible ways. I show some configurations:
[(0, 1), (2, 3), (4, 5)]
[(0, 1), (2, 4), (3, 5)]
[(0, 1), (2, 5), (3, 4)]
and so on.
Here (a, b) = (b, a) and the order of pairs is not important i.e.
[(0, 1), (2,... | [
"Take a look at itertools.combinations.\nmatt@stanley:~$ python\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import itertools\n>>> list(itertools.combinations(range(6), 2))\n[(0, 1), (0, 2), (0, 3), (0,... | [
149,
61,
28,
17,
8,
8,
6,
4,
3,
2,
2,
1,
0
] | [
"Not the most efficient or fastest, but probably the easiest. The last line is a simple way to dedupe a list in python. In this case, pairs like (0,1) and (1,0) are in the output. Not sure if you'd consider those duplicates or not.\nl = [0, 1, 2, 3, 4, 5]\npairs = []\nfor x in l:\n for y in l:\n pairs.... | [
-2
] | [
"python"
] | stackoverflow_0005360220_python.txt |
Q:
Can I use python to replace bmp file header with icon file header?
Join icon header to bmp image data and create new icon. The bmp and icon are 72x72 256 color. Using a hex editor to view the headers I tried to splice these files in the correct place. It seems there are read errors anytime I try to read data from ... | Can I use python to replace bmp file header with icon file header? | Join icon header to bmp image data and create new icon. The bmp and icon are 72x72 256 color. Using a hex editor to view the headers I tried to splice these files in the correct place. It seems there are read errors anytime I try to read data from a non-text file.
from PyQt5.QtCore import QFile
# get icon header
a = o... | [
"import codecs\n\n# get 72x72 icon data\nwith codecs.open(\"images/brown.ico\", encoding='iso-8859-1') as fp:\n icon_data = fp.read()\nfp.close()\n\n# 72x72 bmp to convert to icon--- do not reduce bmp to 256 color\nwith codecs.open(\"images/tiger.bmp\", encoding='iso-8859-1') as fp:\n b = fp.read()\nfp.close(... | [
0
] | [] | [] | [
"bmp",
"file_io",
"icons",
"python"
] | stackoverflow_0074476953_bmp_file_io_icons_python.txt |
Q:
How to correctly important parent modules in submodules, while still being able to run them on their own and via main.py?
My Project has this file Structure:
src
βββ API
βΒ Β βββ API.py
βΒ Β βββ __init__.py
βββ DataBase
βΒ Β βββ CreateDB.py
βΒ Β βββ DB.py
βΒ Β βββ SpacyTags.py
βΒ Β βββ __init__.py
βββ ML
βΒ Β βββ Feature... | How to correctly important parent modules in submodules, while still being able to run them on their own and via main.py? | My Project has this file Structure:
src
βββ API
βΒ Β βββ API.py
βΒ Β βββ __init__.py
βββ DataBase
βΒ Β βββ CreateDB.py
βΒ Β βββ DB.py
βΒ Β βββ SpacyTags.py
βΒ Β βββ __init__.py
βββ ML
βΒ Β βββ FeaturePipe.py
βΒ Β βββ Labeler.py
βΒ Β βββ Predictor.py
βΒ Β βββ Transformer.py
βΒ Β βββ ModelCreator.py
βΒ Β βββ ModelOptimizer.py
βΒ Β ββ... | [
"Unfortunately, I do not believe there is a more elegant solution. Perhaps it is a limitation of python as several tutorials and other SO threads say similar:\n\nGeeks for Geeks\nSO - How to properly import parent module/other submodules in Python\n\nIn this case, I would choose the solution that best fits your nee... | [
0
] | [] | [] | [
"git_submodules",
"import",
"module",
"python"
] | stackoverflow_0074564756_git_submodules_import_module_python.txt |
Q:
how can I convert string type of special character into original?
I wanted to do maths calculation using asterick (*) but what if it is in string format? how can I convert it to normal?
I tried 4 "*" 5 and first of all, I was not even expecting it to multiply it, as the operator is in string format but it gave me ... | how can I convert string type of special character into original? | I wanted to do maths calculation using asterick (*) but what if it is in string format? how can I convert it to normal?
I tried 4 "*" 5 and first of all, I was not even expecting it to multiply it, as the operator is in string format but it gave me an error.
| [
"An asterisk in the form of a string variable cannot be converted directly to a mathematical operator; however, it is possible to take the string \"*\" and use it to perform multiplication by using an if statement.\nLet's say you are given some string variable 'operator', and two integer variables 'a' and 'b'. The ... | [
0
] | [] | [] | [
"operators",
"python",
"special_characters"
] | stackoverflow_0074564587_operators_python_special_characters.txt |
Q:
removing whitespace from dataframe titles
I am trying to remove whitespace from the titles of columns on a dataframe.
my_df=pd.DataFrame({' name_1':[1, 2],' name_2':[3, 4],})
After some research, i've tried:
my_df.columns.map(lstrip())
df.columns.to_series().map(lstrip)
these both give:
NameError: name 'lstri... | removing whitespace from dataframe titles | I am trying to remove whitespace from the titles of columns on a dataframe.
my_df=pd.DataFrame({' name_1':[1, 2],' name_2':[3, 4],})
After some research, i've tried:
my_df.columns.map(lstrip())
df.columns.to_series().map(lstrip)
these both give:
NameError: name 'lstrip' is not defined
even though mystr.lstrip() wo... | [
"Try:\nmy_df.columns = my_df.columns.str.strip()\n\n",
"lstrip is a method of the str class, therefore lstrip() alone is going to produce that error while str.lstrip() or mystr.lstrip() (whit mystr being a string) won't.\nSo, you can use\nmy_df.columns.map(str.lstrip)\n\nbut because pandas has vecorized versions ... | [
1,
1
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074564387_dataframe_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.