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:
Can't figure out why the "QObject::setParent: Cannot set parent, new parent is in a different thread" error appears in Python program
I've made a simple pyqt gui, with threading, and I can't understand what I need to change in my code to avoid the "QObject::setParent: Cannot set parent, new parent is in a differen... | Can't figure out why the "QObject::setParent: Cannot set parent, new parent is in a different thread" error appears in Python program | I've made a simple pyqt gui, with threading, and I can't understand what I need to change in my code to avoid the "QObject::setParent: Cannot set parent, new parent is in a different thread" error. I have a feeling that this error occurs because of QMainWindow, but I'm not sure.
This is my code.
import sys,time, threa... | [
"I forgot about this question. I figured out a solution to my problem and I've attached the code below.\nI wanted to create a background timer that would not lockup my gui. I also wanted the timer to trigger a method inside the MainWindow class upon completion. The GUI looks like trash, but this was solely for test... | [
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0074205770_pyqt_python.txt |
Q:
Complex datarame filtering python pandas
I have a dataframe. I want it to filter it and reduce certain values to a string. The dataframe looks like this
Code:
data = [['42.0', 'A'], ['41.0', 'A'], ['43.0', 'B'],['43.0', 'C'], ['41.0', 'B'], ['42.0', 'B']]
df = pd.DataFrame(data, columns=['Number', 'Level'])
I tr... | Complex datarame filtering python pandas | I have a dataframe. I want it to filter it and reduce certain values to a string. The dataframe looks like this
Code:
data = [['42.0', 'A'], ['41.0', 'A'], ['43.0', 'B'],['43.0', 'C'], ['41.0', 'B'], ['42.0', 'B']]
df = pd.DataFrame(data, columns=['Number', 'Level'])
I tried this
df.groupby(['Number', 'Level']).size(... | [
"Use crosstab with DataFrame.reindex for original order, then add columns names and join together, last create final string in generator comprehension:\ndf = pd.crosstab(df['Number'], df['Level']).astype(str).reindex(df['Number'].unique())\ns = df.add(df.columns.to_series()).agg(','.join, axis=1)\nprint (s)\nNumber... | [
2,
1
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074387861_dataframe_numpy_pandas_python_python_3.x.txt |
Q:
Getting the Protein names and their ID for a given list of peptide sequence (using Python)
I have a list of peptide sequence, I want to map it to the correct protein names from any Open Database like Uniprot, i.e., peptides belonging to the proteins. Can someone guide how to find the protein names and map them, th... | Getting the Protein names and their ID for a given list of peptide sequence (using Python) | I have a list of peptide sequence, I want to map it to the correct protein names from any Open Database like Uniprot, i.e., peptides belonging to the proteins. Can someone guide how to find the protein names and map them, thanks in advance.
| [
"I'd say your best bet is to use the requests module and hook into the API that Uniprot has on their website. The API for peptide sequence searching is here, and the docs for it link from the same page.\nWith this, you should be able to form a dict that contains your search parameters and send a request to the API ... | [
1
] | [] | [] | [
"bioinformatics",
"protein_database",
"python"
] | stackoverflow_0074387827_bioinformatics_protein_database_python.txt |
Q:
Microsoft Graph API Python SDK "Insufficient privileges to complete the operation."
i'm trying to get user data from AAD using Microsoft Graph API Python SDK.
App registration that i have in company tenant has the followiing API permissions:
I'm using the following piece of code to get user's details from AAD:
fr... | Microsoft Graph API Python SDK "Insufficient privileges to complete the operation." | i'm trying to get user data from AAD using Microsoft Graph API Python SDK.
App registration that i have in company tenant has the followiing API permissions:
I'm using the following piece of code to get user's details from AAD:
from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac impor... | [
"Looks like the resource are trying to reach out is incorrect , https://graph.windows.net is used when you want to connect to AAD graph , please check the docs for more info - https://learn.microsoft.com/en-us/previous-versions/azure/ad/graph/howto/azure-ad-graph-api-operations-overview.\nCould you please try by us... | [
1,
1,
0
] | [] | [] | [
"azure_active_directory",
"microsoft_graph_api",
"microsoft_graph_sdks",
"python",
"python_3.x"
] | stackoverflow_0074362124_azure_active_directory_microsoft_graph_api_microsoft_graph_sdks_python_python_3.x.txt |
Q:
How do I remove pyenv virtualenvs
How do I go about removing all these virtual environments? I don't know where the directories are
A:
Assuming that list came from running pyenv virtualenvs, you should be able to run
pyenv uninstall 3.8.2/envs/greenhouse
to remove the 3.8.2/envs/greenhouse environment.
The envi... | How do I remove pyenv virtualenvs | How do I go about removing all these virtual environments? I don't know where the directories are
| [
"Assuming that list came from running pyenv virtualenvs, you should be able to run\npyenv uninstall 3.8.2/envs/greenhouse\n\nto remove the 3.8.2/envs/greenhouse environment.\nThe environments themselves should be subdirectories of whatever pyenv root returns when you run it. Try doing cd $(pyenv root) and then look... | [
22,
2,
1
] | [] | [] | [
"pyenv",
"pyenv_virtualenv",
"python",
"terminal"
] | stackoverflow_0065097575_pyenv_pyenv_virtualenv_python_terminal.txt |
Q:
In the following code I write the Login API but when I print the user it's give me None result
In the following code I created a Login API but when I hit the request in Postman it's always give me error response. How to rectify the problem?
This is my views.py file
from django.shortcuts import render
from rest_fra... | In the following code I write the Login API but when I print the user it's give me None result | In the following code I created a Login API but when I hit the request in Postman it's always give me error response. How to rectify the problem?
This is my views.py file
from django.shortcuts import render
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework.resp... | [
"Django default User model takes the (username & password) field for Authentication.\nin your code, you tried to authenticate with (email & password) so it gives None on every login request.\ntry for Authentication (username & password) instead of (email & password) I mean change like this...\nuser=authenticate(use... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"visual_studio_code"
] | stackoverflow_0074387808_django_django_rest_framework_python_visual_studio_code.txt |
Q:
Get text out of tags with Python and Selenium
I have been trying to scrape a webpage with Python and Selenium and ran into this problem. Basically, the webpage that I'm scraping shows information in a table with pagination, so I want to get the information from all pages. This is the HTML for the pagination system... | Get text out of tags with Python and Selenium | I have been trying to scrape a webpage with Python and Selenium and ran into this problem. Basically, the webpage that I'm scraping shows information in a table with pagination, so I want to get the information from all pages. This is the HTML for the pagination system when I'm at a page that's not the last page (page ... | [
"We can look for a with an href attribute and Next text content. The same can be done for the Last text.\nWith Selenium / Python you can simply use this line:\nif driver.find_elements(By.XPATH, \"//span[@='pagelinks']//a[@href][contains(text(),'Next')]\"):\n # Do what you need to do while still not on the last\n... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping",
"xpath"
] | stackoverflow_0074387937_python_selenium_selenium_webdriver_web_scraping_xpath.txt |
Q:
pyodbc not enough values\n (0)
cursor.execute('''CREATE TABLE PEDIDO(
CPEDIDO INT GENERATED AS IDENTITY PRIMARY KEY,
CCLIENTE INT NOT NULL,
FECHA DATE NOT NULL
)''')
valores=[]
for i in range(10):
print(i)
x=datetime.date(year=2022,month=11,day=i+1)
v... | pyodbc not enough values\n (0) | cursor.execute('''CREATE TABLE PEDIDO(
CPEDIDO INT GENERATED AS IDENTITY PRIMARY KEY,
CCLIENTE INT NOT NULL,
FECHA DATE NOT NULL
)''')
valores=[]
for i in range(10):
print(i)
x=datetime.date(year=2022,month=11,day=i+1)
valores.append((i,x))
cursor.execut... | [
"Name the columns you are inserting into (and you may not need/require including the statement terminator ; in the query):\nINSERT INTO PEDIDO (CCLIENTE, FECHA) VALUES (?,?)\n\nIf you do not then Oracle will expect you to provide a value for every column in the table (including CPEDIDO).\n",
"You created a table ... | [
0,
0
] | [] | [] | [
"oracle",
"pyodbc",
"python",
"sql"
] | stackoverflow_0074386975_oracle_pyodbc_python_sql.txt |
Q:
SQLModel - Adding comments to a tables
I couldn't find in the docs or in examples on the web how to add a comment to a table, so that it's also written in the corresponding SQL DB when the schema is created.
Is it possible in SQLModel? How?
A:
I found a solution on the github issues of SQLModel; please see the a... | SQLModel - Adding comments to a tables | I couldn't find in the docs or in examples on the web how to add a comment to a table, so that it's also written in the corresponding SQL DB when the schema is created.
Is it possible in SQLModel? How?
| [
"I found a solution on the github issues of SQLModel; please see the attached link.\nhttps://github.com/tiangolo/sqlmodel/issues/492#issuecomment-1309849747\n"
] | [
0
] | [] | [] | [
"python",
"sqlmodel"
] | stackoverflow_0074348515_python_sqlmodel.txt |
Q:
How to calculate average values based on a value change in another column in python/pandas
I want to average values in a column that are in the same row of a repeating value in another column. So for rows of data, every time the value changes in a column B, the code would average the previous values of another col... | How to calculate average values based on a value change in another column in python/pandas | I want to average values in a column that are in the same row of a repeating value in another column. So for rows of data, every time the value changes in a column B, the code would average the previous values of another column A for rows where the value repeated in column B before the change occurred.
I have developed... | [
"Here, the indexes of the rows where the values change are written to the ind list. This is done by checking if the previous value is equal to the other. Shift() is used for this.\nNext, in the list comprehensions, at each iteration, the my_func function is called, which calculates the average values and sets them ... | [
0
] | [] | [] | [
"average",
"pandas",
"python"
] | stackoverflow_0074382349_average_pandas_python.txt |
Q:
Google Ads API - Get Ads daily clicks according to Age / Gender
Is it possible to get a daily Age / Gender breakdown for the specific Ad (ad_group_ad)?
Currently, I am trying to use the age_range_view and the gender_view, is there a way to specify a specific Ad (ad_group_ad.id) in the query?
A:
Sadly, it's not ... | Google Ads API - Get Ads daily clicks according to Age / Gender | Is it possible to get a daily Age / Gender breakdown for the specific Ad (ad_group_ad)?
Currently, I am trying to use the age_range_view and the gender_view, is there a way to specify a specific Ad (ad_group_ad.id) in the query?
| [
"Sadly, it's not possible. See more at GAQL documentation for Gender and Age Range views for v11 and v12:\n\nGender View: v11, v12\nAge Range View: v11, v12\n\nYou can get data about ad group level but not about ads while working Gender and Age Range views.\n"
] | [
1
] | [] | [] | [
"google_ads_api",
"google_ads_script",
"python"
] | stackoverflow_0074332063_google_ads_api_google_ads_script_python.txt |
Q:
Merge two DataFrames 1:1
I'd like to merge two DataFrams that contains two common columns. They have the same number of row and I know the order in both columns is the same, so they are already aligned.
My problem is that, after they've merged I'm left with more rows than I originally had.
Is there a way to merge ... | Merge two DataFrames 1:1 | I'd like to merge two DataFrams that contains two common columns. They have the same number of row and I know the order in both columns is the same, so they are already aligned.
My problem is that, after they've merged I'm left with more rows than I originally had.
Is there a way to merge these two DataFrames and keep ... | [
"If they are all equally in length and previously sorted, with the same number of observations per col1 and col2, consider using join instead of merge. However be cautious since the operation is on indexes (by default), rather than column values:\n\nJoin columns with other DataFrame either on index or on a key colu... | [
3,
2,
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074388032_pandas_python.txt |
Q:
Print all variables in a class? - Python
I'm making a program that can access data stored inside a class. So for example I have this class:
#!/usr/bin/env python
import shelve
cur_dir = '.'
class Person:
def __init__(self, name, score, age=None, yrclass=10):
self.name = name
self.firstname = ... | Print all variables in a class? - Python | I'm making a program that can access data stored inside a class. So for example I have this class:
#!/usr/bin/env python
import shelve
cur_dir = '.'
class Person:
def __init__(self, name, score, age=None, yrclass=10):
self.name = name
self.firstname = name.split()[0]
try:
self.... | [
"print db['han'].__dict__\n\n",
"\nRather than using magic methods , Vars could be more\n preferable.\n\nprint(vars(db['han']))\n\n",
"print(vars(objectName))\n\nOutput:\n{'m_var1': 'val1', 'm_var2': 'val2'}\n\nThis will print all the class variables with values initialised. \n",
"Define __str__ or __repr__ ... | [
46,
24,
13,
4,
2,
0,
0,
0
] | [] | [] | [
"class",
"python",
"shelve"
] | stackoverflow_0003992803_class_python_shelve.txt |
Q:
TypeError: __init__() got an unexpected keyword argument 'size'
This is my code below and the error I have is beneath it but I cant figure out why this is happening.
Please share your thoughts
from gensim.models import word2vec
np.set_printoptions(suppress=True)
feature_size = 150
context_size= 2
min_word = 1
wor... | TypeError: __init__() got an unexpected keyword argument 'size' | This is my code below and the error I have is beneath it but I cant figure out why this is happening.
Please share your thoughts
from gensim.models import word2vec
np.set_printoptions(suppress=True)
feature_size = 150
context_size= 2
min_word = 1
word_vec= word2vec.Word2Vec(tokenized, size=feature_size, \
... | [
"I have met the same problem and solved it by looking up the Word2Vec embedding documentation. Notice there are two changes in parameters in new Gensim:\n[1] size -> vector_size\n[2] iter -> epochs\n\nHere is a code example from the documentation:\nfrom gensim.test.utils import common_texts\nfrom gensim.models impo... | [
11,
0
] | [] | [] | [
"python"
] | stackoverflow_0067413006_python.txt |
Q:
Python: API Get requests returns as 1 index in a list
I am trying to:
request Get to https://api.thedogapi.com/v1/images/search (public api without auth)
But the random response is returned in a list, not a dict, so I'm having troubles getting the url value I need.
Script:
import requests
r = requests.get("https:... | Python: API Get requests returns as 1 index in a list | I am trying to:
request Get to https://api.thedogapi.com/v1/images/search (public api without auth)
But the random response is returned in a list, not a dict, so I'm having troubles getting the url value I need.
Script:
import requests
r = requests.get("https://api.thedogapi.com/v1/images/search?format=json")
print(r... | [
"Solution posted by @user56700\nTry: link = r.json()[0][\"url\"]\n"
] | [
0
] | [] | [] | [
"api",
"python"
] | stackoverflow_0074385945_api_python.txt |
Q:
Plotly bar chart legend within subplot
I am wondering on how to make a legend based on the coloured bars rather than individual trace charts. In this case, the legend should be based on 'giraffes', 'orangutans', 'monkeys'.
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subpl... | Plotly bar chart legend within subplot | I am wondering on how to make a legend based on the coloured bars rather than individual trace charts. In this case, the legend should be based on 'giraffes', 'orangutans', 'monkeys'.
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
fig = make_subplots(
rows=1,
c... | [
"Plotly takes the last bar's color in each subplot and assigns it to the legend, which is the green. To solve this problem, you can change the way you build your subplot. I build each bar in each subplot individually to be able to display it in the legend as in the code below:\nExample:\nimport pandas as pd\nimport... | [
1
] | [] | [] | [
"plotly",
"plotly_python",
"python"
] | stackoverflow_0074387221_plotly_plotly_python_python.txt |
Q:
Installation error streamlit: Building wheel for pyarrow (pyproject.toml) ... error
I try to install metaploit, but every time I get errors and I can't get it to work.
During installation I get the following error code:
pip install --upgrade streamlit
(Deleted a lot of irrelevant information)
Building wheels for... | Installation error streamlit: Building wheel for pyarrow (pyproject.toml) ... error | I try to install metaploit, but every time I get errors and I can't get it to work.
During installation I get the following error code:
pip install --upgrade streamlit
(Deleted a lot of irrelevant information)
Building wheels for collected packages: pyarrow
Building wheel for pyarrow (pyproject.toml) ... error
e... | [
"Are you using Python 3.11? Because in that case, it's described in this issue: pyarrow doesn't support Python 3.11 yet (here is the PR in pyarrow's github, it'll arrive in the next release). So either you simply wait until that is released, or you install Python 3.10 until then.\n",
"As of today, there is not py... | [
4,
1,
0
] | [] | [] | [
"python",
"runtime_error",
"streamlit"
] | stackoverflow_0074254073_python_runtime_error_streamlit.txt |
Q:
Error with registration in the pset9 cs5(unexpected exceptions)
"registering user succeeds application raised an exception (see the
log for more details)" "registration rejects duplicate username
application raised an exception (see the log for more details)"
idk what to do :((
REGISTER.HTML:
{% extends "layout.h... | Error with registration in the pset9 cs5(unexpected exceptions) |
"registering user succeeds application raised an exception (see the
log for more details)" "registration rejects duplicate username
application raised an exception (see the log for more details)"
idk what to do :((
REGISTER.HTML:
{% extends "layout.html" %}
{% block title %}
Register
{% endblock %}
{% block mai... | [
"The problem is in index route of app.py (not shown). index.html indicates a variable called \"company\" here <td>{{ summary.company }}</td>. In the index function there is a sql SELECT to get users stock holdings. THere is no column named \"company\" in that table.\n"
] | [
0
] | [] | [] | [
"cs50",
"html",
"javascript",
"python"
] | stackoverflow_0074378327_cs50_html_javascript_python.txt |
Q:
Customize key value in python structured (json) logging from config file
I have to output my python job's logs as structured (json) format for our downstream datadog agent to pick them up. Crucially, I have requirements about what specific log fields are named, e.g. there must be a timestamp field which cannot be ... | Customize key value in python structured (json) logging from config file | I have to output my python job's logs as structured (json) format for our downstream datadog agent to pick them up. Crucially, I have requirements about what specific log fields are named, e.g. there must be a timestamp field which cannot be called e.g. asctime. So a desired log looks like:
{"timestamp": "2022-11-10 00... | [
"You'll need to have a small, minimal amount of Python code, something like\n# in mymodule.py, say\n\nclass CustomJsonFormatter(jsonlogger.JsonFormatter):\n def add_fields(self, log_record, record, message_dict):\n super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)\n log_... | [
1
] | [] | [] | [
"json",
"logging",
"python",
"python_3.x"
] | stackoverflow_0074385061_json_logging_python_python_3.x.txt |
Q:
flask cannot open folder
I am trying to use the flask to open a local folder on the browser, like directly typing file:///D:/ to the address bar. but it failed. when I directly run the home.html on the browser it can work successfully. Is there anything wrong? How can I tell Flask works correctly?
Thanks
app.py
fr... | flask cannot open folder | I am trying to use the flask to open a local folder on the browser, like directly typing file:///D:/ to the address bar. but it failed. when I directly run the home.html on the browser it can work successfully. Is there anything wrong? How can I tell Flask works correctly?
Thanks
app.py
from flask import Flask, render_... | [
"Try this way\n@app.route(\"/home\")\ndef home():\n import os\n arr = os.listdir(\"F:/\")\n return render_template('home.html', arr=arr)\n\nand then on template(home.html) list your files accordingly.\n"
] | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074387669_flask_python.txt |
Q:
Original error: Bad app: App paths need to be absolute or an URL to a compressed app file:
I want to open demo app using appium (in ios simulator using X code)
A:
You are referring a .swift file instead of app.
Changing it to "app": "/path/to/my.app" might work.
A:
You are referring a .swift file instead of .a... | Original error: Bad app: App paths need to be absolute or an URL to a compressed app file: |
I want to open demo app using appium (in ios simulator using X code)
| [
"You are referring a .swift file instead of app.\nChanging it to \"app\": \"/path/to/my.app\" might work.\n",
"You are referring a .swift file instead of .app file. Try writing this\n\"appium:app\": \"/Users/pritwindersingh/Library/Developer/Xcode/DerivedData/WebDriverAgent-bpndfqzifmteusepnbmywejsnvgw/Build/Prod... | [
2,
1
] | [] | [] | [
"appium",
"ios",
"ios_simulator",
"python",
"xcode"
] | stackoverflow_0074385034_appium_ios_ios_simulator_python_xcode.txt |
Q:
Trying to make a one hour loop in python
from notifypy import Notify
import schedule
def remember_water():
notification = Notify()
notification.title = "XXX"
notification.message = "XXX"
notification.send()
schedule.every().hour.do(remember_water())
while True:
schedule.run_pending()
time... | Trying to make a one hour loop in python | from notifypy import Notify
import schedule
def remember_water():
notification = Notify()
notification.title = "XXX"
notification.message = "XXX"
notification.send()
schedule.every().hour.do(remember_water())
while True:
schedule.run_pending()
time.sleep(1)
Tried to make a notification to dr... | [
"Running your code produces:\nTraceback (most recent call last):\n File \"/home/lars/tmp/python/drink.py\", line 11, in <module>\n schedule.every().hour.do(remember_water())\n File \"/home/lars/.local/share/virtualenvs/lars-rUjSNCQn/lib/python3.10/site-packages/schedule/__init__.py\", line 625, in do\n self... | [
2
] | [] | [] | [
"loops",
"notify",
"python",
"schedule"
] | stackoverflow_0074388314_loops_notify_python_schedule.txt |
Q:
how to select column iteratively in spark
If I have dataframe with 100s columns. How do I select iteratevly below columns.
One final dataframe output from below code may be:
|a | id | year|m2000 | m2001 | m2002 | .... | m2015|
|"hello"| 1 | 2001 | 0 | 0 | 0 | ... | 0 |
|"hello"| 1 | 2015 ... | how to select column iteratively in spark | If I have dataframe with 100s columns. How do I select iteratevly below columns.
One final dataframe output from below code may be:
|a | id | year|m2000 | m2001 | m2002 | .... | m2015|
|"hello"| 1 | 2001 | 0 | 0 | 0 | ... | 0 |
|"hello"| 1 | 2015 | 0 | 0 | 0 | ... | 0 |
|"hello"| ... | [
"You are not quite clear on what columns you need. If you want to select everything starting with m plus a, id, year, colRegex may be helpful.\ndf.select('a','id','year', df.colRegex(\"`^m200+.+`\")).show()\n\nIf you want to selectively select columns between 2000 and 2015 use list comprehension with the walrus op... | [
2
] | [] | [] | [
"apache_spark",
"dataframe",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074387346_apache_spark_dataframe_pandas_pyspark_python.txt |
Q:
Django Channels. How to avoid the exception RuntimeError: Task got Future attached to a different loop?
I use Django Channels with channel_layers (RedisChannelLayer).
Using Channels I only need to get live messages from signals when post_save event happens.
I try to send a message from the signals.py module.
The f... | Django Channels. How to avoid the exception RuntimeError: Task got Future attached to a different loop? | I use Django Channels with channel_layers (RedisChannelLayer).
Using Channels I only need to get live messages from signals when post_save event happens.
I try to send a message from the signals.py module.
The fact that the first message is sending properly, I got it successfully in the js console,
but then disconnecti... | [
"After a few days of investigating the issue, I have realized the Exception, RuntimeError, in that case, is just a Warning, not Error.\nBecause the server doesn't break and the Socket is going on further.\nAnd that \"Warning\" is still in a Bug stage in Channels developers.\nIt looks not beauty in the server consol... | [
0
] | [] | [] | [
"django",
"django_channels",
"python",
"redis",
"websocket"
] | stackoverflow_0074346803_django_django_channels_python_redis_websocket.txt |
Q:
Plotting bars as a line matplotlib
I would like to make a bar plot in matplotlib, but instead of bars I would like it to have lines (see picture at the bottom please for an example) It is from this paper: https://arxiv.org/abs/1907.10529
When trying to search for the solution, I only find tutorials or posts about ... | Plotting bars as a line matplotlib | I would like to make a bar plot in matplotlib, but instead of bars I would like it to have lines (see picture at the bottom please for an example) It is from this paper: https://arxiv.org/abs/1907.10529
When trying to search for the solution, I only find tutorials or posts about how to plot a line in a bar graph, but t... | [
"you can play with line width and alpha values to achieve what you want. Note also you need to take care of the ticks values.\nconsidering the values where:\n[0.22, 0.17, 0.13, 0.10, 0.08, 0.07, 0.065, 0.06, 0.055, 0.05]\nYou can do the following:\nimport matplotlib.pyplot as plt\n\nvalues = [0.22, 0.17, 0.13, 0.10... | [
0
] | [] | [] | [
"matplotlib",
"python",
"visualization"
] | stackoverflow_0074387770_matplotlib_python_visualization.txt |
Q:
Why sublist access time increases with sublist size?
The code below initializes a list of random integers, and iterates over it. Given a subset_size, at every iteration i, a sublist of i: i + subset_size is accessed. The time to access the sublist grows with subset_size. For n = 100000 and subset_size = 50000, it ... | Why sublist access time increases with sublist size? | The code below initializes a list of random integers, and iterates over it. Given a subset_size, at every iteration i, a sublist of i: i + subset_size is accessed. The time to access the sublist grows with subset_size. For n = 100000 and subset_size = 50000, it takes 15+ seconds on my i5 mbp. I thought sublists are ret... | [
"\nI thought sublists are retrieved using 2 pointers and lazy evaluation\nbut it looks like there's some c loop behind the scenes that populates\na new list and returns it as a result.\n\nYour assumption is correct. slicing a list always creates new list. Here is the relevant part of the source code. I have added s... | [
2,
0
] | [
"List slice would not be evaluated lazily, the list will be created on every iteration. Use itertools.islice to create lazy slice:\nislice(x, i, i + subset_size)\n"
] | [
-1
] | [
"indexing",
"list",
"performance",
"python"
] | stackoverflow_0074388015_indexing_list_performance_python.txt |
Q:
Why doesn’t Selenium find an element with this XPath expression?
I’m trying to find an element with this XPath expression:
/html/body/div/div[1]/div/div/div[2]/div/div/div/div[2]/form/div[1]/div[3]/div/input
But Selenium can’t find one.
The page I’m trying to access - https://account.aax.com/en-US/login/
I alread... | Why doesn’t Selenium find an element with this XPath expression? | I’m trying to find an element with this XPath expression:
/html/body/div/div[1]/div/div/div[2]/div/div/div/div[2]/form/div[1]/div[3]/div/input
But Selenium can’t find one.
The page I’m trying to access - https://account.aax.com/en-US/login/
I already tried to follow this path by myself, and it’s fine.
| [
"\nYou are missing a delay. WebDriverWait expected_conditions should be used for that.\nYou have to improve your locators.\n\nThe following code works:\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.... | [
1
] | [] | [] | [
"chrome_web_driver",
"python",
"selenium"
] | stackoverflow_0074388383_chrome_web_driver_python_selenium.txt |
Q:
How to link submit button to another page on python Flask framework?
I am learning how to do web development and am using PythonAnywhere with the Flask framework because I was taught python in school and am most familiar with it.
I am making a login page that should redirect to another page after the username and ... | How to link submit button to another page on python Flask framework? | I am learning how to do web development and am using PythonAnywhere with the Flask framework because I was taught python in school and am most familiar with it.
I am making a login page that should redirect to another page after the username and password have been validated and are correct.
I am getting a syntax error ... | [
"Use flask redirect method\nfrom flask import Flask,redirect\n\ndef staff_login():\n errors = \"\"\n if request.method == \"POST\":\n username = None\n password = None\n try:\n username = string(request.form[\"username\"])\n except:\n errors += \"<p> Enter a v... | [
0
] | [] | [] | [
"flask",
"python",
"python_3.x",
"pythonanywhere",
"web"
] | stackoverflow_0074378471_flask_python_python_3.x_pythonanywhere_web.txt |
Q:
Python, round DOWN time to the nearest 15mins clock mark
how am i able to round down time to the nearest 15mins clock mark.
the code below rounds to the nearest 15mins clock mark, i.e if time is 5:08 to becomes 5:15. however i would like to make this round down not up and become 5:00
please help
here is my code
fa... | Python, round DOWN time to the nearest 15mins clock mark | how am i able to round down time to the nearest 15mins clock mark.
the code below rounds to the nearest 15mins clock mark, i.e if time is 5:08 to becomes 5:15. however i would like to make this round down not up and become 5:00
please help
here is my code
fajr_jamaat = ceil(fajr_jamaat_date).strftime('%H:%M:%S')
and t... | [
"this should work.\nimport datetime\n\ndef ceil(dt):\n minut = int(dt.strftime('%M'))*60\n secon = int(dt.strftime('%S'))\n h = int(dt.strftime('%H'))\n tot = minut + secon\n #print(tot)\n nearest = round(tot/900)*900\n #print('time is %d:%d'%(tot/60, tot%60), 'nearest fifteen mark is %d:%d'%(n... | [
0,
0
] | [] | [] | [
"ceil",
"python"
] | stackoverflow_0043938087_ceil_python.txt |
Q:
How can find the substrings that are in alphabetical order within a sorted string list? Python
I should create a program that will find the characters that are in alphabetical order in a given input and find how many characters are in that particular substring or substrings.
For example
Input: cabin
Output: abc, 3... | How can find the substrings that are in alphabetical order within a sorted string list? Python | I should create a program that will find the characters that are in alphabetical order in a given input and find how many characters are in that particular substring or substrings.
For example
Input: cabin
Output: abc, 3
Input: sightfulness
Output: ghi, 3
OUtput: stu, 3
Here is what I have coded so far. I am stuck in t... | [
"You could try something like this:\nstring = input(\"Input string: \")\nchars = sorted(set(string.strip().casefold()))\nparts, part = [], \"\"\nfor a, b in zip(chars, chars[1:] + [\"-\"]):\n part += a\n if ord(a) + 1 != ord(b):\n if len(part) > 1:\n parts.append(part)\n part = \"\"\n... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074383678_python_python_3.x.txt |
Q:
Is there a Paired z test function in python?
Does statsmodels have a paired z test to compare the mean of two dependent samples? I searched this page but couldn't find one.
A:
Since in paired samples you need to test if the mean of the differences observed between the measurments (called d) is different from zer... | Is there a Paired z test function in python? | Does statsmodels have a paired z test to compare the mean of two dependent samples? I searched this page but couldn't find one.
| [
"Since in paired samples you need to test if the mean of the differences observed between the measurments (called d) is different from zero (0) (the difference d is equal to 0 under the null hypothesis), you can use the statsmodels z test for independant samples:\nztest(x1, x2=None, value=0, alternative='two-sided'... | [
0
] | [] | [] | [
"python",
"statistics"
] | stackoverflow_0065453384_python_statistics.txt |
Q:
__pre_init__ functionalty in python?
I would like to make string comparison case insensitive.
For that, I would like to create an immutable class with just one string field.
In the constructor, I would like to call lower() before assigning the value to the field.
I would like to use as much as possible of standard... | __pre_init__ functionalty in python? | I would like to make string comparison case insensitive.
For that, I would like to create an immutable class with just one string field.
In the constructor, I would like to call lower() before assigning the value to the field.
I would like to use as much as possible of standard classes like namedtuple or dataclass.
Usi... | [
"Turns out that dataclasses doesn't provide the functionality I was looking for.\nAttrs however does:\nfrom attr import attrs, attrib\n\n\n@attrs(frozen=True)\nclass Name:\n name: str = attrib(converter=str.lower)\n\n",
"Clarification: If I'm interpreting the question correctly, you specifically want to work w... | [
5,
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0064681510_python.txt |
Q:
how to measure cython execute time to compare with c
I was trying to compare c and cython runtime and decide on which one should I choose for my project. So I tested a simple calculation with both. but I couldn't find any good answer to how to measure cython execute time to compare with c:
C :
#include <stdio.h>
#... | how to measure cython execute time to compare with c | I was trying to compare c and cython runtime and decide on which one should I choose for my project. So I tested a simple calculation with both. but I couldn't find any good answer to how to measure cython execute time to compare with c:
C :
#include <stdio.h>
#include <time.h>
int main() {
int a[3] = {2, 3, 4};
... | [
"Cython builds libraries that could be called from anywhere (here you have defined as cpdef, to be called from python as well as c). you can just call from your c program like you call any other lib.\nLike in your case the function does not need any input, just directly call it from python using timeit and see the ... | [
1,
0
] | [] | [] | [
"c",
"cython",
"python"
] | stackoverflow_0074388522_c_cython_python.txt |
Q:
DLL load failed while importing QtGui
I successfully installed PyQt6 module last night and I used this line of code for my first qt window :
from PyQt6.QtGui import QIcon
and it worked perfectly and without error.
Today I installed pyqt6-tools too for using qt designer
And now when I try to run the exact same fil... | DLL load failed while importing QtGui | I successfully installed PyQt6 module last night and I used this line of code for my first qt window :
from PyQt6.QtGui import QIcon
and it worked perfectly and without error.
Today I installed pyqt6-tools too for using qt designer
And now when I try to run the exact same file from last night I face this error :
Impor... | [
"\nUninstall all modules related to PyQt6.\n\npip uninstall -y PyQt6 pyqt6-plugins PyQt6-Qt6 PyQt6-sip pyqt6-tools qt6-applications qt6-tools\n\nReinstall PyQt6.\n\npip install PyQt6\n"
] | [
0
] | [] | [] | [
"pyqt",
"pyqt6",
"python",
"qt"
] | stackoverflow_0073893299_pyqt_pyqt6_python_qt.txt |
Q:
How to avoid ragged tensors collapse my RAM?
I am trying to read a list of 10.000 tensors in a variable, and then create a ragged tensor from them. Of course, they make my RAM collapse:
def load_batch(path_list):
np_list = []
for path in path_list:
np_list.append(np.load(path, mmap_mode='r... | How to avoid ragged tensors collapse my RAM? | I am trying to read a list of 10.000 tensors in a variable, and then create a ragged tensor from them. Of course, they make my RAM collapse:
def load_batch(path_list):
np_list = []
for path in path_list:
np_list.append(np.load(path, mmap_mode='r'))
return np_list
train_tensors_paths = sort... | [
"One way to retrieve data from a file quickly using tensorflow is\ndata_list = tf.data.Dataset.list_files('arrays/*.npy' , shuffle=False)\n\n#If your data is an int value then cast it as an int32\nbatch_size = 8\ndef load_data(file):\n #print(file)\n return tf.cast(np.load(file) , dtype=tf.float32)\n\ndef pro... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074387803_keras_python_tensorflow.txt |
Q:
Creating a DataFrame from a dictionary of Series results in lost indices and NaNs
dict_with_series = {'Even':pd.Series([2,4,6,8,10]),'Odd':pd.Series([1,3,5,7,9])}
Data_frame_using_dic_Series = pd.DataFrame(dict_with_series)
# Data_frame_using_dic_Series = pd.DataFrame(dict_with_series,index=\[1,2,3,4,5\]), giv... | Creating a DataFrame from a dictionary of Series results in lost indices and NaNs | dict_with_series = {'Even':pd.Series([2,4,6,8,10]),'Odd':pd.Series([1,3,5,7,9])}
Data_frame_using_dic_Series = pd.DataFrame(dict_with_series)
# Data_frame_using_dic_Series = pd.DataFrame(dict_with_series,index=\[1,2,3,4,5\]), gives a NaN value I dont know why
display(Data_frame_using_dic_Series)
I tried labeling ... | [
"When you run:\nData_frame_using_dic_Series = pd.DataFrame(dict_with_series,index=[1,2,3,4,5])\n\nYou request to only use the indices 1-5 from the provided Series, but the original indexing of a Series is from 0, thus resulting in a reindexing.\nIf you want to change the index, do it afterwards:\nData_frame_using_d... | [
0
] | [] | [] | [
"dataframe",
"numpy",
"pandas",
"python",
"series"
] | stackoverflow_0074388626_dataframe_numpy_pandas_python_series.txt |
Q:
How to animate a 3D plot, defined with three functions x=(), y=(), z=()?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_toolkits.mplot3d as Axes3D
r = 20
h = 1.7
phi = np.linspace(0, 4*np.pi, 1000)
theta = np.linspace(-np.pi/4, np.pi/4, 1000)
#theta = np.arc... | How to animate a 3D plot, defined with three functions x=(), y=(), z=()? | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import mpl_toolkits.mplot3d as Axes3D
r = 20
h = 1.7
phi = np.linspace(0, 4*np.pi, 1000)
theta = np.linspace(-np.pi/4, np.pi/4, 1000)
#theta = np.arcsin(0.524)
x = r * np.cos(phi)
y = r * np.sin(phi) * np.cos(theta) - h * np.si... | [
"You need to create a animate callback to update the data.\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport mpl_toolkits.mplot3d as Axes3D\nimport matplotlib.animation as animation\n\nr = 20\nh = 1.7\nN=1000\nphi = np.linspace(0, 4*np.pi, N)\ntheta = np.linspace... | [
1
] | [] | [] | [
"3d",
"animation",
"matplotlib",
"python"
] | stackoverflow_0074388394_3d_animation_matplotlib_python.txt |
Q:
if statement in python airtable records - json
this are 3 records from airtable
I want to make a for loop in python (if value in 'check' is Update2 - do something, else do something else)
{'createdTime': '2022-11-09T15:57:28.000Z',
'fields': {'Last Modified': '2022-11-10T00:22:31.000Z',
'Na... | if statement in python airtable records - json | this are 3 records from airtable
I want to make a for loop in python (if value in 'check' is Update2 - do something, else do something else)
{'createdTime': '2022-11-09T15:57:28.000Z',
'fields': {'Last Modified': '2022-11-10T00:22:31.000Z',
'Name': 'Daniel',
'Status': 'Todo',
... | [
"if record['fields']['check'] == 'update2':\n do something\nelse:\n do something else\n\n"
] | [
1
] | [] | [] | [
"airtable",
"if_statement",
"json",
"python"
] | stackoverflow_0074382892_airtable_if_statement_json_python.txt |
Q:
Is there a way to skip a data when a domain doesn't contain a specific variable
I'm really confused on how to bypass this problem from whois, is there a way so that when whois outputs the domain variable and it doesn't contain the specific variable that i want to showcase, it would just skip it instead of giving m... | Is there a way to skip a data when a domain doesn't contain a specific variable | I'm really confused on how to bypass this problem from whois, is there a way so that when whois outputs the domain variable and it doesn't contain the specific variable that i want to showcase, it would just skip it instead of giving me an error?
And below does not contain any web variable when whois outputs.
This is... | [
"You can use an if-else condition or ternary operator to check whether the dictionary contains the given key or not.\nimport whois\n\ndef whodata(host):\n res = whois.whois(host)\n print(res['registrar'])\n print(res['emails'] if 'emails' in res else '')\n print(res['country'])\n print(\"---------\")... | [
0
] | [] | [] | [
"arrays",
"jupyter",
"list",
"python",
"whois"
] | stackoverflow_0074386534_arrays_jupyter_list_python_whois.txt |
Q:
What is the extra_docker_file_steps parameter in InferenceConfig() when deploying an ACI to Azure?
I am deploying an ACI to Azure and need to add a Java runtime along with my normal Python environment. My inference config looks like this (deploying from Python SDK):
inference_config = InferenceConfig(
... | What is the extra_docker_file_steps parameter in InferenceConfig() when deploying an ACI to Azure? | I am deploying an ACI to Azure and need to add a Java runtime along with my normal Python environment. My inference config looks like this (deploying from Python SDK):
inference_config = InferenceConfig(
runtime="python",
entry_script="scripts/score.py",
conda_file="environment.yml",
... | [
"I just had to deal with it today.\nI used just the extra_docker_file_steps parameter to refer to an extra_steps.dockerfile file in which I defined steps to install libraries/packages to support my inference script (and not installable via Conda or PIP).\nFor example, to properly use opencv I had to install the lib... | [
0
] | [] | [] | [
"azure_container_instances",
"docker",
"java",
"python"
] | stackoverflow_0073474406_azure_container_instances_docker_java_python.txt |
Q:
Is there any existing function to convert a docstring to dict?
Does anyone have the similar experience to print assigned information for different objects?
For instance, the following docstring printed from getattr(obj,'__doc__')
__doc__
Keyword arguments
-----------------
name : str
(default "")
description ... | Is there any existing function to convert a docstring to dict? | Does anyone have the similar experience to print assigned information for different objects?
For instance, the following docstring printed from getattr(obj,'__doc__')
__doc__
Keyword arguments
-----------------
name : str
(default "")
description : str
(default "")
_id : str
(default "")
script : str
... | [
"While waiting for answer, I figured one regex solution which at least can work for the current purpose.\ns = '\\n Keyword arguments\\n -----------------\\n name : str\\n (default \"\")\\n description : str\\n (default \"\")\\n _id : str\\n (default \"\")\\n script : str\\n... | [
0
] | [] | [] | [
"dictionary",
"docstring",
"python"
] | stackoverflow_0074388362_dictionary_docstring_python.txt |
Q:
How to add a tuple which consisting of a list and a string itself into a set in python?
I want to insert multiple tuples into a set which each tuple contains a list and a string.
Each tuple looks like:
sample_tuple = (['list of elements'], 'one_string')
If we check the type of sample_tuple, we can be sure that it... | How to add a tuple which consisting of a list and a string itself into a set in python? | I want to insert multiple tuples into a set which each tuple contains a list and a string.
Each tuple looks like:
sample_tuple = (['list of elements'], 'one_string')
If we check the type of sample_tuple, we can be sure that it is a tuple with 2 elements (one list and one string).
But when I use the "add" method to ins... | [
"Set members must be hashable.\nThat's the way Python ensures that members are unique.\nLists in Python are not hashable (because lists are mutable meaning you can update one item of the list).\nhash([1]) # Error!\n\nIf you don't intent to mutate your sequence of elements, prefer using a tuple that is unmutable an... | [
1,
1
] | [] | [] | [
"hashable",
"python",
"set",
"tuples"
] | stackoverflow_0074387963_hashable_python_set_tuples.txt |
Q:
Python multiprocessing.Pool.apply_async() not executing class function
In a custom class I have the following code:
class CustomClass():
triggerQueue: multiprocessing.Queue
def __init__(self):
self.triggerQueue = multiprocessing.Queue()
def poolFunc(queueString):
... | Python multiprocessing.Pool.apply_async() not executing class function | In a custom class I have the following code:
class CustomClass():
triggerQueue: multiprocessing.Queue
def __init__(self):
self.triggerQueue = multiprocessing.Queue()
def poolFunc(queueString):
print(queueString)
def listenerFunc(self):
pool = multiproce... | [
"There are several problems going on here.\n\nYour instance method, poolFunc, is missing a self parameter.\n\nYou are never properly terminating the Pool. You should take advantage of the fact that a multiprocessing.Pool object is a context manager.\n\nYou're calling apply_async, but you're never waiting for the re... | [
1,
0
] | [] | [] | [
"multiprocessing",
"python",
"python_class",
"python_multiprocessing"
] | stackoverflow_0074387548_multiprocessing_python_python_class_python_multiprocessing.txt |
Q:
How to define new attribute in python class?
I wrote a class like which has 3 hidden attributres:
class Car():
def __init__(self, name, model, brand):
self.__name = name
self.__model = model
self.__brand = brand
Is that possible to create a method for this class to set a new attribute ... | How to define new attribute in python class? | I wrote a class like which has 3 hidden attributres:
class Car():
def __init__(self, name, model, brand):
self.__name = name
self.__model = model
self.__brand = brand
Is that possible to create a method for this class to set a new attribute (publisher)?
I wrote this one, but I didn't get re... | [
"There is no problem if set_publisher is correctly defined as an instance method.\nclass Car:\n def __init__(self, name, model, brand):\n self.__name = name\n self.__model = model\n self.__brand = brand\n\n def set_publisher(self, publisher):\n self.__publisher = publisher\n\nBut i... | [
0
] | [
"You can try this code to use a method (wrapper of setattr) to add attributes by name and value:\n\nclass Car:\n def __init__(self, name, model, brand):\n self.__name = name\n self.__model = model\n self.__brand = brand\n\n def set_attribute(self, attr_name, value):\n setattr(self,... | [
-2
] | [
"class",
"oop",
"python",
"python_3.x"
] | stackoverflow_0074388091_class_oop_python_python_3.x.txt |
Q:
Convert column of strings with key value pairs into columns
I have a CSV file with below format, and wanted to convert Message column into multiple columns with their header and values:
Message Color Count
{'cnt1':12,'cnt2':15,'cn3':36 Yellow 12
{'cnt1':21,'cnt2':25,'cn3':23 Red ... | Convert column of strings with key value pairs into columns | I have a CSV file with below format, and wanted to convert Message column into multiple columns with their header and values:
Message Color Count
{'cnt1':12,'cnt2':15,'cn3':36 Yellow 12
{'cnt1':21,'cnt2':25,'cn3':23 Red 23
{'cnt1':23,'cnt2':21,'cn3':64 Green 19
Output:
| [
"If possible simpliest is add } to end of column and parse dictionaries, pass to json_normalize and add original DataFrame:\nimport ast\n\ndf = pd.json_normalize(dfb.pop('Message').add('}').apply(ast.literal_eval)).join(dfb)\nprint (df) \n cnt1 cnt2 cn3 Color Count\n0 12 15 36 Yellow 12\n1 21... | [
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074388138_pandas_python_python_3.x.txt |
Q:
Failed building wheel for nes-py
Info: I am using Windows 10 with python 3.7.7 and pip 19.2.3
Problem: I was trying to install nes-py in cmd prompt using pip install nes-py, but during the Building wheel for nes-py (setup.py) ... error stage of the install I got the following error:
C:\Program Files (x86)\Microsof... | Failed building wheel for nes-py | Info: I am using Windows 10 with python 3.7.7 and pip 19.2.3
Problem: I was trying to install nes-py in cmd prompt using pip install nes-py, but during the Building wheel for nes-py (setup.py) ... error stage of the install I got the following error:
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Too... | [
"I solved this issue by installing node.js. This installed all the needed files for me and allowed me to install any packages that had a wheel. This isn't a very elegant fix since it also installed many files that I do not need, but it seems to work and is very simple.\n",
"I only solved this issue by installing ... | [
1,
1,
0,
0
] | [] | [] | [
"command_prompt",
"pip",
"python",
"python_wheel",
"windows"
] | stackoverflow_0062620393_command_prompt_pip_python_python_wheel_windows.txt |
Q:
Language names of Languages supported by Fasttext
I am trying to find out the names of languages supported by Fasttext's LID tool, given these language codes listed here:
af als am an ar arz as ast av az azb ba bar bcl be bg bh bn bo bpy br bs bxr ca cbk ce ceb ckb co cs cv cy da de diq dsb dty dv el eml en eo es ... | Language names of Languages supported by Fasttext | I am trying to find out the names of languages supported by Fasttext's LID tool, given these language codes listed here:
af als am an ar arz as ast av az azb ba bar bcl be bg bh bn bo bpy br bs bxr ca cbk ce ceb ckb co cs cv cy da de diq dsb dty dv el eml en eo es et eu fa fi fr frr fy ga gd gl gn gom gu gv he hi hif h... | [
"Most codes I found in Wikipedia's list, but some of them I found on subpage ISO 639 macrolanguage\nBut using Google to find bpy I found page ISO 639 Code Tables and probably there are all codes.\nThere is even page Download and there is file with codes iso-639-3.tab (similar to .csv)\nUsing this file and pandas (f... | [
1
] | [] | [] | [
"fasttext",
"nlp",
"python"
] | stackoverflow_0074386814_fasttext_nlp_python.txt |
Q:
Making editable table using flask and csv file as DB
I am building a flask web application with python and Javascript. So I am using csv file as a DB as this application is very lightweight(Only one user).
In a particular page I am trying to create a completely editable form. What I mean is that the table rows its... | Making editable table using flask and csv file as DB | I am building a flask web application with python and Javascript. So I am using csv file as a DB as this application is very lightweight(Only one user).
In a particular page I am trying to create a completely editable form. What I mean is that the table rows itself is editable and deletable at any place(not in the way ... | [
"try page like this\nimport csv\nfrom csv import DictReader\n\n@app.route(\"/home\")\ndef home(): \n values_list=[]\n with open(\"file.csv\", 'r') as f: #file.csv is name of the csv file\n dict_reader = DictReader(f)\n values_list = list(dict_reader)\n return render_template('home.htm... | [
0
] | [] | [] | [
"flask",
"javascript",
"python"
] | stackoverflow_0074369817_flask_javascript_python.txt |
Q:
Retrieving an array from another array
I have an array consisting of the coordinates (x,y) of certain points. I want to get an array consisting ONLY of the co-ordinates that have -0.1 <= x <= 1.1 and simultaneously -0.1 <= y <= 1.1.
I have very little experience with Python, do you have any ideas?
x_right = np.arr... | Retrieving an array from another array | I have an array consisting of the coordinates (x,y) of certain points. I want to get an array consisting ONLY of the co-ordinates that have -0.1 <= x <= 1.1 and simultaneously -0.1 <= y <= 1.1.
I have very little experience with Python, do you have any ideas?
x_right = np.array[: , 1]
for vor.vertices in coords:
if... | [
"example_points = [(.4,.5),(3,4),(.5,1)]\nresulting_points = [(x,y) for (x,y) in example_points if -0.1<=x<=1.1 and -0.1<=y<=1.1]\nprint(resulting_points)\n\nThis returns a list with the points (0.4,0.5) and (0.5,1) is this what you want?\n"
] | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074388757_numpy_python.txt |
Q:
manage variables in python for loop
below are input date values I have:
job1_started = '2020-01-01'
job1_end = '2021-01-01'
job2_started = '2022-01-01'
job2_end = '2023-01-01'
.
.
jobn_started = '2023-01-01'
jobn_end = '2023-01-01'
below is the input list I have:
lst=['job1','job2',...... 'jobn']
I need ... | manage variables in python for loop | below are input date values I have:
job1_started = '2020-01-01'
job1_end = '2021-01-01'
job2_started = '2022-01-01'
job2_end = '2023-01-01'
.
.
jobn_started = '2023-01-01'
jobn_end = '2023-01-01'
below is the input list I have:
lst=['job1','job2',...... 'jobn']
I need to loop through all values in list and ad... | [
"\nIf I understand correctly, your first question is how to retrieve a variable value by its name. I show you two ways.\n\ndata structure dict\nThere are two intrinsic directories recording all global/local variables from their names to values in the current scope, which can be obtained via globals() and locals() r... | [
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074387773_for_loop_python.txt |
Q:
How to select row by distinct column and max datetime?
Trying to get the last records I inserted in database based on DateTime and distinct column SocialMedia_ID but I get the following error DISTINCT ON fields is not supported by this database backend when it reaches to the below line:
accountsTwitter = StatsTwit... | How to select row by distinct column and max datetime? | Trying to get the last records I inserted in database based on DateTime and distinct column SocialMedia_ID but I get the following error DISTINCT ON fields is not supported by this database backend when it reaches to the below line:
accountsTwitter = StatsTwitter.objects.all().order_by('DateTime').distinct('SocialMedia... | [
"you can get the last records\nlast_record = StatsTwitter.objects.last()\n\nif you want last n records then\nlast_n_records = StatsTwitter.objects.all().order_by('-DateTime')[:n]\n\n"
] | [
0
] | [] | [] | [
"django",
"django_3.0",
"python",
"python_3.9",
"python_3.x"
] | stackoverflow_0074385993_django_django_3.0_python_python_3.9_python_3.x.txt |
Q:
Group List by another list
Let’s say I had two lists like this:
l1 = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’]
l2 = [True, True, True, False, False, True, False, True]
With Python, how could I iterate through these elements in order and group them in groups of 3 or 4 based on l2. So that the output would look like this:
... | Group List by another list | Let’s say I had two lists like this:
l1 = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’]
l2 = [True, True, True, False, False, True, False, True]
With Python, how could I iterate through these elements in order and group them in groups of 3 or 4 based on l2. So that the output would look like this:
groups = [[‘a’,’b’,’c’],[‘d’,’e’... | [
"From what I understood from your question (it took some effort) this is what you're looking for. I wrote a function that would work.\ndef group_lists(l1, l2):\n temp_val = 0\n temp_list = []\n groups = []\n for ind in range(len(l1)):\n if l2[ind]:\n temp_val += 1\n else:\n ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074388588_python.txt |
Q:
Using Bio.SeqIO to write single-line FASTA
QIIME requests this (here) regarding the fasta files it receives as input:
The file is a FASTA file, with sequences in the single line format. That is, sequences are not broken up into multiple lines of a particular length, but instead the entire sequence occupies a singl... | Using Bio.SeqIO to write single-line FASTA | QIIME requests this (here) regarding the fasta files it receives as input:
The file is a FASTA file, with sequences in the single line format. That is, sequences are not broken up into multiple lines of a particular length, but instead the entire sequence occupies a single line.
Bio.SeqIO.write of course follows the fo... | [
"BioPython's SeqIO module uses the FastaIO submodule to read and write in FASTA format.\nThe FastaIO.FastaWriter class can output a different number of characters per line but this part of the interface is not exposed via SeqIO. You would need to use FastaIO directly.\nSo instead of using:\nfrom Bio import SeqIO\nS... | [
7,
2,
1
] | [] | [] | [
"bioinformatics",
"biopython",
"fasta",
"python",
"python_2.7"
] | stackoverflow_0024156578_bioinformatics_biopython_fasta_python_python_2.7.txt |
Q:
How to create a bulleted list in ReportLab
How can I create a bulleted list in ReportLab? The documentation is frustratingly vague. I am trying:
text = ur '''
<para bulletText="•">
item 1
</para>
<para bulletText="•">
item 2
</para>
'''
Story.append(Paragraph(text,TEXT_STYLE))
But I keep getting errors ... | How to create a bulleted list in ReportLab | How can I create a bulleted list in ReportLab? The documentation is frustratingly vague. I am trying:
text = ur '''
<para bulletText="•">
item 1
</para>
<para bulletText="•">
item 2
</para>
'''
Story.append(Paragraph(text,TEXT_STYLE))
But I keep getting errors like list index out of range. It seems that I ca... | [
"The bulletText argument is actually a constructor to the Paragraph object, not the <para> tag :-) Try this:\nstory.append(Paragraph(text, TEXT_STYLE, bulletText='-'))\n\nHave a look at the examples on page 68 (page 74 now, in 2012) of the ReportLab Documentation, though. The convention in ReportLab seems to be to ... | [
10,
10,
0
] | [] | [] | [
"pdf",
"python",
"reportlab"
] | stackoverflow_0000748881_pdf_python_reportlab.txt |
Q:
Django models with key and multiple value choices
im trying to work my way into making an api oriented webapp with Django and i wanted to create a model where i can choose a day and a time for that day. So my first thought was to make a model with an atttibute that can stored set day with a set time, this last one... | Django models with key and multiple value choices | im trying to work my way into making an api oriented webapp with Django and i wanted to create a model where i can choose a day and a time for that day. So my first thought was to make a model with an atttibute that can stored set day with a set time, this last one being of multiple choice, like a dictionary or somethi... | [
"pip install django-jsonfield\n\nNow, create a model in models.py, eg: −\nimport jsonfield\nfrom django.db import models\n\n# Create your models here.\n\nclass Reservation(models.Model):\n reservations = jsonfield.JSONField()\n\nAnother option is create two separate models for Reservation & Time(Slots).\n"
] | [
0
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0074384216_django_postgresql_python.txt |
Q:
python in module of csv
The charmap' codec is unable to encode the character 'u202f' in position 168, which maps to undefined> wr.writerows(unpacking).)
I don't know what the problem is; if someone already has this problem, he can help us.
Please, if anyone can assist me!
A:
you have to change the output encodi... | python in module of csv |
The charmap' codec is unable to encode the character 'u202f' in position 168, which maps to undefined> wr.writerows(unpacking).)
I don't know what the problem is; if someone already has this problem, he can help us.
Please, if anyone can assist me!
| [
"you have to change the output encoding\nimport sys\n\nprint sys.stdout.encoding\nprint u\"Stöcker\".encode(sys.stdout.encoding, errors='replace')\nprint u\"Стоескер\".encode(sys.stdout.encoding, errors='replace')\n\nfor more click here\n"
] | [
0
] | [] | [] | [
"csv",
"python",
"python_itertools"
] | stackoverflow_0074389151_csv_python_python_itertools.txt |
Q:
Trying to access variables while scraping website; trying to get var in script
Trying to web scrape info from this website: http://www.dexel.co.uk/shopping/tyre-results?width=205&profile=55&rim=16&speed=.
For context, I'm trying to find the Tyre brand (Bridgestone, Michelin), pattern (e.g Turanza T001, Ecopia EP50... | Trying to access variables while scraping website; trying to get var in script | Trying to web scrape info from this website: http://www.dexel.co.uk/shopping/tyre-results?width=205&profile=55&rim=16&speed=.
For context, I'm trying to find the Tyre brand (Bridgestone, Michelin), pattern (e.g Turanza T001, Ecopia EP500), Tyre Size (205/55. 16 V (91), 225/50. 16 W (100) XL), Seasonality (if available)... | [
"To create a pandas dataframe from the allTyres data you can do (from the DataFrame you can select columns you want, save it to CSV etc..):\nimport re\nimport json\nimport requests\nimport pandas as pd\n\n\nurl = \"http://www.dexel.co.uk/shopping/tyre-results?width=205&profile=55&rim=16&speed=\"\n\ndata = json.load... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"python_requests",
"request",
"web_scraping"
] | stackoverflow_0074389101_beautifulsoup_python_python_requests_request_web_scraping.txt |
Q:
how to use mysql defaults file (my.cnf) with sqlalchemy?
I'd like to have sqlalchemy get the hostname, username, and password for the mysql database it's connecting to.
The documentation says mysql schemas are specified as such:
mysql_db = create_engine('mysql://scott:tiger@localhost/foo')
Is it possible to inste... | how to use mysql defaults file (my.cnf) with sqlalchemy? | I'd like to have sqlalchemy get the hostname, username, and password for the mysql database it's connecting to.
The documentation says mysql schemas are specified as such:
mysql_db = create_engine('mysql://scott:tiger@localhost/foo')
Is it possible to instead source a mysql defaults file such as /etc/my.cnf and get th... | [
"Here is a result that was found on the sqlalchemy mailing list, posted by Tom H:\nhttp://www.mail-archive.com/sqlalchemy@googlegroups.com/msg11241.html\nfrom sqlalchemy.engine.url import URL\n\nmyDB = URL(drivername='mysql', host='localhost',\n database='my_database_name',\n query={ 'read_default_file' : '/p... | [
10,
4,
4,
0
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0005344396_mysql_python_sqlalchemy.txt |
Q:
Sim808 with Mqtt (AT+CIPSEND)
i am using Sim808 GPS Module to send lat-long and using MQTT to send it to subscriber.
I followed tutorial from here to publish MQTT message over Sim808 but still no luck.
Here is my sample code:
def cmd(cmd, ser):
out = b''; prev = b"101001011"
ser.flushInput(); ser.flushOut... | Sim808 with Mqtt (AT+CIPSEND) | i am using Sim808 GPS Module to send lat-long and using MQTT to send it to subscriber.
I followed tutorial from here to publish MQTT message over Sim808 but still no luck.
Here is my sample code:
def cmd(cmd, ser):
out = b''; prev = b"101001011"
ser.flushInput(); ser.flushOutput()
ser.write(cmd + b'\r');
... | [
"I had the same issue in the beginning. I started to dig deeper into the specification of the MQTT standard here which helped a lot. Make sure to read the yellow marked paragraphs as they contain important exceptions to handle.\nI agree with the comment from @stene-oh to first connect to the broker using the Connec... | [
0
] | [] | [] | [
"at_command",
"mqtt",
"python",
"sim800",
"sim800l"
] | stackoverflow_0062025124_at_command_mqtt_python_sim800_sim800l.txt |
Q:
React JS POST http://localhost:8001/calcul net::ERR_CONNECTION_REFUSED - Back end Fastapi
I have a website developed in react js on the front end. The front makes a request (POST method) to a fastapi python back end.
On the web interface, when I click on the sent button which calls the fastapi API, there is the fo... | React JS POST http://localhost:8001/calcul net::ERR_CONNECTION_REFUSED - Back end Fastapi | I have a website developed in react js on the front end. The front makes a request (POST method) to a fastapi python back end.
On the web interface, when I click on the sent button which calls the fastapi API, there is the following error:
on my local computer, everything is working fine. But when I do the production ... | [
"Replace your API_URL from localhost to URL you have on production\n"
] | [
1
] | [] | [] | [
"axios",
"fastapi",
"python",
"reactjs"
] | stackoverflow_0074389214_axios_fastapi_python_reactjs.txt |
Q:
Error in formulation of a Derivative(PD) controller
I'm applying Proportional-Derivative controller to control my model in ROS. I'm limited to python 2.7.17 version.
There are two types of errors in this script; position error(ep) and heading error(eth).
I've given last_error=0 and trying to get the updation in (e... | Error in formulation of a Derivative(PD) controller | I'm applying Proportional-Derivative controller to control my model in ROS. I'm limited to python 2.7.17 version.
There are two types of errors in this script; position error(ep) and heading error(eth).
I've given last_error=0 and trying to get the updation in (ep_dot) and (eth_dot) as a method to find derivative of er... | [
"I think there is an issue with your calculation of the derivative terms.\nYou get t_start=time.time() at the very beginning of your code and then every time you get in your callback you update t_milli = (time.time() - t_start)*1000 and t = t_milli/1000 with t_start being a constant.\nThen you calculate ep_dot as b... | [
0
] | [] | [] | [
"control_theory",
"python",
"ros"
] | stackoverflow_0074387880_control_theory_python_ros.txt |
Q:
Bigquery - Insert new data row into table by python
I read many documents about google bigquery-python, but I can't understand how to manage bigquery data by python code.
At first, I make a new table as below.
credentials = GoogleCredentials.get_application_default()
service = build('bigquery', 'v2', credentials =... | Bigquery - Insert new data row into table by python | I read many documents about google bigquery-python, but I can't understand how to manage bigquery data by python code.
At first, I make a new table as below.
credentials = GoogleCredentials.get_application_default()
service = build('bigquery', 'v2', credentials = credentials)
project_id = 'my_project'
dataset_id = 'my... | [
"\nEDIT Nov 2018:\n\nThe answer of this question is outdated already as the google cloud client has evolved considerably since this last post. \nThe official docs contains all information needed already; here you can find everything needed for streaming insert and this one has a complete overview of all methods ava... | [
26,
0
] | [] | [] | [
"google_bigquery",
"python"
] | stackoverflow_0036673456_google_bigquery_python.txt |
Q:
Alternatives to tempfile.mkdtemp
To create and declare a temp file all the the same time I am currently using:
import tempfile
myTempFile=tempfile.mkdtemp()+'/script.txt'
While this approach works... I wonder if there are other ways to do it. What I don't like with the current setup is that:
It seems it takes so... | Alternatives to tempfile.mkdtemp | To create and declare a temp file all the the same time I am currently using:
import tempfile
myTempFile=tempfile.mkdtemp()+'/script.txt'
While this approach works... I wonder if there are other ways to do it. What I don't like with the current setup is that:
It seems it takes some time to import tempfile module.
The... | [] | [] | [
"If another another wants to use the temporary file created by another user, it would not be possible. So, if ur use case demands switching to a different user, this is not the library to go to\n"
] | [
-1
] | [
"python"
] | stackoverflow_0024190315_python.txt |
Q:
Is there a way of sending an multipart/form-data array using python requests?
Assume there's an endpoint accepting HTTP requests with multipart/form-data content-type. Here's the example of the body of an acceptable request.
----------------------------033392576939750140334380
Content-Disposition: form-data; name=... | Is there a way of sending an multipart/form-data array using python requests? | Assume there's an endpoint accepting HTTP requests with multipart/form-data content-type. Here's the example of the body of an acceptable request.
----------------------------033392576939750140334380
Content-Disposition: form-data; name="file" filename="dummy_file.txt"
Some dummy file here.
----------------------------... | [
"I found this in the docs: https://requests.readthedocs.io/en/latest/user/quickstart/#more-complicated-post-requests\nUse a list of tuples to create the mapping, not a dict:\nr = requests.post(\n \"https://httpbin.org/anything\",\n files=[\n (\"file\", (\"dummy_file.txt\", b\"File content....\")), \... | [
1
] | [] | [] | [
"http",
"multipartform_data",
"python",
"python_requests"
] | stackoverflow_0074388909_http_multipartform_data_python_python_requests.txt |
Q:
automatically appended string loop
I was supposed to built a program that would automatically print the lyrics of a song (twelve days of christmas) so that it re-prints the same message in each line, but extended by the new lyric pertaining to that line.
For instance:
verse1 = '''On the first day of Christmas
my t... | automatically appended string loop | I was supposed to built a program that would automatically print the lyrics of a song (twelve days of christmas) so that it re-prints the same message in each line, but extended by the new lyric pertaining to that line.
For instance:
verse1 = '''On the first day of Christmas
my true love sent to me:
A Partridge in a Pe... | [
"Here is a naive implementation (reference for the content):\nverses = ['a partridge in a pear tree', 'two turtle doves', 'three French hens',\n 'four calling birds', 'five gold rings', 'six geese a-laying',\n 'seven swans a-swimming', 'eight maids a-milking', 'nine ladies dancing',\n 'te... | [
0
] | [] | [] | [
"for_loop",
"nested",
"python",
"string",
"while_loop"
] | stackoverflow_0074389239_for_loop_nested_python_string_while_loop.txt |
Q:
Using Python to search google and store the websites into variables
I looking for a way to search google with python and store each website into a slot in an data list. Im looking for something like the example code below.
search=input('->')
results=google.search((search),(10))
print results
In this case i want i... | Using Python to search google and store the websites into variables | I looking for a way to search google with python and store each website into a slot in an data list. Im looking for something like the example code below.
search=input('->')
results=google.search((search),(10))
print results
In this case i want it to search google for whatever is in the variable "search", 10 is the am... | [
"As mentioned above google does provide an api for completing searches (https://developers.google.com/custom-search/json-api/v1/overview), and as mentioned depending on what you are trying to accomplish can get quite expensive. Another option is to scrap the google page. Below is an example I created using Beautifu... | [
0,
0
] | [] | [] | [
"python",
"search"
] | stackoverflow_0044421559_python_search.txt |
Q:
Optimize function's parameters with conditions (python)
I begin by saying that I am totally new to this branch of programming, but i think that scipy optimization could be the solution.
I need to find the parameters that return the highest result in a function, but only if the result respect a condition.
The funct... | Optimize function's parameters with conditions (python) | I begin by saying that I am totally new to this branch of programming, but i think that scipy optimization could be the solution.
I need to find the parameters that return the highest result in a function, but only if the result respect a condition.
The function is so long and takes more than 40 parameters, so it's imp... | [
"If you want to build from scratch, a simple completely random \"good enough\" solver might look like this.\nThe solver is the first function, the rest are your (user) functions.\nYou need\n\nyour target long and complicated function\na function that returns a score for a given generated result (or zero if the resu... | [
2
] | [] | [] | [
"optimization",
"python",
"testing"
] | stackoverflow_0074388168_optimization_python_testing.txt |
Q:
Scraping a custom ebay search with BeautifulSoup. How to handle pagination?
I am trying to scrape a custom eBay search that shows 200 items on a single page. I need to get the title of the item, the price and the link to the said item. So far so good. But I also would like the code to follow the link to the next p... | Scraping a custom ebay search with BeautifulSoup. How to handle pagination? | I am trying to scrape a custom eBay search that shows 200 items on a single page. I need to get the title of the item, the price and the link to the said item. So far so good. But I also would like the code to follow the link to the next page with 200 or less items and extract them as well.
This is the code, I am using... | [
"Your current link garners results under 200, thus, no pagination is given, however, navigating to a more popular page, such as listings for \"macbooks\" yields results on multiple pages. The link used for demonstration can be found here. To find the pages, the full pagination a tag text can be found, and when loop... | [
1,
1,
0
] | [] | [] | [
"beautifulsoup",
"ebay_api",
"python",
"web_scraping"
] | stackoverflow_0050633442_beautifulsoup_ebay_api_python_web_scraping.txt |
Q:
Why does "\n" command not working on my output?
\n is not setting a new line for a string in my code. What is the problem?
class Account():
def __init__(self, owner, balance = 0.0):
self.owner = owner
self. balance = balance
def deposit(self, amount):
self.balance += amoun... | Why does "\n" command not working on my output? | \n is not setting a new line for a string in my code. What is the problem?
class Account():
def __init__(self, owner, balance = 0.0):
self.owner = owner
self. balance = balance
def deposit(self, amount):
self.balance += amount
return (f'{amount} dollars has been deposit... | [
"You're just returning the value. Try:\nacct1 = Account('Jose',100)\nprint(acct1.deposit(50))\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074389410_python.txt |
Q:
writing a dict (of list) to a file.txt
I get stuck with writing a dict of list to a .txt file.
I have a dict of lict like this:
product_menu_list = {"Shirt": ["Red", "Orange", "Purple"], "Dress": ["Blue", "Yellow", "Green"]}
To write it into a .txt file, I wrote:
product_lines = product_menu_list
with open('produ... | writing a dict (of list) to a file.txt | I get stuck with writing a dict of list to a .txt file.
I have a dict of lict like this:
product_menu_list = {"Shirt": ["Red", "Orange", "Purple"], "Dress": ["Blue", "Yellow", "Green"]}
To write it into a .txt file, I wrote:
product_lines = product_menu_list
with open('product_record.txt', 'w') as f:
for line in p... | [
"IIUC,\nproduct_lines = product_menu_list\nwith open('product_record.txt', 'w') as f:\n for key, value in product_lines.items():\n f.write(f'{key}\\n')\n for v in value: \n f.write(f' {v}\\n')\n f.write('\\n')\n\nYou will get:\nShirt:\n Red\n Orange\n Purple\n\nDress:\... | [
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074389428_dictionary_list_python.txt |
Q:
How to de-serialize JSON data into a class and then access the values as class variables and use intellisense to access in Python
I have a JSON configuration below
body =
{
"objectId": "068acfee-e5bc-4b27-ad80-59cf0adac4d9",
"name": "abc",
"address": {
"doorNo": 23,
"pinCode": "456"
}
}
I need to ... | How to de-serialize JSON data into a class and then access the values as class variables and use intellisense to access in Python | I have a JSON configuration below
body =
{
"objectId": "068acfee-e5bc-4b27-ad80-59cf0adac4d9",
"name": "abc",
"address": {
"doorNo": 23,
"pinCode": "456"
}
}
I need to deserialize and access the values in an intuitive way by typing using IntelliSense. Currently I am doing as below
import json
class Pay... | [
"Try using types.SimpleNamespace\nimport json\nfrom types import SimpleNamespace\nyour_json_data = '{\"a\":2, \"b\":{\"c\":3\"}}'\nconvt_data = json.loads(your_json_data, object_hook=lambda d: SimpleNamespace(**d))\n# you can use it like this -> convt_data.b.c will have value 3\n\n"
] | [
1
] | [] | [] | [
"deserialization",
"json",
"python",
"serialization"
] | stackoverflow_0074389531_deserialization_json_python_serialization.txt |
Q:
I don't know how to install Pytorch
I don't know how to install Pytorch with pip on windows. No commands I do will work.
I tried:
pip install torch
pip3 install torch
pip install pytorch
pip3 install pytorch
pip install torch torchvisual torchaudio
pip3 install torch torchvisual torchaudio
pip3 install torch==1.1... | I don't know how to install Pytorch | I don't know how to install Pytorch with pip on windows. No commands I do will work.
I tried:
pip install torch
pip3 install torch
pip install pytorch
pip3 install pytorch
pip install torch torchvisual torchaudio
pip3 install torch torchvisual torchaudio
pip3 install torch==1.10.1+cu102 torchvision==0.11.2+cu102
torch... | [
"You probably tried this on Python 3.10, there isn't a build for PyTorch on PyPI for 3.10 yet. Just install Python 3.9 for the time being and you'll be fine with pip install torch.\n(note, this was posted on 2021-12-25; hello people from the future, it seems likely that this won't last too long, so your problem may... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0070476904_python.txt |
Q:
Get all processes using a file in Python
I'd like to find an efficient way to get all the processes using a particular file.
I know I can do psutil.process_iter() and then search process.open_files for the file for each process. This is very inefficient as searching every single process, and every file each proces... | Get all processes using a file in Python | I'd like to find an efficient way to get all the processes using a particular file.
I know I can do psutil.process_iter() and then search process.open_files for the file for each process. This is very inefficient as searching every single process, and every file each process has open, takes a lot of time (10 seconds on... | [
"Yes, in Windows, you can do it in the following way:\nimport ctypes\nfrom ctypes import wintypes\n\npath = r\"C:\\temp\\test.txt\"\n\n# -----------------------------------------------------------------------------\n# generic strings and constants\n# -----------------------------------------------------------------... | [
0
] | [] | [] | [
"psutil",
"python",
"python_3.x",
"windows"
] | stackoverflow_0052213420_psutil_python_python_3.x_windows.txt |
Q:
Not sure how to reorder x-axis labels on matplotlib
I have the following code. I am trying plot a graph.
Currently, the x-axis is not labelled in ascending order: 28-37.99 should come before 38-47.99 but I am not sure how to do this.
Would be so grateful for a helping hand!
fig, axes = plt.subplots(nrows=2,figsize... | Not sure how to reorder x-axis labels on matplotlib | I have the following code. I am trying plot a graph.
Currently, the x-axis is not labelled in ascending order: 28-37.99 should come before 38-47.99 but I am not sure how to do this.
Would be so grateful for a helping hand!
fig, axes = plt.subplots(nrows=2,figsize=(15, 15))
fig.tight_layout(pad=10)
newerdf = newdf.copy... | [
"The basic idea here is that the x_axis in seaborn is not capable of interpreting the given order of the data\nfig, ax = plt.subplots(nrows=1,figsize=(15, 15))\n\n\nbins = [18,28,38,48,58]\nnames = ['<28','28-37.99','38-47.99','48-57.99','58+']\nloc_x_axis = np.arange(0,len(names))\nax.plot(loc_x_axis,your_y_data)\... | [
0
] | [] | [] | [
"matplotlib",
"numpy",
"pandas",
"plot",
"python"
] | stackoverflow_0074388640_matplotlib_numpy_pandas_plot_python.txt |
Q:
Explanation for ValueError: too many values to unpack (expected 2)
I understand in the code below that I am supposed to use [i,j,k] (or a single variable) to retrieve my return values. However, I have assigned two (only i and j), instead of three to the function. This gives the error "ValueError: too many values t... | Explanation for ValueError: too many values to unpack (expected 2) | I understand in the code below that I am supposed to use [i,j,k] (or a single variable) to retrieve my return values. However, I have assigned two (only i and j), instead of three to the function. This gives the error "ValueError: too many values to unpack (expected 2)". I am still trying to understand the error. Is th... | [
"No its not due to indexing from 0.\nWhat happens under the hood is that first your function fn is evaluated, which then returns 3 values, a, b, h. Then the interpreter tries to assign these 3 values into your two variables i, j (essentially unpacking them). Since the left hand side contains 2 variables, the interp... | [
1,
0
] | [] | [] | [
"function",
"python",
"valueerror"
] | stackoverflow_0074389603_function_python_valueerror.txt |
Q:
Numpy: Find indexes of rows in another array
I have two arrays containing lists of 3d coordinates.
I am trying to get a list of the indexes where each element in my array is found in another array.
a = np.array([[0.4,0.6,0.8],
[0.4, 1.0, 1.2],
[0.6,1.0,1.4],
[0.6,1.2,1.6]]... | Numpy: Find indexes of rows in another array | I have two arrays containing lists of 3d coordinates.
I am trying to get a list of the indexes where each element in my array is found in another array.
a = np.array([[0.4,0.6,0.8],
[0.4, 1.0, 1.2],
[0.6,1.0,1.4],
[0.6,1.2,1.6]])
b = np.array([[0.4, 1.0, 1.2],
[0... | [
"You can use b[:,None] for the comparison. It is a special kind of slicing that allows you to compare both arrays row-wise, since the shape of b is now (5,1,3), instead of (5,3).\nidx = np.where( (a==b[:,None]).all(-1) )[1]\n\n#output of idx: [1 0 3 2 2]\n\n"
] | [
0
] | [] | [] | [
"arrays",
"numpy",
"pandas",
"python",
"scipy"
] | stackoverflow_0074387093_arrays_numpy_pandas_python_scipy.txt |
Q:
How to print all messages available in json object received from github in python?
I have received a json object that shows comparison between two tags on github repo. I want to show all messages that are available inside the JSON object. The json object can be seen here: https://api.github.com/repos/git/git/compa... | How to print all messages available in json object received from github in python? | I have received a json object that shows comparison between two tags on github repo. I want to show all messages that are available inside the JSON object. The json object can be seen here: https://api.github.com/repos/git/git/compare/v2.37.4...v2.38.1
I have used the requests library available in python to receive the... | [
"Here this will help\nimport requests\nresponse= requests.get('https://api.github.com/repos/git/git/compare/v2.37.4...v2.38.1')\njson_obj=response.json()\nfor i in json_obj.keys():\n print(i , json_obj[i]) # there i is for the the key and json_obj[i] gives the value at the key\nprint(json_obj[\"base_commit\"][... | [
0,
0
] | [] | [] | [
"github_api",
"json",
"python"
] | stackoverflow_0074388741_github_api_json_python.txt |
Q:
Check if a file is not open nor being used by another process
I my application, i have below requests:
1. There has one thread will regularly record some logs in file. The log file will be rollovered in certain interval. for keeping the log files small.
2. There has another thread also will regularly to process th... | Check if a file is not open nor being used by another process | I my application, i have below requests:
1. There has one thread will regularly record some logs in file. The log file will be rollovered in certain interval. for keeping the log files small.
2. There has another thread also will regularly to process these log files. ex: Move the log files to other place, parse the log... | [
"An issue with trying to find out if a file is being used by another process is the possibility of a race condition. You could check a file, decide that it is not in use, then just before you open it another process (or thread) leaps in and grabs it (or even deletes it).\nOk, let's say you decide to live with that... | [
59,
37,
35,
8,
3,
3,
2,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0011114492_file_python.txt |
Q:
How to return every N alternate rows from a pandas dataframe?
Let's say I have a dataframe with 1000 rows. Is there an easy way of slicing the datframe in sucha way that the resulting datframe consisits of alternating N rows?
For example, I want rows 1-100, 200-300, 400-500, ....and so on and skip 100 rows in betw... | How to return every N alternate rows from a pandas dataframe? | Let's say I have a dataframe with 1000 rows. Is there an easy way of slicing the datframe in sucha way that the resulting datframe consisits of alternating N rows?
For example, I want rows 1-100, 200-300, 400-500, ....and so on and skip 100 rows in between and create a new dataframe out of this.
I can do this by storin... | [
"You can use:\nimport numpy as np\nout = df[np.arange(len(df))%200<100]\n\nfor the demo here is an example with 1-10, 20-30, etc.\ndf = pd.DataFrame(index=range(100))\nout = df[np.arange(len(df))%20<10]\nout.index\n\noutput:\nInt64Index([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, # rows 1-10\n 20, 21, 22, ... | [
2,
1
] | [] | [] | [
"dataframe",
"filter",
"pandas",
"python",
"slice"
] | stackoverflow_0074389643_dataframe_filter_pandas_python_slice.txt |
Q:
null value in column "assigned_facilities_id"
I'm trying to access the dictonary inside the jsonfield serializer "assigned_facilities". But i'm receiving the following error:
django.db.utils.IntegrityError: null value in column "assigned_facilities_id" of relation "users_leadfacilityassign" violates not-null const... | null value in column "assigned_facilities_id" | I'm trying to access the dictonary inside the jsonfield serializer "assigned_facilities". But i'm receiving the following error:
django.db.utils.IntegrityError: null value in column "assigned_facilities_id" of relation "users_leadfacilityassign" violates not-null constraint
DETAIL: Failing row contains (78, null, null,... | [
"You have three tables:\n\nLead table in which lead_id is non nullable since it is primary key\nFacility table in which facility_id is non nullable since it is primary key\nLeadFacility table in which lead_facility_id is non nullable but its two foreign keys (lead_id and facility_id) are nullable.\nAnd you are assi... | [
3,
1,
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"json",
"python"
] | stackoverflow_0074287146_django_django_rest_framework_json_python.txt |
Q:
Substring a column in pandas
I have a dataframe like this
Index
Identifier
0
10769289.0
1
1082471174.0
The "Identifier column is a string column" and I need to remove the ".0"
I'm using the following code:
Dataframe["Identifier"] = Dataframe["Identifier"].replace(regex=['.0'],value='')
But I got this:
IndexId... | Substring a column in pandas | I have a dataframe like this
Index
Identifier
0
10769289.0
1
1082471174.0
The "Identifier column is a string column" and I need to remove the ".0"
I'm using the following code:
Dataframe["Identifier"] = Dataframe["Identifier"].replace(regex=['.0'],value='')
But I got this:
IndexIdentifier0769289182471174... | [
"The dot (.) in regex or in replace can indicate any character. Therefore you have to escape the decimal point. Otherwise it will replace any character followed by a zero. Which in your case would mean that it would replace the 10 at the beginning of 10769289.0 and 1082471174.0, as well as the .0 at the end of each... | [
0
] | [] | [] | [
"python",
"str_replace",
"string"
] | stackoverflow_0074389680_python_str_replace_string.txt |
Q:
How to replace value in list of lists - Python
Hi everyone this is my first question , so please tell me how can I improve asking :),
I'm trying to run this code and I'm not getting the expected result .
i think the problem is that I'm editing values in list of lists
the code :
def f(x1,x2):
return 1.5*(x1)**2... | How to replace value in list of lists - Python | Hi everyone this is my first question , so please tell me how can I improve asking :),
I'm trying to run this code and I'm not getting the expected result .
i think the problem is that I'm editing values in list of lists
the code :
def f(x1,x2):
return 1.5*(x1)**2+0.5*(x2**2)-x1*x2-2*x1
def f_tag_x1 (lst):
x2=l... | [
"This is because x.append(x[k - 1]) appends the same list every time, so every change to one sublist changes all of them. Append a copy instead\nwhile k < 3:\n x.append(x[k - 1][:])\n ...\n\nprint(x) # [[-2, 4], [2.0, 2.0], [1.3333333333333335, 1.3333333333333335]]\n\n"
] | [
0
] | [] | [] | [
"append",
"arrays",
"list",
"numpy",
"python"
] | stackoverflow_0074389735_append_arrays_list_numpy_python.txt |
Q:
What is the concept on Start:Stop:Step
I am new to python and I seem to be unable to understand the concept in Start:Stop:Step. For example
word = "Champ"
print (word[0:5:2])
why do I get cap as I result ? if someone could help me with this I would truly appreciated
I tried using different numbers to see what the ... | What is the concept on Start:Stop:Step | I am new to python and I seem to be unable to understand the concept in Start:Stop:Step. For example
word = "Champ"
print (word[0:5:2])
why do I get cap as I result ? if someone could help me with this I would truly appreciated
I tried using different numbers to see what the outcome was but even there I was not able to... | [
"Let's see this way:\nword = \"Champ\"\n\nprint (word[0:5:2])\n# you are taking index=0, then index=0+2, then index=0+2+2\n# then index=0+2+2+2 (don't have this)\n# so you got 0,2, and 4\n# Hope, makes sense\n\nprint(word[0])\nprint(word[2])\nprint(word[4])\n\n",
"Maybe it's best to imagine it as a simple while-l... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074382817_python.txt |
Q:
Creating or modify function variable from outer scope python
I wrote this code and received an unexpected output than I thought.
def egg():
print(a)
egg() # NameError: name 'a' is not defined **As excepted**
egg.a = 50
egg() # NameError: name 'a' is not defined **Not as excepted**
My hope was that after se... | Creating or modify function variable from outer scope python | I wrote this code and received an unexpected output than I thought.
def egg():
print(a)
egg() # NameError: name 'a' is not defined **As excepted**
egg.a = 50
egg() # NameError: name 'a' is not defined **Not as excepted**
My hope was that after setting agg.a = 50 the next time I would call agg() a variable will... | [
"uisng non local params\ndef main():\n def egg():\n nonlocal a\n print(a)\n\n #egg() # NameError: name 'a' is not defined **As excepted**\n\n a = 50\n\n egg()\nmain()\n\noutput\n50\n\n",
"Callable class can be used to replicate this sort of behaviour without breaking the encapsulation of... | [
2,
0
] | [] | [] | [
"function",
"python",
"scope"
] | stackoverflow_0074389721_function_python_scope.txt |
Q:
What is 'tk::placeWindow' and how can it center the window on my screen?
Im trying to find a way to center the window of a simple counter I made using Tkinter. Trying to find another way than using geometry I came across:
window.eval('tk::placeWindow . center')
But I don't know why this works and also I cant find... | What is 'tk::placeWindow' and how can it center the window on my screen? | Im trying to find a way to center the window of a simple counter I made using Tkinter. Trying to find another way than using geometry I came across:
window.eval('tk::placeWindow . center')
But I don't know why this works and also I cant find it in the documentation. Anyone knows the answer?
| [
"The code below executes code that is written in tcl and calls a tcl procedure. There are quite a few of them, but they mostly used for internal procedures and rarely useful.\nwindow.eval('tk::placeWindow . center')\n\nThe placeWindow procedure can be found here and does nothing that you couldn't do with python. Th... | [
5
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074389627_python_tkinter.txt |
Q:
AttributeError, What am I doing wrong here?
I have a program that I cannot call to run, where I try to call the linearSearch() def from spellCheck.py. Can someone help me understand why my code gives me a AttributeError? I do not understand why when calling initial.linearSearch(choice) won't give me anything.
spel... | AttributeError, What am I doing wrong here? | I have a program that I cannot call to run, where I try to call the linearSearch() def from spellCheck.py. Can someone help me understand why my code gives me a AttributeError? I do not understand why when calling initial.linearSearch(choice) won't give me anything.
spellCheck.py:
class SpellCheck():
def __init__(s... | [
"binarySearch(self, word) and linearSearch(word) are the functions of __init__\nthat's why you are not getting any error on initial.linearSearch(choice).\nIf you want them to be separate functions of SpellCheck() then unindent them.\n"
] | [
3
] | [] | [] | [
"attributeerror",
"python"
] | stackoverflow_0074389747_attributeerror_python.txt |
Q:
How to efficiently apply a function recursively to all arguments in python?
I'd like to be able to apply some function fn to all arguments args arbitrarily i.e. regardless of the structure of the arguments. A recursive approach works.
def convert_args(args, fn):
if isinstance(args, tuple):
ret_list = [... | How to efficiently apply a function recursively to all arguments in python? | I'd like to be able to apply some function fn to all arguments args arbitrarily i.e. regardless of the structure of the arguments. A recursive approach works.
def convert_args(args, fn):
if isinstance(args, tuple):
ret_list = [convert_args(i, fn) for i in args]
return tuple(ret_list)
elif isinst... | [
"You could have the behaviour for each args type defined separately as you were doing now, without recursion:\ndef convert_args(args, fn):\n if isinstance(args, tuple):\n return tuple([fn(i) for i in args])\n elif isinstance(args, list):\n return [fn(i) for i in args]\n elif isinstance(args, ... | [
0
] | [] | [] | [
"cython",
"performance",
"python",
"recursion"
] | stackoverflow_0074389493_cython_performance_python_recursion.txt |
Q:
What is the easiest way to scatter plot a set of grade in Python?
I am developing a program to show the results of a study. Thirty high school students were surveyed in a study involving time spent on the Internet and their grade point average (GPA). The results are shown in Table 13.1. X is the amount of time spe... | What is the easiest way to scatter plot a set of grade in Python? | I am developing a program to show the results of a study. Thirty high school students were surveyed in a study involving time spent on the Internet and their grade point average (GPA). The results are shown in Table 13.1. X is the amount of time spent on the Internet weekly and Y is the GPA of the student.
Given the da... | [
"# Author: Evan Gertis\n# Date : 11/09\n# program: Linear Regression\n# Resource: https://seaborn.pydata.org/generated/seaborn.scatterplot.html \nimport seaborn as sns\nimport pandas as pd\nimport logging\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\n# Step 1... | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074381491_matplotlib_pandas_python.txt |
Q:
FastAPI - after successful login, no Authorization header received, also from Swagger and only when deployed on server
My FastAPI works in my localhost, but when deployed on a server the following happens:
Login succeeds and token is retrieved from the response.
After the successful login, any API call requiring t... | FastAPI - after successful login, no Authorization header received, also from Swagger and only when deployed on server | My FastAPI works in my localhost, but when deployed on a server the following happens:
Login succeeds and token is retrieved from the response.
After the successful login, any API call requiring the dependency oauth2_scheme, raise error 401, including from Swagger.
Debugging the issue, there is no Authorization header ... | [
"Solved, the cause was a hard-to-find network setting that was dropping the auth header from http requests, totally unrelated with FastAPI.\n"
] | [
0
] | [] | [] | [
"docker",
"fastapi",
"oauth_2.0",
"python",
"swagger"
] | stackoverflow_0074362487_docker_fastapi_oauth_2.0_python_swagger.txt |
Q:
Create a QTableWidgetItem with flags()
I dont understand the Qt5 Documentation in the TableWidgetItem-Chapter.
I cant get the right parameters to set my freshly created TableCell as editable.
I've got this piece of code
for i, item in enumerate(event_desc, start=0):
print(i, item)
key = Q... | Create a QTableWidgetItem with flags() | I dont understand the Qt5 Documentation in the TableWidgetItem-Chapter.
I cant get the right parameters to set my freshly created TableCell as editable.
I've got this piece of code
for i, item in enumerate(event_desc, start=0):
print(i, item)
key = QTableWidgetItem(list(event_desc)[i])
... | [
"If you must set a QTableWidgetItem as editable you must do:\nvalue.setFlags(value.flags() | QtCore.Qt.ItemIsEditable)\n\nThe operator | allows to enable a flag, and instead the operation & ~ disables them.\n",
"Additionally, if you use Pyside6 lib like me, the flag may be changed as,\nQt.ItemIsEditable or ~Qt.It... | [
3,
0
] | [] | [] | [
"pyqt",
"pyqt5",
"python",
"qtablewidget",
"qtablewidgetitem"
] | stackoverflow_0058124062_pyqt_pyqt5_python_qtablewidget_qtablewidgetitem.txt |
Q:
Find time shift of two signals using cross correlation
I have two signals which are related to each other and have been captured by two different measurement devices simultaneously.
Since the two measurements are not time synchronized there is a small time delay between them which I want to calculate. Additionally... | Find time shift of two signals using cross correlation | I have two signals which are related to each other and have been captured by two different measurement devices simultaneously.
Since the two measurements are not time synchronized there is a small time delay between them which I want to calculate. Additionally, I need to know which signal is the leading one.
The follow... | [
"A popular approach: timeshift is the lag corresponding to the maximum cross-correlation coefficient. Here is how it works with an example:\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nimport numpy as np\n\n\ndef lag_finder(y1, y2, sr):\n n = len(y1)\n\n corr = signal.correlate(y2, y1, mode='sa... | [
17,
2,
0,
0
] | [] | [] | [
"cross_correlation",
"lag",
"python",
"python_2.7",
"signal_processing"
] | stackoverflow_0041492882_cross_correlation_lag_python_python_2.7_signal_processing.txt |
Q:
Run multiple FTP server instances on same local machine using multiprocessing and pyftpdlib python
I am trying to run multiple instances of FTP servers on same localhost using the following code:
# "create_multiple_ftp_servers.py"
from multiprocessing import Pool
import sys
sys.path.insert(1, r'C:\Users\Desktop\... | Run multiple FTP server instances on same local machine using multiprocessing and pyftpdlib python | I am trying to run multiple instances of FTP servers on same localhost using the following code:
# "create_multiple_ftp_servers.py"
from multiprocessing import Pool
import sys
sys.path.insert(1, r'C:\Users\Desktop\PythonCodes')
import create_ftp_server
ftp_server_dict = {'ftp1': ['127.0.0.1', 'test', 'test@123', r'... | [
"The serve_forever() call is what is causing you issues. This call never returns and is running an infinite loop.\nThe only way I see you could handle this is to run your FTP servers in background threads, one thread per server or using a concurrency library like GEvent (which would ultimately do the same thing as ... | [
0
] | [] | [] | [
"multiprocess",
"pyftpdlib",
"python"
] | stackoverflow_0074389715_multiprocess_pyftpdlib_python.txt |
Q:
How to design an interface including multiprocessing in Python?
I am pretty new in the context of Python programming and code design, so I wanted to ask a question about how to design code right in my example declared in title.
My code includes a client and a server. They are used to obtain and send information to... | How to design an interface including multiprocessing in Python? | I am pretty new in the context of Python programming and code design, so I wanted to ask a question about how to design code right in my example declared in title.
My code includes a client and a server. They are used to obtain and send information to a third-party-program which API is not supported via Python, so I ha... | [
"Python is an object-oriented language that supports classes, which are ideal for encapsulation:\nimport multiprocessing as mp\nfrom ctypes import c_int\nfrom multiprocessing import Value\n\nclass ClientServer:\n def __init__(self) -> None:\n # Where is client defined? It seems like it should be saved her... | [
0
] | [] | [] | [
"multiprocessing",
"package",
"python",
"python_3.10"
] | stackoverflow_0074292109_multiprocessing_package_python_python_3.10.txt |
Q:
Get the frequency of the elements in a column
I have a directory with several files tab-delimited (txt format). Each file is a table with a lot of rows, but I am interested in the 10th column. I want to extract all uniq values of this column and count the occurrence for all files. For this purpose, I have used the... | Get the frequency of the elements in a column | I have a directory with several files tab-delimited (txt format). Each file is a table with a lot of rows, but I am interested in the 10th column. I want to extract all uniq values of this column and count the occurrence for all files. For this purpose, I have used the code below in bash, which works, but when the file... | [
"Here is another option in R:\nlibrary(data.table)\n\nfile_list <- list.files(pattern = \"\\\\.txt\")\n\nmyData <- lapply(file_list, \\(x){\n dat <- fread(x, select = 10) |>\n table() |>\n data.table()\n dat[,file := sub(\"\\\\.txt\", \"\", x)]\n}) |>\n rbindlist()\n\nfinal <- myData[, .(`Nº of repeats` = ... | [
1,
0,
0
] | [] | [] | [
"count",
"loops",
"python",
"r"
] | stackoverflow_0074388974_count_loops_python_r.txt |
Q:
TypeError: argument should be a bytes-like object or ASCII string, not 'tuple'
I want to write dictionary contents to file and save.
I just got this message:
TypeError: argument should be a bytes-like object or ASCII string, not 'tuple'
#Creation of dictionary
final_dict = {}
final_dict['file_name']=d['filename'] ... | TypeError: argument should be a bytes-like object or ASCII string, not 'tuple' | I want to write dictionary contents to file and save.
I just got this message:
TypeError: argument should be a bytes-like object or ASCII string, not 'tuple'
#Creation of dictionary
final_dict = {}
final_dict['file_name']=d['filename']
final_dict1 = {}
final_dict1['binary']=temp
final_dict1['type']=temp1
V10=((['fil... | [
"To be written to a file, objects first need to be converted to str or bytes object depending on the writing mode\n(see Methods of File Objects):\nwith open(file_name, \"w\") as file:\n file.write(str( my_object ))\n\nIf you want to encode (not decode) it in base64 just call b64encode on str(my_object).encode() ... | [
1
] | [] | [] | [
"dictionary",
"json",
"python"
] | stackoverflow_0074389066_dictionary_json_python.txt |
Q:
Making a custom cumsum for Python, by using my own step in-between
I'm working on making a custom Van Westendorp calculator and to make graphs in powerpoint I need to calculate cumulative frequencies. However, I don't want those frequencies to only be per prices (column A):. If I did, I would simply use the cumsum... | Making a custom cumsum for Python, by using my own step in-between | I'm working on making a custom Van Westendorp calculator and to make graphs in powerpoint I need to calculate cumulative frequencies. However, I don't want those frequencies to only be per prices (column A):. If I did, I would simply use the cumsum() function on the column B, representing their frequencies.
I want to c... | [
"You can make a custom function using apply\nWhen you have two dataframes:\ndf = pd.DataFrame(\n {\n 'A':[0.5, 1, 2, 3, 3.5, 4, 5, 5.99, 6, 7.5], \n 'B':[0, 0, 4, 3, 1, 3, 5, 1, 0, 0]\n })\ndf2 = pd.DataFrame({'C':range(0, 10, 2)})\n\nTo get the D column you apply a custom function to df2 where you filt... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074388043_pandas_python.txt |
Q:
Airflow create new tasks based on task return value
How can I get xcom from an airflow task and create other tasks using theses values.
Per exemple:
def func_test():
return ['task_2', 'task_3']
with DAG(
'dag_name',
schedule_interval="@once",
start_date=datetime(2022, 4, 19),
catchup=False,
... | Airflow create new tasks based on task return value | How can I get xcom from an airflow task and create other tasks using theses values.
Per exemple:
def func_test():
return ['task_2', 'task_3']
with DAG(
'dag_name',
schedule_interval="@once",
start_date=datetime(2022, 4, 19),
catchup=False,
default_args= {
'depends_on_past': False,
'retr... | [
"Dynamic task mapping was introduced in Airflow 2.3 to support this use case. While you can use \"classic\" Airflow operators, I suggest using dynamic task mapping in combination with the TaskFlow API, which makes it a lot easier:\nimport datetime\n\nfrom airflow.decorators import task\nfrom airflow.models import D... | [
2
] | [] | [] | [
"airflow",
"python"
] | stackoverflow_0074389804_airflow_python.txt |
Q:
Python Confluent AvroDeserializer - why it is needed to supply schema
The Confluent AvroDeserializer requires the schema_str. However, I do not want to supply the schema, I just need to retrieve it from the registry, and that's it. What am I missing?
classconfluent_kafka.schema_registry.avro.AvroDeserializer(schem... | Python Confluent AvroDeserializer - why it is needed to supply schema | The Confluent AvroDeserializer requires the schema_str. However, I do not want to supply the schema, I just need to retrieve it from the registry, and that's it. What am I missing?
classconfluent_kafka.schema_registry.avro.AvroDeserializer(schema_str, schema_registry_client, from_dict=None)
Doc: https://docs.confluent... | [
"Avro requires a reader schema.\nYou can use the Registry client to fetch a schema string.\n",
"So it really is optional for Python AvroDeserializer; however, it is not (well) documented. The parameters are following:\nclassconfluent_kafka.schema_registry.avro.AvroDeserializer(schema_registry_client, schema_str=N... | [
0,
0
] | [] | [] | [
"avro",
"confluent_schema_registry",
"python"
] | stackoverflow_0074374960_avro_confluent_schema_registry_python.txt |
Q:
Python slice with negative indices experiment
In python tutorial(https://docs.python.org/3/tutorial/introduction.html#strings),
slicing is explained as to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string... | Python slice with negative indices experiment | In python tutorial(https://docs.python.org/3/tutorial/introduction.html#strings),
slicing is explained as to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:
Moving ... | [
"In slicing, \"stop\"-bounds (not using upper bound, or lower bound to avoid confusion if using forward slices) are not considered. Which explains why you do not have the expected result in case 1.\nIf you want to print \"nothyP\", you can use write the following expression: print(word[::-1]). As you see, when you ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074389848_python.txt |
Q:
how do i loop over values within a for loop in python?
I have a df
1 1 2 2
2 2 1 1
I have written a function which:
takes the df in a for loop,
adds row(s) with a default value
replaces the values with another value in randomly selected cols
writes to csv
This is my code:
def add_x(df, max):... | how do i loop over values within a for loop in python? | I have a df
1 1 2 2
2 2 1 1
I have written a function which:
takes the df in a for loop,
adds row(s) with a default value
replaces the values with another value in randomly selected cols
writes to csv
This is my code:
def add_x(df, max):
gt_w_x = df.copy()
counter = 0
for i in rang... | [
"You can use a nested for loop. It works just like the one you have at the beginning of the function:\ndef add_x(df, max):\n for x in range(1,3):\n gt_w_x = df.copy()\n counter = 0\n\n for i in range(1, max):\n if len(gt_w_x) != max:\n counter+=1\n # ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074390062_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.