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:
BTC Price Across Different Crypto Exchanges
I am trying to use CCXT to get the BTC bid and ask price across different exchanges, but running the code sequencially cannot get the price of a given moment correctly. Is there any way to execute them at the same time and return the correct price?
import ccxt
binance =... | BTC Price Across Different Crypto Exchanges | I am trying to use CCXT to get the BTC bid and ask price across different exchanges, but running the code sequencially cannot get the price of a given moment correctly. Is there any way to execute them at the same time and return the correct price?
import ccxt
binance = ccxt.binance()
coinbase = ccxt.coinbase()
ftx = ... | [
"With help from Ari Cooper-Davis, this is what I come up with. It seems like the bid and ask prices between the exchanges are still quite large.\nfrom multiprocessing import Process\nimport ccxt\n\n\ndef func1():\n binance = ccxt.binance()\n stat_list = binance.fetchTicker('BTC/USDT')\n print('Binance', st... | [
0
] | [] | [] | [
"binance",
"ccxt",
"coinbase_api",
"kraken.com",
"python"
] | stackoverflow_0074278135_binance_ccxt_coinbase_api_kraken.com_python.txt |
Q:
What is the difference between python functions `datetime.now()` and `datetime.today()`?
What is the difference between python functions datetime.now() and datetime.today() ?
In [1]: from datetime import datetime
In [2]: datetime.now()
Out[2]: datetime.datetime(2015, 9, 11, 12, 8,28, 909842)
In [3]: datetime.to... | What is the difference between python functions `datetime.now()` and `datetime.today()`? | What is the difference between python functions datetime.now() and datetime.today() ?
In [1]: from datetime import datetime
In [2]: datetime.now()
Out[2]: datetime.datetime(2015, 9, 11, 12, 8,28, 909842)
In [3]: datetime.today()
Out[3]: datetime.datetime(2015, 9, 11, 12,8, 45, 175839)
Thanks in advance.
| [
"datetime.datetime.now() takes tzinfo as keyword argument but datetime.today() does not take any keyword arguments.\nBy default, now() executes with datetime.datetime.now(tz=None)\nAs quoted in the docs: https://docs.python.org/3.6/library/datetime.html#datetime.datetime.now\n\ndatetime.now() return the current loc... | [
49,
14,
4,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0032517248_datetime_python.txt |
Q:
Converting month in string to numeric in Python
There is a list of dates in a form combining month as a string (e.g, Jan) and date as a number (e.g., 13).
a = ['20January', '14March', '3December', '1May', '17June', '2February']
How can I this list to Month-day format (e.g., 0120, 0314, 1203, ...) using datetime.s... | Converting month in string to numeric in Python | There is a list of dates in a form combining month as a string (e.g, Jan) and date as a number (e.g., 13).
a = ['20January', '14March', '3December', '1May', '17June', '2February']
How can I this list to Month-day format (e.g., 0120, 0314, 1203, ...) using datetime.striptime?
| [
"Code\nimport datetime\n\na = ['20January', '14March', '3December', '1May', '17June', '2February']\n\nfor entry in a:\n print(datetime.datetime.strptime(entry, '%d%B').strftime('%m%d'))\n\nOutput\n0120\n0314\n1203\n0501\n0617\n0202\n\nhttps://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-c... | [
2,
0
] | [] | [] | [
"datetime",
"python",
"sorting"
] | stackoverflow_0074283477_datetime_python_sorting.txt |
Q:
How to use pytest fixture with fixture factory?
In scikit-learn, there is a function parametrize_with_checks() that is used as a pytest fixture factory--it returns a pytest.mark.parametrize fixture, and is called as a decorator with an iterable of estimators, e.g.
@parameterize_with_checks(list_of_estimators)
My ... | How to use pytest fixture with fixture factory? | In scikit-learn, there is a function parametrize_with_checks() that is used as a pytest fixture factory--it returns a pytest.mark.parametrize fixture, and is called as a decorator with an iterable of estimators, e.g.
@parameterize_with_checks(list_of_estimators)
My issue is that my list of estimators may change (or I ... | [
"parametrize_with_checks() can not work with the values set by fixtures. It handles models just as a function, not a fixture. You can access fixtures only from test functions.\nSo, looks like you need to set the models as a list or make a call to the model function in parametrize_with_checks()\nimport pytest\nfrom ... | [
1
] | [] | [] | [
"fixtures",
"pytest",
"python",
"scikit_learn"
] | stackoverflow_0074281521_fixtures_pytest_python_scikit_learn.txt |
Q:
(Python) locate certain field of image from image
I want to extract certain part from the image
I am running Python 3.9.12 with CV2 4.6.0 on Ubuntu 22.04.1 LTS
(From) The original pic:
https://ibb.co/RcZ7ntL
(then) The pic want to locate(I want to extract the red part only):
https://ibb.co/dGBfqXx
(the desire pic/... | (Python) locate certain field of image from image | I want to extract certain part from the image
I am running Python 3.9.12 with CV2 4.6.0 on Ubuntu 22.04.1 LTS
(From) The original pic:
https://ibb.co/RcZ7ntL
(then) The pic want to locate(I want to extract the red part only):
https://ibb.co/dGBfqXx
(the desire pic/output) : https://ibb.co/j5h501f
I've tried searching f... | [
"You can do the reverse task:\nrun your OCR first, since it will find all texts in the image for you.\nIf you you tesseract, it will send you all the text AND the locations/boxes where the text is found.\nlike here:\n\n"
] | [
1
] | [] | [] | [
"ocr",
"python"
] | stackoverflow_0074285522_ocr_python.txt |
Q:
How to install specific python version in virtual environment on Mac without pyenv
My Mac has python 3.10.5, and I have created a virtual environment which has python 3.8.5, now I want to create another virtual environment with python 3.7, I have searched online for a while, most ppl would suggest using pyenv, but... | How to install specific python version in virtual environment on Mac without pyenv | My Mac has python 3.10.5, and I have created a virtual environment which has python 3.8.5, now I want to create another virtual environment with python 3.7, I have searched online for a while, most ppl would suggest using pyenv, but I am pretty sure my python 3.8.5 virtual environment is installed without pyenv, I only... | [
"\nfind out the path where your python version is installed\n\nrun below\nvirtualenv -p /your/python/path/python2.6 foldernamehere\n\n\n"
] | [
0
] | [] | [] | [
"pyenv",
"python",
"virtualenv"
] | stackoverflow_0074284336_pyenv_python_virtualenv.txt |
Q:
Running command from Node.js with sudo
Being new to Node.js, I have this question..
I see it mentioned in a few places that node should not be run as root, such as this. I am just using node to set up a simple web service and executing a python script which requires root access. I just don't understand where the d... | Running command from Node.js with sudo | Being new to Node.js, I have this question..
I see it mentioned in a few places that node should not be run as root, such as this. I am just using node to set up a simple web service and executing a python script which requires root access. I just don't understand where the danger lies, as in what could the hacker do.
... | [
"The hacker could do anything if there is any security issues.\nYou could give the user witch runs the web server the permission to do the task your task is intending to do.\nIn general try to avoid root whenever you can (put the tinfoil hat on).\n",
"According to this post from superuser of StackExchange platfor... | [
2,
2,
1,
0
] | [] | [] | [
"child_process",
"express",
"javascript",
"node.js",
"python"
] | stackoverflow_0039785436_child_process_express_javascript_node.js_python.txt |
Q:
Multiple input using Eval() in Python
Can we use eval() to get multiple data ?
Can we get three data like : a , b , c = map(float , float(input().split(' '))
But i want these data are different by using eval()
A:
You can do that as follow, Just remove float from float(input().split(' ')
a, b, c = map(float , inp... | Multiple input using Eval() in Python | Can we use eval() to get multiple data ?
Can we get three data like : a , b , c = map(float , float(input().split(' '))
But i want these data are different by using eval()
| [
"You can do that as follow, Just remove float from float(input().split(' ')\na, b, c = map(float , input().split(' '))\n\n",
"You can't use an assignment operator inside an eval, meaning you can't use eval to assign variables.\nHowever as others have mentioned, a, b, c = map(float, input().split(' ')) will prompt... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074276764_python.txt |
Q:
Python - bug - deleting elements from a list
In an exercise I'm supposed to have a program that asks for multiple inputs and the program should delete the largest and smallest n numbers.
My attempt:
def outliers(lst, n):
new = sorted(lst)
for i in range(0, n):
del new[i]
del new[len(new)... | Python - bug - deleting elements from a list | In an exercise I'm supposed to have a program that asks for multiple inputs and the program should delete the largest and smallest n numbers.
My attempt:
def outliers(lst, n):
new = sorted(lst)
for i in range(0, n):
del new[i]
del new[len(new) - i - 1]
return new
def main():
lst = [... | [
"As you delete element at the beginning, the other elements move forward, just use the slice notation\ndef outliers(lst, n):\n return sorted(lst)[n:-n]\n\n\nprint(outliers([1, 2, 5, 8, 9], 2)) # [5]\nprint(outliers([1, 2, 5, 8, 9], 1)) # [2, 5, 8]\n\n",
"try this:\ndef outliers(lst, n):\n\n new = sorted(l... | [
2,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074285776_list_python.txt |
Q:
Hash opencv frames to memoize function (Python)
I'm replacing portions of a video with frames from a different video. I want the chosen replacement frames to be as similar as possible to the original.
I'm using this function to find the closest frame to the portion:
import functools
import cv2
@functools.cache
de... | Hash opencv frames to memoize function (Python) | I'm replacing portions of a video with frames from a different video. I want the chosen replacement frames to be as similar as possible to the original.
I'm using this function to find the closest frame to the portion:
import functools
import cv2
@functools.cache
def closest_frame(frame, frames):
return min(
... | [
"To specifically answer the question of \"how to make ndarray hashable\": convert each of the arrays in the ndarray, including the outermost, into tuples. Since these are immutable, the result will be hashable. You can simply use the following:\nhash_frame = tuple(tuple(sub) for sub in frame) for the resultant mini... | [
1
] | [] | [] | [
"hash",
"opencv",
"python"
] | stackoverflow_0074284998_hash_opencv_python.txt |
Q:
program which takes two strings as input from the user (str1 and str2)
Write a program that takes two strings as input from the user (str1 and str2) and prints two strings as output (op1 and op2).
op1 should contain all the characters which are present in str1 but NOT present in str2.
op2 should contain all the c... | program which takes two strings as input from the user (str1 and str2) | Write a program that takes two strings as input from the user (str1 and str2) and prints two strings as output (op1 and op2).
op1 should contain all the characters which are present in str1 but NOT present in str2.
op2 should contain all the characters which are present in str2 but NOT present in str1.
For example:
s... | [
"using System;\nusing System.Collections.Generic;\n\npublic class HelloWorld\n{\n\n public Tuple<string, string> StringOutput(string str1, string str2)\n {\n string output1 = \"\";\n string output2 = \"\";\n\n HashSet<char> record = new HashSet<char>();\n for (int i = 0; i < str2.L... | [
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0073284524_python_string.txt |
Q:
Detecting address chunk within a word document
I have a word document with some paragraphs and address details within it. I used textract to extract the sentences of this document line by line into a list. What i want to do is to detect the complete address chunk as one whole sentence string. The address template ... | Detecting address chunk within a word document | I have a word document with some paragraphs and address details within it. I used textract to extract the sentences of this document line by line into a list. What i want to do is to detect the complete address chunk as one whole sentence string. The address template is not fixed and can or cannot have all the details ... | [
"If the text file's structure is constant, you don't need to use nlp, just Python with some hardcoded detections like this:\nlines = []\nwith open(\"textfile.txt\") as textfile:\n lines = textfile.readlines()\n\naddress_line = None\ntelephone_line = None\n\nfor i in range(len(lines)):\n if \"Employee’s addres... | [
1,
1
] | [] | [] | [
"nlp",
"python",
"python_3.x",
"spacy"
] | stackoverflow_0074284994_nlp_python_python_3.x_spacy.txt |
Q:
Outer product on Pandas DataFrame rows
Have two DataFrames with identical columns labels. Columns are label, data1, data2, ..., dataN.
Need to take the product of the DataFrames, multiplying data1 * data1, data2 * data2, etc for every possible combination of rows in DataFrame1 with the rows in DataFrame2. As such,... | Outer product on Pandas DataFrame rows | Have two DataFrames with identical columns labels. Columns are label, data1, data2, ..., dataN.
Need to take the product of the DataFrames, multiplying data1 * data1, data2 * data2, etc for every possible combination of rows in DataFrame1 with the rows in DataFrame2. As such, want the resulting DataFrame to maintain th... | [
"Let's do a cross merge first then mutiple the dn_x with dn_y\nout = df1.merge(df2, how='cross')\nout = (out.filter(like='label')\n .join(out.filter(regex='d.*_x')\n .mul(out.filter(regex='d.*_y').values)\n .rename(columns=lambda col: col.split('_')[0])))\n\nprint(out)\n\n label_x lab... | [
2,
2,
0,
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074203791_pandas_python_python_3.x.txt |
Q:
TypeError: 'coroutine' object is not subscriptable?
I'm working on a project where I get device data from ibeacon bluetooth devices. Normally I can have all Mac addresses and device local_names. But when I want to change the code a little bit I can't get the Mac addresses
Executing Code
import asyncio
from bleak... | TypeError: 'coroutine' object is not subscriptable? | I'm working on a project where I get device data from ibeacon bluetooth devices. Normally I can have all Mac addresses and device local_names. But when I want to change the code a little bit I can't get the Mac addresses
Executing Code
import asyncio
from bleak import BleakScanner
async def main():
print("scanning f... | [
"device.adress solved my problem. Everyone can use this.\n"
] | [
0
] | [] | [] | [
"bluetooth",
"ibeacon",
"python"
] | stackoverflow_0074285783_bluetooth_ibeacon_python.txt |
Q:
how fetch inherit model into another model field value fetch in other module value in odoo15
class StockPicking(models.Model): _inherit = ['stock. Picking'] _description = 'test.test' _order = 'id'
def _default_group_id(self): if self.env.context.get('default_picking_id'): return self.env['stock. Picking'].br... | how fetch inherit model into another model field value fetch in other module value in odoo15 | class StockPicking(models.Model): _inherit = ['stock. Picking'] _description = 'test.test' _order = 'id'
def _default_group_id(self): if self.env.context.get('default_picking_id'): return self.env['stock. Picking'].browse(self.env.context['default_picking_id']).group_id.id return False
1.Inventory--->tranfers--->c... | [
"I have solve this Question Ans and generate QRCode\n\n\n\n"
] | [
0
] | [] | [] | [
"inventory",
"odoo_15",
"python",
"stock"
] | stackoverflow_0073621831_inventory_odoo_15_python_stock.txt |
Q:
Efficiently selecting row of Pandas Dataframe which contains digit
How to select rows which contains digits in dataframe.
I am using this.
s = set([1,2,3,4,5,6,7,8,9,0])
df["text"].apply(lambda x:any(i in list(x) for i in s))
Trying to get separate the sentences with digits.
A:
Use Series.str.contains with \d f... | Efficiently selecting row of Pandas Dataframe which contains digit | How to select rows which contains digits in dataframe.
I am using this.
s = set([1,2,3,4,5,6,7,8,9,0])
df["text"].apply(lambda x:any(i in list(x) for i in s))
Trying to get separate the sentences with digits.
| [
"Use Series.str.contains with \\d for match digit:\ndf = pd.DataFrame({'text':['text1','text','random 4.88 text']})\n\nm = df[\"text\"].str.contains(r'\\d')\nprint (m)\n0 True\n1 False\n2 True\nName: text, dtype: bool\n\nFor filtering:\ndf1 = df[df[\"text\"].str.contains(r'\\d')]\n\n",
"copied from isn... | [
3,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074285990_dataframe_pandas_python.txt |
Q:
docx MailMerge Not Closing Microsoft Word After using document.write()
I have a current script that fills out a template word doc using MailMerge. The issue I noticed is that after iterating through 15 rows/documents, the process works correctly, but in my Task Manager, there is 15 open idle Microsoft Word applic... | docx MailMerge Not Closing Microsoft Word After using document.write() | I have a current script that fills out a template word doc using MailMerge. The issue I noticed is that after iterating through 15 rows/documents, the process works correctly, but in my Task Manager, there is 15 open idle Microsoft Word applications open.. This is not ideal as this will be used daily and should shut ... | [
"I was facing the same problem. You're doing the process but you're not closing the template file.\ntry this:\ndocument.close()\ndocumentation\n"
] | [
0
] | [] | [] | [
"docx",
"docx_mailmerge",
"mailmerge",
"ms_word",
"python"
] | stackoverflow_0072033327_docx_docx_mailmerge_mailmerge_ms_word_python.txt |
Q:
How to merge two csv files with rows and columns merged in a single sheet and create a new single merged csv file?
How to merge two csv files using python and create a merged csv file. I tried below code from available sources but was not able to attain my requirements.
def merge_csv():
# reading csv files
... | How to merge two csv files with rows and columns merged in a single sheet and create a new single merged csv file? | How to merge two csv files using python and create a merged csv file. I tried below code from available sources but was not able to attain my requirements.
def merge_csv():
# reading csv files
data1 = pd.read_csv('C:/folder/csv1.csv')
data2 = pd.read_csv('C:/folder/csv2.csv')
# using merge function by s... | [
"Outer product merges two csv on common columns. You cannot merge without anything in common. In fact you do not want to merge but append.\nConvert your cvs files to DataFrames:\ndf1 = pd.read_csv('C:/folder/csv1.csv')\ndf2 = pd.read_csv('C:/folder/csv2.csv')\n\nAppend both columns in the first DataFrame:\na = df2[... | [
3,
1
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074279628_csv_pandas_python.txt |
Q:
How do I get a specific element in array - MongoDB
Documents store in mongo db in following form
{
"_id" : ObjectId("54fa059ce4b01b3e086c83e9"),
"field1" : "value1",
"field2" : "value2"
"field3" : [
{
"abc123": ["somevalue", "somevalue"]
},
{
"xyz345... | How do I get a specific element in array - MongoDB | Documents store in mongo db in following form
{
"_id" : ObjectId("54fa059ce4b01b3e086c83e9"),
"field1" : "value1",
"field2" : "value2"
"field3" : [
{
"abc123": ["somevalue", "somevalue"]
},
{
"xyz345": ["somevalue", "somevalue"]
}
]
}
What I ... | [
"Maybe something like this:\n db.collection.aggregate([\n {\n$project: {\n field3: {\n \"$filter\": {\n \"input\": \"$field3\",\n \"as\": \"f\",\n \"cond\": {\n $ne: [\n \"$$f.abc123\",\n undefined\n ]\n }\n }\n }\n}\n},\n{\n $unwind: \"$field3\"\n},\n{\n... | [
0
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0074284537_mongodb_pymongo_python.txt |
Q:
I'm having difficulty finding this web element with Selenium webdriver
I am using selenium webdriver to pull data from one website and my goal is to copy and paste that date into another site using python, I am able to pull the data from the 1st site using iFrame + XPATH but on the 2nd site I am failing to locate ... | I'm having difficulty finding this web element with Selenium webdriver | I am using selenium webdriver to pull data from one website and my goal is to copy and paste that date into another site using python, I am able to pull the data from the 1st site using iFrame + XPATH but on the 2nd site I am failing to locate the exact web element. I pasted it below:
<textarea rows="5" aria-invalid="f... | [
"\nThe site can have more than one iframe.\n\n",
"If this element is placed in the body of html but not in iframe you can try to use one of these approaches:\ndriver.find_element(By.ID, 'mui-2')\n\nor\ndriver.find_element(By.XPATH, '//textarea[@placeholder=\"Paste in a list of emails separated by commas or new li... | [
0,
0
] | [] | [] | [
"python",
"selenium",
"webdriver"
] | stackoverflow_0074279681_python_selenium_webdriver.txt |
Q:
No module named 'websocket'
I'm a fairly new to Python and I am trying to enter the following code:
from websocket import create_connection as cc
import json, time
I want to look at BTC and LTC stocks in a live feed type-fashion but I keep getting this error:
ModuleNotFoundError: No module named 'websocket'
I'v... | No module named 'websocket' | I'm a fairly new to Python and I am trying to enter the following code:
from websocket import create_connection as cc
import json, time
I want to look at BTC and LTC stocks in a live feed type-fashion but I keep getting this error:
ModuleNotFoundError: No module named 'websocket'
I've been looking around and it seem... | [
"First, you need to install pip if you don't have it. Type pip in your terminal or cmd to see if it is installed. Or else, install it first by downloading get-pip.py and executing it. \nThen you do pip install websocket, which will install the module for you. \n",
"If the websocket and websocket-client doesn't wo... | [
13,
4,
4,
2,
2,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"websocket"
] | stackoverflow_0047665760_python_python_3.x_websocket.txt |
Q:
Matplotlib: display plot on a remote machine
I have a python code doing some calculation on a remote machine, named A. I connect on A via ssh from a machine named B.
Is there a way to display the figure on machine B?
A:
Sure, you can enable X11 forwarding. Usually this is done by passing the -X or -Y option to s... | Matplotlib: display plot on a remote machine | I have a python code doing some calculation on a remote machine, named A. I connect on A via ssh from a machine named B.
Is there a way to display the figure on machine B?
| [
"Sure, you can enable X11 forwarding. Usually this is done by passing the -X or -Y option to ssh when you connect to the remote computer\nssh -X computerA\n\nNote that the SSH daemon on computer A will also have to be configured to enable X11 forwarding. This is done by putting\nX11Forwarding yes\n\nin computer A's... | [
38,
34,
21,
13,
5,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"matplotlib",
"python",
"ssh"
] | stackoverflow_0003453188_matplotlib_python_ssh.txt |
Q:
TypeError: 'int' object is not iterable (please help )
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
total_height = 0
for height in total_height:
total_height += height
print(total_height)
number_o... | TypeError: 'int' object is not iterable (please help ) | student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
total_height = 0
for height in total_height:
total_height += height
print(total_height)
number_of_students = 0
for student in number_of_students:
number... | [
"You can do the split and parsing to int easier with map:\nstudent_heights = list(map(int, input(\"Input a list of student heights \").split()))\n\nThen, you do not have to iterate over the list, but use sum and len:\navg_height = round(sum(student_heights) / len(student_heights))\n\nThe TypeError you are getting i... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074285929_python.txt |
Q:
A function works fine with one number, but not an array. What am I missing?
Pardon my ignorance, but I'm very new to coding in python. I have a pretty simple function; it just needs to make a calculation based on b's relative location to a and c:
a = 6
b = 3
c = 2
def function(a, b, c):
if ((a >= b) & (b >= c... | A function works fine with one number, but not an array. What am I missing? | Pardon my ignorance, but I'm very new to coding in python. I have a pretty simple function; it just needs to make a calculation based on b's relative location to a and c:
a = 6
b = 3
c = 2
def function(a, b, c):
if ((a >= b) & (b >= c)):
return b - c
elif ((a <= b) & (b >= c)):
return a - c
... | [
"I don't think you need looping here as the problem can be solved using array operations. You could try the below, assuming the arrays are of the same length.\n# import numpy to be able to work with arrays\nimport numpy as np\n\ndef function(a, b, c):\n # declare array t with only zeros\n t = np.zeros_like(a)... | [
1
] | [] | [] | [
"arrays",
"function",
"if_statement",
"numpy",
"python"
] | stackoverflow_0074285862_arrays_function_if_statement_numpy_python.txt |
Q:
How to populate rows of Spark dataframe column based with previous row based on a multiple conditions?
Disclaimer: This might be possible duplicate but I cannot find the exact solution. Please feel free to mark this question as duplicate and provide link to duplicate question in comments.
I am still learning pytho... | How to populate rows of Spark dataframe column based with previous row based on a multiple conditions? | Disclaimer: This might be possible duplicate but I cannot find the exact solution. Please feel free to mark this question as duplicate and provide link to duplicate question in comments.
I am still learning python dataframe operations and this possibly has a very simple solution which I am not able to figure out.
I hav... | [
"understand, there are may tons of similar question but not exakt what your looking for. I hope this helps:\nimport pandas as pd\nfrom io import StringIO\n\ndf = pd.read_csv(StringIO('''\nColumn A Column B Column C Column D Column E Column F Column G\n1 Apr 2022 3 2 3 0\n1 May 2022 ... | [
0
] | [] | [] | [
"data_wrangling",
"dataframe",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074285763_data_wrangling_dataframe_pandas_pyspark_python.txt |
Q:
Is there any way to show figures in VScode remote ssh (windows)
vscode was installed in my windows computer, I use ssh remote service
and when I tried to plot a figure, the figure just did not show up.
e.g.,
the code as follows
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10,10,100)
y = n... | Is there any way to show figures in VScode remote ssh (windows) | vscode was installed in my windows computer, I use ssh remote service
and when I tried to plot a figure, the figure just did not show up.
e.g.,
the code as follows
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10,10,100)
y = np.sin(x)
plt.plot(x,y)
plt.show()
when I run the code in the remote ... | [
"Yes its completely possible, but it requires the x11 Forwarding option.\nIn your ssh config file, add \"ForwardX11 Yes\"\nHost myHost\n Hostname 192.168.1.1\n ForwardX11 Yes\n\nNow the tricky part: the remote computer has to allow the forwarding (usually disabled by default).\nOn the remote host, go to the sshd_... | [
3,
0,
0
] | [] | [] | [
"python",
"ssh",
"visual_studio_code"
] | stackoverflow_0059063892_python_ssh_visual_studio_code.txt |
Q:
TypeError: economico() missing 2 required positional arguments: 'carro' and 'consumo'
I have an assignment to turn in for the University. I already got the correct result in VS Code with the code below (the idea is to show the car with the lowest consumption):
def entrada_carro():
carro = []
for i in range... | TypeError: economico() missing 2 required positional arguments: 'carro' and 'consumo' | I have an assignment to turn in for the University. I already got the correct result in VS Code with the code below (the idea is to show the car with the lowest consumption):
def entrada_carro():
carro = []
for i in range(4):
carro.append(input("Digite o modelo do carro: "))
return carro
def entrad... | [
"You've defined a function economico(carro, consumo) to require two parameters and that main is trying to call it with zero parameters (economico()).\nIf you can't change the main invocation run by your uni's test harness, you'll need to change your functions to read and write\nconsumo and carro as globals instead ... | [
0
] | [] | [] | [
"function",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074286153_function_python_python_2.7_python_3.x.txt |
Q:
Selenium Unable to locate element ng dropdown panel
I am new to selenium webdriver with python.This is my first script
I am trying to select value "300-500" from dropdown but getting error "elenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","sele... | Selenium Unable to locate element ng dropdown panel | I am new to selenium webdriver with python.This is my first script
I am trying to select value "300-500" from dropdown but getting error "elenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@class="ng-dropdown-panel ng-select-bottom"]//... | [
"You can try the below solution.\nfrom selenium.webdriver.common.by\nimport By\nfrom selenium.webdriver.support.ui\nimport WebDriverWait\nfrom selenium.webdriver.support\nimport expected_conditions as EC\n\nelement = WebDriverWait(driver, 20).until(\n EC.element_to_be_clickable((By.XPATH, \"//span[contains(text()... | [
0
] | [] | [] | [
"drop_down_menu",
"element",
"locate",
"python",
"selenium"
] | stackoverflow_0074284939_drop_down_menu_element_locate_python_selenium.txt |
Q:
huggingface transformers longformer optimizer warning AdamW
I get below warning when I try to run the code from this page.
/usr/local/lib/python3.7/dist-packages/transformers/optimization.py:309: FutureWarning: This implementation of AdamW is deprecated and will be removed in a future version. Use thePyTorch imple... | huggingface transformers longformer optimizer warning AdamW | I get below warning when I try to run the code from this page.
/usr/local/lib/python3.7/dist-packages/transformers/optimization.py:309: FutureWarning: This implementation of AdamW is deprecated and will be removed in a future version. Use thePyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warni... | [
"import torch_optimizer as optim\n \noptim.AdamW(params, opt.learning_rate, (opt.optim_alpha, opt.optim_beta), opt.optim_epsilon, weight_decay=opt.weight_decay)\n\nIt can be used this way.\n",
"You need to add optim='adamw_torch', the default is optim='adamw_hf'\nRefer here\nCan you try the following:\n# defin... | [
2,
0
] | [] | [] | [
"huggingface_transformers",
"nlp",
"python"
] | stackoverflow_0071113363_huggingface_transformers_nlp_python.txt |
Q:
Why does my Python binary search algorithm not work for certain items?
My binary search algorithm manages to find some items but does not find others:
myList = [1,3,4,7,12,13,14,16,19,20,28,29,40,45,48,50,67,89,91,94]
item = 67
found = False
lowerBound = 0
upperBound = len(myList) - 1
index = 0
while not found a... | Why does my Python binary search algorithm not work for certain items? | My binary search algorithm manages to find some items but does not find others:
myList = [1,3,4,7,12,13,14,16,19,20,28,29,40,45,48,50,67,89,91,94]
item = 67
found = False
lowerBound = 0
upperBound = len(myList) - 1
index = 0
while not found and lowerBound != upperBound:
index = (upperBound+lowerBound) // 2
if... | [
"Use while not found and lowerBound <= upperBound\nListing iteration of 67\n(lowerBound,upperBound)\n(0,19)\n(10,19)\n(15,19)\n(15,16)\n(16,16)\nWhile you algorithm make exit at same lowerBound and upperBound\n",
"The problem is caused by the statement in the while loop. You wrote while lowerBound != upperBound, ... | [
0,
0
] | [] | [] | [
"binary_search",
"computer_science",
"python"
] | stackoverflow_0074282369_binary_search_computer_science_python.txt |
Q:
Left join table without duplicating right table row values
I have 2 dataframe's as below. I want to join right side table (cycletime) to left table (current data).
Left Table- Current data (df_current)
| datetime_index | current | speed | cycle_counter |
|--------------------------|---------|-------|----... | Left join table without duplicating right table row values | I have 2 dataframe's as below. I want to join right side table (cycletime) to left table (current data).
Left Table- Current data (df_current)
| datetime_index | current | speed | cycle_counter |
|--------------------------|---------|-------|---------------|
| 27-10-2022 08:30:56.3056 | 30 | 60 | 1 ... | [
"You have to find duplicates in column total_time and column up_time according to cycle_counter column and replace them with empty string (\"\"). this will work for all data.\ndf.loc[df.duplicated(['cycle_counter','total_time', 'up_time']), ['total_time','up_time']] = \"\"\nprint(df)\n\n cycle_counter total_ti... | [
1
] | [] | [] | [
"left_join",
"pandas",
"python"
] | stackoverflow_0074285108_left_join_pandas_python.txt |
Q:
Efficient mean and standard deviation calculation using a lot of similar structured files in Python
I have a simple question about mean calculation in a dataframe where all the data was split into a lot of small files..
The structure of such files is similar - it's the data of >1000 experiments for the same condit... | Efficient mean and standard deviation calculation using a lot of similar structured files in Python | I have a simple question about mean calculation in a dataframe where all the data was split into a lot of small files..
The structure of such files is similar - it's the data of >1000 experiments for the same conditions but the data has some uncertainty which has to be estimated statistically.
each file has such struct... | [
"Sorry it seems that there is no \"correct\" answer on this question..\nI have collected one big dataframe and worked with the subqueries to process the data .. But of course that approach isn't fast enough..\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074182511_dataframe_pandas_python.txt |
Q:
Keyword 'Dictionary Should Contain Item' failed by the mismatch of types
Problem:
I'm getting int type from JSON, str type from manually-created dictionary.
Local running passed case, but running on jenkins failed it:
Value of dictionary key 'columns' does not match: 2 (integer) != 2 (string)
Details:
I'm compari... | Keyword 'Dictionary Should Contain Item' failed by the mismatch of types | Problem:
I'm getting int type from JSON, str type from manually-created dictionary.
Local running passed case, but running on jenkins failed it:
Value of dictionary key 'columns' does not match: 2 (integer) != 2 (string)
Details:
I'm comparing 2 dictionaries, first generated by json parser, second i manually create,
S... | [
"Answer for question 2:\nRobot Framework treats variable values as strings so try fixing your dictionary to look like below. Then the variables are integers.\n&{param2} Create Dictionary title=${name_w2} description=Description ${rndString}\n... font_color=f5aef5 back_color=${303030} columns=${2}\... | [
0
] | [] | [] | [
"python",
"robotframework"
] | stackoverflow_0074278932_python_robotframework.txt |
Q:
ValueError when try to convert a negative number from csv file to integer
Hello i have the csv file below, imported with pandas data = pd.read_csv("1.csv"):
x1,x2,xb,y
−2,1,1,1
I need to convert the negative number (-2) to integer with int(), but i get ValueError:
print(data.iloc[1-1]['x1'])
> -2 # str
print(in... | ValueError when try to convert a negative number from csv file to integer | Hello i have the csv file below, imported with pandas data = pd.read_csv("1.csv"):
x1,x2,xb,y
−2,1,1,1
I need to convert the negative number (-2) to integer with int(), but i get ValueError:
print(data.iloc[1-1]['x1'])
> -2 # str
print(int(data.iloc[1-1]['x1']))
> ValueError: invalid literal for int() with base 10: ... | [
"The \"−\" within \"−2\" is not a proper minus sign, looks like it but is not the same.\nYour print would work like this:\nprint(int(data.iloc[1-1]['x1'].replace(\"−\", \"-\")))\n\nAnd if you don't want to replace the problematic minus signs with the correct ones one by one, you could do this operation on the whole... | [
1,
0
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074286147_csv_pandas_python.txt |
Q:
Convert PG file contains many images
I have a pg file when I open it in Windows 7 I notice that it contains many images in one file.
Currently using python I'm trying to count the number of images inside this file or extract them but I can't find anything about pg files.
When I used an online converter, all the im... | Convert PG file contains many images | I have a pg file when I open it in Windows 7 I notice that it contains many images in one file.
Currently using python I'm trying to count the number of images inside this file or extract them but I can't find anything about pg files.
When I used an online converter, all the images were extracted and uploaded to a ZIP ... | [
"PG is not in the list of supported image formats, I'm surprised you can open it at all. If it supports multiple images per file, that support might be the same as provided for TIFF images using the seek function.\n",
"Your file is a multi-page TIFF with 9 sub-images, created by OPENTEXT CORPORATION. You may be ... | [
1,
0
] | [] | [] | [
"image",
"python",
"python_imaging_library"
] | stackoverflow_0074283041_image_python_python_imaging_library.txt |
Q:
Skip input prompt if help passed to click for subcommand
I have a simple Python click program, where I am trying to skip input for two optional parameters if someone issues --help on a subcommand:
import click
@click.group()
@click.option("--user", envvar="PKGPUSH_USER", prompt="user", help="user to auth with")
@... | Skip input prompt if help passed to click for subcommand | I have a simple Python click program, where I am trying to skip input for two optional parameters if someone issues --help on a subcommand:
import click
@click.group()
@click.option("--user", envvar="PKGPUSH_USER", prompt="user", help="user to auth with")
@click.option("--password", envvar="PKGPUSH_PASSWORD", prompt=... | [
"There is a way to do this, although a bit weird and may be error prone:\nclass ConditionalPrompt(click.Group):\n def parse_args(self, ctx, args):\n if ('--help') in args:\n for param in ctx.command.params:\n param.prompt = None\n super().parse_args(ctx, args)\n\n@click.gr... | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_click"
] | stackoverflow_0074197186_python_python_3.x_python_click.txt |
Q:
Groupby and filter rows based on a custom logic
I have a dataframe given below:
df1 = pd.DataFrame({"timestamp": [pd.Timestamp(2016, 7, 29), pd.Timestamp(2017, 8, 22), pd.Timestamp(2017, 10, 9), pd.Timestamp(2018, 1, 9), pd.Timestamp(2018, 3, 31), pd.Timestamp(2018, 7, 5),pd.Timestamp(2018, 8, 5), pd.Timestamp(201... | Groupby and filter rows based on a custom logic | I have a dataframe given below:
df1 = pd.DataFrame({"timestamp": [pd.Timestamp(2016, 7, 29), pd.Timestamp(2017, 8, 22), pd.Timestamp(2017, 10, 9), pd.Timestamp(2018, 1, 9), pd.Timestamp(2018, 3, 31), pd.Timestamp(2018, 7, 5),pd.Timestamp(2018, 8, 5), pd.Timestamp(2018, 9,5), pd.Timestamp(2018, 11, 6),pd.Timestamp(2018,... | [
"Try .drop_duplicates:\ndf1 = df1.drop_duplicates(subset=[\"userId\", \"movieId\"], keep=\"first\")\nprint(df1)\n\nPrints:\n timestamp userId movieId rating\n0 2016-07-29 1 111065 3\n1 2017-08-22 2 35455 4\n2 2017-10-09 2 132531 5\n4 2018-03-31 3 4493 ... | [
2,
2
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074281638_dataframe_group_by_pandas_python.txt |
Q:
Using regex to find files with a particular pattern
I am new to regex. I have read various tutorials, still I have failed to run my simple codes.
My files are organized such as "c1c2c4_aa_1", "c1c2c3_aa_2", "c1c2c8_aa_3", "c1c3c4_aa_4", ... "c1c2c4_bb_41", "c1c8c9_cc_58", "c1c3c11_aa_19"
I want to find all those o... | Using regex to find files with a particular pattern | I am new to regex. I have read various tutorials, still I have failed to run my simple codes.
My files are organized such as "c1c2c4_aa_1", "c1c2c3_aa_2", "c1c2c8_aa_3", "c1c3c4_aa_4", ... "c1c2c4_bb_41", "c1c8c9_cc_58", "c1c3c11_aa_19"
I want to find all those ones that includes "aa" (such as "c1c2c3_aa_3") and conver... | [
"If you have a list like con_list1 = [\"c1c2c4_aa_1\", \"c1c2c3_aa_2\", \"c1c2c8_aa_3\", \"c1c3c4_aa_4\"] you may try something like:\nimport re\n\n\ncon_list1 = [\"c1c2c4_aa_1\", \"c1c2c3_aa_2\", \"c1c2c8_aa_3\", \"c1c3c4_aa_4\"]\n\nregex = \"_aa_\"\nsubst = \"_zz_\"\n\nfor test_str in con_list1:\n result = re.... | [
1,
0,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"regex",
"regexp_replace",
"string"
] | stackoverflow_0074286053_python_python_3.x_regex_regexp_replace_string.txt |
Q:
Spliting dataset to train and test in python
I have dataset whose Label is 0 or 1.
I want to divide my data into test and train sets.For this, I used the
train_test_split method from sklearn at first,
But I want to select the test data in such a way that 10% of them are from class 0 and 90% are from class 1.
How c... | Spliting dataset to train and test in python | I have dataset whose Label is 0 or 1.
I want to divide my data into test and train sets.For this, I used the
train_test_split method from sklearn at first,
But I want to select the test data in such a way that 10% of them are from class 0 and 90% are from class 1.
How can I do this?
| [
"Refer to the official documentation sklearn.model_selection.train_test_split.\nYou want to specify the response variable with the stratify parameter when performing the split.\nStratification preserves the ratio of the class variable when the split is performed.\n",
"Split your dataset in class 1 and class 0, th... | [
2,
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0074286213_python_scikit_learn.txt |
Q:
Mutate multiple pandas dataframe inplace using a function
I would like to write a function that takes multiple dataframes that have the same structure, does specific transformations and saves the transformations inplace.
Dummy dataframes
df = pd.DataFrame({"Full name" : ["John Doe","Deep Smith","Julia Carter","Kat... | Mutate multiple pandas dataframe inplace using a function | I would like to write a function that takes multiple dataframes that have the same structure, does specific transformations and saves the transformations inplace.
Dummy dataframes
df = pd.DataFrame({"Full name" : ["John Doe","Deep Smith","Julia Carter","Kate Newton","Sandy Thompson"],
"Monthly Sal... | [
"EDIT: If pass list of DataFrames, you can return another list (out) or modify existing list dfs. So not possible inplace list of DataFrame without assign back like last step.\nYour function not return list of DataFrame, so you need create empty list and append cleaned DataFrame:\ndef tidy_dfs(dfs):\n out = []\n... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074286171_pandas_python.txt |
Q:
Visualize the structure of a Python module
Is there tool out there which can be used to graphically represent the structure of a python module?
I'm thinking that a graph of sub-modules and classes connected by arrows representing imports.
A:
I think you want the Python library snakefood
sfood:
Given a se... | Visualize the structure of a Python module | Is there tool out there which can be used to graphically represent the structure of a python module?
I'm thinking that a graph of sub-modules and classes connected by arrows representing imports.
| [
"I think you want the Python library snakefood\n\nsfood:\n Given a set of input files or root directories, generate a list of dependencies between the files;\nsfood-graph:\n Read a list of dependencies and produce a Graphviz dot file. (This file can be run through the Graphviz dot tool to produce a viewabl... | [
15,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006957484_python.txt |
Q:
How to override the default formfield for a read only foreign keys field in Django ModelAdmin?
I am overriding the default formfield of foreign keys on ModelAdmins as described here. However, I am not overriding it to return a subset, but instead to defer fields in order to optimize the performance. For example:
c... | How to override the default formfield for a read only foreign keys field in Django ModelAdmin? | I am overriding the default formfield of foreign keys on ModelAdmins as described here. However, I am not overriding it to return a subset, but instead to defer fields in order to optimize the performance. For example:
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwa... | [
"Here I am answering my own question. I haven't managed to solve what the issue presents, but I found a workaround that in my case achieves the same result.\nSince the read-only foreign-key on Django Admin page is shown as a link, I did this:\nfrom django.utils.html import format_html\nfrom django.urls import rever... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_orm",
"foreign_keys",
"python"
] | stackoverflow_0074277402_django_django_admin_django_orm_foreign_keys_python.txt |
Q:
PyCharm cannot find the packages in virtualenv
I have the latest PyCharm CE and am using it with virtualenv. I have defined the interpreter as the interpreter in the virtualenv. The Project Interpreter window in PyCharm lists all the packages I have installed. I confirmed this by running pip freeze > requirements... | PyCharm cannot find the packages in virtualenv | I have the latest PyCharm CE and am using it with virtualenv. I have defined the interpreter as the interpreter in the virtualenv. The Project Interpreter window in PyCharm lists all the packages I have installed. I confirmed this by running pip freeze > requirements.txt and running through the packages manually.
My p... | [
"The problem may lay in PyCharm picking up faulty 'Interpreter Paths' for your virtual environment. Go here:\nPyCharm (menu) -> Preferences (Menu option)\n -> Project: <name> (Dropdown) \n -> Project Interpreter (Menu option)\n -> 'Settings' button (Looks like a gear)\n ... | [
76,
8,
3,
3,
3,
0,
0,
0,
0,
0
] | [
"Goto /venv/bin/ and check all activate scripts. You venv path might be wrong.\n",
"I was not able to assign existing virtual environment to my project, but after going to \n\nFile -> Settings -> project interpreter-> show all-> click on '+' \n\nto create a new virtual environment or we can choose the existing vi... | [
-1,
-1
] | [
"pycharm",
"python",
"virtualenv"
] | stackoverflow_0034520291_pycharm_python_virtualenv.txt |
Q:
extracting a string from between to strings in dataframe
im trying to extract a value from my data frame
i have a column ['Desc'] it contains sentences in the folowing format
_000it_ZZZ$$$-
_0780it_ZBZT$$$-
_011it_BB$$$-
_000it_CCCC$$$-
I want to extract the string between 'it_' and '$$$'
I have tried this co... | extracting a string from between to strings in dataframe | im trying to extract a value from my data frame
i have a column ['Desc'] it contains sentences in the folowing format
_000it_ZZZ$$$-
_0780it_ZBZT$$$-
_011it_BB$$$-
_000it_CCCC$$$-
I want to extract the string between 'it_' and '$$$'
I have tried this code but does not seem to work
# initializing substrings
sub1... | [
"You could try using a regex pattern. It matches your cases you listed here, but I can't guarantee that it will generalize to all possible patterns.\nimport re\n\nstring = \"_000it_ZZZ$$$-\"\np = re.compile(r\"(?<=it_)(.*)(?<!\\W)\")\nm = p.findall(string)\nprint(m) # ['_ZZZ']\n\nThe pattern looks for it in the str... | [
0,
0
] | [] | [] | [
"data_analysis",
"data_preprocessing",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074286394_data_analysis_data_preprocessing_dataframe_pandas_python.txt |
Q:
Name of first column that is non NaN ir Null
I'm looking how to add a column to df that holds the column name of the first column that is not NaN or Null. Example: column "first" based on columns 'A', 'B', 'C', 'D'
Name A B C D First
Alex 100 Nan Null NaN A
Michael 300 400 Null Null A
Stev... | Name of first column that is non NaN ir Null | I'm looking how to add a column to df that holds the column name of the first column that is not NaN or Null. Example: column "first" based on columns 'A', 'B', 'C', 'D'
Name A B C D First
Alex 100 Nan Null NaN A
Michael 300 400 Null Null A
Steve Null 100 100 100 B
John Null Null Nan ... | [
"Convert Null, Nan values to misisng values and if necessary Name to index, then test DataFrame.notna and get first matched column by DataFrame.idxmax, last set NaN if all NaNs per row:\ndf = df.replace(['Null', 'Nan'], np.nan)\ndf = df.set_index('Name')\n\nm = df.notna()\ndf['First'] = m.idxmax(axis=1).where(m.any... | [
3
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074286663_pandas_python.txt |
Q:
DataFrame: cumulative sum of column until condition is reached and return sum in new column
I am new in Python and am currently facing an issue I can't solve. I really hope you can help me out. English is not my native language so I am sorry if I am not able to express myself properly.
Lets suppose i have a data f... | DataFrame: cumulative sum of column until condition is reached and return sum in new column | I am new in Python and am currently facing an issue I can't solve. I really hope you can help me out. English is not my native language so I am sorry if I am not able to express myself properly.
Lets suppose i have a data frame like:
import pandas as pd
df = pd.DataFrame({'a': [1111,2222,3333,4444,5555,6666,7777,8888,9... | [
"Use Series.shift with cumulative sum by Series.cumsum and then aggregate sum:\ndf = df.groupby(df.b.shift(fill_value=0).cumsum())['a'].sum().rename_axis(None).to_frame()\nprint (df)\n a\n0 6666\n1 9999\n2 33330\n\nFor new column use GroupBy.transform with sum first and then set 0 if no match 1 in b by n... | [
2,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"sum"
] | stackoverflow_0061097181_dataframe_pandas_python_sum.txt |
Q:
How use two column values on a dataframe and store the result in a new one
I want to choose two column values for example bananas (from column "fruit") who are not from Italy (from column "country of origin") and store it in a new dataframe.
approach:
a = df[(df['fruit'] == "banana") & (df['country of origin'] != ... | How use two column values on a dataframe and store the result in a new one | I want to choose two column values for example bananas (from column "fruit") who are not from Italy (from column "country of origin") and store it in a new dataframe.
approach:
a = df[(df['fruit'] == "banana") & (df['country of origin'] != "Italy")].index
df.drop(a, inplace=True)
When I run this code I get this error ... | [
"just add the subset of the original df in a new variable.\n>>> df\n fruit country of origin\n0 banana Farao Islands\n1 banana Italy\n>>> b = df[(df['fruit'] == \"banana\") & (df['country of origin'] != \"Italy\")].copy(deep=True)\n>>> b\n fruit country of origin\n0 banana Farao Islands... | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074286562_dataframe_python.txt |
Q:
Convince Python-CFFI to find shared lib
I have a somewhat strange setup:
I have a libmylib.so I cannot modify, but, since the interface is rather convoluted, I wrote a simple wrapper directly into ffbuilder.set_source()
My full lib_builder.py is:
import os
from cffi import FFI
ffibuilder = FFI()
ffibuilder.cdef("... | Convince Python-CFFI to find shared lib | I have a somewhat strange setup:
I have a libmylib.so I cannot modify, but, since the interface is rather convoluted, I wrote a simple wrapper directly into ffbuilder.set_source()
My full lib_builder.py is:
import os
from cffi import FFI
ffibuilder = FFI()
ffibuilder.cdef("""
int start(int port);
int ready(void);
int ... | [
"Following this answer I was able to make it work using:\n#!/usr/bin/env python3\nimport os\nimport sys\nif 'LD_LIBRARY_PATH' not in os.environ:\n os.environ['LD_LIBRARY_PATH'] = os.path.dirname(os.path.realpath(__file__))\n try:\n # print('restarting...')\n os.execve(sys.argv[0], sys.argv, os.e... | [
0,
0
] | [] | [] | [
"python",
"python_cffi"
] | stackoverflow_0074270345_python_python_cffi.txt |
Q:
Get faces of each uv shell on the python maya api
I'm trying to query the faces of each uv shell on a geometry, I'm using maya.cmds but since this needs to run on a callback, I need faster results. I thought about using the api but can't get the same results.
On maya.cmds I use polyEvaluate with the uvShellIds arg... | Get faces of each uv shell on the python maya api | I'm trying to query the faces of each uv shell on a geometry, I'm using maya.cmds but since this needs to run on a callback, I need faster results. I thought about using the api but can't get the same results.
On maya.cmds I use polyEvaluate with the uvShellIds argument. Ex:
print maya.cmds.polyEvaluate('pCube1.f[*]', ... | [
"The MFnMesh method gives you a list of uv ids in a shell. In a default cube you have 14 uv coords in one shell. The polyEvaluate gives you the shell number of the selected faces (in your case) what are six uvcoords all belonging to one shell. If you call the polyEvaluate with a range of uv coord like pCube1.map[0:... | [
0
] | [] | [] | [
"maya",
"python"
] | stackoverflow_0074284756_maya_python.txt |
Q:
This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported
I encountered this error, how do I resolve it?
NotImplementedError: Cannot convert a symbolic Tensor (lstm_2/strided_slice:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy ... | This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported | I encountered this error, how do I resolve it?
NotImplementedError: Cannot convert a symbolic Tensor (lstm_2/strided_slice:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported
# train the model
model = define_model(vocab_size, max_length)
# train the ... | [
"As others have indicated elsewhere this is due to an incompatibility between specific tensorflow versions and specific numpy versions.\nconda version 4.11.0\nCommands to setup working environment:\nconda activate base\nconda env remove -y --name myenv\nconda create -y --name myenv tensorflow=2.4.0\nconda activate ... | [
0,
0
] | [] | [] | [
"numpy",
"python",
"tensorflow",
"tensorflow_datasets"
] | stackoverflow_0070700626_numpy_python_tensorflow_tensorflow_datasets.txt |
Q:
How to calculate mean absolute error horizontally(row-wise) on 2D numpy.array with sklearn.metrics?
I've tried to calculate mean_absolute error of all rows of an 2-D array. Here is my code:
from sklearn.metrics import mean_absolute_error as mae
arr = np.array([[1.7, 3.1], [2.1, 2.7], [0.9, 0.7], [0.3, 0.8]])
resu... | How to calculate mean absolute error horizontally(row-wise) on 2D numpy.array with sklearn.metrics? | I've tried to calculate mean_absolute error of all rows of an 2-D array. Here is my code:
from sklearn.metrics import mean_absolute_error as mae
arr = np.array([[1.7, 3.1], [2.1, 2.7], [0.9, 0.7], [0.3, 0.8]])
result_arr = np.apply_along_axis(mae, 0, arr[:, 0], arr[:,1])
However, I got result like that:
array(0.675)... | [
"I think that you may be confused about the mean absolute error metrics. mae calculates mean error for two sets of items (predictions and y values of a test set), and this is why it returns one number.\nYour desired result indicates that you are looking other some metrics on each row of your array, not the mean of ... | [
0
] | [] | [] | [
"numpy",
"python",
"scikit_learn"
] | stackoverflow_0074285889_numpy_python_scikit_learn.txt |
Q:
Mention outer classes in an inner class
How can I access an inheritance's list from an class inside of that class?
Hi I've been trying to create a chess board in pygame with pieces and wanted to keep things neat by having a "Board" class and in it, a "Chess" class that would contain all the chess specific code.
In... | Mention outer classes in an inner class | How can I access an inheritance's list from an class inside of that class?
Hi I've been trying to create a chess board in pygame with pieces and wanted to keep things neat by having a "Board" class and in it, a "Chess" class that would contain all the chess specific code.
In the chess class I have a function (test) tha... | [
"You cannot directly access attributes from the outer class in your nested inner class. For your use-case, you might consider passing the grid to your method call as an argument\nclass Board:\n def __init__(self, size):\n ...\n\n \n class Chess:\n ...\n \n def test(self, grid):\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074286813_python.txt |
Q:
When working with json why use json.loads?
This is not much an error I am having but I would like the reason behind the following:
For example in a tutorial page we have
json_string = """
{
"researcher": {
"name": "Ford Prefect",
"species": "Betelgeusian",
"relatives": [
{
... | When working with json why use json.loads? | This is not much an error I am having but I would like the reason behind the following:
For example in a tutorial page we have
json_string = """
{
"researcher": {
"name": "Ford Prefect",
"species": "Betelgeusian",
"relatives": [
{
"name": "Zaphod Beeblebrox",
... | [
"Because your second example is not JSON at all, that's Python. They have superficial similarities, but you are only confusing yourself by mixing them.\nFor example, the values None, True, and False are valid in Python but not in JSON, where they would be represented by null, true, and false, respectively. Another ... | [
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074286874_json_python.txt |
Q:
How to convert string to uniqueidentifier in Django?
I'm trying to insert a pre-generated GUID to SQL Server database from another SQL Server database via Django ORM, but keep getting Conversion failed when converting from a character string to uniqueidentifier. I've already changed my field in model to UUID field... | How to convert string to uniqueidentifier in Django? | I'm trying to insert a pre-generated GUID to SQL Server database from another SQL Server database via Django ORM, but keep getting Conversion failed when converting from a character string to uniqueidentifier. I've already changed my field in model to UUID field and started creating
UUID object from my UUID character s... | [
"Why don't you try to create a CharField then make it unique so that you can use it as unique identifier - sample_field = models.CharField(max_length=200, blank=False,null=False,unique=True)\n"
] | [
0
] | [] | [] | [
"django",
"django_orm",
"guid",
"python",
"sql_server"
] | stackoverflow_0074091417_django_django_orm_guid_python_sql_server.txt |
Q:
Python spaCy custom tokenizer suffix and infix problem
I'm working on adding rules to the 'en_core_web_sm' spaCy nlp model's tokeniser, to correctly tokenise the string below:
s = "This string M=20kg/H=200mm"
into tokens ['This', 'string', 'M=', '20', 'kg', '/', 'H=', '200', 'mm']
But having '/' as an infix, and '... | Python spaCy custom tokenizer suffix and infix problem | I'm working on adding rules to the 'en_core_web_sm' spaCy nlp model's tokeniser, to correctly tokenise the string below:
s = "This string M=20kg/H=200mm"
into tokens ['This', 'string', 'M=', '20', 'kg', '/', 'H=', '200', 'mm']
But having '/' as an infix, and 'kg' as a suffix right before the infix complicates the situa... | [
"The tokenizer algorithm isn't recursive. It looks for prefixes and suffixes, then it looks for infixes, and then it stops. It doesn't look again for prefixes and suffixes after splitting on infixes. A full description of the algorithm: https://spacy.io/usage/linguistic-features#how-tokenizer-works\nOne option, if ... | [
0
] | [] | [] | [
"python",
"python_re",
"regex",
"spacy",
"string"
] | stackoverflow_0074273598_python_python_re_regex_spacy_string.txt |
Q:
How to not return a key if its value is None in a recursive function
I have return statement within a recursive function that looks like this:
def recursive_function(data):
....
return {f'uid': uid,'title': title, 'string': string,'create-time': create_time, 'edit-time': edit_time, 'children': children, 'refs': re... | How to not return a key if its value is None in a recursive function | I have return statement within a recursive function that looks like this:
def recursive_function(data):
....
return {f'uid': uid,'title': title, 'string': string,'create-time': create_time, 'edit-time': edit_time, 'children': children, 'refs': refs}
Sometimes some of these values can be None (ex: when the title has a ... | [
"You can achieve this using dictionary comprehension:\nreturn {key:value for key,value in {f'uid': uid,'title': title, 'string': string,'create-time': create_time, 'edit-time': edit_time, 'children': children, 'refs': refs}.items() if value is not None }\n\n\n",
"You can't directly get non-None values from a dict... | [
1,
1
] | [] | [] | [
"json",
"python",
"python_3.x"
] | stackoverflow_0074286842_json_python_python_3.x.txt |
Q:
Correct way to test for numpy.dtype
I'm looking at a third-party lib that has the following if-test:
if isinstance(xx_, numpy.ndarray) and xx_.dtype is numpy.float64 and xx_.flags.contiguous:
xx_[:] = ctypes.cast(xx_.ctypes._as_parameter_,ctypes.POINTER(ctypes.c_double))
It appears that xx_.dtype is numpy.flo... | Correct way to test for numpy.dtype | I'm looking at a third-party lib that has the following if-test:
if isinstance(xx_, numpy.ndarray) and xx_.dtype is numpy.float64 and xx_.flags.contiguous:
xx_[:] = ctypes.cast(xx_.ctypes._as_parameter_,ctypes.POINTER(ctypes.c_double))
It appears that xx_.dtype is numpy.float64 always fails:
>>> xx_ = numpy.zeros(... | [
"This is a bug in the lib.\ndtype objects can be constructed dynamically. And NumPy does so all the time. There's no guarantee anywhere that they're interned, so constructing a dtype that already exists will give you the same one.\nOn top of that, np.float64 isn't actually a dtype; it's a… I don't know what these t... | [
37,
6,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0026921836_numpy_python.txt |
Q:
How to generate numbers and store in particular rows of a column in dataframe
I just need to generate the numbers and store in the column C in the blank spaces
Data
A B C
12525 1FWE23
14654 14654
24798 24798
38945 38945
46456 46485 8
AD545 45346 9
A5D66 A... | How to generate numbers and store in particular rows of a column in dataframe | I just need to generate the numbers and store in the column C in the blank spaces
Data
A B C
12525 1FWE23
14654 14654
24798 24798
38945 38945
46456 46485 8
AD545 45346 9
A5D66 A5D66 10
Expected
A B C
12525 1FWE23 0
14654 14654 ... | [
"First create mask for select rows and assign range with sum True values for lenght:\n#C has empty strings\nm = df.C.eq('')\n\n#C has missing values\n# m = df.C.isna()\n\ndf.loc[m, 'C'] = range(m.sum())\nprint (df)\n A B C\n0 12525 1FWE23 0\n1 14654 14654 1\n2 24798 24798 2\n3 38945 3... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074286462_dataframe_pandas_python.txt |
Q:
Please explain this code to me ... I have been trying to solve it on paper but i cant
def add(x, y):
return x + y
def do twice(func, x, y):
return func(func(x, y), func(x, y))
a = 5
b = 10
print(do_twice(add, a, b))
Someone Please explain it to me in simple words..
A:
In Python, functions are objects too... | Please explain this code to me ... I have been trying to solve it on paper but i cant | def add(x, y):
return x + y
def do twice(func, x, y):
return func(func(x, y), func(x, y))
a = 5
b = 10
print(do_twice(add, a, b))
Someone Please explain it to me in simple words..
| [
"In Python, functions are objects too. You can pass a function as an argument to another function. In this case, add is passed as an argument to do_twice.\nA function name with parentheses after it (add(3, 4)) calls the function; you end up with whatever the function returns. But a function name not followed by par... | [
2,
1,
0,
0
] | [
"This is an example for \"Passing function name as an argument\". So in this example you gave\ndef add(x, y):\n return x + y\n\ndef do_twice(func, x, y):\n return func(func(x, y), func(x, y))\n\na = 5 \nb = 10\n\nprint(do_twice(add, a, b))\n\nYou can pass the \"name\" of the function as an argument to another func... | [
-1
] | [
"python"
] | stackoverflow_0074286884_python.txt |
Q:
How to forward fill the year and the corresponding values in the dataframe
I have a dataframe with 2 columns of period and inventory code as below. I want to forward fill the year for each inventory item from their starting year all the way to 2022. The yellow highlighted are the rows I want to fill for each inven... | How to forward fill the year and the corresponding values in the dataframe | I have a dataframe with 2 columns of period and inventory code as below. I want to forward fill the year for each inventory item from their starting year all the way to 2022. The yellow highlighted are the rows I want to fill for each inventory item. What would be the way to do this? Any suggestions are greatly appreci... | [
"Forward filling via ffill makes only sense, when you have NaN values, that are to be replaced by the last valid one. Hence, you would need to add rows with NaN for each inventory code and an incremented period.\nAlternatively, you could append a dataframe with the missing rows directly:\n#identify maximum period\n... | [
2,
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074213540_numpy_pandas_python.txt |
Q:
"Table 'nest.auth_user' doesn't exist"
I am creating a custom user registration form and I keep getting this error. How do I correct this.
> ProgrammingError at /Identity/register/ (1146, "Table 'nest.auth_user'
> doesn't exist")
I adjusted the authentication system to use email instead of username and I switche... | "Table 'nest.auth_user' doesn't exist" | I am creating a custom user registration form and I keep getting this error. How do I correct this.
> ProgrammingError at /Identity/register/ (1146, "Table 'nest.auth_user'
> doesn't exist")
I adjusted the authentication system to use email instead of username and I switched from SQlite to Mysql.
# Create models fo... | [
"You need to migrate first\npython3 manage.py makemigrations\npython3 manage.py migrate\n\n",
" Need to migrate your model files to database... \n python manage.py makemigrations\n python manage.py migrate\n\n",
"This happened to me when switching from sqlite to mysql. I guess I'd made auth_user on sqlite... | [
0,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0046475759_django_python.txt |
Q:
Convert lists into higher dimension so that elements can be reached by following
I have a matrix that I want to convert to 3D so that I can be able to print the element of list[i][j][k]
a = [[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 2, 3, 4,5], [3, 2, 3, 4, 3, 4], [4, 3, 4, 5, 4, 3], [5, 4, 5, 6, 5, 4]]]
pr... | Convert lists into higher dimension so that elements can be reached by following | I have a matrix that I want to convert to 3D so that I can be able to print the element of list[i][j][k]
a = [[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 2, 3, 4,5], [3, 2, 3, 4, 3, 4], [4, 3, 4, 5, 4, 3], [5, 4, 5, 6, 5, 4]]]
print(a[5][5][0]) # I want to be able to print in 3D`
I get right output if I do a[5][5... | [
"Tried to reproduce your issue. To me, it works if you use the right index. Here, it perfectly works if you do for instance\nprint(a[0][0][5]) # I want to be able to print in 3D`\n\n",
"for list a = [[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 2, 3, 4,5], [3, 2, 3, 4, 3, 4], [4, 3, 4, 5, 4, 3], [5, 4, 5, 6, 5... | [
0,
0
] | [] | [] | [
"3d",
"list",
"matrix",
"python",
"vector"
] | stackoverflow_0074286961_3d_list_matrix_python_vector.txt |
Q:
How to repeat a Foreign Key Model, on multiple fields in another Model ? + Django
I want to build Trip.Model, with multiple Hotel.Model assignments, each under a different field name. Example(_pb, _hv, _nl)
class Trip(models.Model):
hotel_pb = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True)
... | How to repeat a Foreign Key Model, on multiple fields in another Model ? + Django | I want to build Trip.Model, with multiple Hotel.Model assignments, each under a different field name. Example(_pb, _hv, _nl)
class Trip(models.Model):
hotel_pb = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True)
hotel_hv = models.ForeignKey(Hotel, on_delete=models.PROTECT, blank=True)
hotel_nl ... | [
"Use related_name, see below.\nhotel_pb = models.ForeignKey(Hotel, related_name = 'hotel_pb', on_delete=models.PROTECT, blank=True)\n hotel_hv = models.ForeignKey(Hotel, related_name = 'hotel_hv',on_delete=models.PROTECT, blank=True)\n hotel_nl = models.ForeignKey(Hotel, related_name = 'hotel_nl',on_delete=mo... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074281340_django_python.txt |
Q:
I want to create a figure with three bar charts on it
I am trying to create a plot by grouping the data into categories: "Topic", "Person" and "Organisation" similar to this graph:
How can I do this?
Thank you very much.
This was my coding:
figure, axis = plt.subplots(2, 2)
df_per = df_per.sort_values(by=['Freq... | I want to create a figure with three bar charts on it | I am trying to create a plot by grouping the data into categories: "Topic", "Person" and "Organisation" similar to this graph:
How can I do this?
Thank you very much.
This was my coding:
figure, axis = plt.subplots(2, 2)
df_per = df_per.sort_values(by=['Frequency'])
y1 = plt.barh(y=df_per.Person, width=df_per.Freque... | [
"You need to select the axis that you want to plot on as a two dimensional array:\nfigure, axis = plt.subplots(2, 2)\n\ndf_per = df_per.sort_values(by=['Frequency'])\ny1 = axis[0,0].barh(y=df_per.Person, width=df_per.Frequency);\nplt.title('Person')\n\ndf_org = df_org.sort_values(by=['Frequency'])\ny2 = axis[0,1].b... | [
0
] | [] | [] | [
"bar_chart",
"python"
] | stackoverflow_0074286779_bar_chart_python.txt |
Q:
Inset_axes in polar coordinates
I am using matplotlib.axes.Axes.inset_axes (https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.inset_axes.html) to create an child axe of a an existing parent axe.
How do I set it to polar coordinates ?
I can not use this: Matplotlib inset polar plot as 'Axes' object has... | Inset_axes in polar coordinates | I am using matplotlib.axes.Axes.inset_axes (https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.inset_axes.html) to create an child axe of a an existing parent axe.
How do I set it to polar coordinates ?
I can not use this: Matplotlib inset polar plot as 'Axes' object has no property 'polar'.
But inset_axes ... | [
"From the comment of ImportanceOfBeingErnest:\njust use mpl_toolkits.axes_grid1.inset_locator.inset_axes() instead, with the parameter axes_class = matplotlib.projections.get_projection_class('polar').\n",
"From version 3.6, matplotlib.axes.Axes.inset_axes also accepts \"polar\" and \"projection\" parameters, so ... | [
1,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0058595212_matplotlib_python.txt |
Q:
Django Rest Framework - drf-spectacular add extra models to schemas
I used drf-spectacular and have two questions about this module.
I wanna create custom Schemas and overwrite Schema in API endpoints. How to do this?
I search a way to add custom models to Schemas but without connected this with endpoints.
I se... | Django Rest Framework - drf-spectacular add extra models to schemas | I used drf-spectacular and have two questions about this module.
I wanna create custom Schemas and overwrite Schema in API endpoints. How to do this?
I search a way to add custom models to Schemas but without connected this with endpoints.
I see that i can add custom Schema by:
"""
inline_serializer(
... | [
"Use generic view to automatically implement this:\nfrom rest_framework.generics import GenericAPIView\n\nexample of my view:\nclass CategoryDetails(GenericAPIView):\n serializer_class = CategorySerializer\n permission_classes = [IsAdminUser]\n http_method_names = ['get', 'put']\n\n def get_object(self,... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"drf_spectacular",
"python"
] | stackoverflow_0073067668_django_django_rest_framework_drf_spectacular_python.txt |
Q:
sum up a numeric string (1111 = 1+1+1+1=4)
#Develop a program that reads a four-digit integer from the user and displays the sum of the digits in the number. For example, if the user enters 3141 then your program should display 3+1+4+1=9.
ri = input("please enter four digits")
if len(ri) == 4 and ri.isnumeric() =... | sum up a numeric string (1111 = 1+1+1+1=4) | #Develop a program that reads a four-digit integer from the user and displays the sum of the digits in the number. For example, if the user enters 3141 then your program should display 3+1+4+1=9.
ri = input("please enter four digits")
if len(ri) == 4 and ri.isnumeric() == True:
print(ri[0]+ri[1]+ri[2]+ri[3])
else:... | [
"ri = input(\"please enter four digits: \")\nif len(ri) == 4 and ri.isnumeric():\n print(f'{ri}={\"+\".join(ri)}={sum(map(int, ri))}')\nelse:\n print(\"Error: should be four digits!\")\n\nplease enter four digits: 3141\n3141=3+1+4+1=9\n\n",
"ri = input(\"please enter four digits: \")\nres = 0\nfor n in ri:\... | [
0,
0,
0,
0
] | [
"Edit for better answer\ninput_string = input(\"Enter numbers\")\noutput_string = \"\"\nsum = 0\ncount = 0\nfor n in input_string:\n if count < len(input_string)-1:\n output_string += str(n) + \"+\"\n else:\n output_string += str(n) + \"=\"\n sum += int(n)\n count += 1\noutput_string += st... | [
-1
] | [
"converters",
"input",
"isnumeric",
"python",
"sum"
] | stackoverflow_0074286930_converters_input_isnumeric_python_sum.txt |
Q:
Inplace operation on specific lines and columns of dataframe
Say I have a dataframe with negative values on specific columns:
df = pd.DataFrame([[1, 1, -1],[-1, 1, 1],[-1, -1, 1]])
Now, I want to inplace clip the negative values to 0 on only specific lines and columns:
df.loc[[1, 2], [0, 1]].clip(lower=0, inplace... | Inplace operation on specific lines and columns of dataframe | Say I have a dataframe with negative values on specific columns:
df = pd.DataFrame([[1, 1, -1],[-1, 1, 1],[-1, -1, 1]])
Now, I want to inplace clip the negative values to 0 on only specific lines and columns:
df.loc[[1, 2], [0, 1]].clip(lower=0, inplace=True)
But this doesn't work:
df
Out:
0 1 2
0 1 1 -1
1 -1... | [
"How about using df.lt instead:\ndf[df.loc[[1, 2], [0, 1]].lt(0)] = 0\n\nprint(df)\n\n 0 1 2\n0 1 1 -1\n1 0 1 1\n2 0 0 1\n\n",
"You can do this:\ndf.loc[[1, 2], [0, 1]] = df.loc[[1, 2], [0, 1]].clip(lower=0)\n\nOutput:\n 0 1 2\n0 1 1 -1\n1 0 1 1\n2 0 0 1\n\n"
] | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074286991_dataframe_pandas_python.txt |
Q:
Return the enum key when decoding Protobuf in Python
Currently, I am decoding protobuf messages in Python where the output is:
{
"lat": 12.345678,
"lng": -12.345678,
"firmware_status": 3
}
In my case 3 corresponds to FINISHED per the .proto file enum definition. * Note I'm using v3 of protobuf.
enum Fir... | Return the enum key when decoding Protobuf in Python | Currently, I am decoding protobuf messages in Python where the output is:
{
"lat": 12.345678,
"lng": -12.345678,
"firmware_status": 3
}
In my case 3 corresponds to FINISHED per the .proto file enum definition. * Note I'm using v3 of protobuf.
enum FirmwareStatus {
UNKNOWN = 0;
STARTED = 1;
IN_PROGRESS ... | [
"You can use json_format.MessageToDict which has an option so save enums as string\nhttps://github.com/protocolbuffers/protobuf/blob/main/python/google/protobuf/json_format.py#L134\n"
] | [
2
] | [] | [] | [
"protocol_buffers",
"python"
] | stackoverflow_0074282140_protocol_buffers_python.txt |
Q:
Python How to match all text between two strings in multiline
I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines.
The example text is ('\n' is a newline)
speakerC:SHAKSDHKWJHFKJWHFKJWFJ\n
speakerA:SHAKSDHKWJHFKJWHFKJWFJ\n
speakerA:Let's beginning to do s... | Python How to match all text between two strings in multiline | I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines.
The example text is ('\n' is a newline)
speakerC:SHAKSDHKWJHFKJWHFKJWFJ\n
speakerA:SHAKSDHKWJHFKJWHFKJWFJ\n
speakerA:Let's beginning to do some thing.\n ----> I want to capture from here
[there may have a va... | [
"You need to specify last matching position like this:\n.*?speakerA\nThis means match until the first speakerA pattern.\nimport re\n\n\ntext = \"\"\"\nspeakerC:SHAKSDHKWJHFKJWHFKJWFJ\\n\nspeakerA:SHAKSDHKWJHFKJWHFKJWFJ\\n\nspeakerA:Let's beginning to do some thing.\\n ----> I want to capture from here\n[there may h... | [
0
] | [] | [] | [
"multiline",
"python",
"regex"
] | stackoverflow_0074286933_multiline_python_regex.txt |
Q:
Finding Camera Matrix from known Points python
I have 8 3d points of a 3D model and 8 2d points of that model's real world photograph. is it possible to get the camera matrix of that camera using these 3D and 2D points?
here are the 3D points
X Y Z
0 0.098 35.484 16.58
1 17.34 38.638 ... | Finding Camera Matrix from known Points python | I have 8 3d points of a 3D model and 8 2d points of that model's real world photograph. is it possible to get the camera matrix of that camera using these 3D and 2D points?
here are the 3D points
X Y Z
0 0.098 35.484 16.58
1 17.34 38.638 16.28
2 27.65 44.133 0.083
3 17.23 38.678... | [
"Yes, the problem of estimating the camera matrix given 3D points and their projection is called Camera resectioning. You need at least 6 points to be able to solve it.\nIn Python you can use OpenCV's calibrateCamera function:\nretval, cameraMatrix, distCoeffs, rvecs, tvecs = cv2.calibrateCamera(objectPoints, image... | [
1
] | [] | [] | [
"camera_calibration",
"computer_vision",
"python"
] | stackoverflow_0074286097_camera_calibration_computer_vision_python.txt |
Q:
Rewriting functions from r to python
I have function written in R.
V <- function(c, E, HS, EC_50) E + (1 - E) / (1 + exp(HS * (c - EC_50))
I would like to get the same function in Python but I don't know how. I haven't used Python very much before. Therefore, I am asking for forum help.
A:
I think this is what... | Rewriting functions from r to python | I have function written in R.
V <- function(c, E, HS, EC_50) E + (1 - E) / (1 + exp(HS * (c - EC_50))
I would like to get the same function in Python but I don't know how. I haven't used Python very much before. Therefore, I am asking for forum help.
| [
"I think this is what you are looking for:\nimport numpy as np\n\ndef v(c, E, HS, EC_50):\n return E + (1 - E) / (1 + np.exp(HS * (c - EC_50)))\n\n",
"You can use lambda expression\nimport numpy as np\nv = lambda c, E, HS, EC_50: E + (1 - E) / (1 + np.exp(HS * (c - EC_50)))\n\n"
] | [
2,
2
] | [] | [] | [
"function",
"python",
"r"
] | stackoverflow_0074287090_function_python_r.txt |
Q:
The smallest valid alpha value in matplotlib?
Some of my plots have several million lines. I dynamically adjust the alpha value, by the number of lines, so that the outliers more or less disappear, while the most prominent features appear clear. But for some alpha's, the lines just disappear.
What is the smallest ... | The smallest valid alpha value in matplotlib? | Some of my plots have several million lines. I dynamically adjust the alpha value, by the number of lines, so that the outliers more or less disappear, while the most prominent features appear clear. But for some alpha's, the lines just disappear.
What is the smallest valid alpha value for line plots in in matplotlib? ... | [
"As @ImportanceOfBeingErnest suggested in the comments, the lower limit seems to be 1/255.\nI did not have time to go though the source code and all, but I did test it, and assume what happens is, that the input alpha value needs to be represented as an int between 0 and 255:\nint(alpha*255)\n\nWhen the input alpha... | [
6,
0
] | [
"There's no lower limit; the lines just appear to be invisible for very small alpha values.\nIf you draw one line with alpha=0.01 the difference in color is too small for your screen / eyes to discern. If you draw 100 lines with a=0.01 on top of each other, you will see them.\nAs for your problem, you can just add ... | [
-1
] | [
"matplotlib",
"python"
] | stackoverflow_0058788958_matplotlib_python.txt |
Q:
How to type hint a dictionary with values of different types
When declaring a dictionary as a literal, is there a way to type-hint what value I am expecting for a specific key?
And then, for discussion: are there guiding principles around dictionary typing in Python? I'm wondering whether it is considered bad prac... | How to type hint a dictionary with values of different types | When declaring a dictionary as a literal, is there a way to type-hint what value I am expecting for a specific key?
And then, for discussion: are there guiding principles around dictionary typing in Python? I'm wondering whether it is considered bad practice to mix types in dictionaries.
Here's an example:
Consider th... | [
"You are looking for TypedDict. It is currently only a mypy-only extension, but there are plans to make it an officially sanctioned type in the near-future. I am not sure if PyCharm supports this feature yet, though.\nSo, in your case, you'd do:\nfrom mypy_extensions import TypedDict\n\nRectangleElements = TypedDic... | [
17,
2,
0
] | [] | [] | [
"dictionary",
"pycharm",
"python",
"python_typing",
"type_hinting"
] | stackoverflow_0051031757_dictionary_pycharm_python_python_typing_type_hinting.txt |
Q:
"no such column" error when trying to update
I am trying to replace a string with an id:
import sqlite3
TABLES = ['table1', 'table2', ...]
PAR_TYPES_STRINGS = ['foo', 'bar', ...]
PAR_TYPES_ID = [1, 2, ...]
def upateTable(table, parTypeId, parTypeString):
return f"UPDATE {table} SET par_type = {parTypeId} WHERE... | "no such column" error when trying to update | I am trying to replace a string with an id:
import sqlite3
TABLES = ['table1', 'table2', ...]
PAR_TYPES_STRINGS = ['foo', 'bar', ...]
PAR_TYPES_ID = [1, 2, ...]
def upateTable(table, parTypeId, parTypeString):
return f"UPDATE {table} SET par_type = {parTypeId} WHERE par_type = {parTypeString};"
conn = sqlite3.conn... | [
"In the function definition, you need to put {parTypeString} in quotes: '{parTypeString}', because you want to check where the hardcoded column matches that string. Otherwise the expression is interpreted to check equality between two columns, hence the error message.\n"
] | [
0
] | [] | [] | [
"python",
"sql_update",
"sqlite"
] | stackoverflow_0074287024_python_sql_update_sqlite.txt |
Q:
inset_axes polar projection in a polar plot in matplotlib
I would like to create a polar plot with a polar zoom.
This is what I have done do far:
fig = plt.figure(figsize=(30, 15))
G = gridspec.GridSpec(1, 2)
axes_1 = plt.subplot(G[0],projection='polar')
axes_1.inset_axes(bounds=[0.0,0.0,0.1,0.1],projection='pol... | inset_axes polar projection in a polar plot in matplotlib | I would like to create a polar plot with a polar zoom.
This is what I have done do far:
fig = plt.figure(figsize=(30, 15))
G = gridspec.GridSpec(1, 2)
axes_1 = plt.subplot(G[0],projection='polar')
axes_1.inset_axes(bounds=[0.0,0.0,0.1,0.1],projection='polar')
axes_2 = plt.subplot(G[1])
and here the error that I g... | [
"From version 3.6, matplotlib.axes.Axes.inset_axes accepts \"polar\" and \"projection\" parameters. If you use a older version, there is also a workaround using mpl_toolkits.axes_grid1.inset_locator.inset_axes() (see this answer).\nCreating a rectangular zoom of a polar plot is not as straightforward, but this answ... | [
0
] | [] | [] | [
"matplotlib",
"polar_coordinates",
"python",
"zooming"
] | stackoverflow_0065886593_matplotlib_polar_coordinates_python_zooming.txt |
Q:
Google Foobar Challenge 3 - Find the Access Codes
Find the Access Codes
Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (lst[i], lst[j], lst[k]) where i < j < k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 99... | Google Foobar Challenge 3 - Find the Access Codes | Find the Access Codes
Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (lst[i], lst[j], lst[k]) where i < j < k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits within a signed 32-bit... | [
"def solution(l):\n c = [0] * len(l)\n count = 0\n for i in range(0,len(l)):\n j=0\n for j in range(0, i):\n if l[i] % l[j] == 0:\n c[i] = c[i] + 1\n count = count + c[j]\n return count\n\nThis will take O(n^2) time complexity\nTo try it out just ad... | [
9,
5,
4,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"combinations",
"java",
"python"
] | stackoverflow_0039846735_combinations_java_python.txt |
Q:
Python. IOError: [Errno 13] Permission denied: when i'm copying file
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshe... | Python. IOError: [Errno 13] Permission denied: when i'm copying file | I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"... | [
"Read the docs:\n\nshutil.copyfile(src, dst)\nCopy the contents (no metadata) of the file named src to a file\n named dst. dst must be the complete target file name; look at copy()\n for a copy that accepts a target directory path.\n\n",
"use \nshutil.copy instead of shutil.copyfile\nexample:\nshutil.copy(PathO... | [
90,
26,
4,
4,
1,
1,
0,
0,
0
] | [
"I avoid this error by doing this:\n\nImport lib 'pdb' and insert 'pdb.set_trace()' before 'shutil.copyfile', it would just like this:\n\n import pdb\n ...\n print(dst)\n pdb.set_trace()\n shutil.copyfile(src,dst)\n\n\nrun the python file in a terminal, it will execute to the line 'pdb.set_trace()', an... | [
-1,
-3
] | [
"python",
"windows",
"windows_7"
] | stackoverflow_0007518067_python_windows_windows_7.txt |
Q:
'MatplotlibDeprecationWarning' - Warning when trying to plot histogram
I'm trying to use matplotlib to plot a histogram but keep running into this error:
MatplotlibDeprecationWarning: The resize_event function was deprecated in Matplotlib 3.6 and will be removed two minor releases later. Use callbacks.process('res... | 'MatplotlibDeprecationWarning' - Warning when trying to plot histogram | I'm trying to use matplotlib to plot a histogram but keep running into this error:
MatplotlibDeprecationWarning: The resize_event function was deprecated in Matplotlib 3.6 and will be removed two minor releases later. Use callbacks.process('resize_event', ResizeEvent(...)) instead.
Here's my code; feedback on how I can... | [
"Seems like you can find your answer here:\nhttps://github.com/matplotlib/matplotlib/issues/23921\nIn short: it's a bug, and it will be corrected in 3.6.1\n",
"I'm facing the same issue,\nI found a work-around:\n import matplotlib\n matplotlib.use('TkAgg')\n\nError will still be there, but now you can see p... | [
3,
1
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0073848820_matplotlib_pandas_python.txt |
Q:
Dreambooth - RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0
I'm trying to train a model via Dreambooth and I'm running into this problem. I've looked for solutions but none of them seem to work. I read adding ".to(device)" to variables helps but I'm not ... | Dreambooth - RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0 | I'm trying to train a model via Dreambooth and I'm running into this problem. I've looked for solutions but none of them seem to work. I read adding ".to(device)" to variables helps but I'm not sure where to add them. I was wondering if anyone could tell where to add them by the error below, or if anyone had suggestion... | [
"there are a whole bunch of functions in SD that WILL NOT work if you're running --lowvram/--medvram and several of the other command line args. tensors on multiple devices means due to your settings you're at least partially co-processing on your cpu. to test which setting, if you're not sure, don't waste time in ... | [
0
] | [] | [] | [
"python",
"tensor"
] | stackoverflow_0073928870_python_tensor.txt |
Q:
How to parse raw html element in R or Python?
For instance in this website: https://www.amazon.com/Lexani-LXUHP-207-All-Season-Radial-Tire-245/dp/B07FFH8F9V/
So I say "inspect" and I find the element that I'm interested:
<span id="productTitle" class="a-size-large product-title-word-break"> Lexani LXUHP-207... | How to parse raw html element in R or Python? | For instance in this website: https://www.amazon.com/Lexani-LXUHP-207-All-Season-Radial-Tire-245/dp/B07FFH8F9V/
So I say "inspect" and I find the element that I'm interested:
<span id="productTitle" class="a-size-large product-title-word-break"> Lexani LXUHP-207 Performance Radial Tire - 245/45R18 100W </s... | [
"there will be problems with captcha on amazon, but if you beat it you can get what you want by\nimport requests\nfrom bs4 import BeautifulSoup\n\nthe_entire_thing = BeautifulSoup(requests.get('https://www.amazon.com/Lexani-LXUHP-207-All-Season-Radial-Tire-245/dp/B07FFH8F9V/').text, 'lxml').find(id='productTitle')\... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"r",
"rvest",
"web_scraping"
] | stackoverflow_0074285213_beautifulsoup_python_r_rvest_web_scraping.txt |
Q:
Does blocking printing to console in a thread block it for the whole application? [Python]
In an application that I'm writing the user can provide a class which will then be trial runned in a thread to see if it throws any exceptions.
However, I want to suppress any printing by that class in that thread. I know ho... | Does blocking printing to console in a thread block it for the whole application? [Python] | In an application that I'm writing the user can provide a class which will then be trial runned in a thread to see if it throws any exceptions.
However, I want to suppress any printing by that class in that thread. I know how to do this based on this solution, but my question is if this will block the printing for the ... | [
"So as @Markus Safar as pointed out then no, other threads will no be able to print to console as well.\n"
] | [
1
] | [] | [] | [
"printing",
"python",
"stdout"
] | stackoverflow_0074284810_printing_python_stdout.txt |
Q:
How to download the image if we have given url?
I have the following URLs, I want to download these images using a code. There is millions of URL so I want to do it using python.
1) https://image.lexica.art/md/dbbb96f1-fce2-4970-ab62-b4b4e6859fe9
2) https://image.lexica.art/md/76318f25-5736-4cda-965d-96fe34823263
... | How to download the image if we have given url? | I have the following URLs, I want to download these images using a code. There is millions of URL so I want to do it using python.
1) https://image.lexica.art/md/dbbb96f1-fce2-4970-ab62-b4b4e6859fe9
2) https://image.lexica.art/md/76318f25-5736-4cda-965d-96fe34823263
3) https://image.lexica.art/md/c11dd279-757e-43ff-830... | [
"rather complicated ... from wireshark trace, i see it's using HTTP2 and i'm guessing server also checks for browser-like HTTP headers (eg. \"User-Agent\", etc)\nmake sure you install httpx with http2 pip3 install 'httpx[http2]'\nthen try this,\nimport httpx\nfrom PIL import Image\nfrom io import BytesIO\nimport ht... | [
1,
0
] | [] | [] | [
"python",
"python_imaging_library",
"web_scraping"
] | stackoverflow_0074275327_python_python_imaging_library_web_scraping.txt |
Q:
Celery not running (Permission Denied)
I'm not running a Django Project, this is just a simple python project and I want to demonize the celery. Initially I was running it in the shell. Celery sometimes hangs in between(known issue). Hence I need to restart it again and again. Therefore, I need to daemonize it, so... | Celery not running (Permission Denied) | I'm not running a Django Project, this is just a simple python project and I want to demonize the celery. Initially I was running it in the shell. Celery sometimes hangs in between(known issue). Hence I need to restart it again and again. Therefore, I need to daemonize it, so that I can run a script that restarts the c... | [
"Based on comments, You have wrong write permissions to log file.\nPlease change the ownership to celery using:\nchown -R celery:celery /var/log/celery/\nchown -R celery:celery /var/run/celery/\n\n-R switch is used to change permissions recursive inside directory\n",
"Tell celery where to put the pid file:\nceler... | [
26,
0,
0
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0028825760_celery_python.txt |
Q:
Modifying an already existing file gets me an error
I'm trying to modify an already existing file using openpyxl and python. I'm reading values from the file then doing a little programm and re-writing in the next column new values from the python programm.
My excel file is an xlsm file with macros working in it.
... | Modifying an already existing file gets me an error | I'm trying to modify an already existing file using openpyxl and python. I'm reading values from the file then doing a little programm and re-writing in the next column new values from the python programm.
My excel file is an xlsm file with macros working in it.
It looks like this in python :
import pandas as pd
from o... | [
"Try adding, keep_vba=True\nwb = load_workbook('filepath.xlsm', keep_vba=True)\nxlsm is an extension that indicates that a file contains macros. This could be a reason for your problem.\n"
] | [
1
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0074287335_openpyxl_python.txt |
Q:
How to get the list of possible operational attributes for an objectClass with python-ldap?
With this python snippet, I can get the list of all the available objectClasses in a LDAP server:
import ldap
conn = ldap.initialize("ldap://127.0.0.1:389")
conn.simple_bind_s("cn=admin,dc=mydomain,dc=tld", "mypassword")
r... | How to get the list of possible operational attributes for an objectClass with python-ldap? | With this python snippet, I can get the list of all the available objectClasses in a LDAP server:
import ldap
conn = ldap.initialize("ldap://127.0.0.1:389")
conn.simple_bind_s("cn=admin,dc=mydomain,dc=tld", "mypassword")
res = conn.search_s("cn=subschema", ldap.SCOPE_BASE, "(objectclass=*)", ["*", "+"])
subschema_entr... | [
"Operational attributes are maintained by the LDAP server. They are not \"applicable on a given objectClass\". Thus they must not be set by user applications and they are not referenced in object class descriptions.\nYou can look at the instance attribute AttributeType.usage which contains an Integer indicating its... | [
2
] | [] | [] | [
"ldap",
"python",
"python_ldap"
] | stackoverflow_0074280664_ldap_python_python_ldap.txt |
Q:
Pandas dataframe throwing error when appending to CSV
`
import pandas as pd
df = pd.read_csv("stack.csv")
sector_select = "Col2"
df[sector_select] = ["100"]
df.to_csv("stack.csv", index=False, mode='a', header=False)
`
stack.csv has no data other than a header: Col1,Col2,Col3,Col4,Col5
ValueError: Length of v... | Pandas dataframe throwing error when appending to CSV | `
import pandas as pd
df = pd.read_csv("stack.csv")
sector_select = "Col2"
df[sector_select] = ["100"]
df.to_csv("stack.csv", index=False, mode='a', header=False)
`
stack.csv has no data other than a header: Col1,Col2,Col3,Col4,Col5
ValueError: Length of values (1) does not match length of index (2)
Im just trying... | [
"You can use this:\ndf = df.append({\"Col2\": 100}, ignore_index=True)\n\n",
"That code runs for me.\nBut I assume that you would like to run something like this:\nimport pandas as pd\n\ndf = pd.read_csv(\"stack.csv\")\n\nsector_select = \"Col2\"\n\ndf.at[len(df), sector_select] = \"100\"\n\ndf.to_csv(\"stack.csv... | [
1,
0
] | [] | [] | [
"csv",
"dataframe",
"export_to_csv",
"pandas",
"python"
] | stackoverflow_0074286740_csv_dataframe_export_to_csv_pandas_python.txt |
Q:
How to print out square numbers like this?
i need output like this:
1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
this is what i can do but it's not right
size=int(input())
for row in range(1,size+1):
for col in range(1,size+1):
print(row,end=' ')
print(col)
only use forloop
A:
You can do:... | How to print out square numbers like this? | i need output like this:
1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
this is what i can do but it's not right
size=int(input())
for row in range(1,size+1):
for col in range(1,size+1):
print(row,end=' ')
print(col)
only use forloop
| [
"You can do:\nsize = int(input())\nfor i in range(1, size+1):\n print(' '.join(str(max(i, j)) for j in range(1, size+1)))\n\nExample for size of 9:\n1 2 3 4 5 6 7 8 9\n2 2 3 4 5 6 7 8 9\n3 3 3 4 5 6 7 8 9\n4 4 4 4 5 6 7 8 9\n5 5 5 5 5 6 7 8 9\n6 6 6 6 6 6 7 8 9\n7 7 7 7 7 7 7 8 9\n8 8 8 8 8 8 8 8 9\n9 9 9 9 9 9 ... | [
2,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074286350_python.txt |
Q:
java.lang.OutOfMemoryError: java.lang.OutOfMemoryError: Java heap space
I'am suffing this error since 2 days this shows OutOfMemoryError I can't understand that this error is regarding to java or python I tried in configure java to increase the size but its failed.
This code is written in jupiter notebook
imp... | java.lang.OutOfMemoryError: java.lang.OutOfMemoryError: Java heap space | I'am suffing this error since 2 days this shows OutOfMemoryError I can't understand that this error is regarding to java or python I tried in configure java to increase the size but its failed.
This code is written in jupiter notebook
import jpype
import pyspark
from xlrd import open_workbook
import ... | [
"I think you can change memory settings as suggested in the doc how-to-fix-the-java-lang-outofmemoryerror-while-loading-large-spreadsheets\nAlso there is a optimized mode\nhow-to-fix-the-java-lang-outofmemoryerror-while-loading-large-spreadsheets\nOr else, you can choose other alternatives. EasyExcel, for example, ... | [
0
] | [] | [] | [
"excel",
"java",
"python"
] | stackoverflow_0074286824_excel_java_python.txt |
Q:
cython insert element in array.array
I am trying to convert some python code into cython. In the python code I use data of type
array.array('i', [...]) and use the method array.insert to insert an element at a specific index. in cython however, when I try to insert an element using the same method I get this error... | cython insert element in array.array | I am trying to convert some python code into cython. In the python code I use data of type
array.array('i', [...]) and use the method array.insert to insert an element at a specific index. in cython however, when I try to insert an element using the same method I get this error: BufferError: cannot resize an array that... | [
"Partial answer:\n\nBufferError: cannot resize an array that is exporting buffers\n\nThis is telling you that you have a memoryview (or similar) of the array somewhere. It isn't possible to resize it because that memoryview is looking directly into that array's data and resizing the array will require reallocating ... | [
2,
2
] | [] | [] | [
"cython",
"python"
] | stackoverflow_0074282595_cython_python.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'insert' Python
I'm working on a mini project, it's a hangman game in python. I'm currently able to pick a randomwork from a list, ask user to guess and replace blanks with words.
However, i am facing two challenges
When blanks are replaced with correct letters, ... | AttributeError: 'NoneType' object has no attribute 'insert' Python | I'm working on a mini project, it's a hangman game in python. I'm currently able to pick a randomwork from a list, ask user to guess and replace blanks with words.
However, i am facing two challenges
When blanks are replaced with correct letters, and the code runs again, the already placed alphabets are replaced with ... | [
"You don't need to assign the result of blanks.insert() to a variable\nReplace\nif guess in alpha:\n blanks = blanks.insert(alpha_count, guess) \nelse:\n blanks = blanks.insert(alpha_count,'_')\n\nTo\nif guess in alpha:\n blanks.insert(alpha_count, guess) \nelse:\n blanks.insert(alpha_count,'_')\n\nThis... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074287526_python.txt |
Q:
Python parsing ini file with global scope/properties
Sample ini file that I want to parse and change.
global_key = global_value
.include other_file.ini
[section]
key = value
Is there a way to parse and augment this with Python? I know usually ConfigParser is recommended for ini files, I didn't find any way to pa... | Python parsing ini file with global scope/properties | Sample ini file that I want to parse and change.
global_key = global_value
.include other_file.ini
[section]
key = value
Is there a way to parse and augment this with Python? I know usually ConfigParser is recommended for ini files, I didn't find any way to parse a file with global scope.
| [
".ini file always requires section headers.\nIn this case you can create a custom section header and use allow_no_value=True to parse with ConfigParser class. The allow_no_value=False says the parser to parse the settings without values.\n>>> string = \"\"\"\n... global_key = global_value\n... .include other_file.i... | [
1
] | [] | [] | [
"ini",
"python"
] | stackoverflow_0074287404_ini_python.txt |
Q:
Is it possible to encrypt a private_key with a public_key?
I've got the following code:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmet... | Is it possible to encrypt a private_key with a public_key? | I've got the following code:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa
generated_private_key = rsa.generate_private_key... | [
"Yes, you can, simply because you can encrypt any data. However, just as with longer messages, it makes most sense to use hybrid cryptography here: encrypt with a random symmetric data key such as an AES key, and then encrypt the AES key with the private key. As you are using a random key you can use an all zero IV... | [
0
] | [] | [] | [
"cryptography",
"encryption",
"python"
] | stackoverflow_0074287480_cryptography_encryption_python.txt |
Q:
How to remove curly bracket from the output in python?
I am new to Python I have recently start to learn 1 week ago and I am stuck here... Any help will be appreciate...
from tkinter import *
import tkinter as tk
import psycopg2
root = Tk()
def get_info(Employee_Name, Department, Education,Salary):
con = psyc... | How to remove curly bracket from the output in python? | I am new to Python I have recently start to learn 1 week ago and I am stuck here... Any help will be appreciate...
from tkinter import *
import tkinter as tk
import psycopg2
root = Tk()
def get_info(Employee_Name, Department, Education,Salary):
con = psycopg2.connect(dbname = 'postgres',user = 'postgres',password ... | [
"You are inserting a list or tuple into the listbox instead of a string. You need to explicitly convert each row to a string before passing to the insert method. Otherwise, the underlying tcl interpreter will try to preserve the list-like structure of the data by adding curly braces or backslashes when converting t... | [
4,
1,
0
] | [] | [] | [
"python",
"python_3.x",
"python_requests",
"tkinter"
] | stackoverflow_0063613914_python_python_3.x_python_requests_tkinter.txt |
Q:
Need to execute a curl statement in OCP Cron
I am very new with working on OCP . I have a task to schedule a curl statement via crontab but I'm unable to figure out where to pass the curl statement.
Not sure how to even start. I looked up some examples but do not see anything that matches my requirement
A:
OCP i... | Need to execute a curl statement in OCP Cron | I am very new with working on OCP . I have a task to schedule a curl statement via crontab but I'm unable to figure out where to pass the curl statement.
Not sure how to even start. I looked up some examples but do not see anything that matches my requirement
| [
"OCP is based on Kubernetes. In Kubernetes you have the CronJob resource, which seems to be what you're looking for for your resource and allows you to run a job on a specific schedule.\nAs you need to use curl, you can use the curlimage/curl image, which has the curl binary included:\napiVersion: batch/v1\nkind: C... | [
0
] | [] | [] | [
"cron",
"kubernetes",
"openshift",
"python",
"redhat_containers"
] | stackoverflow_0074282470_cron_kubernetes_openshift_python_redhat_containers.txt |
Q:
how do i print a value of a document in pymongo
ok suppose a doc looks like this:
{
_id: ObjectId("63623815660b1cbf9d151a55"),
name: 'Charmander',
pokedex_id: '004',
type: 'Fire',
stats: [ { health: 10 }, { power: 15 }, { defense: 7 } ],
moves: [ 'ember', 'growl', 'n/a', 'n/a' ]
}
i want... | how do i print a value of a document in pymongo | ok suppose a doc looks like this:
{
_id: ObjectId("63623815660b1cbf9d151a55"),
name: 'Charmander',
pokedex_id: '004',
type: 'Fire',
stats: [ { health: 10 }, { power: 15 }, { defense: 7 } ],
moves: [ 'ember', 'growl', 'n/a', 'n/a' ]
}
i want to get only the name element of the document to stor... | [
"try:\n print(str(char_name['name']))\n\n"
] | [
1
] | [] | [] | [
"mongodb",
"output",
"pymongo",
"python"
] | stackoverflow_0074287325_mongodb_output_pymongo_python.txt |
Q:
CSV Parsing difficulty
I have a CSV file with multiple comma seperated values each enclosed in "". One of the fields has multiple comma seperated values enclosed in "". For eg. "test1","Test2","test0,test4,test5". Can i replace the 3rd field with multiple values with a text of my choice? I am facing an error while... | CSV Parsing difficulty | I have a CSV file with multiple comma seperated values each enclosed in "". One of the fields has multiple comma seperated values enclosed in "". For eg. "test1","Test2","test0,test4,test5". Can i replace the 3rd field with multiple values with a text of my choice? I am facing an error while parsing this csv data into ... | [] | [] | [
"This could do the trick for you:\nwith open(\"stack.csv\", 'r') as f:\n with open('new_file.csv', 'w') as f2:\n rows = f.readlines()\n for row in rows:\n new_row = []\n for col in row.split('\",\"'):\n if ',' in col:\n for part in col.split(\... | [
-1
] | [
"csv",
"json",
"parsing",
"python"
] | stackoverflow_0074287687_csv_json_parsing_python.txt |
Q:
Fill missing dates hourly per group with previous value for only certain conditioned values in certain column
I have the following dataframe (sample):
import pandas as pd
data = [['A', '2022-09-01 10:00:00', False, 2], ['A', '2022-09-01 12:00:00', True, 3], ['A', '2022-09-01 14:00:00', False, 1],
['B', '... | Fill missing dates hourly per group with previous value for only certain conditioned values in certain column | I have the following dataframe (sample):
import pandas as pd
data = [['A', '2022-09-01 10:00:00', False, 2], ['A', '2022-09-01 12:00:00', True, 3], ['A', '2022-09-01 14:00:00', False, 1],
['B', '2022-09-01 13:00:00', False, 1], ['B', '2022-09-01 16:00:00', True, 4], ['B', '2022-09-01 18:00:00', False, 3]]
df ... | [
"First create DatetimeIndex with DataFrame.set_index\nand then in lambda function add missing hours by DataFrame.asfreq, last replace missing values by Series.fillna and forward filling missing values:\ndf['date'] = pd.to_datetime(df['date'])\n\ndf = (df.set_index('date')\n .groupby('group')[['indicator', 'v... | [
3
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074287798_dataframe_pandas_python.txt |
Q:
pipenv: packages do not match the hashes from the requirements file
Pipfile
I recently installed O365 and shortuuid packages using following command, which got executed with no problems on Mac M1.
pipenv install --keep-outdated o365 shortuuid
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = tr... | pipenv: packages do not match the hashes from the requirements file | Pipfile
I recently installed O365 and shortuuid packages using following command, which got executed with no problems on Mac M1.
pipenv install --keep-outdated o365 shortuuid
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
black = "*"
[packages]
django = "~=3.2"
djangorestfra... | [
"The package pyrsistent is a dependency of jsonschema, which is pinned to version 4.4.0 in your Pipfile. There are several possible explanations for a hash mismatch when installing from PyPI. One way to simply fix the error would be to regenerate your Pipfile.lock:\n% pipenv lock\n\nAnd then reinstall all packages ... | [
0
] | [] | [] | [
"pipenv",
"python",
"python_3.7"
] | stackoverflow_0074273757_pipenv_python_python_3.7.txt |
Q:
Unable to write Pandas DataFrame to CSV
I am trying to convert a very large JSON file into smaller CSV files. Here is the code I am using
data = pd.read_json(FILE + '.json', lines=True,
chunksize=2000000, orient='records', encoding='utf-8')
for i, chunk in enumerate(data):
chunk.to_csv('..... | Unable to write Pandas DataFrame to CSV | I am trying to convert a very large JSON file into smaller CSV files. Here is the code I am using
data = pd.read_json(FILE + '.json', lines=True,
chunksize=2000000, orient='records', encoding='utf-8')
for i, chunk in enumerate(data):
chunk.to_csv('../data_subset/{}'.format(FILE + '_' + str(i) +... | [
"Isn't it as simple as this? It's hard to tell without your JSON.\nimport pandas as pd\nFILE = \"data\"\ndata = pd.read_json(FILE + '.json', lines=True,\n chunksize=2000000, orient='records', encoding='utf-8')\nfor chunk in data: \n chunk.to_csv(FILE + '.csv', sep='\\t', mode='a', header=False... | [
0
] | [] | [] | [
"csv",
"export_to_csv",
"json",
"pandas",
"python"
] | stackoverflow_0074287828_csv_export_to_csv_json_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.