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:
Fast way to generate a vector of successive powers in DolphinDB
Suppose the base value is x, I would like to create a vector [1, x, x** 2, x** 3,.... , x**n-1] where the i-th element is Xi.
I know in Python it can be implemented with a list. For x=5 and n=10:
[pow(x,i) for i in range(10)]
[1, 5, 25, 125, 625, 312... | Fast way to generate a vector of successive powers in DolphinDB | Suppose the base value is x, I would like to create a vector [1, x, x** 2, x** 3,.... , x**n-1] where the i-th element is Xi.
I know in Python it can be implemented with a list. For x=5 and n=10:
[pow(x,i) for i in range(10)]
[1, 5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125]
Is there a way to do this in Dolphi... | [
"You can directly use the built-in function pow(x,y) in DolphinDB. When the parameter x is a given base value and y is a vector, it returns the desired result.\nx=5\nn=10\npow(x,0..(n-1))\n\noutput:\n[1,5,25,125,625,3125,15625,78125,390625,1953125]\n\n"
] | [
4
] | [] | [] | [
"auto_vectorization",
"dolphindb",
"pow",
"python",
"vectorization"
] | stackoverflow_0074426219_auto_vectorization_dolphindb_pow_python_vectorization.txt |
Q:
9.4.2: Function definition: Volume of a pyramid with modular functions
I'm not sure where I'm off at, here is the ask.
Define a function calc_pyramid_volume() with parameters base_length, base_width, and pyramid_height, that returns the volume of a pyramid with a rectangular base. calc_pyramid_volume() calls the g... | 9.4.2: Function definition: Volume of a pyramid with modular functions | I'm not sure where I'm off at, here is the ask.
Define a function calc_pyramid_volume() with parameters base_length, base_width, and pyramid_height, that returns the volume of a pyramid with a rectangular base. calc_pyramid_volume() calls the given calc_base_area() function in the calculation.
Relevant geometry equatio... | [
"here is a simpler solution:\ndef pyramid_volume(length, width, height):\n return (length * width) * height/3\n \n length = float(input())\n width = float(input())\n height = float(input())\n print('Volume for', length, width, height, \"is:\", pyramid_volume(length, width, height)\n\nI'm p... | [
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0070779568_python.txt |
Q:
How to flatten a dataframe by a column containing ranges
Input dataframe:
df=
pd.DataFrame(columns=['id', 'antibiotic','start_date', 'end_date'],
data=[['Sophie', 'amoxicillin', 15, 17],
['Sophie', 'doxycycline', 19, 21],
['Sophie', 'amoxicillin', 20, 22... | How to flatten a dataframe by a column containing ranges | Input dataframe:
df=
pd.DataFrame(columns=['id', 'antibiotic','start_date', 'end_date'],
data=[['Sophie', 'amoxicillin', 15, 17],
['Sophie', 'doxycycline', 19, 21],
['Sophie', 'amoxicillin', 20, 22],
['Robert', 'cephalexin', 12, 14],
... | [
"One option is to generate a range for each row, explode to create one row per date, then aggregate per id/date:\n(df.assign(date=lambda d: d.apply(lambda r: range(r['start_date'], r['end_date']+1), axis=1))\n .explode('date')\n .groupby(['id', 'date'], dropna=False)['antibiotic'].agg('/'.join)\n .reset_index... | [
3,
2,
1,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0070939862_pandas_python.txt |
Q:
Do Elements not start from 0?
I'm a noob, learning via Datacamp (which is really annoying and nitpicky... I could've sworn elements started from 0, counting the first element in the list as 0???? This is the problem.
"Create downstairs again, as the first 6 elements of areas. This time, simplify the slicing by omi... | Do Elements not start from 0? | I'm a noob, learning via Datacamp (which is really annoying and nitpicky... I could've sworn elements started from 0, counting the first element in the list as 0???? This is the problem.
"Create downstairs again, as the first 6 elements of areas. This time, simplify the slicing by omitting the begin index.
Create upsta... | [
"The Python slice function does start with 0 as the default starting index, however the end is EXCLUSIVE, meaning it does not include the element at the end of the slice.\nslice([start], stop[, step])\n\nlist[:2] # Elements 0 and 1, stopping at 2, or the first two elements\nlist[2:] # Everything except the fi... | [
0,
0
] | [] | [] | [
"element",
"list",
"python",
"slice"
] | stackoverflow_0074440092_element_list_python_slice.txt |
Q:
Operator with 3 variables highest variable show name with pandas and python
I'm trying to obtain the variable with the highest number so basically this are the variables:
number_no = 17
number_yes = 2
number_dontknow = 10
I would like to know with one is the highest I was using max(number_no, number_yes) but it ... | Operator with 3 variables highest variable show name with pandas and python | I'm trying to obtain the variable with the highest number so basically this are the variables:
number_no = 17
number_yes = 2
number_dontknow = 10
I would like to know with one is the highest I was using max(number_no, number_yes) but it gave me the number and I need the variable name, so I would like to have somethin... | [
"I'm not sure if I understand you correctly?\nBut if I understand correctly:\n\nThe 1st solution is that use max rather the variable:\n\ntotal = sum(number_no + number_yes + number_dontknow)\npercentage = max(number_no, number_yes)/total\nprint(percentage+ \"%\")\n#Show percentage to use it in another function\n\n\... | [
1,
1
] | [] | [] | [
"if_statement",
"max",
"operators",
"pandas",
"python"
] | stackoverflow_0074410242_if_statement_max_operators_pandas_python.txt |
Q:
Can I pass in a list as the weights parameter for random.choices()
I am trying to use the random.choices method with two lists: names and values. The values list is the weights.
I am calling the method by doing
random.choices(names, weights = values, k = 1)
The error I am receiving is
ValueError: The number of we... | Can I pass in a list as the weights parameter for random.choices() | I am trying to use the random.choices method with two lists: names and values. The values list is the weights.
I am calling the method by doing
random.choices(names, weights = values, k = 1)
The error I am receiving is
ValueError: The number of weights does not match the population
Can I not use a list as a parameter... | [
"Because I was reading in my data using pandas DataFrame functions, I was trying to pass DataFrame type data into random.choices which it did not like. I converted the data to lists and it worked.\n"
] | [
0
] | [] | [] | [
"python",
"random"
] | stackoverflow_0074438243_python_random.txt |
Q:
Python 3 - How do I extract data from SQL database and process the data and append to pandas dataframe row by row?
I have a MySQL database, its columns are:
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------... | Python 3 - How do I extract data from SQL database and process the data and append to pandas dataframe row by row? | I have a MySQL database, its columns are:
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int unsigned | NO | PRI | NULL | auto_in... | [
"You could make a list of conversion functions for each column:\nfuncs = [\n str.capitalize,\n str.capitalize,\n str.capitalize,\n int,\n str,\n bool,\n bool,\n lambda v: v if v is not None else '',\n lambda v: json.loads(v) if v is not None else [],\n lambda v: json.loads(v) if v is n... | [
2,
0,
0
] | [] | [] | [
"dataframe",
"mysql",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0068574961_dataframe_mysql_pandas_python_python_3.x.txt |
Q:
Split a string column into multiple columns and dynamically name columns
This question is similar to this one pandas: split a string column into multiple columns and dynamically name columns. I modified the data as below
df = pd.DataFrame.from_dict({'study_id': {0: 'study1',
1: 'study2',
2: 'study3',
3: 'stu... | Split a string column into multiple columns and dynamically name columns | This question is similar to this one pandas: split a string column into multiple columns and dynamically name columns. I modified the data as below
df = pd.DataFrame.from_dict({'study_id': {0: 'study1',
1: 'study2',
2: 'study3',
3: 'study4',
4: 'study5'},
'fuzzy_market': {0: '[Age: 18-67], [Country of Birth: A... | [
"try this:\ndata = [*df.pop('fuzzy_market').str.findall(r'([^:\\[]+): ([^\\]]+)').map(dict)]\nres = df.join(pd.DataFrame(data, index=df.index))\nprint(res)\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074440094_pandas_python.txt |
Q:
How to split a dataframe and select all possible pairs?
I have a dataframe that I want to separate in order to apply a certain function.
I have the fields df['beam'], df['track'], df['cycle'] and want to separate it by unique values of each of this three. Then, I want to apply this function (it works between two i... | How to split a dataframe and select all possible pairs? | I have a dataframe that I want to separate in order to apply a certain function.
I have the fields df['beam'], df['track'], df['cycle'] and want to separate it by unique values of each of this three. Then, I want to apply this function (it works between two individual dataframes) to each pair that meets that df['track'... | [
"I don't know how to mark the question as solved so I'll just repeat the solution here:\ndfsplit=df.groupby(['beam','track','cycle'])\nkeys=list(itertools.combinations(dfsplit.keys(),2))\nkeys=list(itertools.filterfalse(lambda k : k[0][1]==k[1][1], keys))\nfor k in keys:\n function(dfsplit[k[0]],dfsplit[k[1]])\n\... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074438954_dataframe_pandas_python.txt |
Q:
Categorisation/matching of stores
i want to write a python code to do the categorisation of store names(chemist,restaurent etc) automatically.
if the store name is Anand Medical store it should fall in chemist cat., if it is 7 General store it should fall in General store cat.
A:
I'm not sure what the question i... | Categorisation/matching of stores | i want to write a python code to do the categorisation of store names(chemist,restaurent etc) automatically.
if the store name is Anand Medical store it should fall in chemist cat., if it is 7 General store it should fall in General store cat.
| [
"I'm not sure what the question is, but if you are looking for a suggestion on how to achieve it then please find below my thought.\nIf you have a list of words that represent different store categories, you can create a dictionary with those words as keys and the corresponding store categories as values.\nWhen you... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074440160_python.txt |
Q:
Mallocing and Freeing in C, but passing the pointer through Python via ctypes
I would like to put a malloc a function in C. I would then like to call this function from Python 3.10 via ctypes.DLL. I then would like to free it.
However, I get a segmentation fault. Here's my very simple C code:
#include <stdlib.h>
... | Mallocing and Freeing in C, but passing the pointer through Python via ctypes | I would like to put a malloc a function in C. I would then like to call this function from Python 3.10 via ctypes.DLL. I then would like to free it.
However, I get a segmentation fault. Here's my very simple C code:
#include <stdlib.h>
struct QueueItem {
void *value;
struct QueueItem *next;
};
struct Queue {
... | [
"If you don't define the restype and argtypes for a function, the restype is assumed to be a C int (c_int), and the argument types are guessed at based on what you pass. The problem here is that the implicit restype of C int is (on a 64 bit system) half the width of a pointer, so the value returned by new_queue is ... | [
0
] | [] | [] | [
"c",
"ctypes",
"pointers",
"python"
] | stackoverflow_0074440165_c_ctypes_pointers_python.txt |
Q:
Split string by starting at one keyword and stopping at the word preceding another
I have a set of strings I want to loop through that are all different but can be broken up using the same keywords. This will extract substrings that all start and stop at the same words but will have different values in them. Take ... | Split string by starting at one keyword and stopping at the word preceding another | I have a set of strings I want to loop through that are all different but can be broken up using the same keywords. This will extract substrings that all start and stop at the same words but will have different values in them. Take the following string:
res = "But also the leap into electronic typesetting, remaining es... | [
"You can use a lookahead assertion:\nre.findall(r'\\bBut.*(?=\\stypesetting\\b)', res)\n\n"
] | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074440278_python_regex.txt |
Q:
How to visually animate Markov chains in Python?
I want to "visually" animate Markov chains like here : http://markov.yoriz.co.uk/ but using Python instead of html css and javascript.
I don't know if there is any library that makes this easy, till now I managed to make a visual representation of Markov chains usin... | How to visually animate Markov chains in Python? | I want to "visually" animate Markov chains like here : http://markov.yoriz.co.uk/ but using Python instead of html css and javascript.
I don't know if there is any library that makes this easy, till now I managed to make a visual representation of Markov chains using Networkx library like in the figure below, but could... | [
"You can do that by sampling from your Markov chain over a certain number of steps (100 in the code below) and modifying the color of the selected node at each step (see more here on how to change color of the nodes with graphviz).\nYou can then create a png file of your network for each step and use imageio to gen... | [
0
] | [] | [] | [
"animation",
"markov_chains",
"networkx",
"python",
"simulation"
] | stackoverflow_0062044102_animation_markov_chains_networkx_python_simulation.txt |
Q:
Failed to build pyarrow for streamlit installation
I am trying the command pip3 install streamlit on a virtual environment on my raspberry pi 4, but I got the following error. Could you help me, please?
Building wheels for collected packages: pyarrow
Building wheel for pyarrow (pyproject.toml): started
Buildin... | Failed to build pyarrow for streamlit installation | I am trying the command pip3 install streamlit on a virtual environment on my raspberry pi 4, but I got the following error. Could you help me, please?
Building wheels for collected packages: pyarrow
Building wheel for pyarrow (pyproject.toml): started
Building wheel for pyarrow (pyproject.toml): finished with stat... | [
"Use this command to explicity install pyarrow\npip install --extra-index-url https://pypi.fury.io/arrow-nightlies --prefer-binary --pre pyarrow\n\nand then try to install streamlit\nNote: This works for python version 3.11\n"
] | [
0
] | [] | [] | [
"pyarrow",
"python",
"streamlit"
] | stackoverflow_0072573760_pyarrow_python_streamlit.txt |
Q:
video streaming using customtkinter
How to video streaming using customtkinter library in class method form ?
i was troubling to configure how to that, i see many examples but i dont know how to implement this on my code
# code for video streaming
def camera(self):
ret, img = cap.read()
cv2image= cv2.cvtCo... | video streaming using customtkinter | How to video streaming using customtkinter library in class method form ?
i was troubling to configure how to that, i see many examples but i dont know how to implement this on my code
# code for video streaming
def camera(self):
ret, img = cap.read()
cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)
... | [
"The main issue is that you have used same name camera for a label and a function. Just rename the function to other name, for example streaming():\n...\nclass TimeIn(customtkinter.CTk):\n ...\n # code for video streaming\n def streaming(self):\n ret, img = cap.read()\n cv2image= cv2.cvtColo... | [
2,
1
] | [] | [] | [
"customtkinter",
"opencv",
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0074410884_customtkinter_opencv_python_python_imaging_library_tkinter.txt |
Q:
How to iterate through a loop to find highest value in a list? (python)
I am tasked with creating two functions one that creates a list of 10 random integers and the other is supposed to find the highest number in the list using a loop (without using the max option). I am having difficulty with the second function... | How to iterate through a loop to find highest value in a list? (python) | I am tasked with creating two functions one that creates a list of 10 random integers and the other is supposed to find the highest number in the list using a loop (without using the max option). I am having difficulty with the second function (getHighest). Nothing is being returned/printed and I am also not getting an... | [
"Your code is almost done. There are some ways to fix it:\nGet the n-th element from the list:\n scores[score]\n\nThis code probably works, but it's not the python way of doing things. Let's make some changes:\nrange(len(scores))\n\nThe range function takes at least one parameter: the stop value. If you pass just a... | [
0,
0
] | [] | [] | [
"function",
"list",
"loops",
"python"
] | stackoverflow_0074440152_function_list_loops_python.txt |
Q:
how do i check if an input is either a float or an integer?
print("hello")
mass_list=[]
volume_list=[]
x=0
while not x=="":
x=input("Enter Mass: ")
if x.isnumeric():
m=float(x)
mass_list.append(m)
while len(volume_list) < len(mass_list):
x=input("Enter volume: ")
if x.isnumeric():
... | how do i check if an input is either a float or an integer? | print("hello")
mass_list=[]
volume_list=[]
x=0
while not x=="":
x=input("Enter Mass: ")
if x.isnumeric():
m=float(x)
mass_list.append(m)
while len(volume_list) < len(mass_list):
x=input("Enter volume: ")
if x.isnumeric():
v=float(x)
volume_list.append(v)
print(mass_list)
... | [
"In Python it's recommended to use the EAFP principle - don't try to verify the input, just use it and let it fail if it's wrong. So instead of:\nx=input(\"Enter Mass: \")\nif x.isnumeric():\n m=float(x)\n mass_list.append(m)\n\nJust do:\nx=input(\"Enter Mass: \")\nm=float(x)\nmass_list.append(m)\n\nIf you n... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074440375_python.txt |
Q:
PyCharm Importing Error (chatterbot / Flask)
I'm currently learning to program a chatbot but I faced an import error while running the program.
here's the error I got:
I already installed the packages:
I have no idea why this error arose nor how to fix it, I hope you can help.
A:
Try to use flask version 1.0.0... | PyCharm Importing Error (chatterbot / Flask) | I'm currently learning to program a chatbot but I faced an import error while running the program.
here's the error I got:
I already installed the packages:
I have no idea why this error arose nor how to fix it, I hope you can help.
| [
"Try to use flask version 1.0.0\n"
] | [
0
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0058755230_pycharm_python.txt |
Q:
Django: Custom User Model with Autoincrementing Id
I am trying to use Django Authentication and I want to create a custom model for the user that has an autoincrementing integer as id. I know about uuid library, but I want the id to be an integer number, that is why I want to avoid it.
My code looks like:
from dja... | Django: Custom User Model with Autoincrementing Id | I am trying to use Django Authentication and I want to create a custom model for the user that has an autoincrementing integer as id. I know about uuid library, but I want the id to be an integer number, that is why I want to avoid it.
My code looks like:
from django.db import models
from django.contrib.auth.models imp... | [
"I tried to solve your requirement... using save method overriding\nModel code:\nclass CustomUserModel(AbstractBaseUser, PermissionsMixin):\n auto_id = models.PositiveBigIntegerField(unique=True)\n username = models.CharField(max_length=255, unique=True)\n email = models.EmailField(verbose_name=\"email add... | [
2
] | [] | [] | [
"django",
"django_authentication",
"django_users",
"python"
] | stackoverflow_0074437544_django_django_authentication_django_users_python.txt |
Q:
What does exactly "nonlocal" keyword do with a variable?
Here is an example code that I have made to try to understand the mechanics of "nonlocal" keyword.
`
# Outer fuction
def func1():
var1 = 2
print("---ID of var1 in func1---")
print(id(var1))
print(locals())
# Inner function
def func2():
nonlocal... | What does exactly "nonlocal" keyword do with a variable? | Here is an example code that I have made to try to understand the mechanics of "nonlocal" keyword.
`
# Outer fuction
def func1():
var1 = 2
print("---ID of var1 in func1---")
print(id(var1))
print(locals())
# Inner function
def func2():
nonlocal var1
var1 += 1
print("---ID of var1 in func2---")
... | [
"locals() is a very weird function that doesn't do what anyone would reasonably expect it to, with some bizarre undocumented quirks. This particular quirk happens to be documented, but it's still really weird. Generally, you shouldn't use locals() unless you really have no other choice.\nThe dict returned by locals... | [
1
] | [] | [] | [
"memory_management",
"namespaces",
"python",
"python_nonlocal",
"scope"
] | stackoverflow_0074440478_memory_management_namespaces_python_python_nonlocal_scope.txt |
Q:
how to access tag with css selector in selenium using descendant(>>)?
xxx, yyy is the things that i want to access with css selector in selenium
xxx=driver.find_element(By.CSS_SELECTOR,'#contents > div.tabWrap.pdtTabWrap.fixed > div.tabContents > section.tabCont.active >
div > div > div.prdDetailConWr... | how to access tag with css selector in selenium using descendant(>>)? | xxx, yyy is the things that i want to access with css selector in selenium
xxx=driver.find_element(By.CSS_SELECTOR,'#contents > div.tabWrap.pdtTabWrap.fixed > div.tabContents > section.tabCont.active >
div > div > div.prdDetailConWrap > div.prdType.prdType11 > div.imgWrap.imgCrop > img')
yyy=driver.find_el... | [
"Try using a space instead:\ndriver.find_element( By.CSS_SELECTOR,'#contents > div.tabWrap.pdtTabWrap.fixed > div.tabContents > section.tabCont.active img')\n\nYou can read more here:\nhttps://www.w3.org/TR/selectors/#descendant-combinators\n"
] | [
0
] | [] | [] | [
"descendant",
"python",
"selenium",
"web_crawler"
] | stackoverflow_0074440546_descendant_python_selenium_web_crawler.txt |
Q:
speed up pandas pd.to_csv
I am writing Dataframe to file using pandas. here is my snippet
df.to_csv(filename, sep=",")
it is taking 1 minute,20 seconds for 1.14 GB
is there any way to improve the performance?
| speed up pandas pd.to_csv | I am writing Dataframe to file using pandas. here is my snippet
df.to_csv(filename, sep=",")
it is taking 1 minute,20 seconds for 1.14 GB
is there any way to improve the performance?
| [] | [] | [
"This could significantly reduce the write time. Please try and feed back.\nstage.to_csv('output.csv.gz'\n , sep='|'\n , header=True\n , index=False\n , chunksize=100000\n , compression='gzip'\n , encoding='utf-8')\n\n"
] | [
-1
] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074440675_dataframe_pandas_python.txt |
Q:
Python Toggle a program on/off with key press
import keyboard
import time
start = 0
if keyboard.on_press("F7") and start == 0:
start = 1
if keyboard.on_press("F7") and start == 1:
start = 0
while start == 1:
keyboard.write("a")
time.sleep(1)
keyboard.send('enter')
print(start)
When I ru... | Python Toggle a program on/off with key press | import keyboard
import time
start = 0
if keyboard.on_press("F7") and start == 0:
start = 1
if keyboard.on_press("F7") and start == 1:
start = 0
while start == 1:
keyboard.write("a")
time.sleep(1)
keyboard.send('enter')
print(start)
When I run this, the process ends immediately. I am new to ... | [
"I am not familiar with keyboard input, but, at a first glance, this won't run as you would expect it to.\nWhat your program is doing, is setting start to 0. Then, that same second (or whatever), it checks whether you are pressing F7 and start == 0. If both conditions are true, it sets start to 1. Then it checks wh... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0068184231_python.txt |
Q:
find largest value on nested for loop for every element of the outer loop
Given two lists , I'm calculating a distance between words in a nested for loop:
from fuzzywuzzy import fuzz
l = ['mango','apple']
l2 = ['ola','john']
for i in l:
for j in l2:
print(i,j,fuzz.ratio(i,j))
mango ola 25
mango john... | find largest value on nested for loop for every element of the outer loop | Given two lists , I'm calculating a distance between words in a nested for loop:
from fuzzywuzzy import fuzz
l = ['mango','apple']
l2 = ['ola','john']
for i in l:
for j in l2:
print(i,j,fuzz.ratio(i,j))
mango ola 25
mango john 22
apple ola 25
apple john 0
I would like to find the maximum value for ever... | [
"The built-in max function allows to select a criterium to sort values (therefore specifying what should be considered maximum) using the keyword argument key. So, you can sort by the third item of each (i,j,fuzz.ratio(i,j)) generated in the inner loop:\nfor i in l:\n print(max([(i,j,fuzz.ratio(i,j)) for j in l2... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074440403_python.txt |
Q:
Python3 toggle script on key press stuck
The goal of this script is to make a switch and let the user toggle it ON and OFF with a key press, and when the switch is ON, the script should execute a loop that print a message in the terminal. In another words, The goal is to repeatedly print a message when the switch ... | Python3 toggle script on key press stuck | The goal of this script is to make a switch and let the user toggle it ON and OFF with a key press, and when the switch is ON, the script should execute a loop that print a message in the terminal. In another words, The goal is to repeatedly print a message when the switch is ON
Here is what i have tried:
import keyboa... | [
"you can put an if condition inside your loop to do a break at a specific key\nex:\nif keyboard.is_pressed(\"F5\") and start == 1:\n break\n\nthis would exit your infinite loop, although a more elegant code would work like this:\ndef check_start():\n global start\n if keyboard.is_pressed(\"F5\") and start ... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0061594593_python_python_3.x.txt |
Q:
TypeError: takes 0 positional arguments but 1 was given
Help me what am I making wrong here since am getting the below error,
TypeError: fizz_buzz() takes 0 positional arguments but 1 was given
class FizzBuzz:
def __init__(self, number_value):
self.number_value = number_value
def fizz_buzz():
... | TypeError: takes 0 positional arguments but 1 was given | Help me what am I making wrong here since am getting the below error,
TypeError: fizz_buzz() takes 0 positional arguments but 1 was given
class FizzBuzz:
def __init__(self, number_value):
self.number_value = number_value
def fizz_buzz():
if number_value % 3 == 0 and number_value % 5 == 0:
... | [
"this means you should have all functions inside a class with atleast one argument, \ndef fizz_buzz(self):\n\n",
"Make sure that when you are creating class methods you always have 1 argument called \"self\":\ndef fizz_buzz(self):\n if number_value % 3 == 0 and number_value % 5 == 0:\n print(\"FizzBuzz\... | [
11,
5,
4,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0060461651_python.txt |
Q:
Why do some features get a feature importance of 0 in lightGBM?
I have trained the following flaml autoML (I have specified the algo to be a lightGBM):
automl = AutoML()
automl.fit(
X_train,
y_train,
estimator_list=["lgbm"],
ta... | Why do some features get a feature importance of 0 in lightGBM? | I have trained the following flaml autoML (I have specified the algo to be a lightGBM):
automl = AutoML()
automl.fit(
X_train,
y_train,
estimator_list=["lgbm"],
task="classification",
metric="roc_auc",
... | [
"For LightGBM, every feature has a reported feature importance, even those that are not used by any splits in the model.\nConsider the following example in Python, using lightgbm==3.3.3.\nimport lightgbm as lgb\nfrom sklearn.datasets import make_regression\n\n# create a 3-feature dataset where only one feature is i... | [
1
] | [] | [] | [
"feature_selection",
"lightgbm",
"python"
] | stackoverflow_0074435217_feature_selection_lightgbm_python.txt |
Q:
Divide date range to specific week number from another DataFrame in pyspark
I have such a pyspark DataFrames:
df1:
+--------------------+----------+----------+----------+----------+----------+------+-----------------+--------+
| NAME | X_NAME | BEGIN | END | A| B| C| ... | Divide date range to specific week number from another DataFrame in pyspark | I have such a pyspark DataFrames:
df1:
+--------------------+----------+----------+----------+----------+----------+------+-----------------+--------+
| NAME | X_NAME | BEGIN | END | A| B| C| D| E|
+--------------------+----------+----------+----------+--... | [
"you can use string format time from datetime module to fetch the weeknumber in the format you needed.\nfrom datetime import date\n\n#this will provide the format you want\ndate.strftime(\"%YW%W\") \n\n",
"Use the datetime functions to find the year and week number and create a series to fill week number and year... | [
0,
0,
0
] | [] | [] | [
"dataframe",
"date",
"datetime",
"pyspark",
"python"
] | stackoverflow_0074430171_dataframe_date_datetime_pyspark_python.txt |
Q:
How to calculate Minus using groupby and by time series?
I have a df like this:
lst_1 = ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B']
lst_2 = [500, 600, 800, 900,700, 800,1000, 1200]
lst_3 = ['10/31/2022', '11/02/2022','11/07/2022', '11/14/2022', '10/31/2022', '11/02/2022','11/07/2022', '11/14/2022']
df1 = pd.DataFrame... | How to calculate Minus using groupby and by time series? | I have a df like this:
lst_1 = ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B']
lst_2 = [500, 600, 800, 900,700, 800,1000, 1200]
lst_3 = ['10/31/2022', '11/02/2022','11/07/2022', '11/14/2022', '10/31/2022', '11/02/2022','11/07/2022', '11/14/2022']
df1 = pd.DataFrame(list(zip(lst_1 , lst_2, lst_3)),
columns =['SKU... | [
"grouper = pd.PeriodIndex(df1['Date_Updated'], freq='w').to_timestamp().strftime('%m/%d/%Y')\ndf = (df1.groupby(['SKU', grouper])['Sum_Qty_Sold']\n .first().reset_index().sort_values('SKU').iloc[:, [0, -1, 1]])\ndf['Sum_Qty_Sold'] = df.groupby('SKU')['Sum_Qty_Sold'].shift(-1) - df['Sum_Qty_Sold']\ndf['Date_Upd... | [
2
] | [] | [] | [
"datetime",
"pandas",
"python"
] | stackoverflow_0074440624_datetime_pandas_python.txt |
Q:
How do I resolve "IndexError: tuple index out of range"?
I am trying to do a time series plot forecast in transformer.
The input size is (None, 30).
However, an error occurs here.
x = layers.MultiHeadAttention(
5 key_dim=1, num_heads=1, dropout=dropout
----> 6 )(inputs, inputs)
7 x = layers.Dropout(dro... | How do I resolve "IndexError: tuple index out of range"? | I am trying to do a time series plot forecast in transformer.
The input size is (None, 30).
However, an error occurs here.
x = layers.MultiHeadAttention(
5 key_dim=1, num_heads=1, dropout=dropout
----> 6 )(inputs, inputs)
7 x = layers.Dropout(dropout)(x)
8 x = layers.LayerNormalization(epsilon=1e-6)(x... | [
"Make the following changes,\nX_train = tf.expand_dims(X_train, -1) #change your input\ninput_shape = X_train.shape[1:] #input shape should change to (30,1)\nmodel_mlp = build_model(\n input_shape,\n head_size=256,\n num_heads=1,\n ff_dim=1,\n num_transformer_blocks=4,\n mlp_units=[128],\n mlp_... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074440662_keras_python_tensorflow.txt |
Q:
How can i compare an input integer value with the rows of a dataframe and return if they match
I used a for loop and compared it with the variable input, i got neither an output nor an error. can someone help
Please check the data frame here
l = []
for i in range(len(df)-1):
for j in range(i+1, len(df)):
... | How can i compare an input integer value with the rows of a dataframe and return if they match | I used a for loop and compared it with the variable input, i got neither an output nor an error. can someone help
Please check the data frame here
l = []
for i in range(len(df)-1):
for j in range(i+1, len(df)):
if df['rgb'].iloc[i] == df['rgb'].iloc[j]:
print(df['rgb'].iloc[i])
l.app... | [
"I think you're code is freezing waiting on input() as written.\nSo you want to return any row where the value you supply is in the column RGB?\nIf so, does this do what you want?\ndf_temp = df[df['rgb'] == '255 255 217 228']\nIf not, can you describe a bit better what you are trying to filter for (what \"z\" is in... | [
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074440707_dataframe_numpy_pandas_python_python_3.x.txt |
Q:
Possible to use more than one argument on __getitem__?
I am trying to use
__getitem__(self, x, y):
on my Matrix class, but it seems to me it doesn't work (I still don't know very well to use python).
I'm calling it like this:
print matrix[0,0]
Is it possible at all to use more than one argument? Thanks. Maybe I ... | Possible to use more than one argument on __getitem__? | I am trying to use
__getitem__(self, x, y):
on my Matrix class, but it seems to me it doesn't work (I still don't know very well to use python).
I'm calling it like this:
print matrix[0,0]
Is it possible at all to use more than one argument? Thanks. Maybe I can use only one argument but pass it as a tuple?
| [
"__getitem__ only accepts one argument (other than self), so you get passed a tuple.\nYou can do this:\nclass matrix:\n def __getitem__(self, pos):\n x,y = pos\n return \"fetching %s, %s\" % (x, y)\n\nm = matrix()\nprint m[1,2]\n\noutputs\nfetching 1, 2\n\nSee the documentation for object.__getitem... | [
82,
31,
5,
0
] | [
"I learned today that you can pass double index to your object that implements getitem, as the following snippet illustrates:\nclass MyClass:\n def __init__(self):\n self.data = [[1]]\n def __getitem__(self, index):\n return self.data[index]\n \nc = MyClass()\nprint(c[0][0])\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0001685389_python.txt |
Q:
How can I fix "Could not build wheels for scikit-image" error?
I am installing scikit-image , during the installation it throws wheel compilation error.
Platform :
Architecture: x64
Compiler : msvc
CPU baseline :
Requested : 'min'
Enabled : none
Flags : none
Extra c... | How can I fix "Could not build wheels for scikit-image" error? | I am installing scikit-image , during the installation it throws wheel compilation error.
Platform :
Architecture: x64
Compiler : msvc
CPU baseline :
Requested : 'min'
Enabled : none
Flags : none
Extra checks: none
CPU dispatch :
Requested : 'max -xop -fma4'
... | [
"Download the appropriate file from https://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-image\nAnd using pip, install the file as: pip install *.whl\nFor me worked pip install scikit_image-0.19.3-cp311-cp311-win_amd64.whl --user in Python 3.11\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"scikit_image"
] | stackoverflow_0070182401_pip_python_scikit_image.txt |
Q:
how to use rasa as library to train model and for testing
I want to use rasa as library instead of framework and using resa as library I want to train model as we train in framework using config,nlu and stories.
A:
import rasa
config = 'confing.yml'
training_files = './data/'
domain = 'domain.yml'
output = './m... | how to use rasa as library to train model and for testing | I want to use rasa as library instead of framework and using resa as library I want to train model as we train in framework using config,nlu and stories.
| [
"import rasa\n\nconfig = 'confing.yml'\ntraining_files = './data/'\ndomain = 'domain.yml'\noutput = './models/'\n\nrasa.train(domain, config, [training_files], output, fixed_model_name='model_name')\n\nthanks to : How to reduce model loading time in rasa 3 python\n"
] | [
0
] | [] | [] | [
"deep_learning",
"nlp",
"python",
"rasa"
] | stackoverflow_0074440704_deep_learning_nlp_python_rasa.txt |
Q:
Why is python returning ValueError: list.remove(x): x not in list when the value is in the list?
I am making a Hangman game for practice. The game is set so that the computer randomly chooses a word from a list I have provided and returns the word in list form. A function then compares user input with the list and... | Why is python returning ValueError: list.remove(x): x not in list when the value is in the list? | I am making a Hangman game for practice. The game is set so that the computer randomly chooses a word from a list I have provided and returns the word in list form. A function then compares user input with the list and checks if user_input in list. If True, then it removes the input from the word to prevent the user to... | [
"Some problems here.\n\nchoose_word() at the beginning of the while loop does nothing: the assignment to choice inside this function modifies only a local variable, not the global environment.\nyou check_input on original_word, but remove from choice: it is going to fail randomly.\ncheck_input returns nothing (i.e.... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074437459_python.txt |
Q:
Normalizing pandas DataFrame with multiindex
I need to normalize data by level 1 in multi-index, given
import pandas as pd
df = pd.DataFrame(np.arange(12).reshape(4,3), index=[["a","a","b","b"],[1,2,1,2]],
columns=["x","y","z"])
so that df is
x y z
a 1 0 1 2
2 3 4 5
b 1 6 ... | Normalizing pandas DataFrame with multiindex | I need to normalize data by level 1 in multi-index, given
import pandas as pd
df = pd.DataFrame(np.arange(12).reshape(4,3), index=[["a","a","b","b"],[1,2,1,2]],
columns=["x","y","z"])
so that df is
x y z
a 1 0 1 2
2 3 4 5
b 1 6 7 8
2 9 10 11
I need to normalize every c... | [
"One option is with a groupby:\ndf/df.groupby(level=0).transform('sum')\nOut[87]: \n x y z\na 1 0.0 0.200000 0.285714\n 2 1.0 0.800000 0.714286\nb 1 0.4 0.411765 0.421053\n 2 0.6 0.588235 0.578947\n\n"
] | [
1
] | [] | [] | [
"multi_index",
"pandas",
"python"
] | stackoverflow_0074440638_multi_index_pandas_python.txt |
Q:
I think ive setup vscode the wrong way or not able to find out a few root reasons for a few errors
why is this error there in the terminal?
i was trying to run a simple file after saving it yet it wasnt able to locate the file in the directory as mentioned, hence was giving the following error.
A:
The simplest w... | I think ive setup vscode the wrong way or not able to find out a few root reasons for a few errors |
why is this error there in the terminal?
i was trying to run a simple file after saving it yet it wasnt able to locate the file in the directory as mentioned, hence was giving the following error.
| [
"The simplest way to fix this is to remove : at the end of second line. It is a typo which kind of destroys rest of the code.\n",
"Delete your current terminal, or Ctrl+Z and press Enter to exit the current python interactive mode.\nWhen your terminal looks like this you can use the play button to run the code.\n... | [
0,
0
] | [] | [] | [
"error_handling",
"python",
"python_3.x",
"visual_studio_code"
] | stackoverflow_0074427847_error_handling_python_python_3.x_visual_studio_code.txt |
Q:
get the named index in nlargest operation in pandas
Given the following df:
word1 word2 distance
mango ola 25
mango johnkoo 33
apple ola 25
apple johnkoo 0
I find the two largest values of distance per group in the following way:
res = df.groupby(['word1... | get the named index in nlargest operation in pandas | Given the following df:
word1 word2 distance
mango ola 25
mango johnkoo 33
apple ola 25
apple johnkoo 0
I find the two largest values of distance per group in the following way:
res = df.groupby(['word1'])['distance'].nlargest(2)
print(res)
word1
apple 2... | [
"You can try with\n(df.sort_values('distance',ascending=False)\n .groupby('word1').head(2).set_index(['word1','word2'])['distance'])\nOut[166]: \nword1 word2 \nmango johnkoo 33\n ola 25\napple ola 25\n johnkoo 0\nName: distance, dtype: int64\n\n",
"Use the positions in the s... | [
3,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074440466_pandas_python.txt |
Q:
ValueError: Columns must be same length as key in pandas
i have df below
Cost,Reve
0,3
4,0
0,0
10,10
4,8
len(df['Cost']) = 300
len(df['Reve']) = 300
I need to divide df['Cost'] / df['Reve']
Below is my code
df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric)
I got the error ... | ValueError: Columns must be same length as key in pandas | i have df below
Cost,Reve
0,3
4,0
0,0
10,10
4,8
len(df['Cost']) = 300
len(df['Reve']) = 300
I need to divide df['Cost'] / df['Reve']
Below is my code
df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric)
I got the error ValueError: Columns must be same length as key
df['C/R'] = df... | [
"Problem is duplicated columns names, verify:\n#generate duplicates\ndf = pd.concat([df, df], axis=1)\nprint (df)\n Cost Reve Cost Reve\n0 0 3 0 3\n1 4 0 4 0\n2 0 0 0 0\n3 10 10 10 10\n4 4 8 4 8\n\ndf[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric... | [
9,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0061650474_pandas_python.txt |
Q:
tkinter - how to run a conditional statement on button press (user enters age and height), output sent to textbox
Relatively new to tkinter so please be kind. I'm playing around with an exercise that gets a user to input their age and height. Based on the conditional it will output whether they can ride that parti... | tkinter - how to run a conditional statement on button press (user enters age and height), output sent to textbox | Relatively new to tkinter so please be kind. I'm playing around with an exercise that gets a user to input their age and height. Based on the conditional it will output whether they can ride that particular attraction. The code below is not finished. I know I need to create a function for button press to run the IF sta... | [
"You need to call .get() on the Entry widgets to get the input values and convert them into integers. Also you need to do the checking inside a function which is triggered by the submit button:\nfrom tkinter import *\n\nwindow = Tk()\nwindow.title(\"Rollercoaster\")\n\nl0 = Label(window, text = \"Can you ride the ... | [
0
] | [] | [] | [
"conditional_statements",
"function",
"if_statement",
"python",
"tkinter"
] | stackoverflow_0074430385_conditional_statements_function_if_statement_python_tkinter.txt |
Q:
Jinja/flask, how to show one photo at a time from a list of photos?
The idea is to have a page where you rate a photo of a dog, and once rating is submitted, the next photo shows up. Not unlike hot or not, for dogs... I thought this part would be simple and maybe I just need to take a break and an answer will come... | Jinja/flask, how to show one photo at a time from a list of photos? | The idea is to have a page where you rate a photo of a dog, and once rating is submitted, the next photo shows up. Not unlike hot or not, for dogs... I thought this part would be simple and maybe I just need to take a break and an answer will come to me.
So far i have implemented registering, logging in, a means to upl... | [
"There are some clues for you...\nYou may check the article first\nFlask SQLalchemy - many to many - show photo with all tags (or blog with all posts etc)\nAnd try the \"jinjagrid\" to batch processing as your html template. To be more clean and controllable.\n<section class=\"section\">\n <div class=\"container... | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074439427_flask_python.txt |
Q:
Mapping tensor in pytorch
I have the following two tensors:
img is a RGB image of shape (224,224,3)
uvs is a tensor with same spacial size e.g. (224, 224, 2) that maps to coordinates (x,y). In other words it provides (x,y) coordinates for every pixel of the input image.
I want to create now a new output image te... | Mapping tensor in pytorch | I have the following two tensors:
img is a RGB image of shape (224,224,3)
uvs is a tensor with same spacial size e.g. (224, 224, 2) that maps to coordinates (x,y). In other words it provides (x,y) coordinates for every pixel of the input image.
I want to create now a new output image tensor that contains on index (x,... | [
"Try with:\nout = img[idx[...,0], idx[...,1]]\n\n",
"I was able to solve it (with the help of Quang Hoang answer)\nout[idx[...,0], idx[...,1]] = img\n\n",
"What you need is torch.nn.functional.grid_sample(). You can do something like this:\nwidth, height, channels = (224, 224, 3)\n\n# Note that the image is cha... | [
1,
1,
0
] | [] | [] | [
"numpy",
"python",
"pytorch"
] | stackoverflow_0066693083_numpy_python_pytorch.txt |
Q:
Find the column name which has the maximum value for each row
I have a DataFrame like this one:
Communications and Search Business General Lifestyle
0 0.745763 0.050847 0.118644 0.084746
0 0.333333 0.000000 0.583333 0.083333
0 0.617021 0.042553 0.297872 0.042553
0 0.435897 ... | Find the column name which has the maximum value for each row | I have a DataFrame like this one:
Communications and Search Business General Lifestyle
0 0.745763 0.050847 0.118644 0.084746
0 0.333333 0.000000 0.583333 0.083333
0 0.617021 0.042553 0.297872 0.042553
0 0.435897 0.000000 0.410256 0.153846
0 0.358974 0.076923 0.41... | [
"You can use idxmax with axis=1 to find the column with the greatest value on each row:\n>>> df.idxmax(axis=1)\n0 Communications\n1 Business\n2 Communications\n3 Communications\n4 Business\ndtype: object\n\nTo create the new column 'Max', use df['Max'] = df.idxmax(axis=1).\nTo find the ro... | [
278,
50,
14,
0,
0
] | [] | [] | [
"dataframe",
"max",
"pandas",
"python"
] | stackoverflow_0029919306_dataframe_max_pandas_python.txt |
Q:
How to specify edge style(solid, dotted, dashed) when using draw_circular function in networkx?
How to specify edge style(solid, dotted, dashed) when using draw_circular function in networkx? I know I can specify edge color using edge_color attribute, is there a similar one like "edge_style"?
A:
the keyword 'sty... | How to specify edge style(solid, dotted, dashed) when using draw_circular function in networkx? | How to specify edge style(solid, dotted, dashed) when using draw_circular function in networkx? I know I can specify edge color using edge_color attribute, is there a similar one like "edge_style"?
| [
"the keyword 'style' controls the edge_style you can use '-' for solid or '--' for dashed\nnx.draw_networkx( XXXXXXXX, style='--')\n\n",
"you can use style parameter in draw_networkx() function as below:\nnx.draw_networkx(G, pos=None, style='-')\n\nEdge line style e.g.: ‘-‘, ‘–’, ‘-.’, ‘:’ or words like ‘solid’ ... | [
2,
0,
0
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0060436850_networkx_python.txt |
Q:
pairwise(1 to 1) multiplication of columns to create a new column
I have a dataframe as such:
Col1 Col2 Col3.... Col64 Col1 Volume Col2 Volume....Col64 Volume.... Col1 Value Col2 Value...Col 64 Value
2 3 4 5 5 7 9 3 5
3 4 5 11 ... | pairwise(1 to 1) multiplication of columns to create a new column | I have a dataframe as such:
Col1 Col2 Col3.... Col64 Col1 Volume Col2 Volume....Col64 Volume.... Col1 Value Col2 Value...Col 64 Value
2 3 4 5 5 7 9 3 5
3 4 5 11 8 6 5 6 5
5 3 ... | [
"Use DataFrame.filter for get all columns with Volume and Value with $ for end of string, remove substrings and then filter df by columns from df1, multiple and divide columns with DataFrame.add_suffix, replace missing columns 0 and append to original DataFrame:\ndf1 = df.filter(regex='Volume$').rename(columns=lamb... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074441159_pandas_python.txt |
Q:
How do I print elements of _VariantDataset?
I'm working on formatting data for LSTM model.
Here's what I'm doing:
aa=pd.DataFrame()
aa["a"]=range(30)
aa["b"]=range(30,60)
aa["c"]=range(60,90)
bb=pd.DataFrame()
bb["r"]=range(90,120)
all=tf.data.Dataset.zip((
tf.data.Dataset.from_tensor_slices(aa.values),
... | How do I print elements of _VariantDataset? | I'm working on formatting data for LSTM model.
Here's what I'm doing:
aa=pd.DataFrame()
aa["a"]=range(30)
aa["b"]=range(30,60)
aa["c"]=range(60,90)
bb=pd.DataFrame()
bb["r"]=range(90,120)
all=tf.data.Dataset.zip((
tf.data.Dataset.from_tensor_slices(aa.values),
tf.data.Dataset.from_tensor_slices(bb.values)))
... | [
"You can use Dataset.flat_map, to flatten a dataset of windows into a single dataset.\nds = all.batch(history_len, drop_remainder=True).window(batch_size, shift=1)\nds = ds.flat_map(lambda x, y: tf.data.Dataset.zip((x.batch(batch_size), y.batch(batch_size))))\n\nfor i,j in ds:\n print(i)\n\ntf.Tensor(\n[[[ 0 3... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow",
"tensorflow_datasets"
] | stackoverflow_0074438455_keras_python_tensorflow_tensorflow_datasets.txt |
Q:
Change the 3rd value from a dictionary
I have a dictionary that looks like this:
dict = {id: ["gavin", "gavin123@email.com", age, 55, [111, 222, 333]]}
There are more keys but that's not important. I want to be able to change the age value to be a number instead of age so the new dictionary would look like this
d... | Change the 3rd value from a dictionary | I have a dictionary that looks like this:
dict = {id: ["gavin", "gavin123@email.com", age, 55, [111, 222, 333]]}
There are more keys but that's not important. I want to be able to change the age value to be a number instead of age so the new dictionary would look like this
dict = {id: ["gavin", "gavin123@email.com", 2... | [
"In your particular case\ndict[id][2] = 20\n\nChange in yor dict key from id to \"id\"\ndict[\"id\"][2] = 20\n\nNothing wrong but: id is builtins def id(__obj: object) -> int\nReturn the identity of an object.\nThis is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory ... | [
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074423972_dictionary_python.txt |
Q:
os.startfile() doesn't work after compiling python script with pyinstaller
I've made selfdestruct function that create a batch file that deletes the executable. It works when running the python file and the batch file opens normally. But after compiling it to an exe using pyinstaller it doesn't open.
I tried this
... | os.startfile() doesn't work after compiling python script with pyinstaller | I've made selfdestruct function that create a batch file that deletes the executable. It works when running the python file and the batch file opens normally. But after compiling it to an exe using pyinstaller it doesn't open.
I tried this
import os, sys
batchFilePath = 'C:\\Users\\Admin\\Desktop\\selfDelete.bat'
patho... | [
"Use sys.executable when targeting the executable. However your should note that when running the code as a python script sys.executable points to python.exe. So running your code as a python script would delete your python executable.\nAs such, I suggest testing to make sure that the code is being run from the com... | [
0
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0074415706_pyinstaller_python.txt |
Q:
Remove newline at the end of a file in python
I'm modifying a file with python that may already contain newlines like the following :
#comment
something
#new comment
something else
My code appends some lines to this file, I'm also writing the code that will remove what I added (ideally also working if other modi... | Remove newline at the end of a file in python | I'm modifying a file with python that may already contain newlines like the following :
#comment
something
#new comment
something else
My code appends some lines to this file, I'm also writing the code that will remove what I added (ideally also working if other modifications occurred in the file).
Currently, I end u... | [
"use str.rstrip() method:\nmy_file = open(\"text.txt\", \"r+\")\ncontent = my_file.read()\ncontent = content.rstrip('\\n')\nmy_file.seek(0)\n\nmy_file.write(content)\nmy_file.truncate()\nmy_file.close()\n\n",
"I needed a way to remove newline at eof without having to read the whole file into memory. The code bel... | [
3,
0
] | [] | [] | [
"newline",
"python"
] | stackoverflow_0070233834_newline_python.txt |
Q:
HoW to check VIF SCORE
enter image description here
I wANTt to read each column one by one and check its vif score with others BUT THIS ERROR POPS UP
A:
IndexError simple says that the index is out of range. its not in the array. let me give an example
array = [1, 2, 3] # Create a Array with 3 Elements
# Output... | HoW to check VIF SCORE | enter image description here
I wANTt to read each column one by one and check its vif score with others BUT THIS ERROR POPS UP
| [
"IndexError simple says that the index is out of range. its not in the array. let me give an example\narray = [1, 2, 3] # Create a Array with 3 Elements\n# Outputs the IndexError since the 4th element doesn't exist\nelement = array[3] # (Keep In Mind We Also Start Counting on 0)\n\nanother example can be for a dic... | [
0
] | [] | [] | [
"pandas",
"python",
"valueerror"
] | stackoverflow_0074441061_pandas_python_valueerror.txt |
Q:
How Iterate each element row and compare with another elements in row
I have to fetch the values from CSV within my local machine and iterate each element and compare them with each element of another row.
My CSV is stored in my Local C drive and read the value, now I need help to iterate each element from source... | How Iterate each element row and compare with another elements in row | I have to fetch the values from CSV within my local machine and iterate each element and compare them with each element of another row.
My CSV is stored in my Local C drive and read the value, now I need help to iterate each element from source and target.
import csv
with open('C:\\Users\\user\\Desktop\\test_readwrite... | [
"I am pretty sure this could be marked as a duplicate.\nNevertheless, using pandas should make it easier to compare.\nimport pandas as pd\n\ndf = pd.read_csv('data.csv')\n\n# Compare column 1 and column 2\ndef compare(x, y):\n # Your condition, return true or false\n # I am using equality\n return x == y\n... | [
0
] | [] | [] | [
"opencsv",
"python",
"sift"
] | stackoverflow_0074441284_opencsv_python_sift.txt |
Q:
input depth must be evenly divisible by filter depth: 1 vs 3 [[{{node model/conv1_conv/Conv2D}}]]
actually I have the first experience about computer vision project and run my code ,and get this error .in fact I wrote one code for color_mode='rgb' and the other for color_mode='grayescale'... when I run the code fo... | input depth must be evenly divisible by filter depth: 1 vs 3 [[{{node model/conv1_conv/Conv2D}}]] | actually I have the first experience about computer vision project and run my code ,and get this error .in fact I wrote one code for color_mode='rgb' and the other for color_mode='grayescale'... when I run the code for RGB is ok but for grayscale, I got this error.
input depth must be evenly divisible by filter depth: ... | [
"it is solved.instead of use color_mode='grayescale', keep it in RGB and add this function to pass it as\n preprocessing_function \ndef gray_to_rgb(img):\n x=np.dot(img[...,:3], [0.2989, 0.5870, 0.1140])\n mychannel=np.repeat(x[:, :, np.newaxis], 3, axis=2)\n return mychannel\n\n",
"I had the same issue. I ... | [
2,
0
] | [] | [] | [
"computer_vision",
"deep_learning",
"python"
] | stackoverflow_0061407465_computer_vision_deep_learning_python.txt |
Q:
SELECT option from dropdown using Selenium Python
been dealing with a countries dropdown using Selenium Python;
here is the Div tag of the drop-down menu:
<div cdk-overlay-origin="" class="mat-select-trigger ng-tns-c95-29"><div class="mat-select-value ng-tns-c95-29" id="mat-select-value-1"><span class="mat-select-... | SELECT option from dropdown using Selenium Python | been dealing with a countries dropdown using Selenium Python;
here is the Div tag of the drop-down menu:
<div cdk-overlay-origin="" class="mat-select-trigger ng-tns-c95-29"><div class="mat-select-value ng-tns-c95-29" id="mat-select-value-1"><span class="mat-select-placeholder mat-select-min-line ng-tns-c95-29 ng-star-i... | [
"You can use the selenium's Select() class only for html <select> tags. But this dropdown is implemented with <div>, so you can handle it just like html elements.\nFirst you need to click the dropdown to expand the options and then click the option you need:\nWebDriverWait(browser, 10).until(EC.presence_of_element_... | [
1
] | [] | [] | [
"automation",
"python",
"selenium",
"system"
] | stackoverflow_0074437900_automation_python_selenium_system.txt |
Q:
Can't import dll module in Python
I've been stressin for a few days trying to compile a modified version of libuvc on windows and now that I've finally done it, I can't seem to load it on Python. This lib that I've already compiled and successfully imported using the same version of Python on Linux machines, doesn... | Can't import dll module in Python | I've been stressin for a few days trying to compile a modified version of libuvc on windows and now that I've finally done it, I can't seem to load it on Python. This lib that I've already compiled and successfully imported using the same version of Python on Linux machines, doesn't like w10 at all.
System
win 10 64 ... | [
"Starting with Python 3.8, the .dll search mechanism has changed (Win specific).\nAccording to [Python.Docs]: os.add_dll_directory(path) (emphasis is mine):\n\nAdd a path to the DLL search path.\nThis search path is used when resolving dependencies for imported extension modules (the module itself is resolved throu... | [
20,
18,
2,
1
] | [
"Just \"Visual C++ Redistributable Package per Visual Studio 2013\". The problem will be solved.\n",
"You can specify the path to the library\nimport snap7\nimport struct\nfrom snap7.common import Snap7Library\nfrom snap7.util import *\n\n# If you are using a different location for the library\nSnap7Library(lib_l... | [
-1,
-2
] | [
"ctypes",
"python",
"uvc",
"winapi",
"windows"
] | stackoverflow_0059330863_ctypes_python_uvc_winapi_windows.txt |
Q:
How to reorganize scraped data from messed tables with python?
I'm trying to scrap data and reorganize it in a df. The problem is to select the information in the tables, since it is not a perfect table such as in the wikipedia models I trainned.
The information in this site should correspond as a row in the final... | How to reorganize scraped data from messed tables with python? | I'm trying to scrap data and reorganize it in a df. The problem is to select the information in the tables, since it is not a perfect table such as in the wikipedia models I trainned.
The information in this site should correspond as a row in the final product. The final result should be something like the organization... | [
"You have to iterate the second table and prepand all info from first on to the data - Choosed this solution, cause it is not clear if there can be multiple documents from same type, so it would not make sense to have something like link [typeA]1, link[typeA]2, ...:\nwalrus operator is a new syntax that is only ava... | [
1
] | [] | [] | [
"beautifulsoup",
"dataframe",
"html",
"python",
"web_scraping"
] | stackoverflow_0074441024_beautifulsoup_dataframe_html_python_web_scraping.txt |
Q:
How to extract user account name and video id from a shortened tiktok URL?
I'm trying to get the URL of a tiktok video from a shortened URL in order to extract the @username of the poster and the video id of the post. Some examples of shortened URL's I've come across seem to be shared URL's on Facebook/Twitter in ... | How to extract user account name and video id from a shortened tiktok URL? | I'm trying to get the URL of a tiktok video from a shortened URL in order to extract the @username of the poster and the video id of the post. Some examples of shortened URL's I've come across seem to be shared URL's on Facebook/Twitter in the form of "m.tiktok.com" or more specifically, "https://vm.tiktok.com/pF6GGf/"... | [
"TikTok might be not redirecting you the right URL because it is detecting your User-Agent. If you update your headers with some 'browser-like' User-Agent, it should work.\nHere's how you can solve your problem.\nimport re\nimport requests\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)... | [
6,
0
] | [] | [] | [
"python",
"url_shortener",
"web_scraping"
] | stackoverflow_0062634579_python_url_shortener_web_scraping.txt |
Q:
Having an issue seeing the heat signature on the map using HeatMapWithTime
I'm not able to see my data on the map when I run the following script. I can see the map, the temporal slider is present at the bottom and scrolls through the dates I provided, however, I do not see a heat signature at any of the location... | Having an issue seeing the heat signature on the map using HeatMapWithTime | I'm not able to see my data on the map when I run the following script. I can see the map, the temporal slider is present at the bottom and scrolls through the dates I provided, however, I do not see a heat signature at any of the locations. Is there something I'm leaving off of this?
This is the table I'm working wi... | [
"Since there is no data presented, I created a graph using sample data. The time period is 30 days, and there are 30 latitude and longitude locations in date units. That is the data for the heatmap, and it is a multiple list. I now have 30 latitude/longitude and heatmap values ready for one day in the date slider. ... | [
1,
0
] | [] | [] | [
"cartodb",
"folium",
"heatmap",
"python",
"time"
] | stackoverflow_0074383936_cartodb_folium_heatmap_python_time.txt |
Q:
Intro to Python: How to ask the user if they want to repeat the for loop?
I need help figuring out how to ask the user if they would like to repeat the program. Any help is much appreciated. I am relatively new to Python and it would be great to receive some advice!
X = int(input("How many numbers would you like t... | Intro to Python: How to ask the user if they want to repeat the for loop? | I need help figuring out how to ask the user if they would like to repeat the program. Any help is much appreciated. I am relatively new to Python and it would be great to receive some advice!
X = int(input("How many numbers would you like to enter? "))
Sum = 0
sumNeg = 0
sumPos = 0
for i in range(0,X,1):
number =... | [
"Ask the user for input at the end of the loop to continue or not. If the user doesn't want to continue, use a break statement to break out of the loop.\nhttps://www.simplilearn.com/tutorials/python-tutorial/break-in-python#:~:text='Break'%20in%20Python%20is%20a,condition%20triggers%20the%20loop's%20termination.\n"... | [
1,
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074441179_loops_python.txt |
Q:
Python Selenium Internet Explorer scripts don't work
If I make a simple script like this:
from selenium import webdriver
from selenium.webdriver.ie.service import Service
import os
from pathlib import Path
path = Path().absolute()
path = os.path.join(path, 'IEDriverServer')
driver = webdriver.Ie(executable_path=p... | Python Selenium Internet Explorer scripts don't work | If I make a simple script like this:
from selenium import webdriver
from selenium.webdriver.ie.service import Service
import os
from pathlib import Path
path = Path().absolute()
path = os.path.join(path, 'IEDriverServer')
driver = webdriver.Ie(executable_path=path)
driver.get('https://www.google.com/')
print("ANYTHING... | [
"If you want to automate Edge IE mode with IEDriver, you need to:\n\nDefine InternetExplorerOptions with additional properties that point to the Microsoft Edge browser.\nStart an instance of InternetExplorerDriver and pass it InternetExplorerOptions. IEDriver launches Microsoft Edge and then loads your web content ... | [
0
] | [] | [] | [
"internet_explorer",
"python",
"selenium"
] | stackoverflow_0074435275_internet_explorer_python_selenium.txt |
Q:
Numpy: how I can determine if all elements of numpy array are equal to a number
I need to know if all the elements of an array of numpy are equal to a number
It would be like:
numbers = np.zeros(5) # array[0,0,0,0,0]
print numbers.allEqual(0) # return True because all elements are 0
I can make an algorithm but, t... | Numpy: how I can determine if all elements of numpy array are equal to a number | I need to know if all the elements of an array of numpy are equal to a number
It would be like:
numbers = np.zeros(5) # array[0,0,0,0,0]
print numbers.allEqual(0) # return True because all elements are 0
I can make an algorithm but, there is some method implemented in numpy library?
| [
"You can break that down into np.all(), which takes a boolean array and checks it's all True, and an equality comparison:\nnp.all(numbers == 0)\n# or equivalently\n(numbers == 0).all()\n\n",
"If you want to compare floats, use np.isclose instead:\nnp.all(np.isclose(numbers, numbers[0]))\n\n",
"np.array_equal() ... | [
28,
11,
1,
0
] | [
"Are numpy methods necessary? If all the elements are equal to a number, then all the elements are the same. You could do the following, which takes advantage of short circuiting.\nnumbers[0] == 0 and len(set(numbers)) == 1 \n\nThis way is faster than using np.all()\n"
] | [
-1
] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0040094938_arrays_numpy_python.txt |
Q:
How to create a column based on the min date of multiple columns?
print (df)
Event1 Event2 Event3
0 7/27/2014 NaN NaN
1 3/5/2016 NaN 2/1/2013
2 5/13/2017 5/10/2013 NaN
3 NaN NaN 4/28/2014
4 NaN 5/12/2013 3/6/2016
5 NaN NaN ... | How to create a column based on the min date of multiple columns? |
print (df)
Event1 Event2 Event3
0 7/27/2014 NaN NaN
1 3/5/2016 NaN 2/1/2013
2 5/13/2017 5/10/2013 NaN
3 NaN NaN 4/28/2014
4 NaN 5/12/2013 3/6/2016
5 NaN NaN NaN
Hi all,
I have 3 columns in my pandas dataframe, I want to cre... | [
"Filter columns with Event with DataFrame.filter, convert to datetimes and get minimal values, last for original format use Series.dt.strftime:\ndf['new'] = (df.filter(like='Event')\n .apply(pd.to_datetime)\n .min(axis=1)\n .dt.strftime('%m/%d/%Y'))\nprint (df)\n Event... | [
3
] | [] | [] | [
"min",
"nan",
"pandas",
"python"
] | stackoverflow_0074441539_min_nan_pandas_python.txt |
Q:
netplan not working after change default python
in ubuntu 18.04, when i change default python from python 3.6 to other version by this command:
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1
or when i ... | netplan not working after change default python | in ubuntu 18.04, when i change default python from python 3.6 to other version by this command:
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1
or when i remove python 3.6 and install other version netplan a... | [
"I faced the same issue before with vagrant. If you use update-alternatives to make python3 alias points to another version of Python, vagrant will not work. You cannot use update-alternatives to change the alias of Python3.\n",
"For some reason I lost my python configuration after an update made by my ubuntu ser... | [
3,
1,
0
] | [] | [] | [
"netplan",
"python",
"ubuntu"
] | stackoverflow_0065558712_netplan_python_ubuntu.txt |
Q:
Fit fixed rectangle to set of points
i was wondering if someone every tried to fit a rectangle with a fixed size to a given set of points.
Imagine you have a set of points which is unsorted and not always showing a full hull of a rectangle. The image below should demonstrate the problem:
The set of points can var... | Fit fixed rectangle to set of points | i was wondering if someone every tried to fit a rectangle with a fixed size to a given set of points.
Imagine you have a set of points which is unsorted and not always showing a full hull of a rectangle. The image below should demonstrate the problem:
The set of points can vary and points could be missing.
I would lik... | [
"Just an outline of the solution:\n\nThe height and width of your rectangle is fixed, so you can define it with three parameters (x0, y0, theta): say the lower left corner and rotation.\nUse a distance function like pnt2line given here http://www.fundza.com/vectors/point2line/index.html\nNow write a wrapper functio... | [
1,
0,
0
] | [
"I couldn't find it so wrote a code myself. You can fit it using the least square rectangles.\nRefer to the result\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport cv2\n\nimport matplotlib.pyplot as plt\n\ndef plot_graph(X,Y, slopes,constants):\n plt.plot(X,Y,\"go\")\n \n def abline(s... | [
-1
] | [
"computational_geometry",
"curve_fitting",
"least_squares",
"math",
"python"
] | stackoverflow_0038260549_computational_geometry_curve_fitting_least_squares_math_python.txt |
Q:
Extracting values in a timeseries data and calculate the tie duration
Problem statement:
There are multiple instances of charging and discharging for each vehicle column_name= 'soc', from this column get two new df (ref Required output) get minimum SOC, maximum SOC for charging cycle each vehicle and similarly get... | Extracting values in a timeseries data and calculate the tie duration | Problem statement:
There are multiple instances of charging and discharging for each vehicle column_name= 'soc', from this column get two new df (ref Required output) get minimum SOC, maximum SOC for charging cycle each vehicle and similarly get min SoC and max SoC for every discharge cycle and time duration(discharge... | [
"Problem statement:\nThere are multiple instances of charging and discharging for each vehicle Column_name='soc',from this column get a two new df(Ref- Required output) where minimum SOC, maximum SOC for a particular vehicle where the status= Charging .Similarly fetch min SOC and max SOC and time duration(Discharge... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074438854_pandas_python.txt |
Q:
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.help' raised an error: TypeError: object NoneType can't be used in 'await' expression
I am trying to make an custom help command with discord.py but I can't get past this one problem which I've been trying to get rid of for while now, but no luck.
Heres ... | discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.help' raised an error: TypeError: object NoneType can't be used in 'await' expression | I am trying to make an custom help command with discord.py but I can't get past this one problem which I've been trying to get rid of for while now, but no luck.
Heres the code:
import discord
from discord.ext import commands
class MyHelpCommand(commands.HelpCommand):
async def send_bot_help(self, mapping):
... | [
"async function u are can using in @commands or @bot function\nTrue code:\n@commands.slash_command(name='help', description='Sending bot`s help')\n#its example, u can use @commands.command(alias='help')\n#slash command are using only in disnake or other library\nasync def help(inter):\n#or async def help(ctx), if u... | [
0
] | [] | [] | [
"discord.py",
"python",
"python_asyncio",
"typeerror"
] | stackoverflow_0074432508_discord.py_python_python_asyncio_typeerror.txt |
Q:
Running python script using Outlook VBA
Im trying to run a python script using Outlook Vba. When I run the below code. A python icon appears in the taskbar for a second and disappears. When in fact it should open a dialogue box and prompt me to enter folder name. After which it should run the rest of the script as... | Running python script using Outlook VBA | Im trying to run a python script using Outlook Vba. When I run the below code. A python icon appears in the taskbar for a second and disappears. When in fact it should open a dialogue box and prompt me to enter folder name. After which it should run the rest of the script as usual.
Please help me run this script from o... | [
"VBA (nor Outlook) doesn't provide anything for debugging such cases. The best what you could do is to add log statements to the python script where you could output everything what happens in the code. Analyzing log files you will be able to figure the cause of the problem.\n",
"You have a space in the file name... | [
0,
0,
0
] | [] | [] | [
"outlook",
"python",
"shellexecute",
"vba"
] | stackoverflow_0074129221_outlook_python_shellexecute_vba.txt |
Q:
PermissionError: [Errno 13] Permission denied on CSS file - Python Flask
I apologize if this very specific scenario has been answered on another question, I have tried fixes proposed on several similar questions, but nothing seems to work.
When trying to run my Flask (Python 3.8.2) app I keep getting the followin... | PermissionError: [Errno 13] Permission denied on CSS file - Python Flask | I apologize if this very specific scenario has been answered on another question, I have tried fixes proposed on several similar questions, but nothing seems to work.
When trying to run my Flask (Python 3.8.2) app I keep getting the following error on an specific CSS file:
Johns-MacBook-Air:FlaskApp john$ ./app.py
*... | [
"Flask app is now working after setting up venv virtual environment.\n"
] | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074436023_flask_python.txt |
Q:
dask-ml preprocessing raise AttributeError
I use Dask dataframe and dask-ml to manipulate my data. When I use dask-ml Min-max scaler, I get this error. Is there a way to prevent this error and make it work?
import dask.dataframe as dd
from dask_ml.preprocessing import MinMaxScaler
df = dd.read_csv('path to csv', ... | dask-ml preprocessing raise AttributeError | I use Dask dataframe and dask-ml to manipulate my data. When I use dask-ml Min-max scaler, I get this error. Is there a way to prevent this error and make it work?
import dask.dataframe as dd
from dask_ml.preprocessing import MinMaxScaler
df = dd.read_csv('path to csv', parse_dates=['CREATED_AT']
... | [
"Since the error message is ambiguous, an issue was opened: Better error message when using invalid 'MinMAxScaler.fit()' inputs\nBy the way, the way to solve this problem is using appropriate type as input. something like this:\nscaler = dask_ml.preprocessing.MinMaxScaler()\ncol_1 = df['col_1'].values\nscaler.fit(... | [
0
] | [] | [] | [
"dask",
"dask_dataframe",
"dask_ml",
"python"
] | stackoverflow_0074338504_dask_dask_dataframe_dask_ml_python.txt |
Q:
Reading an excel file, extracting each cell value as a str and doing some action on each cell value, Python
I have uploaded an excel file, what I need to do is extract each cell value as str object from the uploaded file and run a query on the cell value.
Unfortunately, nothing is working.
def read_agent_list(requ... | Reading an excel file, extracting each cell value as a str and doing some action on each cell value, Python | I have uploaded an excel file, what I need to do is extract each cell value as str object from the uploaded file and run a query on the cell value.
Unfortunately, nothing is working.
def read_agent_list(request):
request.session.clear_expired()
if request.is_ajax():
if request.method == "POST":
... | [
"To access each cell of excel you can use the following approach:\nfor col in df.columns:\n for row in range(df[df.columns[0]].count()):\n cell = df[col][row]\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074441668_django_python.txt |
Q:
Python, Trio async function upon needs
Within trio/anyio, is it possible to pause the tasks until i do specific operation and then continue all of it.
Let's say that i run specific function to obtain a valid cookie and then i start to crawl a website, But after sometimes this cookie got expired and i would need to... | Python, Trio async function upon needs | Within trio/anyio, is it possible to pause the tasks until i do specific operation and then continue all of it.
Let's say that i run specific function to obtain a valid cookie and then i start to crawl a website, But after sometimes this cookie got expired and i would need to run the previous function again to obtain a... | [
"You simply wrap get_cookies in an async with some_lock block. In that block, if you already have a cookie (let's say it's a global variable) you return it, otherwise you acquire one and then set the global.\nWhen you notice that the cookie has expired, you delete it (i.e. set the global back to None) and call get_... | [
2
] | [] | [] | [
"anyio",
"python",
"python_trio"
] | stackoverflow_0074440978_anyio_python_python_trio.txt |
Q:
NoSuchElement have tried every path type
I have trying to input an email into the login section of the page and can not get it to work.
I have the same error everytime "NoSuchElement"
The website is https://accela.kerncounty.com/CitizenAccess/Default.aspx
I have tried XPath, Name and ID
def wait(y):
for x in r... | NoSuchElement have tried every path type | I have trying to input an email into the login section of the page and can not get it to work.
I have the same error everytime "NoSuchElement"
The website is https://accela.kerncounty.com/CitizenAccess/Default.aspx
I have tried XPath, Name and ID
def wait(y):
for x in range(y):
print(x)
time.sleep(1... | [
"There are several issues here:\n\nElement you trying to access is inside an iframe. So, you first have to switch into it in order to access elements there.\nYou need to use correct locators. /html/body/form/div[3]/div/div[7]/div[1]/table/tbody/tr/td[2]/div[2]/div[2]/table/tbody/tr/td/div/div[2]/table/tbody/tr/td[1... | [
1
] | [] | [] | [
"iframe",
"python",
"selenium",
"selenium_webdriver",
"xpath"
] | stackoverflow_0074441655_iframe_python_selenium_selenium_webdriver_xpath.txt |
Q:
How to stop Python Selenium from maximizing the window on download
I created a code to download programmatically files from a website, each time a download occurs the window running with selenium maximizes and i need to minimize it to continue work.
How can i prevent it from maximizing on each download event?
A:
... | How to stop Python Selenium from maximizing the window on download | I created a code to download programmatically files from a website, each time a download occurs the window running with selenium maximizes and i need to minimize it to continue work.
How can i prevent it from maximizing on each download event?
| [
"You basically have to write this line of code after the line of code which initialises download event\ndriver.minimize_window()\n\nThis will automatically minimize window after each download event\nNote: Minimize function is only available in Selenium 4, so if you are using previous versions of Selenium then this ... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver"
] | stackoverflow_0071986733_python_selenium_selenium_webdriver.txt |
Q:
Trying to find duplicates in a 2D List (PYTHON)
Trying to find duplicates in an array where each list inside the list is a different row of a document. Im trying to find the words where that are the same
def helper(a):
for x in range(len(a)-1):
for y in range(len(a[x])):
for i in range(len(a)):
... | Trying to find duplicates in a 2D List (PYTHON) | Trying to find duplicates in an array where each list inside the list is a different row of a document. Im trying to find the words where that are the same
def helper(a):
for x in range(len(a)-1):
for y in range(len(a[x])):
for i in range(len(a)):
for j in range(len(a[x])-1):
if(a[x][y]==a... | [
"a =[[\"i\", \"will\", \"always\", \"be\", \"very\", \"happy\"],[\"happy\",\"people\", \"are\", \"cool\", \"very\"]]\nfor i in range(len(a)-1):\n res = set(a[i]) & set(a[i+1])\n print(res)\n\nUsing sets you are able to acheive this with only one loop\n",
"Concise answer thanks to a list comprehension that a... | [
1,
1,
0
] | [
"Your for is kind of complicated. I would solve it like this:\nsame_words = list()\n\nfor scanning_list in a:\n for scanned_list in a:\n if scanning_list == scanned_list:\n continue\n for scanning_item in scanning_list:\n if scanning_item in scanned_list and scanning_item not in same_wor... | [
-1
] | [
"2d",
"python"
] | stackoverflow_0074441622_2d_python.txt |
Q:
Filter list of dict in python
filter the dictionary based on filter criteria
records = [
{"category": "automobile", "type": "car", "model": "suv", "year": "2010"},
{"category": "automobile", "type": "car", "model": "all", "year": "2010"},
{"category": "automobile", "type": "car", "model": "sedan", "yea... | Filter list of dict in python | filter the dictionary based on filter criteria
records = [
{"category": "automobile", "type": "car", "model": "suv", "year": "2010"},
{"category": "automobile", "type": "car", "model": "all", "year": "2010"},
{"category": "automobile", "type": "car", "model": "sedan", "year": "2010"},
{"category": "auto... | [
"records = [\n {\"category\": \"automobile\", \"type\": \"car\", \"model\": \"suv\", \"year\": \"2010\"},\n {\"category\": \"automobile\", \"type\": \"car\", \"model\": \"all\", \"year\": \"2010\"},\n {\"category\": \"automobile\", \"type\": \"car\", \"model\": \"sedan\", \"year\": \"2010\"},\n {\"categ... | [
0,
0
] | [] | [] | [
"dictionary",
"filter",
"list",
"python",
"search"
] | stackoverflow_0074440401_dictionary_filter_list_python_search.txt |
Q:
cannot properly return askdirectory() value
I'm making a project in which I have to implement a browse folder button and further put that file path into another function. I made a function that asks me for the directory and it returns the path. but the problem I am facing is whenever I'm calling the function the w... | cannot properly return askdirectory() value | I'm making a project in which I have to implement a browse folder button and further put that file path into another function. I made a function that asks me for the directory and it returns the path. but the problem I am facing is whenever I'm calling the function the window also opens for me to select the path again.... | [
"use code below:\nfrom tkinter import *\nfrom tkinter import filedialog\nimport tkinter as tk\n\nfull = tk.Tk()\nfull.geometry(\"400x200\")\nname = Label(full, text = \"Enter Image Directory\").place(x = 5,y = 30)\ndir=None\ndef askDir():\n global dir\n dir = filedialog.askdirectory()\n test()\n\ndef test(... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074439885_python_tkinter.txt |
Q:
Program can't find a specific value in a csv dataset
I'm trying to write a program that takes a CSV file from GitHub and graphs covid cases using matplotlib.
I added comments to the program so it should be self explanatory.
The first part of the code is the error, the second part is the program itself.
It gives me... | Program can't find a specific value in a csv dataset | I'm trying to write a program that takes a CSV file from GitHub and graphs covid cases using matplotlib.
I added comments to the program so it should be self explanatory.
The first part of the code is the error, the second part is the program itself.
It gives me this error, from what i understand it can't locate the Or... | [
"You need to set the index of stats to County in order to merge the two dataframes. Add this line to your code:\nstats = pd.read_csv(\"california_county_stats.txt\", delimiter=\",\")\ncovid = covid.set_index(\"County\")\nstats = stats.set_index(\"County\") # <- add this\n...\n\n"
] | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074441213_csv_python.txt |
Q:
How can I get the nearest entity in python
My code:
from mss import mss
import math
import cv2
import numpy as np
import torc
with mss() as sct:
monitor = {"top": 220, "left": 640, "width": 640, "height":640}
while True:
screenshot = np.array(sct.grab(monitor))
results = model(screenshot, size=600... | How can I get the nearest entity in python | My code:
from mss import mss
import math
import cv2
import numpy as np
import torc
with mss() as sct:
monitor = {"top": 220, "left": 640, "width": 640, "height":640}
while True:
screenshot = np.array(sct.grab(monitor))
results = model(screenshot, size=600)
df = results.pandas().xyxy[0]
distance... | [
"It's not entirely clear, what you are after... but my guess is, that there is a small mistake when calculating the center of the enemies. Either use:\ncenterX = (xmax + xmin) / 2 # do not add xmin here\ncenterY = (ymax + ymin) / 2 # do not add ymin here\n\nor calculate the distance between the minimum and maximu... | [
1
] | [] | [] | [
"math",
"mss",
"pandas",
"python",
"pytorch"
] | stackoverflow_0074430781_math_mss_pandas_python_pytorch.txt |
Q:
Scipy Sparse Row/Column Dot Products
What is the readable and efficient way to compute the dot product between two columns or rows of a sparse matrix using scipy? Let's say that we want to take the dot product of two vectors x and y, two columns of sparse matrix A, then I'm currently doing:
x = A.getcol(i)
... | Scipy Sparse Row/Column Dot Products | What is the readable and efficient way to compute the dot product between two columns or rows of a sparse matrix using scipy? Let's say that we want to take the dot product of two vectors x and y, two columns of sparse matrix A, then I'm currently doing:
x = A.getcol(i)
y = A.getcol(j)
dot = (x.transpose() ... | [
"Sparse matrices have a dot method, so you can also go with\ndot = x.T.dot(y)[0, 0]\n\nBut I personally find your code at least as good as the above.\n",
"I found it to be somewhat more efficient to use csc_matrix.multiply:\nIn [77]: %timeit (x.transpose() * y)[0,0]\n98.6 µs ± 1.01 µs per loop (mean ± std. dev. o... | [
3,
0
] | [] | [] | [
"code_readability",
"python",
"readability",
"scipy"
] | stackoverflow_0014865935_code_readability_python_readability_scipy.txt |
Q:
Python debugging when using relative import
I'm debugging a python file and it prompts me attempted relative import with no known parent package.
How to solve it? Thanks!!
A:
You have to write like
from kitti_ultis import some_function
Because you are import some function from the file. First you have to write ... | Python debugging when using relative import | I'm debugging a python file and it prompts me attempted relative import with no known parent package.
How to solve it? Thanks!!
| [
"You have to write like\nfrom kitti_ultis import some_function\n\nBecause you are import some function from the file. First you have to write file name and then you import what ever you want in that file like function, variable, class.\n"
] | [
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0074441797_import_python.txt |
Q:
Is there a way to word wrap or insert a line break with Altair labels?
Is there a way to insert a line break when displaying longer labels in Altair?
d = {'source': ['short label', 'a longer label that needs a line break', 'short label', 'a longer label that needs a line break'], 'variable': ['begin','begin','end'... | Is there a way to word wrap or insert a line break with Altair labels? | Is there a way to insert a line break when displaying longer labels in Altair?
d = {'source': ['short label', 'a longer label that needs a line break', 'short label', 'a longer label that needs a line break'], 'variable': ['begin','begin','end','end'], 'value':[75, 25, 20, 80]}
df = pd.DataFrame(data=d)
slope = alt.Ch... | [
"For this particular example, you could add a new line character to the label that needs the new line: 'a longer label that \\nneeds a line break' and then change the parameters inside mark_text to include lineBreak=r'\\n'\nd = {'source': ['short label', 'a longer label that \\nneeds a line break', 'short label', '... | [
5,
0,
0
] | [] | [] | [
"altair",
"python"
] | stackoverflow_0062204795_altair_python.txt |
Q:
When iterating using multiple 'def's in 'class', the function is undefined
First, before making the code into a class, I made it into a def. Since it works normally in this code, I thought that it would work normally even if I grouped it into a class.
winner = ''
def start():
pla2 = 0
pla1 = int(input("Wha... | When iterating using multiple 'def's in 'class', the function is undefined | First, before making the code into a class, I made it into a def. Since it works normally in this code, I thought that it would work normally even if I grouped it into a class.
winner = ''
def start():
pla2 = 0
pla1 = int(input("What is pla1's choice? 1 , 2 , 3 :"))
if pla1 == 3:
return 'winner 2'
... | [
"When creating classes you need to pass in the self-method and you also need to call the start function in order to actually run it.\nclass twoplayer:\n winner = ''\n def start(self):\n pla2 = 0\n pla1 = int(input(\"What is pla1's choice? 1 , 2 , 3 :\"))\n if pla1 == 3:\n retur... | [
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0074441866_class_python.txt |
Q:
Nginx error: 502 Bad Gateway nginx/1.23.2 on Docker + Django + Postgres
So this is the error I got from my log
2022/11/15 04:30:08 [error] 29#29: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.80.1, server: mysite.local, request: "GET /favicon.ico HTTP/1.1", upstream: "... | Nginx error: 502 Bad Gateway nginx/1.23.2 on Docker + Django + Postgres | So this is the error I got from my log
2022/11/15 04:30:08 [error] 29#29: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.80.1, server: mysite.local, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://192.168.80.3:3000", host: "mysite.local", referrer: "http://mysite.lo... | [
"To access a service from another docker or service, you should use docker service name not container name. Here your django service name is django_api_backend. Replace it nginx config.\n"
] | [
0
] | [] | [] | [
"django",
"docker",
"nginx",
"nginx_config",
"python"
] | stackoverflow_0074440757_django_docker_nginx_nginx_config_python.txt |
Q:
GDAL Warp produces a black image
I am calling GDAL warp using the python distribution on a NITF file and it simply outputs all zero values which creates an empty black image. The command I'm calling is
import osgeo.gdal as gdal
gdal.Warp("out.ntf", "inp.ntf")
I've tried using Translate as sort of a test to make ... | GDAL Warp produces a black image | I am calling GDAL warp using the python distribution on a NITF file and it simply outputs all zero values which creates an empty black image. The command I'm calling is
import osgeo.gdal as gdal
gdal.Warp("out.ntf", "inp.ntf")
I've tried using Translate as sort of a test to make sure GDAL as a whole is functioning an... | [
"One thing that's important is to close the Dataset, depending a little on how you run it (script, repl, notebook etc).\nThis Python interface to the command-line utilities returns an opened Dataset, so you can explicitly close it with.\nimport osgeo.gdal as gdal\n\nds = gdal.Warp(\"out.ntf\", \"inp.ntf\")\nds = No... | [
0
] | [] | [] | [
"gdal",
"gdal_python_bindings",
"gis",
"osgeo",
"python"
] | stackoverflow_0074434526_gdal_gdal_python_bindings_gis_osgeo_python.txt |
Q:
Getting unique combinations and also remove element from list
I am trying to loop thrue a list in python of integers, finding all uniqe combinations but if one element has been used from the list to create a combination the element can not be used again.
import itertools
import collections
list = [1, 3, 6, 8, 10,... | Getting unique combinations and also remove element from list | I am trying to loop thrue a list in python of integers, finding all uniqe combinations but if one element has been used from the list to create a combination the element can not be used again.
import itertools
import collections
list = [1, 3, 6, 8, 10, 13, 18, 25, 40, 60]
result_comb = []
result_val = []
for L in ran... | [
"I find the easy way to do this is to run through the binary numbers. 1 means the element is included, 0 means it isn't.\nlst = [1, 3, 6, 8, 10, 13, 18, 25, 40, 60]\n\ndef makecombos(lst):\n for i in range(2**len(lst)):\n result = [lst[bit] \n for bit in range(len(lst))\n if i & (1<... | [
1
] | [] | [] | [
"list",
"python",
"python_3.x",
"python_itertools"
] | stackoverflow_0074441767_list_python_python_3.x_python_itertools.txt |
Q:
How to scrape all results from list instead of be limited to only 20?
I'm using beautifulsoup and trying to scrape some cars24.com data. The list, however, only contains 20 cars details. That's weird, since the page contains a lot more car details (I tried saving it). What am I doing wrong and how can I get it to ... | How to scrape all results from list instead of be limited to only 20? | I'm using beautifulsoup and trying to scrape some cars24.com data. The list, however, only contains 20 cars details. That's weird, since the page contains a lot more car details (I tried saving it). What am I doing wrong and how can I get it to scrape the whole page?
This is my code:
from bs4 import BeautifulSoup as bs... | [
"Use the API endpoint.\nFor example:\nimport requests\n\nurl = \"https://api-sell24.cars24.team/buy-used-car?sort=P&serveWarrantyCount=true&gaId=&page=1&storeCityId=2&pinId=110001\"\ncars = requests.get(url).json()['data']['content']\nbase = \"https://www.cars24.com/buy-used-\"\n\nfor car in cars:\n car_name = \... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074441091_beautifulsoup_python_web_scraping.txt |
Q:
How to insert a string column to another string column in pandas dataframe?
I have a dataset with over 100,000rows and 300 columns,
Here is the sample dataset:
pd.options.display.max_colwidth = 1000
df = pd.DataFrame({'EVENT_DTL':['1. Name : John Johns \n2. Date : 05 March 2013 \n3. founded : 75075 Plano, Dallas ... | How to insert a string column to another string column in pandas dataframe? | I have a dataset with over 100,000rows and 300 columns,
Here is the sample dataset:
pd.options.display.max_colwidth = 1000
df = pd.DataFrame({'EVENT_DTL':['1. Name : John Johns \n2. Date : 05 March 2013 \n3. founded : 75075 Plano, Dallas Texas \n4. Charactor : Impersive \n5. Corona corelation : Cannot be found',
... | [
"You can split and merge again:\ndf2 = df['EVENT_DTL'].str.split('(?<=\\n4\\.)', expand=True)\ndf['EVENT_DTL'] = df2[0]+' '+df['EVENT_DTL_2']+' '+df2[1]\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074441249_pandas_python.txt |
Q:
Pandas multiindex: drop rows with group-specific condition
I have created a data frame as follows:
np.random.seed(0)
lvl0 = ['A','B']
lvl1 = ['x', 'y', 'z']
idx = pd.MultiIndex.from_product([lvl0, lvl1])
cols = ['c1', 'c2']
df = pd.DataFrame(index=idx, columns=cols)
df.loc[:] = np.random.randint(0,2, size=df.shape... | Pandas multiindex: drop rows with group-specific condition | I have created a data frame as follows:
np.random.seed(0)
lvl0 = ['A','B']
lvl1 = ['x', 'y', 'z']
idx = pd.MultiIndex.from_product([lvl0, lvl1])
cols = ['c1', 'c2']
df = pd.DataFrame(index=idx, columns=cols)
df.loc[:] = np.random.randint(0,2, size=df.shape)
for v in lvl0:
df.loc[(v, 'mode'), :] = np.nan
df.sort_in... | [
"Use:\nnp.random.seed(0)\nlvl0 = ['A','B']\nlvl1 = ['x', 'y', 'z']\nidx = pd.MultiIndex.from_product([lvl0, lvl1])\ncols = ['c1', 'c2']\ndf = pd.DataFrame(index=idx, columns=cols)\ndf.loc[:] = np.random.randint(0,2, size=df.shape)\n\ndf.sort_index(inplace=True)\n\n#get first modes per groups\nmodes = df.groupby(lev... | [
1
] | [] | [] | [
"group_by",
"multi_index",
"pandas",
"python"
] | stackoverflow_0074435718_group_by_multi_index_pandas_python.txt |
Q:
Importing two repositories with the same package name
I have an issue where I have two git repositories (AdaBins,BLIP) that have the same package name models that I'm trying to import and use in the same run. It appears that when I import one of the packages, the namespace gets locked, preventing me from using fun... | Importing two repositories with the same package name | I have an issue where I have two git repositories (AdaBins,BLIP) that have the same package name models that I'm trying to import and use in the same run. It appears that when I import one of the packages, the namespace gets locked, preventing me from using functions from the same package.
AdaBins.infer ends up calli... | [
"I had the same issue but solved it with the axe. I forked and refactored that folder. I did fork it quite some time ago already and it never changed until now so I hope it is kinda stable for quite some time. But now I can use it aside from Blip. if you like feel free to use my fork https://github.com/osi1880vr/Ad... | [
0
] | [] | [] | [
"dependencies",
"jupyter",
"jupyter_notebook",
"python",
"python_3.x"
] | stackoverflow_0074332747_dependencies_jupyter_jupyter_notebook_python_python_3.x.txt |
Q:
How to transfer values from multiple columns to other columns using Pandas?
I have multiple columns in a pandas dataframe that I want to reduce from wide form to long form so that it essentially multiplies the number of rows in my dataframe by 2 and also adds a new column to indicate where each row comes from orig... | How to transfer values from multiple columns to other columns using Pandas? | I have multiple columns in a pandas dataframe that I want to reduce from wide form to long form so that it essentially multiplies the number of rows in my dataframe by 2 and also adds a new column to indicate where each row comes from originally.
I have the following dataframe df where cols a1, b1, c1, and d1 all belon... | [
"Use wide_to_long and create new columns with group:\ndf = (pd.wide_to_long(df.reset_index(), \n stubnames=['a','b','c','d'], i=['index','name'], j='new_col')\n .droplevel(0)\n .reset_index())\ndf['new_col'] = 'group' + df['new_col'].astype(str)\nprint (df)\n name new_col a b ... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074441383_dataframe_pandas_python.txt |
Q:
Is there any workaround to save csv with multiple sheets in python
I'm currently working with a pandas data frame and need to save data via CSV for different categories.so I thought to maintain one CSV and add separate sheets to each category. As per my research via CSV, we can't save data for multiple sheets. is ... | Is there any workaround to save csv with multiple sheets in python | I'm currently working with a pandas data frame and need to save data via CSV for different categories.so I thought to maintain one CSV and add separate sheets to each category. As per my research via CSV, we can't save data for multiple sheets. is there any workaround for this? I need to keep the format as CSV(cant use... | [
"No.\nA CSV file is just a text file, it doesn't have a standard facility for \"multiple sheets\" like spreadsheet files do.\nYou could save each \"sheet\" as a separate file, but that's about it.\n"
] | [
3
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074442155_csv_pandas_python.txt |
Q:
from list of list in pandas dataframe to new set of list with multiple columns in pandas dataframe
I have these values in dataset in a pandas dataframe column
col1
[[1,2],[1,2]]
[[3,4],[3,4]]
[[5,6],[5,6]]
I want to get a new column of two elements as list in new columns as rows.
This is the columns that I want t... | from list of list in pandas dataframe to new set of list with multiple columns in pandas dataframe | I have these values in dataset in a pandas dataframe column
col1
[[1,2],[1,2]]
[[3,4],[3,4]]
[[5,6],[5,6]]
I want to get a new column of two elements as list in new columns as rows.
This is the columns that I want to get.
col1 col2
[1,1] [2,2]
[3,3] [4,4]
[5,5] [6,6]
| [
"Assuming lists, use the DataFrame constructor:\nout = pd.DataFrame(df['col1'].tolist(), columns=['col1', 'col2'])\n\nIf you have strings, first convert to lists:\ndf['col1'] = df['col1'].apply(pd.eval)\n\n",
"Assuming so is the name of your dataframe and \"a\" the name of the original column you want to split yo... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074442142_dataframe_pandas_python.txt |
Q:
Reading ints in input in a Python program
I have to take input from the user then the operator has to print what number is before the input and after the input like:
input= 3
has to print 2 and 4
I used range, did I do it wrong? I am just a beginner in Python.
number=int(input)
for num in range(number ,+ 1, -1):
... | Reading ints in input in a Python program | I have to take input from the user then the operator has to print what number is before the input and after the input like:
input= 3
has to print 2 and 4
I used range, did I do it wrong? I am just a beginner in Python.
number=int(input)
for num in range(number ,+ 1, -1):
print(num)
| [
"You first need to use input() to let the user register a number.\nThen, simply print the number with number - 1 and number + 1.\nnumber = int(input(\"What is your number? \"))\nprint(f\"{number - 1} {number + 1}\")\n\nOutputs to:\nWhat is your number? 3\n2 4\n\n",
"you don't need range do this task\nnum = int(in... | [
1,
0,
0
] | [] | [] | [
"input",
"integer",
"python"
] | stackoverflow_0074442082_input_integer_python.txt |
Q:
Extracting an element of a dictionary in a pandas column
I've been trying to work out on extracting elements from a dictionary in a Pandas column, and put these items into a couple of new columns.
I have a DataFrame consisting of 2 columns, i.e. ID and data (dictionary).
ID data
0 6602629924 {'@status': 'found... | Extracting an element of a dictionary in a pandas column | I've been trying to work out on extracting elements from a dictionary in a Pandas column, and put these items into a couple of new columns.
I have a DataFrame consisting of 2 columns, i.e. ID and data (dictionary).
ID data
0 6602629924 {'@status': 'found', '@_fa': 'true', 'coredata...
1 55599317400 {'@status': 'f... | [
"use json_normalize()\nnew_df=new_df.join(pd.json_normalize(new_df.pop('data')))\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074442171_pandas_python.txt |
Q:
Merge records that follow one another within group
I have the following dataframe:
A B start_date end_date id
0 1 2 2022-01-01 2022-01-10 1
1 2 2 2022-02-02 2022-02-05 2
2 1 2 2022-01-11 2022-01-15 3
3 2 2 2022-02-06 2022-02-10 4
4 2 2 2022-02-11 2022-02-15 5
5 2 3 2022-01-14 2022-01-1... | Merge records that follow one another within group | I have the following dataframe:
A B start_date end_date id
0 1 2 2022-01-01 2022-01-10 1
1 2 2 2022-02-02 2022-02-05 2
2 1 2 2022-01-11 2022-01-15 3
3 2 2 2022-02-06 2022-02-10 4
4 2 2 2022-02-11 2022-02-15 5
5 2 3 2022-01-14 2022-01-17 6
6 2 3 2022-01-19 2022-01-22 7
There are sever... | [
"You can use a custom grouper to join the successive dates per group:\ndf[['start_date', 'end_date']] = df[['start_date', 'end_date']].apply(pd.to_datetime)\n\nm = (df['start_date'].sub(df.groupby(['A', 'B'])\n ['end_date'].shift()\n .add(pd.Timedelta('1d'))\n ... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074442081_pandas_python.txt |
Q:
Store the data on a timeseries database
I have been using an API to fetch some timeseries data and using Grafana to visualise that data. But lately I had a few issues that I had to solve and for that I need to go back in time and for some reason if the API I'm using has some server errors or anything then basicall... | Store the data on a timeseries database | I have been using an API to fetch some timeseries data and using Grafana to visualise that data. But lately I had a few issues that I had to solve and for that I need to go back in time and for some reason if the API I'm using has some server errors or anything then basically I can't do my work. So, I was wondering if ... | [
"You could try following steps:\n\nSet up an InfluxDB instance\nCollect data through HTTP API and store it in InfluxDB via Telegraf's HTTP Plugin: here you need to configure two settings: [[inputs.http]] and [[outputs.influxdb]]\nSet up the Grafana which talks to InfluxDB\n\nHere is a working sample you could learn... | [
0
] | [] | [] | [
"api",
"database",
"javascript",
"python",
"time_series"
] | stackoverflow_0074402847_api_database_javascript_python_time_series.txt |
Q:
Scrolldown a table inside a div tag in through Selenium in Python
I wanted to scroll till the last row of https://covid19.who.int/table using Selenium framework in python.
See below my snippet
url = 'https://covid19.who.int/table/'
Path_ChromeDriver = 'E:\chromedriver_win32\chromedriver.exe'
driver = webdriver.Chr... | Scrolldown a table inside a div tag in through Selenium in Python | I wanted to scroll till the last row of https://covid19.who.int/table using Selenium framework in python.
See below my snippet
url = 'https://covid19.who.int/table/'
Path_ChromeDriver = 'E:\chromedriver_win32\chromedriver.exe'
driver = webdriver.Chrome(Path_ChromeDriver)
driver.get(url)
time.sleep(10)
driver.execute_sc... | [
"First get all the rows of the table using this line of code.\nrows = driver.find_elements_by_css_selector(\"div[class=\\\"tr depth_0 \\\"]\")\n\nNow scroll to last row like this:\ndriver.execute_script(\"arguments[0].scrollIntoView()\",rows[len(rows)-1]\n\nBy this, the table will be scrolled till the last row whic... | [
0,
0
] | [] | [] | [
"python",
"selenium",
"web",
"web_scraping"
] | stackoverflow_0067652821_python_selenium_web_web_scraping.txt |
Q:
Joining lists with pandas
I have a large messy SQL database which I have started cleaning up and I need to check if user IDs exist in the tables, preferably in one view. I have started with left joins, listing all user IDs but the performance is really poor with 5+ tables in my case.
So I have decided to use pytho... | Joining lists with pandas | I have a large messy SQL database which I have started cleaning up and I need to check if user IDs exist in the tables, preferably in one view. I have started with left joins, listing all user IDs but the performance is really poor with 5+ tables in my case.
So I have decided to use python and get the IDs in lists and ... | [
"Okay so I figured it out. The dataset I wanted to have would have looked like this:\nusers table1 table2 table3\n----- ------ ------ ------\n1 True None None\n2 True True None\n3 None None True\n4 None None None\n5 True True True\n\n... | [
0
] | [] | [] | [
"join",
"merge",
"pandas",
"python",
"sql"
] | stackoverflow_0074434091_join_merge_pandas_python_sql.txt |
Q:
Disable a method in a ViewSet, django-rest-framework
ViewSets have automatic methods to list, retrieve, create, update, delete, ...
I would like to disable some of those, and the solution I came up with is probably not a good one, since OPTIONS still states those as allowed.
Any idea on how to do this the right wa... | Disable a method in a ViewSet, django-rest-framework | ViewSets have automatic methods to list, retrieve, create, update, delete, ...
I would like to disable some of those, and the solution I came up with is probably not a good one, since OPTIONS still states those as allowed.
Any idea on how to do this the right way?
class SampleViewSet(viewsets.ModelViewSet):
queryse... | [
"The definition of ModelViewSet is:\nclass ModelViewSet(mixins.CreateModelMixin, \n mixins.RetrieveModelMixin, \n mixins.UpdateModelMixin,\n mixins.DestroyModelMixin,\n mixins.ListModelMixin,\n GenericViewSet)\n\nSo rather tha... | [
340,
226,
29,
9,
6,
3,
3,
3,
3,
2,
0,
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"django_views",
"python"
] | stackoverflow_0023639113_django_django_rest_framework_django_views_python.txt |
Q:
Is 'simpful' package or library?
When i search 'simpful' in google, they say that it is one of the library of python.
And I think so.
But my professor said me that 'simpful' is one of the package.
What is the fact?
Is 'simpful' package or library?
and Am i missing knowledge?
A:
Look at the description on PyPi an... | Is 'simpful' package or library? | When i search 'simpful' in google, they say that it is one of the library of python.
And I think so.
But my professor said me that 'simpful' is one of the package.
What is the fact?
Is 'simpful' package or library?
and Am i missing knowledge?
| [
"Look at the description on PyPi and you'll see it described as a library\n"
] | [
0
] | [] | [] | [
"fuzzy",
"package",
"python"
] | stackoverflow_0074442291_fuzzy_package_python.txt |
Q:
how to I process messages a set chunk at a time without losing messages that don't fit into a chunk
I need to process a set of messages and put them into chunks of 10 at a time. The total number of messages is unknown since they are feeding in as this process occurs.
simple example:
message_count = 0
chunk_limit =... | how to I process messages a set chunk at a time without losing messages that don't fit into a chunk | I need to process a set of messages and put them into chunks of 10 at a time. The total number of messages is unknown since they are feeding in as this process occurs.
simple example:
message_count = 0
chunk_limit = 10
while messages_exist:
message_count += 1
if message_count >= chunk_limit:
proce... | [
"In your example, could you not just call process_chunk() after the while loop checking for messages is done? After the while loop exits, you know there are no more messages so you can just take whatever messages are left and have not been included in a chunk yet and make smaller chunk out of them.\nMay I know what... | [
0
] | [] | [] | [
"azure",
"azure_queues",
"message_queue",
"python"
] | stackoverflow_0073992828_azure_azure_queues_message_queue_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.