content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to #include in Xcode
#include <Python.h> the error of this code is 'Python.h' file not found.
I've installed python by brew, the results show below. And the path of python already written in to $PATH
MacBook-Pro test % python --version
Python 3.10.8
MacBook-Pro test % brew search python
==> Formulae
app-engin... | How to #include in Xcode | #include <Python.h> the error of this code is 'Python.h' file not found.
I've installed python by brew, the results show below. And the path of python already written in to $PATH
MacBook-Pro test % python --version
Python 3.10.8
MacBook-Pro test % brew search python
==> Formulae
app-engine-python pyt... | [
"I've fixed this problem by using g++,\ng++ main.cpp -o test -I /usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/include/ -L /usr/local/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib -l python3.10\n\n"
] | [
0
] | [] | [] | [
"c++",
"python",
"python_3.x",
"xcode"
] | stackoverflow_0074458612_c++_python_python_3.x_xcode.txt |
Q:
Python, Streamlit AgGrid add new row to AgGrid Table
I am trying to add a new row to an AgGrid Table using streamlit and python
At this point, I just want to add 1 or more new rows to the table generated by the AgGrid by pressing the "add row" button.
After pressing the "add row" button I generate a second table w... | Python, Streamlit AgGrid add new row to AgGrid Table | I am trying to add a new row to an AgGrid Table using streamlit and python
At this point, I just want to add 1 or more new rows to the table generated by the AgGrid by pressing the "add row" button.
After pressing the "add row" button I generate a second table with the new row mistakenly, so I get 2 data-tables instead... | [
"Here is a sample minimal code.\nimport streamlit as st\nimport pandas as pd\nfrom st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode\n\n\ndef generate_agrid(df):\n gb = GridOptionsBuilder.from_dataframe(df)\n gb.configure_selection(selection_mode=\"multiple\", use_checkbox=True)\n gridoptions = g... | [
1
] | [] | [] | [
"graph",
"pandas",
"python",
"streamlit"
] | stackoverflow_0074449270_graph_pandas_python_streamlit.txt |
Q:
How to append only the numbers in a row to a variable using float and an if statement in a for loop
Given a data set with the goal of graphing the data these issues arise:
The header is an entry in the list,
Some of the entries are blank (data missing),
Even the numbers are in the form of strings
income=[]
ferti... | How to append only the numbers in a row to a variable using float and an if statement in a for loop | Given a data set with the goal of graphing the data these issues arise:
The header is an entry in the list,
Some of the entries are blank (data missing),
Even the numbers are in the form of strings
income=[]
fertility=[]
for row in csv:
income.append(row[2])
fertility.append(row[3])
print(income)
print(fertility... | [
"You can do this more simply by just doing both float conversions in a single try/except:\nincome = []\nfertility = []\nfor row in csv:\n try:\n i, f = float(row[2]), float(row[3])\n income.append(i)\n fertility.append(f)\n except ValueError:\n pass\n\nIf either float() call raises... | [
1,
0
] | [] | [] | [
"for_loop",
"if_statement",
"python"
] | stackoverflow_0074484028_for_loop_if_statement_python.txt |
Q:
Run kafka consumer without while loop using python
I am using Confluentinc Kafka with Python & multi-threading. In this I have N worker threads running in parallel, whenever a thread completes its work
it poll the message from kafka on demand. This whole job is done using the while loop. By using the while loop m... | Run kafka consumer without while loop using python | I am using Confluentinc Kafka with Python & multi-threading. In this I have N worker threads running in parallel, whenever a thread completes its work
it poll the message from kafka on demand. This whole job is done using the while loop. By using the while loop my main thread gets blocked & there is no other operation... | [
"You could use supervisor Python library to run 5 processes in parallel with one consumer. That would simplify your code and offer you better process management.\nOtherwise, your while loop should be in the Thread body with a callback for the records it had polled, not in the main loop, iterating over each future, ... | [
0
] | [] | [] | [
"apache_kafka",
"confluent_kafka_python",
"python",
"while_loop"
] | stackoverflow_0074455299_apache_kafka_confluent_kafka_python_python_while_loop.txt |
Q:
How can you merge two data frames on a column that both data frames have if the column d types are not the same?
I have two dataframes with a column called "US Postal State Code" and I am trying to merge them together on that column into a new dataframe. The problem is that the column has an object dtype in the fi... | How can you merge two data frames on a column that both data frames have if the column d types are not the same? | I have two dataframes with a column called "US Postal State Code" and I am trying to merge them together on that column into a new dataframe. The problem is that the column has an object dtype in the first dataframe and a int64 dtype in the second dataframe.
I tried to change the column with the object dtype to int64 u... | [
"You'll have to convert one of the columns to the others datatype with a custom function:\ndef convert_postal(p):\n if p == \"AL\":\n return 35045\n elif p = \"OtherCodes\":\n return other_codes_numerical_code\n\nEnterprise3[\"US Postal State Code\"] = Enterprise3[\"US Postal State Code\"].map(c... | [
0,
0
] | [] | [] | [
"computer_science",
"data_science",
"python"
] | stackoverflow_0074484066_computer_science_data_science_python.txt |
Q:
How to create a single DataFrame column from two separate arrays being pulled through a loop
I want to create a DataFrame that prints precipitation type for multiple cities based on certain criteria. I have multiple variables that I would like to run through a single loop. For example, if temperature > 32 and prec... | How to create a single DataFrame column from two separate arrays being pulled through a loop | I want to create a DataFrame that prints precipitation type for multiple cities based on certain criteria. I have multiple variables that I would like to run through a single loop. For example, if temperature > 32 and precipitation amount > 0 then return "Rain". I use an API to pull current forecast data, so my actual ... | [
"Is this what you're looking for?\n\nimport pandas as pd\n\n\ndef rain_condition(tmp, _precip):\n \"\"\"\n Calculate the rain condition based on the temperature and precipitation.\n \n Parameters\n ----------\n tmp : list\n Temperatures.\n _precip : list\n Precipitation values.\n\... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074480950_pandas_python.txt |
Q:
How does QuantLib forwardRate function work?
I'm looking to find the expected interest rates for some period in the future based on the term structure of government bonds in python.
I'm trying to use this code as a base: http://gouthamanbalaraman.com/blog/quantlib-term-structure-bootstrap-yield-curve.html
I was ho... | How does QuantLib forwardRate function work? | I'm looking to find the expected interest rates for some period in the future based on the term structure of government bonds in python.
I'm trying to use this code as a base: http://gouthamanbalaraman.com/blog/quantlib-term-structure-bootstrap-yield-curve.html
I was hoping that this is what the forwardRate() function ... | [
"Based on that code it sounds like you're looking to calculate the 1Y forward rate for a particular date d. The forwardRate() method you mentioned should do just that, but check that the daycount and compounding are consistent with your yield curve definition since those can cause forward rates to look odd.\nOtherw... | [
1
] | [] | [] | [
"python",
"quantlib"
] | stackoverflow_0074437250_python_quantlib.txt |
Q:
plotly.py layout images - hover events
In plotly python, is it possible to trigger a hover event for images in your plot? I have a plot with a layout image. I would like to detect if the user hovers the mouse over the image.
example plot with image:
fig = go.Figure()
fig.add_trace(
go.Scatter(x=[0, 0.5, 1, 2,... | plotly.py layout images - hover events | In plotly python, is it possible to trigger a hover event for images in your plot? I have a plot with a layout image. I would like to detect if the user hovers the mouse over the image.
example plot with image:
fig = go.Figure()
fig.add_trace(
go.Scatter(x=[0, 0.5, 1, 2, 2.2], y=[1.23, 2.5, 0.42, 3, 1])
)
fig.add... | [
"I'm going to start out with code and explanation; at the end of this answer, I've added all of the code again in one chunk.\nAs far as I know, as long as it's a layout object, there is no simple method of instituting hover content. If you would like hover content, then instead of a layout object, make it a trace.\... | [
0
] | [] | [] | [
"hover",
"image",
"javascript",
"plotly",
"python"
] | stackoverflow_0074479798_hover_image_javascript_plotly_python.txt |
Q:
Multiplying a multi index dataframe with single index dataframe
I have a dataframe "A" which is multi indexed shown below
LL SK Di Co
Bracket yr_wk
1 121 2 2 4 3
12... | Multiplying a multi index dataframe with single index dataframe | I have a dataframe "A" which is multi indexed shown below
LL SK Di Co
Bracket yr_wk
1 121 2 2 4 3
122 3 6 5 4
123... | [
"import pandas as pd\ndf = pd.DataFrame({'yr_wk': [121, 122,123], 'LL': [2, 3, 3], 'SK':[2,6,2]})\ndf2 = pd.DataFrame({'yr_wk': [121, 122,123], 'Factor': [0.98, 1.045, 0.92]})\ndf = df.merge(df2, on = 'yr_wk')\nfor key in ['LL', 'SK']:\n df[key] = df[key] * df['Factor']\ndf = df.drop('Factor', axis=1)\ndf\n\n",
... | [
0,
0,
0
] | [] | [] | [
"multi_index",
"pandas",
"python"
] | stackoverflow_0074484077_multi_index_pandas_python.txt |
Q:
How to Configure Poetry Environments in Pycharm With Windows + WSL2?
TL;DR: can't configure a Python Interpreter on PyCharm (Windows) using an existing Poetry environment in WSL. When trying to set the Poetry environment path under Add Python Interpreter > Poetry Environment > Existing Environment, the needed Pyth... | How to Configure Poetry Environments in Pycharm With Windows + WSL2? | TL;DR: can't configure a Python Interpreter on PyCharm (Windows) using an existing Poetry environment in WSL. When trying to set the Poetry environment path under Add Python Interpreter > Poetry Environment > Existing Environment, the needed Python executable simply does not show. What am I doing wrong?
===============... | [
"Let me get this straight: You want PyCharm for Windows to execute Python binaries in WSL?\nThat cannot happen.\nBinaries in WSL are \"ELF\" binaries which Windows cannot execute (outside WSL). If the virtualenv was created by poetry from within WSL, it will contain ELF Python binaries. And that is why PyCharm for ... | [
0
] | [] | [] | [
"pycharm",
"python",
"python_poetry",
"ubuntu_20.04",
"wsl_2"
] | stackoverflow_0070205270_pycharm_python_python_poetry_ubuntu_20.04_wsl_2.txt |
Q:
How can I read a function's signature including default argument values?
Given a function object, how can I get its signature? For example, for:
def my_method(first, second, third='something'):
pass
I would like to get "my_method(first, second, third='something')".
A:
import inspect
def foo(a, b, x='blah')... | How can I read a function's signature including default argument values? | Given a function object, how can I get its signature? For example, for:
def my_method(first, second, third='something'):
pass
I would like to get "my_method(first, second, third='something')".
| [
"import inspect\n\ndef foo(a, b, x='blah'):\n pass\n\nprint(inspect.signature(foo))\n# (a, b, x='blah')\n\nPython 3.5+ recommends inspect.signature().\n",
"Arguably the easiest way to find the signature for a function would be help(function):\n>>> def function(arg1, arg2=\"foo\", *args, **kwargs): pass\n>>> he... | [
237,
58,
15,
10,
8,
7,
6,
6,
0
] | [] | [] | [
"arguments",
"inspect",
"python"
] | stackoverflow_0002677185_arguments_inspect_python.txt |
Q:
Video written through OpenCV on Raspberry Pi not running
I was working on saving live feed from USB webcam through opencv on Raspberry PI 4 B+ . Here is the code
import cv2
cap = cv2.VideoCapture(0)
fourcc=cv2.VideoWriter_fourcc(''D','I','V','X'')
out=cv2.VideoWriter('output.mp4',fourcc,25,(640,480))
while True:
... | Video written through OpenCV on Raspberry Pi not running | I was working on saving live feed from USB webcam through opencv on Raspberry PI 4 B+ . Here is the code
import cv2
cap = cv2.VideoCapture(0)
fourcc=cv2.VideoWriter_fourcc(''D','I','V','X'')
out=cv2.VideoWriter('output.mp4',fourcc,25,(640,480))
while True:
ret, frame = cap.read()
cv2.imshow('frame', frame)
... | [
"There are two issues, I would like to address:\n\nIssue #1: DIVX should be declared as:\n\n\n\n\nfourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')\n\n\nIssue #2:\n\n\n\n\nYou have declared to create the video with the size (640, 480). Therefore each frame you returned should be also (640, 480)\n\n\nframe = cv2.r... | [
2,
0
] | [] | [] | [
"live_streaming",
"opencv",
"python",
"raspberry_pi4"
] | stackoverflow_0063873746_live_streaming_opencv_python_raspberry_pi4.txt |
Q:
Filter rows with consecutive numbers
I have some data.
I want to remain with rows when an ID has 4 consecutive numbers. For example, if ID 1 has rows 100, 101, 102, 103, 105, the "105" should be excluded.
Data:
ID X
0 1 100
1 1 101
2 1 102
3 1 103
4 1 105
5 2 100
6 2 102
7 2 ... | Filter rows with consecutive numbers | I have some data.
I want to remain with rows when an ID has 4 consecutive numbers. For example, if ID 1 has rows 100, 101, 102, 103, 105, the "105" should be excluded.
Data:
ID X
0 1 100
1 1 101
2 1 102
3 1 103
4 1 105
5 2 100
6 2 102
7 2 103
8 2 104
9 3 100
10 3 101
11... | [
"You can identify the consecutive values, then filter the groups by size with groupby.filter:\n# group consecutive X\ng = df['X'].diff().gt(1).cumsum() # no need to group here, we'll group later\n\n# filter groups\nout = df.groupby(['ID', g]).filter(lambda g: len(g)>=4)#.reset_index(drop=True)\n\noutput:\n ID ... | [
4,
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0073072372_pandas_python.txt |
Q:
How do I elegantly rename Pandas value counts output?
I want to call df['item'].value_counts() and, with minimal manipulation, end up with a dataframe with columns item and count.
I can do something like this:
df['item'].value_counts().reset_index().rename(columns={"item":"count", "index": "item"})
... which is f... | How do I elegantly rename Pandas value counts output? | I want to call df['item'].value_counts() and, with minimal manipulation, end up with a dataframe with columns item and count.
I can do something like this:
df['item'].value_counts().reset_index().rename(columns={"item":"count", "index": "item"})
... which is fine but I'm like 95% sure there is a cleaner way to do this... | [
"Let us try with groupby\ndf.groupby('item')['item'].count().reset_index(name='count')\n\n",
"Using set_axis is very slightly cleaner.\ndf['item'].value_counts().reset_index().set_axis(['item','count'], axis=1)\n\n",
"Using groupby, value_counts, and to_frame\nimport pandas as pd # 1.5.1\n\n\ndf = pd.DataFrame... | [
2,
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074484322_pandas_python.txt |
Q:
Prediction for horse racing scikit learn - multiple rows per race
Goal
I want to train a model with Scikit-learn that predicts the outcome of horse races. I have a CSV file that includes multiple features like position, age, weight, horse_name, race_id etc.
Problem
In my original CSV file each horse is represented... | Prediction for horse racing scikit learn - multiple rows per race | Goal
I want to train a model with Scikit-learn that predicts the outcome of horse races. I have a CSV file that includes multiple features like position, age, weight, horse_name, race_id etc.
Problem
In my original CSV file each horse is represented in one row. With positions from 1-8 each race consists of 8 rows. When... | [
"if I correctly understand your problem you want to convert your old dataframe to new dataframe and feed that to your model.\n you can use this code:\nimport pandas as pd\nimport numpy as np\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\ndf = pd.DataFrame({'position': [1, 2,... | [
1,
0
] | [] | [] | [
"python",
"scikit_learn"
] | stackoverflow_0061385916_python_scikit_learn.txt |
Q:
matplotlib make axis ticks label for dates bold
I want to have bold labels on my axis, so I can use the plot for publication. I also need to have the label of the lines in the legend plotted in bold.
So far I can set the axis labels and the legend to the size and weight I want. I can also set the size of the axis ... | matplotlib make axis ticks label for dates bold | I want to have bold labels on my axis, so I can use the plot for publication. I also need to have the label of the lines in the legend plotted in bold.
So far I can set the axis labels and the legend to the size and weight I want. I can also set the size of the axis labels to the size I want, however I am failing with ... | [
"I think the problem is because the ticks are made in LaTeX math-mode, so the font properties don't apply.\nYou can get around this by adding the correct commands to the LaTeX preamble, using rcParams. Specifcally, you need to use \\boldmath to get the correct weight, and \\usepackage{sfmath} to get sans-serif font... | [
18,
15,
8,
0,
0
] | [] | [] | [
"matplotlib",
"python",
"tex"
] | stackoverflow_0029766827_matplotlib_python_tex.txt |
Q:
PyShell and IPython are showing an extra indentation that is not there
I just started using tmux along with slime, PyShell and IPython and I have ran into the following problem.
I am trying to run the following code:
names = ['a', 'b', 'c']
nc = { name : 0 for name in names}
count = 1
for name in names:
nc[nam... | PyShell and IPython are showing an extra indentation that is not there | I just started using tmux along with slime, PyShell and IPython and I have ran into the following problem.
I am trying to run the following code:
names = ['a', 'b', 'c']
nc = { name : 0 for name in names}
count = 1
for name in names:
nc[name] += count
count += 1
print(nc)
and when I normally run the file in te... | [
"The error is caused by IPython inserting an indent automatically. To turn off automatic indent, use %autoindent command in IPython. To keep the option off when you restart IPython, add the line\nc.TerminalInteractiveShell.autoindent=False\n\nto your ipython_config.py which is located in a profile_profilename folde... | [
1,
0
] | [] | [] | [
"python",
"slime",
"tmux",
"vim"
] | stackoverflow_0074483618_python_slime_tmux_vim.txt |
Q:
How to get number of values in each row of a sparse tensor?
I have a Sparse Tensor as follows:
st = tf.sparse.from_dense([[1, 0, 2, 5], [3, 0, 0, 4], [0, 0, 0, 0], [1, 1, 3, 0], [1, 2, 2, 2]])
print(st)
SparseTensor(indices=tf.Tensor(
[[0 0]
[0 2]
[0 3]
[1 0]
[1 3]
[3 0]
[3 1]
[3 2]
[4 0]
[4 1]
[4 2]
[... | How to get number of values in each row of a sparse tensor? | I have a Sparse Tensor as follows:
st = tf.sparse.from_dense([[1, 0, 2, 5], [3, 0, 0, 4], [0, 0, 0, 0], [1, 1, 3, 0], [1, 2, 2, 2]])
print(st)
SparseTensor(indices=tf.Tensor(
[[0 0]
[0 2]
[0 3]
[1 0]
[1 3]
[3 0]
[3 1]
[3 2]
[4 0]
[4 1]
[4 2]
[4 3]], shape=(12, 2), dtype=int64), values=tf.Tensor([1 2 5 3 4 1... | [
"You can use bin count on the indices.\ntf.math.bincount(tf.cast(st.indices[:,0], tf.int32))\n\n"
] | [
1
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074481219_python_tensorflow.txt |
Q:
Create a function called square that takes in a number and returns the square of that number
Question:- Create a function called square that takes in a number and returns the square of that number. If what's passed in is not a float or an int, return "None"
Code:-
def square(x):
if x % 2 == 0:
return x... | Create a function called square that takes in a number and returns the square of that number | Question:- Create a function called square that takes in a number and returns the square of that number. If what's passed in is not a float or an int, return "None"
Code:-
def square(x):
if x % 2 == 0:
return x**x
else:
return None
print(square(5))
Error:-
None !- 25 : square should return 25
Y... | [
"why are you doing modulus 2 here?\ndef square(x):\n if isinstance(x,int) or isinstance(x,float):\n return x**2\n else:\n return none\nprint(square(5))\n\n"
] | [
-1
] | [] | [] | [
"python"
] | stackoverflow_0074484388_python.txt |
Q:
Get the Excel column label (A, B, ..., Z, AA, ..., AZ, BA, ..., ZZ, AAA, AAB, ...)
Given the letter(s) of an Excel column header I need to output the column number.
It goes A-Z, then AA-AZ then BA-BZ and so on.
I want to go through it like it's base 26, I just don't know how to implement that.
It works fine for si... | Get the Excel column label (A, B, ..., Z, AA, ..., AZ, BA, ..., ZZ, AAA, AAB, ...) | Given the letter(s) of an Excel column header I need to output the column number.
It goes A-Z, then AA-AZ then BA-BZ and so on.
I want to go through it like it's base 26, I just don't know how to implement that.
It works fine for simple ones like AA because 26^0 = 1 + 26^1 = 26 = 27.
But with something like ZA, if I do... | [
"If we decode \"A\" as 0, \"B\" as 1, ... then \"Z\" is 25 and \"AA\" is 26.\nSo it is not a pure 26-base encoding, as then a prefixed \"A\" would have no influence on the value, and \"AAAB\" would have to be the same as \"B\", just like in the decimal system 0001 is equal to 1. But this is not the case here.\nThe ... | [
1,
1,
0
] | [] | [] | [
"base",
"excel",
"python"
] | stackoverflow_0072383708_base_excel_python.txt |
Q:
How return a value with the input function?
Hi guys I'm new to python. I've been trying to return a value with an input function to the return can anyone help me out?
def bike_wash(amount):
print("Welcome to your bike wash")
print("Please enter your desired wash")
if (amount == 100):
print... | How return a value with the input function? | Hi guys I'm new to python. I've been trying to return a value with an input function to the return can anyone help me out?
def bike_wash(amount):
print("Welcome to your bike wash")
print("Please enter your desired wash")
if (amount == 100):
print("Thanks for choosing basic wash")
print(... | [
"The answer depends on which version of Python you're using.\nPython 3\nYou can simply pass the result of input (a string) to int (a function which turns a string into an integer).\n amount = int(input(\"Enter a number\"))\n\nPython 2\nThe python2 equivalent (to the input function from python3) is raw_input\n a... | [
0
] | [] | [] | [
"input",
"python",
"return",
"user_input"
] | stackoverflow_0074484461_input_python_return_user_input.txt |
Q:
Python Reverse a string using recursion, explanation
I need to reverse a string using recursion, I was able to accidentally write a code that successfully accomplishes the task, but I don't really understand why. Here's what I have
import stdio
import sys
# Entry point
def main():
s = sys.argv[1]
stdio.wr... | Python Reverse a string using recursion, explanation | I need to reverse a string using recursion, I was able to accidentally write a code that successfully accomplishes the task, but I don't really understand why. Here's what I have
import stdio
import sys
# Entry point
def main():
s = sys.argv[1]
stdio.writeln(_reverse(s))
# Returns the reverse of the string ... | [
"s[:len(s)-1] or the same value but shorter s[:-1] is essentially a string with the last element removed, the length of it is 1 shorter than the original.\nYou then call the function with that shorter string.\nSo a step by step resolution would look something like this:\nreverse(\"hello\") # len(\"hello\") != 0 so ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074484470_python.txt |
Q:
Python asyncio: how are tasks scheduled?
I'm new to Python asyncio and I'm doing some experiments. I have the following code:
async def say_after(n, s):
await asyncio.sleep(n)
print(s)
async def main():
task1 = asyncio.create_task(say_after(2, 'a'))
task2 = asyncio.create_task(say_after(1, 'b'))
... | Python asyncio: how are tasks scheduled? | I'm new to Python asyncio and I'm doing some experiments. I have the following code:
async def say_after(n, s):
await asyncio.sleep(n)
print(s)
async def main():
task1 = asyncio.create_task(say_after(2, 'a'))
task2 = asyncio.create_task(say_after(1, 'b'))
await task1
print('x', flush=True)
... | [
"Executing say_after (without await) creates a coroutine object, but does not start it yet.\nIf you await on the coroutine object, then you are executing the coroutine until the Python encounters one of await or return (or end of function) in the coroutine. \"Executing\" here means transforming the coroutine into a... | [
1,
0,
0
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0070813763_python_python_asyncio.txt |
Q:
Merge two spark dataframes with different columns to get all columns
Lets say I have 2 spark dataframes:
Location Date Date_part Sector units
USA 7/1/2021 7/1/2021 Cars 200
IND 7/1/2021 7/1/2021 Scooters 180
COL 7/1/2021 7/1/2021 Tru... | Merge two spark dataframes with different columns to get all columns | Lets say I have 2 spark dataframes:
Location Date Date_part Sector units
USA 7/1/2021 7/1/2021 Cars 200
IND 7/1/2021 7/1/2021 Scooters 180
COL 7/1/2021 7/1/2021 Trucks 100
Location Date Brands units values
UK ... | [
"union : this function resolves columns by position (not by name)\nThat is the reason why you believed \"The values are being swapped and one column from second dataframe is missing.\"\nYou should use unionByName, but this functions requires both dataframe to have the same structure.\nI offer you this simple code ... | [
2,
0
] | [] | [] | [
"apache_spark",
"pyspark",
"python"
] | stackoverflow_0068844904_apache_spark_pyspark_python.txt |
Q:
Python giving a key error while inside a Try/Except loop
I am running the code:
CODE
def create_hec_kw(self, kw):
print(f'Creating Keyword {kw}')
data = {'name': kw, 'slug': kw.lower().replace(' ', '-')}
response = requests.post(self.create_url('tags'), headers=self.get_headers(), json=data)
# crea... | Python giving a key error while inside a Try/Except loop | I am running the code:
CODE
def create_hec_kw(self, kw):
print(f'Creating Keyword {kw}')
data = {'name': kw, 'slug': kw.lower().replace(' ', '-')}
response = requests.post(self.create_url('tags'), headers=self.get_headers(), json=data)
# created_kw_id = response.json()['data']['term_id'] if response.jso... | [
"Use KeyError instead of TypeError to catch it.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074484004_python.txt |
Q:
How do I isolate a specific key from a dictionary using greater or less than arguments on a string of values?
Just started coding; so, I am happy to clarify if there are questions.
I have a dictionary where each key is associated with a string of 2 values
my_dict = {'KEY##' : (X, Y)}
e.g., my_dict = {'CAR10' : (4,... | How do I isolate a specific key from a dictionary using greater or less than arguments on a string of values? | Just started coding; so, I am happy to clarify if there are questions.
I have a dictionary where each key is associated with a string of 2 values
my_dict = {'KEY##' : (X, Y)}
e.g., my_dict = {'CAR10' : (4, -3), 'BAT15' : (2, 5), 'DOG22' : (-2, 1)}
I would like to isolate and print out any key(s) where, for example, -1<... | [
"I think this list comprehenshion is what you want:\nmy_filtered_keys = [k for (k, (x, y)) in my_dict.items() if -1<x<3 and 3<y<7]\nprint(my_filtered_keys)\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074484468_dictionary_python.txt |
Q:
Logistic growth curve using scipy is not quite right
I'm trying to fit a simple logistic growth model to dummy data using Python's Scipy package. The code is shown below, along with the output that I get. The correct output is shown below it. I'm not quite sure what's going wrong here.
import scipy.optimize as opt... | Logistic growth curve using scipy is not quite right | I'm trying to fit a simple logistic growth model to dummy data using Python's Scipy package. The code is shown below, along with the output that I get. The correct output is shown below it. I'm not quite sure what's going wrong here.
import scipy.optimize as optim
from scipy.integrate import odeint
import numpy as np
i... | [
"Your optimization does not allow changing N0, which is dramatically different from the actual t=0 value in the list.\n",
"This is the edit they're hinting at, maybe this'll help you understand:\n# include N0 as an argument\ndef logistic_solution(t, N0, r, K):\n return odeint(logistic_de, N0, t, (r, K), tfirst... | [
1,
1,
0
] | [] | [] | [
"differential_equations",
"python",
"scipy"
] | stackoverflow_0069292456_differential_equations_python_scipy.txt |
Q:
Return position of columns with the same name in pandas
I would like to get the position of columns with the same name (that is column A).
DataFrame a:
A B A C
text1 text3 text5 text7
text2 text4 text6 text8
I can get position of column A but how to get the position of the sec... | Return position of columns with the same name in pandas | I would like to get the position of columns with the same name (that is column A).
DataFrame a:
A B A C
text1 text3 text5 text7
text2 text4 text6 text8
I can get position of column A but how to get the position of the second column. There are multiple dataframe with different numbe... | [
"Your result can be easily achieved using np.where().\ndf = pd.DataFrame(\n data=[[\"text1\", \"text2\", \"text5\", \"text7\"], [\"text2\", \"text4\", \"text6\", \"text8\"]],\n columns=[\"A\", \"B\", \"A\", \"D\"],\n)\nnp.where(df.columns == \"A\")[0]\n\nOutput:\narray([0, 2], dtype=int64)\n\n",
"res = []\n... | [
2,
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074484498_pandas_python.txt |
Q:
Get class that defined method
How can I get the class that defined a method in Python?
I'd want the following example to print "__main__.FooClass":
class FooClass:
def foo_method(self):
print "foo"
class BarClass(FooClass):
pass
bar = BarClass()
print get_class_that_defined_method(bar.foo_method)... | Get class that defined method | How can I get the class that defined a method in Python?
I'd want the following example to print "__main__.FooClass":
class FooClass:
def foo_method(self):
print "foo"
class BarClass(FooClass):
pass
bar = BarClass()
print get_class_that_defined_method(bar.foo_method)
| [
"import inspect\n\ndef get_class_that_defined_method(meth):\n for cls in inspect.getmro(meth.im_class):\n if meth.__name__ in cls.__dict__: \n return cls\n return None\n\n",
"I don't know why no one has ever brought this up or why the top answer has 50 upvotes when it is slow as hell, but ... | [
78,
13,
9,
8,
2,
2,
1
] | [] | [] | [
"python",
"python_2.6",
"python_datamodel"
] | stackoverflow_0000961048_python_python_2.6_python_datamodel.txt |
Q:
how to remove dictionary element by outlier values Python
Suppose my dictionary contains > 100 elements and one or two elements have values different than other values; most values are the same (12 in the below example). How can I remove these a few elements?
Diction = {1:12,2:12,3:23,4:12,5:12,6:12,7:12,8:2}
I w... | how to remove dictionary element by outlier values Python | Suppose my dictionary contains > 100 elements and one or two elements have values different than other values; most values are the same (12 in the below example). How can I remove these a few elements?
Diction = {1:12,2:12,3:23,4:12,5:12,6:12,7:12,8:2}
I want a dictionary object:
Diction = {1:12,2:12,4:12,5:12,6:12,7:... | [
"d = {1:12,2:12,3:23,4:12,5:12,6:12,7:12,8:2}\nnew_d = {}\n\nunique_values = []\nunique_count = []\nmost_occurence = 0\n\n# Find unique values\nfor k, v in d.items():\n if v not in unique_values:\n unique_values.append(v)\n\n# Count their occurrences\ndef count(dict, unique_value):\n count = 0\n fo... | [
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074484416_dictionary_python.txt |
Q:
How to send 'Headers' in websocket python
how can i make this
This is my code
import websockets
async def test():
async with websockets.connect('ws://iqoption.com') as websocket:
response = await websocket.recv()
print(response)
# Client async code
The cuestion is , can i send this headers ... | How to send 'Headers' in websocket python | how can i make this
This is my code
import websockets
async def test():
async with websockets.connect('ws://iqoption.com') as websocket:
response = await websocket.recv()
print(response)
# Client async code
The cuestion is , can i send this headers to get Authenticated in the server
Headers
... | [
"I think you are currently missing a basic understanding of WebSockets as is shown on your previous experiments. WebSockets are not plain sockets. WebSockets are some socket-like think created after a HTTP handshake. You cannot just take the socket from the connection as you've tried after requests but you have to ... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"sockets",
"websocket"
] | stackoverflow_0060308749_python_python_3.x_sockets_websocket.txt |
Q:
Creating a table with nested loops in python
I'm learning abort nested loops and I've gotten an assignment to create a function that takes two integer inputs. Then it should create something like in this image. Only problem is that when I use an odd number for columns it doesnt work.
It has to be an "advanced nest... | Creating a table with nested loops in python | I'm learning abort nested loops and I've gotten an assignment to create a function that takes two integer inputs. Then it should create something like in this image. Only problem is that when I use an odd number for columns it doesnt work.
It has to be an "advanced nested loop" for the assignment to be approved.
def cr... | [
"I have made one iteration of the code which you want. It prints the correct output for even and odd number of rows and columns. It is very similar to the outputs you want. When you provide further clarification for your question, I can provide an updated code.\nrows = 20\ncolumns = 41\n\nfor i in range(rows):\n ... | [
0,
0
] | [] | [] | [
"nested_loops",
"python"
] | stackoverflow_0065792749_nested_loops_python.txt |
Q:
How to properly import the ConfigServiceV2Client attribute from google-cloud-logging_v2 package in Python?
I tried importing the ConfigServiceV2Client attribute as follows:
from google.cloud.logging_v2.services.config_service_v2 import ConfigServiceV2Client
And I got the following error:
AttributeError: module 'g... | How to properly import the ConfigServiceV2Client attribute from google-cloud-logging_v2 package in Python? | I tried importing the ConfigServiceV2Client attribute as follows:
from google.cloud.logging_v2.services.config_service_v2 import ConfigServiceV2Client
And I got the following error:
AttributeError: module 'google.cloud.logging_v2' has no attribute 'ConfigServiceV2Client'
How should I import it?
| [
"Based on the error that you're getting it seems like you are missing some updated features, Install the google-cloud-logging package using pip as follows:\npip install --upgrade google-cloud-logging\nbased on the google documentation.\nAfter installing it try importing it in to your project.\nOr just uninstall the... | [
0
] | [] | [] | [
"google_cloud_logging",
"python"
] | stackoverflow_0074479034_google_cloud_logging_python.txt |
Q:
What is causing the error (index out of range)
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
index = []
for i in s:
if i.isdigit():
index += i
break
print(index)
if 6 >= le... | What is causing the error (index out of range) | def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
index = []
for i in s:
if i.isdigit():
index += i
break
print(index)
if 6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and ... | [
"A smaller example shows the problem\ndef is_valid(s):\n index = []\n for i in s:\n if i.isdigit():\n index += i\n break\n print(index)\n if 6 >= len(s) >= 2 and s[0:1].isalpha() and s.isupper() and index[0] != '0':\n return True\n\nis_valid(\"KEVIN\")\n\n\"KEVIN\" do... | [
1,
0
] | [] | [] | [
"for_loop",
"if_statement",
"python",
"python_3.x",
"return"
] | stackoverflow_0074484709_for_loop_if_statement_python_python_3.x_return.txt |
Q:
Why doesn't httpx ssl context set cipher
ctx = httpx.create_ssl_context()
ctx.set_ciphers("TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_ECDSA_... | Why doesn't httpx ssl context set cipher | ctx = httpx.create_ssl_context()
ctx.set_ciphers("TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:TLS_ECDHE_RSA_WI... | [
"You need to ensure that every single cipher name there use OpenSSL's naming for the ciphers.\nThere's a possibility one or more of the ciphers you used there are the \"public\" names, but OpenSSL has their own names for those ciphers.\nTake a look at this for the mapping:\nhttps://www.openssl.org/docs/man1.1.1/man... | [
0
] | [] | [] | [
"encryption",
"http",
"httpx",
"python",
"ssl"
] | stackoverflow_0072265009_encryption_http_httpx_python_ssl.txt |
Q:
How to edit python3.10 resources to include collections.abc in place of collections due to AttributeError no attribute 'MutableMapping'
Trying to install some image editing software (face recognition type).
Ubuntu 18.04, python3.10 which took too much work to get it upgraded but was needed for the image software.
... | How to edit python3.10 resources to include collections.abc in place of collections due to AttributeError no attribute 'MutableMapping' | Trying to install some image editing software (face recognition type).
Ubuntu 18.04, python3.10 which took too much work to get it upgraded but was needed for the image software.
Getting the AttributeError when I install numpy and none of the online threads solve this for me.
Tried to install packages and the central i... | [
"Looks like there are a lot of SO threads dealing with this. Since I had problems with my last Ubuntu upgrade, I'm currently using the windows boot, and Anaconda.\nHere:\nIn [591]: sys.version\nOut[591]: '3.9.12 (main, Apr 4 2022, 05:22:27) [MSC v.1916 64 bit (AMD64)]'\n\nIn [592]: np.__version__\nOut[592]: '1.21.... | [
0
] | [] | [] | [
"collections",
"numpy",
"python",
"python_3.10"
] | stackoverflow_0074484232_collections_numpy_python_python_3.10.txt |
Q:
Replace some string in python
I have two address like:
first_address = 'Красноярский край, г Красноярск, пр-кт им газеты Красноярский Рабочий, 152г, квартира (офис) /1'
second_address = 'Красноярский край, г Красноярск, пр-кт им.газеты "Красноярский рабочий", 152г'
And I want to replace all text before квартира (... | Replace some string in python | I have two address like:
first_address = 'Красноярский край, г Красноярск, пр-кт им газеты Красноярский Рабочий, 152г, квартира (офис) /1'
second_address = 'Красноярский край, г Красноярск, пр-кт им.газеты "Красноярский рабочий", 152г'
And I want to replace all text before квартира (офис) /1
My code looks like:
c = fi... | [
"Looks like you want to take substrings from second_address until they run out, then use substrings from first_address. Here's a straightforward way to do it.\nfirst_subs = first_address.split(',')\nsecond_subs = second_address.split(',')\n[(f if s is None else s) \n for (f, s) in zip(first_subs, \n ... | [
0
] | [] | [] | [
"algorithm",
"python",
"replace",
"string"
] | stackoverflow_0074484803_algorithm_python_replace_string.txt |
Q:
How to analyze source code by pygments(using pygount) and get a SUM
Using pygount I am trying to get the SUM of: Codes, Comments and Empty. I do not have any errors but I think I messed my relative paths.
Firstly check the tree below for a visualization
C:\...\Projects\TestProject
├───utils
│ ├───__init__.py
│ ... | How to analyze source code by pygments(using pygount) and get a SUM | Using pygount I am trying to get the SUM of: Codes, Comments and Empty. I do not have any errors but I think I messed my relative paths.
Firstly check the tree below for a visualization
C:\...\Projects\TestProject
├───utils
│ ├───__init__.py
│ └───loc.py
└───launcher.py
ROOT_DIR const def is inside __init__ of ut... | [
"You can use os.path.join instead of /\n"
] | [
0
] | [] | [] | [
"pygments",
"python"
] | stackoverflow_0067830036_pygments_python.txt |
Q:
Monte Carlo Python Question: Simulation of three dice in which the sum > 10, returns True, otherwise return False
This is a Monte Carlo Simulation question. Here is my code.
def simulate():
"""
Simulate three dice and return true if sum is > 10
"""
die_1 = randint(1,6)
die_2 = randint(1, 6)
... | Monte Carlo Python Question: Simulation of three dice in which the sum > 10, returns True, otherwise return False | This is a Monte Carlo Simulation question. Here is my code.
def simulate():
"""
Simulate three dice and return true if sum is > 10
"""
die_1 = randint(1,6)
die_2 = randint(1, 6)
die_3 = randint(1,6)
sum = die_1 + die_2 + die_3
if sum > 10:
return True
else:
return False
... | [
"For checking, you can store all summation result to see whether the occurrence, and probability roughly match your expectation.\nYour code is fine if it is error-free although the indentation is weird. And i suggest not to use 'sum' as a variable name as it is a build in function name. It still works, but this may... | [
0
] | [] | [] | [
"montecarlo",
"python"
] | stackoverflow_0074484774_montecarlo_python.txt |
Q:
Find last duplicate character from string
I have a string abbccdeefght,I want to find the last duplicate character from the string.
For above string the result should be character 'e'.
I tried using Counter from collections module in python.
from collections import Counter
c=Counter('abbccdeefght')
c
>>> Counter(... | Find last duplicate character from string | I have a string abbccdeefght,I want to find the last duplicate character from the string.
For above string the result should be character 'e'.
I tried using Counter from collections module in python.
from collections import Counter
c=Counter('abbccdeefght')
c
>>> Counter({'c': 2, 'b': 2, 'e': 2, 'a': 1, 'd': 1, 'g': 1... | [
"This way you will get index of last duplicate character \ndef last_duplicate(line):\n c=Counter(line)\n #>>> Counter({'c': 2, 'b': 2, 'e': 2, 'a': 1, 'd': 1, 'g': 1, 'f': 1, 'h': 1, 't': 1})\n\n for i, x in reversed(line):\n if c[x] > 1:\n return len(line) - i - 1\n\nSurely you can find ... | [
1,
0,
0,
0,
0,
0
] | [
"I think this I quite pretty solution:\nfrom collections import Counter\nc=dict(Counter('abbccdeefght'))# get counts as dictionary\nlast_duplicate = list(filter(lambda k: c[k] == 2, c.keys()))[-1]#get only duplicates and take the last one\n\n"
] | [
-1
] | [
"python",
"string"
] | stackoverflow_0040452159_python_string.txt |
Q:
Pythonnet cann't load System.IO.Path (.net 6.0)
I use Python 3.10 and Net 6.0. And my C# code call Directory.GetFiles function from System.IO.
When I call dll from python using Pythonnet, it showed cannot load type: System.IO.Path.
Please provide some instructions. Thanks.
A:
from clr_loader import get_coreclr
f... | Pythonnet cann't load System.IO.Path (.net 6.0) | I use Python 3.10 and Net 6.0. And my C# code call Directory.GetFiles function from System.IO.
When I call dll from python using Pythonnet, it showed cannot load type: System.IO.Path.
Please provide some instructions. Thanks.
| [
"from clr_loader import get_coreclr\nfrom pythonnet import set_runtime\nrt = get_coreclr(runtime_config = r\"D:\\runtimeConfig.json\")\nset_runtime(rt)\n\nand json file:\n{\n \"runtimeOptions\": {\n \"tfm\": \"net6.0\",\n \"framework\": {\n \"name\": \"Microsoft.NETCore.App\",\n \"version\": \"6.0.... | [
0
] | [] | [] | [
"c#",
"python",
"python.net"
] | stackoverflow_0074479097_c#_python_python.net.txt |
Q:
Is there a way to list all video URLs of YouTube search results in Python?
I'm using Playwright and BeautifulSoup, I can see important part of the URL (href="/watch?v=5iK4_44i8jU") but have not been able to list it, what am I missing?
# pip install playwright
# playwright install
from playwright.sync_api import s... | Is there a way to list all video URLs of YouTube search results in Python? | I'm using Playwright and BeautifulSoup, I can see important part of the URL (href="/watch?v=5iK4_44i8jU") but have not been able to list it, what am I missing?
# pip install playwright
# playwright install
from playwright.sync_api import sync_playwright
import regex as re
from bs4 import BeautifulSoup
with sync_playw... | [
"I believe you want something like this:\nfor element in soup.find_all(\"a\", {\"class\":\"...\"}):\n print(element['href'])\n\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"playwright",
"python",
"web_scraping"
] | stackoverflow_0074484963_beautifulsoup_playwright_python_web_scraping.txt |
Q:
a password checker with an error i can't find
username ="fay"
password ="321"
user_name = input("What is your username?:")
if user_name==username:
passWord= input("Please enter your password:")
if passWord == password:
print("welcome!")
else:
password_=("please re-enter password:")
else... | a password checker with an error i can't find | username ="fay"
password ="321"
user_name = input("What is your username?:")
if user_name==username:
passWord= input("Please enter your password:")
if passWord == password:
print("welcome!")
else:
password_=("please re-enter password:")
else:
user_name=("please re-enter username:")
#i w... | [] | [] | [
"I think you should to try this:\nusername =\"fay\"\npassword =\"321\"\nuser_name = input(\"What is your username?:\")\nwhile user_name!=username:\n user_name=input(\"please re-enter username:\")\n\npassWord= input(\"Please enter your password:\")\n\nwhile passWord != password:\n passWord=input(\"please re-en... | [
-1
] | [
"python"
] | stackoverflow_0074484949_python.txt |
Q:
how can I turn cell into a dataframe
I have this data:
df['profile'] = {
'symbol': 'AAPL',
'price': 150.72,
'beta': 1.246644,
'volAvg': 89576498,
'mktCap': 2397668846469,
'lastDiv': 0.91,
'range': '129.04-182.94',
'changes': 1.93,
'companyName': 'Apple Inc.',
'curre... | how can I turn cell into a dataframe | I have this data:
df['profile'] = {
'symbol': 'AAPL',
'price': 150.72,
'beta': 1.246644,
'volAvg': 89576498,
'mktCap': 2397668846469,
'lastDiv': 0.91,
'range': '129.04-182.94',
'changes': 1.93,
'companyName': 'Apple Inc.',
'currency': 'USD',
'cik': '0000320193',
... | [
"I guess you have something like this:\ndf = pd.DataFrame({\n 'ID' : 0, \n 'status' : [{\n 'symbol': 'AAPL', \n 'price': 150.72, \n 'beta': 1.246644, \n 'volAvg': 89576498, \n 'mktCap': 2397668846469, \n 'lastDiv': 0.91, \n 'range': '129.04-182.94', \n '... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074484951_dataframe_pandas_python.txt |
Q:
Python, non-blocking pipe, flushing, and missing stdout/stderr
I have two python processes connected by a pipe. The pipe was created with:
read_file_descriptor, write_file_descriptor = os.pipe()
os.set_blocking(read_file_descriptor, False)
os.set_inheritable(read_file_descriptor, True)
The parent process forks of... | Python, non-blocking pipe, flushing, and missing stdout/stderr | I have two python processes connected by a pipe. The pipe was created with:
read_file_descriptor, write_file_descriptor = os.pipe()
os.set_blocking(read_file_descriptor, False)
os.set_inheritable(read_file_descriptor, True)
The parent process forks off a child, and the child reads from the read file descriptor using c... | [
"The problem turned out to be a race condition between two different mechanisms for indicating completion. One mechanism was the termination character, the other was a sigterm handler. The sigterm was sent between when the print statements completed their execution and when the terminating character was written. Si... | [
0
] | [] | [] | [
"file_descriptor",
"io",
"posix",
"python"
] | stackoverflow_0074466173_file_descriptor_io_posix_python.txt |
Q:
Outer join to check existence each records of two pandas dataframes like SQL
I have to tables looks like following:
Table T1
ColumnA
ColumnB
A
1
A
3
B
1
C
2
Table T2
ColumnA
ColumnB
A
1
A
4
B
1
D
2
in SQL I will do following query to check the existence of each record
select
COALESCE(T1.ColumnA,T2.Col... | Outer join to check existence each records of two pandas dataframes like SQL | I have to tables looks like following:
Table T1
ColumnA
ColumnB
A
1
A
3
B
1
C
2
Table T2
ColumnA
ColumnB
A
1
A
4
B
1
D
2
in SQL I will do following query to check the existence of each record
select
COALESCE(T1.ColumnA,T2.ColumnA) as ColumnA
,T1.ColumnB as ExistT1
,T2.ColumnB as Exi... | [
"pd.merge has an indicator parameter that could be helpful here:\n(t1\n.merge(t2, how = 'outer', indicator=True)\n.loc[lambda df: df._merge!=\"both\"]\n.assign(ExistT1 = lambda df: df.ColumnB.where(df._merge.eq('left_only')), \n ExistT2 = lambda df: df.ColumnB.where(df._merge.eq('right_only')) )\n.drop(colum... | [
1,
0
] | [] | [] | [
"merge",
"outer_join",
"pandas",
"python"
] | stackoverflow_0074484411_merge_outer_join_pandas_python.txt |
Q:
Not being able to round float at end of function
I have the code finished up in fact it is entirely done but I just need help at the end of my function for it to return a rounded float.
def average_area(glacier_list):
average=0
Sum=0
for row in glacier_list:
Sum += float(row[9])
... | Not being able to round float at end of function | I have the code finished up in fact it is entirely done but I just need help at the end of my function for it to return a rounded float.
def average_area(glacier_list):
average=0
Sum=0
for row in glacier_list:
Sum += float(row[9])
average = Sum / len(glacier_list)
return average... | [
"You'll want to use round(average, 2) to round the average to the 2nd decimal point, and then convert it to a string and format it to only include 2 characters after the \".\" decimal point, and then convert it back to a float before returning it.\ncredit where it's due: this was a paraphrasing of the best answer o... | [
0
] | [] | [] | [
"for_loop",
"list",
"python"
] | stackoverflow_0074484986_for_loop_list_python.txt |
Q:
Why am I not able to see the random numbers generated using python for large input values?
So I am trying to generate my own adjacency list using random.randint. I am not able to view the output.
Its just few values and then dots. I want to input these values into my algorithm. How to view these generated values.
... | Why am I not able to see the random numbers generated using python for large input values? | So I am trying to generate my own adjacency list using random.randint. I am not able to view the output.
Its just few values and then dots. I want to input these values into my algorithm. How to view these generated values.
This is the output I'am getting.
Thank you for your help!
| [
"The below code should help:\nimport numpy as np\nimport pandas as pd\n\na = np.random.randint(0,2, size=(500,500))\nprint(a)\n\ndf = pd.DataFrame(a)\nprint(df)\ndf.to_csv(\"output.csv\")\n\n"
] | [
0
] | [] | [] | [
"adjacency_matrix",
"python",
"random"
] | stackoverflow_0074485068_adjacency_matrix_python_random.txt |
Q:
How to use QFileDialog to open file with .mid suffix
I have created a subclass for an option to Open File. Alongside PYQT5, I have imported the python library Mido & py-midi in order to read the MIDI files. If my logic is correct. I will use PYQT5's FileDialog in order to retrieve a file, assign it to a variable a... | How to use QFileDialog to open file with .mid suffix | I have created a subclass for an option to Open File. Alongside PYQT5, I have imported the python library Mido & py-midi in order to read the MIDI files. If my logic is correct. I will use PYQT5's FileDialog in order to retrieve a file, assign it to a variable and then use Mido to read that said MIDI file when I Will t... | [
"I believe you're a bit confused on how QFileDialog works.\nFirst of all, by default Qt tries to use the native file dialog the system provides, so generally you should not try to create your own by subclassing, unless you need very special behavior.\nThen, QFileDialog is a QDialog that already has its own (private... | [
1,
0
] | [] | [] | [
"file_extension",
"mido",
"pyqt5",
"python",
"qfiledialog"
] | stackoverflow_0066153996_file_extension_mido_pyqt5_python_qfiledialog.txt |
Q:
pandas Series plot color
I'm writing a generic plotting function that's used in a few different cases. Its input is sometimes a Series, sometimes a DataFrame. Sometimes I specify the plot color, sometimes I want to use the default behavior.
I would think that passing color=None would allow the default color logic ... | pandas Series plot color | I'm writing a generic plotting function that's used in a few different cases. Its input is sometimes a Series, sometimes a DataFrame. Sometimes I specify the plot color, sometimes I want to use the default behavior.
I would think that passing color=None would allow the default color logic to work, but it is not a valid... | [
"If you don't supply color, the function will use default value (i.e. pd.DataFrame([[1, 2, 3]]).plot()).\nIt also seems that neither DataFrame nor Series have a keyword color. So, if you want to supply None use colormap.\n#Both work\npd.Series([1, 2, 3]).plot(colormap=None)\npd.DataFrame([[1, 2, 3]]).plot(colormap=... | [
0
] | [] | [] | [
"pandas",
"plot",
"python"
] | stackoverflow_0074484799_pandas_plot_python.txt |
Q:
Pygame WINDOWRESIZED black screen
I'm trying to resize a window in pygame but only get a black screen. See the before and after pictures below. What am I doing wrong?
import pygame as pg
from pygame.locals import *
pg.init()
yellow = (255, 255, 134)
grey = (142, 142, 142)
square_size = 100
width = 7 * square_s... | Pygame WINDOWRESIZED black screen | I'm trying to resize a window in pygame but only get a black screen. See the before and after pictures below. What am I doing wrong?
import pygame as pg
from pygame.locals import *
pg.init()
yellow = (255, 255, 134)
grey = (142, 142, 142)
square_size = 100
width = 7 * square_size
height = 7 * square_size
radius = i... | [
"You need to redraw the scene after resizing the window. I recommend redrawing the scene in each frame. The typical PyGame application loop has to:\n\nlimit the frames per second to limit CPU usage with pygame.time.Clock.tick\nhandle the events by calling either pygame.event.pump() or pygame.event.get().\nupdate th... | [
1
] | [] | [] | [
"pygame",
"python",
"resize"
] | stackoverflow_0074483012_pygame_python_resize.txt |
Q:
Kernel died restarting whenever training a model
Here's the code:
# import libraries
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# import dataset
from keras.preprocessing.image import Imag... | Kernel died restarting whenever training a model | Here's the code:
# import libraries
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# import dataset
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator()
... | [
"A very cumbersome issue with tensorflow-gpu. It took me days to find the best working solution.\nWhat seems to be the problem:\nI know you might have installed cudnn and cuda (just like me) after watching youtube videos or internet documentation. But since cuda and cudnn are very strict about version clashes so it... | [
4,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0044110799_keras_python_tensorflow.txt |
Q:
SQLalchemy select from postgresql table
I have this model
import os
from dotenv import load_dotenv
from sqlalchemy import Column, Date, Float, Integer, String,Numeric
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import declarative_base, Session
Base = declarative_base()
class MS(Base):
try:... | SQLalchemy select from postgresql table | I have this model
import os
from dotenv import load_dotenv
from sqlalchemy import Column, Date, Float, Integer, String,Numeric
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import declarative_base, Session
Base = declarative_base()
class MS(Base):
try:
__tablename__ = 'ms'
column_not_... | [
"The problem was that PostgreSQL is case-sensitive and the data model was using the upper-case spelling of a column in the table which is all in lower-case (in my case)\nso fixed it as this\n PROVIDER = Column(\"provider\",String) \n\n"
] | [
0
] | [] | [] | [
"orm",
"postgresql",
"python",
"python_3.x",
"sqlalchemy"
] | stackoverflow_0074485023_orm_postgresql_python_python_3.x_sqlalchemy.txt |
Q:
Don't indent first level of tree in a recursive tree printer
I would like to refactor a recursive tree-printing function I wrote so that the root node, the first call, is not indented at all.
Tree = dict[str, 'Tree']
def print_tree(tree: Tree, prefix: str=''):
if not tree:
return
markers = [('├── '... | Don't indent first level of tree in a recursive tree printer | I would like to refactor a recursive tree-printing function I wrote so that the root node, the first call, is not indented at all.
Tree = dict[str, 'Tree']
def print_tree(tree: Tree, prefix: str=''):
if not tree:
return
markers = [('├── ', '│ '), ('└── ', ' ')]
children = list(tree.items())
... | [
"Beautiful algorithm, I like it! (Much better than mine)\nThis is the best I could do with your given restraints:\nTree = dict[str, 'Tree']\ndef print_tree(tree: Tree, prefix: str=None):\n markers = [('├── ', '│ '), ('└── ', ' '), ('', '')]\n for i, (key, subtree) in enumerate(tree.items()):\n is_... | [
1,
0
] | [] | [] | [
"python",
"python_3.x",
"recursion"
] | stackoverflow_0074484283_python_python_3.x_recursion.txt |
Q:
django KeyError: 'some-ForeignKey-field-in-model'
I am very badly stuck on this error for days, and I am unable to understand what it is trying to tell me as it is only 2 words.
The error is coming when I am trying to insert data into the DB table using python manage.py shell
> from app_name.models import Usermana... | django KeyError: 'some-ForeignKey-field-in-model' | I am very badly stuck on this error for days, and I am unable to understand what it is trying to tell me as it is only 2 words.
The error is coming when I am trying to insert data into the DB table using python manage.py shell
> from app_name.models import Usermanagement
> from app_name.models import Inquery
i = Inque... | [
"You probably want to use Usermanagement.objects.get(userid=0) instead of Usermanagement(userid=0)\nTo get an existing foreignkey and not create an instance of a User not saved in the database and thus not reachable\n",
"as answered by @vctrd\nmy query now is :\nInquery ( inqueryid=6, inquerynumber=\"INQ765758499... | [
0,
0
] | [] | [] | [
"django",
"django_models",
"django_orm",
"django_views",
"python"
] | stackoverflow_0074479899_django_django_models_django_orm_django_views_python.txt |
Q:
Find the closing price of stocks in last 90 days using python
Details of Case: There are 161 stocks in excel file, you have to find closing price for these stocks for last 90days
Download files using following links : https://drive.google.com/drive/folders/1utGBygI2vcs0hYlnTpCA_i3Uo8VRj1lH?usp=sharing
File 1: Lis... | Find the closing price of stocks in last 90 days using python | Details of Case: There are 161 stocks in excel file, you have to find closing price for these stocks for last 90days
Download files using following links : https://drive.google.com/drive/folders/1utGBygI2vcs0hYlnTpCA_i3Uo8VRj1lH?usp=sharing
File 1: List of Stocks case study : Symbol of stocks
File 2: Sample Output For... | [
"I think you shoud try pandas_datareader package .\nIt will help you to find a data as you want.\nimport pandas as pd\nfrom pandas_datareader import data\n\nsymbol = 'INFY' # pass the symbol name\nend = pd.datetime.now() # current date and time - can be changed as per requirement\nstart = end - pd.Timedelta(days=90... | [
0
] | [] | [] | [
"excel",
"python",
"stock"
] | stackoverflow_0074484328_excel_python_stock.txt |
Q:
`Building wheel for opencv-python (PEP 517) ... -` runs forever
When I run
!pip install imgaug==0.4.0
the following is the output
Collecting imgaug==0.4.0
Using cached https://files.pythonhosted.org/packages/66/b1/af3142c4a85cba6da9f4ebb5ff4e21e2616309552caca5e8acefe9840622/imgaug-0.4.0-py2.py3-none-any.whl
Req... | `Building wheel for opencv-python (PEP 517) ... -` runs forever | When I run
!pip install imgaug==0.4.0
the following is the output
Collecting imgaug==0.4.0
Using cached https://files.pythonhosted.org/packages/66/b1/af3142c4a85cba6da9f4ebb5ff4e21e2616309552caca5e8acefe9840622/imgaug-0.4.0-py2.py3-none-any.whl
Requirement already satisfied: Pillow in /opt/conda/envs/Python-3.6/lib/... | [
"i had the same problem, everything worked out:\npip install --upgrade pip setuptools wheel\n\n",
"Solve by install openCV-Python explicitly first using\n!pip install opencv-python==4.3.0.38\nIf this version does not exist it would open version that exist.\nThen you can run !pip install imgaug.\nAs the older vers... | [
45,
22,
1,
1,
0
] | [
"pip install opencv-python==4.5.3.56\n\nuse this , its work for me 100%.\nand it will save your time too.\n",
"Small PSA for anyone trying to run the command pip install opencv-contrib-python on a Raspberry Pi.\nIf it seems stuck, know that the installation will take 2 hours.\n",
"try using old version of pytho... | [
-1,
-1,
-5
] | [
"opencv_python",
"python",
"python_3.x"
] | stackoverflow_0063669752_opencv_python_python_python_3.x.txt |
Q:
Python MetaTrader5 indicators
I'm using Metatrader5 module for python and this is my code
'''
#python
from datetime import datetime
import MetaTrader5 as mt5
# display data on the MetaTrader 5 package
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)... | Python MetaTrader5 indicators | I'm using Metatrader5 module for python and this is my code
'''
#python
from datetime import datetime
import MetaTrader5 as mt5
# display data on the MetaTrader 5 package
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)
# import the 'pandas' module for ... | [
"No. Its possible if using other modules though.\nHere is a method using another that could achieve it: \nhttps://www.mql5.com/en/articles/5691\nAlternatively, you can pull the data from MT5 and throw it in TA-lib for analysis. TA-lib consumes the data and provides values for the indicators outside MT5.\nCheck out ... | [
1,
0
] | [] | [] | [
"metatrader5",
"python"
] | stackoverflow_0060404229_metatrader5_python.txt |
Q:
Error trying to migrate my database. Typing error
Sorry but I don't know what is happening when I try to run (python3 manage.py makemigrations).
I really don't know what's going on I'm looking for an answer for a while but I can't figure out where the error is:
(paginas) root@janstar:/home/paginas/proyectodedjango... | Error trying to migrate my database. Typing error | Sorry but I don't know what is happening when I try to run (python3 manage.py makemigrations).
I really don't know what's going on I'm looking for an answer for a while but I can't figure out where the error is:
(paginas) root@janstar:/home/paginas/proyectodedjango# python3 manage.py makemigrations
Traceback (most rece... | [
"In the error message it says that you need a string instead of 'PosixPath' try turning the path into a string.\n",
"You can also use:\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n }\n\n",
"Sim... | [
0,
0,
0
] | [] | [] | [
"django",
"django_database",
"django_settings",
"python"
] | stackoverflow_0074478247_django_django_database_django_settings_python.txt |
Q:
Count the number of tokens/expressions in a Python program
There exist many tools to count the source lines of code in a program. I currently use cloc. I often use this as a proxy to measure complexity of a project I'm working on, and occasionally spend a few weeks trying to minimize this measure. However, it's no... | Count the number of tokens/expressions in a Python program | There exist many tools to count the source lines of code in a program. I currently use cloc. I often use this as a proxy to measure complexity of a project I'm working on, and occasionally spend a few weeks trying to minimize this measure. However, it's not ideal, because it's affected by things like the length of vari... | [
"The line grammar = grammar_path.read_text(encoding=\"UTF-8\") has ten tokens, or eleven if you count the NEWLINE token at the end of the line. You can easily see that, using the generate_tokens method from built-in tokenize standard library module. (Although I use v3.11 in the examples below, the tokenize model ha... | [
1
] | [] | [] | [
"abstract_syntax_tree",
"interpreter",
"parsing",
"python"
] | stackoverflow_0074484976_abstract_syntax_tree_interpreter_parsing_python.txt |
Q:
appending a CSV column to a list using a for loop
Code written by Abdulmalik
import csv
def loadCSVData(filename):
list = [] #list for storing file content
with open(filename, newline='') as file:#
fileContent = csv.DictReader(file)
for line in fileContent:
list.append(line['S... | appending a CSV column to a list using a for loop | Code written by Abdulmalik
import csv
def loadCSVData(filename):
list = [] #list for storing file content
with open(filename, newline='') as file:#
fileContent = csv.DictReader(file)
for line in fileContent:
list.append(line['Score'])
print(list)
fileContent.clo... | [
"You writen print statement inside the loop .That's why it's printing output like this.\nYou need to write print out side from a loop, like this.\nwith open(filename, newline='') as file:# \n fileContent = csv.DictReader(file)\n for line in fileContent:\n list.append(line['Score'])\n print(list)\n ... | [
1
] | [] | [] | [
"csv",
"for_loop",
"list",
"python",
"python_3.x"
] | stackoverflow_0074483539_csv_for_loop_list_python_python_3.x.txt |
Q:
Cant find Funktion Screenshot() from pyautogui is Not find in Visual Studio
I installed the package pyautogui with pip install pyautogui. All functions of this Package worked fine, But when I type „pyautogui.“ there is no Option to choose the function „Screenshot()“. So only the function Screenshot() is Not found... | Cant find Funktion Screenshot() from pyautogui is Not find in Visual Studio | I installed the package pyautogui with pip install pyautogui. All functions of this Package worked fine, But when I type „pyautogui.“ there is no Option to choose the function „Screenshot()“. So only the function Screenshot() is Not found. I dont know where the issue is but I Hope that I can find the Solution here. Th... | [
"One way is to change the language server to Jedi by adding the following configuration in settings.json.\n \"python.languageServer\": \"Jedi\",\n\n\n"
] | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074474688_python_visual_studio_code.txt |
Q:
Pandas Dataframe - Replacing None-like Values with None in All Columns
I need to clean up a dataframe whose columns come from different sources and have different types. This means that I can have, for example, string columns that contain "nan", "none", "NULL", (as a string instead of a None value).
My goal is to ... | Pandas Dataframe - Replacing None-like Values with None in All Columns | I need to clean up a dataframe whose columns come from different sources and have different types. This means that I can have, for example, string columns that contain "nan", "none", "NULL", (as a string instead of a None value).
My goal is to find all empty values and replace them with None. This works fine:
for colum... | [
"This seems to be a somewhat controversial topic (see e.g. this thread) but it's often said that list comprehensions are more computationally efficient than for loops, especially when iterating over pandas dataframes.\nI also prefer using list comprehensions stylistically as it leads to fewer levels of indentation ... | [
1,
1,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074485204_pandas_python.txt |
Q:
How to create a new instance from a class object in Python
I need to dynamically create an instance of a class in Python. Basically I am using the load_module and inspect module to import and load the class into a class object, but I can't figure out how to create an instance of this class object.
A:
I figured o... | How to create a new instance from a class object in Python | I need to dynamically create an instance of a class in Python. Basically I am using the load_module and inspect module to import and load the class into a class object, but I can't figure out how to create an instance of this class object.
| [
"I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.\nclass k:\n pass\n\na = k()\nk2 = a.__class__\na2 = k2()\n\nAt this point, a and a2 are both instances of the same class (class k).\n",
"Just call t... | [
154,
25,
3,
2,
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0005924879_oop_python.txt |
Q:
High/low game in Pycharm
import random
name = input("Enter your name:")
print("Hello and welcome to the game", name + "!")
lower_num = int(input("Enter the Lower bound:"))
print()
higher_num = int(input("Enter the Higher bound:"))
print()
user_num = random.randint(0, 10)
guess_num = int(input())
while True... | High/low game in Pycharm | import random
name = input("Enter your name:")
print("Hello and welcome to the game", name + "!")
lower_num = int(input("Enter the Lower bound:"))
print()
higher_num = int(input("Enter the Higher bound:"))
print()
user_num = random.randint(0, 10)
guess_num = int(input())
while True:
if user_num == guess_nu... | [
"You have to write the input inside the loop. If the person don't guess right num then the loop continue. For this, you need to write 'continue' under the elif. Then he can guess again.\nwhile True:\n guess_num = int(input(\"Guess a number now:\"))\n if user_num == guess_num:\n print('\\n\"You guessed ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074483837_python.txt |
Q:
How to forward a graphic message to a bot and return the text
Some questions about using python-telegram-bot
I'm using python-telegram-bot to create a telegram bot.
I want to forward a graphic message (similar to the one below) to the robot, and the robot removes the image and returns the text.
I didn't find an ex... | How to forward a graphic message to a bot and return the text | Some questions about using python-telegram-bot
I'm using python-telegram-bot to create a telegram bot.
I want to forward a graphic message (similar to the one below) to the robot, and the robot removes the image and returns the text.
I didn't find an example in the official documentation.
I hope someone can help me.
I... | [
"I sloved it\njust use the code below\ndef callback(update: Update, context: CallbackContext):\n print(update.message.caption)\n\nthen python will print out the text\ndon't forget to import CallbackContext and Updater\n"
] | [
0
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram"
] | stackoverflow_0074484764_python_python_telegram_bot_telegram.txt |
Q:
Sqlalchemy dynamic filtering of multiple options
Using SQLAlchemy, I want to query the following SQL-Statement for table 'Tab1' with a column 'Col1':
Select *
from Tab1
where Tab1.Col1 == value1 or Tab1.Col1 == value2
'value1' and 'value2' come from a list which is potentially longer and dynamic.
Following the a... | Sqlalchemy dynamic filtering of multiple options | Using SQLAlchemy, I want to query the following SQL-Statement for table 'Tab1' with a column 'Col1':
Select *
from Tab1
where Tab1.Col1 == value1 or Tab1.Col1 == value2
'value1' and 'value2' come from a list which is potentially longer and dynamic.
Following the answer in here how to dynamic "_or" in filter query sql... | [
"You can pass the comparisons to the or_ function and it will create an expression that will evaluate to COMPARISON0 OR COMPARISON1 OR ...\nfrom sqlalchemy.sql import or_\n\nq_cat = session.query(Tab1).filter(or_(*data_comparisons)).all()\n\n\nAlthough if you are just using equality then I think in_ might be better... | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0074479466_python_sqlalchemy.txt |
Q:
Widget-based web framework in Python (similar to vaadin, GWT or zkoss)
I am basically from Java, but I need to use Python for a new project. I prefer widget based web framework like zkoss, vaadin, GWT etc.
Does python has widget based framework?
A:
You can use Muntjac, it is a semi-automatic translation of vaadi... | Widget-based web framework in Python (similar to vaadin, GWT or zkoss) | I am basically from Java, but I need to use Python for a new project. I prefer widget based web framework like zkoss, vaadin, GWT etc.
Does python has widget based framework?
| [
"You can use Muntjac, it is a semi-automatic translation of vaadin, and depending on your needs about python you just can use jython inside vaadin, but you will lost the 3th party c extesions to python...\n",
"Pyjs is a GWT port in python, and should do what you are looking for.\n",
"Note that Vaadin can be use... | [
3,
1,
1,
1,
0
] | [] | [] | [
"justpy",
"python"
] | stackoverflow_0012963531_justpy_python.txt |
Q:
Selenium and beautiful soup unable to find video tag tag on webpage
I need a web scraping experts help. Im trying to get the src from the video tag of this website. When I try to use selenium or beautifulsoup4 to catch it, its as if doesnt exist. find_elements returns an empty list. This "//*[@id="player"]/div[2]/... | Selenium and beautiful soup unable to find video tag tag on webpage | I need a web scraping experts help. Im trying to get the src from the video tag of this website. When I try to use selenium or beautifulsoup4 to catch it, its as if doesnt exist. find_elements returns an empty list. This "//*[@id="player"]/div[2]/div[3]/video" is the XPATH for that element from inspect elements in safa... | [
"The element can be found using this code:\nvideo = driver.find_element(By.XPATH, '//*[@id=\"player\"]/div[2]/div[3]/video')\n\nBut this element doesn't have the src attribute, so you will not be able to get it from the element. And looks like there is no possibility to get the video from this page.\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074484584_beautifulsoup_html_python_selenium_web_scraping.txt |
Q:
Azure text to speech and play it in virtual microphone using python
My use case is to convert text to speech using Azure and then play it into a virtual microphone.
option 1 - with an intermediate .wav file
I tried both steps manually on a Jupiter notebook.
The problem is, the output .wav file of Azure cannot be ... | Azure text to speech and play it in virtual microphone using python | My use case is to convert text to speech using Azure and then play it into a virtual microphone.
option 1 - with an intermediate .wav file
I tried both steps manually on a Jupiter notebook.
The problem is, the output .wav file of Azure cannot be played directly on the python
"error: No file 'file.wav' found in working... | [
"Create a speech service and get the key and location of the service.\n\nThen set the environment with that key. Open command prompt and use the below code block.\nsetx SPEECH_KEY yourkey\n\nUse import azure.cognitiveservices.speech as speechsdk\nAfter conversion, use the below code block to get the virtual device.... | [
0,
0
] | [] | [] | [
"azure",
"azure_cognitive_services",
"python",
"text_to_speech"
] | stackoverflow_0074376903_azure_azure_cognitive_services_python_text_to_speech.txt |
Q:
MT5 python not returning updated data
MT5 is not returning data for the most recent index
import MetaTrader5 as mt5
mt5.initialize()
import pandas as pd
instrument = mt5.copy_rates_from_pos('BTCUSD',mt5.TIMEFRAME_H1,0,20)
instrument = pd.DataFrame(instrument)
instrument['time'] = pd.to_datetime(instrument['time']... | MT5 python not returning updated data | MT5 is not returning data for the most recent index
import MetaTrader5 as mt5
mt5.initialize()
import pandas as pd
instrument = mt5.copy_rates_from_pos('BTCUSD',mt5.TIMEFRAME_H1,0,20)
instrument = pd.DataFrame(instrument)
instrument['time'] = pd.to_datetime(instrument['time'], unit = 's')
instrument = instrument.set_i... | [
"you can actually update the close price every second if you want to. You have to run it with datetime otherwise you wont return the updated date and time from mt5. and run your function to pull the data from inside loop.\nfrom datetime import datetime\nimport time\nimport MetaTrader5 as mt\nimport pandas as pd\n\n... | [
0
] | [] | [] | [
"metatrader5",
"python"
] | stackoverflow_0074245502_metatrader5_python.txt |
Q:
Efficent way to find index of member in string enum
I have a constant Enum class that looks something like this:
class Animals(Enum):
Dog= 'dog'
Cat= 'cat'
Chicken = 'chicken'
Horse = 'horse'
I need to find a simple and efficient way to find the index of one of the members of the Enum. so I came u... | Efficent way to find index of member in string enum | I have a constant Enum class that looks something like this:
class Animals(Enum):
Dog= 'dog'
Cat= 'cat'
Chicken = 'chicken'
Horse = 'horse'
I need to find a simple and efficient way to find the index of one of the members of the Enum. so I came up with the following oneliner:
list(Animals).index(Animal... | [
"You have a few options:\n\nUse the index values as the values of your Enum, or perhaps IntEnum\n\nclass Animals(Enum):\n Dog= 0\n Cat= 1\n Chicken = 2\n Horse = 3\nAnimals.Chicken.value #returns 2\n\n\nIf you want to keep the textual description too, then subclass Enum, and add the needed attributes (s... | [
0,
0
] | [] | [] | [
"enums",
"performance",
"python"
] | stackoverflow_0074472714_enums_performance_python.txt |
Q:
How to convert HTML tag into string using python
I have my html content as:
html = <div>new notes</div><div><ol><li>kssd</li></ol><ul><li>cds</li><li>dsdsk</li></ul><font color=\"#66717b\">ndsmnd</font></div>
When I convert the above expression to string, it throws error
html_str = str(html)
I can see the " are ... | How to convert HTML tag into string using python | I have my html content as:
html = <div>new notes</div><div><ol><li>kssd</li></ol><ul><li>cds</li><li>dsdsk</li></ul><font color=\"#66717b\">ndsmnd</font></div>
When I convert the above expression to string, it throws error
html_str = str(html)
I can see the " are already escaped here. do I need to replace /" with //"... | [
"I think you need to use get_text()\nfrom bs4 import BeautifulSoup\nhtmlvar = BeautifulSoup(html)\nprint(htmlvar.get_text())\n\n",
"you can try this:\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(html, 'html.parser')\n\nprint(soup.prettify())\n\ntag = soup.html\n\nstring = str(tag)\n\nprint(string)\n\n"
... | [
0,
0
] | [] | [] | [
"html",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074485126_html_python_python_2.7_python_3.x.txt |
Q:
Folium and ColorMap -- is not JSON serializable
The problem in question is: Object of type LinearColormap is not JSON serializable
maps['Zona de tarifa'] = maps['Zona de tarifa'].astype('int')
linear = cm.LinearColormap(["green", "yellow", "red"], vmin=maps['Zona de tarifa'].min(), vmax=maps['Zona de tarifa'].max(... | Folium and ColorMap -- is not JSON serializable | The problem in question is: Object of type LinearColormap is not JSON serializable
maps['Zona de tarifa'] = maps['Zona de tarifa'].astype('int')
linear = cm.LinearColormap(["green", "yellow", "red"], vmin=maps['Zona de tarifa'].min(), vmax=maps['Zona de tarifa'].max())
map = folium.Map(location=[maps.new_latitud.mean(... | [
"Since the colors available for markers are limited, you can color-code them by specifying colors from the color list. We have applied your code using sample data.\nimport folium\nimport pandas as pd\nimport random\n\nmaps = pd.DataFrame({'new_latitud': [random.uniform(36, 43.48) for _ in range(10)],\n ... | [
1
] | [] | [] | [
"colormap",
"folium",
"python"
] | stackoverflow_0074480861_colormap_folium_python.txt |
Q:
Can not retrieve likes and dislikes in youtube with the pytube module
I using pytube library
However, I didn't find functions for getting likes and dislikes in YouTube video
There are functions for fetching title, description, etc. but no functions for fetching channel name or number of likes
i tried this code
fro... | Can not retrieve likes and dislikes in youtube with the pytube module | I using pytube library
However, I didn't find functions for getting likes and dislikes in YouTube video
There are functions for fetching title, description, etc. but no functions for fetching channel name or number of likes
i tried this code
from pytube import YouTube
link = input('Enter your link:')
video = YouTube(li... | [
"For finding views you can use views method the method you are looking for is available in another module named pafy\nfrom pytube import YouTube\nlink =\"https://www.youtube.com/watch?v=1_gXTjBZOms\"\nvideo = YouTube(link)\nprint(f\"The video title is:\\n{video.title} \\n------------------------------\")\nprint(f\"... | [
1,
1,
0
] | [] | [] | [
"python",
"pytube"
] | stackoverflow_0067668286_python_pytube.txt |
Q:
Transpose data from column to row in excel with python
I have many text file Data, and I selected my data from the text and inserted it into one Excel File, but I have one problem:
Data exported in the column, Like below:
David
1253.2500
2568.000
8566.236
Jack
3569.00
5269.22
4586.00
But I want to output the da... | Transpose data from column to row in excel with python | I have many text file Data, and I selected my data from the text and inserted it into one Excel File, but I have one problem:
Data exported in the column, Like below:
David
1253.2500
2568.000
8566.236
Jack
3569.00
5269.22
4586.00
But I want to output the data in rows, like the one below:
David 1253.2500 2568.000 856... | [
"Assuming this input:\ndf = pd.DataFrame({'col': ['David', '1253.2500', '2568.000', '8566.236', 'Jack', '3569.00', '5269.22', '4586.00']})\n\nYou can use:\ns = pd.to_numeric(df['col'], errors='coerce')\nm = s.isna()\n\nout = (df\n .assign(col=df['col'].where(m).ffill(),\n value=s, index=m.groupby(m.cums... | [
0
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"python"
] | stackoverflow_0074485384_dataframe_excel_pandas_python.txt |
Q:
Elasticsearch indexing stops in middle
When i am indexing my data it stops in middle, i have attached screenshot. one thing i have noticed is when ES is not indexing, python start to use swap memory upto 50 GB, and every-time my indexing stops at 54%. Any help is appreciated. Thanks
`
for ok, action in parallel_bu... | Elasticsearch indexing stops in middle | When i am indexing my data it stops in middle, i have attached screenshot. one thing i have noticed is when ES is not indexing, python start to use swap memory upto 50 GB, and every-time my indexing stops at 54%. Any help is appreciated. Thanks
`
for ok, action in parallel_bulk(
client=client,
index=pro... | [
"i have used parallel bulk, to increase indexing speed. Also i had very very huge data set, which i reduced. That helped a lot\nhttps://elasticsearch-py.readthedocs.io/en/7.x/helpers.html#elasticsearch.helpers.parallel_bulk\n"
] | [
0
] | [] | [] | [
"elasticsearch",
"python",
"runtime_error"
] | stackoverflow_0074358258_elasticsearch_python_runtime_error.txt |
Q:
Adding custom title to django form fields
I would like to add custom title to one of my form fields. I made some modifications but it still not working.
My forms.py file
`
from django.forms import ModelForm
from django import forms
from .models import bug
from phonenumber_field.modelfields import PhoneNumberField
... | Adding custom title to django form fields | I would like to add custom title to one of my form fields. I made some modifications but it still not working.
My forms.py file
`
from django.forms import ModelForm
from django import forms
from .models import bug
from phonenumber_field.modelfields import PhoneNumberField
status_choice = [("Pending","Pending"),("Fixe... | [
"In forms.py:\nJust add label directly to form field so:\nfixed_by = forms.CharField(max_length=30, label=\"Fixed by/Assigned to\")\n\n"
] | [
2
] | [] | [] | [
"django",
"django_forms",
"django_models",
"django_templates",
"python"
] | stackoverflow_0074485359_django_django_forms_django_models_django_templates_python.txt |
Q:
How can I save my results in the same file as different columns in case of a 'for-cylce'
def get_df():
df = pd.DataFrame()
os.chdir("C:/Users/s/Desktop/P")
for file in os.listdir():
if file.endswith('.csv'):
av_a = np.average(a, axis=0)
np.savetxt('merged_average.cs... | How can I save my results in the same file as different columns in case of a 'for-cylce' | def get_df():
df = pd.DataFrame()
os.chdir("C:/Users/s/Desktop/P")
for file in os.listdir():
if file.endswith('.csv'):
av_a = np.average(a, axis=0)
np.savetxt('merged_average.csv', av_a, delimiter=',')
I've tried to save it but it always overwrites with the next file an... | [
"At the moment, your code is a bit hard to read, as you are declaring variables which are not used (df) and using variables which are not declared (a). In the future, try to give a minimal reproducible example of your problematic code.\nI'll still try to give you an interpreted answer:\nIf you want to store multipl... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074479757_python.txt |
Q:
AssertionError: Shape of new values must be compatible with manager shape
Error with pandas apply
I have a pandas data frame with following columns
col = ["File_Path", "Function_Body", "Prediction", "Line_Number"]
I am applying get_prediction() function on column Function body and it returns three values
List (P... | AssertionError: Shape of new values must be compatible with manager shape | Error with pandas apply
I have a pandas data frame with following columns
col = ["File_Path", "Function_Body", "Prediction", "Line_Number"]
I am applying get_prediction() function on column Function body and it returns three values
List (Prediction): Ex. [1,1,0,0,0]
List (Confidence): Ex. [64.000, 88.000,0,0,0]
List ... | [
"I also encountered this problem. This is how I solved it\nfinal_df[\"Prediction\"], final_df[\"Confidence\"], c = zip(*final_df[\"Function_Body\"].apply(lambda x:get_prediction(x)))\n\nfinal_df[\"Tokens\"] = list(c)\n\nbecause the output 'c' is a tuple, DataFrame should get a list, so you should convert the tuple... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0062610174_numpy_pandas_python_python_3.x.txt |
Q:
decision boundary for classification
I have trained my machine learning classification model in Python.
For the result analysis when I am trying to draw a decision surface or boundary in google colab using sklearn(scikit-learn) inspection module
from sklearn.inspection import DecisionBoundaryDisplay
I am getting... | decision boundary for classification | I have trained my machine learning classification model in Python.
For the result analysis when I am trying to draw a decision surface or boundary in google colab using sklearn(scikit-learn) inspection module
from sklearn.inspection import DecisionBoundaryDisplay
I am getting the following error.
I have upgraded sk... | [
"sklearn v1.0.2 does not have DecisionBoundaryDisplay: https://scikit-learn.org/1.0/modules/classes.html#module-sklearn.inspection\nsklearn v1.1.3 does: https://scikit-learn.org/stable/modules/classes.html#module-sklearn.inspection\n"
] | [
0
] | [] | [] | [
"analysis",
"classification",
"evaluation",
"python",
"scikit_learn"
] | stackoverflow_0074485529_analysis_classification_evaluation_python_scikit_learn.txt |
Q:
How to not make the program restart after a value error?
So I recently started coding and just learned about 'try' and 'except' for 'ValueError'. I made this calculator but it restarts if you don't input an int on the 'second' input. How do I make it ask for pnly the 'second' variable instead of asking for the fir... | How to not make the program restart after a value error? | So I recently started coding and just learned about 'try' and 'except' for 'ValueError'. I made this calculator but it restarts if you don't input an int on the 'second' input. How do I make it ask for pnly the 'second' variable instead of asking for the first one again?
while True:
try:
first = int(input("... | [
"Use a separate while with try/except blocks for the two prompts. And since you are doing the same thing multiple times, put the common part in a function\ndef get_input(prompt, cast_to=int):\n while True:\n try:\n return cast_to(input(prompt))\n except ValueError:\n print(\"I... | [
3,
1,
1
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0074485597_pycharm_python.txt |
Q:
Putting Result of Multiplication in a List
I am trying to put a series of multiplications inside a list, I am using the code below:
listx = []
for i in range (2):
list = [(3*i)]
listx.append(list)
The problem is that this will put the two results inside two separate lists inside a lists, I just wants the ... | Putting Result of Multiplication in a List | I am trying to put a series of multiplications inside a list, I am using the code below:
listx = []
for i in range (2):
list = [(3*i)]
listx.append(list)
The problem is that this will put the two results inside two separate lists inside a lists, I just wants the floats to be inside the first list.
| [
"listx = []\nfor i in range (2):\n listx.append(3*i)\n\nJust use this one. There is no need to create another list for storing the result. You created another list to store the value and appended that list into your listx\n",
"You can also use list comprehensions. Basically it's the same with for cycles but it... | [
2,
2
] | [] | [] | [
"append",
"list",
"python"
] | stackoverflow_0074485583_append_list_python.txt |
Q:
Is there a better way to get to the file from a python stack trace referencing it?
From a Python stack trace in either Output or Terminal, how to go to the file, or even better, the line where the error was raised? Ctrl-click doesn't respond. I have been doing ctrl-e and type the file name, but is there a faster... | Is there a better way to get to the file from a python stack trace referencing it? | From a Python stack trace in either Output or Terminal, how to go to the file, or even better, the line where the error was raised? Ctrl-click doesn't respond. I have been doing ctrl-e and type the file name, but is there a faster way?
| [
"Using ctrl+click in the terminal can go directly to the error line of the error file.\n\nIf you need to achieve the same effect in the OUTPUT panel you can submit a feature request on GitHub.\n"
] | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074332623_python_visual_studio_code.txt |
Q:
What is the function for Varied amount input data for Python?
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.
Ex: If the input is:
15 20 0 5
the output is:
10 20
nums = []
# initialse
number = 0
# loop... | What is the function for Varied amount input data for Python? | Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.
Ex: If the input is:
15 20 0 5
the output is:
10 20
nums = []
# initialse
number = 0
# loop until there isn't an input
while number != "":
# ask for user inpu... | [
"I solved the problem correctly using this:\nuser_input = input()\n\ntokens = user_input.split() # Split into separate strings\n\nnums = [] \nfor token in tokens: # Convert strings to integers\n nums.append(int(token))\n\navg = sum(nums) / len(nums) # Calculates average of all intege... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0071744679_python.txt |
Q:
In PySimpleGUI, how can I have a hyperlink in a text field?
I am creating a search engine based on this Youtube tutorial which gives the output of the search result in a sg.Output element. I want each result to be clickable and open in Windows File Explorer with the file selected.
My issues is in a PySimpleGUI out... | In PySimpleGUI, how can I have a hyperlink in a text field? | I am creating a search engine based on this Youtube tutorial which gives the output of the search result in a sg.Output element. I want each result to be clickable and open in Windows File Explorer with the file selected.
My issues is in a PySimpleGUI output box (sg.Output) I can only seem to have text.
How can I have ... | [
"It will be much complex to enable hyperlink function for sg.Output or sg.Multiline.\nHere's simple code to provide hyperlink function for sg.Text, also work for some other elements, by using options enable_events=True and tooltip.\n\nimport webbrowser\nimport PySimpleGUI as sg\n\nurls = {\n 'Google':'https://ww... | [
4,
0
] | [] | [] | [
"pysimplegui",
"python"
] | stackoverflow_0066866390_pysimplegui_python.txt |
Q:
python selenium send_keys CONTROL, 'c' not copying actual text
I successfully highlight the section in a web page, but send_keys, .send_keys(Keys.CONTROL, "c"), does not place the intended text to copy in clipboard, only the last thing I manually copied is in clipboard:
from selenium import webdriver
from seleni... | python selenium send_keys CONTROL, 'c' not copying actual text | I successfully highlight the section in a web page, but send_keys, .send_keys(Keys.CONTROL, "c"), does not place the intended text to copy in clipboard, only the last thing I manually copied is in clipboard:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox() ... | [
"Try using the code below:\nInclude the header below to import ActionChains\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n\nactions = ActionChains(driver)\n\nactions.key_down(Keys.CONTROL)\n\nactions.send_keys(\"c\")\n\nactions.key_up(Keys.CONTROL)\n\n",
"Try this:\nfrom selenium import web... | [
7,
4,
3,
1,
0
] | [] | [] | [
"python",
"screen_scraping",
"selenium"
] | stackoverflow_0037763110_python_screen_scraping_selenium.txt |
Q:
How is throttling disabled for testing in Django Rest Framework?
Upon implementing a throttle for a REST API, I'm encountering an issue when running my tests all at once.
Upon isolating the subject TestCase and running the test runner, the TestCase passes its assertions. However when all the tests are ran I get th... | How is throttling disabled for testing in Django Rest Framework? | Upon implementing a throttle for a REST API, I'm encountering an issue when running my tests all at once.
Upon isolating the subject TestCase and running the test runner, the TestCase passes its assertions. However when all the tests are ran I get the following error: AssertionError: 429 != 400. Which that type of erro... | [
"One way to do this is by setting your config files up to support testing versions:\n\n# config.py \n\nREST_FRAMEWORK = {\n 'TEST_REQUEST_DEFAULT_FORMAT': 'json',\n 'DEFAULT_THROTTLE_RATES': {\n 'voting': '5/minute'\n }\n}\n\n\nTESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'\n\nif TESTING:\n ... | [
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python"
] | stackoverflow_0067463665_django_django_rest_framework_python.txt |
Q:
Roblox won't detect mouse movement from autopygui
I am trying to create a script that automatically rejoins a roblox game on disconnect. I have beeen using ctypes to obtain a pixel on the screen, and if the pixel matches a color, it should automatically press the rejoin button. the problem is that it wont press th... | Roblox won't detect mouse movement from autopygui | I am trying to create a script that automatically rejoins a roblox game on disconnect. I have beeen using ctypes to obtain a pixel on the screen, and if the pixel matches a color, it should automatically press the rejoin button. the problem is that it wont press the button. After some troubleshooting, I have figured ou... | [
"Pyautogui has issues with clicking on roblox, but i've found a workaround:\nReplace py.click(button=\"left\") with autoit.mouse_click(\"left\")\n import autoit\n autoit.mouse_click(\"left\")\n\n"
] | [
1
] | [] | [] | [
"pyautogui",
"python",
"roblox"
] | stackoverflow_0074351571_pyautogui_python_roblox.txt |
Q:
pandas read specific table
how can i get only AP ' "EO7" Hardware Information ' table from output like below. can i do this with pandas.
AP "EO7" Basic Information
---------------------------------------
Item Value
---- -----
AP IP Address 11.22.33.44
LMS IP Address ... | pandas read specific table | how can i get only AP ' "EO7" Hardware Information ' table from output like below. can i do this with pandas.
AP "EO7" Basic Information
---------------------------------------
Item Value
---- -----
AP IP Address 11.22.33.44
LMS IP Address 2.2.2.2
Group aa
... | [
"Here is a starting point.\ninfo = {}\ncapture = False\nfor line in open(\"x.txt\"):\n if not capture:\n capture = \"Hardware Information\" in line\n continue\n if \"EO7\" in line:\n break\n if \"Item\" in line:\n f1 = line.find(\"Item\")\n f2 = line.find(\"Value\")\n ... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074428303_pandas_python.txt |
Q:
Reading multiple Json files and combining into one file as per the date in Python
I get JSON extracts throughout a day which is executed for different dates.
As a preprocess step I would like to combine all JSONs with same date and merge them into common file with date as name.
Multiple Json files
tmp/emp1.json
t... | Reading multiple Json files and combining into one file as per the date in Python | I get JSON extracts throughout a day which is executed for different dates.
As a preprocess step I would like to combine all JSONs with same date and merge them into common file with date as name.
Multiple Json files
tmp/emp1.json
tmp/emp2.json
tmp/emp3.json
tmp/emp4.json
tmp/emp5.json
tmp/emp6.json
Format of each js... | [
"Here, is the solution for the issue. I have made one function you just need to pass the input directory path and output directory path. Rest it will handle.\n\nFirst, I converted the JSON into a pandas data frame.\n\nThen grouped them based on the startTime.\n\nAfter that club the data with the same date into the ... | [
2,
1
] | [] | [] | [
"collections",
"dataframe",
"json",
"pandas",
"python"
] | stackoverflow_0074484870_collections_dataframe_json_pandas_python.txt |
Q:
Is there a way to discern an object from the background with OpenCV?
I always wanted to have a device that, from a live camera feed, could detect an object, create a 3D model of it, and then identify it. It would work a lot like the Scanner tool from Subnautica. Imagine my surprise when I found OpenCV, a free-to... | Is there a way to discern an object from the background with OpenCV? | I always wanted to have a device that, from a live camera feed, could detect an object, create a 3D model of it, and then identify it. It would work a lot like the Scanner tool from Subnautica. Imagine my surprise when I found OpenCV, a free-to-use computer vision tool for Python!
My first step is to get the computer... | [
"Welcome to SO and the exiting world of machine vision !\nWhat you are describing is a very classical problem in the field, and not a trivial one at all. It depends heavily on the shape and appearance of what you define as the object of interest and the overall structure, homogeneity and color of the background. Re... | [
0
] | [] | [] | [
"object_detection",
"opencv",
"python"
] | stackoverflow_0074484556_object_detection_opencv_python.txt |
Q:
Python How to find if the given inputted strings can be found inside the second inputted strings?
** I AM NEW TO PYTHON **
I would like to know how to write a function that returns True if the first string, regardless of position, can be found within the second string by using two strings taken from user input. Al... | Python How to find if the given inputted strings can be found inside the second inputted strings? | ** I AM NEW TO PYTHON **
I would like to know how to write a function that returns True if the first string, regardless of position, can be found within the second string by using two strings taken from user input. Also by writing the code, it should not be case sensitive; by using islower() or isupper().
Example Outpu... | [
"Is this what you're looking for?\nstring_1 = input(\"first string: \")\nstring_2 = input(\"second string: \")\n\nif string_1.lower() in string_2.lower(): \n print(True)\nelse:\n print(False)\n\nA \"function\" would be:\ndef check_occuring(substring, string):\n if substring.lower() in string.lower(): \n ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074485862_python.txt |
Q:
What does "bound method" error mean when I call a function?
I am creating a word parsing class and I keep getting a
bound method Word_Parser.sort_word_list of <__main__.Word_Parser instance at 0x1037dd3b0>
error when I run this:
class Word_Parser:
"""docstring for Word_Parser"""
def __init__(self, sentenc... | What does "bound method" error mean when I call a function? | I am creating a word parsing class and I keep getting a
bound method Word_Parser.sort_word_list of <__main__.Word_Parser instance at 0x1037dd3b0>
error when I run this:
class Word_Parser:
"""docstring for Word_Parser"""
def __init__(self, sentences):
self.sentences = sentences
def parser(self):
... | [
"There's no error here. You're printing a function, and that's what functions look like.\nTo actually call the function, you have to put parens after that. You're already doing that above. If you want to print the result of calling the function, just have the function return the value, and put the print there. For ... | [
85,
18,
4,
3,
1,
0,
0,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0013130574_class_python.txt |
Q:
Moviepy write_videofile works the second time but not the first?
I'm concatenating a list of video objects together then writing them with write_videofile, weirdly enough the first time I write the file, it plays fine for the first halfish then the first few frames of each clip in the file afterwards plays before ... | Moviepy write_videofile works the second time but not the first? | I'm concatenating a list of video objects together then writing them with write_videofile, weirdly enough the first time I write the file, it plays fine for the first halfish then the first few frames of each clip in the file afterwards plays before freezing. But here's the odd part, If I write the exact same video obj... | [
"If you cannot consistently replicate the issue, it's most likely not an issue with your code.\nTry opening the produced clip with a different program, such as VLC.\n",
"I came across with the same problem when writting multiple videos at the same time with write_videofile, it seems like the later tasks will caus... | [
0,
0
] | [] | [] | [
"ffmpeg",
"moviepy",
"python",
"video"
] | stackoverflow_0064542559_ffmpeg_moviepy_python_video.txt |
Q:
How I can replace values with src.replace method in pandas?
I want to replace values in certain column.
example of datatable is below,
Name of datatable is df
column1 column2
aaaa cup
bbbb coffee
cccc juice
dddd tea
What I want to this result below
column1 column2
aaaa pink
bbbb brown
... | How I can replace values with src.replace method in pandas? | I want to replace values in certain column.
example of datatable is below,
Name of datatable is df
column1 column2
aaaa cup
bbbb coffee
cccc juice
dddd tea
What I want to this result below
column1 column2
aaaa pink
bbbb brown
cccc orange
dddd white
So I tried this below
df['column2... | [
"We can try using str.replace with a callback function:\nchange_word = {\n 'cup':'pink' ,'coffee':'brown',\n 'juice':'orange','tea':'white'\n}\nregex = r'\\b(?:' + r'|'.join(change_word.keys()) + r')\\b'\ndf[\"column2\"] = df[\"column2\"].str.replace(regex, lambda m: change_word[m.group()], regex=True)\n\n... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074485980_pandas_python.txt |
Q:
I want to convert a list of lists of tuples to list of dictionaries
Input is
[('monday', '09:00:00', '17:00:00'),
('tuesday', '09:00:00', '17:00:00'),
('wednesday', '09:00:00', '17:00:00')]
The needed output is
[{'dayOfweek': 'monday', 'time': ['09:00:00', '17:00:00']},
{'dayOfweek': 'tuesday', 'time': ['09:00... | I want to convert a list of lists of tuples to list of dictionaries | Input is
[('monday', '09:00:00', '17:00:00'),
('tuesday', '09:00:00', '17:00:00'),
('wednesday', '09:00:00', '17:00:00')]
The needed output is
[{'dayOfweek': 'monday', 'time': ['09:00:00', '17:00:00']},
{'dayOfweek': 'tuesday', 'time': ['09:00:00', '17:00:00']},
{'dayOfweek': 'wednesday', 'time': ['09:00:00', '17... | [
"We will use a list comprehension:\nlist1=[('monday', '09:00:00', '17:00:00'), \n('tuesday', '09:00:00', '17:00:00'), \n('wednesday', '09:00:00', '17:00:00')]\n\nwe create a new_list\nnew_list=[{'dayOfweek': list1[i][0], 'time': list(list1[i][1:3])} for i in range(len(list1))]\n\nOutput\n>>> print(new_list)\n\n[{'d... | [
0,
0,
0,
0
] | [] | [] | [
"dictionary",
"dictionary_comprehension",
"list",
"nested_lists",
"python"
] | stackoverflow_0074485821_dictionary_dictionary_comprehension_list_nested_lists_python.txt |
Q:
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python
I am currently working on a project which fills a form automatically. And the next button appears when the form is filled, that's why it gives me an error.
I have trie... | selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python | I am currently working on a project which fills a form automatically. And the next button appears when the form is filled, that's why it gives me an error.
I have tried:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//input[@type='button' and @class='button']")))
Next = driver.find_element_by_x... | [
"If the path of the xpath is right, maybe you can try this method to solve this problem. Replace the old code with the following code:\nbutton = driver.find_element_by_xpath(\"xpath\")\ndriver.execute_script(\"arguments[0].click();\", button)\n\nI solved this problem before, but to be honestly, I don't know the rea... | [
70,
6,
4,
1,
0,
0,
0,
0,
0,
0
] | [
"You could try:\ndriver.execute_script(\"arguments[0].click();\", button)\n\n\nThis solution solved my problems when I faced similar issues.\n"
] | [
-1
] | [
"css_selectors",
"python",
"selenium",
"webdriverwait",
"xpath"
] | stackoverflow_0057741875_css_selectors_python_selenium_webdriverwait_xpath.txt |
Q:
Calculating YTD change for weekly data
I have a table with weekly data like below:
Date
A
B
C
D
1/1/2022
4
5
5
2
1/7/2022
3
5
9
4
1/14/2022
4
8
5
6
1/21/2022
4
6
1
4
I want to create an YTD change table like the below where YTD change is calculated as ('last value of the year' - 'first value of the year') / ... | Calculating YTD change for weekly data | I have a table with weekly data like below:
Date
A
B
C
D
1/1/2022
4
5
5
2
1/7/2022
3
5
9
4
1/14/2022
4
8
5
6
1/21/2022
4
6
1
4
I want to create an YTD change table like the below where YTD change is calculated as ('last value of the year' - 'first value of the year') / 'first value of the year' (i.e.,... | [
"You could achieve this by using groupby with apply (the pct_change method is closely related by can only be applied on consecutive rows in a group).\ndf['Date'] = pd.to_datetime(df['Date'])\ndf = df.sort_values('Date').set_index('Date')\ndf.groupby(df.index.year).apply(lambda x: x.iloc[-1].subtract(x.iloc[0]).div(... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074485885_dataframe_pandas_python.txt |
Q:
Spectral and Spatial Measures of Sharpness - How to calculate slope of magnitude spectrum?
I am trying to implement the S1 measure (Spectral Measure of Sharpness - Section III-A) from this paper. Here we have to calculate slope (alpha) of the magnitude spectrum for an image in order to measure sharpness. I am able... | Spectral and Spatial Measures of Sharpness - How to calculate slope of magnitude spectrum? | I am trying to implement the S1 measure (Spectral Measure of Sharpness - Section III-A) from this paper. Here we have to calculate slope (alpha) of the magnitude spectrum for an image in order to measure sharpness. I am able to write the other part of the algorithm, but unable to calculate the slope. Here is my code. F... | [
"You could check this MATLAB code. See also another MATLAB code.\nAccording to the latter one, we need to know freq and power value, and then we could fit these two var with a linear function, the slope of the line is what we need. We could get the slope with np.polyfit.\nNow, our question is how to get the freq of... | [
0
] | [] | [] | [
"dft",
"fft",
"image_processing",
"python",
"signal_processing"
] | stackoverflow_0054825974_dft_fft_image_processing_python_signal_processing.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.