content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to split one column into 3 columns in python or PySpark
I have:
Customerkeycode
B01:B14:110083
I want:
PlanningCustomerSuperGroupCode, DPGCode, APGCode
BO1, B14, 110083
A:
import pandas as pd
df = pd.DataFrame(
{
"Customerkeycode": [
"B01:B14:110083",
... | How to split one column into 3 columns in python or PySpark | I have:
Customerkeycode
B01:B14:110083
I want:
PlanningCustomerSuperGroupCode, DPGCode, APGCode
BO1, B14, 110083
| [
"import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"Customerkeycode\": [\n \"B01:B14:110083\",\n \"B02:B15:110084\"\n ]\n }\n)\n\ndf['PlanningCustomerSuperGroupCode'] = df['Customerkeycode'].apply(lambda x: x.split(\":\")[0])\ndf['DPGCode'] = df['Customerkeycode'].apply(lamb... | [
0,
0,
0
] | [] | [] | [
"apache_spark_sql",
"list",
"pyspark",
"python"
] | stackoverflow_0074134988_apache_spark_sql_list_pyspark_python.txt |
Q:
In pandas splitting the column on question mark (?)
I have a file with the value as below (mix of values in a column with ? and without ?):
/a/b/c?abc=0
d/e/f
I just need the rows that contains "?"
then,
split this row using the "?", so that I get the output as /a/b/c as one column and anything after as other col... | In pandas splitting the column on question mark (?) | I have a file with the value as below (mix of values in a column with ? and without ?):
/a/b/c?abc=0
d/e/f
I just need the rows that contains "?"
then,
split this row using the "?", so that I get the output as /a/b/c as one column and anything after as other column
I have tried as below :
data['url'].str.contains("?"... | [
"Use Series.str.extract for get values after ? with escape by \\ because special regex character and $ for end of string:\ndata['new'] = data['url'].str.extract('\\?(.*)$')\nprint (data)\n url new\n0 /a/b/c?abc=0 abc=0\n1 d/e/f NaN\n\nYour solution working if escape ?, because not exist s... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074136435_pandas_python.txt |
Q:
Failed to compile .c file generated by cython
I'm using cython to convert my python file into c file, but when I tried to compile the c file, it failed for me.
Python.h: No such file or directory
#include "Python.h"
^
compilation terminated.
I read this post: Cython Fatal Error: Python.... | Failed to compile .c file generated by cython | I'm using cython to convert my python file into c file, but when I tried to compile the c file, it failed for me.
Python.h: No such file or directory
#include "Python.h"
^
compilation terminated.
I read this post: Cython Fatal Error: Python.h No such file or directory
But I can't understand ... | [
"Use:\nsudo updatedb\n\nlocate Python.h\n\nexport CPATH=/usr/include/python3.5m:$CPATH \n\n(change your python version here)\n\nexport LD_LIBRARY_PATH=/usr/lib:$LD_LIBRARY_PATH\n\n\n"
] | [
0
] | [] | [] | [
"cython",
"python"
] | stackoverflow_0061831582_cython_python.txt |
Q:
python recursive dict search in list
I need some help recursively searching a python dict that contains nested lists.
I have a structure like the below example. The value of key "c" is a list of one or more dicts. The structure can be nested multiple times (as you can see in the second item), but the pattern is th... | python recursive dict search in list | I need some help recursively searching a python dict that contains nested lists.
I have a structure like the below example. The value of key "c" is a list of one or more dicts. The structure can be nested multiple times (as you can see in the second item), but the pattern is the same. In all likelihood, the nested dept... | [
"You could probably use a function like this:\ndef process_dict(my_dict):\n if my_dict['ref'] == 'hij789':\n my_dict['b'] = 'something'\n if 'c' in my_dict:\n for d in my_dict['c']:\n process_dict(d)\n\nand just use\nprocess_dict(my_dict)\n\nto produce the desired result, assuming I u... | [
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074134047_python.txt |
Q:
Getting the literal out of a python Literal type, at runtime?
How can I get the literal value out of a Literal[] from typing?
from typing import Literal, Union
Add = Literal['add']
Multiply = Literal['mul']
Action = Union[Add,Multiply]
def do(a: Action):
if a == Add:
print("Adding!")
elif a == Mu... | Getting the literal out of a python Literal type, at runtime? | How can I get the literal value out of a Literal[] from typing?
from typing import Literal, Union
Add = Literal['add']
Multiply = Literal['mul']
Action = Union[Add,Multiply]
def do(a: Action):
if a == Add:
print("Adding!")
elif a == Multiply:
print("Multiplying!")
else:
raise Value... | [
"The typing module provides a function get_args which retrieves the arguments with which your Literal was initialized.\n>>> from typing import Literal, get_args\n>>> l = Literal['add', 'mul']\n>>> get_args(l)\n('add', 'mul')\n\nHowever, I don't think you gain anything by using a Literal for what you propose. What w... | [
32,
0
] | [] | [] | [
"literals",
"python",
"python_3.8",
"types",
"typing"
] | stackoverflow_0059163553_literals_python_python_3.8_types_typing.txt |
Q:
Tensor slicing: tensorflow vs pytorch
I was testing this simple slicing operation in TF and PyTorch which should match in both
import tensorflow as tf
import numpy as np
import torch
tf_x = tf.random.uniform((4, 64, 64, 3))
pt_x = torch.Tensor(tf_x.numpy())
pt_x = pt_x.permute(0, 3, 1, 2)
# slicing operation
prin... | Tensor slicing: tensorflow vs pytorch | I was testing this simple slicing operation in TF and PyTorch which should match in both
import tensorflow as tf
import numpy as np
import torch
tf_x = tf.random.uniform((4, 64, 64, 3))
pt_x = torch.Tensor(tf_x.numpy())
pt_x = pt_x.permute(0, 3, 1, 2)
# slicing operation
print(np.any(pt_x[:, :, 1:].permute(0, 2, 3, 1)... | [
"On one hand, you have pt_x equal to tf_x, use np.isclose to verify:\n>>> np.isclose(pt_x.view(b, h, w, c).numpy(), tf_x.numpy()).all()\nTrue\n\nOn the other hand, you are slicing both tensors differently: pt_x[:, :, 1:] removes the first element along axis=2, while tf_x[:, 1:] removed the first element along axis=... | [
1
] | [] | [] | [
"numpy",
"python",
"pytorch",
"slice",
"tensorflow"
] | stackoverflow_0074136269_numpy_python_pytorch_slice_tensorflow.txt |
Q:
ImportError: cannot import name 'Celery'
I'm trying to learn Celery i'm using Django 2.0 and celery 5.0.2 and my os is Ubuntu.
This is my structure
My project structure is:
celery/
manage.py
celery/
__init__.py
cerely_app.py
settings.py
urls.py
wsgi.py
apps/
main/
__init__.... | ImportError: cannot import name 'Celery' | I'm trying to learn Celery i'm using Django 2.0 and celery 5.0.2 and my os is Ubuntu.
This is my structure
My project structure is:
celery/
manage.py
celery/
__init__.py
cerely_app.py
settings.py
urls.py
wsgi.py
apps/
main/
__init__.py
admin.py
apps.py
mo... | [
"I recently upgraded from Python 3.6 to Python 3.7 and I am using Celery 4.4.6 and Django 2.2.x and it also gave me a similar error:\nImportError: cannot import name 'Celery' from 'celery'\n\nHowever, as I had my project setup as told in the docs it was referring to the right package. Only after some lost hours I s... | [
6,
2
] | [] | [] | [
"celery",
"django",
"python",
"python_3.x"
] | stackoverflow_0065011159_celery_django_python_python_3.x.txt |
Q:
"BadZipFile: File is not a zip file" - Error popped up all of a sudden
One minute my script works multiple days in a row, next minute I get this error.
File "<ipython-input-196-abdb28a77366>", line 1, in <module>
runfile('F:/-/-/-/cleaner_games_appstore_babil.py', wdir='F:/-/-/-')
File "C:\ProgramData\Ana... | "BadZipFile: File is not a zip file" - Error popped up all of a sudden | One minute my script works multiple days in a row, next minute I get this error.
File "<ipython-input-196-abdb28a77366>", line 1, in <module>
runfile('F:/-/-/-/cleaner_games_appstore_babil.py', wdir='F:/-/-/-')
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line ... | [
"Excel XLSX files are zipped, XLS files are not.\nI believe this bug is related to a combination of\n\nXLS is not zipped, and\nSince python-3.9, the openpyxl module must be used with XLSX files.\n\nThis problem is easy to solve by checking which type of Excel file is uploaded and using the appropriate engine to rea... | [
8,
5,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0057817758_python.txt |
Q:
Django Filter by ForeignKey value
Suppose I have two models
class DocumentType(BaseModel):
name = models.CharField(max_length=128)
code = models.CharField(max_length=128)
exp_days = models.PositiveIntegerField("Remind me before (Days)", blank=True, null=True)
def __str__(self):
return str(... | Django Filter by ForeignKey value | Suppose I have two models
class DocumentType(BaseModel):
name = models.CharField(max_length=128)
code = models.CharField(max_length=128)
exp_days = models.PositiveIntegerField("Remind me before (Days)", blank=True, null=True)
def __str__(self):
return str(self.name)
class Document(BaseModel):... | [
"You can use F() object that represents the value of a model field. so to reference exp_days from related model you can use F('type__exp_days')\nAn answer from Lutz Prechelt shows how to move the F() expression outside the timedelta.\nHere is the modified code\nfrom django.db.models import F\n\ndocuments = Document... | [
1
] | [] | [] | [
"django",
"django_filter",
"django_orm",
"python"
] | stackoverflow_0074134592_django_django_filter_django_orm_python.txt |
Q:
Cannot make Sentry work with Google Cloud Function (python 3.9)
I'm desperately trying to monitor a python 3.9 Google Cloud function exceptions with Sentry, but cannot make it work. Even with the tiny function shown below, exceptions are not ingested into Sentry. I already triple-check the DSN.
# main.py
import se... | Cannot make Sentry work with Google Cloud Function (python 3.9) | I'm desperately trying to monitor a python 3.9 Google Cloud function exceptions with Sentry, but cannot make it work. Even with the tiny function shown below, exceptions are not ingested into Sentry. I already triple-check the DSN.
# main.py
import sentry_sdk
from sentry_sdk.integrations.gcp import GcpIntegration
sent... | [
"GcpIntegration is currently only available for Python 3.7 - check code reference here.\nYou can make it work, if you use serverless_function decorator:\nimport sentry_sdk\nfrom sentry_sdk.integrations.serverless import serverless_function\n\nsentry_sdk.init(\n dsn=\"https://***@***.ingest.sentry.io/***\",\n)\n\... | [
0
] | [] | [] | [
"google_cloud_functions",
"python",
"python_3.x",
"sentry"
] | stackoverflow_0073970481_google_cloud_functions_python_python_3.x_sentry.txt |
Q:
How to take out every fourth character in a string and print it out?
How can I make a function that takes in a string, and returns every fourth character in that string? So if the string was, "I Was Told There'd Be cake," the return would be: "Islh'ek". Here you can see the "I" is the first letter, then at the fou... | How to take out every fourth character in a string and print it out? | How can I make a function that takes in a string, and returns every fourth character in that string? So if the string was, "I Was Told There'd Be cake," the return would be: "Islh'ek". Here you can see the "I" is the first letter, then at the fourth index it is "s". I am not able to make the code for this.
This is how ... | [
"Try:\ns = \"I Was Told There'd Be cake\"\n\nprint(\"\".join(s[::4]))\n\nPrints:\nIslh'ek\n\n",
"my_string = \"I Was Told There'd Be Cake\"\n\ndef my_function(string):\n result_string = \"\"\n i = 0\n while i <= len(string) - 1:\n if string[i] != \"\":\n result_string += string[i]\n ... | [
1,
0,
0,
0,
0
] | [] | [] | [
"function",
"python",
"string"
] | stackoverflow_0074127509_function_python_string.txt |
Q:
No module named mysql even thought the code was wroking earlier
Screenshot of the error
import mysql.connector as sqlcon
con1=sqlcon.connect(host="localhost",user='root',passwd='ishaan094',database='db1')
if con1.is_connected():
print('Connection established.')
else:
print('COnnection not established.')
cu... | No module named mysql even thought the code was wroking earlier | Screenshot of the error
import mysql.connector as sqlcon
con1=sqlcon.connect(host="localhost",user='root',passwd='ishaan094',database='db1')
if con1.is_connected():
print('Connection established.')
else:
print('COnnection not established.')
cur1=con1.cursor()
cur1.execute('select * from empl')
data=cur1.fetchal... | [
"There may be multiple python environments on your machine.\nCheck that the interpreter environment you are currently using is the one with the pymsql package installed.\nUse the Ctrl+Shift+P --> Python:Select Interpreter switch to use the correct interpreter.\n\nThe best way is to use a virtual environment to mana... | [
0
] | [] | [] | [
"mysql",
"mysql_connector_python",
"mysql_python",
"python",
"visual_studio_code"
] | stackoverflow_0074136462_mysql_mysql_connector_python_mysql_python_python_visual_studio_code.txt |
Q:
FastAPI does not replace "+" plus symbol in GET request
I understand this is not a FastAPI issue, but how to avoid this using FastAPI?
For example:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
async def root(q: str):
return {"message": f"{q}"}
Issuing the following request:
http://127.0.0.1:800... | FastAPI does not replace "+" plus symbol in GET request | I understand this is not a FastAPI issue, but how to avoid this using FastAPI?
For example:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
async def root(q: str):
return {"message": f"{q}"}
Issuing the following request:
http://127.0.0.1:8000/?q=1+1
returns:
{"message":"1 1"}
| [
"+ is a reserved character in URLs which is used to denotate whitespace (as your result indicates). URL-encode your values to avoid this:\nhttp://127.0.0.1:8000/?q=1%2b1\n\n",
"The plus sign (+) has a semantic meaning in the query string, i.e., representing the space character. Similarly, the ampersand sign (&), ... | [
5,
1
] | [] | [] | [
"fastapi",
"http",
"python",
"starlette",
"urlencode"
] | stackoverflow_0074126062_fastapi_http_python_starlette_urlencode.txt |
Q:
Error while loading texture atlas in my kivy application
I am unable to open up a individual sprite within my atlas that I have compiled using kivy pillow. I keep getting 'Error loading texture' within the python interpreter. I am new to kivy so my biggest inclination to what is wrong is my file structure or how i... | Error while loading texture atlas in my kivy application | I am unable to open up a individual sprite within my atlas that I have compiled using kivy pillow. I keep getting 'Error loading texture' within the python interpreter. I am new to kivy so my biggest inclination to what is wrong is my file structure or how im referencing via string. There is very little documentation o... | [
"So I thought that you had to include the atlas with the page number and also specify the atlas name again before the referenced sprite. So this was a easy fix that I feel dumb about. But here is the correct source string for anyone with a little difficulty understanding the format. \nGridLayout:\n cols:1\n r... | [
1,
0
] | [] | [] | [
"file_structure",
"kivy",
"python",
"texture_atlas"
] | stackoverflow_0054365454_file_structure_kivy_python_texture_atlas.txt |
Q:
Django: ImportError: cannot import name 'Celery' from 'celery'
So I've installed celery and got the file celery_tasks_settings.py in my project directory next to settings.py. This I got was a way to avoid conflicts with the package itself.
I also did
find -name '*celery*.pyc'
as a way to find any celery.pyc files... | Django: ImportError: cannot import name 'Celery' from 'celery' | So I've installed celery and got the file celery_tasks_settings.py in my project directory next to settings.py. This I got was a way to avoid conflicts with the package itself.
I also did
find -name '*celery*.pyc'
as a way to find any celery.pyc files that may have been generated before.The result:
/__pycache__/celery... | [
"I upgraded importlib-metadata from verion 0.19 to version 1.5.0 and it totally resolved this issue for me. \nFor reference, I had an almost identical full traceback:\nTraceback (most recent call last):\n File \"manage.py\", line 21, in <module>\n main()\n File \"manage.py\", line 17, in main\n execute_from... | [
4,
1,
0
] | [] | [] | [
"celery",
"django",
"python"
] | stackoverflow_0059514262_celery_django_python.txt |
Q:
missing month count from the datetime column in pandas dataframe
Existing Dataframe :
Id Date_of_activity
A 2020-09-17 12:36:00
A 2020-11-02 00:00:00
A 2020-12-02 00:00:00
A 2021-01-02 00:00:00
A 2021-02... | missing month count from the datetime column in pandas dataframe | Existing Dataframe :
Id Date_of_activity
A 2020-09-17 12:36:00
A 2020-11-02 00:00:00
A 2020-12-02 00:00:00
A 2021-01-02 00:00:00
A 2021-02-02 00:00:00
A 2021-03-03 12:12:00
A ... | [
"You can use:\n# convert to Monthly period\ns = pd.to_datetime(df['Date_of_activity']).dt.to_period('M')\n\n# compute the difference per group\n# if != 1, then there is a missing month\nout = (s.sort_values()\n .groupby(df['Id'], sort=False)\n .apply(lambda g: g.drop_duplicates().diff().ne('M').sum()-... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074136592_pandas_python.txt |
Q:
How to set a common dynamic value for all Django models in Django admin page?
I have an application, where i have created a next button to redirect to the next model. What i want is that, when i am in the first admin page, eg. Master is the model, and it is connected with other models based foreign key relationshi... | How to set a common dynamic value for all Django models in Django admin page? | I have an application, where i have created a next button to redirect to the next model. What i want is that, when i am in the first admin page, eg. Master is the model, and it is connected with other models based foreign key relationship. I want this Master ID, to get automatically populate when the next button is cli... | [
"hello maybe what you need here is to take a look at paginator and you can decide to view one element peer page so your next button can show you the next object and so one no need of cookie for that.\n"
] | [
1
] | [] | [] | [
"cookies",
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0074135000_cookies_django_django_admin_django_forms_python.txt |
Q:
saving appended list/dictionary to pandas dataframe
I am working on a code like below, which slices the address column. For this I have created a dictionary and created an empty list final to append all the pre processing.see code
import pandas as pd
data = {'id': ['001', '002', '003'],
'address': ["Will... | saving appended list/dictionary to pandas dataframe | I am working on a code like below, which slices the address column. For this I have created a dictionary and created an empty list final to append all the pre processing.see code
import pandas as pd
data = {'id': ['001', '002', '003'],
'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA",
... | [
"What about this?\ndata = {'id': ['001', '002', '003'],\n 'address': [\"William J. Clare\\\\n290 Valley Dr.\\\\nCasper, WY 82604\\\\nUSA\",\n \"1180 Shelard Tower\\\\nMinneapolis, MN 55426\\\\nUSA\",\n \"William N. Barnard\\\\n145 S. Durbin\\\\nCasper, WY 82601\\\\nUSA\... | [
0,
0
] | [] | [] | [
"arrays",
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074136446_arrays_dataframe_list_pandas_python.txt |
Q:
How to restrict users to only type English in Django forms?
i have a model form with field (forms.textinput) and i want users just can type english in this field and if they want type with another language get a error
thank you
A:
So first of all, if you would want to restrict the character set used just check i... | How to restrict users to only type English in Django forms? | i have a model form with field (forms.textinput) and i want users just can type english in this field and if they want type with another language get a error
thank you
| [
"So first of all, if you would want to restrict the character set used just check if every char is element of strings.ascii_letters, maybe even add punctuation.\nSemantically there is no trivial way known to me by default, also the idea may be oversimplified by you.\n"
] | [
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0074136699_django_django_forms_python.txt |
Q:
Update operation in a model removes all the users stored in a many to many field in that model - Django
In my app a student can send a teacher a follow request that gets accepted by the teacher and the student gets added to the teacher's follower list. The way I am storing the students as a follower for the teache... | Update operation in a model removes all the users stored in a many to many field in that model - Django | In my app a student can send a teacher a follow request that gets accepted by the teacher and the student gets added to the teacher's follower list. The way I am storing the students as a follower for the teacher is by a many to many relationship model. Below is the code:
home_tuition_students = models.ManyToManyField(... | [
"Okay, I was just playing with the code to figure out what was going wrong and found out that the problem was cause be the serializer that was being used. The serializer that was being used was serializing all the fields including the many to many field. I figured out that the serializer should only contain the fie... | [
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"python"
] | stackoverflow_0074136378_django_django_models_django_rest_framework_python.txt |
Q:
Python | Jenkins API | Unable to get build data or build response
Python Version - 3.10.4 and
Jenkins Version - 2.321
Am trying to fetch the build information using python script and Jenkins API.
from jenkinsapi.jenkins import Jenkins
def get_server_instance():
jenkins_url = 'My build URL/api/json?pretty=true... | Python | Jenkins API | Unable to get build data or build response | Python Version - 3.10.4 and
Jenkins Version - 2.321
Am trying to fetch the build information using python script and Jenkins API.
from jenkinsapi.jenkins import Jenkins
def get_server_instance():
jenkins_url = 'My build URL/api/json?pretty=true'
server = Jenkins(jenkins_url, username = 'my user id', password =... | [
"You are not calling get_job_details in main.\n"
] | [
1
] | [] | [] | [
"automation",
"jenkins",
"jenkins_api",
"jenkins_pipeline",
"python"
] | stackoverflow_0072394063_automation_jenkins_jenkins_api_jenkins_pipeline_python.txt |
Q:
Is there a better way to create a randomizer web domain name generator?
i want to ask whether there is a better solution to get a much more randomize output. this is my code.
Combined = open("dictionaries/Combined.txt", 'r', encoding="utf-8")
Example = open("dictionaries/examples.txt", 'w', encoding="utf-8")
I fi... | Is there a better way to create a randomizer web domain name generator? | i want to ask whether there is a better solution to get a much more randomize output. this is my code.
Combined = open("dictionaries/Combined.txt", 'r', encoding="utf-8")
Example = open("dictionaries/examples.txt", 'w', encoding="utf-8")
I first opened the dictionary and then the output is going to be written on a .tx... | [
"you need the random.choice statement to select a random value from a list.\nIn my example you can also set the amount of results and subdomains.\nBTW: You might reconsider using http and https as part of subdomains. That might be very confusing\nmy_list = ['access',\n 'account',\n 'admin',\n ... | [
1
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0074136519_jupyter_notebook_python.txt |
Q:
Replace value in DataFrame when value not empty
I want to replace the values from a DataFrame column with values from a List.
How do I replace them only when the value in the list is not an empty string ?
Both are ordered the same way :
Dataframe List
ID Date UpdatedDate
... | Replace value in DataFrame when value not empty | I want to replace the values from a DataFrame column with values from a List.
How do I replace them only when the value in the list is not an empty string ?
Both are ordered the same way :
Dataframe List
ID Date UpdatedDate
1 19/04/2022 20/10/2022
2 12/07/... | [
"Assuming you list is a list that looks like this:\nlst = ['20/10/2022', '', '03/10/2022', '14/10/2022', '', '19/10/2022']\nYou can add that to your df as a new column like this:\ndf['lst'] = lst\n\n Date lst\n0 19/04/2022 20/10/2022\n1 12/07/2022 \n2 27/09/2022 03/10/2022\n3 11/05/... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074136704_dataframe_pandas_python.txt |
Q:
plt.show() does nothing when used for the second time
I am just starting to learn data science using python on Data Camp and I noticed something while using the functions in matplotlib.pyplot
import matplotlib.pyplot as plt
year = [1500, 1600, 1700, 1800, 1900, 2000]
pop = [458, 580, 682, 1000, 1650, 6,127]
plt.... | plt.show() does nothing when used for the second time | I am just starting to learn data science using python on Data Camp and I noticed something while using the functions in matplotlib.pyplot
import matplotlib.pyplot as plt
year = [1500, 1600, 1700, 1800, 1900, 2000]
pop = [458, 580, 682, 1000, 1650, 6,127]
plt.plot(year, pop)
plt.show() # Here a window opens up and sh... | [
"Answer\nYes, this is normal expected behavior for matplotlib figures.\n\nExplanation\nWhen you run plt.plot(...) you create on the one hand the lines instance of the actual plot:\n>>> print( plt.plot(year, pop) )\n[<matplotlib.lines.Line2D object at 0x000000000D8FDB00>]\n\n...and on the other hand a Figure instanc... | [
35,
0,
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0050452455_matplotlib_python.txt |
Q:
How to create multiple images in tkinter that can scale
I am creating a 3D rendering system in Tkinter and adding in textured walls. However, when I want to create another image the original disappears, and It will only render 1 wall and it appears that there can only be one wall.
Code:
import getkey
import thread... | How to create multiple images in tkinter that can scale | I am creating a 3D rendering system in Tkinter and adding in textured walls. However, when I want to create another image the original disappears, and It will only render 1 wall and it appears that there can only be one wall.
Code:
import getkey
import threading
import PIL
from PIL import Image, ImageTk
from tkinter im... | [
"I have experienced a similar situation when I was doing my project. You are rewriting the realImg every single time it loops. It is a problem because as soon as you create a new image in that SAME variable then the old one is gone. So you have to make sure it's still present like a memory because ImageTk will not ... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074136048_python_tkinter.txt |
Q:
In Python, Is there a C++ equivalent to declaring a function and defining it after it's used?
I'm sorry if this has already been answered. I didn't really know how to search for this particular question.
In C++ you can define a variable at the top to later define. For example:
int printOne();
int main()
{
co... | In Python, Is there a C++ equivalent to declaring a function and defining it after it's used? | I'm sorry if this has already been answered. I didn't really know how to search for this particular question.
In C++ you can define a variable at the top to later define. For example:
int printOne();
int main()
{
cout << printOne() << endl;
return 0;
}
int printOne
{
return 1;
}
I'm pretty new to Pyth... | [
"you don't have to. Python evaluates everything at run-time:\ndef a():\n print(b())\n\ndef b():\n return 12\n\na()\n\nso when a is called b is already defined.\nnote: that doesn't work because when a() is called b isn't defined yet:\ndef a():\n print(b())\n\na()\n\ndef b():\n return 12\n\nTraceback (mos... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0042027376_python.txt |
Q:
How to cumulatively sum the first elements when using the .over() function for a specific column in Python Polars
I was wondering if someone could please enlighten me.
I am trying to cumulatively sum pty_nber over/groupby a specific column (Declaration).
My original idea was to use something along:
dataset.filter(... | How to cumulatively sum the first elements when using the .over() function for a specific column in Python Polars | I was wondering if someone could please enlighten me.
I am trying to cumulatively sum pty_nber over/groupby a specific column (Declaration).
My original idea was to use something along:
dataset.filter(pl.col("pty_nber").first().over("Declaration").cumsum() < 30 )
But unfortunately, it does not take into account the .o... | [
"So I am not sure if you want just to have the yellow marked entries or keep the whole dataframe and just remove the rows where CUMSUM is greater than 30. So I implemented in two ways:\nData\nI simplified a little bit your example data\nimport polars as pl\ndf = pl.DataFrame(\n {\n \"declaration\": [2, 2,... | [
0
] | [] | [] | [
"python",
"python_polars"
] | stackoverflow_0074125922_python_python_polars.txt |
Q:
How I can upgrade my Ubuntu python3.7 to python3.8 latest version?
I am tried by this command
sudo pip3 install --upgrade python
but still, it did not work.
A:
Try this:
sudo apt-get update
sudo apt-get install python3.8
And if you want to replace the 3.7 with 3.8 for the python3 on your computer use the fol... | How I can upgrade my Ubuntu python3.7 to python3.8 latest version? | I am tried by this command
sudo pip3 install --upgrade python
but still, it did not work.
| [
"Try this:\nsudo apt-get update\n\nsudo apt-get install python3.8\n\nAnd if you want to replace the 3.7 with 3.8 for the python3 on your computer use the following after running the above commands.\nsudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 1\n\nsudo update-alternatives --instal... | [
19,
18,
1
] | [] | [] | [
"python",
"python_3.x",
"ubuntu_19.04"
] | stackoverflow_0058591889_python_python_3.x_ubuntu_19.04.txt |
Q:
Divide 'count' and 'sum' inside agg function in pandas
Using groupby and agg, is it possible to, in the same expression, get the 'count' divided by 'sum' returned?
data=pd.DataFrame({'id':[1,1,1,2,2,3,3,3,3,4, 4],
'val':[10,11,10,13,12,15,12,9, 8, 14, 2]})
data.groupby(['id'])['val'].agg(['count','su... | Divide 'count' and 'sum' inside agg function in pandas | Using groupby and agg, is it possible to, in the same expression, get the 'count' divided by 'sum' returned?
data=pd.DataFrame({'id':[1,1,1,2,2,3,3,3,3,4, 4],
'val':[10,11,10,13,12,15,12,9, 8, 14, 2]})
data.groupby(['id'])['val'].agg(['count','sum'])
| [
"Use lambda function:\ns = data.groupby(['id'])['val'].agg(lambda g: g.count()/g.sum())\nprint (s)\nid\n1 0.096774\n2 0.080000\n3 0.090909\n4 0.125000\nName: val, dtype: float64\n\nOr use DataFrame.eval, with rename count and sum columns to a, b:\ns = data.groupby(['id'])['val'].agg([('a','count'),('b',... | [
2,
1
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074136930_group_by_pandas_python.txt |
Q:
Bold font weight for LaTeX axes label in matplotlib
In matplotlib you can make the text of an axis label bold by
plt.xlabel('foo',fontweight='bold')
You can also use LaTeX with the right backend
plt.xlabel(r'$\phi$')
When you combine them however, the math text is not bold anymore
plt.xlabel(r'$\phi$',fontweight... | Bold font weight for LaTeX axes label in matplotlib | In matplotlib you can make the text of an axis label bold by
plt.xlabel('foo',fontweight='bold')
You can also use LaTeX with the right backend
plt.xlabel(r'$\phi$')
When you combine them however, the math text is not bold anymore
plt.xlabel(r'$\phi$',fontweight='bold')
Nor do the following LaTeX commands seem to hav... | [
"Unfortunately you can't bold symbols using the bold font, see this question on tex.stackexchange. \nAs the answer suggests, you could use \\boldsymbol to bold phi:\nr'$\\boldsymbol{\\phi}$'\n\nYou'll need to load amsmath into the TeX preamble:\nmatplotlib.rc('text', usetex=True)\nmatplotlib.rcParams['text.latex.pr... | [
39,
19,
16,
1,
1,
0,
0
] | [
"Update for recent Matplotlib versions\nIn more recent versions of Matplotlib, the preamble must be specified as a string.\nimport matplotlib.pyplot as plt\n\nplt.rcParams.update(\n {\n \"text.usetex\": True,\n \"text.latex.preamble\": r\"\\usepackage{bm}\",\n\n # Enforce default LaTeX font.... | [
-1
] | [
"latex",
"matplotlib",
"python"
] | stackoverflow_0014324477_latex_matplotlib_python.txt |
Q:
Unit Testing Functions without Return Value in Python
My final project in CS50 is a salary slip generator in pdf format. I got these functions with me but I don't know to test them.
create_pdf() - function that opens my data file (.xlsx), iterates over its data, puts them into variables which will then be called ... | Unit Testing Functions without Return Value in Python | My final project in CS50 is a salary slip generator in pdf format. I got these functions with me but I don't know to test them.
create_pdf() - function that opens my data file (.xlsx), iterates over its data, puts them into variables which will then be called by fpdf to put them into the pdf file. This function will g... | [
"Mine is a generic answer regardless of the language used.\nGenerally, when I have to test some method or function that has side effects or does not return any data, I check for some basic functions called within this function, and I mock them.\nThese core features are features that I assume are working and do not ... | [
2
] | [] | [] | [
"pyfpdf",
"python",
"unit_testing"
] | stackoverflow_0074136789_pyfpdf_python_unit_testing.txt |
Q:
how to extract a number followed by a specific word using RegEX python
I have a dataframe of string texts example:
descripton
..32 cars are coming full of attendees..
..64 attendees..
..8 participants are allowed..
I want to extract using regex the number plus a specific word "participant or participants, attenda... | how to extract a number followed by a specific word using RegEX python | I have a dataframe of string texts example:
descripton
..32 cars are coming full of attendees..
..64 attendees..
..8 participants are allowed..
I want to extract using regex the number plus a specific word "participant or participants, attendant or attendees" after it immediately, so the output from this column should... | [
"Try:\ndf[\"new column\"] = df[\"description\"].str.extract(\n r\"(\\d+\\s+(?:participants?|attendant|attendees))\"\n)\n\nprint(df)\n\nPrints:\n description new column\n0 ..32 cars are coming full of attendees.. NaN\n1 ..64 attendees.. ... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"regex"
] | stackoverflow_0074136950_dataframe_pandas_python_regex.txt |
Q:
Pandas indexing by integer
Coming from Excel background, I find indexes so confusing in code.
Typically I'll make something an index that I feel should be one, then lose the functionality I would have had when it was a column.
I've a df with 4 digit years from 2015 to 2113 as the index. If i call a for loop on the... | Pandas indexing by integer | Coming from Excel background, I find indexes so confusing in code.
Typically I'll make something an index that I feel should be one, then lose the functionality I would have had when it was a column.
I've a df with 4 digit years from 2015 to 2113 as the index. If i call a for loop on the index they are class type int (... | [
"On the problem df, indeed the index's data type is string.\nIndex(['2019','2020','2021'],dtype='object')\n\nWhen you write\ndf[df.index==2020]\n\nA blank result is expected because you search for int 2020 not string '2020'.\nThen, in code\ndf.loc[2020]\n\nIs a wrong code for searching some data with some condition... | [
0
] | [] | [] | [
"dataframe",
"indexing",
"pandas",
"python"
] | stackoverflow_0074136828_dataframe_indexing_pandas_python.txt |
Q:
pandas combining 2 dataframe and filling all rows
i have 2 dataframe
df1: df2:
A B C D X Y Z
1 2 3 4 p2 p3 p4
5 6 7 8
9 10 11 12
How can i concat the 2 dataframe such that the output is
A B C D X Y Z
1 2 3 4 p2... | pandas combining 2 dataframe and filling all rows | i have 2 dataframe
df1: df2:
A B C D X Y Z
1 2 3 4 p2 p3 p4
5 6 7 8
9 10 11 12
How can i concat the 2 dataframe such that the output is
A B C D X Y Z
1 2 3 4 p2 p3 p4
5 6 7 8 p2 p3 p4
9 10 11 12 p2 ... | [
"Use a cross merge:\nout = df1.merge(df2, how='cross')\n\noutput:\n A B C D X Y Z\n0 1 2 3 4 p2 p3 p4\n1 5 6 7 8 p2 p3 p4\n2 9 10 11 12 p2 p3 p4\n\nYou will however lose the original index of df1. If it is important to keep use:\nout = df1.merge(df2, how='cross').set_axis(df... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074137053_dataframe_pandas_python.txt |
Q:
Return decimal fields from list
I have a generator which yields to datatype on is decimal and other is string i need the method to just return the decimal
def my_generator():
yield amount, name
def get_amount(obj):
p = list()
gen = obj.my_generator()
for i in gen:
p.append(i)
return p... | Return decimal fields from list | I have a generator which yields to datatype on is decimal and other is string i need the method to just return the decimal
def my_generator():
yield amount, name
def get_amount(obj):
p = list()
gen = obj.my_generator()
for i in gen:
p.append(i)
return p
get_amount()
now it is returning [... | [
"Simply get only the first value from your tuple with i[0].\nExample:\nfrom decimal import Decimal\nfrom random import randint\n\ndef my_generator(count):\n for _ in range(count):\n yield Decimal(randint(1000, 2000)), \"some str\"\n\ndef get_amount(count):\n p = []\n for i in my_generator(count):\n ... | [
1
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074136956_list_python_python_3.x.txt |
Q:
Alternate daily between 'True' or 'False' idemptotently
I'd like to write a function that will idempotently output either True or False on alternate datetime days, starting from a non-specific date and going on indefinitely.
For example, passing a datetime representing October 1st might output True, then October 2... | Alternate daily between 'True' or 'False' idemptotently | I'd like to write a function that will idempotently output either True or False on alternate datetime days, starting from a non-specific date and going on indefinitely.
For example, passing a datetime representing October 1st might output True, then October 2nd will output False, then October 3rd True, and so on... It ... | [
"To do this, we need a calendar representation that just counts days without regard to anything else — no weeks or months or years. Skimming the datetime module docs, one possibility would appear to be the date.toordinal() method. Then we check whether that number is odd or even in the usual way.\ndef date_check(da... | [
3,
2
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0074136968_datetime_python.txt |
Q:
ModuleNotFoundError: No module named 'visdom' when importing visdom
When i'm trying to run the following from python console (pycharm)
import visdom
When I try to run:
module = self._system_import(name, *args, **kwargs)
I get the following error:
ModuleNotFoundError: No module named 'visdom'
I've tried to inst... | ModuleNotFoundError: No module named 'visdom' when importing visdom | When i'm trying to run the following from python console (pycharm)
import visdom
When I try to run:
module = self._system_import(name, *args, **kwargs)
I get the following error:
ModuleNotFoundError: No module named 'visdom'
I've tried to install it through pip (pip install visdom), pip3 (pip3 install visdom) and c... | [
"Always include full traceback firstly in your question. With what i have encountered before, try the following\nUpgrade pip,\npython -m pip install --upgrade pip\n\nThey try,\npython -m pip install visdom\n\n",
"I’ve encountered the same issue. I made it by installing visdom0.2.1 while the default version is 0.2... | [
5,
0
] | [
"Try to install with pip:\nInstall Python server and client from pip\nRequires Python 3\n"
] | [
-1
] | [
"conda",
"pip",
"python",
"visdom"
] | stackoverflow_0060623224_conda_pip_python_visdom.txt |
Q:
setuptools: package data folder location
I use setuptools to distribute my python package. Now I need to distribute additional datafiles.
From what I've gathered fromt the setuptools documentation, I need to have my data files inside the package directory. However, I would rather have my datafiles inside a subdire... | setuptools: package data folder location | I use setuptools to distribute my python package. Now I need to distribute additional datafiles.
From what I've gathered fromt the setuptools documentation, I need to have my data files inside the package directory. However, I would rather have my datafiles inside a subdirectory in the root directory.
What I would like... | [
"Option 1: Install as package data\nThe main advantage of placing data files inside the root of your Python package\nis that it lets you avoid worrying about where the files will live on a user's\nsystem, which may be Windows, Mac, Linux, some mobile platform, or inside an Egg. You can\nalways find the directory da... | [
121,
21,
0
] | [
"I think that you can basically give anything as an argument *data_files* to setup().\n"
] | [
-4
] | [
"python",
"setuptools"
] | stackoverflow_0004519127_python_setuptools.txt |
Q:
Disable console messages in Flask server
I have a Flask server running in standalone mode (using app.run()). But, I don't want any messages in the console, like
127.0.0.1 - - [15/Feb/2013 10:52:22] "GET /index.html HTTP/1.1" 200 -
...
How do I disable verbose mode?
A:
You can set level of the Werkzeug logger to... | Disable console messages in Flask server | I have a Flask server running in standalone mode (using app.run()). But, I don't want any messages in the console, like
127.0.0.1 - - [15/Feb/2013 10:52:22] "GET /index.html HTTP/1.1" 200 -
...
How do I disable verbose mode?
| [
"You can set level of the Werkzeug logger to ERROR, in that case only errors are logged:\nimport logging\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\n\nHere is a fully working example tested on OSX, Python 2.7.5, Flask 0.10.0:\nfrom flask import Flask\napp = Flask(__name__)\n\nimport logging\n... | [
179,
18,
18,
15,
12,
11,
10,
7,
4,
3,
0,
0
] | [
"A brute force way to do it if you really don't want anything to log into the console beside print() statements is to logging.basicConfig(level=logging.FATAL). This would disable all logs that are of status under fatal. It would not disable printing but yeah, just a thought :/\nEDIT:\nI realized it would be selfish... | [
-1,
-3
] | [
"flask",
"python"
] | stackoverflow_0014888799_flask_python.txt |
Q:
Problems on post method with form and tuple data
I'm trying to make a post request to this url:
url
I'm trying this code to get this request:
from requests import get, post
data = {
'entrada': {
'site': 'site',
'origen': 'origen',
'tipo': 'turismo',
'fecha': 2022,
'marc... | Problems on post method with form and tuple data | I'm trying to make a post request to this url:
url
I'm trying this code to get this request:
from requests import get, post
data = {
'entrada': {
'site': 'site',
'origen': 'origen',
'tipo': 'turismo',
'fecha': 2022,
'marca': -1,
'marcanombre': '',
'modelo': -... | [
"Try:\nimport requests\n\napi_url = \"https://configurador.motorflash.com/tm_servicios.php?servicio=getBuscador&canal=jato\"\n\npayload = {\n \"entrada[site]\": \"motorflashback\",\n \"entrada[origen]\": \"jato\",\n \"entrada[tipo]\": \"turismo\",\n \"entrada[fecha]\": \"2020\",\n \"entrada[marca]\":... | [
1
] | [] | [] | [
"forms",
"post",
"python",
"request",
"tuples"
] | stackoverflow_0074136489_forms_post_python_request_tuples.txt |
Q:
Find the longest common substring from two sentences
My question is how to find the longest common substring from two sentences.
For example:
sequence 1 = "there were a dozen eggs in the basket"
sentence 2 = "mike ate a dozen eggs for breakfast"
The longest common substring from sentence 1 and sentence 2 would be ... | Find the longest common substring from two sentences | My question is how to find the longest common substring from two sentences.
For example:
sequence 1 = "there were a dozen eggs in the basket"
sentence 2 = "mike ate a dozen eggs for breakfast"
The longest common substring from sentence 1 and sentence 2 would be "e a dozen eggs ", including the spaces.
My general idea i... | [
"The longest common substring from two sentences\nUsing two loops and list comprehension.\ns1 = \"there were a dozen eggs in the basket\"\ns2 = \"mike ate a dozen eggs for breakfast\"\n\nlst=[s1[i:j] for i in range(len(s1)) for j in range(len(s1)) if s1[i:j] in s2]\n\nresult = max(lst, key = len)\n\nprint(result)\n... | [
0
] | [] | [] | [
"longest_substring",
"python",
"suffix",
"suffix_tree"
] | stackoverflow_0074136485_longest_substring_python_suffix_suffix_tree.txt |
Q:
how can I add index as key value in a list of dict in python?
I have a list like below -
[{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'}, {'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'},
{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'}]
Ne... | how can I add index as key value in a list of dict in python? | I have a list like below -
[{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'}, {'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'},
{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'}]
Need to add index key and its value in these three records.
Expected ... | [
"Try:\nlst = [\n {\"amount\": 1100000, \"target\": 120000, \"time\": \"2022-09-30T00:00:00.000Z\"},\n {\"amount\": 1100000, \"target\": 120000, \"time\": \"2022-09-30T00:00:00.000Z\"},\n {\"amount\": 1100000, \"target\": 120000, \"time\": \"2022-09-30T00:00:00.000Z\"},\n]\n\nfor idx, d in enumerate(lst):\n... | [
1,
1
] | [] | [] | [
"dictionary",
"indexing",
"list",
"python"
] | stackoverflow_0074136936_dictionary_indexing_list_python.txt |
Q:
ModuleNotFoundError in unittest when mocking class method
I want to test a method of a class. There I want to mock a method that is in another class. But I always get the error below.
Error
Ran 1 test in 0.005s
FAILED (errors=1)
Error
Traceback (most recent call last):
File "D:\dev\test_unittest\lib\site-packa... | ModuleNotFoundError in unittest when mocking class method | I want to test a method of a class. There I want to mock a method that is in another class. But I always get the error below.
Error
Ran 1 test in 0.005s
FAILED (errors=1)
Error
Traceback (most recent call last):
File "D:\dev\test_unittest\lib\site-packages\mock\mock.py", line 1343, in patched
with self.decorati... | [
"There are a number of problems with your unit test code.\nInvalid import path\nThis is what is causing the error you are seeing. If you look at the documentation of unittest.mock.patch, you'll see that the target string must be in a form that is importable from the environment you are calling patch from, i.e. the ... | [
1
] | [] | [] | [
"mocking",
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0074102503_mocking_python_python_unittest_unit_testing.txt |
Q:
How does asyncio actually work?
This question is motivated by my another question: How to await in cdef?
There are tons of articles and blog posts on the web about asyncio, but they are all very superficial. I couldn't find any information about how asyncio is actually implemented, and what makes I/O asynchronous... | How does asyncio actually work? | This question is motivated by my another question: How to await in cdef?
There are tons of articles and blog posts on the web about asyncio, but they are all very superficial. I couldn't find any information about how asyncio is actually implemented, and what makes I/O asynchronous. I was trying to read the source co... | [
"How does asyncio work?\nBefore answering this question we need to understand a few base terms, skip these if you already know any of them.\nGenerators\nGenerators are objects that allow us to suspend the execution of a python function. User curated generators are implemented using the keyword yield. By creating a ... | [
503,
189,
28,
18,
6,
0
] | [
"If you picture an airport control tower, with many planes waiting to land on the same runway. The control tower can be seen as the event loop and runway as the thread. Each plane is a separate function waiting to execute. In reality only one plane can land on the runway at a time. What asyncio basically does it al... | [
-1
] | [
"python",
"python_3.x",
"python_asyncio",
"python_internals"
] | stackoverflow_0049005651_python_python_3.x_python_asyncio_python_internals.txt |
Q:
Can load image, but when I load it again within the second round of a loop it crashes
Title, it returns the error "_tkinter.TclError: image "pyimage3" doesn't exist" I have tried changing the root = tk.Tk
() to root = tk.TopLevel() as suggested by previous users who received the same error.
The script goes through... | Can load image, but when I load it again within the second round of a loop it crashes | Title, it returns the error "_tkinter.TclError: image "pyimage3" doesn't exist" I have tried changing the root = tk.Tk
() to root = tk.TopLevel() as suggested by previous users who received the same error.
The script goes through a list of image files on a CSV file, the idea is to create a slideshow and the CSV file sa... | [
"Whenever you create a new image using ImageTk.PhotoImage() you have to make sure that image variable stays during the entire time your code runs. This means for example if you create the first image in a variable img then you must not use the SAME variable for a new image because once the old image is rewritten i... | [
0
] | [] | [] | [
"image",
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0074133450_image_python_python_imaging_library_tkinter.txt |
Q:
Looking for a way to delete specific lines whot don't contain list of numbers [python] [pandas]
I'm looking for a way to delete specific lines (on a excel sheet) who dont contain list of numbers.
I know the further exemple is not working, it's just to explain propely what i want to do
import pandas as pd
# Read E... | Looking for a way to delete specific lines whot don't contain list of numbers [python] [pandas] | I'm looking for a way to delete specific lines (on a excel sheet) who dont contain list of numbers.
I know the further exemple is not working, it's just to explain propely what i want to do
import pandas as pd
# Read Excel sheet
excel_sheet = pd.read_excel('sheet.xlsx', index_col=0)
# List of int that appears in a se... | [
"Here is a reproducible example of a solution:\nimport pandas as pd\ndf = pd.read_csv(\"https://raw.githubusercontent.com/practiceprobs/datasets/main/iris/iris.csv\")\n\nmy_list = [5.1,4.9,4.7]\n\ndf[df['sepal_length'].isin(my_list) == False]\n\n"
] | [
0
] | [] | [] | [
"drop",
"excel",
"pandas",
"python"
] | stackoverflow_0074137194_drop_excel_pandas_python.txt |
Q:
Can Enterprise Architect Python API be used to connect to running instances of EA
I currently use the following code to open a new instance and then query it,
eaRep = win32com.client.Dispatch('EA.Repository')
eaRep.OpenFile("Model.eapx")
However, I now require to access the EA file that has already been opened. I... | Can Enterprise Architect Python API be used to connect to running instances of EA | I currently use the following code to open a new instance and then query it,
eaRep = win32com.client.Dispatch('EA.Repository')
eaRep.OpenFile("Model.eapx")
However, I now require to access the EA file that has already been opened. Is there a way to do it with Python API for Enterprise Architect?
| [
"You can connect to the running instance like this:\napp = win32com.client.GetActiveObject(\"EA.App\")\n\n"
] | [
0
] | [] | [] | [
"enterprise_architect",
"python"
] | stackoverflow_0074136544_enterprise_architect_python.txt |
Q:
Python Selenium - element is not attached to the page document - once button is clicked
When I click on an item inside a dropdown list, the item is correctly clicked but the error: "stale element is not attached to the page document" is raised.
I guess this error is raised because of an element I use as changed in... | Python Selenium - element is not attached to the page document - once button is clicked | When I click on an item inside a dropdown list, the item is correctly clicked but the error: "stale element is not attached to the page document" is raised.
I guess this error is raised because of an element I use as changed inside the DOM or has been refreshed, but I didn't find any solutions for now. Here's my code:
... | [
"Since by clicking on elements inside the dropdown list the page is changing and elements are refreshed you have to grab select_question_type elements again after the refreshing. Something like this:\nexam_question_type = self.driver.find_element(By.XPATH, f\"//*[name()='svg'][@class='css-19bqh2r']\")\nexam_questio... | [
1
] | [] | [] | [
"for_loop",
"python",
"selenium",
"selenium_webdriver",
"staleelementreferenceexception"
] | stackoverflow_0074136578_for_loop_python_selenium_selenium_webdriver_staleelementreferenceexception.txt |
Q:
Keras .fit giving better performance than manual Tensorflow
I'm new to Tensorflow and Keras. To get started, I followed the https://www.tensorflow.org/tutorials/quickstart/advanced tutorial. I'm now adapting it to train on CIFAR10 instead of MNIST dataset. I recreated this model https://keras.io/examples/cifar10_c... | Keras .fit giving better performance than manual Tensorflow | I'm new to Tensorflow and Keras. To get started, I followed the https://www.tensorflow.org/tutorials/quickstart/advanced tutorial. I'm now adapting it to train on CIFAR10 instead of MNIST dataset. I recreated this model https://keras.io/examples/cifar10_cnn/ and I'm trying to run it in my own codebase.
Logically, if t... | [
"I know this question already has an answer, but I faced the same problem and the solution seemed to be something different, that's not specified in the documentation.\nI copy & paste here the answer (and the relative link) I found on GitHub, which solved the issue in my case:\n\nThe problem is caused by broadcasti... | [
1,
0
] | [] | [] | [
"deep_learning",
"keras",
"python",
"tensorflow"
] | stackoverflow_0062193877_deep_learning_keras_python_tensorflow.txt |
Q:
How can I handle overfitting of a model?
I'm using XGBoost model to predict attacks, But I get 100% accuracy, I tried Random Forest as well, and same, I get 100%. How can I handle this ovrefitting problem ?
The steps I followed are:
Data cleaning
Data splitting
Feature scaling
Feature selection
I even tried to cha... | How can I handle overfitting of a model? | I'm using XGBoost model to predict attacks, But I get 100% accuracy, I tried Random Forest as well, and same, I get 100%. How can I handle this ovrefitting problem ?
The steps I followed are:
Data cleaning
Data splitting
Feature scaling
Feature selection
I even tried to change this order, but still get the same thing.
... | [
"Overfitting occurs when your model becomes too complex for its task. Simply said instead of learning patterns in your data, the model will be able to learn every case it is presented in the training set by heart.\nTo avoid this, you will have to choose a model that is less complex, in your case reduce the depth of... | [
2,
1
] | [] | [] | [
"classification",
"python",
"random_forest",
"security",
"xgboost"
] | stackoverflow_0074131790_classification_python_random_forest_security_xgboost.txt |
Q:
How to read, modify and save an Excel file in Python?
I wonder how can I read an Excel file using Python (xlsx extension), then modify only rows 4,5,6,7,... and save modified values in such format with the same header (yellow rows, picture, name of the columns - Description, Part number,...) and fixed columns widt... | How to read, modify and save an Excel file in Python? | I wonder how can I read an Excel file using Python (xlsx extension), then modify only rows 4,5,6,7,... and save modified values in such format with the same header (yellow rows, picture, name of the columns - Description, Part number,...) and fixed columns width.
When modifying the rows 4,5,6,7... I must use data fram... | [
"You can use openpyxl to modify existing .xlsx files.\nYou can find a lot of information about this package online, and you can see an example here.\n"
] | [
2
] | [] | [] | [
"excel",
"pandas",
"python",
"xlsx",
"xml"
] | stackoverflow_0074136153_excel_pandas_python_xlsx_xml.txt |
Q:
Formatting when redirecting stderr and stdout to logger
In some cases I need to monkey-patch stderr and stdout to redirect them to logging. I'm using the solutions from How to redirect stdout and stderr to logger in Python. This code nearly works:
import logging, sys
logging.basicConfig(filename='test.log', forma... | Formatting when redirecting stderr and stdout to logger | In some cases I need to monkey-patch stderr and stdout to redirect them to logging. I'm using the solutions from How to redirect stdout and stderr to logger in Python. This code nearly works:
import logging, sys
logging.basicConfig(filename='test.log', format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S'... | [
"The problem is that in the process of outputting the exception traceback to stdout/stderr, the structure (the fact that it's an exception traceback) has been lost - it's just a set of random lines of text, as far as the logger is concerned.\nTo overcome this, you'd have to buffer the text in LoggerWriter and proce... | [
0
] | [] | [] | [
"logging",
"python",
"python_logging",
"stdout"
] | stackoverflow_0074134910_logging_python_python_logging_stdout.txt |
Q:
How do I sort an array into multiple arrays alphabetically
I'm trying to sort an array into multiple arrays by their starting letter
this is an example
list1 = ["apple", "banana", "carrot", "avocado"]
into this
a = ["apple", "avocado"]
b = ["banana"]
c = ["carrot"]
A:
Use itertools.groupby
from itertools import... | How do I sort an array into multiple arrays alphabetically | I'm trying to sort an array into multiple arrays by their starting letter
this is an example
list1 = ["apple", "banana", "carrot", "avocado"]
into this
a = ["apple", "avocado"]
b = ["banana"]
c = ["carrot"]
| [
"Use itertools.groupby\nfrom itertools import groupby\nlist1 = [\"apple\", \"banana\", \"carrot\", \"avocado\"]\nprint([list(val) for _, val in groupby(sorted(list1), key=lambda x: x[0])])\n# [['apple', 'avocado'], ['banana'], ['carrot']]\n# IF want dictionary \nprint({k : list(val) for k, val in groupby(sorted(lis... | [
3,
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0074137304_python.txt |
Q:
Pandas DataFrame stack multiple column values into single column without changing one of the columns
I'm trying to reshape a data frame in a certain way.
This is the data frame I have,
col_1
col_2
One
Roxanne
Two
Ghina
Roxanne
Leila
Ghina
George
Three
Rock
Four
Rock
I'd like to reshape the dataframe such t... | Pandas DataFrame stack multiple column values into single column without changing one of the columns | I'm trying to reshape a data frame in a certain way.
This is the data frame I have,
col_1
col_2
One
Roxanne
Two
Ghina
Roxanne
Leila
Ghina
George
Three
Rock
Four
Rock
I'd like to reshape the dataframe such that it looks like this:
col_3
Roxanne
Ghina
Leila
George
Rock
Rock
One
... | [
"You can use:\nout = (df[['col_2', 'col_1']].melt(value_name='col_3')[['col_3']]\n .drop_duplicates(ignore_index=True)\n )\n\nOr:\nout = (df.loc[:, ::-1].unstack().reset_index(drop=True).to_frame(name='col_3')\n .drop_duplicates(ignore_index=True)\n )\n\noutput:\n col_3\n0 Roxanne\n1 G... | [
0,
0
] | [] | [] | [
"dataframe",
"multiple_columns",
"pandas",
"python",
"stack"
] | stackoverflow_0074137405_dataframe_multiple_columns_pandas_python_stack.txt |
Q:
Moving in 2D coordinate plane, keeping track of position and distance from the origin
So i'm trying to make a code (mainly using class) that would allow me to make a robot move (imagine there's a coordinate plane) starting from the center (0,0) UP, DOWN, LEFT or RIGHT. We were task to have the program repeatedly... | Moving in 2D coordinate plane, keeping track of position and distance from the origin | So i'm trying to make a code (mainly using class) that would allow me to make a robot move (imagine there's a coordinate plane) starting from the center (0,0) UP, DOWN, LEFT or RIGHT. We were task to have the program repeatedly ask for a string input to identify the direction and distance movement, and then output th... | [
"First you need to make an object of the class Robot to be able to use its methods. This is called object oriented programming (OOP) I suggest read some of the basics of it. \nFor this specific problem you don't need an OOP solution. \nRemove the class definition and simply use the function itself :\n def movement(... | [
2
] | [
"You are going to design a program which allows a robot to move in a 2D coordinate system starting from the original point (0, 0). The robot can move to the next point (x, y) specified by the user. If the next point is (999, 999), the program ends and prints out the distance moved at each step.\n"
] | [
-1
] | [
"class",
"coordinates",
"position",
"python",
"python_3.x"
] | stackoverflow_0058413884_class_coordinates_position_python_python_3.x.txt |
Q:
Python comment inside a multi-line string
So let's say I have a string like so :
foo = '''
some
important
stuff
'''
Is it possible to comment something inside it ? for instance :
foo = '''
some
# important
stuff
'''
A:
It is impossible, because ''' is a multi-line string. Everything inside it is a string. If y... | Python comment inside a multi-line string | So let's say I have a string like so :
foo = '''
some
important
stuff
'''
Is it possible to comment something inside it ? for instance :
foo = '''
some
# important
stuff
'''
| [
"It is impossible, because ''' is a multi-line string. Everything inside it is a string. If you explain why you need it I can think of an other solution for your problem.\n",
"No. ''' is a multi-line string. Anything inside it is part of the string, even lines starting with #.\nIf you're in a situation where you ... | [
1,
1,
0
] | [
"Comments are often outdated as they are not maintained and overlooked by the IDE.\nHow about a function, you still can add your comment there but at least we have some code as a foundation\ndef define_an_important_string() -> str:\n \"\"\"\n some things here are important\n \n Returns: string with stuf... | [
-1
] | [
"comments",
"python"
] | stackoverflow_0074136594_comments_python.txt |
Q:
How to Store correlation matrix's values in dataframe
I have a df. I want to apply a correlation matrix between the columns and store the result values in another dataframe, however, I do not want to keep the upper part of the matrix, which is useless given that it's duplicate from the other part, I also don't wan... | How to Store correlation matrix's values in dataframe | I have a df. I want to apply a correlation matrix between the columns and store the result values in another dataframe, however, I do not want to keep the upper part of the matrix, which is useless given that it's duplicate from the other part, I also don't want the diagonal (1,1,1,1). So i applied a mask, and then app... | [
"Tuples in columns are problematic, here is solution for change tuple for scalar name:\ndft.columns = ['name' if x == ('name', 'name') else x for x in dft.columns]\n\ndf = dft.melt(id_vars='name', \n var_name=\"Var1_Var2\", \n value_name=\"Value\")\nprint (df)\n name Var1_Var2 Value\n0 test... | [
1
] | [] | [] | [
"correlation",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074137468_correlation_dataframe_pandas_python.txt |
Q:
Cascading logging in Python - Are there pitfalls i dont see?
I spent a lot of time in finding a setup for logging that works best for our projects. Our team is quite young and standards are establishing only now. We want to have well formatted logs that are taken care of in different handlers. That should be true ... | Cascading logging in Python - Are there pitfalls i dont see? | I spent a lot of time in finding a setup for logging that works best for our projects. Our team is quite young and standards are establishing only now. We want to have well formatted logs that are taken care of in different handlers. That should be true if the whole application is started from main as well as a sub-pac... | [
"\nAre there pitfalls i am overseeing or does a way exist that makes it easier maintainable when projects really go up in scale?\n\nYes, there are problems with this arrangement at any scale beyond \"ad-hoc one-off script that won't be used frequently or maintained/developed by multiple people\".\n\nYou do not defi... | [
2
] | [] | [] | [
"logging",
"production",
"python"
] | stackoverflow_0074137240_logging_production_python.txt |
Q:
exchangelib OAUTH authentication NonExistentMailbox error
I have a Python script that is reading Office 365 emails and downloading attachments.
I am using exchangelib and trying to switch from Basic Authentication to OAUTH2.
My old script was authenticating without any issues:
from exchangelib import Credentials, ... | exchangelib OAUTH authentication NonExistentMailbox error | I have a Python script that is reading Office 365 emails and downloading attachments.
I am using exchangelib and trying to switch from Basic Authentication to OAUTH2.
My old script was authenticating without any issues:
from exchangelib import Credentials, Account
username = 'xxx@yyy.com'
pwd = '123456'
credentials = ... | [
"I tried to reproduce the same in my environment and got the below results:\nI created one Azure AD application and added API permissions with admin consent as below:\n\nNow, I ran the same code as you and got the same error as below:\nfrom exchangelib import OAuth2Credentials\n\nusername = 'xxx@tenant.onmicrosoft.... | [
1
] | [] | [] | [
"azure",
"azure_active_directory",
"exchangelib",
"office365",
"python"
] | stackoverflow_0074127098_azure_azure_active_directory_exchangelib_office365_python.txt |
Q:
How can I save dataset to the correct HDF5 group?
I am running a script that iterates through a folder and creates a set of groups to replicate the directory in a HDF5 file. I am then going through the files and adding the data from the files to HDF5 datasets. However, I am looking to save the datasets into the co... | How can I save dataset to the correct HDF5 group? | I am running a script that iterates through a folder and creates a set of groups to replicate the directory in a HDF5 file. I am then going through the files and adding the data from the files to HDF5 datasets. However, I am looking to save the datasets into the correct groups but unsure how?
#Development Script Save f... | [
"/ only works to join pathlib.Path objects and you have strings.\nJust do\nf\"{grp_name}/{file}\"\n\nor\nposixpath.join(grp_name, file)\n\n(posixpath to ensure forward slashes no matter which platform you're on)\nYou will also naturally need to do the same grp_name determination in the second loop:\ngrp_name = path... | [
2
] | [] | [] | [
"h5py",
"hdf5",
"python"
] | stackoverflow_0074137390_h5py_hdf5_python.txt |
Q:
How to purge tasks in celery queues using Redis as the broker
Part1
I've read and tried various SO threads to purge the celery tasks using Redis, but none of them worked. Please let me know how to purge tasks in celery using Redis as the broker.
Part 2
Also, I've multiple queues. I can run it within the project di... | How to purge tasks in celery queues using Redis as the broker | Part1
I've read and tried various SO threads to purge the celery tasks using Redis, but none of them worked. Please let me know how to purge tasks in celery using Redis as the broker.
Part 2
Also, I've multiple queues. I can run it within the project directory, but when demonizing, the workers dont take task. I still n... | [
"celery purge should be enough to clean up the queue in redis. However, your worker will have its own reserved tasks and it will send them back to the queue when you stop the worker. So, first, stop all the workers. Then run celery purge.\n",
"If you have several queues, celery purge will purge the default one. Y... | [
13,
13,
2,
0,
0
] | [] | [] | [
"celery",
"python"
] | stackoverflow_0028561082_celery_python.txt |
Q:
How to calculate the Mean Median Mode and Range for datas from Input Python
I am trying to Calculate the mean, median, mode and range for sets of data in Python, and to Interpret these statistics in the context of data and how to describe and interpret data displays using median, mean and range.
My Code so far is... | How to calculate the Mean Median Mode and Range for datas from Input Python | I am trying to Calculate the mean, median, mode and range for sets of data in Python, and to Interpret these statistics in the context of data and how to describe and interpret data displays using median, mean and range.
My Code so far is:
from statistics import median
from statistics import mean
from statistics impor... | [
"The way you are defining 'data' is wrong. You can try the code below. I only change the 'data' variable.\nfrom statistics import median\nfrom statistics import mean\nfrom statistics import mode\nfrom math import isnan\nfrom itertools import filterfalse\ntitle = input('Definition of data set: ')\n# Input list of el... | [
0,
0
] | [] | [] | [
"mean",
"median",
"mode",
"python",
"range"
] | stackoverflow_0074137462_mean_median_mode_python_range.txt |
Q:
How to run simple Python project on Docker
I have a simple Python model with front-end and back-end.
The backend code only response the hello world message to frontend.
I want to run this project on docker, but I am not sure how to write Dockerfile and docker-compose.yml file.
A:
This question probably needs som... | How to run simple Python project on Docker | I have a simple Python model with front-end and back-end.
The backend code only response the hello world message to frontend.
I want to run this project on docker, but I am not sure how to write Dockerfile and docker-compose.yml file.
| [
"This question probably needs some work to clarify your use case, but I'll answer as best as I can.\nGenerally, containers orchestrated in compose are all hosted on the same network, by default host networking. So, all should need to do is have a Dockerfile for each of your python projects, expose a port, connect t... | [
1
] | [] | [] | [
"docker",
"python"
] | stackoverflow_0074137097_docker_python.txt |
Q:
How can I create a column from an element extracted from a column that is formed by a list of dictionaries?
How can I create a column in the dataset containing the text values from the hashtag column?
The code is as follows:
tw_data = pd.read_json('tw_hurricane_data.json',lines=True)
#creating an additional colu... | How can I create a column from an element extracted from a column that is formed by a list of dictionaries? | How can I create a column in the dataset containing the text values from the hashtag column?
The code is as follows:
tw_data = pd.read_json('tw_hurricane_data.json',lines=True)
#creating an additional column with hashtag information obtained from the entities column
tw_data['hashtags'] = tw_data['entities'].apply(lam... | [
"hastags is a collection. You have not mentioned how to process the collection of values, so assumed that you want all values:\ntw_data[['hashtags']].apply(lambda x: [e[\"text\"] for e in x[\"hastags\"]], axis=1)\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074136878_dataframe_pandas_python.txt |
Q:
Convert png/jpg to word file using python
I need to convert lots of jpg/png files to docx files & then to pdf. My sole concern is to write the data in an image to a pdf file & if I need to edit any text manually, I can do that in word & save it in the corresponding pdf file.
I've tried using API but failed as the ... | Convert png/jpg to word file using python | I need to convert lots of jpg/png files to docx files & then to pdf. My sole concern is to write the data in an image to a pdf file & if I need to edit any text manually, I can do that in word & save it in the corresponding pdf file.
I've tried using API but failed as the text is not correctly matching.
My image files ... | [
"from PIL import Image\nfrom pytesseract import pytesseract\n\n#Define path to tessaract.exe\npath_to_tesseract = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\n\n\n#Define path to image\npath_to_image = 'texttoimage.png'\n\n#Point tessaract_cmd to tessaract.exe\npytesseract.tesseract_cmd = path_to_tesseract\n... | [
2
] | [] | [] | [
"converters",
"jpeg",
"png",
"python"
] | stackoverflow_0074137111_converters_jpeg_png_python.txt |
Q:
Inserting an image inside a table cell in Google Docs API
Is it possible to insert an image directly inside a cell in Google Docs using the API? I wanted to put an image only on the first column in a 1x2 table cell. I've read the documentation, **insertInlineImage** said: The image must be inserted inside the boun... | Inserting an image inside a table cell in Google Docs API | Is it possible to insert an image directly inside a cell in Google Docs using the API? I wanted to put an image only on the first column in a 1x2 table cell. I've read the documentation, **insertInlineImage** said: The image must be inserted inside the bounds of an existing Paragraph. For instance, it cannot be inserte... | [
"This is possible, you can either:\n\nUse a library like https://github.com/tanaikech/gdoctableapppy to make things slightly easier\nWrite the process yourself, the process is as follows:\n\nInsert a placeholder tag where you want your image to be inside a table, e.g. {{myImage}}\nDo a batch update on the document... | [
1
] | [] | [] | [
"google_docs_api",
"python"
] | stackoverflow_0073020693_google_docs_api_python.txt |
Q:
Why doesn't loss function decrease under 1.5?
I'm trying to do machine learning using mnist dataset in pytorch, but the loss function doesn't decrease under 1.5.
I want the loss function to decrease under 1.
What to do for this problem?
what code should I fix?
This is my code:
BATCH_SIZE = 8
transform =torchvisi... | Why doesn't loss function decrease under 1.5? | I'm trying to do machine learning using mnist dataset in pytorch, but the loss function doesn't decrease under 1.5.
I want the loss function to decrease under 1.
What to do for this problem?
what code should I fix?
This is my code:
BATCH_SIZE = 8
transform =torchvision.transforms.Compose([torchvision.transforms.ToTen... | [
"Since I have done a similar task (with a different but comparable network) I know that the Loss when using cross_entropy decreases lower than 1.5. In my case accuracy was ~95% and the loss ~0.200. When inspecting your picture I saw that for the test loss (in the picture you named it Loss evaluate) the value matche... | [
0
] | [] | [] | [
"machine_learning",
"mnist",
"python"
] | stackoverflow_0074136617_machine_learning_mnist_python.txt |
Q:
I am getting "error": "invalid_client" on social_oauth2 when I try to get the tokens through Postman for DjangoOauth
I have attached some of the installations from requirements.txt. I am unable to get the token even after changing versions of djangorestframework etc. Please help. I have been trying different thing... | I am getting "error": "invalid_client" on social_oauth2 when I try to get the tokens through Postman for DjangoOauth | I have attached some of the installations from requirements.txt. I am unable to get the token even after changing versions of djangorestframework etc. Please help. I have been trying different things for 3 days.
Django==3.1.4
django-oauth-toolkit==2.2.0
django-storages==1.9.1
djangorestframework==3.11.1
docutils==0.15.... | [
"I found the solution. The application hashes the client secret on saving it, so we have to copy the client secret and client ID BEFORE SAVING it. The hashed client secret gives invalid client error. Thank you.\nThis is how the unhashed and hashed client secret looks like. We use the unhashed one.\nUnhashed:\nkvTb... | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"django_socialauth",
"python"
] | stackoverflow_0074127295_django_django_rest_framework_django_socialauth_python.txt |
Q:
Pandas - Adding rows from one dataframe to the another
I am trying to add manually row (one by one) from one dataframe to the another:
path = "...csv"
data = pd.read_csv(path, na_values='NULL')
path2 = "...csv"
data2 = pd.read_csv(path2, na_values='NULL')
for row in data2.itertuples():
x = input("Do you ... | Pandas - Adding rows from one dataframe to the another | I am trying to add manually row (one by one) from one dataframe to the another:
path = "...csv"
data = pd.read_csv(path, na_values='NULL')
path2 = "...csv"
data2 = pd.read_csv(path2, na_values='NULL')
for row in data2.itertuples():
x = input("Do you want to add the row, please write Yes or No")
if x=='Y... | [
"DataFrame.itertuples returns a namedtuple, you can convert it to dictionary with ._asdict() and create a one row DataFrame\ndf1 = df1.append(pd.DataFrame([row._asdict()]).set_index('Index'))\n# or\ndf1 = pd.concat([df1, pd.DataFrame([row._asdict()]).set_index('Index')])\n\n",
"You need to pass a Dataframe or Sei... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074137272_dataframe_pandas_python.txt |
Q:
Clear file contents if file is opened as "a" append
Given :
with open("some file path", mode="a", encoding='utf-8') as envConfig_file:
pass
Is there a way to clear the whole file without opening the file again as "w"?
A:
You can use the seek and truncate methods.
As a side note, for reading and then rewrit... | Clear file contents if file is opened as "a" append | Given :
with open("some file path", mode="a", encoding='utf-8') as envConfig_file:
pass
Is there a way to clear the whole file without opening the file again as "w"?
| [
"You can use the seek and truncate methods.\nAs a side note, for reading and then rewriting, the more usual mode would be r+\nwith open(\"some file path\", mode=\"r+\", encoding='utf-8') as envConfig_file:\n ... # read the file\n envConfig_file.seek(0)\n envConfig_file.truncate()\n ... # write new conte... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074137494_python.txt |
Q:
How to fix "django.core.exceptions.FieldError: Unknown field(s) (username) specified"
I have an app that uses a custom User model called MyUser, a custom User manager, and a custom UserCreationForm. I'm trying to add the rest of the fields from the MyUser model to the UserCreationForm, but I keep getting the error... | How to fix "django.core.exceptions.FieldError: Unknown field(s) (username) specified" | I have an app that uses a custom User model called MyUser, a custom User manager, and a custom UserCreationForm. I'm trying to add the rest of the fields from the MyUser model to the UserCreationForm, but I keep getting the error: django.core.exceptions.FieldError: Unknown field(s) (username) specified for MyUser. What... | [
"I have encountered the same issue just today and this is how I have solved it. When I created my custom user model I also created a custom UserCreation form. So when creating your forms make sure that you use the custom form you created and not the built in UserCreation Form that django provides. Example\nThis is ... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0073094888_django_python.txt |
Q:
How to add a sentence before the the number/int PYTHON
Here's the code i did:
list = input("Enter the number: ")
p = print("Trailing zeroes = ")
print(p, list.count("0"))
Output:
Enter the number: 10000
Trailing zeroes =
None 4
The output i wanted:
Enter the number: 10000
Trailing zeroes = 4
A:
To count ... | How to add a sentence before the the number/int PYTHON | Here's the code i did:
list = input("Enter the number: ")
p = print("Trailing zeroes = ")
print(p, list.count("0"))
Output:
Enter the number: 10000
Trailing zeroes =
None 4
The output i wanted:
Enter the number: 10000
Trailing zeroes = 4
| [
"To count trailing zeroes you could do this:\nnum = input('Enter number: ')\n\nntz = len(s)-len(s.rstrip('0'))\n\nprint(f'Your input has {ntz} trailing zeroes')\n\n",
"Here is a working example of the code:\ni = input(\"Enter the number: \")\n\np = \"Trailing zeroes = \" + str(i.count(\"0\"))\n\nprint(p)\n\nOutpu... | [
1,
0,
0,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074137370_list_python_python_3.x.txt |
Q:
Tuples of dictionary in python
Given a dictionary
{4: {'idx': [45, 177, 181],
'Baggage': array([ 13, 103, 87]),
'infeed_idx': array([1, 3, 3])},
7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],
'Baggage': array([12, 27, 50, 51, 16, 30, 15, 59, 16, 8]),
'infeed_idx': array([1, 1, 1... | Tuples of dictionary in python | Given a dictionary
{4: {'idx': [45, 177, 181],
'Baggage': array([ 13, 103, 87]),
'infeed_idx': array([1, 3, 3])},
7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],
'Baggage': array([12, 27, 50, 51, 16, 30, 15, 59, 16, 8]),
'infeed_idx': array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2])},
I would l... | [
"Let's say dct is your dictionary:\nfor k, d in dct.items():\n d['tuple_id'] = list(zip(d['idx'], d['infeed_idx']))\n\n",
"di = {4: {'idx': [45, 177, 181],\n 'Baggage': np.array([ 13, 103, 87]),\n 'infeed_idx': np.array([1, 3, 3])}, \n 7: {'idx': [62, 105, 173, 174, 186, 57, 74, 102, 115, 164],\n... | [
1,
1,
0,
0
] | [] | [] | [
"dictionary",
"python",
"tuples"
] | stackoverflow_0074137619_dictionary_python_tuples.txt |
Q:
Script to transact tokens on the Polygon chain?
I like to automatically transfer funds from all my Metamask wallets into one central wallet automatically on the Polygon chain. How exactly do I do this? Currently I don't how to exactly approach this as the token I'd like to transact is on the polygon chain and I've... | Script to transact tokens on the Polygon chain? | I like to automatically transfer funds from all my Metamask wallets into one central wallet automatically on the Polygon chain. How exactly do I do this? Currently I don't how to exactly approach this as the token I'd like to transact is on the polygon chain and I've only seen implementations for the Ethereum chain. Th... | [
"You are using wrong RPC url for Polygon Mainnet.\nif you are using infura, then it should be like this:\nw3 = Web3(HTTPProvider(\"https://polygon.infura.io/v3/YOUR_INFURA_PROJECT_ID\"))\n\nor you can use public RPC url:\nw3 = Web3(HTTPProvider(\"https://polygon-rpc.com/\"))\n\n"
] | [
0
] | [] | [] | [
"erc20",
"ethereum",
"polygon",
"python",
"web3py"
] | stackoverflow_0074101941_erc20_ethereum_polygon_python_web3py.txt |
Q:
Group and Nested Group for python
I have some data like this,
menu_list = [
{'name':'ABC','parent_id':None,'id':5},
{'name':'XYZ','parent_id':5,'id':7},
{'name':'APPLE','parent_id':7,'id':8},
{'name':'Mango','parent_id':5,'id':9},
{'name':'Mango-small','parent_id':9,'id':10},
]
i was expecting the ... | Group and Nested Group for python | I have some data like this,
menu_list = [
{'name':'ABC','parent_id':None,'id':5},
{'name':'XYZ','parent_id':5,'id':7},
{'name':'APPLE','parent_id':7,'id':8},
{'name':'Mango','parent_id':5,'id':9},
{'name':'Mango-small','parent_id':9,'id':10},
]
i was expecting the final group by result like,
ABC
----XYZ... | [
"you can use recursive function to solve this problem.\nmenu_list = [\n\n {'name':'ABC','parent_id':None,'id':5},\n {'name':'XYZ','parent_id':5,'id':7},\n {'name':'APPLE','parent_id':7,'id':8},\n {'name':'Mango','parent_id':5,'id':9},\n {'name':'Mango-small','parent_id':9,'id':10},\n]\n\n\ndef rec_somehin... | [
2,
1,
0
] | [] | [] | [
"python",
"python_3.8"
] | stackoverflow_0074135937_python_python_3.8.txt |
Q:
how to Perform Divide operations in Pyspark while updating the column?
I have a SQL Query which I want to change into pyspark. we have a Column called CGPA which contains some values and i need to divide the values by 25 where our conditions are matching
UPDATE STUDENT_TABLE
SET STUDENT_TABLE.CGPA = ([STUDENT_TAB... | how to Perform Divide operations in Pyspark while updating the column? | I have a SQL Query which I want to change into pyspark. we have a Column called CGPA which contains some values and i need to divide the values by 25 where our conditions are matching
UPDATE STUDENT_TABLE
SET STUDENT_TABLE.CGPA = ([STUDENT_TABLE].CGPA/25)
WHERE (((STUDENT_TABLE.CGPA)>"5" Or (STUDENT_TABLE.CGPA)="100")... | [
"I have taken the following sample data for my dataframe to demonstrate.\ndata = [[1,4],[2,10],[3,40],[4,100],[5,0],[6,5]]\ndf = spark.createDataFrame(data=data,schema=['id','CGPA'])\ndisplay(df)\n\n\n\nLooking at your SQL query, as you want to update when either of the conditions is true (i.e., or condition in SQL... | [
1
] | [] | [] | [
"apache_spark",
"azure_databricks",
"pyspark",
"python"
] | stackoverflow_0074137422_apache_spark_azure_databricks_pyspark_python.txt |
Q:
Create column of lists
Is there a direct way to create col_list, which specifies when only fruit and clothes are not na?
df fruit clothes trending ...
0 apple shirt no
1 np.NaN trouser yes
2 np.NaN np.NaN yes
df fruit clothes trending ... col_list
0 apple shirt n... | Create column of lists | Is there a direct way to create col_list, which specifies when only fruit and clothes are not na?
df fruit clothes trending ...
0 apple shirt no
1 np.NaN trouser yes
2 np.NaN np.NaN yes
df fruit clothes trending ... col_list
0 apple shirt no ["fruit", "cloth... | [
"Use list comprehension:\nL= ['fruit','clothes']\n\ncols = np.array(L)\ndf['col_list'] = [cols[x].tolist() if x.any() else np.nan for x in df[L].notna().to_numpy()]\n\nprint (df)\n fruit clothes trending col_list\n0 apple shirt no [fruit, clothes]\n1 NaN trouser yes [clothes]... | [
1,
1
] | [] | [] | [
"list",
"pandas",
"python"
] | stackoverflow_0074137746_list_pandas_python.txt |
Q:
Python os.system without the output
I'm running this:
os.system("/etc/init.d/apache2 restart")
It restarts the webserver, as it should, and like it would if I had run the command directly from the terminal, it outputs this:
* Restarting web server apache2 ...
waitin... | Python os.system without the output | I'm running this:
os.system("/etc/init.d/apache2 restart")
It restarts the webserver, as it should, and like it would if I had run the command directly from the terminal, it outputs this:
* Restarting web server apache2 ...
waiting ... | [
"Avoid os.system() by all means, and use subprocess instead:\nwith open(os.devnull, 'wb') as devnull:\n subprocess.check_call(['/etc/init.d/apache2', 'restart'], stdout=devnull, stderr=subprocess.STDOUT)\n\nThis is the subprocess equivalent of the /etc/init.d/apache2 restart &> /dev/null.\nThere is subprocess.DE... | [
57,
34,
25,
1,
0,
0
] | [] | [] | [
"os.system",
"python",
"subprocess"
] | stackoverflow_0005596911_os.system_python_subprocess.txt |
Q:
Elasticsearch : How to delete an Index using python
Forgive me if this is quite basic but I have Python 2.7 and Elasticsearch 2.1.1 and I am just trying to delete an index using
es.delete(index='researchtest', doc_type='test')
but this gives me
return func(*args, params=params, **kwargs)
TypeError: delete() tak... | Elasticsearch : How to delete an Index using python | Forgive me if this is quite basic but I have Python 2.7 and Elasticsearch 2.1.1 and I am just trying to delete an index using
es.delete(index='researchtest', doc_type='test')
but this gives me
return func(*args, params=params, **kwargs)
TypeError: delete() takes at least 4 arguments (4 given)
I also tried
es.delet... | [
"For ES 8+ use:\nfrom elasticsearch import Elasticsearch\nes = Elasticsearch()\n\nes.options(ignore_status=[400,404]).indices.delete(index='test-index')\n\nFor older versions use this notation:\nfrom elasticsearch import Elasticsearch\nes = Elasticsearch()\n\nes.indices.delete(index='test-index', ignore=[400, 404])... | [
159,
11,
1,
0,
0
] | [] | [] | [
"elasticsearch",
"python",
"python_2.7"
] | stackoverflow_0035134162_elasticsearch_python_python_2.7.txt |
Q:
How can I pass a dictionary name into a function and handle KeyError inside the function?
I have a function:
def print_boardrow(row, content, alt_content):
for i in row:
try:
print(content, end="")
except KeyError:
print(alt_content, end="")
And I want to call it like t... | How can I pass a dictionary name into a function and handle KeyError inside the function? | I have a function:
def print_boardrow(row, content, alt_content):
for i in row:
try:
print(content, end="")
except KeyError:
print(alt_content, end="")
And I want to call it like this:
print_boardrow(row, slot[i[0]][0], " ")
But this wouldnt work as 'i' is defined inside... | [
"How about restructuring the code slightly?\ndef print_boardrow(row, key, alt_content):\n print(row.get(key, alt_content), end='')\n\nprint_board_row(row, i[0], ' ')\n\nNot sure what the loop inside the original function is achieving so left it out here. The general idea is the use of get() which removes the po... | [
0
] | [] | [] | [
"error_handling",
"function",
"python"
] | stackoverflow_0074137692_error_handling_function_python.txt |
Q:
Why is the list_comprehension version slower (python)? Are there better ways?
I have a line of code, and I'm surprised, that the list comprehended version is slower. I want to calculate "average sphere distances".
The steps needed to be done:
choose a node
chose all elements at a distance "d" around it (shell at ... | Why is the list_comprehension version slower (python)? Are there better ways? | I have a line of code, and I'm surprised, that the list comprehended version is slower. I want to calculate "average sphere distances".
The steps needed to be done:
choose a node
chose all elements at a distance "d" around it (shell at distance d)
find the shells of radius "d" around all nodes at distance "d"
calculat... | [
"The first version is faster than the rest because you don't call GetShellj(WA,i,eli) as many times.\nIf you slap the @cache or @lru_cache decorator on that function, all of the approaches should be approximately as fast.\n"
] | [
2
] | [] | [] | [
"dijkstra",
"python",
"scipy",
"shortest_path",
"vectorization"
] | stackoverflow_0074137860_dijkstra_python_scipy_shortest_path_vectorization.txt |
Q:
Create shortcut files in Windows 7 using Python
Is there a simple way to create shortcuts in Windows 7 on Python? I looked it up online but they did not seem that simple.
I have tried using this simple method:
hi = open("ShortcutFile.lnk", "w")
hi.close()
Which creates a shortcut file. But how would I edit the l... | Create shortcut files in Windows 7 using Python | Is there a simple way to create shortcuts in Windows 7 on Python? I looked it up online but they did not seem that simple.
I have tried using this simple method:
hi = open("ShortcutFile.lnk", "w")
hi.close()
Which creates a shortcut file. But how would I edit the link it is connected to. Like the file it would open? ... | [
"Old, but I would still like to post an answer to help out anyone who might have the same question and in need of a code example. \nFirst, download pywin32 with pip install pywin32 or download the sourceforge binaries or the pywin32 wheel file and pip install.\nimport win32com.client\nimport pythoncom\nimport os\n#... | [
20,
5,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"operating_system",
"python",
"shortcut",
"windows_7"
] | stackoverflow_0026986470_operating_system_python_shortcut_windows_7.txt |
Q:
How do I get the index of an element in a list that I'm cycling through?
Im trying to brute force a caesar cypher for a school project, and am trying to iterate through a list (the dictionary), to do this I've used itertools to make the list 'infinte' so shifting x by 4 will return a instead of an error.
However: ... | How do I get the index of an element in a list that I'm cycling through? | Im trying to brute force a caesar cypher for a school project, and am trying to iterate through a list (the dictionary), to do this I've used itertools to make the list 'infinte' so shifting x by 4 will return a instead of an error.
However: when using itertools.cycle(dictionary) i get the error "AttributeError: 'itert... | [
"You have two options here.\nThe first is just to save the original list, and index into that:\nchars = list('abc')\nchars_cycle = itertools.cycle(chars)\nfor i, c in enumerate(chars_cycle):\n print(c, chars.index(c))\n if i > 14:\n break\n\nAnother option is to include the index in the cycle itself:\n... | [
0
] | [] | [] | [
"list",
"python",
"python_itertools"
] | stackoverflow_0074137856_list_python_python_itertools.txt |
Q:
How to silent an output from Prophet?
I`m using Prophet (Time series library by Facebook) and it makes a lot of output. Something like this:
Prophet output
I`m already silent some output like this:
@contextmanager
def suppress_stdout():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
... | How to silent an output from Prophet? | I`m using Prophet (Time series library by Facebook) and it makes a lot of output. Something like this:
Prophet output
I`m already silent some output like this:
@contextmanager
def suppress_stdout():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
... | [
"I suspect you are using an IPython-like environment e.g. Jupyter notebook. Then you can use the %%capture magic command in a cell.\nFor example,\n%%capture\noutput = do_some_verbose_things(args)\n\nBy default it also captures the stderr which I think the outputs you see are going there.\n",
"The problem here is ... | [
1,
1
] | [] | [] | [
"facebook_prophet",
"output",
"python"
] | stackoverflow_0067003595_facebook_prophet_output_python.txt |
Q:
Cannot add conda environment to Pycharm - Conda executable path is empty even when it's not
I am pretty proficient in pycharm but it is the first time I stumble into this problem.
I created a conda environment
Finding the conda executable which for me is in /home/my_username/.miniconda3/envs/py39/bin/python
Addin... | Cannot add conda environment to Pycharm - Conda executable path is empty even when it's not | I am pretty proficient in pycharm but it is the first time I stumble into this problem.
I created a conda environment
Finding the conda executable which for me is in /home/my_username/.miniconda3/envs/py39/bin/python
Adding it to pycharm results in:
I tried to search for this issue and error but the results didnt he... | [
"Got it, thank you!\nIn the path you should define a path to the python.exe in the conda environment directory.\nHere is an example:\n\n",
"I ended up re-installing the OS and now it works, I would not call it a solution but it is what it is - I couldnt waste more time on this as I have work to do.\n",
"You nee... | [
0,
0,
0
] | [] | [] | [
"anaconda",
"conda",
"pycharm",
"python"
] | stackoverflow_0073538040_anaconda_conda_pycharm_python.txt |
Q:
Subdivide integers using a given ratio without producing floats
I need to subdivide a given amount of items (lets say 10) using a given ratio [0.55, 0.45]. The result here should either be 6:4 or 5:5. The usual approach [0.55*10, 0.45*10] would result in [6, 5] (11, not 10).
Another example: divide 7 using ratio: ... | Subdivide integers using a given ratio without producing floats | I need to subdivide a given amount of items (lets say 10) using a given ratio [0.55, 0.45]. The result here should either be 6:4 or 5:5. The usual approach [0.55*10, 0.45*10] would result in [6, 5] (11, not 10).
Another example: divide 7 using ratio: [0.36, 0.44, 0.07, 0.07, 0.03, 0.03] which ideally should yield somet... | [
"Here's my try on the matter :) The hardest part being reversing the sort operation and matching it with results... If you don't need to keep the original order of ratios, then you can delete part of the last function.\ndef scale_ratio(ratios: list) -> list:\n sum_ = sum(ratios)\n return [x/sum_ for x in rati... | [
2,
2,
0
] | [] | [] | [
"list",
"math",
"python"
] | stackoverflow_0034156371_list_math_python.txt |
Q:
Djnago send mail not working, also not showing any error
Settings.py
DEFAULT_FROM_EMAIL = 'testing.email2908@gmail.com'
SERVER_EMAIL = 'testing.email2908@gmail.com'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'testing.email2908@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAILL_USE_TLS = True
... | Djnago send mail not working, also not showing any error | Settings.py
DEFAULT_FROM_EMAIL = 'testing.email2908@gmail.com'
SERVER_EMAIL = 'testing.email2908@gmail.com'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'testing.email2908@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAILL_USE_TLS = True
views.py
print('Helloo')
send_mail(
'Testing',
'Hi',
... | [
"try this\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\nEMAIL_HOST_USER = 'emailId'\nEMAIL_HOST_PASSWORD = 'password'\n\n",
"Need to set Following configuration in settings.py\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074137161_django_python.txt |
Q:
Return the label of a slider instead of the value in the callback
I have this code:
from dash import Dash, html, dcc
from dash.dependencies import Input, Output
app = Dash()
app.layout = html.Div([
dcc.Slider(0, 10,
step=None,
marks={
0: '0 kid',
3: '3 kids',
5... | Return the label of a slider instead of the value in the callback | I have this code:
from dash import Dash, html, dcc
from dash.dependencies import Input, Output
app = Dash()
app.layout = html.Div([
dcc.Slider(0, 10,
step=None,
marks={
0: '0 kid',
3: '3 kids',
5: '5 kids',
10: '10 kids'
},
value=5,
id="my-slider... | [
"You can use a dictionary to solve this problem. First, try to define a dictionary and add it to marks inside dcc.Slider and then reuse it inside the callback.\nFull example:\nfrom dash import Dash, html, dcc\nfrom dash.dependencies import Input, Output\n\napp = Dash()\n\nmarks_dict={ #<------ this is the... | [
2
] | [] | [] | [
"plotly_dash",
"python",
"slider"
] | stackoverflow_0074137248_plotly_dash_python_slider.txt |
Q:
Merging rows in one pandas dataframe
I have a pandas dataframe looking like this:
variable value
0 company_id
1 company_name Rechner
2 former_company_name
3 company_street Teststraße
4 company_str... | Merging rows in one pandas dataframe | I have a pandas dataframe looking like this:
variable value
0 company_id
1 company_name Rechner
2 former_company_name
3 company_street Teststraße
4 company_street_nr 20
5 comp... | [
"First group values as array:\ndf2 = df.groupby(\"variable\").agg(list)\n\n>> value\n>> variable \n>> company_id [nan]\n>> company_name [Rechner, Rechner2]\n>> company_street [Teststra... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074137756_dataframe_pandas_python.txt |
Q:
How to hide a Pydantic discriminator field from FastAPI docs
We have a discriminator field type which we want to hide from the Swagger UI docs:
class Foo(BDCBaseModel):
type: Literal["Foo"] = Field("Foo", exclude=True)
Name: str
class Bar(BDCBaseModel):
type: Literal["Bar"] = Field("Bar", exclude=True... | How to hide a Pydantic discriminator field from FastAPI docs | We have a discriminator field type which we want to hide from the Swagger UI docs:
class Foo(BDCBaseModel):
type: Literal["Foo"] = Field("Foo", exclude=True)
Name: str
class Bar(BDCBaseModel):
type: Literal["Bar"] = Field("Bar", exclude=True)
Name: str
class Demo(BDCBaseModel):
example: Union[Foo,... | [
"This is a very common situation and the solution is farily simple. Factor out that type field into its own separate model.\nThe typical way to go about this is to create one FooBase with all the fields, validators etc. that all child models will share (in this example only name) and then subclass it as needed. In ... | [
1,
0
] | [] | [] | [
"fastapi",
"pydantic",
"python"
] | stackoverflow_0074137116_fastapi_pydantic_python.txt |
Q:
Getting CUDA error when trying to train MBART Model
from transformers import MBart50TokenizerFast
from transformers import MBartForConditionalGeneration
tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt",src_lang="", tgt_lang="")
model = MBartForConditionalGeneration.from_p... | Getting CUDA error when trying to train MBART Model | from transformers import MBart50TokenizerFast
from transformers import MBartForConditionalGeneration
tokenizer = MBart50TokenizerFast.from_pretrained("facebook/mbart-large-50-many-to-many-mmt",src_lang="", tgt_lang="")
model = MBartForConditionalGeneration.from_pretrained("facebook/mbart-large-50-many-to-many-mmt");
ba... | [
"There are a few things that you can try in order to reduce the memory footprint and avoid OOM issues:\n\nGradient accumulation: When using gradient accumulation, gradient calculation is done in smaller steps rather than all at once for a batch. In order to use this, all you have to do is set the gradient_accumulat... | [
0
] | [] | [] | [
"computer_vision",
"machine_translation",
"nlp",
"python"
] | stackoverflow_0074065165_computer_vision_machine_translation_nlp_python.txt |
Q:
Keep duplicates in a list in Python
I know this is probably an easy answer but I can't figure it out. What is the best way in Python to keep the duplicates in a list:
x = [1,2,2,2,3,4,5,6,6,7]
The output should be:
[2,6]
I found this link: Find (and keep) duplicates of sublist in python, but I'm still relativel... | Keep duplicates in a list in Python | I know this is probably an easy answer but I can't figure it out. What is the best way in Python to keep the duplicates in a list:
x = [1,2,2,2,3,4,5,6,6,7]
The output should be:
[2,6]
I found this link: Find (and keep) duplicates of sublist in python, but I'm still relatively new to Python and I can't get it to wor... | [
"I'd use a collections.Counter:\nfrom collections import Counter\nx = [1, 2, 2, 2, 3, 4, 5, 6, 6, 7]\ncounts = Counter(x)\noutput = [value for value, count in counts.items() if count > 1]\n\nHere's another version which keeps the order of when the item was first duplicated that only assumes that the sequence passed... | [
16,
10,
2,
0,
0
] | [] | [] | [
"duplicates",
"python"
] | stackoverflow_0015812547_duplicates_python.txt |
Q:
Beautiful Soup Parsing from a HTML Website
I'm very new to web scrapping and perhaps python3 as well, was hoping to receive help in order to solve my problem.
I am scraping from the following webpage: http://ets.aeso.ca/ets_web/ip/Market/Reports/CSDReportServlet
I received code from: New to Beautiful Soup. Need to... | Beautiful Soup Parsing from a HTML Website | I'm very new to web scrapping and perhaps python3 as well, was hoping to receive help in order to solve my problem.
I am scraping from the following webpage: http://ets.aeso.ca/ets_web/ip/Market/Reports/CSDReportServlet
I received code from: New to Beautiful Soup. Need to scrape tables from an online report
Here's the ... | [
"It's been a while, so maybe you've already solved some or all of the issues, but in case you haven't, I can suggest some solutions.\n(First, I saved the DataFrame as ggDf with ggDf = get_gas(soup), so it's easier to refer to and I don't have to call get_gas again and again.)\n\n\nQuestion: Not sure why the code sp... | [
0
] | [] | [] | [
"beautifulsoup",
"pandas",
"python"
] | stackoverflow_0073954775_beautifulsoup_pandas_python.txt |
Q:
Append list to dictionary
I am working on a code like below, which slices the address column. For this I have created a dictionary and created an empty list final to append all the pre processing.see code
import pandas as pd
data = {'id': ['001', '002', '003'],
'address': ["William J. Clare\\n290 Valley ... | Append list to dictionary | I am working on a code like below, which slices the address column. For this I have created a dictionary and created an empty list final to append all the pre processing.see code
import pandas as pd
data = {'id': ['001', '002', '003'],
'address': ["William J. Clare\\n290 Valley Dr.\\nCasper, WY 82604\\nUSA",
... | [
"If you want to assing to dictionary\ndf_dict['address'] = final\n\nBut you can assign directly to dataframe\ndf['address'] = final\n\nYou could even use .apply(function) to do it without creating dictionary\ndef preprocess(value):\n parts = value.split(\"\\\\n\") \n if len(parts) > 3:\n parts = parts[... | [
0
] | [] | [] | [
"dataframe",
"dictionary",
"list",
"pandas",
"python"
] | stackoverflow_0074137223_dataframe_dictionary_list_pandas_python.txt |
Q:
How To Export GCP Security Command Center Findings To BigQuery?
Similar to this: How to export GCP's Security Center Assets to a Cloud Storage via cloud Function?
I need to export the Findings as seen in the Security Command Center to BigQuery so we can easily filter the data we need and generate custom reports.
U... | How To Export GCP Security Command Center Findings To BigQuery? | Similar to this: How to export GCP's Security Center Assets to a Cloud Storage via cloud Function?
I need to export the Findings as seen in the Security Command Center to BigQuery so we can easily filter the data we need and generate custom reports.
Using this documentation as an example (https://cloud.google.com/secur... | [
"Not sure if this existed back then in Q2 of 2021, but now there is documentation telling how to do this:\nhttps://cloud.google.com/security-command-center/docs/how-to-analyze-findings-in-big-query\nYou can create exports of SCC findings to bigquery using this command:\ngcloud scc bqexports create BIG_QUERY_EXPORT ... | [
1,
0
] | [] | [] | [
"cloud_security",
"google_bigquery",
"google_cloud_platform",
"python",
"securitycenter"
] | stackoverflow_0067303225_cloud_security_google_bigquery_google_cloud_platform_python_securitycenter.txt |
Q:
Invalid character found in method name. HTTP method must be tokens
Edit: I no longer work at this place, and we switched to node.js anyway, so I cannot verify if anyone's answers are correct. Please vote to close (just need one more).
This is not a duplicate of the other questions (or at least the ones I came acro... | Invalid character found in method name. HTTP method must be tokens | Edit: I no longer work at this place, and we switched to node.js anyway, so I cannot verify if anyone's answers are correct. Please vote to close (just need one more).
This is not a duplicate of the other questions (or at least the ones I came across) because I don't use SSL/HTTPS anywhere in my code. I was also able t... | [
"I had a similar issue and adding \n<dependency>\n <groupId>com.fasterxml.jackson.core</groupId>\n <artifactId>jackson-databind</artifactId>\n <version>2.6.3</version>\n</dependency>\n\nfixed the issue for me. \n",
"#Increase header buffer size\n#server.tomact.max-http-header-size: 8192 this is lose ef... | [
1,
1,
1,
0
] | [] | [] | [
"java",
"python",
"raspberry_pi",
"spring_boot",
"tomcat"
] | stackoverflow_0044372545_java_python_raspberry_pi_spring_boot_tomcat.txt |
Q:
Combining time series data frames
I have two dataframes and like to add a column to the first one with volume information from the second one. The first dataframe should have a volume column with the sum of the volume from the second dataframe determined between the index rows of the first dataframe.
Can someone p... | Combining time series data frames | I have two dataframes and like to add a column to the first one with volume information from the second one. The first dataframe should have a volume column with the sum of the volume from the second dataframe determined between the index rows of the first dataframe.
Can someone point me in the right direction please? ... | [
"You can use a merge_asof:\ndf1.index = pd.to_datetime(df1.index)\ndf2.index = pd.to_datetime(df2.index)\n\ns = pd.Series(range(len(df1)), index=df1.index, name='id')\n\ndf1['volume'] = s.map(\n pd.merge_asof(df2, df1.assign(id=s)['id'],\n left_index=True, right_index=True)\n .groupby('id').su... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074138142_pandas_python.txt |
Q:
Getting only decoded payload from JWT in python
Is there a nice way (using maybe some library) to get only payload from JWT saved as string variable?
Other than manually parsing it for content between first and second dots and then decoding.
A:
The library PyJWT has an option to decode a JWT without verification... | Getting only decoded payload from JWT in python | Is there a nice way (using maybe some library) to get only payload from JWT saved as string variable?
Other than manually parsing it for content between first and second dots and then decoding.
| [
"The library PyJWT has an option to decode a JWT without verification:\nWithout this option, the decode function does not only decode the token but also verifies the signature and you would have to provide the matching key. And that's of course the recommended way. \nBut if you, for whatever reason, just want to de... | [
62,
4
] | [] | [] | [
"jwt",
"python"
] | stackoverflow_0059425161_jwt_python.txt |
Q:
500 internal server error while using Django and React
I faced some problem using react and django.
When I made a http request to django server, I got 500 Internal Server Error.
My code looks like.
urls.py
from usercontrol.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', User... | 500 internal server error while using Django and React | I faced some problem using react and django.
When I made a http request to django server, I got 500 Internal Server Error.
My code looks like.
urls.py
from usercontrol.views import *
urlpatterns = [
path('admin/', admin.site.urls),
path('auth/', UserView.as_view(), name="something")
]
usercontrol/views.py
... | [
"Need to install corsheaders in django.\npip install django-cors-headers\n\nAlso need to add following configuration in settings.py and add corsheaders in Installed_apps\nCORS_ORIGIN_ALLOW_ALL = True\n\nCORS_ORIGIN_WHITELIST = [\n \"http://127.0.0.1:3000\", \n \"http://127.0.0.1\", \n \"http://localhost:30... | [
0
] | [] | [] | [
"django",
"internal_server_error",
"python",
"reactjs"
] | stackoverflow_0074132428_django_internal_server_error_python_reactjs.txt |
Q:
Is there a way to download a sample CSV file
I used a sample of a csv program to do some tables on Jupiter notebook, I now need to download that sample csv file so I can look at it in excel, is there a way I can download the sample
I need to download lf if possible.
Here is my code:
warnings.filterwarnings("ignore... | Is there a way to download a sample CSV file | I used a sample of a csv program to do some tables on Jupiter notebook, I now need to download that sample csv file so I can look at it in excel, is there a way I can download the sample
I need to download lf if possible.
Here is my code:
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd
import ... | [
"You first need to convert the sample to a dataframe and then you can export it.\ndframe.to_csv(“file_name.csv”)\n\nLet me know if it works.\n",
"Answer from here:\nimport urllib.request\nurllib.request.urlretrieve(\"http://jupyter.com/diamond.csv\", \"diamond.csv\")\n\n",
"if what you mean by download is expor... | [
2,
1,
1
] | [] | [] | [
"assign",
"csv",
"export_to_csv",
"jupyter_notebook",
"python"
] | stackoverflow_0074127744_assign_csv_export_to_csv_jupyter_notebook_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.