content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How would I constrain a method to only return one of a set of specific values in python?
Is there a pythonic way to constrain the output of a method so that it can only be one of a set? Sort of like typing but for specific values only. I hope you can see what I'm trying to get at with this snippet:
class Rule:
... | How would I constrain a method to only return one of a set of specific values in python? | Is there a pythonic way to constrain the output of a method so that it can only be one of a set? Sort of like typing but for specific values only. I hope you can see what I'm trying to get at with this snippet:
class Rule:
def evaluate(self, user_id: int) -> {"PASS", "FAIL", "ERROR"}:
...
In the above case... | [
"In python 3.8 or higher, you can use Literal types:\nfrom typing import Literal\n\nclass Rule:\n def evaluate(self, user_id: int) -> Literal[\"PASS\", \"FAIL\", \"ERROR\"]:\n ...\n\n",
"Yes there is. Commonly Enum is used for this. (https://docs.python.org/3/library/enum.html)\nfrom enum import Enum\n\... | [
4,
1
] | [] | [] | [
"methods",
"python",
"typing"
] | stackoverflow_0074319485_methods_python_typing.txt |
Q:
Split numpy array based on sequences of same neighbouring values
I have the following numpy array
import numpy as np
arr = np.array([1,1,1,2,2,2,3,3,2,2,2,1,1,1,2,2])
I split this array into parts, where each part has the same value consequently using this question
def consecutive(data, stepsize=1):
return np... | Split numpy array based on sequences of same neighbouring values | I have the following numpy array
import numpy as np
arr = np.array([1,1,1,2,2,2,3,3,2,2,2,1,1,1,2,2])
I split this array into parts, where each part has the same value consequently using this question
def consecutive(data, stepsize=1):
return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)
consecutive(ar... | [
"Analysis of your code\nYour code is quite convoluted:\nSo, let's comment\ntimes_appeared_dict = dict(zip([str(l) for l in list(np.unique(arr))], [-1]*len(list(np.unique(arr))))) # dictionary which will count the times of appearences\n# As Ahmed said, no need to use str(l) as key here. l is a better key, and we spa... | [
3,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074317725_numpy_python.txt |
Q:
rename variables in Python code using Python
I have some Python code as a string,
string = """
import numpy as nmp
y = 5
def f(x):
return nmp.sum(x) + y
x = 1
print(f(x))
"""
Using Python, I would like to rename
the import to nmp to np,
the function argument x to X (but not the x = 1), and
y to Y.
To this ... | rename variables in Python code using Python | I have some Python code as a string,
string = """
import numpy as nmp
y = 5
def f(x):
return nmp.sum(x) + y
x = 1
print(f(x))
"""
Using Python, I would like to rename
the import to nmp to np,
the function argument x to X (but not the x = 1), and
y to Y.
To this end, I must be able to identify every usage of the... | [
"The code below traverses the source code as an ast.AST object, updating names based on a provided mapping. This mapping lists the new names for the objects to be mutated, and also specifies any scopes in which the replacement should be prohibited:\nimport ast\ndef walk(tree, mp, scope=['main']):\n for i in tree.... | [
1
] | [] | [] | [
"abstract_syntax_tree",
"parsing",
"python"
] | stackoverflow_0074308592_abstract_syntax_tree_parsing_python.txt |
Q:
How to print variables with rich console
I want to print the series variable in bold and color it red after the user input is provided.
This is the code I am currently using...
series = console.input("Search [bold cyan]Series[/] :earth_asia:\n> ")
console.print('Searching for [bold red] $(series) [/]')
This is th... | How to print variables with rich console | I want to print the series variable in bold and color it red after the user input is provided.
This is the code I am currently using...
series = console.input("Search [bold cyan]Series[/] :earth_asia:\n> ")
console.print('Searching for [bold red] $(series) [/]')
This is the actual output I see...
Search Series
> samp... | [
"You need to use f-string here:\nfrom rich.console import Console\n\nconsole = Console()\n\nseries = console.input(\"Search [bold cyan]Series[/] :earth_asia:\\n> \")\nconsole.print(f'Searching for [bold red] {series} [/]')\n\nor you could do this:\nconsole.print('Searching for [bold red] {} [/]'.format(series))\n\n... | [
0
] | [] | [] | [
"python",
"rich"
] | stackoverflow_0074319436_python_rich.txt |
Q:
Seeing if a certain element is in a 2nd list without using any
This is my first time submitting here, so please bear with me on formatting.
So, I have a normal list of strings like:
name = ["Michael", "Helen", "Mike", "Joe", "Michael"]
I need to append these to another list if they don't repeat, and then later pr... | Seeing if a certain element is in a 2nd list without using any | This is my first time submitting here, so please bear with me on formatting.
So, I have a normal list of strings like:
name = ["Michael", "Helen", "Mike", "Joe", "Michael"]
I need to append these to another list if they don't repeat, and then later print out that list. So the next list would be like
norepeat_list = ["... | [
"The closest working code I can think of to your example is:\nname = [\"Michael\", \"Helen\", \"Mike\", \"Joe\", \"Michael\"]\ntime = [\"08:42:39\", \"08:39:56\", \"08:58:43\", \"09:04:03\", \"05:32:54\"]\n\nseen_names = []\nnorepeat_list = []\nfor i in range(len(name)):\n if name[i] not in seen_names:\n ... | [
2
] | [
"In this case I advise you use the \"zip\" function.\nfor n,t in zip(name,time):\n print(n,t)\n\nthis will zip the two lists together and you have access to the values of both lists.\n\n",
"As you wrote \"each name has another value associated with it in another list of times\" I assume name and time has the s... | [
-1,
-1
] | [
"python"
] | stackoverflow_0074317262_python.txt |
Q:
Function is not getting stopped at return at if conditions
I'm new to python, this below funtion is not getting stop at if condition where it needs to stop.
def check_pi_installation_status():
proc1cmd = "grep " + AppName
p1 = subprocess.Popen(['kubectl', 'get', 'pi', '-A'], stdout=subprocess.PIPE)
p2 = s... | Function is not getting stopped at return at if conditions | I'm new to python, this below funtion is not getting stop at if condition where it needs to stop.
def check_pi_installation_status():
proc1cmd = "grep " + AppName
p1 = subprocess.Popen(['kubectl', 'get', 'pi', '-A'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(proc1cmd, shell=True, stdin=p1.stdout, stdout=su... | [
"Instead of using multiple if statements, why not use if, elif and else? The main difference here is that when you have multiple if statements, all of them will run no matter what, so change it to this:\nif (imagenamepi[2] == 'Installed'):\n print(\"Successfully Installed\")\n return\nelif (imagenamepi[2] ... | [
1
] | [] | [] | [
"break",
"function",
"if_statement",
"python",
"return"
] | stackoverflow_0074318932_break_function_if_statement_python_return.txt |
Q:
How do I add Python list in order?
I want to make a code that receives a random list and stores only positive numbers.
However, if I run it with the code I wrote, I only get positive numbers, but the order is reversed. What should I do?
As an example of the code, [3, 2, 1, 0] is displayed.
I want to print this out... | How do I add Python list in order? | I want to make a code that receives a random list and stores only positive numbers.
However, if I run it with the code I wrote, I only get positive numbers, but the order is reversed. What should I do?
As an example of the code, [3, 2, 1, 0] is displayed.
I want to print this out [0, 1, 2, 3].
def filter(list):
fli... | [
"sort before returning the list\ndef filter(list):\n flist = []\n for i in list:\n if list[i]>=0:\n flist.append(list[i])\n else:\n continue\n flist.sort()\n return flist\n \nlist = [-1,-2,-3,-4,0,1,2,3]\nprint(filter(list))\n\nOutpu... | [
0,
0,
0,
0
] | [
"Try:\nprint(filter(list[::-1]))\n\n"
] | [
-1
] | [
"list",
"python"
] | stackoverflow_0074319047_list_python.txt |
Q:
RecursionError: maximum recursion depth exceeded while calling a Python object in CNN-LSTM model
I was trying to build a CNN-LSTM hybrid model for image classification with two class but at the time of fitting the model I have faced an error as RecursionError: maximum recursion depth exceeded while calling a Pytho... | RecursionError: maximum recursion depth exceeded while calling a Python object in CNN-LSTM model | I was trying to build a CNN-LSTM hybrid model for image classification with two class but at the time of fitting the model I have faced an error as RecursionError: maximum recursion depth exceeded while calling a Python object.
The code is mentioned in below,
import keras
import matplotlib.pyplot as plt
from keras.mode... | [
"you cat increase this limit with sys.setrecursionlimit(biggerlimit) but this is discouraged.\nrather, try to reshape your model so as to not hit this limit\n"
] | [
1
] | [] | [] | [
"conv_neural_network",
"deep_learning",
"lstm",
"machine_learning",
"python"
] | stackoverflow_0074319670_conv_neural_network_deep_learning_lstm_machine_learning_python.txt |
Q:
Error , Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ram to unpickle a file
I am running into this error , i can't unpickle a file on my jupyter notebook:
import os
import pickle
import joblib
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
filename = open("... | Error , Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ram to unpickle a file | I am running into this error , i can't unpickle a file on my jupyter notebook:
import os
import pickle
import joblib
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
filename = open("loan_model3.pkl", "rb")
mdl = pickle.load(filename)
mdl.close()
and it always shows the below error message , even th... | [
"I got the same error too when I was trying to store my Sequential model in .pkl file, since Sequential model is a TensorFlow Keras model so we have to store it in .h5 file and Keras saves models in this format as it can easily store the weights and model configuration in a single file.\nCode:\n from keras.models... | [
1,
0,
0,
0
] | [] | [] | [
"joblib",
"pickle",
"python",
"scikit_learn",
"tensorflow"
] | stackoverflow_0071676507_joblib_pickle_python_scikit_learn_tensorflow.txt |
Q:
Why would someone pass a string through an empty function instead of using the string directly in Python?
I am working through some old code for a tKinter GUI and at the top of their code they create the following definition:
def _(text):
return text
The code then proceeds to use the _ function around almost ... | Why would someone pass a string through an empty function instead of using the string directly in Python? | I am working through some old code for a tKinter GUI and at the top of their code they create the following definition:
def _(text):
return text
The code then proceeds to use the _ function around almost all of the strings being passed to the tKinter widgets. For example:
editmenu.add_command(label=_("Paste"), com... | [
"This is a stub for a pattern typically used for internationalization. The pattern is explicitly documented at https://docs.python.org/3/library/gettext.html#deferred-translations\n_(\"Foo\") is intended to have _ look up the string Foo in the current user's configured language.\nPutting the stub in now -- before a... | [
6
] | [] | [] | [
"internationalization",
"python",
"tkinter"
] | stackoverflow_0074319666_internationalization_python_tkinter.txt |
Q:
How to generate a list from a pandas dataframe with column name and values as nested list
How to generate a list from a pandas dataframe with column name and values as nested list?
this is my dataframe:
a b c d
0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16
i would like to generate a list
list1 = [[a,1], [a,... | How to generate a list from a pandas dataframe with column name and values as nested list | How to generate a list from a pandas dataframe with column name and values as nested list?
this is my dataframe:
a b c d
0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16
i would like to generate a list
list1 = [[a,1], [a,2], [a,3],[a,4]]
list2 = [[b,5], [b,6], [b,7],[b,8]]
| [
"One can use a list comprehension for that.\n\nFor list1\nlist1 = [[a, b] for a, b in zip(['a'] * len(df), df['a'])]\n\n[Out]: [['a', 1], ['a', 2], ['a', 3], ['a', 4]]\n\n\nFor list2:\nlist2 = [[a, b] for a, b in zip(['b'] * len(df), df['b'])]\n\n[Out]: [['b', 5], ['b', 6], ['b', 7], ['b', 8]]\n\n\n\n",
"You coul... | [
0,
0,
0
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074319612_dataframe_list_pandas_python.txt |
Q:
Download image by requests not work correct
I have a question.
Is there any possibility to download images that are currently on the website through requests, but without using the url?
In my case, it does not work, because the image on the website is different than the one under the link from which I am downloadi... | Download image by requests not work correct | I have a question.
Is there any possibility to download images that are currently on the website through requests, but without using the url?
In my case, it does not work, because the image on the website is different than the one under the link from which I am downloading it. This is due to the fact that the image cha... | [
"i'd rather try to use PIL (Python Image Library) and get a screenshot of the element's bounding box (coordinates and size). You can get those with libs like BS4 (BeautifulSoup) or Selenium.\nThen you'd have a local copy (screenshot) of what the user would see.\nA lot of sites have protection against scrapers and c... | [
0
] | [] | [] | [
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074319664_python_python_requests_web_scraping.txt |
Q:
Unexpected results from Python if statement
Here is my code which is producing some unexpected results when input value is changed. (I know that there are lot of comments in it, I was using that as a means of debugging).
age = 0
age = input("please enter your age ")
#print(age)
#int(age)
#print(type(age))
age1 = ... | Unexpected results from Python if statement | Here is my code which is producing some unexpected results when input value is changed. (I know that there are lot of comments in it, I was using that as a means of debugging).
age = 0
age = input("please enter your age ")
#print(age)
#int(age)
#print(type(age))
age1 = int(age)
#print(type(age1))
print(age1)
if age1 >... | [
"You have an error in line else: age1 < 30 second condition is not needed, just write this part as:\nif age1 > 30:\n print(\"old\")\nelse:\n print(\"young\")\n\n",
"There are only two possibilities here:\n\nAge is greater than 30\n\nAge is equal to or less than 30\n\n\nSo, you only need one if statement, an... | [
1,
0
] | [] | [] | [
"if_statement",
"python",
"user_input"
] | stackoverflow_0074319626_if_statement_python_user_input.txt |
Q:
Error after trying to import external libraries in Python : "oserror: (winerror 193) %1 is not a valid win32 application"
I have the same error when trying to import any external library in Python :
import sklearn
runfile('C:/Users/pc/.spyder-py3/temp.py', wdir='C:/Users/pc/.spyder-py3')
Traceback (most recent ca... | Error after trying to import external libraries in Python : "oserror: (winerror 193) %1 is not a valid win32 application" | I have the same error when trying to import any external library in Python :
import sklearn
runfile('C:/Users/pc/.spyder-py3/temp.py', wdir='C:/Users/pc/.spyder-py3')
Traceback (most recent call last):
File ~\.spyder-py3\temp.py:1 in <module>
import sklearn
File ~\AppData\Roaming\Python\Python39\site-packag... | [
"The error is architecture mismatch and is detailed in [SO]: Python Ctypes - loading dll throws OSError: [WinError 193] %1 is not a valid Win32 application (@CristiFati's answer).\nSo, technically this is a duplicate, but I'm going to dive a bit deeper.\nThe root cause of the error is [SO]: PyCharm doesn't recogniz... | [
0
] | [] | [] | [
"oserror",
"python",
"python_3.x",
"pywin32",
"winapi"
] | stackoverflow_0074262298_oserror_python_python_3.x_pywin32_winapi.txt |
Q:
Manipulate Data per row pandas
I'm new to pandas and need help manipulating data per row and not the whole column based on a condition.
I have a DF that contains these columns:
Repository
Age
DMZ Linux
65 days
Linux
3 days
Windows
95 days
Condition is:
if 'DMZ' in Repository and age > 60 - true
if 'DMZ' in ... | Manipulate Data per row pandas | I'm new to pandas and need help manipulating data per row and not the whole column based on a condition.
I have a DF that contains these columns:
Repository
Age
DMZ Linux
65 days
Linux
3 days
Windows
95 days
Condition is:
if 'DMZ' in Repository and age > 60 - true
if 'DMZ' in repo and age < 60 - false... | [
"You could use pandas.loc and pandas.Series.str.contains, with the invert ~ operator:\nimport pandas as pd\ndata = {'Repository':['DMZ Linux','Linux','Windows'],\n 'Age':['65 days','3 days','95 days']\n }\ndf = pd.DataFrame(data)\n\n# Create a new column with the age as an int\ndf['int_Age']=df['Age'].str... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074319195_dataframe_pandas_python.txt |
Q:
How to do a groupby of a Ray dataset using two keys?
Let’s say I want to groupby A and B and calc the sum of Sales? How should I go about it?
import pandas as pd
import ray
ray.init()
rdf = ray.data.from_pandas(pd.DataFrame({'A':[1,2,3],'B':[1,1,4],'Sales':[20,30,40]})
I did try doing rdf.groupby([‘A’,‘B’]) but ... | How to do a groupby of a Ray dataset using two keys? | Let’s say I want to groupby A and B and calc the sum of Sales? How should I go about it?
import pandas as pd
import ray
ray.init()
rdf = ray.data.from_pandas(pd.DataFrame({'A':[1,2,3],'B':[1,1,4],'Sales':[20,30,40]})
I did try doing rdf.groupby([‘A’,‘B’]) but it gives me an error stating the key column must not be a ... | [
"This is not supported yet, but it's planned to add: https://github.com/ray-project/ray/issues/25732\nThe workaround is adding a new column to the dataset, say \"C\", which combines \"A\" and \"B\" in the way you want, and then groupby column \"C\".\n"
] | [
2
] | [] | [] | [
"distributed",
"parallel_processing",
"python",
"python_3.x",
"ray"
] | stackoverflow_0074316688_distributed_parallel_processing_python_python_3.x_ray.txt |
Q:
Force recreation of logger for a given name in python
I get a regular non-root logger of the default type:
logger = logging.getLogger('a')
Now I want to change the type and get a new logger for the same name:
logging.setLoggerClass(type('NewLoggerClass', (logging.Logger,), {}))
logger = logging.getLogger('a')
I ... | Force recreation of logger for a given name in python | I get a regular non-root logger of the default type:
logger = logging.getLogger('a')
Now I want to change the type and get a new logger for the same name:
logging.setLoggerClass(type('NewLoggerClass', (logging.Logger,), {}))
logger = logging.getLogger('a')
I would like the second call to getLogger to respect the new ... | [
"You can't do this (other than low-level hackery) once a logger has been created. You'll need to call setLoggerClass() before you instantiate any loggers via getLogger().\n",
"If in doubt ... \"Use the source, Luke!\"\nSo spelunking into logging/__init__.py, one can see that a call to logging.getLogger actually i... | [
1,
1
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0074314932_logging_python.txt |
Q:
pandas.read_excel() randomly skips rows, sets cells to nan
When I read this file with pandas, only 15 of the 44 rows are read, seemingly without a system. Cell E31 is set to nan, and I'm unable to find out why.
How to reproduce:
% pip show pandas
Name: pandas
Version: 1.5.1
(...)
% python3
Python 3.10.7 (main, Sep... | pandas.read_excel() randomly skips rows, sets cells to nan | When I read this file with pandas, only 15 of the 44 rows are read, seemingly without a system. Cell E31 is set to nan, and I'm unable to find out why.
How to reproduce:
% pip show pandas
Name: pandas
Version: 1.5.1
(...)
% python3
Python 3.10.7 (main, Sep 15 2022, 01:51:29) [Clang 14.0.0 (clang-1400.0.29.102)] on darw... | [
"Thanks to Сергей Кох's answer, I was able to find the problem: Without my knowledge, there are several hidden sheets in my Excel file. Only one is visible (the one with the 44 rows), but it is not in the first position. The one in the first position is a hidden one that happens to be very similar to the visible on... | [
1,
0
] | [] | [] | [
"excel",
"pandas",
"python"
] | stackoverflow_0074313641_excel_pandas_python.txt |
Q:
RuntimeError: CUDA error encountered, when using cuml
When I use rapids I always meet errors:
Now, I run:
from cuml.datasets.regression import make_regression
data, values = make_regression(n_samples=200000, n_features=50,
n_informative=7, bias=-4.2,
no... | RuntimeError: CUDA error encountered, when using cuml | When I use rapids I always meet errors:
Now, I run:
from cuml.datasets.regression import make_regression
data, values = make_regression(n_samples=200000, n_features=50,
n_informative=7, bias=-4.2,
noise=0.3, random_state=10)
The error message is:
Traceback... | [
"RAPIDS 22.10 requires a GPU with Compute Capability 7.0 or higher on WSL 2. This requirement is documented in the installation guide at https://rapids.ai/wsl2.html.\nThe GeForce 1080 has Compute Capability 6.1, and is not supported at this time. See https://developer.nvidia.com/cuda-gpus for additional references ... | [
1
] | [] | [] | [
"cuda",
"cudf",
"docker",
"python",
"rapids"
] | stackoverflow_0074312288_cuda_cudf_docker_python_rapids.txt |
Q:
am getting identical sha256 for each json file in python
I am in a huge hashing crisis. Using the chip-0007's default format I generatedfew JSON files. Using these files I have been trying to generate sha256 hash value. And I expect a unique hash value for each file.
However, python code isn't doing so. I thought... | am getting identical sha256 for each json file in python | I am in a huge hashing crisis. Using the chip-0007's default format I generatedfew JSON files. Using these files I have been trying to generate sha256 hash value. And I expect a unique hash value for each file.
However, python code isn't doing so. I thought there might be some issue with JSON file but, it is not. Some... | [
"Because of output buffering, you're calling sha256_gen(filepath) before anything is written to the file, so you're getting the hash of an empty file. You should do that outside the with, so that the JSON file is closed and the buffer is flushed.\n with open(filepath, 'w') as f:\n ... | [
2
] | [] | [] | [
"json",
"python",
"python_3.x",
"sha256"
] | stackoverflow_0074319600_json_python_python_3.x_sha256.txt |
Q:
I have no clue why this isnt working. Seems like a simple script but I keep getting 0 as my result which I know is incorrect
rows = len(myarray[0,:])
columns = len(myarray[:,1])
number_of_coordinates = 0
i=0
j=0
while i < rows:
while j < columns:
if int(myarray[i][j]) == 1:
print("Found one... | I have no clue why this isnt working. Seems like a simple script but I keep getting 0 as my result which I know is incorrect | rows = len(myarray[0,:])
columns = len(myarray[:,1])
number_of_coordinates = 0
i=0
j=0
while i < rows:
while j < columns:
if int(myarray[i][j]) == 1:
print("Found one!")
number_of_coordinates += 1
j += 1
i += 1
print(number_of_coordinates)
Should print out a high number ... | [
"You don't reinitialize j to zero,\nrows = len(myarray[0,:])\ncolumns = len(myarray[:,1])\nnumber_of_coordinates = 0\ni=0\nj=0\nwhile i < rows:\n \n while j < columns:\n if int(myarray[i][j]) == 1:\n print(\"Found one!\")\n number_of_coordinates += 1\n j += 1\n i += 1\n ... | [
0
] | [] | [] | [
"arrays",
"if_statement",
"python",
"while_loop"
] | stackoverflow_0074320068_arrays_if_statement_python_while_loop.txt |
Q:
Dropping rows by index that doesn't exist in other dataframe
If i have 2 dataframe, let's say dfA like this:
hour distance short_summary
1 5 2.02 Overcast
2 7 1.16 Overcast
3 3 1.35 Partly Cloudy
4 12 1.17 Overcast
5 22 1.80 Overcas... | Dropping rows by index that doesn't exist in other dataframe | If i have 2 dataframe, let's say dfA like this:
hour distance short_summary
1 5 2.02 Overcast
2 7 1.16 Overcast
3 3 1.35 Partly Cloudy
4 12 1.17 Overcast
5 22 1.80 Overcast
6 9 1.72 Partly Cloudy
7 18 1.09 Pa... | [
"dfA = dfA.loc[dfB.index,:] does what you want. Here's a demonstration.\ndfA = pd.DataFrame(\n {'hour': {1: 5, 2: 7, 3: 3, 4: 12, 5: 22, 6: 9, 7: 18},\n 'distance': {1: 2.02, 2: 1.16, 3: 1.35, 4: 1.17, 5: 1.8, 6: 1.72, 7: 1.09},\n 'short_summary': {1: 'Overcast',\n 2: 'Overcast',\n 3: 'Partly_C... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074319859_dataframe_pandas_python.txt |
Q:
Find all hashtags
I have a class Tweet that contains several tweets. Then there's a list that contains all the tweets. These tweets also have users, amount of retweets and age, which is not relevant to my question. Only content matters.
tweet1 = Tweet("@realDonaldTrump", "Despite the negative press covfefe #bigsm... | Find all hashtags | I have a class Tweet that contains several tweets. Then there's a list that contains all the tweets. These tweets also have users, amount of retweets and age, which is not relevant to my question. Only content matters.
tweet1 = Tweet("@realDonaldTrump", "Despite the negative press covfefe #bigsmart", 1249, 54303)
twe... | [
"You are returning after the first iteration of the loop. You need to go through all tweets and add the hastags to a list:\ndef get_hashtags(tweets):\n result = []\n for x in tweets:\n result.extend(re.findall(r'#\\w+', x.content))\n return result\n\nFor sorting, you can use a defaultdict to add up ... | [
1
] | [] | [] | [
"list",
"oop",
"python",
"twitter"
] | stackoverflow_0074320172_list_oop_python_twitter.txt |
Q:
Problem with Regex "The string is outside the " Python
I need to get string which are not attachments.
(Is not between <li></li>)
Example:
i need this string!
<div>i need this string too!</div>
:)<li>I don't need this string!</li>:)
Result:
i need this string!
<div>i need this string too!</div>
:):)
I tried this... | Problem with Regex "The string is outside the " Python | I need to get string which are not attachments.
(Is not between <li></li>)
Example:
i need this string!
<div>i need this string too!</div>
:)<li>I don't need this string!</li>:)
Result:
i need this string!
<div>i need this string too!</div>
:):)
I tried this:
^(?!<li>.*$).*(?<!<\/li>)
But the problem is that if ther... | [
"Use re.sub() to remove the string you don't want, instead of trying to match everything else.\nresult = re.sub('<li>.*?</li>', '', text);\n\n"
] | [
0
] | [] | [] | [
"python",
"python_re",
"regex"
] | stackoverflow_0074320170_python_python_re_regex.txt |
Q:
Pandas: Grabbing values from three different columns based on values in first column
I have a dataframe that looks like this:
rowid,kepid,kepoi_name,kepler_name,koi_disposition,koi_vet_stat,koi_vet_date,koi_pdisposition,koi_score,koi_fpflag_nt,koi_fpflag_ss,koi_fpflag_co,koi_fpflag_ec,koi_disp_prov,koi_comment,koi... | Pandas: Grabbing values from three different columns based on values in first column | I have a dataframe that looks like this:
rowid,kepid,kepoi_name,kepler_name,koi_disposition,koi_vet_stat,koi_vet_date,koi_pdisposition,koi_score,koi_fpflag_nt,koi_fpflag_ss,koi_fpflag_co,koi_fpflag_ec,koi_disp_prov,koi_comment,koi_period,koi_time0bk,koi_time0,koi_eccen,koi_longp,koi_impact,koi_duration,koi_ingress,koi_... | [
"value = 10797460\ndf.loc[df['kepid']==value, ['koi_impact', 'koi_duration', 'koi_depth']]\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074320131_python.txt |
Q:
Returning a Parameter from a Python Tkinter Pop-Up-Window Entry
I am trying to create a pop up window with Tkinter where I can enter values with an entry window to use them in the main code.
Currently I am trying to simply output the input. I can't get it to work, does anyone have an idea how I can solve this prob... | Returning a Parameter from a Python Tkinter Pop-Up-Window Entry | I am trying to create a pop up window with Tkinter where I can enter values with an entry window to use them in the main code.
Currently I am trying to simply output the input. I can't get it to work, does anyone have an idea how I can solve this problem?
Here is a small snippet of my code. I have not used the variable... | [
"You need to pass in eKnopf as a parameter to take_over_Temp()\neKnopf = Entry(top, bd = 5)\neKnopf.place(x=10, y=100, width=100)\nbutton_take_Temp = Button(\n top,\n text='Set Temperature', \n fg=\"red\", \n # use a lambda to pass `eKnopf` as an argument \n command=lambda ent=eKnopf: take_over_Temp(... | [
0
] | [] | [] | [
"popupwindow",
"python",
"tkinter",
"tkinter_entry"
] | stackoverflow_0074320179_popupwindow_python_tkinter_tkinter_entry.txt |
Q:
Unexpected behaviour of python matrix (list of lists), assignment is changing whole column
please help me with a question, cause Im getting mad.
I'm creating a 0-matrix, than tried to changed it's first element value to one, but it changes the whole column instead, and I don't get why:
def id_mtrx(n):
... | Unexpected behaviour of python matrix (list of lists), assignment is changing whole column | please help me with a question, cause Im getting mad.
I'm creating a 0-matrix, than tried to changed it's first element value to one, but it changes the whole column instead, and I don't get why:
def id_mtrx(n):
m = [[0]*n]*n
m[0][0]=1
return m
here is output:
[[1, 0], [1, 0]]
while I... | [
"You are creating multiple references to the same list object instead of creating new list, try:\nn = 2\nm = [[0 for _ in range(0, n)] for _ in range (0, n)]\nm[0][0] = 1\nprint(m)\n\noutput is:\n[[1, 0], [0, 0]]\n"
] | [
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0074320267_arrays_python.txt |
Q:
Using assign to add a Series to a DataFrame in order to create a new DataFrame
Given this data frame called 'names' and a series calles 'surnames', which is sorted differently, is it possible to use the assign function to add (on the left) the series to the data frame, to create a new data frame and maintain the o... | Using assign to add a Series to a DataFrame in order to create a new DataFrame | Given this data frame called 'names' and a series calles 'surnames', which is sorted differently, is it possible to use the assign function to add (on the left) the series to the data frame, to create a new data frame and maintain the order of 'name'?
name = pd.DataFrame({'name': ['Max', 'Andre', 'Albert'],
'coun... | [
"Did you try\nname = name.assign(surname=surname)[['surname', 'name', 'country']]\n\n",
"Yep, make sure you name your series so it'll have a column name, but you just have to call concat as such:\nimport pandas as pd\nname = pd.DataFrame({'name': ['Max', 'Andre', 'Albert'],\n'country': ['Germany', 'France', 'Germ... | [
2,
1
] | [] | [] | [
"assign",
"dataframe",
"python"
] | stackoverflow_0074320247_assign_dataframe_python.txt |
Q:
Accessing the index in 'for' loops
How do I access the index while iterating over a sequence with a for loop?
xs = [8, 23, 45]
for x in xs:
print("item #{} = {}".format(index, x))
Desired output:
item #1 = 8
item #2 = 23
item #3 = 45
A:
Use the built-in function enumerate():
for idx, x in enumerate(xs):
... | Accessing the index in 'for' loops | How do I access the index while iterating over a sequence with a for loop?
xs = [8, 23, 45]
for x in xs:
print("item #{} = {}".format(index, x))
Desired output:
item #1 = 8
item #2 = 23
item #3 = 45
| [
"Use the built-in function enumerate():\nfor idx, x in enumerate(xs):\n print(idx, x)\n\nIt is non-pythonic to manually index via for i in range(len(xs)): x = xs[i] or manually manage an additional state variable.\nCheck out PEP 279 for more.\n",
"\nUsing a for loop, how do I access the loop index, from 1 to 5... | [
8194,
1203,
241,
125,
71,
64,
45,
44,
39,
20,
18,
18,
17,
17,
13,
10,
8,
7,
5,
5,
3,
2,
1,
0
] | [
"A loop with a \"counter\" variable set as an initialiser that will be a parameter, in formatting the string, as the item number.\nThe for loop accesses the \"listos\" variable which is the list. As we access the list by \"i\", \"i\" is formatted as the item price (or whatever it is).\nlistos = [8, 23, 45, 12, 78]\... | [
-4,
-5
] | [
"list",
"loops",
"python"
] | stackoverflow_0000522563_list_loops_python.txt |
Q:
How to fit a curve (3d), where points have specified normal in python?
I have following three points in 3d space with their respective normal vectors.
A, B, C are positions and N_A, N_B,and N_C are their respective normal vectors.
A = np.array([ 348.92065834, -1402.3305998, 32.69313966])
N_A = np.array([-0.86... | How to fit a curve (3d), where points have specified normal in python? | I have following three points in 3d space with their respective normal vectors.
A, B, C are positions and N_A, N_B,and N_C are their respective normal vectors.
A = np.array([ 348.92065834, -1402.3305998, 32.69313966])
N_A = np.array([-0.86925426, 0.02836434, -0.49355091])
B = np.array([282.19332067, 82.5202799... | [
"Meta-problems: next time,\n\nexplain what you're actually doing (attempting regression on interplanetary electromagnetic bow shock from satellite readings) or else this is clearly an x/y problem\ninvest some time in learning fundamental vector calculus, which is inescapable for this class of problem\n\nDo not disc... | [
0
] | [] | [] | [
"curve_fitting",
"python",
"scipy"
] | stackoverflow_0074293191_curve_fitting_python_scipy.txt |
Q:
Superimposing 2 Wind Roses into 1 Wind Rose
I have 2 dataframes (1 is a climate average and 1 is a current month) of wind speed and wind direction of the same length that I need to combine or superimpose to 1 windrose. The idea is to combine in one image, the climate average wind rose and the current month wind ro... | Superimposing 2 Wind Roses into 1 Wind Rose | I have 2 dataframes (1 is a climate average and 1 is a current month) of wind speed and wind direction of the same length that I need to combine or superimpose to 1 windrose. The idea is to combine in one image, the climate average wind rose and the current month wind rose. Most of the superimposed images use a common,... | [
"I have found a way to superimpose the two plots into one plot - simply add a new line to the call to plot the df1 wind rose with \"ax.bar(df2.wind_direction_deg, df2.wind_speed_ms, normed=True, opening=0.8, bins=np.range(0,10,1), cmap=newcmapcolor, edgecolor='None'). This is working for me.\n"
] | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python",
"rose_plot",
"windrose"
] | stackoverflow_0074269782_matplotlib_pandas_python_rose_plot_windrose.txt |
Q:
IndexError: list index out of range, error pulling 1 item from database
I'm developing an inventory control system in python and I had a problem when I need to pull data from the bank to see if it already exists
this is my code:
import mariadb
banco = mariadb.connect(
host="127.0.0.1",
user="root",
pa... | IndexError: list index out of range, error pulling 1 item from database | I'm developing an inventory control system in python and I had a problem when I need to pull data from the bank to see if it already exists
this is my code:
import mariadb
banco = mariadb.connect(
host="127.0.0.1",
user="root",
passwd="",
database="controle_estoque"
)
# Ask the user to enter data
text... | [
"Is your problem because no result is being returned from the database or because the user has entered an invalid input into textProduct?\nIf the issue is because there is nothing returned from the database, you can wrap the line giving you an error in a Try: block, with an Except: block instructing what you want t... | [
1
] | [] | [] | [
"mariadb",
"mysql",
"python"
] | stackoverflow_0074320259_mariadb_mysql_python.txt |
Q:
Visualisation of binary search tree in terminal
I am looking for a Python tool to visualize a binary search tree and also do insert and delete operations.
Something like this:
50
\
70
/ \
/ \
63 90
insert(50)
insert(70)
insert(90)
insert(63)
and
delete(70)
50
\
63
\
\
90
Does anyone ... | Visualisation of binary search tree in terminal | I am looking for a Python tool to visualize a binary search tree and also do insert and delete operations.
Something like this:
50
\
70
/ \
/ \
63 90
insert(50)
insert(70)
insert(90)
insert(63)
and
delete(70)
50
\
63
\
\
90
Does anyone have something like?
greetz
duffy6
| [
"I made it like this with binarytree and pybush:\n# from binarytree import tree\nfrom pybush import delete, add, Node\n\neingabe = int(input(\"First value: \"))\ntree_root = Node(eingabe)\nwhile True:\n eingabe2 = input(\"Add Value (i5) or remove value (r3) or exit(e): \")\n aktion = eingabe2[:1]\n wert =... | [
0,
0
] | [] | [] | [
"binary_search_tree",
"binary_tree",
"data_visualization",
"python",
"tree"
] | stackoverflow_0071785033_binary_search_tree_binary_tree_data_visualization_python_tree.txt |
Q:
Does that make sense to make a list of dataframes and analyze the list elements pair wise?
I am querying several signals from InfluxDB to the Pandas dataframe every 5 minutes. If these signals meet a specific condition, I add the dataframes to the list. Then I want to take dataframes pair wise and perform a calcul... | Does that make sense to make a list of dataframes and analyze the list elements pair wise? | I am querying several signals from InfluxDB to the Pandas dataframe every 5 minutes. If these signals meet a specific condition, I add the dataframes to the list. Then I want to take dataframes pair wise and perform a calculation on them.
df_list = data_pool() # data_pool() returns list of dataframes
for i in range(len... | [
"It took me a long time to find where the issue came from. The problem is that pandas dataframe got updated inside calc() function and affected the original one. To tackle this problem, I made a copy of dataframe inside the calc() function. I suggest reading this Pandas: Knowing when an operation affects the origin... | [
0
] | [] | [] | [
"dataframe",
"influxdb_python",
"python"
] | stackoverflow_0074318153_dataframe_influxdb_python_python.txt |
Q:
Combine Duplicate Rows in a Column in PySpark Dataframe
I have duplicate rows in a PySpark data frame and I want to combine and sum all of them into one row per column based on duplicate entries in one column.
Current Table
Deal_ID Title Customer In_Progress Deal_Total
30 Deal 1 Client A 350 ... | Combine Duplicate Rows in a Column in PySpark Dataframe | I have duplicate rows in a PySpark data frame and I want to combine and sum all of them into one row per column based on duplicate entries in one column.
Current Table
Deal_ID Title Customer In_Progress Deal_Total
30 Deal 1 Client A 350 900
30 Deal 1 Client A 360 850
50 Deal ... | [
"\nYou have a SQL tag, so that's how it will work in there\n\nselect \n\ndeal_id,\ntitle,\ncustomer,\nsum(in_progress) as in_progress,\nsum(deal_total) as deal_total\nfrom <table_name>\ngroup by 1,2,3\n\n\notherwise you can use the same group by function in python pandas / dataframe and apply to your datadrame:\n\n... | [
1,
1
] | [] | [] | [
"pyspark",
"python"
] | stackoverflow_0074320351_pyspark_python.txt |
Q:
SQL Query not getting values after the same query is ran
so I have this class with a class session object that initializes a session in init: self.session = Session() and then I have a run method that makes a query processes some data and then returns, and all of this is managed by the schedule module so the run m... | SQL Query not getting values after the same query is ran | so I have this class with a class session object that initializes a session in init: self.session = Session() and then I have a run method that makes a query processes some data and then returns, and all of this is managed by the schedule module so the run method runs every n seconds. My issue is the first time the fun... | [
"The way sqlalchemy sessions work, they store locally a sort of cache that doesn't get reloaded until you either run session.refresh(object) or close and reopen the session.\nThis was fixed by doing:\nwith Session() as session:\n <code>\n\ninside the run function instead of opening the session in __init__\n"
] | [
0
] | [] | [] | [
"mysql",
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0074030864_mysql_python_python_3.x_sqlalchemy.txt |
Q:
Assign constructors in class with results from 1 api call python
I'm fairly new to oop and had a quick question about constructors.
From an API call i get a large response of which I only want to preserve a subset in a class based data structure. This is the approach i was thinking about, but I think i would be ca... | Assign constructors in class with results from 1 api call python | I'm fairly new to oop and had a quick question about constructors.
From an API call i get a large response of which I only want to preserve a subset in a class based data structure. This is the approach i was thinking about, but I think i would be calling the api twice, whereas, I just want to call it once , preserve t... | [
"I'm solving like this for the moment, but curious if others have thoughts.\nclass folder():\n def __init__(self, id):\n self.id = id\n self.folder_metadata = self.get_folder_metadata(id)\n self.name = self.folder_metadata.name\n self.region = self.folder_metadata.region\n\n def get_fo... | [
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0074320039_oop_python.txt |
Q:
Add Text on Image using PIL
I have an application that loads an Image and when the user clicks it, a text area appears for this Image (using jquery), where user can write some text on the Image. Which should be added on Image.
After doing some research on it, I figured that PIL (Python Imaging Library ) can help ... | Add Text on Image using PIL | I have an application that loads an Image and when the user clicks it, a text area appears for this Image (using jquery), where user can write some text on the Image. Which should be added on Image.
After doing some research on it, I figured that PIL (Python Imaging Library ) can help me do this. So I tried couple of ... | [
"I think ImageFont module available in PIL should be helpful in solving text font size problem. Just check what font type and size is appropriate for you and use following function to change font values.\n# font = ImageFont.truetype(<font-file>, <font-size>)\n# font-file should be present in provided path.\nfont = ... | [
212,
31,
18,
13,
12,
11,
7,
3,
0
] | [
"To add text on an image file, just copy/paste the code below\n<?php\n$source = \"images/cer.jpg\";\n$image = imagecreatefromjpeg($source);\n$output = \"images/certificate\".rand(1,200).\".jpg\";\n$white = imagecolorallocate($image,255,255,255);\n$black = imagecolorallocate($image,7,94,94);\n$font_size = 30;\n$rota... | [
-9
] | [
"django",
"image",
"python",
"python_imaging_library"
] | stackoverflow_0016373425_django_image_python_python_imaging_library.txt |
Q:
I have created a automation script to automate a task in web application. How to run the same script by 4 different user roles?
I have created a automation script to automate a task in web application. But i want the same script to be run by 4 different user roles. How to do it? I'm using python language
I'm am a ... | I have created a automation script to automate a task in web application. How to run the same script by 4 different user roles? | I have created a automation script to automate a task in web application. But i want the same script to be run by 4 different user roles. How to do it? I'm using python language
I'm am a newbie.
| [
"You might need to run your script for the different users.\nimport getpass\n\nreader_id = input(\"Enter UserID for reader: \")\nreader_pw = getpass.getpass(\"Password: \")\n\nauthor_id = input(\"Enter UserID for author: \")\nauthor_pw = getpass.getpass(\"Password: \")\n\nadmin_id = input(\"Enter UserID for admin: ... | [
0
] | [] | [] | [
"automation",
"python",
"selenium"
] | stackoverflow_0074320452_automation_python_selenium.txt |
Q:
Anaconda3 2.4 with python 3.5 installation error (procedure entry not found; Windows 10)
I have just made up my mind to change from python 2.7 to python 3.5 and therefore tried to reinstall Anaconda (64 bit) with the 3.5 environment. When I try to install the package I get several errors in the form of (translatio... | Anaconda3 2.4 with python 3.5 installation error (procedure entry not found; Windows 10) | I have just made up my mind to change from python 2.7 to python 3.5 and therefore tried to reinstall Anaconda (64 bit) with the 3.5 environment. When I try to install the package I get several errors in the form of (translation from German, so maybe not exact):
The procedure entry "__telemetry_main_return_trigger" cou... | [
"Finally I have found the reason. So, if anybody else has this problem:\nHere the entry points are an issue as well and Michael Sarahan gives the solution. Install the Visual C++ Redistributable for Visual Studio 2015, which is used by the new version of python, first. After that install the Anaconda-package and it... | [
9,
2,
2,
0,
0,
0,
0
] | [] | [] | [
"anaconda",
"failed_installation",
"python",
"python_3.x"
] | stackoverflow_0033625683_anaconda_failed_installation_python_python_3.x.txt |
Q:
numerical output expected, ConditionSet() returned
I'm working on my master's thesis where I've encountered a problem with trying to program a formula to calculate the payback period of a solar installation taking the rising energy prices into consideration.
the code I've used is as follows:
from sympy import *
x ... | numerical output expected, ConditionSet() returned | I'm working on my master's thesis where I've encountered a problem with trying to program a formula to calculate the payback period of a solar installation taking the rising energy prices into consideration.
the code I've used is as follows:
from sympy import *
x = symbols("x")
Eq1 = x
Eq2 = 3 / (1 * (1 + 0.02)**x)
pri... | [
"That's because you used solveset, which returns a set as output. Now, you could try to use solve, but in this case it would raise a NotImplementedError.\nSince you are interested to a numerical solution, you can try nsolve and provide an initial guess:\n# solve Eq2 - Eq1=0 for x, taking 2 as the initial guess\nnso... | [
3
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074315614_python_sympy.txt |
Q:
How to make a batch of image patches, not separate patches
I have written some lines of code to extract 5 bounding boxes/patches of a single image. When I run this code and print its output shape it's something like this (5, 256), five patches each with a vector of 256. The problem is the separate extraction of pa... | How to make a batch of image patches, not separate patches | I have written some lines of code to extract 5 bounding boxes/patches of a single image. When I run this code and print its output shape it's something like this (5, 256), five patches each with a vector of 256. The problem is the separate extraction of patches from a single image, when I feed 5000+ images to this code... | [
"You can create a ImagePatchesAndEmbedding layer that will stack the captured bounding boxes and apply xception:\nclass ImagePatchesAndEmbedding(keras.layers.Layer):\n def __init__(self, crop_size, num_boxes=5, minval=0, maxval=1):\n super(ImagePatchesAndEmbedding, self).__init__()\n self.crop_siz... | [
1
] | [] | [] | [
"keras",
"python",
"scikit_learn",
"tensorflow"
] | stackoverflow_0074313417_keras_python_scikit_learn_tensorflow.txt |
Q:
How do I Filter a viewlist based on a selection made on a createview form? Django
I am learning how to use Python & Django. I don't have much experience, and this has been a huge learning process for me. Please forgive any ignorance in my question.
I am designing a Django app and have a few relational tables creat... | How do I Filter a viewlist based on a selection made on a createview form? Django | I am learning how to use Python & Django. I don't have much experience, and this has been a huge learning process for me. Please forgive any ignorance in my question.
I am designing a Django app and have a few relational tables created. My question involves only my first 2 models/forms/views.
Here are my models
`
class... | [
"After messing around with it longer, I was able to achieve near my goal using\nfilteredArr = rdata.filter(programname=> programname.customer_id == input.value)\n"
] | [
1
] | [] | [] | [
"django",
"html",
"json",
"python"
] | stackoverflow_0074309941_django_html_json_python.txt |
Q:
Pyplot - format label in math mode of a variable
g = 0.0
for i in range(0,5,1):
plt.plot(a,b,label='$K_{0:.2f}(x)$'.format(g))
g += 0.31
I do not manage to get the whole number in subscript in math mode, it displays just the first in subscript.
How can this issue be solved?
A:
This should work fine:
plt... | Pyplot - format label in math mode of a variable | g = 0.0
for i in range(0,5,1):
plt.plot(a,b,label='$K_{0:.2f}(x)$'.format(g))
g += 0.31
I do not manage to get the whole number in subscript in math mode, it displays just the first in subscript.
How can this issue be solved?
| [
"This should work fine:\nplt.plot(a,b,label='$K_{%s}(x)$' % \"{0:.2f}\".format(g))\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python",
"string_formatting"
] | stackoverflow_0074320580_matplotlib_python_string_formatting.txt |
Q:
Add dynamically widget in a loop, and get its name, pyQt5
I want to add a widget in a formLayout with a loop.
In an other function, I want to be able to interact with those widgets, that I have just created.
I tried with a dictionnary. But I have this error: dlg.pushb_freflechis.clicked.connect(recup_fichiers_sele... | Add dynamically widget in a loop, and get its name, pyQt5 | I want to add a widget in a formLayout with a loop.
In an other function, I want to be able to interact with those widgets, that I have just created.
I tried with a dictionnary. But I have this error: dlg.pushb_freflechis.clicked.connect(recup_fichiers_selec)
NameError: name 'recup_fichiers_selec' is not defined
from P... | [
"your code is so messy i can not understand it much! but if you want to create widgets and save them in a dictionary a simple example in pyqt (not ui) is like this which you add objects to dictionary:\nkeys = dict()\nfor i in range(1, 7):\n keys[i] = QtWidgets.QPushButton(f'key_{i}')\n keys[i].clicked.connec... | [
0
] | [] | [] | [
"pyqt5",
"python"
] | stackoverflow_0074319430_pyqt5_python.txt |
Q:
How to Concatenate a specific Value in column when Conditions are matching?
I have a SQL Code which i am trying to Convert into Pyspark?
The SQL Query looks like this: I need to Concatenate '0' at starting of 'ADDRESS_HOME' if the below Query Conditions Satisfies.
UPDATE STUDENT_DATA
SET STUDENT_DATA.ADDRES... | How to Concatenate a specific Value in column when Conditions are matching? | I have a SQL Code which i am trying to Convert into Pyspark?
The SQL Query looks like this: I need to Concatenate '0' at starting of 'ADDRESS_HOME' if the below Query Conditions Satisfies.
UPDATE STUDENT_DATA
SET STUDENT_DATA.ADDRESS_HOME = "0" & [STUDENT_DATA].ADDRESS_HOME
WHERE (((STUDENT_DATA.STATE_ABB)="T... | [
"If you want to align the ADDRESS_HOME to be 5 digits and pad with 0, you can use lpad.\ndf = df.withColumn('ADDRESS_HOME', F.lpad('ADDRESS_HOME', 5, '0'))\n\nIf you want only pad with 1 char (0), when the ADDRESS_HOME has less than 5 chars.\ndf = (df.withColumn('ADDRESS_HOME', F.when(F.length('ADDRESS_HOME') < 5, ... | [
2,
1
] | [] | [] | [
"databricks",
"pyspark",
"python"
] | stackoverflow_0074318223_databricks_pyspark_python.txt |
Q:
Extract count value from Kusto query in Python
I'm struggling with extracting the count value from a Kusto Query, in the Kusto Python SDK.
I know the query works from the UI console, but whenever I try to do so in Python, it fails.
Here's my query:
query = f"""
{table}
| where isempty({column})
| where TimeGenerat... | Extract count value from Kusto query in Python | I'm struggling with extracting the count value from a Kusto Query, in the Kusto Python SDK.
I know the query works from the UI console, but whenever I try to do so in Python, it fails.
Here's my query:
query = f"""
{table}
| where isempty({column})
| where TimeGenerated > ago(2h)
| count
"""
query_result = kusto_cl... | [
"The Kusto SDK returns multiple result sets, which includes the result set(s) of your query, in addition to the query properties and the execution statistics.\nWhat you want is the primary_results\nquery_result = dataframe_from_result_table(query_result.primary_results[0])['Count']\n\nUsing SDKs --> Python --> Expl... | [
0
] | [] | [] | [
"azure_data_explorer",
"kql",
"python"
] | stackoverflow_0074319337_azure_data_explorer_kql_python.txt |
Q:
Threads not executing concurrently
I am working with a simple Python script that controls a sensor and reads measurements from this sensor. I want to take different measurement types concurrently, the function below can be used for each type of measurement:
def measure(measurement_type, num_iterations):
file =... | Threads not executing concurrently | I am working with a simple Python script that controls a sensor and reads measurements from this sensor. I want to take different measurement types concurrently, the function below can be used for each type of measurement:
def measure(measurement_type, num_iterations):
file = open(measurement_type, 'w')
writer ... | [
"when you call your function directly in the target operation, Python will first try to evaluate what your function returns and execute its code.\nThere is a special way to indicate to the threading module that you want some arguments for your function and not call your function until the moment you start the threa... | [
1
] | [] | [] | [
"multithreading",
"python",
"python_3.x",
"python_theano",
"raspberry_pi4"
] | stackoverflow_0074320314_multithreading_python_python_3.x_python_theano_raspberry_pi4.txt |
Q:
How to Queue the multiple API requests at same time in FastAPI with Gunicorn
How can I queue the multiple API request in FastAPI.
For example if there is an API which takes 10 seconds to complete the request and there are 10 API requests at same time then how can We handle that part.
If anyone can help on this the... | How to Queue the multiple API requests at same time in FastAPI with Gunicorn | How can I queue the multiple API request in FastAPI.
For example if there is an API which takes 10 seconds to complete the request and there are 10 API requests at same time then how can We handle that part.
If anyone can help on this then it would be a great help
Thanks
I tried to use the selenium using fastAPI and Gu... | [
"Queueing is done by the server (gunicorn in your case), not by FastAPI.\nGunicorn has a backlog where the requests are being queued. You can control it using --backlog=N switch. The default backlog size is 2048, so the error is probably due to a timeout on the client. Try to increase it.\nYou can spawn multiple wo... | [
0
] | [] | [] | [
"fastapi",
"gunicorn",
"linux",
"python",
"selenium"
] | stackoverflow_0074286292_fastapi_gunicorn_linux_python_selenium.txt |
Q:
pyinstaller onefile exe and external configuration files
I created a python software, it uses configuration files in external folder.
I give an example of the folder's structure
--Src
--Src/main.py
--reader
--reader/conf.ini
when I run the comand pyinstaller --onefile main.py the final executable file main.exe con... | pyinstaller onefile exe and external configuration files | I created a python software, it uses configuration files in external folder.
I give an example of the folder's structure
--Src
--Src/main.py
--reader
--reader/conf.ini
when I run the comand pyinstaller --onefile main.py the final executable file main.exe connot read from the configuration file reader/conf.ini, but if I... | [
"Since files are read at runtime instead of compile-time, the config file would need to exist when the executable is ran. If you don't want this, you can hard-code these values as constants into your program, however, the configuration wouldn't be able to be modified unless you re-compile the source code.\n"
] | [
1
] | [] | [] | [
"exe",
"pyinstaller",
"python"
] | stackoverflow_0074320551_exe_pyinstaller_python.txt |
Q:
What is the best way to click on element with selenium where id is changing dynamically?
I have web-page where I am trying to automate publishing of products with Selenium.
You can check situation here:
https://player.vimeo.com/video/767368522?h=a8feaf8791
I am able to click onto everything else but this button (b... | What is the best way to click on element with selenium where id is changing dynamically? | I have web-page where I am trying to automate publishing of products with Selenium.
You can check situation here:
https://player.vimeo.com/video/767368522?h=a8feaf8791
I am able to click onto everything else but this button (because the id the number part is automatically generated).
I've thought of selecting it by cla... | [
"To click on the button U redu you can use any of the xpath option\nWebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, '//button[.//span[text()=\"U redu\"]]'))).click()\n\nOR\nWebDriverWait(driver, 5).until(EC.visibility_of_element_located((By.XPATH, '//button[contains(.,\"U redu\")]'))).cli... | [
0,
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"webdriverwait",
"xpath"
] | stackoverflow_0074320496_python_selenium_selenium_chromedriver_webdriverwait_xpath.txt |
Q:
Is there a way to extract data based on keyword from XML?
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Catalog>
<CatalogItemLine>
<NameValue name="Car_id">111-2020-3</NameValue>
<NameValue name="Car Name">Honda Accord</NameValue>
<NameValue name="Price at location 98134">40000</Na... | Is there a way to extract data based on keyword from XML? | <?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<Catalog>
<CatalogItemLine>
<NameValue name="Car_id">111-2020-3</NameValue>
<NameValue name="Car Name">Honda Accord</NameValue>
<NameValue name="Price at location 98134">40000</NameValue>
<NameValue name="type">Gas</NameValue>
<Name... | [
"Try the below\nimport xml.etree.ElementTree as ET\n\nxml = '''<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>\n<Catalog>\n <CatalogItemLine>\n <NameValue name=\"Car_id\">111-2020-3</NameValue>\n <NameValue name=\"Car Name\">Honda Accord</NameValue>\n <NameValue name=\"Price at locat... | [
0
] | [] | [] | [
"elementtree",
"python",
"xml",
"xml_parsing"
] | stackoverflow_0074319615_elementtree_python_xml_xml_parsing.txt |
Q:
Python - Time-weighted average Pandas, grouped by time interval
I have a time-series in a Pandas DataFrame. The timestamps can be uneven (one every 1-5 minutes), but there will always be one every 5 minutes (timestamps with minutes ending in 0,5,10,15,20,25,30,35,40,45,50,55).
Example:
2017-01-01 2:05:00 32.90
2... | Python - Time-weighted average Pandas, grouped by time interval | I have a time-series in a Pandas DataFrame. The timestamps can be uneven (one every 1-5 minutes), but there will always be one every 5 minutes (timestamps with minutes ending in 0,5,10,15,20,25,30,35,40,45,50,55).
Example:
2017-01-01 2:05:00 32.90
2017-01-01 2:07:30 29.83
2017-01-01 2:10:00 45.76
2017-01-01 2:15:... | [
"This one was tricky. I would love to see another commenter do this more efficiently, since I have a hunch there is a better way to do this. \nI also skipped one part, which is parameterizing the 15 minute value, but I point out how you might do it in the comment. This is left as an exercise for the reader :D It sh... | [
9,
1,
0,
0,
0
] | [] | [] | [
"pandas",
"python",
"time_series",
"timestamp",
"weighted_average"
] | stackoverflow_0046030055_pandas_python_time_series_timestamp_weighted_average.txt |
Q:
Python type hint: Intersection of types (class implementing interface)
I have a python class defining an interface
class InterfaceFoo:
pass
some abstract class
class AbstractBar:
pass
and perhaps a concrete class
class Bar(InterfaceFoo):
pass
implementing my interface (or, if you wish, both the inte... | Python type hint: Intersection of types (class implementing interface) | I have a python class defining an interface
class InterfaceFoo:
pass
some abstract class
class AbstractBar:
pass
and perhaps a concrete class
class Bar(InterfaceFoo):
pass
implementing my interface (or, if you wish, both the interfaces Interface Foo and AbstractBar).
Now in some situations, I would like ... | [
"The solution is indeed the typing.Protocol. However the challenge here lies in the fact that you want a combination of nominal subtyping (i.e. a type declared to inherit from another) and structural subtyping (i.e. a type has a certain interface).\nThe Protocol is defined in a way that prohibits simply using multi... | [
2
] | [] | [] | [
"python",
"python_3.x",
"type_hinting"
] | stackoverflow_0074320095_python_python_3.x_type_hinting.txt |
Q:
Cannot use list to list curson returned from find in mongodb
i am working with mongodb and i used the method find to retrieve data which is stored in a cursor, when i try to list the result using the function 'result' i can't. Do you have any idea?.It did work with other datas but i don't know why it's not working... | Cannot use list to list curson returned from find in mongodb | i am working with mongodb and i used the method find to retrieve data which is stored in a cursor, when i try to list the result using the function 'result' i can't. Do you have any idea?.It did work with other datas but i don't know why it's not working here. I thank you in advance for your help.
The script is:
cursor... | [
"Your (current) error has nothing to do with converting the cursor to a list. Rather your error is that the code is not successfully connecting to (specifically authenticating with) the database. The very last line of the error you pasted:\npymongo.errors.OperationFailure: Authentication failed., full error: {'ok':... | [
0
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0074317775_mongodb_python.txt |
Q:
getting a NameError: name 'a' is not defined
def compa9():
a=int(input("enter the first number"))
b=int(input("enter the second number"))
compa9()
if a==b:
a==a
b==b
print("they are equal")
if a>b:
a==a
b==b
print (a,"is bigger and") (b,"is smaller")
if a<b:
a==a
b==b
p... | getting a NameError: name 'a' is not defined | def compa9():
a=int(input("enter the first number"))
b=int(input("enter the second number"))
compa9()
if a==b:
a==a
b==b
print("they are equal")
if a>b:
a==a
b==b
print (a,"is bigger and") (b,"is smaller")
if a<b:
a==a
b==b
print (b,"is bigger and") (a,"is smaller")
#i tr... | [
"As the top comment indicates, defining a variable in a function does not make that variable accessible within the global scope. Here is one change to your function that results in the functionality that you seem to be expecting.\ndef compa9():\n a=int(input(\"enter the first number\"))\n b=int(input(\"enter ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074320584_python.txt |
Q:
Formatting the months and dates in a subplot
I am trying to create a time series of the sea surface temperature data over the whole year for six consecutive years and plot them using the subplots. I want to mark the x-ticks as the months. I tried using the matplotlib.dates option. However the years doesn't change ... | Formatting the months and dates in a subplot | I am trying to create a time series of the sea surface temperature data over the whole year for six consecutive years and plot them using the subplots. I want to mark the x-ticks as the months. I tried using the matplotlib.dates option. However the years doesn't change on the subsequent subplots.
import numpy as np
imp... | [
"I love NumPy as much as the next person but this is a good use case for pandas. Pandas has the advantage of being able to label rows with more meaningful things than just positional index. For example, you can use dates. This is very convenient.\nFirst, load your data:\nimport pandas as pd\nimport glob\n\ndfs = []... | [
1,
0
] | [] | [] | [
"datetime_format",
"matplotlib",
"numpy",
"python",
"time_series"
] | stackoverflow_0074308612_datetime_format_matplotlib_numpy_python_time_series.txt |
Q:
Throttle PySpark batch write to Event Hubs
I am trying to write a script to send data to Event Hubs from a PySpark dataframe. This script should be able to use Spark to send anywhere from single events to millions. I have used this guide as a reference point; however, since I am using df.write.format("eventhubs").... | Throttle PySpark batch write to Event Hubs | I am trying to write a script to send data to Event Hubs from a PySpark dataframe. This script should be able to use Spark to send anywhere from single events to millions. I have used this guide as a reference point; however, since I am using df.write.format("eventhubs").options(**conf).save() instead of using Structur... | [
"I tried to reproduce the same in my environment and I got below results:\nInstall this libraire: com.microsoft.azure:azure-eventhubs-spark_2.12:2.3.22\n\nPlease follow below syntax and connection String Endpoint:\n\nCode:\n\nconnectionString = \"Endpoint=sb://<Namespase>.servicebus.windows.net/<Event_hub_name>;En... | [
0
] | [] | [] | [
"apache_spark",
"azure_eventhub",
"databricks",
"pyspark",
"python"
] | stackoverflow_0074020494_apache_spark_azure_eventhub_databricks_pyspark_python.txt |
Q:
ElasticSearch keyword match vector
first of all, sorry if what I'm asking is stupid, but I'm very new to Elastic Search. Here's what I need to do: I have an array of keywords that I need to search for in every document of an index. Here's the mapping:
{
"resumes": {
"mappings": {
"properties": {
... | ElasticSearch keyword match vector | first of all, sorry if what I'm asking is stupid, but I'm very new to Elastic Search. Here's what I need to do: I have an array of keywords that I need to search for in every document of an index. Here's the mapping:
{
"resumes": {
"mappings": {
"properties": {
"text": {
"type": "text",
... | [
"Using scripts in elasticsearch is not healthy because they are not performative. I managed to do what you want but I warn you about performance issues.\nIn field \"vector_field\" your have your matrix.\nPOST idx_teste/_doc \n{\n \"description\": \"Hello there, I've only programmed in python.\"\n}\n\nPOST idx_test... | [
0
] | [] | [] | [
"elasticsearch",
"elk",
"keyword",
"python"
] | stackoverflow_0074309126_elasticsearch_elk_keyword_python.txt |
Q:
decode the word in a way that every letter x, if it is the ith letter of the alpha starting from the left, replace it with the ith chara from right
Problem
The code is to decode the word in such a way that For every letter x, if it is the ith letter of
the alphabet starting from the left, replace it with the ith l... | decode the word in a way that every letter x, if it is the ith letter of the alpha starting from the left, replace it with the ith chara from right | Problem
The code is to decode the word in such a way that For every letter x, if it is the ith letter of
the alphabet starting from the left, replace it with the ith letter starting from the right.
. For example, the string 'abcd' would be encoded to 'zyxw'.
Note: all the letters of the word are lower case alphabets
Ed... | [
"At the risk of doing your homework for you...\ndef codeword(word: str) -> str:\n ABC = 'abcdefghijklmnopqrstuvwxyz'\n encoded_chars = [ABC[-ABC.index(char) - 1] for char in word.lower()]\n return ''.join(encoded_chars)\n\n\nprint(codeword('aaa'))\n# => 'zzz'\nprint(codeword('abc'))\n# => 'zyx'\nprint(code... | [
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074320618_python_string.txt |
Q:
Numba: double free or corruption (!prev) Aborted (core dumped)
I'm trying to speed up the following function using numba.
import numpy as np
from numba import jit, prange
@jit(nopython=True, parallel=True)
def find_reg_numba(states):
reg = []
states_sum = np.sum(states, axis=1)
for i in prange(st... | Numba: double free or corruption (!prev) Aborted (core dumped) | I'm trying to speed up the following function using numba.
import numpy as np
from numba import jit, prange
@jit(nopython=True, parallel=True)
def find_reg_numba(states):
reg = []
states_sum = np.sum(states, axis=1)
for i in prange(states.shape[0]):
if states_sum[i] > 0 and states_sum[i] < 5:
... | [
"Not sure why your code produces an error. Related error posts are:\n\nnumpy double free or corruption (!prev) segmentation fault\nError in `python': double free or corruption (!prev)\nPython double free error for huge datasets\n\nHowever, these proved unhelpful.\nHere's an alternative Numba version of find_reg_nu... | [
2,
0
] | [] | [] | [
"numba",
"numpy",
"python"
] | stackoverflow_0060207653_numba_numpy_python.txt |
Q:
Regex: Remove all special characters that are not apostrophes between letters
I have a string like so:
s = "i'm sorry, sir, but this is a 'gluten-free' restaurant. we don't serve bread."
and I am trying to use re.sub to replace all special characters that are not apostrophes between letters with a space, so 'glut... | Regex: Remove all special characters that are not apostrophes between letters | I have a string like so:
s = "i'm sorry, sir, but this is a 'gluten-free' restaurant. we don't serve bread."
and I am trying to use re.sub to replace all special characters that are not apostrophes between letters with a space, so 'gluten-free' becomes gluten free and i'm will stay as i'm.
I have tried this:
import re... | [
"You may use this regex with a nested lookahead+lookbehind:\n>>> s = \"i'm sorry, sir, but this is a 'gluten-free' restaurant. we don't serve bread.\"\n>>> print ( re.sub(r\"(?!(?<=[a-z])'[a-z])[^\\w\\s]\", ' ', s, flags=re.I) )\ni'm sorry sir but this is a gluten free restaurant we don't serve bread\n\nRegEx ... | [
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0064091221_python_regex.txt |
Q:
beautiful soup, looking for class isn't working returns only the table of content header?
So the idea is to scrap this particular page
getting started with python perlego
so the idea is for a particular book, we look at the table of content and return every heading from Title Page to other books you may like
by us... | beautiful soup, looking for class isn't working returns only the table of content header? | So the idea is to scrap this particular page
getting started with python perlego
so the idea is for a particular book, we look at the table of content and return every heading from Title Page to other books you may like
by using inspect element i found the tag and classes the table was using
however in my following co... | [
"The data about TOC is loaded from external URL via JavaScript. You can use the requests/json modules to load it:\nimport json\nimport requests\n\n# the number at the end of URL is ID of the boook:\najax_url = \"https://api.perlego.com/metadata/v2/metadata/books/toc/921329\"\ndata = requests.get(ajax_url).json()\n\... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_requests",
"web_scraping"
] | stackoverflow_0074320227_beautifulsoup_python_python_requests_web_scraping.txt |
Q:
list range and length function in python
I have got this error
TypeError: string indices must be integers
I am try to call this function
def encrypt():
text = input("Type your message:\n").lower()
for i in alphabet:
if i == text[range(len(text)]:
print(i)
alphabet = ['a', '... | list range and length function in python | I have got this error
TypeError: string indices must be integers
I am try to call this function
def encrypt():
text = input("Type your message:\n").lower()
for i in alphabet:
if i == text[range(len(text)]:
print(i)
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k... | [
"range(len(text)) is a range function\nIt was to be an integer in string indices text[range(len(text)] not a range function.\nLike text[0] or text[1] , etc,\nthat's why you are getting TypeError: string indices must be integers\nI am not sure what exactly are you trying, here is a guess:\ndef encrypt():\n\n text... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074317983_python.txt |
Q:
How to get solve NoReverseMatch Django 2.0
I'm a novice to Python and Django. I am learning it from a tutorial but stuck in between. Already tried with some other StackOverflow solution but no luck. The following error I'm getting
Error: NoReverseMatch at /catalog/
Someone, please help me with the mistake that I h... | How to get solve NoReverseMatch Django 2.0 | I'm a novice to Python and Django. I am learning it from a tutorial but stuck in between. Already tried with some other StackOverflow solution but no luck. The following error I'm getting
Error: NoReverseMatch at /catalog/
Someone, please help me with the mistake that I have made.
url.py
urlpatterns += [
path('book... | [
"I had the same problem, I solved it by adding a for loop to the book_renew_librarian template\n{% block content %}\n\n{% for bookinst in bookinstance_list %}\n\n\n <h1>Renew: {{ book_instance.book.title }}</h1>- <a href=\"{% url 'renew-book-librarian' bookinst.id %}\">Renew</a> \n <p>Borrower: {{ book_instance... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0052690001_django_python.txt |
Q:
There is currently a lease on the blob and no lease ID was specified in the request
I am using python sdk for this and want to perform move to blob from one container to another but lease creating problem after breaking the lease also.
from azure.storage.blob import BlobLeaseClient, BlobServiceClient
from app.... | There is currently a lease on the blob and no lease ID was specified in the request | I am using python sdk for this and want to perform move to blob from one container to another but lease creating problem after breaking the lease also.
from azure.storage.blob import BlobLeaseClient, BlobServiceClient
from app.models.remediation import RemediationRequest, RemediationType
from app.shared.azure_s... | [
"I tried in my environment and got below results:\nIn my environment I have an two containers with name\n\nTest\nTest1\n\nPortal:\n\nIn test container,I have a blob with leased state and also normal state.\nPortal(test container):\n\nAfter I tried with below code and the file is broken with lease and successfully c... | [
0
] | [] | [] | [
"azure",
"azure_blob_storage",
"azure_storage_files",
"blobstorage",
"python"
] | stackoverflow_0074217563_azure_azure_blob_storage_azure_storage_files_blobstorage_python.txt |
Q:
Python noob question. Looping through all to find correct combination
Sorry for noob question. Just started learning coding with Python - beginners level.
Wasn't able to find in the net what I require.
Creating function to loop through the entire line, in order to find right combination - 7,8,9 - regardless of inp... | Python noob question. Looping through all to find correct combination | Sorry for noob question. Just started learning coding with Python - beginners level.
Wasn't able to find in the net what I require.
Creating function to loop through the entire line, in order to find right combination - 7,8,9 - regardless of input length and of target position, and return 'true' if found. Wasn't able t... | [
"The answer offered by @Carson is entirely correct.\nI offer this not really as an answer to the question but as an alternative and more efficient approach.\nIn OP's question he is looking for an occurrence of 3 consecutive values described by way of a list. Let's call that a triplet.\nIf we iterate over the input ... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074278899_python.txt |
Q:
How to solve this def function
Hi I am new to python I need to write program that does write with def function.
I basically need to that if I write anyting it will convert from small word to big and contrariwise and last is if I write number than it adds +5 so basically if I write 5 It will show number 10. I dont... | How to solve this def function | Hi I am new to python I need to write program that does write with def function.
I basically need to that if I write anyting it will convert from small word to big and contrariwise and last is if I write number than it adds +5 so basically if I write 5 It will show number 10. I dont knwo how to wrtie the last step. I ... | [
"It is very difficult to make sense of what you were thinking with your attempt. However, here is a function that has the behavior you describe.\ndef vyp(a):\n if a.isdigit():\n return str(int(a)+5)\n return a.swapcase()\n\nprint(vyp(\"22\")) # 27\nprint(vyp(\"HellO\")) # hELLo\n\nNote that this o... | [
0
] | [] | [] | [
"converters",
"function",
"python"
] | stackoverflow_0074320790_converters_function_python.txt |
Q:
AttributeError: type object 'WordFamily' has no attribute 'words
when I call the check_type function, it would appear AttributeError: type object 'WordFamily' has no attribute 'words'
class WordFamily:
def __init__(self, words, suffixes):
self.words = words
self.suffixes = suffixes
def check_type(... | AttributeError: type object 'WordFamily' has no attribute 'words | when I call the check_type function, it would appear AttributeError: type object 'WordFamily' has no attribute 'words'
class WordFamily:
def __init__(self, words, suffixes):
self.words = words
self.suffixes = suffixes
def check_type(word):
for w in WordFamily.words:
if word in w or word + Wor... | [
"I think you should refactor your class so check_type accepts self as the first argument and you can therefore reference instance variables. Otherwise check_type is trying to act like a @class_method but the values are not intended to act that way in your case.\nclass WordFamily:\n def __init__(self, words, suffix... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074320788_python.txt |
Q:
Resume execution of python process after killing parent
I'm sorry if this has been asked before - I just don't know how to search for the right answer and would be very thankful for a pointer.
I'm trying to do the following in Python (on Linux):
import psutil
from time import sleep
from subprocess import run
from ... | Resume execution of python process after killing parent | I'm sorry if this has been asked before - I just don't know how to search for the right answer and would be very thankful for a pointer.
I'm trying to do the following in Python (on Linux):
import psutil
from time import sleep
from subprocess import run
from shlex import split
psutil.Process().parent().kill()
sleep(3)... | [
"If you run this code in terminal, your parent process will be shell(bash is default shell in my system). If session leader (which is shell in this context) that has a controlling terminal die, then SIGHUP signal is sent by linux kernel to each process in the foreground job, and the controlling terminal is disassoc... | [
0
] | [] | [] | [
"process",
"python",
"subprocess"
] | stackoverflow_0074317794_process_python_subprocess.txt |
Q:
Mean of largest and smallest number in a list of three numbers that are inputted
I am trying to figure out how to find the average of the largest and smallest number out of three numbers that are inputted into the program.
number1 = int(input('Enter First number : '))
number2 = int(input('Enter Second number : '))... | Mean of largest and smallest number in a list of three numbers that are inputted | I am trying to figure out how to find the average of the largest and smallest number out of three numbers that are inputted into the program.
number1 = int(input('Enter First number : '))
number2 = int(input('Enter Second number : '))
number3 = int(input('Enter Third number : '))
def largest(num1, num2, num3):
if (... | [
"IIRC the mean is all the numbers added and then divided by the number of terms you added.\nLets say I entered 1, 2, and 3 for each of the inputs. I would add the max and min up to get 4 and then divide that by 2(there are 2 numbers I added together, min and max) to get the mean average of 2 (4/2 = 2).\nHeres your ... | [
0
] | [] | [] | [
"mean",
"python"
] | stackoverflow_0074320890_mean_python.txt |
Q:
Using list comprehension to get attributes of objects
I want to make a list comprehension that stores a specific attribute of several objects and prints them to the screen.
This is what I tried:
class TextBox(object):
def __init__(self, text=""):
self.text = text
// imagine there are several TextBox o... | Using list comprehension to get attributes of objects | I want to make a list comprehension that stores a specific attribute of several objects and prints them to the screen.
This is what I tried:
class TextBox(object):
def __init__(self, text=""):
self.text = text
// imagine there are several TextBox objects in this list
textContainer = []
print([i.text for i... | [
"The error is because you didn't write the list comprehension correctly. You should set a variable, e.g., i, as the representative of the elements of the list through which you're iterating, and use it to get the attribute you want, e.g., i.text:\nprint([i.text for i in textContainer])\n\n"
] | [
0
] | [] | [] | [
"nameerror",
"python"
] | stackoverflow_0074321005_nameerror_python.txt |
Q:
List of tuples of arbitrary length to nested dictionary
So I have a list of tuples of the form:
my_list=[('a','aa','aaa',0),('a','aa','aab',1),('a','ab','aba',2)]
And I need it to convert it to a nested dictionary:
out={'a':{'aa':{'aaa':0,'aab':1},'ab':{'aba':2}}}
The crucial piece of my setting is that I do not... | List of tuples of arbitrary length to nested dictionary | So I have a list of tuples of the form:
my_list=[('a','aa','aaa',0),('a','aa','aab',1),('a','ab','aba',2)]
And I need it to convert it to a nested dictionary:
out={'a':{'aa':{'aaa':0,'aab':1},'ab':{'aba':2}}}
The crucial piece of my setting is that I do not know in advance the length of the tuples in my_list (4 is ju... | [
"Just loop over the first keys, setting aside the last pair of items which will be a key-value pair, and set dictionaries in-between (using setdefault here, but you could do that part manually):\nresult = {}\nfor *keys, last_key, value in my_list:\n current = result\n for key in keys:\n current = curre... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074321001_python_python_3.x.txt |
Q:
Cryptographically-secure, exactly-weighted sampling
How do I choose k elements with replacement and weights under the following conditions?
Randomness must be cryptographically-secure, e.g. as used in the secrets module.
Weighting must be exact, i.e. use integral instead of floating-point arithmetic.
Self-author... | Cryptographically-secure, exactly-weighted sampling | How do I choose k elements with replacement and weights under the following conditions?
Randomness must be cryptographically-secure, e.g. as used in the secrets module.
Weighting must be exact, i.e. use integral instead of floating-point arithmetic.
Self-authored code is likely to be less secure and efficient than av... | [
"I would just rip apart the choices implemention from the random module. Something like:\nfrom random import SystemRandom\nfrom itertools import accumulate as _accumulate, repeat as _repeat\nfrom bisect import bisect as _bisect\n\ndef choices(population, weights, *, k=1):\n randrange = SystemRandom().randrange\... | [
1
] | [] | [] | [
"python",
"python_3.x",
"random"
] | stackoverflow_0074320740_python_python_3.x_random.txt |
Q:
How to exit with non zero code using Python Multiprocessing?
I have a use case where I want my script that runs multiple functions parallelly using multiprocessing to exit with non zero code and that should stop running the script immediately on seeing the return code 1 or errors from any of the functions.
Here i... | How to exit with non zero code using Python Multiprocessing? | I have a use case where I want my script that runs multiple functions parallelly using multiprocessing to exit with non zero code and that should stop running the script immediately on seeing the return code 1 or errors from any of the functions.
Here is what I am trying to do, not sure if my approach is correct and w... | [
"To exit completely you can just use sys.exit() without argument. Just the documentation says:\n\nThe sys.exit() function allows the developer to exit from Python. The\nexit function takes an optional argument, typically an integer, that\ngives an exit status. Zero is considered a “successful termination”.\nBe sure... | [
1,
0
] | [] | [] | [
"exit_code",
"multiprocessing",
"python"
] | stackoverflow_0074315533_exit_code_multiprocessing_python.txt |
Q:
Copying a tuple to an entire row in a dataframe
I am trying to for loop through a dataframe and copy an entire row to a temporary dataframe. row is of type tuple so how do I copy each item in the tuple to a different column of the same row in a dataframe? Please see the example of my dataframe and my desired outp... | Copying a tuple to an entire row in a dataframe | I am trying to for loop through a dataframe and copy an entire row to a temporary dataframe. row is of type tuple so how do I copy each item in the tuple to a different column of the same row in a dataframe? Please see the example of my dataframe and my desired output
Here is my dataframe df:
╔════════╦═══════════════... | [
"Assuming that your_file.csv is the first table mentioned in your example, you can read it into df and:\nSolution 1:\nParse its rows to get what you need in temp_df:\ntemp_df_records = []\n\nfor _, row in df.iterrows():\n items = row[\"Items\"].split(',')\n row_dict = row.drop(\"Items\").to_dict()\n for it... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074321004_pandas_python.txt |
Q:
What are the best method to scrape the data from the website?
I need an idea for extracting the data from 990 form schedule J where we can filter the taxpayer name and scrape the data. Is there a way.
Is there a way to scrape this - part II. I have attached a link.
https://projects.propublica.org/nonprofits/organi... | What are the best method to scrape the data from the website? | I need an idea for extracting the data from 990 form schedule J where we can filter the taxpayer name and scrape the data. Is there a way.
Is there a way to scrape this - part II. I have attached a link.
https://projects.propublica.org/nonprofits/organizations/452766110/202031279349301913/IRS990ScheduleJ
extract the da... | [
"You could explore Selenium Webdriver; the tricky part is figuring out the names/tags of the web elements that you want to get extract the data from.\n"
] | [
0
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074320780_python_web_scraping.txt |
Q:
Django - pass dict from POST form
There is a from with various elements
<input name='id' value='123'/>
<input name='some_value' value='123'/>
<!-- thing that i want-->
<input name='array[key_1]' value='value_1'/>
<input name='array[key_2]' value='value_2'/>
<input name='array[key_3]' value='value_3'/>
<input name=... | Django - pass dict from POST form | There is a from with various elements
<input name='id' value='123'/>
<input name='some_value' value='123'/>
<!-- thing that i want-->
<input name='array[key_1]' value='value_1'/>
<input name='array[key_2]' value='value_2'/>
<input name='array[key_3]' value='value_3'/>
<input name='array[key_4]' value='value_4'/>
</form... | [
"Try below code.\nviews.py:\ndef DemotimeView(request):\n if request.method == 'POST': \n data = dict(request.POST)\n del data['csrfmiddlewaretoken']\n print({i:j[0] for i,j in data.items()})\n return render(request, 'index.html',)\n\nHtml:\n<form action=\"\" method=\"post\">\n {% csr... | [
1,
0,
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0074313088_django_django_forms_django_templates_python.txt |
Q:
Iterate a nested dictionary and filter specific fields
I have an example object which is mixed of lists and dicts:
{
"field_1" : "aaa",
"field_2": [
{
"name" : "bbb",
.....
"field_4" : "ccc",
"field_need_to_filter" : False,
},
{
"name" : "d... | Iterate a nested dictionary and filter specific fields | I have an example object which is mixed of lists and dicts:
{
"field_1" : "aaa",
"field_2": [
{
"name" : "bbb",
.....
"field_4" : "ccc",
"field_need_to_filter" : False,
},
{
"name" : "ddd",
.....
"details": [
{
... | [
"Ok, it took me some time to think about the different cases and fix bugs, but this works (at least on your example of dict); note that it assumes that dicts containing \"field_need_to_filter\": True are end-points (the function doesn't delve deeper into those)). I'll be glad to add explanations to the code if you ... | [
1
] | [
"If that is your correct code, the you call iterate_fun instead of iterate_func after the check for field name of ddd\n"
] | [
-1
] | [
"dictionary",
"list",
"nested_loops",
"python",
"recursion"
] | stackoverflow_0074318573_dictionary_list_nested_loops_python_recursion.txt |
Q:
How to make a dictionary to a nested dictionary
I have a dictionary as follow:
d1 = {1:"Peter", 2:"Teddy"}
I want to make it to:
d1 = {1:"Peter", 2:"Teddy", 3:{"Oliver" : "Big"}}
I have tried but it doesn't work:
d1[3]["Oliver"]="Big"
A:
Try
d1[3] = {"Oliver": "Big"}
A:
You can first try
d1[3] = {}
Then
d1[... | How to make a dictionary to a nested dictionary | I have a dictionary as follow:
d1 = {1:"Peter", 2:"Teddy"}
I want to make it to:
d1 = {1:"Peter", 2:"Teddy", 3:{"Oliver" : "Big"}}
I have tried but it doesn't work:
d1[3]["Oliver"]="Big"
| [
"Try\nd1[3] = {\"Oliver\": \"Big\"}\n\n",
"You can first try\nd1[3] = {}\n\nThen\nd1[3][\"Oliver\"]=\"Big\"\n\n"
] | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0074321159_python.txt |
Q:
Error while running a lambda function to change all items in a series meeting certain conditions; the error returns the first item in series
I have a series from the Titanic data frame that divides the passangers by first, second and third class. The .unique_values() returned are ['1', '2', '3', '?']. I would like... | Error while running a lambda function to change all items in a series meeting certain conditions; the error returns the first item in series | I have a series from the Titanic data frame that divides the passangers by first, second and third class. The .unique_values() returned are ['1', '2', '3', '?']. I would like to change the '?' value to 'Unknown'.
I tried running the following code:
df['Pclass'] = df['Pclass'].map(lambda x: 'Unknown' if (df['Pclass'][x]... | [
"Assuming your dataframe in this form:\n Pclass\n0 1\n1 2\n2 3\n3 ?\n\nyou have to use pandas.DataFrame.apply function.\nimport pandas as pd\n\ndata = [1, 2, 3, \"?\"]\ndf = pd.DataFrame(data=data, columns=['Pclass'])\n\ndf['Pclass'] = df['Pclass'].apply(lambda x: 'Unknown' if x == '?' else x)\... | [
0
] | [] | [] | [
"dataframe",
"lambda",
"pandas",
"python",
"series"
] | stackoverflow_0074321213_dataframe_lambda_pandas_python_series.txt |
Q:
networkx: nx.draw is not drawing
I am running a simple python script on my shell.
In the script I create a simple graph(2 nodes, 1 edge) and trying to draw it to my screen.
I do not get any error, but the graph is not showing
import matplotlib
import networkx as nx
G = nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.a... | networkx: nx.draw is not drawing | I am running a simple python script on my shell.
In the script I create a simple graph(2 nodes, 1 edge) and trying to draw it to my screen.
I do not get any error, but the graph is not showing
import matplotlib
import networkx as nx
G = nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_edge(1, 2)
nx.draw(G)
I don't get ... | [
"Maybe try\nimport matplotlib.pyplot as plt \nimport networkx as nx\n\nG = nx.DiGraph()\nG.add_node(1)\nG.add_node(2)\nG.add_edge(1, 2)\nnx.draw(G)\nplt.draw()\n\nthis works for me\n",
"I needed to add\nimport pylab\npylab.show()\n\nas followed:\nimport pylab\nimport matplotlib \nimport networkx as nx\n\nG = nx.D... | [
1,
0,
0
] | [] | [] | [
"matplotlib",
"networkx",
"python"
] | stackoverflow_0066713697_matplotlib_networkx_python.txt |
Q:
Gunicorn Flask app does not doing system commands
This is my code`
@app.route('/social_add/<us_id>/<us_phone>/<us_birth>/<us_gen>', methods=['POST', 'GET'])
def social_add(us_id, us_phone, us_birth, us_gen):
os.system("sudo chmod 777 /home/gor/tarber/static/user_image")
os.system("mkdir /ho... | Gunicorn Flask app does not doing system commands | This is my code`
@app.route('/social_add/<us_id>/<us_phone>/<us_birth>/<us_gen>', methods=['POST', 'GET'])
def social_add(us_id, us_phone, us_birth, us_gen):
os.system("sudo chmod 777 /home/gor/tarber/static/user_image")
os.system("mkdir /home/gor/tarber/static/user_image/" + us_id)
os.s... | [
"os.mkdir(filename, mode=0o777)\n\n",
"There is a big warning block in the documentation at https://docs.python.org/3/library/subprocess.html#popen-constructor to use the full path to the executeable and that you can use shutil.which() to find it.\nso basicly\nsubprocess.Popen(\"sudo /bin/chmod 777 /home/gor/tar... | [
0,
0,
0
] | [] | [] | [
"flask",
"gunicorn",
"python",
"python_venv"
] | stackoverflow_0062211896_flask_gunicorn_python_python_venv.txt |
Q:
How to Pass a list as value of parameter in python POST method?
I am stuck into pass data as list into Ids, POST ...Please help if anyone knows it. Here is my Python Code
``
import json
import requests
from config import api_url
data = [1234, 4214]
payload = json.dumps({
"Ids": data,
"serviceProfile": "... | How to Pass a list as value of parameter in python POST method? | I am stuck into pass data as list into Ids, POST ...Please help if anyone knows it. Here is my Python Code
``
import json
import requests
from config import api_url
data = [1234, 4214]
payload = json.dumps({
"Ids": data,
"serviceProfile": "915"
})
response = requests.request("POST", api_url["url"], heade... | [
"usually you would send it as a json body\nresult requests.post(url,json={\n \"Ids\": data,\n \"serviceProfile\": \"915\"\n\n})\n\nI think is probably what you need ...\n"
] | [
0
] | [] | [] | [
"post",
"python",
"python_requests",
"rest"
] | stackoverflow_0074321261_post_python_python_requests_rest.txt |
Q:
Zshrc launching python prompt - multiple pythons
I wonder if this is all a PATH issue. I have MacBook Pro 12.6, with homebrew. No pyenv or virtualenv. (perhaps I should..) I am using nvim.
When I start iterm it launches python to the python command prompt rather than my zsh prompt. When I ctrl D it goes straight t... | Zshrc launching python prompt - multiple pythons | I wonder if this is all a PATH issue. I have MacBook Pro 12.6, with homebrew. No pyenv or virtualenv. (perhaps I should..) I am using nvim.
When I start iterm it launches python to the python command prompt rather than my zsh prompt. When I ctrl D it goes straight to the zshell prompt with no complaints.
Last login: Su... | [
"My suggestion is to start with an empty zshrc/zprofile and work back slowly from there. Add in a few lines at a time until you have what you want. Adding items one change at a time and testing is the best way to get out of this hole and find out where the included script is that is causing your issues. Once you ad... | [
1,
0
] | [] | [] | [
"iterm",
"oh_my_zsh",
"python",
"zsh"
] | stackoverflow_0074170025_iterm_oh_my_zsh_python_zsh.txt |
Q:
Django: Not Found static/admin/css
I just deployed my first Django app on Heroku but I notice that it doesn't have any CSS like when I runserver on the local machine. I know there's something wrong with static files but I don't understand much about it even when I already read the docs. I can do
python3 manage.py ... | Django: Not Found static/admin/css | I just deployed my first Django app on Heroku but I notice that it doesn't have any CSS like when I runserver on the local machine. I know there's something wrong with static files but I don't understand much about it even when I already read the docs. I can do
python3 manage.py collectstatic
to create a static folder ... | [
"You also need to add the static directory to your urls.py file. Add the following:\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n ...\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\n",
"You shouldn't change BASE_DIR\nIn settings.py ed... | [
35,
11,
5,
2,
1,
1,
0
] | [] | [] | [
"deployment",
"django",
"heroku",
"python"
] | stackoverflow_0039291223_deployment_django_heroku_python.txt |
Q:
Pytorch cosine similarity NxN elements
I have 128 vectors of embeddings
image.shape = torch.Size([128, 512])
text.shape = torch.Size([128, 512])
And I want to calculate the tensor containing the cosine similarity between all elements (i.e:
cosine.shape = torch.Size([128, 128])
Where the first row is the cosine s... | Pytorch cosine similarity NxN elements | I have 128 vectors of embeddings
image.shape = torch.Size([128, 512])
text.shape = torch.Size([128, 512])
And I want to calculate the tensor containing the cosine similarity between all elements (i.e:
cosine.shape = torch.Size([128, 128])
Where the first row is the cosine similarity between the 1st image and all text... | [
"The way pytorch computes cosine similarity internally is like this:\n def cos_sim(A, B, dim, eps=1e-08):\n numerator = torch.mul(A, B).sum(axis=dim, keepdims=True)\n A_l2 = torch.mul(A, A).sum(axis=dim, keepdims=True)\n B_l2 = torch.mul(B, B).sum(axis=dim, keepdims=True)\n denominator = torc... | [
3,
0,
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0067199317_python_pytorch.txt |
Q:
Python Min function using key: return minimum and its value
I want to get the minimum of a set using a specific ordering key. However I don't want to get just the minimum but also its value according to the used key.
Explaining this with a toy example:
The set {"0", "00", "000"} using min({"0", "00", "000"}, key =... | Python Min function using key: return minimum and its value | I want to get the minimum of a set using a specific ordering key. However I don't want to get just the minimum but also its value according to the used key.
Explaining this with a toy example:
The set {"0", "00", "000"} using min({"0", "00", "000"}, key = len) provides that the minimum is "0". But I want the answer to ... | [
"So, you could do something like:\nmin(map(lambda x: (len(x), x), my_set))\n\nDepending on the nature of my_set, this could be slightly different (since it is using the value in its comparison operation when len(x) are equal). To get the exactly equivalent behavior, you would need:\nmin(map(lambda x: (len(x), x), m... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074321242_python_python_3.x.txt |
Q:
How to make memory cache for node-red with wide external (python, LabVIEW, telnet, etc.) support?
I know how to use memcached with python, telnet, JavaScript and via server CGI scripts.
I don't know how to use memcached with node-red.
In pseudo code (~python) I want to do the following with node red:
Import memcac... | How to make memory cache for node-red with wide external (python, LabVIEW, telnet, etc.) support? | I know how to use memcached with python, telnet, JavaScript and via server CGI scripts.
I don't know how to use memcached with node-red.
In pseudo code (~python) I want to do the following with node red:
Import memcached
client = memcached.Client("127.0.0.1", 65554)
msg_payload = client.get("foo")
client.set("bar", 1)... | [
"Partial answer is like this.\nPut this into function node:\nconst server = \"localhost:11211\";\nconst client = new memcacheClient.MemcacheClient({ server });\n\nclient.set(\"key\", \"set_test_data_to_key\", (err, r) => {});\n\nclient.get(\"key\", function (err, data){\n var newMsg = { payload: data.value };\n ... | [
0
] | [] | [] | [
"iot",
"memcached",
"message_queue",
"node_red",
"python"
] | stackoverflow_0074253729_iot_memcached_message_queue_node_red_python.txt |
Q:
How to post text in desired boxes on website - then scrape the result next to it?
Unfortunately I'm stuck with the following problem and I'm kindly asking you for help:
I wanted to create a small Python script to track the prices of an electricity supplier, to to see if it's worth switching there.
The website is a... | How to post text in desired boxes on website - then scrape the result next to it? | Unfortunately I'm stuck with the following problem and I'm kindly asking you for help:
I wanted to create a small Python script to track the prices of an electricity supplier, to to see if it's worth switching there.
The website is as follows: https://tibber.com/de/stromtarif#price-calculator
The problem is, the prices... | [
"That information is being hydrated in page from an API endpoint, which you need to scrape directly (you can find it in Dev tools - Network tab). Here is one way to do it:\nimport requests\nimport pandas as pd\n\npostcode = '72535'\n\nurl = f'https://tibber.com/de/api/lookup/price-overview?postalCode={postcode}'\n\... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074320876_beautifulsoup_html_python_web_scraping.txt |
Q:
Programmatically accessing PTS times in MP4 container
Background
For a research project, we are recording video data from two cameras and feed a synchronization pulse directly into the microphone ADC every second.
Problem
We want to derive a frame time stamp in the clock of the pulse source for each camera frame t... | Programmatically accessing PTS times in MP4 container | Background
For a research project, we are recording video data from two cameras and feed a synchronization pulse directly into the microphone ADC every second.
Problem
We want to derive a frame time stamp in the clock of the pulse source for each camera frame to relate the camera images temporally. With our current met... | [
"You need to run ffprobe to retrieve the PTS times. I don't know the exact command, but if you're ok with another package, try ffmpegio:\npip install ffmpegio-core \n\n// OR \n\npip install ffmpegio // if you also want to use it to read video frames & audio samples\n\nIf you're on Windows, see this doc on where ffm... | [
1
] | [] | [] | [
"audio",
"ffmpeg",
"mp4",
"python",
"video"
] | stackoverflow_0074317331_audio_ffmpeg_mp4_python_video.txt |
Q:
How to do a left-join on a data variable's values using xarray?
Imagine having a dataset of shipments where every shipID can contain multiple products:
In [2]: shipDS
Out[2]:
<xarray.Dataset>
Dimensions: (shipID: 6)
Coordinates:
* shipID (shipID) int64 1 1 2 3 4 4
Data variables:
prodID (shipID... | How to do a left-join on a data variable's values using xarray? | Imagine having a dataset of shipments where every shipID can contain multiple products:
In [2]: shipDS
Out[2]:
<xarray.Dataset>
Dimensions: (shipID: 6)
Coordinates:
* shipID (shipID) int64 1 1 2 3 4 4
Data variables:
prodID (shipID) int64 90 91 92 90 90 91
qtyShipped (shipID) int64 1 1 1 1 1 1
... | [
"You can use xarray's Advanced Indexing rules to reindex prodDS to conform to the dimensions of shipDS:\nIn [4]: products_shipped = prodDS.sel(prodID=shipDS.prodID)\n ...: products_shipped\nOut[4]:\n<xarray.Dataset>\nDimensions: (shipID: 6)\nCoordinates:\n prodID (shipID) int64 90 91 92 90 90 91\n * ... | [
1
] | [] | [] | [
"python",
"python_xarray"
] | stackoverflow_0074318816_python_python_xarray.txt |
Q:
Compare Algorithm written in Python on a Raspberry Pi with an Algorithm written in C on a STM32
english is not my first language, so sorry for my bad writting.
i need to optimize an Algorithm, which is written with Python and running on a Raspberry Pi. The clue is, that i need to write the optimized Code as a C-Pr... | Compare Algorithm written in Python on a Raspberry Pi with an Algorithm written in C on a STM32 | english is not my first language, so sorry for my bad writting.
i need to optimize an Algorithm, which is written with Python and running on a Raspberry Pi. The clue is, that i need to write the optimized Code as a C-Programm running on a stm32f4.
It is a image-processing algorithm (i know, image-processing with C on a... | [
"\nOfcourse i need a method of benchmarking the two programms.\n\nFor embedded systems, this is always done by toggling an GPIO pin at the start and end of the algorithm, then measure the time with an oscilloscope. This should be possible on Rasp PI and a STM32 target both. But you'll be measuring raw execution spe... | [
1,
0
] | [] | [] | [
"arm",
"c",
"python",
"raspberry_pi",
"stm32"
] | stackoverflow_0074314893_arm_c_python_raspberry_pi_stm32.txt |
Q:
How to log the contents of a ConfigParser?
How can I print the contents of a Python 2.7 ConfigParser to logging?
The only solution I can find is to write to a temporary file and read that file back in. Another idea I had was to get a fake "file handle" from the logging utility and pass that to the ConfigParser wr... | How to log the contents of a ConfigParser? | How can I print the contents of a Python 2.7 ConfigParser to logging?
The only solution I can find is to write to a temporary file and read that file back in. Another idea I had was to get a fake "file handle" from the logging utility and pass that to the ConfigParser write method, but I don't know how to get such a h... | [
"As this is the top Google search result and I was hoping to find a solution to print the values of the ConfigParser instance to stdout, here's a one-liner to help all future readers:\nprint({section: dict(config[section]) for section in config.sections()})\n\n",
"You should be able to create a writable object th... | [
40,
6,
4,
0
] | [] | [] | [
"logging",
"python",
"python_2.7"
] | stackoverflow_0023662280_logging_python_python_2.7.txt |
Q:
Surround all characters
I want to "surround" all characters in a string with pipes:
'abc' => '|a|b|c|'
'abcde' => '|a|b|c|d|e|'
'x' => '|x|'
'' => '|'
What's a good way to do it, preferably as a one-line expression? Here's a way with a loop:
s = 'abcde'
t = '|'
for c in s:
t += c + '|'
print(t) ... | Surround all characters | I want to "surround" all characters in a string with pipes:
'abc' => '|a|b|c|'
'abcde' => '|a|b|c|d|e|'
'x' => '|x|'
'' => '|'
What's a good way to do it, preferably as a one-line expression? Here's a way with a loop:
s = 'abcde'
t = '|'
for c in s:
t += c + '|'
print(t) # |a|b|c|d|e|
| [
"Turns out we can create something from nothing:\ns.replace('', '|')\n\nDemo:\nfor s in 'abc', 'abcde', 'x', '':\n print(s.replace('', '|'))\n\nOutput:\n|a|b|c|\n|a|b|c|d|e|\n|x|\n|\n\n",
"You can use '|'.join(), just need to add two null strings.\ndef f(s):\n return '|'.join(['', *s, ''])\n\n>>> f('abc')\n... | [
6,
2,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074321155_python_string.txt |
Q:
Using Jupyter behind a proxy
Is there a similar config to that of .condarc (anaconda 4.0.0) that allows Jupyter to be configured to work behind a corporate proxy on a local machine?
Error received:
HTTPError: HTTP Error 407: Proxy Authentication Required
A:
Way easier: Just add the following to your notebook:
In... | Using Jupyter behind a proxy | Is there a similar config to that of .condarc (anaconda 4.0.0) that allows Jupyter to be configured to work behind a corporate proxy on a local machine?
Error received:
HTTPError: HTTP Error 407: Proxy Authentication Required
| [
"Way easier: Just add the following to your notebook:\nIn [1]: import os\n os.environ['http_proxy'] = \"http://user:passwd@host:port\" \n os.environ['https_proxy'] = \"https://user:passwd@host:port\" \n\nafter that, requests will work OK=200, e.g.\nIn [2]: import requests\n requests.get(\"https... | [
24,
12,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"anaconda",
"conda",
"jupyter",
"python"
] | stackoverflow_0036629707_anaconda_conda_jupyter_python.txt |
Q:
XML print text of child tag below two parrents
Here is my xml. I only want to print out status result and type text from childern.
<response status="success">
<result>
<job>
<tenq>2022/11/04 17:10:58</tenq>
<tdeq>17:10:58</tdeq>
<id>2054</id>
<user>mradmin</user>
<type>Commit</t... | XML print text of child tag below two parrents | Here is my xml. I only want to print out status result and type text from childern.
<response status="success">
<result>
<job>
<tenq>2022/11/04 17:10:58</tenq>
<tdeq>17:10:58</tdeq>
<id>2054</id>
<user>mradmin</user>
<type>Commit</type>
<status>ACT</status>
<queued>NO</qu... | [
"I figured it out:\nfor child in root.findall('.//job'): \n print(child.find('type').tex... | [
0
] | [] | [] | [
"children",
"parent",
"parsing",
"python",
"xml"
] | stackoverflow_0074321376_children_parent_parsing_python_xml.txt |
Q:
Copy a file from s3 to GCP object storage by piping or streaming get from s3 to put in cloud storage
Is it possible to make an API call to S3 to fetch a file and then pipe the result into an API call to GCP cloud storage(Object storage) to put an object. This will effectively copy the file from S3 to Azure blob.
M... | Copy a file from s3 to GCP object storage by piping or streaming get from s3 to put in cloud storage | Is it possible to make an API call to S3 to fetch a file and then pipe the result into an API call to GCP cloud storage(Object storage) to put an object. This will effectively copy the file from S3 to Azure blob.
My goal is to do this completely in-memory without writing anything to disk and also being able to handle f... | [
"Sure, Google Cloud Storage's gsutil can copy between clouds. Once you install it and configure it with your GCP credentials, open up the \".boto\" file and add a section with your AWS credentials:\n[Credentials]\naws_access_key_id = ACCESS_KEY_ID\naws_secret_access_key = SECRET_ACCESS_KEY\n\nThen run a copy comman... | [
0,
0,
0
] | [] | [] | [
"amazon_s3",
"bytesio",
"google_cloud_platform",
"google_cloud_storage",
"python"
] | stackoverflow_0074289050_amazon_s3_bytesio_google_cloud_platform_google_cloud_storage_python.txt |
Q:
Dealing with multiline fields in Google Sheet when exported to csv or tsv and retrieved using Python requests.get()
Lets say I have a Google Sheet that looks like this.
You can export it so it can be reached with a URL similar to this
# CSV
https://docs.google.com/spreadsheets/d/e/Eis4Ya-Le9Py/pub?gid=0&single=tr... | Dealing with multiline fields in Google Sheet when exported to csv or tsv and retrieved using Python requests.get() | Lets say I have a Google Sheet that looks like this.
You can export it so it can be reached with a URL similar to this
# CSV
https://docs.google.com/spreadsheets/d/e/Eis4Ya-Le9Py/pub?gid=0&single=true&output=csv
# TSV
https://docs.google.com/spreadsheets/d/e/Eis4Ya-Le9Py/pub?gid=0&single=true&output=tsv
If you downlo... | [
"Thanks to @Lorena Gomez I found the answer.\nThe behavior is different whether you request a tsv / csv file because tsv files do not include the 'newline(s)' that may occur within the fields.\nIn code:\nurl_base=\"https://docs.google.com/spreadsheets/d/e/2PA...be/pub?gid=0&single=true&output=\"\n\nimport io\nimpor... | [
1,
0
] | [] | [] | [
"csv",
"google_sheets",
"python"
] | stackoverflow_0074291964_csv_google_sheets_python.txt |
Q:
"unsupported format character at index "
I'm trying to format a PostgreSQL query in python and that query has to have '%' between the name of a survey so I can filter surveys by name.
Here is the code:
sql = """select survey_data
from survey_data.survey_data
where codigo_do_projeto like '%s%'
ORDER BY data_de_ini... | "unsupported format character at index " | I'm trying to format a PostgreSQL query in python and that query has to have '%' between the name of a survey so I can filter surveys by name.
Here is the code:
sql = """select survey_data
from survey_data.survey_data
where codigo_do_projeto like '%s%'
ORDER BY data_de_inicio_da_coleta desc
limit %s
offset %s"""
How... | [
"You have to escape the %.\n\nsql = \"\"\"select survey_data\nfrom survey_data.survey_data \nwhere codigo_do_projeto like '%%'||%s||'%%'\nORDER BY data_de_inicio_da_coleta desc \nlimit %s\noffset %s\"\"\"\n\nOr you can do:\n\nsearch_val = '%search_term%'\n\n\nsql = \"\"\"select survey_data\nfrom survey_data.survey_... | [
0
] | [
"You need to put the survey_name part inside single quotes:\nsql = \"\"\"SELECT survey_data\nFROM survey_data.survey_data \nWHERE project_code like '%{0}%'\nORDER BY starting_date desc \nLIMIT {1} \nOFFSET {2}*{1}\"\"\".format(survey_name,items_per_page,page_number)\n\n"
] | [
-1
] | [
"postgresql",
"python"
] | stackoverflow_0074320161_postgresql_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.