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:
Using Arduino Ultrasonic Sensor with Pyfirmata
I'm trying to use pyfirmata to use an Arduino Ultrasonic sensor. I used Arduino Uno board and HC-SR04 Ultrasonic sensor. Here is the code I'm using. The code ran smoothly, it's just that it seems the echo pin failed to get an impulse from the trigger ultrasonic sound,... | Using Arduino Ultrasonic Sensor with Pyfirmata | I'm trying to use pyfirmata to use an Arduino Ultrasonic sensor. I used Arduino Uno board and HC-SR04 Ultrasonic sensor. Here is the code I'm using. The code ran smoothly, it's just that it seems the echo pin failed to get an impulse from the trigger ultrasonic sound, so it keeps on getting False (LOW reading) and thus... | [
"I haven't done the exact math but given a range of 50cm you're at about 3ms travel time. That would mean you need to turn off the pulse and poll the pin state within that time.\nThat's not going to happen. The echo probably arrives befor you have turned off the emitter through PyFirmata. You should do the delay me... | [
0,
0,
0
] | [] | [] | [
"arduino",
"arduino_ultra_sonic",
"arduino_uno",
"pyfirmata",
"python"
] | stackoverflow_0074443453_arduino_arduino_ultra_sonic_arduino_uno_pyfirmata_python.txt |
Q:
FastApi returning response take long time and block everything
I got problem with my api FastApi, I got a big request that return me 700k rows. This request take 50 sec to be treat. But, the return response take 2mins and completely block the server who can't handle other request during those 2 mins.
And I don't K... | FastApi returning response take long time and block everything | I got problem with my api FastApi, I got a big request that return me 700k rows. This request take 50 sec to be treat. But, the return response take 2mins and completely block the server who can't handle other request during those 2 mins.
And I don't Know how to handle this ... Here is my code :
@app.get("/request")
as... | [
"You should not make a 700k row database request from FastAPI or any other web server.\nI would update this application logic / query to offload the processing to the database or to an external worker and only make a query for the result.\nAsyncIO prevents the application from blocking while waiting for IO, not pro... | [
1,
0
] | [] | [] | [
"fastapi",
"python"
] | stackoverflow_0072576972_fastapi_python.txt |
Q:
How to use Python Fitz detect Hyphen when using search_for?
I'm new to the Fitz library and am working on a project where I need to find a string in a PDF page. I'm running into a case where the text on the page that I'm searching on is hyphenated. I am aware of the TEXT_DEHYPHENATE flag that I can use in the sear... | How to use Python Fitz detect Hyphen when using search_for? | I'm new to the Fitz library and am working on a project where I need to find a string in a PDF page. I'm running into a case where the text on the page that I'm searching on is hyphenated. I am aware of the TEXT_DEHYPHENATE flag that I can use in the search for function, but that doesn't work for me (as shown in the im... | [
"Your first approach should work, look here:\n# insert some hyphenated text\npage.insert_textbox((100,100,300,300),\"The objective of 'xxx' was design and assemble a low-\\ncost and efficient tool.\")\n157.94699853658676\n\n# now search for it again\npage.search_for(\"lowcost\") # 2 rectangles!\n[Rect(159.30097961... | [
0
] | [] | [] | [
"pymupdf",
"python",
"python_pdfkit",
"python_pdfreader"
] | stackoverflow_0074647583_pymupdf_python_python_pdfkit_python_pdfreader.txt |
Q:
How to get url .pdf + text from ... class + onclick ...
Can someone give me a tip how to find the way?
I need to get link of pdf file + the text("Instructions (DE)") from this tag:
<td class="col-download-data" onclick="openPdf('https://www.roco.cc/static/version1662032330/frontend/Casisoft/Roco/en_GB/doc/AN/1/DE... | How to get url .pdf + text from ... class + onclick ... | Can someone give me a tip how to find the way?
I need to get link of pdf file + the text("Instructions (DE)") from this tag:
<td class="col-download-data" onclick="openPdf('https://www.roco.cc/static/version1662032330/frontend/Casisoft/Roco/en_GB/doc/AN/1/DE/62200-BA_7937.pdf');">Instructions (DE)</td>
No, I am gettin... | [
"for url in productlinks:\n r = requests.get(url, allow_redirects=False)\n content = BeautifulSoup(r.text, 'lxml')\n for tag in content.find_all('a'):\n on_click = tag.get('onclick')\n if on_click:\n pdf = re.findall(r\"'([^']*)'\", on_click)\n print(pdf)\n\n"
] | [
0
] | [] | [] | [
"onclick",
"output",
"pdf",
"python",
"web_scraping"
] | stackoverflow_0074661995_onclick_output_pdf_python_web_scraping.txt |
Q:
Grouping Python dictionaries in hierarchical form with multiple keys?
Here is my list of dicts:
[{'subtopic': 'IAM',
'topic': 'AWS',
'attachments': ['{"workflow.name": "aws_iam_policies_info","workflow.parameters": {"region": "us-east"}}'],
'text': 'Sure! I can help with AWS IAM policies info'},
{'subtopic'... | Grouping Python dictionaries in hierarchical form with multiple keys? | Here is my list of dicts:
[{'subtopic': 'IAM',
'topic': 'AWS',
'attachments': ['{"workflow.name": "aws_iam_policies_info","workflow.parameters": {"region": "us-east"}}'],
'text': 'Sure! I can help with AWS IAM policies info'},
{'subtopic': 'ECS',
'topic': 'AWS',
'attachments': ['{"workflow.name": "aws_ecs_re... | [
"To group the list of dictionaries by topic and subtopic, you can create an empty dictionary and then loop through the list of dictionaries to add each item to the appropriate nested level in the dictionary.\nresult = {}\n\nfor item in data:\n topic = item['topic']\n subtopic = item['subtopic']\n\n if topi... | [
1,
1
] | [] | [] | [
"dictionary",
"itertools_groupby",
"python",
"python_3.x",
"python_itertools"
] | stackoverflow_0074662274_dictionary_itertools_groupby_python_python_3.x_python_itertools.txt |
Q:
How to replace .append with .concat in pandas dataframe?
Here is my code
dataframe = pd.DataFrame(columns = my_columns)
for stock in stocks['Ticker'][:1]:
api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote/?token={IEX_CLOUD_API_TOKEN}'
data = requests.get(api_url).json()
dataframe = da... | How to replace .append with .concat in pandas dataframe? | Here is my code
dataframe = pd.DataFrame(columns = my_columns)
for stock in stocks['Ticker'][:1]:
api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote/?token={IEX_CLOUD_API_TOKEN}'
data = requests.get(api_url).json()
dataframe = dataframe.append(
pd.Series([stock, data['latestPrice'], mar... | [
"dataframe = pd.DataFrame(columns = my_columns)\nfor stock in stocks['Ticker'][:1]:\n api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote/?token={IEX_CLOUD_API_TOKEN}'\n data = requests.get(api_url).json()\n new_row = pd.DataFrame(\n [\n [stock, data[\"latestPrice\"], marketCa... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074662439_dataframe_pandas_python.txt |
Q:
Sympy intersection of FiniteSets with strings
Define two sympy FiniteSet sets a and b with each of them containing only one string element:
a = FiniteSet('red')
b = FiniteSet('yellow')
If I ask for the Intersection of those sets:
Intersection(a,b)
I was expecting to get as result an empty set {}, but I just get ... | Sympy intersection of FiniteSets with strings | Define two sympy FiniteSet sets a and b with each of them containing only one string element:
a = FiniteSet('red')
b = FiniteSet('yellow')
If I ask for the Intersection of those sets:
Intersection(a,b)
I was expecting to get as result an empty set {}, but I just get Intersection({red}, {yellow}).
Why is that?
It work... | [
"The intersection cannot unambiguously give a result for objects which are variables. Your strings became Symbols with color names and a might equal b or it might not. If your elements were 'a+1' and 'a+2' the intersection would be an empty set because those two cannot be the same for finite values.\nIf you intend ... | [
1
] | [] | [] | [
"python",
"set",
"set_theory",
"sympy"
] | stackoverflow_0074662655_python_set_set_theory_sympy.txt |
Q:
Django and adding a static image
Good evening,
I've just completed this tutorial:
https://docs.djangoproject.com/en/4.1/intro/tutorial01/
and I need to add a new directory to display a dataset (unrelated to the polls app)
I've set up my new directory as I did the first steps in the tutorial.
My steps:
...\> py man... | Django and adding a static image | Good evening,
I've just completed this tutorial:
https://docs.djangoproject.com/en/4.1/intro/tutorial01/
and I need to add a new directory to display a dataset (unrelated to the polls app)
I've set up my new directory as I did the first steps in the tutorial.
My steps:
...\> py manage.py startapp newendpoint
newendpo... | [
"Step 1:\n\nInstall pillow\n\n$ pip install pillow\n\nStep 2:\nAdd the model for the image in your apps models.py\n\nclass Imagemodel(models.Model):\n # .....\n pic = models.ImageField(upload_to='images/', null=True) # U can change to `FileField` for files\n\nStep 3:\nMake migrations and migrate:\n$ py manag... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074662462_django_python.txt |
Q:
Call compound.finance api with parameters
I'm trying to simply call the compound.finance api "https://api.compound.finance/api/v2/account" with the parameter max_health. the doc says
"If provided, should be given as { "value": "...string formatted
number..." }".
(https://compound.finance/docs/api#account-service... | Call compound.finance api with parameters | I'm trying to simply call the compound.finance api "https://api.compound.finance/api/v2/account" with the parameter max_health. the doc says
"If provided, should be given as { "value": "...string formatted
number..." }".
(https://compound.finance/docs/api#account-service)
So I tried 4 methods here below:
response = r... | [
"They did not update the API docs. You should send a POST request and provide params as a request body.\nimport json\nimport requests\n\nurl = \"https://api.compound.finance/api/v2/account\"\ndata = {\n \"max_health\": {\"value\": \"1.0\"}\n}\n\nresponse = requests.post(url, data=json.dumps(data)) # <Response [... | [
2,
0
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0072715891_python_python_requests.txt |
Q:
How to change the "shape" of pairplot in Seaborn?
I plotted this pairplot correlating only one features with all the others, how can i visualize it in a better way? I need to visualize 4 columns. In the official documentation of pairplot i can't find the option.
This is the df:
This is the part of the code:
sns.p... | How to change the "shape" of pairplot in Seaborn? | I plotted this pairplot correlating only one features with all the others, how can i visualize it in a better way? I need to visualize 4 columns. In the official documentation of pairplot i can't find the option.
This is the df:
This is the part of the code:
sns.pairplot(data=dftrain,
y_vars=['medv'],
... | [
"The shape of a pairplot can't be changed. But, you can create a similar relplot if you convert the dataframe to long form.\nHere is some simple example code, starting from dummy data:\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.ra... | [
2,
2
] | [] | [] | [
"pairplot",
"pandas",
"python",
"seaborn",
"shapes"
] | stackoverflow_0074662654_pairplot_pandas_python_seaborn_shapes.txt |
Q:
Is there a way to loop through an entire Python script with an Input function?
I have a very basic Blackjack simulator where I input whether I want to Hit or Stay. When I choose it, it then tells me the result. I want to run this over multiple times. Is there a function where after I get the result of the hand, it... | Is there a way to loop through an entire Python script with an Input function? | I have a very basic Blackjack simulator where I input whether I want to Hit or Stay. When I choose it, it then tells me the result. I want to run this over multiple times. Is there a function where after I get the result of the hand, it will restart from the top of the script?
I am using Jupyter notebook and am current... | [
"You can use a basic game play pattern such as the following to do what you want.\n# Function to request input and verify input type is valid\ndef getInput(prompt, respType= None):\n while True:\n resp = input(prompt)\n if respType == str or respType == None:\n break\n else:\n ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074662285_python.txt |
Q:
Python3 find position/index of a name/element in a list with more than one of the same name
I am having a problem that I just don't know how to solve and nothing I'm finding is helping. My problem is that I have a list of names (strings), in this list I will have the same name show up more than once.
lst = ['hello... | Python3 find position/index of a name/element in a list with more than one of the same name | I am having a problem that I just don't know how to solve and nothing I'm finding is helping. My problem is that I have a list of names (strings), in this list I will have the same name show up more than once.
lst = ['hello.com', 'hello.com', 'hello.com', 'world.com', 'test1.com']
index = web_lst.index(domain)+1
print(... | [
"You can get both the index and the element using a for-loop.\nfor i in range(len(lst)):\n element = lst[i]\n if element == domain:\n print(i)\n\nThis should give you all indexes of domain.\nEdited Code:\nd = {}\nc = 0\nfor i in range(len(lst)):\n element = lst[i]\n if element == domain:\n ... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"sqlite3_python"
] | stackoverflow_0074662809_python_python_3.x_sqlite3_python.txt |
Q:
Pagination on pandas dataframe.to_html()
I have a huge pandas dataframe I am converting to html table i.e. dataframe.to_html(), its about 1000 rows. Any easy way to use pagination so that I dont have to scroll the whole 1000 rows. Say, view the first 50 rows then click next to see subsequent 50 rows?
A:
Update 2... | Pagination on pandas dataframe.to_html() | I have a huge pandas dataframe I am converting to html table i.e. dataframe.to_html(), its about 1000 rows. Any easy way to use pagination so that I dont have to scroll the whole 1000 rows. Say, view the first 50 rows then click next to see subsequent 50 rows?
| [
"Update 2022\nIt seems that there is now a simple and modern solution, using itables.\nInstallation:\npip install itables\n\nBasic usage (from the GitHub readme):\nfrom itables import show\n\nshow(df)\n\nResult:\n\nThere is also a command for displaying all tables in the notebook like this by default.\nOriginal ans... | [
13,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0038893448_pandas_python.txt |
Q:
Python - Find x and y values of a 2D gaussian given a value for the function
I have a 2D gaussian function f(x,y). I know the values x₀ and y₀ at which the peak g₀ of the function occurs. But then I want to find xₑ and yₑ values at which f(xₑ, yₑ) = g₀ / e¹. I know there are multiple solutions to this, but at leas... | Python - Find x and y values of a 2D gaussian given a value for the function | I have a 2D gaussian function f(x,y). I know the values x₀ and y₀ at which the peak g₀ of the function occurs. But then I want to find xₑ and yₑ values at which f(xₑ, yₑ) = g₀ / e¹. I know there are multiple solutions to this, but at least one is sufficient.
So far I have
def f(x, y, g0,x0,y0,sigma_x,sigma_y,offset):
... | [
"There are an infinite number of possibilities (or possibly 1 trivial or none in special cases regarding the value of g0). A solution can be computed analytically in constant time using a direct method. No need for approximations or iterative methods to find roots of a given function. It is just pure maths.\nGaussi... | [
2,
1
] | [] | [] | [
"gaussian",
"numpy",
"python"
] | stackoverflow_0074660993_gaussian_numpy_python.txt |
Q:
How do I print values by sections?
How do I print values like this:
I'm making program that returns a store invoice, but I don't know how to print the result like that.
I tried .format but the values don't have the same length.
A:
num = 142
print("This is right-aligned by 10 units. {:>10}".format(num))
| How do I print values by sections? | How do I print values like this:
I'm making program that returns a store invoice, but I don't know how to print the result like that.
I tried .format but the values don't have the same length.
| [
"num = 142\nprint(\"This is right-aligned by 10 units. {:>10}\".format(num))\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074662835_python_python_3.x.txt |
Q:
Why won't the second pushed tile show?
I placed the rectangles over the images. I then bound a click to a call that flipped tiles over by lowering the rectangle below the image. It works for the first call to the function, but when I click another tile, that one won't flip over. The program still registers the sec... | Why won't the second pushed tile show? | I placed the rectangles over the images. I then bound a click to a call that flipped tiles over by lowering the rectangle below the image. It works for the first call to the function, but when I click another tile, that one won't flip over. The program still registers the second flip because it'll flip everything back ... | [
"It is because the update will be performed after chooseTile() returns to tkinter mainloop(). But the images are already reset to lower layer when the function returns, so you cannot see the second selected image.\nThe simple fix is calling self.canvas.update_idletasks() to force the update to show the second sele... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074650846_python_tkinter.txt |
Q:
I have a list of list. Need to merge all the elements that is only "a" letters into a single string, moving the other elements down a position
x1 = ['a','1','2','b','4']
x2 = ['a','a','2','b','4']
x3 = ['a','a','a','b','4']
x4 = ['a','1','2','b','4']
xxxx = x1,x2,x3,x4
name2f = []
for i in xxxx:
a1 = i[0]
... | I have a list of list. Need to merge all the elements that is only "a" letters into a single string, moving the other elements down a position |
x1 = ['a','1','2','b','4']
x2 = ['a','a','2','b','4']
x3 = ['a','a','a','b','4']
x4 = ['a','1','2','b','4']
xxxx = x1,x2,x3,x4
name2f = []
for i in xxxx:
a1 = i[0]
b1 = i[1]
c1 = i[2]
if a1.isalpha:
if b1.isalpha:
if c1.isalpha:
print("false 3")
... | [
"Figured it out, went through the elements as a range and it worked:\n item = []\n for items in xxxx:\n for i in items[0:3]:\n if re.match(r'[A-Z]', i) and bool(re.search(r'[0-9]', i)) == False:\n item.append(i)\n items.remove(i)\n\n w = \" \".join(item)\n pr... | [
1,
0
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0074662229_list_loops_python.txt |
Q:
Add decorator to component decorator in KFP v2 in Vertex AI
Usually, KFP v2 supports adding a component decorator like this:
@component
def test():
print("hello world")
I would like to add an additional decorator to add new functionality like this:
@component
@added_functionality
def test():
print("hello worl... | Add decorator to component decorator in KFP v2 in Vertex AI | Usually, KFP v2 supports adding a component decorator like this:
@component
def test():
print("hello world")
I would like to add an additional decorator to add new functionality like this:
@component
@added_functionality
def test():
print("hello world")
Where added_functionality is imported and looks like this:
f... | [
"You aren't. This is a disappointing limitation of Kubeflow currently.\n"
] | [
0
] | [] | [] | [
"google_cloud_vertex_ai",
"kfp",
"python"
] | stackoverflow_0071959035_google_cloud_vertex_ai_kfp_python.txt |
Q:
Adding edges to Graph by iterating through adjacency matrix
I have this code, which adds edges with a weight to a graph from adjacency matrix:
matrix = [[0, 1, 2, 3, 4],
[1, 0, 5, 6, 0],
[2, 5, 0, 0, 0],
[3, 0, 0, 0, 6],
[4, 0, 0, 6, 0]]
g1 = Graph(len(matrix))
for i in ra... | Adding edges to Graph by iterating through adjacency matrix | I have this code, which adds edges with a weight to a graph from adjacency matrix:
matrix = [[0, 1, 2, 3, 4],
[1, 0, 5, 6, 0],
[2, 5, 0, 0, 0],
[3, 0, 0, 0, 6],
[4, 0, 0, 6, 0]]
g1 = Graph(len(matrix))
for i in range(len(matrix)):
for j in range(len(matrix)):
if ma... | [
"One way to solve this is to add an additional check for the edge that is being added, before actually adding the edge. For example, you can add a check to make sure the edge is not already present in the graph. You can do this by looping through the graph and checking if the edge is already present before adding i... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074663056_python_python_3.x.txt |
Q:
No module named 'tensorflow.tsl'
I'm trying to install Tensorflow. I did the installation using the cmd.exe prompt and the installation was a success. But when I try to import TensorFlow appear the following error
ModuleNotFoundError: No module named 'tensorflow.tsl'
I follow this steps to install tensorflow:
$ p... | No module named 'tensorflow.tsl' | I'm trying to install Tensorflow. I did the installation using the cmd.exe prompt and the installation was a success. But when I try to import TensorFlow appear the following error
ModuleNotFoundError: No module named 'tensorflow.tsl'
I follow this steps to install tensorflow:
$ pip install -U pip
$ pip install tensor... | [
"Check the version of tensorflow-serving-api and update it with\n$ pip install tensorflow-serving-api==X.Y.0\n\nX and Y should match your TensorFlow version. You can determine your TensorFlow version with\n$ pip freeze | grep tensorflow\n\n"
] | [
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074632821_python_tensorflow.txt |
Q:
Why doesn't mean square error work in case of angular data?
Suppose, the following is a dataset for solving a regression problem:
H -9.118 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 7.470 6.452 6.069 6.197 6.434 8.264 9.047 2.222
H 5.488 5.166 4.852 5.164 4.943 8.103 -9.... | Why doesn't mean square error work in case of angular data? | Suppose, the following is a dataset for solving a regression problem:
H -9.118 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 7.470 6.452 6.069 6.197 6.434 8.264 9.047 2.222
H 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 -8.536 6.452 6.069 6.197 6.434 8.264 9.047 11.954 ... | [
"Data that represent angles like 180 degrees, causes problems with most loss functions because they are not meant for radiants. MSE calculates a huge error between 0 and 359 although 0=360. It simply doesn’t understand the concepts of radiants and angles.\nThere are a number of ways to fix this depending on what yo... | [
2,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"mean_square_error",
"neural_network",
"python",
"radians"
] | stackoverflow_0071187809_mean_square_error_neural_network_python_radians.txt |
Q:
Problem with coding multi-frame jump animation (GDScript)
So I am a beginner programmer using GDScript and got stuck with playing jump animation. All my animations are like 2 frames and where easy to code, but my jump is multi-frame and I couldn't find a tutorial to help.
Also I'm not comfortable with anim.tree -s... | Problem with coding multi-frame jump animation (GDScript) | So I am a beginner programmer using GDScript and got stuck with playing jump animation. All my animations are like 2 frames and where easy to code, but my jump is multi-frame and I couldn't find a tutorial to help.
Also I'm not comfortable with anim.tree -s, I prefer to hard code them in.
My code (I know its basic):
ex... | [
"I presume you would insert a line $AnimatedSprite.play(\"jump\") or similar to play your jump animation. Correct?\nThen the issue is that it gets replaced by the \"walk\" (or \"run\") or \"idle\" animation the next frame.\nWell, do you want those animations to play while the character is on the air (not is_on_floo... | [
0
] | [] | [] | [
"animation",
"gdscript",
"godot",
"python"
] | stackoverflow_0074660243_animation_gdscript_godot_python.txt |
Q:
BeautifulSoup find a href in marquee
I'm using bs4 to scrape links from a scrolling marquee. I'm able to get the marquee data, which is returned as a bs4 resultSet element. However, I cannot seem to access the href's within the data.
I'm sure I'm missing something as I'm new to web scraping, and appreciate any gui... | BeautifulSoup find a href in marquee | I'm using bs4 to scrape links from a scrolling marquee. I'm able to get the marquee data, which is returned as a bs4 resultSet element. However, I cannot seem to access the href's within the data.
I'm sure I'm missing something as I'm new to web scraping, and appreciate any guidance anyone has.
Note: I can get the link... | [
"\nI can get the links easy peasy with selenium and chrome driver\n\nProbably because the div with h-48 class is loaded with JavaScript; even if it wasn't, I don't think soup.find('div', class_='h-48') would work because that element has more classes, and you need to pass all of them as class_ [and I don't think so... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074661666_beautifulsoup_python_web_scraping.txt |
Q:
Why doesn't it work I'm trying to make a simple calculator
def add(a, b):
return a + b
print("choose 1 to add and 2 to subtract")
select = input("enter choice 1/2")
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
print(a, "+", b, "=", add(a, b))
I don't kno... | Why doesn't it work I'm trying to make a simple calculator | def add(a, b):
return a + b
print("choose 1 to add and 2 to subtract")
select = input("enter choice 1/2")
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
print(a, "+", b, "=", add(a, b))
I don't know why it doesn't wanna add
| [
"You need to convert the select variable to integer. By default, the input is taken as string value. You can also use f-string (see more at Formatted String Literals documentation) for printing values from variables in the print statement which gives you much more flexibility to format the string:\ndef add(a, b):\n... | [
0,
0,
0,
0
] | [] | [] | [
"calculator",
"python",
"python_3.x"
] | stackoverflow_0074662980_calculator_python_python_3.x.txt |
Q:
By-pass 'Select a Certificate' prompt in Chrome using Selenium (Python)
When going to a specific site and logging in, it then requires me (through a prompt which I can't access the web elements of) to validate it using a specific certificate to authenticate myself. The certificate itself already appears to be load... | By-pass 'Select a Certificate' prompt in Chrome using Selenium (Python) | When going to a specific site and logging in, it then requires me (through a prompt which I can't access the web elements of) to validate it using a specific certificate to authenticate myself. The certificate itself already appears to be loaded but the issue is just submitting / clicking the "Ok" response.
So, I've tr... | [
"I would suggest trying Following :\nfrom selenium.webdriver.chrome.options import Options as ChromeOptions\n\n chrome_options = ChromeOptions()\n chrome_options.add_experimental_option(\n 'prefs', {\n 'required_client_certificate_for_user': <Path_to_certificate>\n }\n )\n\nI got t... | [
0,
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver",
"webdriver"
] | stackoverflow_0074587029_python_selenium_selenium_chromedriver_selenium_webdriver_webdriver.txt |
Q:
Python- Read values from CSV file and add columns values to REST API iteration calls
I'm new to python, I'm reading csv file having 2 columns as ID and Filepath (headers not present). Trying to enter the ID into the URL and filepath into the below rest api call. Can't get the values of the row.
If the value at row... | Python- Read values from CSV file and add columns values to REST API iteration calls | I'm new to python, I'm reading csv file having 2 columns as ID and Filepath (headers not present). Trying to enter the ID into the URL and filepath into the below rest api call. Can't get the values of the row.
If the value at row[0] is TDEVOPS-1 it's returning numeric value.
import csv
filename1 = 'E:\\Upload-PM\\att... | [
"It is not clear to me what is the exact error you are getting. But did you try using format?\nurlvalue = \"https://<url>.atlassian.com/rest/api/3/issue/{}/attachments\".format(row[0])\n\nUPDATE - corresponding to the comments, the issue seems to be with how you read the csv file. Id recommend to use the “r” flag f... | [
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074658350_csv_python.txt |
Q:
Results called before closing connection are not showing / error: sqlite3.ProgrammingError: Cannot operate on a closed database
The following code is throwing the error 'sqlite3.ProgrammingError: Cannot operate on a closed database.'
Considering that I close the connection after the queries are done, I don't under... | Results called before closing connection are not showing / error: sqlite3.ProgrammingError: Cannot operate on a closed database | The following code is throwing the error 'sqlite3.ProgrammingError: Cannot operate on a closed database.'
Considering that I close the connection after the queries are done, I don't understand why this is happening.
import sqlite3
def database():
connection = sqlite3.connect('database.db')
connection.row_facto... | [] | [] | [
"The issue was that i had not added a .fetchall() clause at the end of the query.\nCorrected code:\nimport sqlite3\n\ndef database():\n connection = sqlite3.connect('database.db')\n connection.row_factory = sqlite3.Row\n return connection\n\ndef _index():\n connection = database()\n posts = connectio... | [
-1
] | [
"python",
"sqlite"
] | stackoverflow_0074662203_python_sqlite.txt |
Q:
Python PIL 0.5 opacity, transparency, alpha
Is there any way to make an image half transparent?
the pseudo code is something like this:
from PIL import Image
image = Image.open('image.png')
image = alpha(image, 0.5)
I googled it for a couple of hours but I can't find anything useful.
A:
I realize this question... | Python PIL 0.5 opacity, transparency, alpha | Is there any way to make an image half transparent?
the pseudo code is something like this:
from PIL import Image
image = Image.open('image.png')
image = alpha(image, 0.5)
I googled it for a couple of hours but I can't find anything useful.
| [
"I realize this question is really old, but with the current version of Pillow (v4.2.1), there is a function called putalpha. It seems to work fine for me. I don't know if will work for every situation where you need to change the alpha, but it does work. It sets the alpha value for every pixel in the image. It see... | [
25,
4,
2,
1,
0,
0
] | [] | [] | [
"alpha",
"opacity",
"python",
"python_imaging_library",
"transparency"
] | stackoverflow_0024731035_alpha_opacity_python_python_imaging_library_transparency.txt |
Q:
how to run loader on successful form submission only?
I want that the loader should start ONLY and ONLY when the form has been successfully submitted (instead of just the onclick submit button event that the code does currently). How can I do so?
<div id="loader" class= "lds-dual-ring hidden overlay" >
... | how to run loader on successful form submission only? | I want that the loader should start ONLY and ONLY when the form has been successfully submitted (instead of just the onclick submit button event that the code does currently). How can I do so?
<div id="loader" class= "lds-dual-ring hidden overlay" >
<div class="lds-dual-ring hidden overlay"> </div>
<... | [
"To show the loader when the AJAX call is successful, you can move the code that shows the loader from the click event handler for the submit button to the success callback function in the AJAX call. Here is an example of how you can modify your code to do this:\n$('#submitBtn').click(function () {\n // Submit t... | [
0
] | [] | [] | [
"django",
"flask",
"html",
"javascript",
"python"
] | stackoverflow_0074662942_django_flask_html_javascript_python.txt |
Q:
'numpy.ndarray' object has no attribute 'xaxis' - not sure why
I have the following code.
I am trying to loop through a dataframe 'out' and create a separate subplot for each group and level.
There are 35 groups and 5 levels, producing 175 plots in total.
I thus want to create 5 figures each with 35 subplots (7 ro... | 'numpy.ndarray' object has no attribute 'xaxis' - not sure why | I have the following code.
I am trying to loop through a dataframe 'out' and create a separate subplot for each group and level.
There are 35 groups and 5 levels, producing 175 plots in total.
I thus want to create 5 figures each with 35 subplots (7 rows and 5 columns).
However, when I try to assign specific plots to d... | [
"In fig,axes = plt.subplots(7,5), axes is a 2D array of axes (actually pairs of x, y axes).\nIn sns.lineplot(data=newframe,x='x',y='y',ax=axes[i]) you are passing a 1D array axes[i], not a single axis (pair) as lineplot may expect.\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"loops",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074659542_jupyter_notebook_loops_matplotlib_pandas_python.txt |
Q:
d.py number of bans in a guild
So I tried using embed.add_field(name="Ban Count", value=f"{len(await ctx.guild.bans())} Bans",inline=False)
but I get this error object async_generator can't be used in 'await' expression How do I display the amount of bans?
A:
You must first convert the bans into a list, then g... | d.py number of bans in a guild | So I tried using embed.add_field(name="Ban Count", value=f"{len(await ctx.guild.bans())} Bans",inline=False)
but I get this error object async_generator can't be used in 'await' expression How do I display the amount of bans?
| [
"You must first convert the bans into a list, then get the length of the list:\nbans_list = [entry async for entry in ctx.guild.bans()]\nnumber_of_bans = len(bans_list)\n\n# output number of bans, etc...\n\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074663211_discord_discord.py_python.txt |
Q:
Python program not working - simple mathematic function
cat Prog4CCM.py
numberArray = []
count = 0
#filename = input("Please enter the file name: ")
filename = "t.txt" # for testing purposes
file = open(filename, "r")
for each_line in file:
numberArray.append(each_line)
for i in numberArray:
print(i)
... | Python program not working - simple mathematic function | cat Prog4CCM.py
numberArray = []
count = 0
#filename = input("Please enter the file name: ")
filename = "t.txt" # for testing purposes
file = open(filename, "r")
for each_line in file:
numberArray.append(each_line)
for i in numberArray:
print(i)
count = count + 1
def findMaxValue(numbe... | [
"At a quick glance, the function findFirstOccurence miss return statement. If you want us to help you debug the code in detail, you may need to provide your test data, like t.txt\n",
"You forgot to add a return in the findFirstOccurence() function, in case the vtf response is not in the list and there is an error... | [
1,
1
] | [] | [] | [
"algorithm",
"python",
"python_3.x"
] | stackoverflow_0074663165_algorithm_python_python_3.x.txt |
Q:
(matplot, 3d, plot_surface, Animation) How can I freez z axis from moving in the animaton
I want to make an animation of a drum vibration in python. My problem is that the zero point of the z_axis keeps moving. How can I freeze the z_axis? video link
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
z=sol[0... | (matplot, 3d, plot_surface, Animation) How can I freez z axis from moving in the animaton | I want to make an animation of a drum vibration in python. My problem is that the zero point of the z_axis keeps moving. How can I freeze the z_axis? video link
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
z=sol[0]
def init():
surf,=ax.plot_surface(xv,yv,z0)
ax.set_xlim(0,1)
ax.set_ylim(0,1)
... | [
"I find a solution.\nfig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})\nz=sol[0]\nz0=add_boundry(z[0])\n#surf=ax.plot_surface(np.empty_like(xv),np.empty_like(yv),np.empty_like(z0))\n\ndef init():\n surf=ax.plot_surface(xv,yv,z0)\n ax.set_xlim(0,1)\n ax.set_ylim(0,1)\n ax.set_zlim(-0.2,0.2)\n ... | [
0
] | [] | [] | [
"matplotlib",
"matplotlib_animation",
"python"
] | stackoverflow_0074662936_matplotlib_matplotlib_animation_python.txt |
Q:
XGBoost Error when saving and loading xgboost model using Pickle, JSON and JobLib
I have trained and saved an xgboost regressor model in Jupyter Notebook (Google Colab) and tried to load it in my local machine without success. I have tried to save and load the model in multiple formats: .pkl using pickle library, ... | XGBoost Error when saving and loading xgboost model using Pickle, JSON and JobLib | I have trained and saved an xgboost regressor model in Jupyter Notebook (Google Colab) and tried to load it in my local machine without success. I have tried to save and load the model in multiple formats: .pkl using pickle library, .sav using joblib library or .json.
When I load the model in VS Code, I get the followi... | [
"The issue was a mismatch between the two versions of xgboost when saving the model in Google Colab (xgboost version 0.9) and loading the model in my local Python environment (xgboost version 1.5.1).\nI managed to solve the problem by upgrading my xgboost package to the latest version (xgboost version 1.7.1) both o... | [
0
] | [] | [] | [
"data_science",
"python",
"visual_studio_code",
"xgboost"
] | stackoverflow_0074662799_data_science_python_visual_studio_code_xgboost.txt |
Q:
Sagemaker Regex pattern matching
In Sagemaker validation:auc metric monitor has the following regex
.*\[[0-9]+\].*#011validation-auc:([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?).*
that searches the logs and extracts the matching metrics. I have to log the metrics, so that, they can match the above regex. For this, ... | Sagemaker Regex pattern matching | In Sagemaker validation:auc metric monitor has the following regex
.*\[[0-9]+\].*#011validation-auc:([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?).*
that searches the logs and extracts the matching metrics. I have to log the metrics, so that, they can match the above regex. For this, I tried the following
[2]#011validatio... | [
"I assume you are using a SageMaker Training Job, if you are using the SageMaker SDK you can set metric_definitions in your Estimator object to set the metric's regex.\nKindly see this link for more information: https://docs.aws.amazon.com/sagemaker/latest/dg/training-metrics.html#define-train-metrics\n"
] | [
0
] | [] | [] | [
"amazon_sagemaker",
"python",
"regex"
] | stackoverflow_0074662448_amazon_sagemaker_python_regex.txt |
Q:
How to send specifically an IMAGE file from client to server using Python Paramiko
So I want to send and IMAGE file from client to server using Python Paramiko. For example: .jpeg, .jpg, .png
I don't get an error, but, it does print this message:
Failure
Here is example code:
from PIL import ImageGrab
imp... | How to send specifically an IMAGE file from client to server using Python Paramiko | So I want to send and IMAGE file from client to server using Python Paramiko. For example: .jpeg, .jpg, .png
I don't get an error, but, it does print this message:
Failure
Here is example code:
from PIL import ImageGrab
import paramiko
class Client:
def __init__(self, hostname, username, password)... | [
"Based on the issue post on paramiko github repo, you need to specify the destination parameter to the file name instead of the directory name, such as\nsftp_client.put(\"screenshot.png\", \"/home/screenshot.png\")\n"
] | [
0
] | [] | [] | [
"class",
"function",
"python",
"python_3.x",
"server"
] | stackoverflow_0074663210_class_function_python_python_3.x_server.txt |
Q:
How come a variable in a function is able to reference from outside it's scope?
In this case, the "all_lines" variable is initalised in the context manager, and it is accessible from the function "part_1".
total = 0
with open("advent_input.txt", "r") as txt:
all_lines = []
context_total = 0
for line in... | How come a variable in a function is able to reference from outside it's scope? | In this case, the "all_lines" variable is initalised in the context manager, and it is accessible from the function "part_1".
total = 0
with open("advent_input.txt", "r") as txt:
all_lines = []
context_total = 0
for line in txt:
all_lines.append((line.rstrip().split(" ")))
def part_1():
# tota... | [
"Python does not have general block scope, so anything assigned within the with will be accessible outside of the block.\ncontext_total is different though since you're reassigning it within the function. If you assign within a function, the variable will be treated as a local unless you use global to specify other... | [
1,
0
] | [] | [] | [
"function",
"python",
"scope"
] | stackoverflow_0074663272_function_python_scope.txt |
Q:
How do I close a full-screen matplotlib figure?
How may I close a full-screen matplotlib window? I spawned the figure using:
plt.ion()
fig = plt.figure('Optimizer')
plt.tight_layout()
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
However, plt.close("all") does not seem to do anything, and I couldn'... | How do I close a full-screen matplotlib figure? | How may I close a full-screen matplotlib window? I spawned the figure using:
plt.ion()
fig = plt.figure('Optimizer')
plt.tight_layout()
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
However, plt.close("all") does not seem to do anything, and I couldn't find many things online to try that are relevant to... | [
"Alt F4 does the trick for me (Ubuntu / Windows). But I have not tried it on a Pi.\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0070239693_matplotlib_python.txt |
Q:
Alternatives to .explode() when turning a colum of list into a single colum
So by far whenever I had a dataframe that has a column of list such as the following:
'category_id'
[030000, 010403, 010402, 030604, 234440]
[030000, 010405, 010402, 030604, 033450]
[030000, 010403, 010407, 030604, 030600]
[030000, 010403,... | Alternatives to .explode() when turning a colum of list into a single colum | So by far whenever I had a dataframe that has a column of list such as the following:
'category_id'
[030000, 010403, 010402, 030604, 234440]
[030000, 010405, 010402, 030604, 033450]
[030000, 010403, 010407, 030604, 030600]
[030000, 010403, 010402, 030609, 032600]
Usually whenever I want to make this category_id column... | [
"It might not be the fastest method, but you can simply explode each row of the pandas frame, and combine:\nimport pandas\n\ndf = pandas.DataFrame({\"col1\":[[12,34,12,34,45,56], [12,14,154,6]], \"col2\":['a','b']})\n# col1 col2\n#0 [12, 34, 12, 34, 45, 56] a\n#1 [12, 14, 154, 6] ... | [
0,
0
] | [] | [] | [
"databricks",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074662147_databricks_pandas_pyspark_python.txt |
Q:
How do you use OpenAI Gym 'wrappers' with a custom Gym environment in Ray Tune?
How do you use OpenAI Gym 'wrappers' with a custom Gym environment in Ray Tune?
Let's say I built a Python class called CustomEnv (similar to the 'CartPoleEnv' class used to create the OpenAI Gym "CartPole-v1" environment) to create my... | How do you use OpenAI Gym 'wrappers' with a custom Gym environment in Ray Tune? | How do you use OpenAI Gym 'wrappers' with a custom Gym environment in Ray Tune?
Let's say I built a Python class called CustomEnv (similar to the 'CartPoleEnv' class used to create the OpenAI Gym "CartPole-v1" environment) to create my own (custom) reinforcement learning environment, and I am using tune.run() from Ray ... | [
"I was able to answer my own question about how to get Ray's tune.run() to work with a wrapped custom class for a Gym environment. The documentation for Ray Environments was helpful.\nThe solution was to register the custom class through Ray. Assuming you have defined your Gym wrappers (classes) as discussed abov... | [
0
] | [] | [] | [
"openai_gym",
"python",
"ray",
"tensorflow"
] | stackoverflow_0074637712_openai_gym_python_ray_tensorflow.txt |
Q:
How can I make it so you input a "Worker code" and get the worker details same as when you "print(Worker_36.details)"? - Python
I am new to python and just playing around please help!
Worker_31 = Worker('David', 'Williamson',31 , 92500, 5, 37)
Worker_32 = Worker('Frank', 'Murphy',32 , 58500, 6, 27)
Worker_33 = Wor... | How can I make it so you input a "Worker code" and get the worker details same as when you "print(Worker_36.details)"? - Python | I am new to python and just playing around please help!
Worker_31 = Worker('David', 'Williamson',31 , 92500, 5, 37)
Worker_32 = Worker('Frank', 'Murphy',32 , 58500, 6, 27)
Worker_33 = Worker('Josephine', 'Dover',33 , 69500, 2, 30)
Worker_34 = Worker('Chester', 'Cohen',34 , 88500, 3, 52)
Worker_35 = Worker('Saba', "Bren... | [
"Instead of declaring many separate Worker variables, make a list of them:\nworkers = [\n Worker(...),\n Worker(...),\n Worker(...),\n Worker(...),\n]\n\nAnd then you can refer to workers[36].\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074663319_python.txt |
Q:
SymPy: Replace all ints with floats in expression
Seems like SymPy makes it pretty easy to do the opposite - convert all floats to ints, but I'm curious how to do the reverse?
The specific problem I'm running into is with the RustCodeGen spitting out expressions with mixed f64/int types, which makes the compiler u... | SymPy: Replace all ints with floats in expression | Seems like SymPy makes it pretty easy to do the opposite - convert all floats to ints, but I'm curious how to do the reverse?
The specific problem I'm running into is with the RustCodeGen spitting out expressions with mixed f64/int types, which makes the compiler unhappy.
Any suggestions on ways to get around this prog... | [
"I would recommend faking the integer with a symbol having desired float name:\n>>> f= expr.xreplace({i:Symbol(str(i)+\".\") for i in expr.atoms(Integer)})\n>>> routine = CG.routine(\"\", f, variables, {})\n>>> CG._call_printer(routine)```\n\n"
] | [
0
] | [] | [] | [
"codegen",
"python",
"rust",
"sympy"
] | stackoverflow_0074663159_codegen_python_rust_sympy.txt |
Q:
Close or Switch Tabs in Playwright/Python
I'm doing an automation, at the time of download it opens a tab, sometimes it doesn't close automatically, so how can I close a tab in playwright using python?
A:
I managed to make a code that closes only a specific tab!
all_pages = page.context.pages
await all_pages[1].... | Close or Switch Tabs in Playwright/Python | I'm doing an automation, at the time of download it opens a tab, sometimes it doesn't close automatically, so how can I close a tab in playwright using python?
| [
"I managed to make a code that closes only a specific tab!\nall_pages = page.context.pages\nawait all_pages[1].close()\n\n",
"You can also use the close method on the Page object that represents the tab you want to close. Here is an example of how you might do this:\n# launch a browser and create a new context\nb... | [
1,
0
] | [] | [] | [
"browser",
"playwright",
"playwright_python",
"python",
"tabs"
] | stackoverflow_0073209567_browser_playwright_playwright_python_python_tabs.txt |
Q:
How to create a working progress bar using Bootstrap and Flask
I have simple textarea form, outputs the result below the form, and I'd like to have a progress bar display upon clicking submit.
I've searched else where to no avail and no idea where to start.
Can someone guide this poor soul in the right direction? ... | How to create a working progress bar using Bootstrap and Flask | I have simple textarea form, outputs the result below the form, and I'd like to have a progress bar display upon clicking submit.
I've searched else where to no avail and no idea where to start.
Can someone guide this poor soul in the right direction? (novice by the way)
| [
"First, you will need to create a Flask route that returns the current progress value. This route can be called using an AJAX request from the progress bar element to update the progress bar value dynamically.\nfrom flask import Flask, jsonify\n\napp = Flask(__name__)\n\n@app.route('/progress')\ndef progress():\n ... | [
0
] | [] | [] | [
"bootstrap_5",
"python"
] | stackoverflow_0074662867_bootstrap_5_python.txt |
Q:
How to update new line colours in Plotly from a button click and access results?
I want to plot an image, draw freehand over the image, then be able to press a custom button so that freehand drawing is now in a different colour. I cannot figure out how to make the button press change the line colour though.
The co... | How to update new line colours in Plotly from a button click and access results? | I want to plot an image, draw freehand over the image, then be able to press a custom button so that freehand drawing is now in a different colour. I cannot figure out how to make the button press change the line colour though.
The code I have tried is here below. I've tried using all four button methods described in t... | [
"If I understand correctly, you want all of the drawn lines to change color when the button is selected.\nI've got two solutions for you.\nThe first doesn't do exactly what you're asking for, but it's entirely in Python. Instead of changing the last line drawn, all subsequent lines are drawn with the selected color... | [
0
] | [] | [] | [
"google_colaboratory",
"interactive",
"plotly",
"python"
] | stackoverflow_0074659489_google_colaboratory_interactive_plotly_python.txt |
Q:
Swap position of keys in a dictionary for same value
I have a dictionary
cost = {
(0,1):70,
(0,2):40,
(1,2):65
}
I would like a dictionary where the values for the opposite keys are also the same. To clarify,
(0,1):70 is also the same as (1,0):70
I tried to flip the values of the k... | Swap position of keys in a dictionary for same value | I have a dictionary
cost = {
(0,1):70,
(0,2):40,
(1,2):65
}
I would like a dictionary where the values for the opposite keys are also the same. To clarify,
(0,1):70 is also the same as (1,0):70
I tried to flip the values of the keys using this:
for i,j in cost.keys():
cost [j,i]==co... | [
"Try this code snippet, to see if that's what you want:\n# make a new dict to reflect the swap keys:\ncost1 = {}\n\nfor key, val in cost.items():\n x, y = key # unpack the key\n cost1[(y, x)] = val # swap x, y - tuple as the new key\n \nprint(cost1)\n# {(1, 0): 70, (2, 0): 40, (2, 1): 65... | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074663417_dictionary_python.txt |
Q:
Is there a way to format a json byte array and write it to a file?
I have a byte array that I made, and I am writing it to a json file. This works, but I want to have a formatted JSON file instead of a massive wall of text.
I have tried decoding the byte array with utf-8, but instead I get UnicodeDecodeError: 'utf... | Is there a way to format a json byte array and write it to a file? | I have a byte array that I made, and I am writing it to a json file. This works, but I want to have a formatted JSON file instead of a massive wall of text.
I have tried decoding the byte array with utf-8, but instead I get UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte. My p... | [
"The error is that you are trying to pass then bytes, and json.dumps() is trying to serialize them somehow, but can't, which is written in the error output.\nTo save the file in JSON you need to translate the byte stream into a Python dictionary, which will already accept JSON perfectly and without problems.\nIt wo... | [
0,
0
] | [] | [] | [
"arrays",
"json",
"python"
] | stackoverflow_0074663109_arrays_json_python.txt |
Q:
How to call a Python function from Node.js
I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application to make use of the power of machine learning libraries?
A:
Easiest way I know of is to use "child... | How to call a Python function from Node.js | I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application to make use of the power of machine learning libraries?
| [
"Easiest way I know of is to use \"child_process\" package which comes packaged with node.\nThen you can do something like:\nconst spawn = require(\"child_process\").spawn;\nconst pythonProcess = spawn('python',[\"path/to/script.py\", arg1, arg2, ...]);\n\nThen all you have to do is make sure that you import sys in... | [
357,
201,
55,
15,
10,
9,
4,
3,
3,
2,
0,
0
] | [] | [] | [
"express",
"node.js",
"python"
] | stackoverflow_0023450534_express_node.js_python.txt |
Q:
Create new column using custom function pandas df error
I want to create a new column which gives every row a category based on their value in one specific column. Here is the function:
def assign_category(df):
if df['AvgVAA'] >= -4:
return 'Elite'
elif df['AvgVAA'] <= -4 and df['AvgVAA'] > -4.5:
retur... | Create new column using custom function pandas df error | I want to create a new column which gives every row a category based on their value in one specific column. Here is the function:
def assign_category(df):
if df['AvgVAA'] >= -4:
return 'Elite'
elif df['AvgVAA'] <= -4 and df['AvgVAA'] > -4.5:
return 'Above Average'
elif df['AvgVAA'] <= -4.5 and df['AvgVAA'... | [
"You're so close. Instead of:\ndf_upd.apply(assign_category(df_upd), axis = 1)\n\nUse:\ndf_upd.apply(assign_category, axis = 1)\n\nIn the updated approach, you are applying the function to df_upd (as intended), whereas in the original approach, you are essentially doing:\nx = assign_category(df)\ndf.apply(x, axis =... | [
2
] | [] | [] | [
"apply",
"function",
"pandas",
"python"
] | stackoverflow_0074663358_apply_function_pandas_python.txt |
Q:
How do I separate text after using BeautifulSoup in order to plot?
I am trying to make a program that scrapes the data from open insider and take that data and plot it. Open insider shows what insiders of the company are buying or selling the stock. I want to be able to show, in an easy to read format, what compan... | How do I separate text after using BeautifulSoup in order to plot? | I am trying to make a program that scrapes the data from open insider and take that data and plot it. Open insider shows what insiders of the company are buying or selling the stock. I want to be able to show, in an easy to read format, what company, insider type and how much of the stock was purchased.
Here is my code... | [
"What Julian said then store values in a dict, load it into a Pandas dataframe and visualize it with plotly.express.\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0074663423_beautifulsoup_python.txt |
Q:
What is a pandas.core.Frame.DataFrame, and how to convert it to pd.DataFrame?
Currently I was trying to do a machine learning classification of 6 time series datasets (in .csv format) using MiniRocket, an sktime machine learning package. However, when I imported the .csv files using pd.read_csv and run them throug... | What is a pandas.core.Frame.DataFrame, and how to convert it to pd.DataFrame? | Currently I was trying to do a machine learning classification of 6 time series datasets (in .csv format) using MiniRocket, an sktime machine learning package. However, when I imported the .csv files using pd.read_csv and run them through MiniRocket, the error "TypeError: X must be in an sktime compatible format" pops ... | [
"If you just take the values from your old DataFrame with .values, you can create a new DataFrame the standard way. If you want to keep the same columns and index values, just set those when you declare your new DataFrame.\ndf_new = pd.DataFrame(df_old.values, columns=df_old.columns, index=df_old.index)\n\n",
"Mo... | [
0,
0
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074663328_csv_dataframe_pandas_python_python_3.x.txt |
Q:
What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?
What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?
In my opinion, 'VALID' means there will be no zero padding outside the edges when we do max pool.
According to A guide to convolutio... | What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow? | What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?
In my opinion, 'VALID' means there will be no zero padding outside the edges when we do max pool.
According to A guide to convolution arithmetic for deep learning, it says that there will be no padding in pool operator, i.e. jus... | [
"If you like ascii art:\n\n\"VALID\" = without padding:\n inputs: 1 2 3 4 5 6 7 8 9 10 11 (12 13)\n |________________| dropped\n |_________________|\n\n\"SAME\" = with zero padding:\n pad| ... | [
748,
200,
187,
106,
80,
59,
38,
28,
13,
12,
12,
9,
9,
9,
2,
1,
0
] | [] | [] | [
"deep_learning",
"python",
"tensorflow"
] | stackoverflow_0037674306_deep_learning_python_tensorflow.txt |
Q:
How to pass a parameter from client side to server in python
I am using flask and flask-restx try to create a protocol to get a specific string from another service. I am wonder if there is a way I can pass the parameter from another function to server side.
For example, here's my server side:
from flask_restx imp... | How to pass a parameter from client side to server in python | I am using flask and flask-restx try to create a protocol to get a specific string from another service. I am wonder if there is a way I can pass the parameter from another function to server side.
For example, here's my server side:
from flask_restx import Api,fields,Resource
from flask import Flask
app = Flask(__name... | [
"You can use request parameters or the request body to pass in data to your endpoints. For example, you could define your endpoint like this:\n@api.route('/language')\nclass Language(Resource):\n @api.marshal_with(parent)\n @api.response(403, \"Unauthorized\")\n def get(self):\n a = request.args.get... | [
0,
0
] | [] | [] | [
"flask",
"flask_restplus",
"flask_restx",
"python"
] | stackoverflow_0074663441_flask_flask_restplus_flask_restx_python.txt |
Q:
ValueError when trying to write a for loop in python
When I run this:
import pandas as pd
data = {'id': ['earn', 'earn','lose', 'earn'],
'game': ['darts', 'balloons', 'balloons', 'darts']
}
df = pd.DataFrame(data)
print(df)
print(df.loc[[1],['id']] == 'earn')
The output is:
id game
0 earn dart... | ValueError when trying to write a for loop in python | When I run this:
import pandas as pd
data = {'id': ['earn', 'earn','lose', 'earn'],
'game': ['darts', 'balloons', 'balloons', 'darts']
}
df = pd.DataFrame(data)
print(df)
print(df.loc[[1],['id']] == 'earn')
The output is:
id game
0 earn darts
1 earn balloons
2 lose balloons
3 earn darts
i... | [
"for i,row in df.iterrows():\n if row.id == \"earn\":\n print(\"yes\")\n\n",
"Its complicated. pandas is geared towards operating on entire groups of data, not individual cells. df.loc may create a new DataFrame, a Series or a single value, depending on how its indexed. And those produce DataFrame, Seri... | [
1,
0
] | [] | [] | [
"loops",
"python",
"valueerror"
] | stackoverflow_0074663367_loops_python_valueerror.txt |
Q:
I am trying to figure out a grading system and cant seem to get it to work (python)
i have a problem which i am trying to solve and cant for the life of me figure it out. I feel like its the simplest answer but yet i'm still stuck.
The instructions stated that the application must do the following:
Ask the user to... | I am trying to figure out a grading system and cant seem to get it to work (python) | i have a problem which i am trying to solve and cant for the life of me figure it out. I feel like its the simplest answer but yet i'm still stuck.
The instructions stated that the application must do the following:
Ask the user to input the marks for the five subjects in a list/array.
The program must ensure that the ... | [
"Firstly, you can use a while loop so that you don't have to manually copy & paste for each mark. e.g.:\nmarksList = []\ni = 1\n\nwhile len(marksList) < 5:\n mark = int(input(f\"Input mark {i}\"))\n if 0 <= mark <= 100:\n print(\"Mark is acceptable\")\n marksList.append(mark)\n i += 1\n ... | [
0,
0,
0
] | [
"We can use the map function for the input. Map syntax looks like this: map(function, iter). By replacing function with int. We apply int to each element in input().split()\nAssuming all marks have to be between 0-100, we can use all() which checks if all items in a list are True. If x == True, we then print our re... | [
-1
] | [
"python"
] | stackoverflow_0074663209_python.txt |
Q:
How to add a cooldown time in between commands so that user's can't spam my bot with commands
Like the title says. I need to make a way to force users to wait maybe 15 or 30 seconds between commands. So if they run it again it will let them know how much longer they need to wait.
A:
I figured it out by referenci... | How to add a cooldown time in between commands so that user's can't spam my bot with commands | Like the title says. I need to make a way to force users to wait maybe 15 or 30 seconds between commands. So if they run it again it will let them know how much longer they need to wait.
| [
"I figured it out by referencing the following code:\nfrom time import time\n\nMAX_USAGE = 5\n\n\nasync def callback(update: Update, context: ContextTypes.DEFAULT_TYPE):\n count = context.user_data.get(\"usageCount\", 0)\n restrict_since = context.user_data.get(\"restrictSince\", 0)\n\n if restrict_since:\... | [
0
] | [] | [] | [
"python",
"python_telegram_bot"
] | stackoverflow_0074661186_python_python_telegram_bot.txt |
Q:
storing a variable from turtle.onclick(turtle.textinput())
I'm trying to program a slidepuzzle game and I've been given several potential files to load. The files need to be loaded from a clickable button within turtle itself. Ive written the following code-
def button_click(x,y):
if (x > 247 and x < 315) and ... | storing a variable from turtle.onclick(turtle.textinput()) | I'm trying to program a slidepuzzle game and I've been given several potential files to load. The files need to be loaded from a clickable button within turtle itself. Ive written the following code-
def button_click(x,y):
if (x > 247 and x < 315) and (y > -292 and y < -246): #exit on click exit
turtle.oncl... | [
"load has now successfully become a variable, I just had to remove the turtle.onclick- now the code looks like this.\ndef button_click(x,y):\nif (x > 247 and x < 315) and (y > -292 and y < -246): #exit on click exit\n turtle.onclick(quit(1))\nelif (x > 143 and x < 213) and (y > -302 and y < -236): #load on click... | [
0
] | [] | [] | [
"python",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074663018_python_python_turtle_turtle_graphics.txt |
Q:
how to extract data from the database and pass it to the function in Django
I`m beginner Django user, please help me. I have multiple records in a sqlite3 data table. Please tell me how to read this data from the database in Django and write it to the views.py function.
This is my models.py
class Value(models.Mode... | how to extract data from the database and pass it to the function in Django | I`m beginner Django user, please help me. I have multiple records in a sqlite3 data table. Please tell me how to read this data from the database in Django and write it to the views.py function.
This is my models.py
class Value(models.Model):
capacity = models.FloatField('Емкость конденсатора')
amplitude = mode... | [
"\n#views.py\n\nfrom models import Value\n\n#in the view\nvals = Value.objects.all()\nfor v in vals:\n c = v.capacity #and so on\n\n"
] | [
1
] | [] | [] | [
"django",
"python",
"sqlite"
] | stackoverflow_0074662676_django_python_sqlite.txt |
Q:
CSV using '-' as NULL. Error to convert column to INT
I have a CSV
df = pd.read_csv('data.csv')
Table:
Column A
Column B
Column C
4068744
-1472525
2596219
198366
-
-
The file is using '-' for nul values
I tried converting to int without handling that '-'.
My question is: how do I strip the string '-' without ... | CSV using '-' as NULL. Error to convert column to INT | I have a CSV
df = pd.read_csv('data.csv')
Table:
Column A
Column B
Column C
4068744
-1472525
2596219
198366
-
-
The file is using '-' for nul values
I tried converting to int without handling that '-'.
My question is: how do I strip the string '-' without changing the negative values?
df['Column B'] = df... | [
"Higher version of pandas can hold integer dtypes with missing values. Normal int conversion doesn't support null values.\n# replace - with null\ndf.replace('-', pd.NA, inplace=True)\n# and use Int surrounding with ''\ndf['Column B'] = df['Column B'].astype('Int64')\n\noutput:\n> df\n\n Column A Column B Column C... | [
0
] | [] | [] | [
"dataframe",
"nul",
"pandas",
"python"
] | stackoverflow_0074663597_dataframe_nul_pandas_python.txt |
Q:
How do I fix TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'?
I'm trying to remake Tic-Tac-Toe on python. But, it wont work.
I tried
`
game_board = ['_'] * 9
print(game_board[0]) + " | " + (game_board[1]) + ' | ' + (game_board[2])
print(game_board[3]) + ' | ' + (game_board[4]) + ' | ' + (game_bo... | How do I fix TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'? | I'm trying to remake Tic-Tac-Toe on python. But, it wont work.
I tried
`
game_board = ['_'] * 9
print(game_board[0]) + " | " + (game_board[1]) + ' | ' + (game_board[2])
print(game_board[3]) + ' | ' + (game_board[4]) + ' | ' + (game_board[5])
print(game_board[6]) + ' | ' + (game_board[7]) + ' | ' + (game_board[8])
`
bu... | [
"Is this you want..!?\nCode:-\ngame_board = ['_']*9\nprint(game_board[0]+\" | \"+(game_board[1])+' | '+(game_board[2]))\nprint(game_board[3]+' | '+(game_board[4])+' | '+(game_board[5]))\nprint(game_board[6]+' | '+(game_board[7])+' | '+(game_board[8]))\n\nOutput:-\n_ | _ | _\n_ | _ | _\n_ | _ | _\n\n",
"This is be... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074663591_python.txt |
Q:
How can I count the digits of a number with leading zeroes in python
In a number without leading zeroes I would do this
import math
num = 1001
digits = int(math.log10(num))+1
print (digits)
>>> 4
but if use a number with leading zeroes like "0001" I get
SyntaxError: leading zeros in decimal integer literals are ... | How can I count the digits of a number with leading zeroes in python | In a number without leading zeroes I would do this
import math
num = 1001
digits = int(math.log10(num))+1
print (digits)
>>> 4
but if use a number with leading zeroes like "0001" I get
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
I would like to be able... | [
"You can't reasonably have a number with leading digits unless it's a string!\nTherefore, if you're accepting a string, just remove them and check the difference in length\n>>> value = input(\"enter a number: \")\nenter a number: 0001\n>>> value_clean = value.lstrip(\"0\")\n>>> leading_zeros = len(value) ... | [
1,
0
] | [] | [] | [
"digits",
"python"
] | stackoverflow_0074663343_digits_python.txt |
Q:
getting tensorflow to run on GPU
I've been trying to get this to work forever and still no luck
I have:
GTX 1050 Ti (on Lenovo Legion laptop)
the laptop also has an Intel UHD Graphics 630 (i'm not sure if maybe this is interfering?)
Anaconda
Visual Studio
Python 3.9.13
CUDA 11.2
cuDNN 8.1
I added these to the PAT... | getting tensorflow to run on GPU | I've been trying to get this to work forever and still no luck
I have:
GTX 1050 Ti (on Lenovo Legion laptop)
the laptop also has an Intel UHD Graphics 630 (i'm not sure if maybe this is interfering?)
Anaconda
Visual Studio
Python 3.9.13
CUDA 11.2
cuDNN 8.1
I added these to the PATH:
C:\Program Files\NVIDIA GPU Computi... | [
"You can upgrade tensorflow to 2.0. It should solve your problem.\n",
"Check your tensorflow version and compatability with GPU, update your GPU drivers. CUDA 9/10 would do the job.\nfollow the official tensorflow link:\nhttps://www.tensorflow.org/install/pip#windows-native_1\nDo all the steps in the same environ... | [
0,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074663667_python_tensorflow.txt |
Q:
How to get the scoreboard to work in Turtle Graphics?
**I just need to update the score constantly when the ball crashes into the platform.
What also I do not know is how to clone the ball to make multiple balls in the arena
If anyone can give some input that would be great also
Here is the code I have:**
import t... | How to get the scoreboard to work in Turtle Graphics? | **I just need to update the score constantly when the ball crashes into the platform.
What also I do not know is how to clone the ball to make multiple balls in the arena
If anyone can give some input that would be great also
Here is the code I have:**
import turtle
import random
from random import randint
import time
... | [
"To create a scoreboard in this code, you can add a variable to keep track of the score and display it on the screen. Here is how you can do that:\nAdd a variable to keep track of the score. You can do this by adding the following line at the top of the code, after the import statements:\nscore = 0\n\nAdd code to u... | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_turtle",
"turtle_graphics"
] | stackoverflow_0074663758_python_python_3.x_python_turtle_turtle_graphics.txt |
Q:
I don't understand why my class variables are undefined and can't be accessed
I am trying to create a poker game in python using classes. the first thing i am trying to do is to create a deck. this is my code :
class Poker:
rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']
suit = ["D", "C", "S",... | I don't understand why my class variables are undefined and can't be accessed | I am trying to create a poker game in python using classes. the first thing i am trying to do is to create a deck. this is my code :
class Poker:
rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']
suit = ["D", "C", "S", "H"]
original_deck = [(i + j) for i in rank for j in suit]
def __init__(se... | [
"Use self to reference class attributes. In Python, class attributes should be accessed using the self keyword. This makes the code more readable and helps avoid naming conflicts. You can modify your code to use self to reference the rank and suit attributes like this:\nclass Poker:\n rank = ['A','2','3','4','5'... | [
1
] | [] | [] | [
"class",
"oop",
"python",
"python_3.x",
"scope"
] | stackoverflow_0074663772_class_oop_python_python_3.x_scope.txt |
Q:
How do I create a function that will end the program?
I have difficulties creating a counter (which is errorCount) for my while loop statement. I want my counter to function so that if the user answered a question incorrectly 5 times the program will terminate. furthermore, I have 3 questions for the user and I wa... | How do I create a function that will end the program? | I have difficulties creating a counter (which is errorCount) for my while loop statement. I want my counter to function so that if the user answered a question incorrectly 5 times the program will terminate. furthermore, I have 3 questions for the user and I want to accumulate all the errorCounts so that if it hit 5 th... | [
"You have overly complicated the code.\nquestions = [\"You have the jewel in your possession, and defeated Joker at his own game\",\n\"You now hold the precious jewel in your hands, but it's not over, you must leave the maze!\",\n\"*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep tryin... | [
0,
0
] | [] | [] | [
"for_loop",
"if_statement",
"python",
"spyder",
"while_loop"
] | stackoverflow_0074663626_for_loop_if_statement_python_spyder_while_loop.txt |
Q:
reviews of a firm
My goal is to scrape the entire reviews of this firm. I tried manipulating @Driftr95 codes:
def extract(pg):
headers = {'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'}
url = f'https://www.glassdoor.com/Revi... | reviews of a firm | My goal is to scrape the entire reviews of this firm. I tried manipulating @Driftr95 codes:
def extract(pg):
headers = {'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'}
url = f'https://www.glassdoor.com/Reviews/3M-Reviews-E446_P{p... | [
"\nAll four subratings will turn out to be N.A.\n\nthere were some things that I didn't account for because I hadn't encountered them before, but the updated version of getDECstars shouldn't have that issue. (If you use the longer version with argument isv=True, it's easier to debug and figure out what's missing fr... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074650912_beautifulsoup_python_selenium_web_scraping.txt |
Q:
I'm finding it hard to understand how functions work. Would someome mind explaining them?
Please excuse the extra modulus. I've taken a small part of my code out to convert it into functions to make my code less messy. However I'm finding it really hard to understand how I put values in and take them out to print ... | I'm finding it hard to understand how functions work. Would someome mind explaining them? | Please excuse the extra modulus. I've taken a small part of my code out to convert it into functions to make my code less messy. However I'm finding it really hard to understand how I put values in and take them out to print or do things with. See the code I'm using below. VideoURL would be replaced with a url of a vid... | [
"It's because you have named your function as BeautifulSoup which is as same as the name of the function from the library you have imported. Instead of using the function BeautifulSoup from bs4, it is now running the code you have defined which takes only one argument. So give your function another name.\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"function",
"python",
"pytube"
] | stackoverflow_0074663775_beautifulsoup_function_python_pytube.txt |
Q:
How to Split a column into two by comma delimiter, and put a value without comma in second column and not in first?
I have a column in a df that I want to split into two columns splitting by comma delimiter. If the value in that column does not have a comma I want to put that into the second column instead of firs... | How to Split a column into two by comma delimiter, and put a value without comma in second column and not in first? | I have a column in a df that I want to split into two columns splitting by comma delimiter. If the value in that column does not have a comma I want to put that into the second column instead of first.
Origin
New York, USA
England
Russia
London, England
California, USA
USA
I want the result to be:... | [
"We can try using str.extract here:\ndf[\"Location\"] = df[\"Origin\"].str.extract(r'(.*),')\ndf[\"Country\"] = df[\"Origin\"].str.extract(r'(\\w+(?: \\w+)*)$')\n\n",
"Here is a way by using str.extract() and named groups\ndf['Origin'].str.extract(r'(?P<Location>[A-Za-z ]+(?=,))?(?:, )?(?P<Country>\\w+)')\n\nOutp... | [
2,
0
] | [] | [] | [
"multiple_columns",
"pandas",
"python",
"split"
] | stackoverflow_0070795642_multiple_columns_pandas_python_split.txt |
Q:
python requests not work with vpn ProxyError('Cannot connect to proxy.',
I use requests with vpn and it show error
(Caused by ProxyError('Cannot connect to proxy.', OSError(0, 'Error')))
this is code
import requests
con = requests.get(url)
I can visit url in browser with vpn. I hav to use vpn to requests.
use Py... | python requests not work with vpn ProxyError('Cannot connect to proxy.', | I use requests with vpn and it show error
(Caused by ProxyError('Cannot connect to proxy.', OSError(0, 'Error')))
this is code
import requests
con = requests.get(url)
I can visit url in browser with vpn. I hav to use vpn to requests.
use Python 3.7.9
| [
"using pyPAC works for me...\nhttps://pypac.readthedocs.io/en/latest/\nfrom pypac import PACSession\nfrom requests.auth import HTTPProxyAuth\nsession = PACSession()\nr = session.get('http://google.com')\n\nyou may need to update your python version or use an older version of pyPAC that matches your python version.\... | [
0
] | [] | [] | [
"networking",
"python",
"python_requests",
"urllib",
"vpn"
] | stackoverflow_0074106849_networking_python_python_requests_urllib_vpn.txt |
Q:
How do I find the other elements in a list given one of them?
Given one element in a list, what is the most efficient way that I can find the other elements?
(e.g. if a list is l=["A","B","C","D"] and you're given "B", it outputs "A", "C" and "D")?
A:
Your question-: How do I find the other elements in a list gi... | How do I find the other elements in a list given one of them? | Given one element in a list, what is the most efficient way that I can find the other elements?
(e.g. if a list is l=["A","B","C","D"] and you're given "B", it outputs "A", "C" and "D")?
| [
"Your question-: How do I find the other elements in a list given one of them?\nThink like.. How can i remove that element in a list to get all other elements in a list [Quite simple to approach now!!]\nSome methods are:-\ndef method1(test_list, item):\n #List Comprehension\n res = [i for i in test_list if i... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074663785_python.txt |
Q:
How do I loop through this dictionary correctly in python?
favorite_foods = {'bill': 'cake', 'alex': 'patacones'}
for name in favorite_foods:
print(f"I dont agree with your favorite food {name.title()}.")
for food in (favorite_foods.values()):
print(f"{food.title()} is delicious, but not th... | How do I loop through this dictionary correctly in python? | favorite_foods = {'bill': 'cake', 'alex': 'patacones'}
for name in favorite_foods:
print(f"I dont agree with your favorite food {name.title()}.")
for food in (favorite_foods.values()):
print(f"{food.title()} is delicious, but not that good!")
if food in (favorite_foods.values() endswith(s)
... | [
"use .items() to loop through dict. Also, if you want the output to be a long string (i.e., no new line), you can use list and join.\nfavorite_foods = {'bill': 'cake', 'alex': 'patacones'}\n\noutput = []\nfor k,v in favorite_foods.items():\n output.append(f\"I dont agree with your favorite food {k.title()}.\")\n... | [
0,
0,
0
] | [] | [] | [
"dictionary",
"loops",
"python"
] | stackoverflow_0074663867_dictionary_loops_python.txt |
Q:
What is happening inside of my printFun function that is causing this behaviour
I am trying to figure out recursion and how it operates and I cant seem to figure out what is happening in this code.
def printFun(test):
if (test < 1):
return
else:
print(test, end="a ")
pri... | What is happening inside of my printFun function that is causing this behaviour | I am trying to figure out recursion and how it operates and I cant seem to figure out what is happening in this code.
def printFun(test):
if (test < 1):
return
else:
print(test, end="a ")
printFun(test-1) # statement 2
print(test, end="n ")
return
# Driver ... | [
"Its because the stack unwinds depth first. In pseudocode, with each indentation being a new call to the function, you get\ncall printFun(3)\n print 3a\n call printFun(2)\n print 2a\n call printFun(1)\n print 1a\n call printFun(0)\n print nothing\n ... | [
2,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074663859_python_recursion.txt |
Q:
Python: cv2 can't open USB camera. "error: (-215:Assertion failed)"
I'd like to use cv2 with a Desktop PC that I build myself. I've bought a USB webcamera and successufuly installed it since it works smoothly when I access it. My probem is that it seems that cv2 is not able to open my camera. This is the error I'm... | Python: cv2 can't open USB camera. "error: (-215:Assertion failed)" | I'd like to use cv2 with a Desktop PC that I build myself. I've bought a USB webcamera and successufuly installed it since it works smoothly when I access it. My probem is that it seems that cv2 is not able to open my camera. This is the error I'm getting:
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
cv2.error: O... | [
"rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\nBefore this line of code, did you also write something like cv2.imread(...)? I experienced the error exactly the same with yours when I mistakenly put a wrong image address in the cv2.imread(), so my advice is to double check if you pass a correct image address... | [
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0074358640_opencv_python.txt |
Q:
How to merge csv file with xlsx file and save it into a new combined file
The files of both csv and xlsx contain same context, with same header and all. But would like to combine all under one file and then having another column to identify which is csv, which is xlsx. How do I go about doing so?
extension = 'csv'... | How to merge csv file with xlsx file and save it into a new combined file | The files of both csv and xlsx contain same context, with same header and all. But would like to combine all under one file and then having another column to identify which is csv, which is xlsx. How do I go about doing so?
extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}.format(extension))]
combined)csv =... | [
"To merge CSV and XLSX files and save them into a new combined file using the code you provided, you can use the pandas library in Python to read the CSV and XLSX files, concatenate them into a single DataFrame, and then write the resulting DataFrame to a new CSV file. Here is an example of how you could modify you... | [
1,
1
] | [] | [] | [
"csv",
"python",
"xlsx"
] | stackoverflow_0074663750_csv_python_xlsx.txt |
Q:
Creating a scipy-dev environment
I am following steps in the contributor guide to create a development environment. I am up to step 2.
The Python-level dependencies for building SciPy will be installed as part of the conda environment creation - see environment.yml
Note that we’re installing SciPy’s build depende... | Creating a scipy-dev environment | I am following steps in the contributor guide to create a development environment. I am up to step 2.
The Python-level dependencies for building SciPy will be installed as part of the conda environment creation - see environment.yml
Note that we’re installing SciPy’s build dependencies and some other software, but not... | [
"It doesn't matter where the environment file is, one just needs to ensure the path they provide exists. In fact, Conda can even create it from a URL:\nconda env create -f https://github.com/scipy/scipy/raw/main/environment.yml\n\nNote that most users find it useful to name their environments by passing an --name,-... | [
0,
0
] | [] | [] | [
"conda",
"python",
"scipy"
] | stackoverflow_0074621983_conda_python_scipy.txt |
Q:
Kivy: laptop touch pad - mouse cursor move
My problem is simple and certainly isn't any news: I can manage my Kivy desktop app with a mouse pretty reasonably. Unfortunately, touch pad is a different story: a single finger move is interpreted as a swipe so there's no way to just move the mouse cursor where it's nee... | Kivy: laptop touch pad - mouse cursor move | My problem is simple and certainly isn't any news: I can manage my Kivy desktop app with a mouse pretty reasonably. Unfortunately, touch pad is a different story: a single finger move is interpreted as a swipe so there's no way to just move the mouse cursor where it's needed. Google isn't very cooperative; maybe I don'... | [
"A solution: comment out probesysfs line in ~/.kivy/config.ini.\n...\n[input]\nmouse = mouse\n#%(name)s = probesysfs\n...\n\n"
] | [
1
] | [] | [] | [
"desktop_application",
"gesture",
"kivy",
"python",
"touchpad"
] | stackoverflow_0074646535_desktop_application_gesture_kivy_python_touchpad.txt |
Q:
Python: How to ffill and bfill a column with nan?
How might I ffill and bfill a column that contains nans?
Consider this example:
# data
df = pd.DataFrame([
[np.nan, '2019-01-01', 'P', 'O', 'A'],
[np.nan, '2019-01-02', 'O', 'O', 'A'],
['A', '2019-01-03', 'O', 'O', 'A'],
... | Python: How to ffill and bfill a column with nan? | How might I ffill and bfill a column that contains nans?
Consider this example:
# data
df = pd.DataFrame([
[np.nan, '2019-01-01', 'P', 'O', 'A'],
[np.nan, '2019-01-02', 'O', 'O', 'A'],
['A', '2019-01-03', 'O', 'O', 'A'],
['A', '2019-01-04', 'O', 'P', 'A'],
[np... | [
"The following works for me:\ndf['ID'] = df['ID'].ffill(limit=1).bfill(limit=2)\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074663824_pandas_python.txt |
Q:
Error with while (cap.isopened()): in python using cv2
There are a lot of examples using
while (cap.isopened()):
to loop through a video, but I've found that it always errors out on the last frame. I'm currently using this instead
while (cap.get(1) < cap.get(7)):
but is there something I need to do to get the fi... | Error with while (cap.isopened()): in python using cv2 | There are a lot of examples using
while (cap.isopened()):
to loop through a video, but I've found that it always errors out on the last frame. I'm currently using this instead
while (cap.get(1) < cap.get(7)):
but is there something I need to do to get the first method to work and not error out?
I'm just doing normal ... | [
"The first method is most likely failing because you're reading a frame after the video is over (and thus getting a blank frame), and then trying to do things to that blank frame which aren't allowed. You can add a check to see if the frame you got was blank:\n while(cap.isOpened()):\n ret, frame = cap.re... | [
4,
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0027148047_opencv_python.txt |
Q:
Python TypeError: Unhashable type when inheriting from subclass with __hash__
I have a base class and a subclass, such as:
class Base:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
def __hash__(self):
return hash(self.x)
class Subclass(Base... | Python TypeError: Unhashable type when inheriting from subclass with __hash__ | I have a base class and a subclass, such as:
class Base:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return self.x == other.x
def __hash__(self):
return hash(self.x)
class Subclass(Base):
def __init__(self, x, y):
super().__init__(x)
self.y = y
... | [
"The __eq__ rule applies both to classes without any subclasses implementing __hash__ and to classes that have a parent class with a hash function. If a class overrides __eq__, it must override __hash__ alongside it.\nTo fix your sample:\nclass Base:\n def __init__(self, x):\n self.x = x\n def __eq__(s... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074664008_python_python_3.x.txt |
Q:
How do I write all my BeautifulSoup data from a website to a text file? Python
I am trying to read data from open insider and put it into an easy to read text file. Here is my code so far:
from bs4 import BeautifulSoup
import requests
page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month"... | How do I write all my BeautifulSoup data from a website to a text file? Python | I am trying to read data from open insider and put it into an easy to read text file. Here is my code so far:
from bs4 import BeautifulSoup
import requests
page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month")
'''print(page.status_code)
checks to see if the page was downloaded successfully'... | [
"Open file then the for loop and added \\n for new line:\nfrom bs4 import BeautifulSoup\nimport requests\n\npage = requests.get(\"http://openinsider.com/top-insider-purchases-of-the-month\")\n\n'''print(page.status_code)\nchecks to see if the page was downloaded successfully'''\n\nsoup = BeautifulSoup(page.content,... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"txt"
] | stackoverflow_0074663991_beautifulsoup_python_txt.txt |
Q:
Is there a way to transform a list of tuples into a dictionary in python?
I am doing an assignment in which I need to open a raw mailing list, saved in a CSV file, filter the users that have been unsubscribed, and print back the resulting mailing list to another CSV file. To do so, I first need to create tuples wi... | Is there a way to transform a list of tuples into a dictionary in python? | I am doing an assignment in which I need to open a raw mailing list, saved in a CSV file, filter the users that have been unsubscribed, and print back the resulting mailing list to another CSV file. To do so, I first need to create tuples with each row in the original list, and then transform the tuples into a dictiona... | [
"This seems like an XY problem - you are trying to solve problem X (filter csv) with solution Y (a dictionary) when there is a better way to solve X.\nGoing from the description of your problem, there is no need for a dictionary. You can filter the CSV row by row and write directly to the new file.\nwith open(\"mai... | [
0
] | [
"you can try to use dict class , such as my_dict = dict(tuple_list)\n"
] | [
-1
] | [
"csv",
"dictionary",
"python",
"tuples"
] | stackoverflow_0074663927_csv_dictionary_python_tuples.txt |
Q:
rich.table prints unicode when I want ascii
I am trying to print MAC address using python rich library. Below is code. The ":cd" in the MAC address get converted to an actual CD disk emoji. How to prevent that from happening?
from rich.console import Console
from rich.table import Table
table = Table(safe_box=Tru... | rich.table prints unicode when I want ascii | I am trying to print MAC address using python rich library. Below is code. The ":cd" in the MAC address get converted to an actual CD disk emoji. How to prevent that from happening?
from rich.console import Console
from rich.table import Table
table = Table(safe_box=True)
table.add_column("MAC address")
table.add_row(... | [
"The documentation describes this. You use backslash to escape characters that would otherwise be recognized.\ntable.add_row(\"08:00:27\\\\:cd:af:88\")\n\nIf you have a string, do\ns = s.replace(':cd','\\\\:cd')\n\nhttps://rich.readthedocs.io/en/stable/markup.html\nFOLLOWUP\nI looked at the full emoji list in the ... | [
0
] | [] | [] | [
"python",
"rich"
] | stackoverflow_0074663714_python_rich.txt |
Q:
How to get rid of python in VS Code's sidebar?
I tried python and didn't like it, but under the "Explorer" sidebar in VS Code, it still has a python section.
I tried deleting the python extensions, reloading VS Code and looking in settings. It's possible I missed it in settings.
| How to get rid of python in VS Code's sidebar? | I tried python and didn't like it, but under the "Explorer" sidebar in VS Code, it still has a python section.
I tried deleting the python extensions, reloading VS Code and looking in settings. It's possible I missed it in settings.
| [] | [] | [
"Holy Sh*t i am stupid. My folder containing the code was Named \"Python.\" sorry y'all\n"
] | [
-2
] | [
"c#",
"python",
"visual_studio_code"
] | stackoverflow_0074664012_c#_python_visual_studio_code.txt |
Q:
Can you open a Python shell in Atom editor?
You can open multiple tabs in the Atom editor, and have a multiple column layout as well. However, I am not being able to find out how to open a Python shell inside Atom so that I can load a Python script in the Python interactive shell.
Does anyone know the steps to ach... | Can you open a Python shell in Atom editor? | You can open multiple tabs in the Atom editor, and have a multiple column layout as well. However, I am not being able to find out how to open a Python shell inside Atom so that I can load a Python script in the Python interactive shell.
Does anyone know the steps to achieve this?
| [
"The script package is likely what you want, it allows you to test your code by running part or all of it at a time:\n\nYou can install it by opening the settings view with Ctrl-, switching to the Install panel and searching for script. You can also install from the command line by running:\napm install script\n\n... | [
31,
0
] | [
"You need to go into: Packages --> Settings view --> Install packages and themes and then type \"terminal\" and install the one that starts with \"platformio\":\n\nInstall it and then you will have the + button down there.\n"
] | [
-1
] | [
"atom_editor",
"python"
] | stackoverflow_0033708758_atom_editor_python.txt |
Q:
telegram bot location python
How to get location from user using telegram bot? I tried this:
location_keyboard = KeyboardButton(text="send_location", request_location=True)
contact_keyboard = KeyboardButton(text ='Share contact', request_contact=True)
custom_keyboard = [[ location_keyboard], [contact_... | telegram bot location python | How to get location from user using telegram bot? I tried this:
location_keyboard = KeyboardButton(text="send_location", request_location=True)
contact_keyboard = KeyboardButton(text ='Share contact', request_contact=True)
custom_keyboard = [[ location_keyboard], [contact_keyboard ]]
| [
"You need to do the following:\nCall sendMessage function with the following params:\n{\n chat_id : 1234,\n text: \"your message\",\n reply_markup: \n {keyboard: \n [\n [{text: \"Send Your Mobile\", request_contact: true}],\n [{text: \"Send Your Location\", request_location: true}]\n ]\n }\n}\n\n"... | [
1,
0
] | [] | [] | [
"bots",
"location",
"python",
"telegram"
] | stackoverflow_0043424621_bots_location_python_telegram.txt |
Q:
How to use Class to iterate over an array?
I'm working on Python classes, but I'm running into a "not iterable" error; however, at least from what I can tell, it should iterable.
class Stuff:
def __init__(self, values):
self.values = values
def vari(self):
mean = sum(self.values)/len(s... | How to use Class to iterate over an array? | I'm working on Python classes, but I'm running into a "not iterable" error; however, at least from what I can tell, it should iterable.
class Stuff:
def __init__(self, values):
self.values = values
def vari(self):
mean = sum(self.values)/len(self.values)
_var = sum((v - mean)**2 for... | [
"Is this what you wanted !?\nCode:-\nimport math\nclass Stuff:\n def __init__(self,values):\n self.values = values\n \n def vari(self):\n mean = sum(self.values)/len(self.values)\n _var = sum((v - mean)**2 for v in self.values) / len(self.values)\n return _var\n\n def std_dev... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074664020_python.txt |
Q:
Starting w/ python 3.8, Pandas won't let me reassign value in a DataFrame
Code that works under Pandas 1.3.5 and python 3.7 or earlier:
import pandas as pd
import numpy as np
hex_name = '123456abc'
multi_sub_dir_id_list = [hex_name, hex_name, hex_name]
multi_leaf_node_dirs = ['one', 'two', 'three']
x_dir_multi_in... | Starting w/ python 3.8, Pandas won't let me reassign value in a DataFrame | Code that works under Pandas 1.3.5 and python 3.7 or earlier:
import pandas as pd
import numpy as np
hex_name = '123456abc'
multi_sub_dir_id_list = [hex_name, hex_name, hex_name]
multi_leaf_node_dirs = ['one', 'two', 'three']
x_dir_multi_index = pd.MultiIndex.from_arrays ([multi_sub_dir_id_list, multi_leaf_node_dirs],... | [
"Here is my interpretation of what your code does.\nYour setup code:\nimport pandas as pd\nimport numpy as np\nhex_name = '123456abc'\nmulti_sub_dir_id_list = [hex_name, hex_name, hex_name]\nmulti_leaf_node_dirs = ['one', 'two', 'three'] \nx_dir_multi_index = pd.MultiIndex.from_arrays ([multi_sub_dir_id_list, multi... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074622796_dataframe_pandas_python.txt |
Q:
How do I create a directed graph from a csv file and use DFS to traverse and print it?
How do I create a directed graph from a csv file and use DFS to traverse and print it?
I have made the connect method but it keeps on showing error when I tried to connect elements.
I have tried making edges method as well but k... | How do I create a directed graph from a csv file and use DFS to traverse and print it? | How do I create a directed graph from a csv file and use DFS to traverse and print it?
I have made the connect method but it keeps on showing error when I tried to connect elements.
I have tried making edges method as well but keeps getting confused after I add that method
Directedgraph.csv
Directedgraph.csv
Content of... | [
"Is parseCSV intended for any use? Seems like the vertices are not connected to each other when it is parsed. Also your CSV has multiple entries but parseCSV seems to be only taking in first 2 values.\n"
] | [
0
] | [] | [] | [
"csv",
"depth_first_search",
"graph",
"python",
"python_3.x"
] | stackoverflow_0074663638_csv_depth_first_search_graph_python_python_3.x.txt |
Q:
Why am I getting an Attribute Error for my code when it should be working
I have a class ScrollingCredits. In that, I have a method load_credits. Please have a look at the code
class ScrollingCredits:
def __init__(self):
self.load_credits("end_credits.txt")
(self.background, self.background_r... | Why am I getting an Attribute Error for my code when it should be working | I have a class ScrollingCredits. In that, I have a method load_credits. Please have a look at the code
class ScrollingCredits:
def __init__(self):
self.load_credits("end_credits.txt")
(self.background, self.background_rect) = load_image("starfield.gif", True)
self.font = pygame.font.Font... | [
"There is function definition and calling issue for load_credits, if you want to access the function with self\nMake the load_credits outside the __init__ function like below.\nclass ScrollingCredits:\n def __init__(self):\n self.load_credits(\"end_credits.txt\")\n............\n\n def load_credits(self... | [
1
] | [] | [] | [
"attributeerror",
"error_handling",
"python",
"python_3.x"
] | stackoverflow_0074664065_attributeerror_error_handling_python_python_3.x.txt |
Q:
Use list items in variable in python requests url
I am trying to make a call to an API and then grab event_ids from the data. I then want to use those event ids as variables in another request, then parse that data. Then loop back and make another request using the next event id in the event_id variable for all th... | Use list items in variable in python requests url | I am trying to make a call to an API and then grab event_ids from the data. I then want to use those event ids as variables in another request, then parse that data. Then loop back and make another request using the next event id in the event_id variable for all the IDs.
so far i have the following
def nba_odds():
... | [
"event_ids is an entire list of event ids. You make a single URL with the full list converted to its string view (['dbx-1425135', 'dbx-1425133', ...]). But it looks like you want to get information on each event in turn. To do that, put the second request in the loop so that it runs for every event you find interes... | [
0,
0
] | [] | [] | [
"python",
"request"
] | stackoverflow_0074664098_python_request.txt |
Q:
Python Count Characters
Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include the input character and use the plural form, n's if the number of times the characters appears is no... | Python Count Characters | Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include the input character and use the plural form, n's if the number of times the characters appears is not exactly 1.
Ex: If the input... | [
"user_string=input(str())\ncharacter=user_string[0]\nphrase=user_string[1:]\ncount=0\n\nfor i in phrase:\n if i == character:\n count = count+1\n\nif count != 1:\n print(str(count) + \" \" + character + \"'s\")\nelse:\n print(str(count) + \" \" + character)\n\n",
"Suggest just using str.count.\nus... | [
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0073437641_python.txt |
Q:
how to apply if conditional using def with multi parameter
I am new to def function , I am trying to get the logic in def function with multiple if condition. I want x,y,z to be flexible parameter so I can change parameter value in x,y,z. but i can't get the desired output. anyone help ?
df =
date comp m... | how to apply if conditional using def with multi parameter | I am new to def function , I am trying to get the logic in def function with multiple if condition. I want x,y,z to be flexible parameter so I can change parameter value in x,y,z. but i can't get the desired output. anyone help ?
df =
date comp mark value score test1
0 2022-01-01 a 1 10 ... | [
"you can use mask instead apply\ncond1 = (df['mark'] > 3) & (df['value'] > 30)\ndf['score'].mul(2).mask(cond1, df['score'].mul(10))\n\noutput:\n0 200\n1 400\n2 600\n3 4000\n4 5000\nName: score, dtype: int64\n\nmake output to test1 column\ndf.assign(test1=df['score'].mul(2).mask(cond1, df['score'].... | [
0
] | [] | [] | [
"function",
"if_statement",
"pandas",
"python"
] | stackoverflow_0074664035_function_if_statement_pandas_python.txt |
Q:
What is a good way to generate all strings of length n over a given alphabet within a range in dictionary order?
I want to write a generator s_generator(alphabet, length, start_s, end_s) that generates strings of length n over a given alphabet in dictionary order starting with start_s and ending at end_s.
For exam... | What is a good way to generate all strings of length n over a given alphabet within a range in dictionary order? | I want to write a generator s_generator(alphabet, length, start_s, end_s) that generates strings of length n over a given alphabet in dictionary order starting with start_s and ending at end_s.
For example, s_generator('ab', 4, 'aaaa', 'bbbb') generates ['aaaa', 'aaab', 'aaba', 'aabb', 'abaa', 'abab', 'abba', 'abbb', '... | [
"use itertools and comprehension list\nfrom itertools import product\n\ndef s_generator(alphabet, length, start_s, end_s):\n products = product(alphabet, repeat=length)\n return [''.join(x) for x in products if ''.join(x) >= start_s and ''.join(x) <= end_s]\n\n\nprint(s_generator('ab', 4, 'aaaa', 'bbbb'))\n\n... | [
0
] | [] | [] | [
"algorithm",
"python",
"string"
] | stackoverflow_0074664066_algorithm_python_string.txt |
Q:
Python vitual environment (venv): Share libraries in usage and dev/test venvs
I am new in python venv, so sorry for possible stupid question.
I am developing a small library. I've created dev virtual environment with all packages which is necessary for the library usage and freeze all versions of requirements to r... | Python vitual environment (venv): Share libraries in usage and dev/test venvs | I am new in python venv, so sorry for possible stupid question.
I am developing a small library. I've created dev virtual environment with all packages which is necessary for the library usage and freeze all versions of requirements to requirements.txt.
I also would like to create requirements_test.txt with all packag... | [
"\nIs it possible to share some libs from one venv to another?\n\nNo. The same library (or application) will be installed once per virtual environment, the installations can not be shared between environments. And it is perfectly fine like this. That is the whole point of virtual environments, that two installation... | [
3,
0
] | [
"I think it is recommended and advised to have multiple venvs, and multiple environments, be it on the same machine. so just have another venv. Its okay to have same library being present in both venvs.\n",
"Even with virtual environments, there are many libraries that come preinstalled with python and are not ne... | [
-1,
-1
] | [
"python",
"virtualenv"
] | stackoverflow_0060973272_python_virtualenv.txt |
Q:
How to import XOR function from Crypto.Cipher module?
cannot import name 'XOR' from 'Crypto.Cipher'
(/usr/local/lib/python3.8/dist-packages/Crypto/Cipher/__init__.py)
I just tried importing XOR function into my code & this is the error that i have got when i executed my code in the google colab.
Can i get the s... | How to import XOR function from Crypto.Cipher module? | cannot import name 'XOR' from 'Crypto.Cipher'
(/usr/local/lib/python3.8/dist-packages/Crypto/Cipher/__init__.py)
I just tried importing XOR function into my code & this is the error that i have got when i executed my code in the google colab.
Can i get the solution for this?
I just need to import XOR function using ... | [
"pip install crypto\n\ninstalls https://github.com/chrissimpkins/crypto which does not appear to be import-able class-library. Its examples and test scripts suggest crypto and decrypto should be executes as commands.\n\nReadme: https://github.com/chrissimpkins/crypto\nTests/examples: https://github.com/chrissimpki... | [
0
] | [] | [] | [
"cryptography",
"package",
"python"
] | stackoverflow_0074664087_cryptography_package_python.txt |
Q:
Converting floats from input into integers within an equation python
Program is supposed to take an integer and a factor of x and evaluate the polynomial a_nx^n+a_{n-1}x^{n-1}+a_{n-2}x^{n-2}+ ... a_2x^2+a_1x+a_0, where each a_i is a coefficient of the corresponding power of x.
Basically, the polynomial 3x^4+2x^3+x... | Converting floats from input into integers within an equation python | Program is supposed to take an integer and a factor of x and evaluate the polynomial a_nx^n+a_{n-1}x^{n-1}+a_{n-2}x^{n-2}+ ... a_2x^2+a_1x+a_0, where each a_i is a coefficient of the corresponding power of x.
Basically, the polynomial 3x^4+2x^3+x+5 can be represented as the integer 32015 since the x^2 coefficient is 0.... | [
"I've researched about floating-point numbers and the docs also state this as an error. However, what they recommend is using repr() which is a built-in function to convert your input into 17 significant digits. You could also create an if condition that runs the repr() function only when required.\nWhy does this p... | [
0
] | [] | [] | [
"integer",
"logic",
"python"
] | stackoverflow_0074661744_integer_logic_python.txt |
Q:
How can I store current directory as variable in python?
I'm trying to build a basic terminal that performs basic operations in python. I have made all the main functions, but the cd function isn't working to change my current directory.
I suspect that the problem is in the way I store my current directory file. P... | How can I store current directory as variable in python? | I'm trying to build a basic terminal that performs basic operations in python. I have made all the main functions, but the cd function isn't working to change my current directory.
I suspect that the problem is in the way I store my current directory file. Perhaps I need to store it as variable instead of using functio... | [
"It looks like you are storing the current working directory in the path variable when you import it at the beginning of your code. However, when you call os.chdir in your cd function, it changes the current working directory, but it doesn't update the path variable to reflect this change. As a result, when you cal... | [
0,
0,
0
] | [] | [] | [
"python",
"web_scraping"
] | stackoverflow_0074664156_python_web_scraping.txt |
Q:
How to nest a dictionary in another empty dictionary inside a nested for loop?
I created two for loops where the loop for roi in rois is nested in the loop for subject in subjects.
My aim is creating a dictionary called dict_subjects that includes yet another dictionary that, in turn, includes the key-value pair r... | How to nest a dictionary in another empty dictionary inside a nested for loop? | I created two for loops where the loop for roi in rois is nested in the loop for subject in subjects.
My aim is creating a dictionary called dict_subjects that includes yet another dictionary that, in turn, includes the key-value pair roi: comp.
This is my current code:
rois = ["roi_x", "roi_y", "roi_z" ...] # a long l... | [
"To fix your code, you need to create the inner dictionary for each subject before you start the loop for roi in rois. You can do this by adding the following code before the loop\nfor roi in rois:\n\ndict_subjects[subject] = {}\n\nThis will create an empty dictionary for each subject in the outer loop, and you can... | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074664242_dictionary_python.txt |
Q:
UnboundLocalError: local variable 'dist' referenced before assignment
I am trying to train a model for supervised learning for Hidden Markov Model (HMM)and test it on a set of observations however, keep getting this error. The goal is to predict the state based on the observations. How can I fix this and how can I... | UnboundLocalError: local variable 'dist' referenced before assignment | I am trying to train a model for supervised learning for Hidden Markov Model (HMM)and test it on a set of observations however, keep getting this error. The goal is to predict the state based on the observations. How can I fix this and how can I view the transition matrix?
The version for Pomegranate is 0.14.4
Trying t... | [
"To fix this error, you need to ensure that the transition matrix is defined before calling model.bake(). This can be done by using the following code to define the transition matrix:\n# Define the transition matrix\ntransition_matrix = np.array([[0.7, 0.3, 0.0],\n [0.3, 0.7, 0.0],\n ... | [
1,
1
] | [] | [] | [
"hidden_markov_models",
"pomegranate",
"python",
"supervised_learning"
] | stackoverflow_0074538741_hidden_markov_models_pomegranate_python_supervised_learning.txt |
Q:
PyQT5 ui file, does not load properly from the executable file
I am building a PyQt5 application by constructing the interfaces with the designer and the exporting to .ui files. The latter are then loaded by my main class. Here is an example of my source code under the name main.py:
main.py
import os.path
import P... | PyQT5 ui file, does not load properly from the executable file | I am building a PyQt5 application by constructing the interfaces with the designer and the exporting to .ui files. The latter are then loaded by my main class. Here is an example of my source code under the name main.py:
main.py
import os.path
import PyQt5.QtWidgets as qtw
from PyQt5.uic import loadUi
import sys
class... | [
"Add this somewhere at the top of your program:\nimport sys\nimport os\n\nif getattr(sys, 'frozen', False):\n RELATIVE_PATH = os.path.dirname(sys.executable)\nelse:\n RELATIVE_PATH = os.path.dirname(__file__)\n\nThen when you go to call loadUi():\nself._ui_path = RELATIVE_PATH + \"/ui_path\" # Update this as... | [
1,
0
] | [] | [] | [
"pyqt5",
"python"
] | stackoverflow_0071398328_pyqt5_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.