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 read specific file while passing multiple parameters in python?
I am trying to read specific big query table by passing argument value in my function, so depends on which argument value I pass, my function should read specific datatable. To do so, I was able to write this in python, but I feel like this is ... | how to read specific file while passing multiple parameters in python? | I am trying to read specific big query table by passing argument value in my function, so depends on which argument value I pass, my function should read specific datatable. To do so, I was able to write this in python, but I feel like this is not quite elegant. I tried to use *args and **kwargs, but seems **kwargs cou... | [
"You have confusion over the how *args and **kwargs works in general. Please see this article to help you demystify. You can also see this SO answer: here\nWorking version of your code with inline comments:\ndef _readbqTble1(which_dim=\"lifespan\", which_src=\"asia\", **kwargs):\n def str_join(*args):\n r... | [
1
] | [] | [] | [
"dataframe",
"function",
"python"
] | stackoverflow_0074636896_dataframe_function_python.txt |
Q:
Django Rest Framework : RetrieveUpdateAPIView
I want to add multiple data to database with RetrieveUpdateAPIView and I am not able to add that data in database. How can I update this all date in single Patch method.
My view is like
class CompanyDetailViewAPI(RetrieveUpdateAPIView):
queryset = Companies.objects... | Django Rest Framework : RetrieveUpdateAPIView | I want to add multiple data to database with RetrieveUpdateAPIView and I am not able to add that data in database. How can I update this all date in single Patch method.
My view is like
class CompanyDetailViewAPI(RetrieveUpdateAPIView):
queryset = Companies.objects.all()
serializer_class = CompanyDetailsSeriali... | [
"You can use a single Patch request to update the data in the database. You will need to use a custom serializer to include all the fields you want to update. Here is an example of how you could do this:\nclass CompanyDetailViewAPI(RetrieveUpdateAPIView):\nqueryset = Companies.objects.all()\nserializer_class = Comp... | [
0
] | [] | [] | [
"django",
"django_rest_framework",
"mysql",
"pgadmin",
"python"
] | stackoverflow_0074628350_django_django_rest_framework_mysql_pgadmin_python.txt |
Q:
Hey, I've just started learning python. Can someone explain how this function is returning the value? I made this by following a tutorial
def raiseToPower(basNum, powNum):
result = 1
for index in range(powNum):
result = result * basNum
return result
print(raiseToPower(3, 3))
result: '27'
| Hey, I've just started learning python. Can someone explain how this function is returning the value? I made this by following a tutorial | def raiseToPower(basNum, powNum):
result = 1
for index in range(powNum):
result = result * basNum
return result
print(raiseToPower(3, 3))
result: '27'
| [] | [] | [
"def raiseToPower(basNum, powNum):\n\n result = 1\n \n for index in range(powNum): # here multiplying baseNum with itself powNum times\n result = result * basNum\n return result\n\n\nCalculating 3^3\n\nprint(raiseToPower(3, 3))\n27\n\n\nCalculating 2^10\n\nprint(raiseToPower(2, 10))\n1024\n\n"
] | [
-4
] | [
"python"
] | stackoverflow_0074637279_python.txt |
Q:
Why does `scipy.sparse.csr_matrix` broadcast multiplication but not subtraction?
I am trying to understand solutions to this question here, and while I can just reuse the code I would prefer to know what is happening before I do.
The question is about how to tile a scipy.sparse.csr_matrix object, and the top answe... | Why does `scipy.sparse.csr_matrix` broadcast multiplication but not subtraction? | I am trying to understand solutions to this question here, and while I can just reuse the code I would prefer to know what is happening before I do.
The question is about how to tile a scipy.sparse.csr_matrix object, and the top answer (by @user3357359) at the time of writing shows how to tile a single row of a matrix ... | [
"With dense arrays, broadcasted multiplication and matrix multiplication can do the same thing for special cases. For example with 2 1d arrays\nIn [3]: x = np.arange(3); y = np.arange(5)\n\nbroadcasted:\nIn [4]: x[:,None]*y # (3,1)*(5,) => (3,1)*(1,5) => (3,5)\nOut[4]: \narray([[0, 0, 0, 0, 0],\n [0, 1, 2,... | [
0
] | [] | [] | [
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0074634985_python_scipy_sparse_matrix.txt |
Q:
To iterate through a .txt table in python
Student ID, Assignment, Score
123456, Zany Text, 100
123456, Magic 9 Ball, 60
123456, Nim Grab, 80
123456, Dungeon Crawl, 78
123456, Ultimate TODO List, 90
654321, Zany Text, 48
This is the content of the .txt file, I need to iterate through this text and get the average ... | To iterate through a .txt table in python | Student ID, Assignment, Score
123456, Zany Text, 100
123456, Magic 9 Ball, 60
123456, Nim Grab, 80
123456, Dungeon Crawl, 78
123456, Ultimate TODO List, 90
654321, Zany Text, 48
This is the content of the .txt file, I need to iterate through this text and get the average Score of all the students (and do some other st... | [
"It should be something like:\n# read the file\ncontent = []\nwith open(\"scores.txt\", \"r\") as infile:\n for line in infile:\n if not line.isspace(): # skip empty lines\n content.append(line.strip().split(','))\n\n# print the content \nfor row in content:\n for element in row:\n ... | [
1,
0,
0
] | [] | [] | [
"arrays",
"list",
"multidimensional_array",
"python",
"tuples"
] | stackoverflow_0074637025_arrays_list_multidimensional_array_python_tuples.txt |
Q:
PyCharm terminal and project interpreter do not match
I have developed a project with PyCharm using Python 3.7. Now I want to upgrade the project to Python 3.10.
I managed to install Python 3.10 and select it as the project interpreter but the terminal in PyCharm is still using 3.7. Why is that? How to use 3.10 in... | PyCharm terminal and project interpreter do not match | I have developed a project with PyCharm using Python 3.7. Now I want to upgrade the project to Python 3.10.
I managed to install Python 3.10 and select it as the project interpreter but the terminal in PyCharm is still using 3.7. Why is that? How to use 3.10 in all cases?
*Additional question is whether it is possible ... | [
"Case 1. Starting with a single fresh project\nThe interpreter that gets activated when you open the terminal (or a new terminal tab) is the one chosen in File > Settings > Project > Python Interpreter provided you've chosen File > Settings > Tools > Terminal > Activate virtualenv.\nIf you start with a fresh projec... | [
1
] | [] | [] | [
"interpreter",
"pycharm",
"python"
] | stackoverflow_0074605697_interpreter_pycharm_python.txt |
Q:
Automated Market Makers - Liquidity Pool - Question about the calculation
Esteemed,
I would like to code all the steps for the correct calculation of a pool balance according to Uniswap V2 logic.
Anyone who knew how to help can write in any programming language (Python, Javascript etc.), in this example I used R.
... | Automated Market Makers - Liquidity Pool - Question about the calculation | Esteemed,
I would like to code all the steps for the correct calculation of a pool balance according to Uniswap V2 logic.
Anyone who knew how to help can write in any programming language (Python, Javascript etc.), in this example I used R.
The balancing process for a liquidity pool can be seen here: example1 and examp... | [
"For DeFi protocols using automated market makers, we implement a pool of a pair of assets (for example, BTC-USDT), and we price the two assets simply with:\nb * u = constant\nHere b is the amount of BTC in the pool, and u is the amount of USDT. Besides, the constant is often written as K in many papers.\nNow assum... | [
0,
0
] | [] | [] | [
"cryptocurrency",
"javascript",
"logic",
"python",
"r"
] | stackoverflow_0070148373_cryptocurrency_javascript_logic_python_r.txt |
Q:
A problem concerning ordering issue using sort_vlue(pandas)
I want to find out a max value, so I use df.groupby('h_type').max()['h_price'] but it gives a strange result. Therefore, I use the following code and then find out there is an ordering issue
bond=pd.read_csv('/content/drive/MyDrive/test/datahistory/c.cs... | A problem concerning ordering issue using sort_vlue(pandas) | I want to find out a max value, so I use df.groupby('h_type').max()['h_price'] but it gives a strange result. Therefore, I use the following code and then find out there is an ordering issue
bond=pd.read_csv('/content/drive/MyDrive/test/datahistory/c.csv',index_col='h_type')
a=bond.loc['mansion']
aMax=a.sort_values([... | [
"Problem is column h_price is not numeric, need:\nbond=pd.read_csv('/content/drive/MyDrive/test/datahistory/c.csv',index_col='h_type')\nbond['h_price'] = bond['h_price'].str.replace(',','.', regex=True).astype(float)\n\na=bond.loc['mansion']\naMax=a.sort_values(['h_price'],ascending=False)\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074636885_pandas_python.txt |
Q:
Rearrange object DataFrame
I'm trying to rearrange an object dataframe to be in DDMMYYYY format.
The original format was MM/DD/YYYY.
import string
import pandas as pd
csv_file = 'export.csv'
df = pd.read_csv(csv_file, index_col=False)
df["Date1"] = df["Order_Date"].str.split(" ").str.get(0)
df["Date"] = df["Date1... | Rearrange object DataFrame | I'm trying to rearrange an object dataframe to be in DDMMYYYY format.
The original format was MM/DD/YYYY.
import string
import pandas as pd
csv_file = 'export.csv'
df = pd.read_csv(csv_file, index_col=False)
df["Date1"] = df["Order_Date"].str.split(" ").str.get(0)
df["Date"] = df["Date1"].str.split("/")
zz= df["Date"]... | [
"Instead solitting convert column to datetimes byto_datetime and then use Series.dt.strftime:\ndf[\"Date\"] = pd.to_datetime(df[\"Order_Date\"].str.split().str.get(0)).dt.strftime('%d%m%Y')\n\nOr use Series.str.extract for valeus before first space:\ndf[\"Date\"] = (pd.to_datetime(df[\"Order_Date\"].str.extract('(.... | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074637483_dataframe_pandas_python.txt |
Q:
How do I detect if a string with whitespace contains a number in pandas?
I'm trying to seperate a list of mailing addresses and names that are intertwined in a single column due to poor formating. I initially wanted to grab all of the entries that are alphanumeric so I can separate them however I'm having trouble ... | How do I detect if a string with whitespace contains a number in pandas? | I'm trying to seperate a list of mailing addresses and names that are intertwined in a single column due to poor formating. I initially wanted to grab all of the entries that are alphanumeric so I can separate them however I'm having trouble with the .isalnum() function. My string is a mailing address so I can't remove... | [
"Possible duplicate: Check if a string contains a number.\ndef has_numbers(inputString):\n return any(char.isdigit() for char in inputString)\n\nhas_numbers(\"123 main st\")\nTrue\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074637221_pandas_python.txt |
Q:
i am a new python user and i tried ursina, i created a little 2d shooter game but i don't know how to add a reload time for the each shot
I want to have a delay between each shot or maybe a limited bulled number and then a reload time.
def input (key):
if key == 'space':
e = Entity(y=zeri.y, x=zeri.x+2... | i am a new python user and i tried ursina, i created a little 2d shooter game but i don't know how to add a reload time for the each shot | I want to have a delay between each shot or maybe a limited bulled number and then a reload time.
def input (key):
if key == 'space':
e = Entity(y=zeri.y, x=zeri.x+2, model='quad', collider='box', texture="textures/bum.png")
e.animate_x(30, duration=2, curve=curve.linear)
invoke(destroy, e, ... | [
"This would give you delay after each shot (untested pseudo code out of my head but you should get the picture)\nfrom time import time\n\nshot_threshold = 20 # Each shot no sooner than 20ms from last one\nlast_shot = None\n\nif key == 'space':\n if not last_shot or time.time_ns() - last_shot > shot_threshold:\n ... | [
0
] | [] | [] | [
"python",
"ursina"
] | stackoverflow_0074620120_python_ursina.txt |
Q:
importing a csv file with clean columns using pandas?
so i'm trying to import this csv file and each value is seperated by a comma but how do i make new rows and columns from the imported data?
I tried importing it as normal and printing the data frame in different ways.
A:
try the same with
df = pd.read_csv('fi... | importing a csv file with clean columns using pandas? | so i'm trying to import this csv file and each value is seperated by a comma but how do i make new rows and columns from the imported data?
I tried importing it as normal and printing the data frame in different ways.
| [
"try the same with\ndf = pd.read_csv('file_name.csv', sep = ',')\n\nthis might work\n"
] | [
0
] | [] | [] | [
"csv",
"dataframe",
"format",
"pandas",
"python"
] | stackoverflow_0074636627_csv_dataframe_format_pandas_python.txt |
Q:
How to pass a javascript variable in html to views.py?
I am currently trying to make an website using django.
And i faced a problem like i wrote in title.
What i want to make is like this,
first of all, shop page shows all products.
But, when a user select a brand name on dropdown menu, shop page must shows only t... | How to pass a javascript variable in html to views.py? | I am currently trying to make an website using django.
And i faced a problem like i wrote in title.
What i want to make is like this,
first of all, shop page shows all products.
But, when a user select a brand name on dropdown menu, shop page must shows only that brand products.
To do this, i have to get a variable whi... | [
"base.html\n{% load static %}\n\n<!DOCTYPE html>\n<html lang='en'>\n <head>\n <title>{% block title %}My amazing site{% endblock %}</title>\n <meta charset='utf-8'>\n <link rel=\"stylesheet\" href=\"{% static 'base.css' %}\">\n </head>\n\n <body>\n <div id=\"content\">\n ... | [
0
] | [] | [] | [
"django",
"javascript",
"python"
] | stackoverflow_0074636986_django_javascript_python.txt |
Q:
How to append a column to a DataFrame that collects values of another DataFrame in Python?
I have two tables (as Pandas' DataFrame), one is like
name
val
name1
0
name2
1
the other is
name
tag
name1
tg1
name1
tg2
name1
tg3
name1
tg3
name2
kg1
name2
kg1
name3
other
and I want to append a column to the f... | How to append a column to a DataFrame that collects values of another DataFrame in Python? | I have two tables (as Pandas' DataFrame), one is like
name
val
name1
0
name2
1
the other is
name
tag
name1
tg1
name1
tg2
name1
tg3
name1
tg3
name2
kg1
name2
kg1
name3
other
and I want to append a column to the first DataFrame collecting all values of the second table by name, i.e.
... | [
"Use DataFrame.join with aggregate lists:\ndf = df1.join(df2.groupby('name')['tag'].agg(list).rename('new_column'), on='name')\nprint (df)\n name val new_column\n0 name1 0 [tg1, tg2, tg3, tg3]\n1 name2 1 [kg1, kg1]\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074637551_dataframe_pandas_python.txt |
Q:
How to remove the error of 'can only concatenate str (not "float") to str' in Python while returning a string?
I am trying to calculate a percentage of landmass occupied by a country from the total landmass.I am taking two arguments as string and float in a function and returning String along with the calculated p... | How to remove the error of 'can only concatenate str (not "float") to str' in Python while returning a string? | I am trying to calculate a percentage of landmass occupied by a country from the total landmass.I am taking two arguments as string and float in a function and returning String along with the calculated percentage in it. For example the Input =area_of_country("Russia", 17098242) and Output = "Russia is 11.48% of the to... | [
"You need to cast the percentage (since it's a float) into a string when concatenating using the + operator. So your return statement would look like:\nreturn str(st) + \"is\" + str(percentage) + \"of total world mass!\"\n\n",
"instead of this:\n\nreturn st + \"is\" + percentage + \"of total world mass!\"\n\nTry ... | [
2,
1
] | [] | [] | [
"data_structures",
"integer",
"python",
"string"
] | stackoverflow_0074637548_data_structures_integer_python_string.txt |
Q:
Error concatenating specific sheet from multiple workbooks into one df
I am trying to separate out a specific sheet from about 300 excel workbooks and combine them into a single dataframe.
I have tried this code:
import pandas as pd
import glob
import openpyxl
from openpyxl import load_workbook
pd.set_option("dis... | Error concatenating specific sheet from multiple workbooks into one df | I am trying to separate out a specific sheet from about 300 excel workbooks and combine them into a single dataframe.
I have tried this code:
import pandas as pd
import glob
import openpyxl
from openpyxl import load_workbook
pd.set_option("display.max_rows", 100, "display.max_columns", 100)
allexcelfiles = glob.glob(r... | [
"You can concat dictonary of DataFrames, reason is because multiple sheetnames in list_of_sheetnames:\nfor ExcelFile in allexcelfiles:\n wb = load_workbook(ExcelFile)\n\n list_of_sheetnames = [sheet for sheet in wb.sheetnames if \"SAR\" in sheet]\n \n dfs = pd.read_excel(ExcelFile, sheet_name = list_of_... | [
0
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"python"
] | stackoverflow_0074637544_dataframe_excel_pandas_python.txt |
Q:
error while inserting values python mysql
everything syntax is right but still getting errors .how to fix this error ?
not inserting data due to syntax error
try:
cur.execute('insert into test(PassengerId,SibSp,Parch,Embarked) values(892,0,0,'Q'),(893,1,0,'S'),(894,0,0,'Q'),(895,0,0,'S'),(896,1,1,'S')')
pr... | error while inserting values python mysql | everything syntax is right but still getting errors .how to fix this error ?
not inserting data due to syntax error
try:
cur.execute('insert into test(PassengerId,SibSp,Parch,Embarked) values(892,0,0,'Q'),(893,1,0,'S'),(894,0,0,'Q'),(895,0,0,'S'),(896,1,1,'S')')
print('data inserted successfully')
except Except... | [
"Since you have using ' to wrap the parameters,so you need to use \" to wrap the sql itself\ntry:\n cur.execute(\"insert into test(PassengerId,SibSp,Parch,Embarked) values(892,0,0,'Q'),(893,1,0,'S'),(894,0,0,'Q'),(895,0,0,'S'),(896,1,1,'S')\")\n print('data inserted successfully')\nexcept Exception as e:\n ... | [
1
] | [] | [] | [
"jupyter_notebook",
"mysql",
"python"
] | stackoverflow_0074637584_jupyter_notebook_mysql_python.txt |
Q:
how to run same set of scenarios in 2 backgrounds in behave python
I have 2 backgrounds for my login page 1) in which the user accepts the cookie 2) user declines cookies.
Feature:ORG_LOGIN|Login action with organization ID after accepting cookies
Background:
Given User is on login page
When user accept... | how to run same set of scenarios in 2 backgrounds in behave python | I have 2 backgrounds for my login page 1) in which the user accepts the cookie 2) user declines cookies.
Feature:ORG_LOGIN|Login action with organization ID after accepting cookies
Background:
Given User is on login page
When user accepts the cookies
And User navigates to organization tab
And clicks ... | [
"I resolved it by removing duplicate implementations of the steps.\n"
] | [
0
] | [] | [] | [
"bdd",
"python",
"selenium_webdriver"
] | stackoverflow_0074637546_bdd_python_selenium_webdriver.txt |
Q:
How can I use pdb (Python debugger) in Visual Studio Code IDE's debugger?
I always used pdb for Python debugging before. Recently, I start using Visual Studio Code.
It looks in Visual Studio Code debugger, if I set a breakpoint(), Visual Studio Code will show variables' value at stopped position in the left window... | How can I use pdb (Python debugger) in Visual Studio Code IDE's debugger? | I always used pdb for Python debugging before. Recently, I start using Visual Studio Code.
It looks in Visual Studio Code debugger, if I set a breakpoint(), Visual Studio Code will show variables' value at stopped position in the left window and I have to control it by a GUI bar.
So in "integratedTerminal" or "external... | [
"According to the information you described, when I use \"breakpoint()\" in the code, I click F5 to debug the code in Visual Studio Code. When the code stops, we can use the shortcut key Ctrl + Shift + ` to open a new terminal and enter the pdb interactive window. At this point, we can not only see the debug variab... | [
2,
0
] | [] | [] | [
"pdb",
"python",
"visual_studio_code",
"vscode_debugger"
] | stackoverflow_0065677725_pdb_python_visual_studio_code_vscode_debugger.txt |
Q:
Triggering an Azure Function that takes more than 2 minutes to run from logic apps
I am trying to trigger an Azure Function from Logic Apps. Running the Azure function takes more than 2 minutes as it is reading a file from a location, converts it to another format and then writes it to a different location. The pr... | Triggering an Azure Function that takes more than 2 minutes to run from logic apps | I am trying to trigger an Azure Function from Logic Apps. Running the Azure function takes more than 2 minutes as it is reading a file from a location, converts it to another format and then writes it to a different location. The problem is that the Logic Apps is creating a request, waits for 2 minutes to get a respons... | [
"Continue the work on another logic app.\nJust change your logic app to return Accepted/OK response and calls the function.\nThe function does the work and after it finishes (or fails) it calls another logic app where it continues the work (or deal with the error).\n",
"I agree with @Mocas, and also you can make ... | [
0,
0
] | [] | [] | [
"azure_functions",
"azure_logic_apps",
"python"
] | stackoverflow_0074446349_azure_functions_azure_logic_apps_python.txt |
Q:
Django | joined path is located outside of the base path component {% static img.thumbnail.url %}, Error 400 with whitenoise
I've finish my first app in Django and works perfectly, but still have pre-deployment problems since I set DEGUG=False ...
Here is just to display an image in a template... T_T
I was using t... | Django | joined path is located outside of the base path component {% static img.thumbnail.url %}, Error 400 with whitenoise | I've finish my first app in Django and works perfectly, but still have pre-deployment problems since I set DEGUG=False ...
Here is just to display an image in a template... T_T
I was using this, but now it does'nt work when I use whitenoise to serve my image localy... And it return a Bad Request(400) error...
Models.p... | [
"Bro, you cant load staticfile when you use images on models, there is 2 different ways to work with images in django.\nStatics files is for files that are static(images files like logo of your company, banners, javascript files, css files)\nMedia Files is for dinamic files like user photo, user gallery, product im... | [
6,
2,
0
] | [
"Try <img src=\"{{ img.thumbnail.image.url }}\" alt=\"{{ img.alt}}\">\n"
] | [
-1
] | [
"bad_request",
"django",
"django_staticfiles",
"python"
] | stackoverflow_0037241902_bad_request_django_django_staticfiles_python.txt |
Q:
join two rows itertively to create new table in spark with one row for each two rows in new table
Have a table where I want to go in range of two rows
id | col b | message
1 | abc | hello |
2 | abc | world |
3 | abc 1| morning|
4 | abc | night |
...|... | .... |
100| abc1 | Monday |
101| abc1 ... | join two rows itertively to create new table in spark with one row for each two rows in new table | Have a table where I want to go in range of two rows
id | col b | message
1 | abc | hello |
2 | abc | world |
3 | abc 1| morning|
4 | abc | night |
...|... | .... |
100| abc1 | Monday |
101| abc1 | Tuesday|
How to I create below table that goes in a range of two and shows the first id with the sec... | [
"With pandas, you can use:\ngroup = np.arange(len(df))//2\n\n(df.astype({'id': 'str'})\n .groupby(group)\n .agg(**{'id_': ('id', ':'.join),\n 'id': ('id', 'first'),\n 'first': ('col b', 'first'),\n 'last': ('message', 'last'),\n })\n .set_index('id')\n .agg(','.join, a... | [
1,
1
] | [] | [] | [
"apache_spark",
"dataframe",
"pyspark",
"python"
] | stackoverflow_0074626112_apache_spark_dataframe_pyspark_python.txt |
Q:
Create .CSV file based on similar key in two data frame
I would like to generate .csv file based on identical columns in ground truth prediction values. I have tried lots of ways but I am able to create single .csv file but unable to create an individual .csv file.
main_predicted.csv: It contains more than 4500 re... | Create .CSV file based on similar key in two data frame | I would like to generate .csv file based on identical columns in ground truth prediction values. I have tried lots of ways but I am able to create single .csv file but unable to create an individual .csv file.
main_predicted.csv: It contains more than 4500 records with image name and prediction result
imgs pred
imag... | [
"read the file and filter with imgs from actual labels\nimg_preds = pd.read_csv('main_predicted.csv')\n\nimages = img_preds['imgs']\n\nactual_labels = pd.read_csv('labels.csv')\n\noutput = img_preds[img_preds['imgs'].isin(actual_labels['imgs'].to_list())]\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"pytorch"
] | stackoverflow_0074636197_dataframe_pandas_python_pytorch.txt |
Q:
change the content of zip object by adding blank line at the end
I am opening a zip file using python like this...
with open('/home/ubuntu/myzip/myzip.zip', 'rb') as zf:
It is working as expected. The contents zf.read() are passed to an API. Is there any way to modify the file without chaging it's content? For e.... | change the content of zip object by adding blank line at the end | I am opening a zip file using python like this...
with open('/home/ubuntu/myzip/myzip.zip', 'rb') as zf:
It is working as expected. The contents zf.read() are passed to an API. Is there any way to modify the file without chaging it's content? For e.g. adding an enter mark at the end.
I need to do this so that the serv... | [
"Opening ZIP Files for Reading and Writing\nimport zipfile\n\n>>> with zipfile.ZipFile(\"sample.zip\", \nmode=\"r\") as archive:\n... archive.printdir()\n...\nFile Name \nModified Size\nhello.txt \n2021-09-07 19:50:10 8... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074637702_python.txt |
Q:
Global variable with Django and Celery
I have a code like this,
wl_data = {}
def set_wl_data():
global wl_data
wl_data = get_watchlist_data()
def get_wl_data(scripcodes):
# Filtering Data
result = {scripcode:detail for scripcode, detail in wl_data.iteritems() if int(scripcode) in scripcodes or sc... | Global variable with Django and Celery | I have a code like this,
wl_data = {}
def set_wl_data():
global wl_data
wl_data = get_watchlist_data()
def get_wl_data(scripcodes):
# Filtering Data
result = {scripcode:detail for scripcode, detail in wl_data.iteritems() if int(scripcode) in scripcodes or scripcode in scripcodes}
return result
I... | [
"If you're doing anything with global variables in a Django project, you're doing it wrong. In this case, Celery and Django are running in completely separate processes, so cannot share data. You need to get Celery to store that data somewhere - in the db, or a file - so that Django can pick it up and serve it.\n",... | [
3,
0
] | [] | [] | [
"celery",
"django",
"django_celery",
"global_variables",
"python"
] | stackoverflow_0018465918_celery_django_django_celery_global_variables_python.txt |
Q:
AWS - NoCredentialsError: Unable to locate credentials
I'm new in AWS also a beginner in python.
I have situation in here,I'm facing this kind of issue:
"The NoCredentialsError is an error encountered when using the Boto3 library to interface with Amazon Web Services (AWS).Specifically, this error is encountered w... | AWS - NoCredentialsError: Unable to locate credentials | I'm new in AWS also a beginner in python.
I have situation in here,I'm facing this kind of issue:
"The NoCredentialsError is an error encountered when using the Boto3 library to interface with Amazon Web Services (AWS).Specifically, this error is encountered when your AWS credentials are missing, invalid, or cannot be ... | [
"The correct path is ~/.aws, not ~/aws. Please double check your setup with aws docs:\n\nin a folder named .aws in your home directory.\n\n"
] | [
2
] | [] | [] | [
"amazon_web_services",
"python"
] | stackoverflow_0074637735_amazon_web_services_python.txt |
Q:
Stuck at CS50's Finance: index() does not show stocks info
Programming noob here having some trouble with Harvard's CS50 Finance problem.
I am really stuck! No matter what I do, I just can't get to see the stocks information at the index.html page ("stock symbol", "shares", "current price", "total shares value"). ... | Stuck at CS50's Finance: index() does not show stocks info | Programming noob here having some trouble with Harvard's CS50 Finance problem.
I am really stuck! No matter what I do, I just can't get to see the stocks information at the index.html page ("stock symbol", "shares", "current price", "total shares value"). My table rows are there, but they are blank:
index.html page wit... | [] | [] | [
"instead of this:\n {% for stock in stocks %}\n <tr>\n <td>{{ stocks[\"symbol\"] }}</td>-\n <td>{{ stocks[\"shares\"] }}</td>\n <td>{{ stocks[\"price\"] }}</td>\n <td>{{ stocks[\"shares_value\"] }}</td>\n </tr>\n {% endfor %}\n\ntry this:\n {% for stock in stocks %}\n <tr... | [
-1
] | [
"flask",
"jinja2",
"python"
] | stackoverflow_0074634546_flask_jinja2_python.txt |
Q:
Having trouble finding the text of google search result
I've been trying to use BeautifulSoup to find the text of each search result on google. Using the developer tools, I can see that this is represented by a <h3> with the class " LC20lb DKV0Md ".
However I cant seem find this using BeautifulSoup. What am I doin... | Having trouble finding the text of google search result | I've been trying to use BeautifulSoup to find the text of each search result on google. Using the developer tools, I can see that this is represented by a <h3> with the class " LC20lb DKV0Md ".
However I cant seem find this using BeautifulSoup. What am I doing wrong?
import requests
from bs4 import BeautifulSoup
res =... | [
"You do not have to search by class, you simply can select all <h3> that includes a <div> and than get_text() of each:\nimport requests\nfrom bs4 import BeautifulSoup\n\nres = requests.get('http://google.com/search?q=world+news')\nsoup = BeautifulSoup(res.content, 'html.parser')\n\n[x.get_text() for x in soup.selec... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0069062701_beautifulsoup_python_web_scraping.txt |
Q:
python for loop parallel processing - appending data to list
I am have below step in my code which is taking around 45 to 50 mins to run (there are other steps which barely take few seconds)
So I am trying to optimize the execution/run time for this step it is essentially a for loop inside a function
def getSwitch... | python for loop parallel processing - appending data to list | I am have below step in my code which is taking around 45 to 50 mins to run (there are other steps which barely take few seconds)
So I am trying to optimize the execution/run time for this step it is essentially a for loop inside a function
def getSwitchStatus(dashboard: meraki.DashboardAPI,switches):
statuses = [... | [
"It's saying that your switchsts() fucntion have not switches in it.\nso try this if it works:\ndef switchsts(switches):\n print(\"Inside switchsts\")\n for dic in switches:\n statuses.append(dashboard.switch.getDeviceSwitchPortsStatuses(dic['serial'],t0=yesterday_midnight)) \n\ndef getSwitchStatus(das... | [
0
] | [] | [] | [
"for_loop",
"parallel_processing",
"python",
"python_3.x"
] | stackoverflow_0074637765_for_loop_parallel_processing_python_python_3.x.txt |
Q:
how can i do "removeEmptyTag:False" in django-ckeditor in settings.py
source
<div class="icon-lg text-white m-b15"><i class="flaticon-fuel-station"></i></div>
output
<div class="icon-lg text-white m-b15"> </div>
django-ckeditor automatic remove tag :{
A:
There is this issue on github, it is actually no... | how can i do "removeEmptyTag:False" in django-ckeditor in settings.py |
source
<div class="icon-lg text-white m-b15"><i class="flaticon-fuel-station"></i></div>
output
<div class="icon-lg text-white m-b15"> </div>
django-ckeditor automatic remove tag :{
| [
"There is this issue on github, it is actually not a bug, it is a feature.\nTo disable this feature add this to your config:\n\n'allowedContent': True, 'extraAllowedContent': '*(*)',\n\nOptional - customizing CKEditor editor\n"
] | [
0
] | [] | [] | [
"django",
"django_ckeditor",
"python"
] | stackoverflow_0074637817_django_django_ckeditor_python.txt |
Q:
Web-scrape. BeautifulSoup. Multiple Pages. How on earth would you do that?
Hi I am a Newbie to programming. So I spent 4 days trying to learn python. I evented some new swear words too.
I was particularly interested in trying as an exercise some web-scraping to learn something new and get some exposure to see how ... | Web-scrape. BeautifulSoup. Multiple Pages. How on earth would you do that? | Hi I am a Newbie to programming. So I spent 4 days trying to learn python. I evented some new swear words too.
I was particularly interested in trying as an exercise some web-scraping to learn something new and get some exposure to see how it all works.
This is what I came up with. See code at end. It works (to a degre... | [
"In this case, to do pagination, instead of for i in range(1, 100) which is a hardcoded way of paging, it's better to use a while loop to dynamically paginate all possible pages.\n\"While\" is an infinite loop and it will be executed until the transition to the next page is possible, in this case it will check for ... | [
0
] | [
"Create the URL by putting the page number in it, then put the rest of your code into a for loop and you can use len(winenames) to count how many results you have. You should do the writing outside the for loop. Here's your code with those changes:\nimport requests\nimport csv\nfrom bs4 import BeautifulSoup\n\nnum_... | [
-1
] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0067665789_beautifulsoup_python_web_scraping.txt |
Q:
Having trouble using the fetchone method in python
This is the error I have tried fixing this plenty and find myself stuck
total = cur.fetchone()[2]
IndexError: tuple index out of range
import sqlite3
def display_records(results):
for row in results:
print(row[0], row[1], row[2])
print()
def... | Having trouble using the fetchone method in python | This is the error I have tried fixing this plenty and find myself stuck
total = cur.fetchone()[2]
IndexError: tuple index out of range
import sqlite3
def display_records(results):
for row in results:
print(row[0], row[1], row[2])
print()
def display_total(total):
for row in total:
p... | [
"The error is telling you that the returned tuple from cur.fetchone() does not have a third element. This is because the SQL statement (for x==4) only asks for a single parameter, namely sum(Population).\nHence the row returned by fetchone() only consists of a tuple with a single element. To get rid of the error, y... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074623539_python.txt |
Q:
If-elif-else statement not working in simple Python 3.3 class?
My code is:
def nameAndConfirm():
global name,confirm
print("What is your name? ")
name = input()
str(name)
print("Is",name,"correct? ")
confirm = input()
str(confirm)
print(confirm)
if confirm.upper() == "Y" or "Y... | If-elif-else statement not working in simple Python 3.3 class? | My code is:
def nameAndConfirm():
global name,confirm
print("What is your name? ")
name = input()
str(name)
print("Is",name,"correct? ")
confirm = input()
str(confirm)
print(confirm)
if confirm.upper() == "Y" or "YES":
classSelection()
elif confirm.upper() == "N" or "NO... | [
"The condition confirm.upper() == \"Y\" or \"YES\" and the other one are not evaluated as you expect. You want \nconfirm.upper() in {\"Y\", \"YES\"}\n\nor\nconfirm.upper() == \"Y\" or confirm.upper() == \"YES\"\n\nYour condition is equivalent to:\n(confirm.upper() == \"Y\") or \"YES\"\n\nwhich is always truthy:\nIn... | [
10
] | [
"That't not the correct way to implement \"or\" in your if condition:\n\nconfirm.upper() == \"Y\" or confirm.upper() == \"YES\"\n\nIt should be like this\n"
] | [
-1
] | [
"if_statement",
"python",
"python_3.x"
] | stackoverflow_0018624465_if_statement_python_python_3.x.txt |
Q:
Loaded keras model with custom layer has different weights to model which was saved
I have implemented a Transformer encoder in keras using the template provided by Francois Chollet here. After I train the model I save it using model.save, but when I load it again for inference I find that the weights seem to be r... | Loaded keras model with custom layer has different weights to model which was saved | I have implemented a Transformer encoder in keras using the template provided by Francois Chollet here. After I train the model I save it using model.save, but when I load it again for inference I find that the weights seem to be random again, and therefore my model loses all inference ability.
I have looked at similar... | [
"The weights are saved (you can load them with load_weights after loading the model). The problem is that you create new layers in __init__. You need to recreate them from their config, for example:\n class TransformerEncoder(layers.Layer):\n def __init__(self, embed_dim, dense_dim, num_heads, attention_confi... | [
1
] | [
"the secrete is how it works you can try it with the model.get_weights() but I sample in the layer.get_weight() that is because easiliy see.\nSample: Custom layer with random initial values, result in small of randoms number changed when run it couple of time.\nimport tensorflow as tf\n\nclass MyDenseLayer(tf.keras... | [
-1
] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074636441_keras_python_tensorflow.txt |
Q:
Unable to read data from mongoDB using Pyspark or Python in AWS EMR
I am trying to read data from 3 node MongoDB cluster(replica set) using PySpark and native python in AWS EMR. I am facing issues while executing the codes with in AWS EMR cluster as explained below but the same codes are working fine in my local w... | Unable to read data from mongoDB using Pyspark or Python in AWS EMR | I am trying to read data from 3 node MongoDB cluster(replica set) using PySpark and native python in AWS EMR. I am facing issues while executing the codes with in AWS EMR cluster as explained below but the same codes are working fine in my local windows machine.
spark version - 2.4.8
Scala version - 2.11.12
MongoDB ver... | [
"there were some issues with AWS account peering between our dev and MongoDB hosted AWS account as explained below\n\nTraffic was flowing through VPC Peering for one of the routes instead of Transit Gateway.\nMongoDB IPs were not falling under CIDR ranges of the Route Table\n\nafter adding transit gateway for Mongo... | [
0
] | [] | [] | [
"amazon_emr",
"mongodb",
"pyspark",
"python"
] | stackoverflow_0073973822_amazon_emr_mongodb_pyspark_python.txt |
Q:
`model.summary()` with TensorFlow model subclassing print output shape as "multiple"
I tried to implement Vgg network with following VggBlock.
class VggBlock(tf.keras.Model):
def __init__(self, filters, repetitions):
super(VggBlock, self).__init__()
self.repetitions = repetitions
self.conv_layers = ... | `model.summary()` with TensorFlow model subclassing print output shape as "multiple" | I tried to implement Vgg network with following VggBlock.
class VggBlock(tf.keras.Model):
def __init__(self, filters, repetitions):
super(VggBlock, self).__init__()
self.repetitions = repetitions
self.conv_layers = [Conv2D(filters=filters, kernel_size=(3, 3), padding='same', activation='relu') for _ in r... | [
"You already linked some workarounds. You seem to be landing here, because the output shape of each layer cannot be determined. As stated here:\n\nYou can do all these things (printing input / output shapes) in a\nFunctional or Sequential model because these models are static graphs\nof layers.\nIn contrast, a subc... | [
0
] | [] | [] | [
"keras",
"model",
"python",
"subclass",
"tensorflow"
] | stackoverflow_0074636279_keras_model_python_subclass_tensorflow.txt |
Q:
how to find substrintstring between two words in regex of python
I have this kind of string in python programme
Quantity: 1
Return reason: Style not as expected
Customer comments: Colour is too deeo
Return Shipping Carrier: courier
I want to get the string between customer comment and return shipping carrier wi... | how to find substrintstring between two words in regex of python | I have this kind of string in python programme
Quantity: 1
Return reason: Style not as expected
Customer comments: Colour is too deeo
Return Shipping Carrier: courier
I want to get the string between customer comment and return shipping carrier with regex so, how to find this substring
| [
"If you would like to search over multiline string, use the following re flags:\nre.findall('Customer comments: (.*)Return Shipping Carrier', s, re.MULTILINE|re.DOTALL)\n\n"
] | [
1
] | [] | [] | [
"python",
"substr"
] | stackoverflow_0074637535_python_substr.txt |
Q:
Unexpected behavior in a nested while loop
I'm trying to better understand how Python flow control works. Accordingly, I wrote a little script to understand how to make functional menus that include the ability to enter and leave sub-menus. The code below works as expected (no errors, it prints the expected outp... | Unexpected behavior in a nested while loop | I'm trying to better understand how Python flow control works. Accordingly, I wrote a little script to understand how to make functional menus that include the ability to enter and leave sub-menus. The code below works as expected (no errors, it prints the expected output, etc). But when I enter option 4 "Exit" in th... | [
"Your code is quite messy:\n\nYou don't require to create variables for while. You can use True and break\nLooks like you're repeating code a lot of times, we'll fix that later on\n\nHere's the fixed code:\nimport time\nimport os\n\ndef stage1():\n print(\"stage1\")\n time.sleep(1)\n while True:\n #... | [
0,
0
] | [] | [] | [
"loops",
"nested",
"python",
"python_3.x",
"while_loop"
] | stackoverflow_0074637867_loops_nested_python_python_3.x_while_loop.txt |
Q:
AttributeError: module 'lib' has no attribute 'EVP_MD_CTX_new'
I'm attempting to use the Python package googleapiclient to download analytics, but it's giving me an OpenSSL related traceback:
File "/project/.env/lib/python3.7/site-packages/googleanalytics/auth/__init__.py", line 95, in authenticate
accounts ... | AttributeError: module 'lib' has no attribute 'EVP_MD_CTX_new' | I'm attempting to use the Python package googleapiclient to download analytics, but it's giving me an OpenSSL related traceback:
File "/project/.env/lib/python3.7/site-packages/googleanalytics/auth/__init__.py", line 95, in authenticate
accounts = oauth.authenticate(credentials)
File "/project/.env/lib/python3.... | [
"It is happening due to dependency mismatch between pyopenssl and cyrptography.\nI managed to solve this issue by downgrading cryptography library using following command.\n\npip install cryptography==36.0.0\n\n"
] | [
0
] | [] | [] | [
"google_api_client",
"pyopenssl",
"python"
] | stackoverflow_0071191038_google_api_client_pyopenssl_python.txt |
Q:
Unable to locate the element on an angular website
I have tried the below code and it is always timing out. But when I look it up with the browser inspector, I can see the Username input element.
I have also tried to find it by ID but not able to.
Tried almost all of the existing questions/solutions on this forum ... | Unable to locate the element on an angular website | I have tried the below code and it is always timing out. But when I look it up with the browser inspector, I can see the Username input element.
I have also tried to find it by ID but not able to.
Tried almost all of the existing questions/solutions on this forum but was unable to figure it out.
driver.get("htt... | [
"2 issues here:\n\nAfter clicking on \"DAT Power\" on the first page a new tab is opened. To continue working there you need to switch the driver to the second tab.\nYou will probably want to enter a text into the username there. If so you need to wait for element clickability, not presence only.\nAlso, the current... | [
0
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"selenium_webdriver",
"webdriverwait"
] | stackoverflow_0074636236_python_python_3.x_selenium_selenium_webdriver_webdriverwait.txt |
Q:
Drawing text on images in pillow
i was trying to solve a problem i had in a code that should draw text from a text file on a picture. the problem i had is that the program stack all the text on each other in every picture after the first picture(2,3,4,5). i can't explain what's the problem so i'll just leave a pho... | Drawing text on images in pillow | i was trying to solve a problem i had in a code that should draw text from a text file on a picture. the problem i had is that the program stack all the text on each other in every picture after the first picture(2,3,4,5). i can't explain what's the problem so i'll just leave a photo (https://i.stack.imgur.com/nkY2O.pn... | [
"Here's a pretty reasonable, but none too complicated method:\n#!/usr/bin/env python3\n\nfrom PIL import Image, ImageDraw, ImageFont\n\n# Generate annotations file with 3 lines\nannotations = 'annotations.txt'\nwith open(annotations, 'w') as f:\n f.write(\"Merry\\nChristmas\\nStackOverflow\")\n\n# Open backgroun... | [
0,
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0074597779_python_python_imaging_library.txt |
Q:
Pytorch's share_memory_() vs built-in Python's shared_memory: Why in Pytorch we don't need to access the shared memory-block?
Trying to learn about the built-in multiprocessing and Pytorch's multiprocessing packages, I have observed a different behavior between both. I find this to be strange since Pytorch's packa... | Pytorch's share_memory_() vs built-in Python's shared_memory: Why in Pytorch we don't need to access the shared memory-block? | Trying to learn about the built-in multiprocessing and Pytorch's multiprocessing packages, I have observed a different behavior between both. I find this to be strange since Pytorch's package is fully-compatible with the built-in package.
Concretely, I'm refering to the way variables are shared between processes. In Py... | [
"You are writing a love letter to the pytorch authors.\nThat is, you are patting them on the back,\ncongratulating their wrapper efforts as \"a job well done!\"\nIt's a lovely library.\nLet's take a step back and use a very simple\ndata structure, a dictionary d.\nIf parent initializes d with some values,\nand then... | [
2,
1
] | [] | [] | [
"multiprocessing",
"python",
"pytorch",
"shared_memory"
] | stackoverflow_0074635994_multiprocessing_python_pytorch_shared_memory.txt |
Q:
How can I generate pseudo random sequence of binary number using Hopefield neural network?
For some work, I need to generate a sequence of random binary patterns using the Hopefield neural network.
Like I want to generate a 42-bit long binary sequence such as '11101100011100111001100011001110001010001' How can I ... | How can I generate pseudo random sequence of binary number using Hopefield neural network? | For some work, I need to generate a sequence of random binary patterns using the Hopefield neural network.
Like I want to generate a 42-bit long binary sequence such as '11101100011100111001100011001110001010001' How can I generate it?
I have tried several ways but no proper solution is coming out.
| [
"Use numpy to pick a random int.\nHere we specifiy dtype to address up to 64 bits, and a maximum value of 2^42.\nUse f-string to print the binary representation and pad with leading 0 if needed.\nimport numpy as np\n\nn = np.random.randint(2**42, dtype=np.int64)\nprint(f\"{n:042b}\")\n\n"
] | [
1
] | [] | [] | [
"binary",
"python",
"random"
] | stackoverflow_0074637615_binary_python_random.txt |
Q:
I need to join every two string in the list
input list = ["Raman","Panjikar","Rohan","singh","roshan","kumar"]
output list = ["Raman Panjikar","Rohan singh","roshan kumar"]
Tried concat but it did not work.
A:
input_list = ["Raman","Panjikar","Rohan","singh","roshan","kumar"]
output_list=[]
if len(input_list)%2=... | I need to join every two string in the list | input list = ["Raman","Panjikar","Rohan","singh","roshan","kumar"]
output list = ["Raman Panjikar","Rohan singh","roshan kumar"]
Tried concat but it did not work.
| [
"input_list = [\"Raman\",\"Panjikar\",\"Rohan\",\"singh\",\"roshan\",\"kumar\"]\noutput_list=[]\nif len(input_list)%2==0:\n l=len(input_list)\nelse:\n l=len(input_list)-1\nfor i in range(0,l,2):\n x=f'{input_list[i]} {input_list[i+1]}'\n output_list.append(x)\nprint(output_list)\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074637476_python.txt |
Q:
How can i add subject to my python email program in ssl?
I want to add subject to my python email program how can i do that? i dont want to use any python libraries i just want to do that with ssl, Can anyone can give me code example so that i can just copy paste? i looked 4 stack over flow solutions too but i don... | How can i add subject to my python email program in ssl? | I want to add subject to my python email program how can i do that? i dont want to use any python libraries i just want to do that with ssl, Can anyone can give me code example so that i can just copy paste? i looked 4 stack over flow solutions too but i dont understand how to do that in my program the reason was i am ... | [
"You can make the subject as a header of the body text.\nTry this :\nimport smtplib, ssl\n\nemail = \"myemail@gmail.com\"\npassword = \"mypassword\"\n\nsubject= \"Put here your subject\"\nbody = \"\"\"\\\nHello World\n\"\"\"\nmessage = 'Subject: {}\\n\\n{}'.format(subject, body)\n\nreceiver = \"reciveremail@gmail.c... | [
0
] | [] | [] | [
"python",
"python_3.x",
"ssl"
] | stackoverflow_0074638146_python_python_3.x_ssl.txt |
Q:
Python: website's class prints out an empty list
I'm trying to scrape everything in the class stats (item price and price changes) with the following script:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
url = "https://secure.runescape.com/m=itemdb_oldschool/Dragon+warhammer/vie... | Python: website's class prints out an empty list | I'm trying to scrape everything in the class stats (item price and price changes) with the following script:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
url = "https://secure.runescape.com/m=itemdb_oldschool/Dragon+warhammer/viewitem?obj=13576"
uClient = uReq(url)
page_html = uCl... | [
"check the value of page_soup variable:\n<html style=\"height:100%\"><head><META NAME=\"ROBOTS\" CONTENT=\"NOINDEX, NOFOLLOW\"><meta name=\"format-detection\" content=\"telephone=no\"><meta name=\"viewport\" content=\"initial-scale=1.0\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\"><script type... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0067440401_beautifulsoup_python_web_scraping.txt |
Q:
Issues viewing or sharing items upload to Sharepoint with msgraph in Python
I've been trying to upload files to a Sharepoint site using a python app.
I've successfully authenticated with my Azure app, using msgraph.
I've successfully (I think) uploaded files -
/drives/{drive_id}/root:/path/to/file:/content
return... | Issues viewing or sharing items upload to Sharepoint with msgraph in Python | I've been trying to upload files to a Sharepoint site using a python app.
I've successfully authenticated with my Azure app, using msgraph.
I've successfully (I think) uploaded files -
/drives/{drive_id}/root:/path/to/file:/content
returns
@microsoft.graph.downloadUrl: https://xxx.sharepoint.com/_layouts/15/download.a... | [
"It looks like you're having trouble viewing the files you've uploaded to your SharePoint site. There are a few potential causes for this issue, so I'll try to provide some suggestions that may help you resolve it.\nFirst, make sure that you're using the correct URL to view the files. The property in the response ... | [
0
] | [] | [] | [
"file_upload",
"msgraph",
"python",
"share",
"sharepoint"
] | stackoverflow_0074570308_file_upload_msgraph_python_share_sharepoint.txt |
Q:
How to fill empty cells and any cell which contains only spaces with Null in Spark DataFrame?
I have a dataset which has empty cells, and also cells which contain only spaces (one or more). I want to convert all these cells into Null.
Sample dataset:
data = [("", "CA", " "), ("Julia", "", None),("Robert", " ", No... | How to fill empty cells and any cell which contains only spaces with Null in Spark DataFrame? | I have a dataset which has empty cells, and also cells which contain only spaces (one or more). I want to convert all these cells into Null.
Sample dataset:
data = [("", "CA", " "), ("Julia", "", None),("Robert", " ", None), ("Tom", "NJ", " ")]
df = spark.createDataFrame(data,["name", "state", "code"])
df.show()
... | [
"you could use trim to remove the spaces which leaves a blank and then check for blanks in all cells.\nsee example below\ndata_sdf. \\\n selectExpr(*['if(trim({0}) = \"\", null, {0}) as {0}'.format(c) for c in data_sdf.columns]). \\\n show()\n\n# +------+-----+----+\n# | name|state|code|\n# +------+-----+---... | [
1,
1
] | [] | [] | [
"dataframe",
"null",
"pyspark",
"python"
] | stackoverflow_0074638211_dataframe_null_pyspark_python.txt |
Q:
Find position of object by Key in json file
Is there anyway i can find the position of object by its key in Json file. I tried with the collection module but seems not to work with data from the json file even though its dictionary
reda.json file
[{"carl": "33"}, {"break": "55"}, {"user": "heake"}, ]
import json... | Find position of object by Key in json file | Is there anyway i can find the position of object by its key in Json file. I tried with the collection module but seems not to work with data from the json file even though its dictionary
reda.json file
[{"carl": "33"}, {"break": "55"}, {"user": "heake"}, ]
import json
import collections
json_data = json.load(open('... | [
"You can use enumerate to generate indices for a sequence:\njson_data = [{\"carl\": \"33\"}, {\"break\": \"55\"}, {\"user\": \"heake\"}]\nkey = 'break'\nfor index, record in enumerate(json_data):\n if key in record:\n print(index)\n\nThis outputs: 1\n",
"You don't require collections for this. Simply us... | [
3,
0
] | [] | [] | [
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0074638267_dictionary_python_python_3.x.txt |
Q:
it throws a 404 when without url prefix (FLASK)
You see Im having a problem where in flask, I made a web app. and I added the URL prefix as views
and you see without /views attached to localhost it throws a 404, I wanna change it so it will redirect automatically to /views when you go to the regular URL such as ht... | it throws a 404 when without url prefix (FLASK) | You see Im having a problem where in flask, I made a web app. and I added the URL prefix as views
and you see without /views attached to localhost it throws a 404, I wanna change it so it will redirect automatically to /views when you go to the regular URL such as http://127.0.0.1:8000/
I tried adding @app.route in app... | [
"You could redirect automatically from http://127.0.0.1:8000/ to http://127.0.0.1:8000/views using the code below.\nfrom flask import Flask, jsonify, redirect\n\napp = Flask(__name__)\n\n#Page 1\n@app.route('/', methods=['GET'])\ndef welcome():\n return redirect(\"http://127.0.0.1:8000/views\", code=302)\n\n#Pag... | [
0
] | [] | [] | [
"flask",
"python",
"python_3.x",
"url",
"web"
] | stackoverflow_0074638293_flask_python_python_3.x_url_web.txt |
Q:
Visualizing Image Augmentations Using Keras Image Data Generator - Input data in `NumpyArrayIterator` should have rank 4
I've built a CNN model and used pickled German traffic sign images to train it. I've experimented with applying data augmentations to the images and I'm having trouble displaying these images us... | Visualizing Image Augmentations Using Keras Image Data Generator - Input data in `NumpyArrayIterator` should have rank 4 | I've built a CNN model and used pickled German traffic sign images to train it. I've experimented with applying data augmentations to the images and I'm having trouble displaying these images using matplotlib and the Keras Image Data Generator.
I've imported the necessary libraries for the processes and below is where ... | [
"Expand the dimensions of the array in axis-0\ndatagen.flow(np.expand_dims(X_train_gray[i], 0), batch_size = 1)\n\n#<keras.preprocessing.image.NumpyArrayIterator at 0x23b5ff0f5b0>\n\n"
] | [
0
] | [] | [] | [
"imagedatagenerator",
"keras",
"matplotlib",
"python",
"tensorflow"
] | stackoverflow_0074634887_imagedatagenerator_keras_matplotlib_python_tensorflow.txt |
Q:
Django search bar isn't giving correct results
views.py
from django.shortcuts import render
from ecommerceapp.models import Product
from django.db.models import Q
def searchResult(request):
products=None
query=None
if 'q' in request.GET:
query = request.GET.get('q')
products=Product.ob... | Django search bar isn't giving correct results | views.py
from django.shortcuts import render
from ecommerceapp.models import Product
from django.db.models import Q
def searchResult(request):
products=None
query=None
if 'q' in request.GET:
query = request.GET.get('q')
products=Product.objects.all().filter(Q(name__contains=query) | Q(desc_... | [
"\nExample: When I type x in the search bar, it give me the results 'shirt' instead of giving '0 results found'.\n\nThe __contains is used to check whether the field contains given word or not, it is case-sensitive. And using | in Q objects means it is optional and works as OR condition, so maybe it is possible whe... | [
1
] | [] | [] | [
"django",
"python",
"searchbar"
] | stackoverflow_0074638132_django_python_searchbar.txt |
Q:
How can I get the coordinate information of model.visualize_topics() function - BERTopic
I am trying to get the coordinate informations of the docs placed on the graph by model.visualize_topics() for my BERTopic topic analysis project. Is there any way to see the source code of the function and save the coordinate... | How can I get the coordinate information of model.visualize_topics() function - BERTopic | I am trying to get the coordinate informations of the docs placed on the graph by model.visualize_topics() for my BERTopic topic analysis project. Is there any way to see the source code of the function and save the coordinates to use for more advanced analysis?
I found following code as the source code of the visualiz... | [
"In order to allow for modularity in BERTopic the plotting was separated of the main functions. You can find all information about plotting in BERTopic here and, more specifically, you can find the code for plotting.visualize_topics here.\nHaving said that, part of that function is creating the coordinate system as... | [
0
] | [] | [] | [
"bert_language_model",
"python",
"topic_modeling"
] | stackoverflow_0074566683_bert_language_model_python_topic_modeling.txt |
Q:
Delete a file in a directory except for first file (or specific file) in Python
I want to delete all files in a directory except for one file in python.
I used os.remove and os.system(with rm and fine), but all of them return errors.
Lets say I have a folder X and in there I have files named 1 2 3 4.
alongside fol... | Delete a file in a directory except for first file (or specific file) in Python | I want to delete all files in a directory except for one file in python.
I used os.remove and os.system(with rm and fine), but all of them return errors.
Lets say I have a folder X and in there I have files named 1 2 3 4.
alongside folder X, I have main.py. in main.py how can I write a command to go to the folder and d... | [
"You can do this in Python using various functions from the os module rather than relying on find.\nfrom os import chdir, listdir, remove, getcwd\n\ndef delete_from(directory: str, keep: list) -> None:\n cwd = getcwd()\n try:\n chdir(directory)\n for file in listdir():\n if not file i... | [
1
] | [] | [] | [
"delete_file",
"find",
"os.system",
"python",
"rm"
] | stackoverflow_0074638353_delete_file_find_os.system_python_rm.txt |
Q:
Check column names and column types in Great Expectations
Currently, I am validating the table schema with expect_table_columns_to_match_set by feeding in a list of columns. However, I want to validate the schema associated with each column such as string. The only available Great Expectations rule expect_column_v... | Check column names and column types in Great Expectations | Currently, I am validating the table schema with expect_table_columns_to_match_set by feeding in a list of columns. However, I want to validate the schema associated with each column such as string. The only available Great Expectations rule expect_column_values_to_be_of_type has to be written for each column name and ... | [
"Great Expectations does not have a built-in rule that allows you to validate both the names and the schema of columns in a table at the same time。 However, you can use a combination of the and rules to achieve the same\nFirst, you can use the rule to validate the names of the columns in the table。 This rule takes ... | [
0
] | [] | [] | [
"great_expectations",
"python"
] | stackoverflow_0074483457_great_expectations_python.txt |
Q:
"ProgrammingError: column users_appuser.id does not exist" extending User model django
I am extending User on django and didn't realize I need to add phone number. When I made the model below, I forgot to makemigrations migrate before creating an AppUser. So I had made an AppUser/User combo as normal, but before t... | "ProgrammingError: column users_appuser.id does not exist" extending User model django | I am extending User on django and didn't realize I need to add phone number. When I made the model below, I forgot to makemigrations migrate before creating an AppUser. So I had made an AppUser/User combo as normal, but before the db was ready. It asks me to provide a default and I provided the string '1' because it wo... | [
"This is happening because you are migrating both your apps and admin models at the same time.\nTo fix this,\n\nDelete Database,\nDelete migrations,\nMigrate admin models first before applying makemigrations\nDo make migrations and migrate.\n\n"
] | [
0
] | [] | [] | [
"django",
"django_1.10",
"django_contrib",
"python",
"python_3.x"
] | stackoverflow_0039951088_django_django_1.10_django_contrib_python_python_3.x.txt |
Q:
How to use 3 or more telegram clients at the same time?
i want to use 3 or more telegram clients at the same time, with 1 or/and 2 clients i don't have problems, but with 3 clients i get errors.
client2 = TelegramClient('session1', api_id2, api_hash2)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^... | How to use 3 or more telegram clients at the same time? | i want to use 3 or more telegram clients at the same time, with 1 or/and 2 clients i don't have problems, but with 3 clients i get errors.
client2 = TelegramClient('session1', api_id2, api_hash2)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\telethon\client\tele... | [
"Change each client to use different session names, and properly start them (right now, you're only starting client repeatedly)\nclient = TelegramClient('session', api_id, api_hash)\nclient.start()\nclient1 = TelegramClient('session1', api_id1, api_hash1)\nclient1.start()\nclient2 = TelegramClient('session2', api_i... | [
0
] | [] | [] | [
"multiple_instances",
"python",
"telegram",
"telethon"
] | stackoverflow_0074634227_multiple_instances_python_telegram_telethon.txt |
Q:
Vscode seems to be changing directory when running a python script
I seem to be having a vscode related issue. I am doing the open() function but no matter what I ask it to do it gives me a directory error. The file that I want the python script to interact with is in the same folder so it should work but when I d... | Vscode seems to be changing directory when running a python script | I seem to be having a vscode related issue. I am doing the open() function but no matter what I ask it to do it gives me a directory error. The file that I want the python script to interact with is in the same folder so it should work but when I do "import os" and "os.getcwd()" the directory it says I am in is Desktop... | [
"This is caused by vscode using workspace as root floder.\nThis will lead to a problem. When you use the os.getcwd() method in the deep directory of the workspace, you will still get the workspace directory.\nYou can open your settings and search Python > Terminal: Execute In File Dir then check it.\n\nYou can also... | [
1
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074637571_python_visual_studio_code.txt |
Q:
Python function not executing in azure automation runbook
I am working on writing a function in python azure automation runbook, where the basic gist of what I'm trying to accomplish is shown in the code below. But, I'm perplexed as when I take the code out of the function and run the code as is it all works as ex... | Python function not executing in azure automation runbook |
I am working on writing a function in python azure automation runbook, where the basic gist of what I'm trying to accomplish is shown in the code below. But, I'm perplexed as when I take the code out of the function and run the code as is it all works as expected. But, when the function is used I see the output for St... | [
"Your code worked successfully and achieved the expected outcomes when I tried it in my environment, as shown below:\nFirst and foremost, you should add the requests(3.8) module/package to the Azure Automation runbook as you are using it in code.\nAdd a package:\nPath:\nAzure automation account -> Python packages -... | [
1
] | [] | [] | [
"azure",
"azure_automation",
"python"
] | stackoverflow_0074634586_azure_azure_automation_python.txt |
Q:
Can someone explain to my why my django admin theme is dark?
I host my small project on pythonanywhere and after i host it i check if it is working and when i click the django admin, the theme of my django admin is dark and when i tried to run on my local host the theme is white so i tried to double check my stati... | Can someone explain to my why my django admin theme is dark? | I host my small project on pythonanywhere and after i host it i check if it is working and when i click the django admin, the theme of my django admin is dark and when i tried to run on my local host the theme is white so i tried to double check my static url and i think it is fine and btw this is my static url for my ... | [
"As part of the Django 3.2 release, the admin now has a dark theme that is applied based on a prefers-color-scheme media query. Release Notes\n\nThe admin now supports theming, and includes a dark theme that is enabled according to browser settings. See Theming support for more details.\n\n",
"From django 3.2 we ... | [
14,
8,
6,
2,
1
] | [] | [] | [
"django",
"python",
"pythonanywhere"
] | stackoverflow_0067135053_django_python_pythonanywhere.txt |
Q:
How to run Xvfb with xvfbwrapper on AWS EC2 to records screen of selenium headless session
I have a problem running selenium sesion with Xvfb to record video file with sesion. Below is my session and wrapper
from selenium import webdriver
from xvfbwrapper import Xvfb
class TestPages(unittest.TestCase):
def s... | How to run Xvfb with xvfbwrapper on AWS EC2 to records screen of selenium headless session | I have a problem running selenium sesion with Xvfb to record video file with sesion. Below is my session and wrapper
from selenium import webdriver
from xvfbwrapper import Xvfb
class TestPages(unittest.TestCase):
def setUp(self):
self.xvfb = Xvfb(width=1280, height=720)
self.addCleanup(self.xvfb.s... | [
"After very long research of multiple way to run this on AWS came to few concussions:\n\nRunning on AWS Linux is way too complicated, definitely recommend AWS Ubuntu EC2 for this. This is due to lack of information and some libraries not compatible (scrot, issues with DISPLAY).\nThe problem at some point is FFMPEG ... | [
0
] | [] | [] | [
"amazon_ec2",
"python",
"selenium",
"xvfb"
] | stackoverflow_0074574411_amazon_ec2_python_selenium_xvfb.txt |
Q:
Is there a way to plot a line that is a consistent length using matplotlib/cartopy?
I am using matplotlib and cartopy to draw lines overlaid on maps in python. As of right now, I am just identifying the lat/lon of two points and plotting a line between them. Since I am taking cross sections across these lines, I w... | Is there a way to plot a line that is a consistent length using matplotlib/cartopy? | I am using matplotlib and cartopy to draw lines overlaid on maps in python. As of right now, I am just identifying the lat/lon of two points and plotting a line between them. Since I am taking cross sections across these lines, I would like to find a way to make the line the same length (say 300km long) no matter where... | [
"The Geod class from pyproj is very convenient for these types of operations. The example below moves in a line from a given lat/lon based on an azimuth and distance (in meters).\nSince you mention starting with a mid-point, you can do this twice for each direction to get the full line.\nIn the example below, I jus... | [
1,
0
] | [] | [] | [
"cartopy",
"line",
"matplotlib",
"python"
] | stackoverflow_0074636590_cartopy_line_matplotlib_python.txt |
Q:
how to make 1111 into 1 in python
i want to make function to make from 1111 into 1 and 0000 into 0.
for the example:
Input:
['1111', '1111', '0000', '1111', '1111', '0000', '1111', '0000', '0000', '1111', '0000', '0000', '0000', '0000', '0000', '0000', '0000', '1111', '0000', '0000', '1111', '1111', '0000', '0000'... | how to make 1111 into 1 in python | i want to make function to make from 1111 into 1 and 0000 into 0.
for the example:
Input:
['1111', '1111', '0000', '1111', '1111', '0000', '1111', '0000', '0000', '1111', '0000', '0000', '0000', '0000', '0000', '0000', '0000', '1111', '0000', '0000', '1111', '1111', '0000', '0000', '0000', '0000', '1111', '0000', '1111... | [
"You can easily use list comprehension and the join() method:\nlst = ['1111', '1111', '0000', '1111', '1111', '0000', '1111', '0000', '0000', '1111', '0000', '0000', '0000', '0000', '0000', '0000', '0000', '1111', '0000', '0000', '1111', '1111', '0000', '0000', '0000', '0000', '1111', '0000', '1111', '1111', '0000'... | [
2,
1,
0,
0
] | [] | [] | [
"algorithm",
"binary",
"python",
"scalar"
] | stackoverflow_0074637992_algorithm_binary_python_scalar.txt |
Q:
Tkinter Enter widget is not taking input into floating number
I'm using an API to convert one unit to another. I'm trying to get input from user by "Entry Widget" as floating number. This is my code.
import requests
import tkinter as tk
root = tk.Tk()
def pressMe():
out_entry.insert(1, f'{result}')
in_en... | Tkinter Enter widget is not taking input into floating number | I'm using an API to convert one unit to another. I'm trying to get input from user by "Entry Widget" as floating number. This is my code.
import requests
import tkinter as tk
root = tk.Tk()
def pressMe():
out_entry.insert(1, f'{result}')
in_entry = tk.Entry(root)
in_entry.pack()
out_entry = tk.Entry(root)
ou... | [
"it is as jasonharper said: \"You are calling .get() on your Entry a millisecond or so after it was created - it's not physically possible for the user to have typed in anything yet!\"\nwhat you can do:\nimport requests\nimport tkinter as tk\nroot = tk.Tk()\n\nin_entry = tk.Entry(root)\nin_entry.pack()\n\nout_entry... | [
0
] | [] | [] | [
"api",
"python",
"tkinter",
"tkinter_entry"
] | stackoverflow_0074564400_api_python_tkinter_tkinter_entry.txt |
Q:
Syntax for interpolating planes (Python)
I have a function D(x,y,z) in which I want to evaluate (via interpolation) planes within the z, y, and z axis. i.e. I want the output of my interpolations to be a 2D plane holding one of the values fixed, D(x,y,0) for example.
I have created an interpolating function via sc... | Syntax for interpolating planes (Python) | I have a function D(x,y,z) in which I want to evaluate (via interpolation) planes within the z, y, and z axis. i.e. I want the output of my interpolations to be a 2D plane holding one of the values fixed, D(x,y,0) for example.
I have created an interpolating function via scipy using some given values of D, D_values, fo... | [
"The typical approach to combining multiple arrays with different sizes corresponding to different dimensions in numpy and scipy is to use broadcasting. Here is a sample problem to illustrate the application:\nx_positions = np.linspace(0, 10, 101)\ny_positions = np.linspace(-10, 10, 201)\nz_positions = np.linspace(... | [
1,
1,
0
] | [] | [] | [
"interpolation",
"plane",
"python",
"scipy"
] | stackoverflow_0074574442_interpolation_plane_python_scipy.txt |
Q:
How to get ax plot id for matplotlib RectangleSelector callback?
I have multiple ax plot with RectangleSelector and its callback as below.
from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
def select_callback(eclick, erelease):
x1, y1 = eclick.xdata, eclick.yd... | How to get ax plot id for matplotlib RectangleSelector callback? | I have multiple ax plot with RectangleSelector and its callback as below.
from matplotlib.widgets import RectangleSelector
import numpy as np
import matplotlib.pyplot as plt
def select_callback(eclick, erelease):
x1, y1 = eclick.xdata, eclick.ydata
x2, y2 = erelease.xdata, erelease.ydata
fig = plt.figure(cons... | [
"You can use a partial:\nfrom matplotlib.widgets import RectangleSelector\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom functools import partial\n\ndef select_callback(eclick, erelease, idx):\n x1, y1 = eclick.xdata, eclick.ydata\n x2, y2 = erelease.xdata, erelease.ydata\n print(idx)\n\nfig = ... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074635825_matplotlib_python.txt |
Q:
Keyword argument (kwargs) function error in Python
Following is the code:
def my_funct(**kwarg):
print(kwarg[fn]*kwarg[sn])
print('enter 2 numbers to get product of')
a=input()
print('enter second number')
b=input()
my_funct(fn=a,sn=b)
The output is error saying 'fn is not defined'. What is the solution?
A:
... | Keyword argument (kwargs) function error in Python | Following is the code:
def my_funct(**kwarg):
print(kwarg[fn]*kwarg[sn])
print('enter 2 numbers to get product of')
a=input()
print('enter second number')
b=input()
my_funct(fn=a,sn=b)
The output is error saying 'fn is not defined'. What is the solution?
| [
"Kwargs is a dictionary where the variable name is the key and has type str. You are trying to find the value to the key which is saved in the variable fn but this variable hasn't been defined. Instead what you want is the value corresponding to the key 'fn', so you do\nprint(kwarg['fn'] * kwarg['sn'])\n\nEdit: Bec... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074638569_python.txt |
Q:
Exception has occurred: ModuleNotFoundError No module named 'src'
I am facing this problem while my "from src.simulation.simulator import Simulator" is in the same directory. what should i do now to resolve this problem?
I have tried to solve this problem but did not understand what to do!!
A:
Since you haven't ... | Exception has occurred: ModuleNotFoundError No module named 'src' | I am facing this problem while my "from src.simulation.simulator import Simulator" is in the same directory. what should i do now to resolve this problem?
I have tried to solve this problem but did not understand what to do!!
| [
"Since you haven't updated for a long time, I have made a guess.\nThis maybe caused by vscode using workspace as root floder.\nThis will lead to a problem. When you use the os.getcwd() method in the deep directory of the workspace, you will still get the workspace directory.\nYou can open your settings and search P... | [
0
] | [] | [] | [
"module_export",
"python",
"visual_studio_code"
] | stackoverflow_0074384770_module_export_python_visual_studio_code.txt |
Q:
Raspberry Pi 4B, running Python Script using serial at boot
I'm currently using crontab on a Raspberry Pi 4 Model B to launch my python script at boot.
I've added this at the bottom of sudo crontab -e :
@reboot sh /home/pi/start.sh > /home/pi/logs/cronlog 2>&1 &
My start.sh script is like that :
#!/bin/sh
# start... | Raspberry Pi 4B, running Python Script using serial at boot | I'm currently using crontab on a Raspberry Pi 4 Model B to launch my python script at boot.
I've added this at the bottom of sudo crontab -e :
@reboot sh /home/pi/start.sh > /home/pi/logs/cronlog 2>&1 &
My start.sh script is like that :
#!/bin/sh
# start.sh
cd /home/pi/Desktop/Python_Scripts/Projet
sudo python3 main.... | [
"Most likely cron is executing before the serial interface is initialized and causing your python script to raise an exception.\nThis can be verified by adding a relatively small delay (ie: 30 seconds) into your python script to see if it then functions properly.\nIf the script only needs to be run once, a simple f... | [
0,
0
] | [
"I also use Raspberry pi4.\nI reccomend you use crontab -e without sudo. \nMy crontab -e like this: \n@reboot bash /usr/bin/start_counter.sh\nMy /usr/bin/start_counter.sh:\n#!/usr/bin/bash\nwhile true\ndo\n python3 /home/pi/people_counter_android/main.py\ndone\n\nIn my way its work. I hope this help you.\n"
] | [
-1
] | [
"cron",
"python",
"python_3.x",
"raspberry_pi",
"raspberry_pi4"
] | stackoverflow_0067487273_cron_python_python_3.x_raspberry_pi_raspberry_pi4.txt |
Q:
using break function within the function to stop the further execution of program
def my_function(df_1) :
df_1 = df_1.filter[['col_1','col_2','col_3']]
# Keeping only those records where col_1 == 'success'
df_1 = df_1[df_1['col_1'] == 'success']
# C... | using break function within the function to stop the further execution of program | def my_function(df_1) :
df_1 = df_1.filter[['col_1','col_2','col_3']]
# Keeping only those records where col_1 == 'success'
df_1 = df_1[df_1['col_1'] == 'success']
# Checking if the df_1 shape is 0
if df_1.shape[0]==0:
print('No rec... | [
"You need to use\n if df_1.shape[0]==0:\n print('No records found')\n return \n\n",
"Just for further clarification, the answers above are correct, but the break statement is an used in loops like a for loop or while loop to end the loop prematurely.\nFunctions on the other hand end either at the ... | [
3,
1,
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074638627_dataframe_python.txt |
Q:
Fill matrix with For Loop
I am trying to fill a matrix with a for loop in Python, this may be an math problem more than anything else, or I just need to find a new solution. I need to write this loop (just an example but the same concept):
matrix = np.zeros((1,8))
for i, j in zip(range(2,6), range(1,5)):
matri... | Fill matrix with For Loop | I am trying to fill a matrix with a for loop in Python, this may be an math problem more than anything else, or I just need to find a new solution. I need to write this loop (just an example but the same concept):
matrix = np.zeros((1,8))
for i, j in zip(range(2,6), range(1,5)):
matrix[0,0*i:2*i] = [i*2, j*2]
The ... | [
"I have managed to solve this myself now, maybe not the most elegant solution, but it works. So instead of using the range(2,6) and range(1,5) to assign the values to the right place in the matrix, I added another variable range(4) which I call p.\nmatrix = np.zeros((1,8))\nfor i, j, p in zip(range(2,6), range(1,5)... | [
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074638447_for_loop_python.txt |
Q:
Office365-REST-Python-Client - How to read more than 100 rows from a Sharepoint (MS-List)
I'm using the following Python (v3.8.10) code with the latest version of the Office365-REST-Python-Client to access an MS-List on my Sharepoint site:
sp_lists = ctx.web.lists
s_list = sp_lists.get_by_title(staff_list)... | Office365-REST-Python-Client - How to read more than 100 rows from a Sharepoint (MS-List) | I'm using the following Python (v3.8.10) code with the latest version of the Office365-REST-Python-Client to access an MS-List on my Sharepoint site:
sp_lists = ctx.web.lists
s_list = sp_lists.get_by_title(staff_list)
l_items = s_list.get_items()
ctx.load(l_items)
ctx.execute_query()
It works excep... | [
"Found the answer - in case this is useful to anyone\nsp_lists = ctx.web.lists\ns_list = sp_lists.get_by_title(staff_list)\nl_items= s_list.items.paged(500).get().execute_query()\n\n[Courtesy of]\n[1]: https://github.com/vgrem/Office365-REST-Python-Client/blob/master/examples/sharepoint/lists/read_large_list.py\n"
... | [
0
] | [] | [] | [
"office365_rest_client",
"python",
"sharepoint",
"sharepoint_list"
] | stackoverflow_0074628645_office365_rest_client_python_sharepoint_sharepoint_list.txt |
Q:
Uploaded data from excel to Python
I am trying to use a program written on github.
The author provides an example of running the code with random data.
xy = pd.DataFrame(np.random.normal(0, 1, (500, 3)), columns=["x_0", "x_1", "x_2"])
xy["y"] = xy.sum(axis=1) + np.random.normal(0, 1, 500)
# set a unique and monot... | Uploaded data from excel to Python | I am trying to use a program written on github.
The author provides an example of running the code with random data.
xy = pd.DataFrame(np.random.normal(0, 1, (500, 3)), columns=["x_0", "x_1", "x_2"])
xy["y"] = xy.sum(axis=1) + np.random.normal(0, 1, 500)
# set a unique and monotonically increasing index (default index... | [
"You can use pd.read_excel to load in an excel file:\nxy = pd.read_excel(\"/path/to/file\")\n\nIt is recommended to store the data in .csv format, though. You can still open it in excel and it is much more efficient with storage.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074638789_python.txt |
Q:
Check unique value when define concrete class for abstract variable in python
Suppose that I have this architecture for my classes:
# abstracts.py
import abc
class AbstractReader(metaclass=abc.ABCMeta):
@classmethod
def get_reader_name(cl):
return cls._READER_NAME
@classmethod
@property... | Check unique value when define concrete class for abstract variable in python | Suppose that I have this architecture for my classes:
# abstracts.py
import abc
class AbstractReader(metaclass=abc.ABCMeta):
@classmethod
def get_reader_name(cl):
return cls._READER_NAME
@classmethod
@property
@abc.abstractmethod
def _READER_NAME(cls):
raise NotImplementedErr... | [
"This is a very special case, but it can be solved with a singleton pattern.\nTo ease things for our selfes we first create a singleton annotation\n# anotations.py\n\ndef singleton(clazz):\n \"\"\"Singleton annotator ensures the annotated class is a singleton\"\"\"\n\n class ClassW(clazz):\n \"\"\"Crea... | [
1,
1
] | [] | [] | [
"design_patterns",
"oop",
"python",
"python_3.x"
] | stackoverflow_0074638479_design_patterns_oop_python_python_3.x.txt |
Q:
Tkinter program does not terminate
import threading
import tkinter
from tkinter import *
flag = False
def terminate_prog():
global win3, mylabel
global flag
flag = True
win3.destroy()
def loop_func():
global flag, mylabel
while True:
if flag:
break
else:
... | Tkinter program does not terminate | import threading
import tkinter
from tkinter import *
flag = False
def terminate_prog():
global win3, mylabel
global flag
flag = True
win3.destroy()
def loop_func():
global flag, mylabel
while True:
if flag:
break
else:
mylabel.config(text="Loop")
g... | [
"I have left comments in the code, for the purpose of self learning.\nAlso see:\n\nSimpleNamespace\nScoping rules\ntkinters after method\nlambda function\n\n\nimport tkinter as tk\n#import tkinter once and avoid wildcard imports\nimport types\n\nnamespace = types.SimpleNamespace()\n#use simplenamespace instead of a... | [
1
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074625860_python_tkinter_user_interface.txt |
Q:
MinMaxScaler for dataframe: ValueError: setting an array element with a sequence
I do the preprocessing for the data to apply to K-means cluster for time-series data following hour. Then, I normalize the data but it shows the error:
`
Traceback (most recent call last):
File ".venv\lib\site-packages\pandas\core\s... | MinMaxScaler for dataframe: ValueError: setting an array element with a sequence | I do the preprocessing for the data to apply to K-means cluster for time-series data following hour. Then, I normalize the data but it shows the error:
`
Traceback (most recent call last):
File ".venv\lib\site-packages\pandas\core\series.py", line 191, in wrapper
raise TypeError(f"cannot convert the series to {co... | [
"The problem here is the datatype of df_hours I preprocessed.\nSolution: change row['SumView'] to row['SumView'].values[0] and do the same with row['CountStudent'].\n"
] | [
0
] | [] | [] | [
"dataframe",
"normalization",
"python"
] | stackoverflow_0074592554_dataframe_normalization_python.txt |
Q:
How to get the specific multiple value out from a list in python and If the user input is equal to the mulitple values print output
Pass=[0,20,40,60,80,100,120]
while True:
Pass_Input=int(input("Enter : "))
if Pass_Input in Pass[5:6]:
print("Progress")
elif Pass_Input in Pass[0:2]:
prin... | How to get the specific multiple value out from a list in python and If the user input is equal to the mulitple values print output | Pass=[0,20,40,60,80,100,120]
while True:
Pass_Input=int(input("Enter : "))
if Pass_Input in Pass[5:6]:
print("Progress")
elif Pass_Input in Pass[0:2]:
print("Progress Module Trailer")
elif Pass_Input in Pass[0]:
print("Exclude")
Input:
Enter : 120
Output I get:
Traceback (most ... | [
"In your last elif evaluation, you are using Pass[0] which is not a list but a value. You should write\nelif Pass_Input == Pass[0]\n\n",
"Pass[5:6] is [100]\nand 120 is not in [100] with no doubt.\nlist slice Pass[5:6] means from 5 to 6, which 5 is included and 6 is not.\nIn [1]: Pass=[0,20,40,60,80,100,120]\nIn ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074638769_python.txt |
Q:
Removing double quotations marks from String in Pandas Series
i am currently looping through a subset of a Pandas DataFrame and the string values inside have double quotation marks surrounding them. If i don't get them removed, i won't be able to compare them to what i need them compared to.
This is the code i hav... | Removing double quotations marks from String in Pandas Series | i am currently looping through a subset of a Pandas DataFrame and the string values inside have double quotation marks surrounding them. If i don't get them removed, i won't be able to compare them to what i need them compared to.
This is the code i have so far:
df_asinn = df.copy()
for index, screen_name in df.loc[:, ... | [
"Not quite sure exactly what you're getting at: see comment by @Panda Kim. However, two things that might point you in the right direction:\n\nCalling string.replace(char, '') will replace all instances of char in string with a blank string, effectively removing them. I usually use this method, though translate wor... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074638744_pandas_python.txt |
Q:
Run python exe in raspberry Pi
I have a python script named client.py and I created an .exe file using pyinstaller in windows 10.
pyinstaller client.py
I want to run this .exe in Raspberry Pi 3. What should I do in order to do so?
A:
2 ways:
Compile the code on the raspberry pi. PyInstaller supports Linux, and... | Run python exe in raspberry Pi | I have a python script named client.py and I created an .exe file using pyinstaller in windows 10.
pyinstaller client.py
I want to run this .exe in Raspberry Pi 3. What should I do in order to do so?
| [
"2 ways:\n\nCompile the code on the raspberry pi. PyInstaller supports Linux, and it works almost identically.\nUse wine\n\n"
] | [
0
] | [
"You would just need to copy the client.py to the raspberry py, install any required pip modules and run via python client.py\n.exe binaries typically are windows only... There are ways to emulate a Windows environment and run windows applications on a linux system but doing such is extremely heavy-handed and would... | [
-1,
-1
] | [
"pyinstaller",
"python",
"raspberry_pi"
] | stackoverflow_0061200250_pyinstaller_python_raspberry_pi.txt |
Q:
How to fix error: 'AnnAssign' nodes are not implemented in Python
I try to do following:
import pandas as pd
d = {'col1': [1, 7, 3, 6], 'col2': [3, 4, 9, 1]}
df = pd.DataFrame(data=d)
out = df.query('col1 > col2')
out= col1 col2
1 7 4
3 6 1
This works OK. But when I modify column name col1 -... | How to fix error: 'AnnAssign' nodes are not implemented in Python | I try to do following:
import pandas as pd
d = {'col1': [1, 7, 3, 6], 'col2': [3, 4, 9, 1]}
df = pd.DataFrame(data=d)
out = df.query('col1 > col2')
out= col1 col2
1 7 4
3 6 1
This works OK. But when I modify column name col1 --> col1:suf
d = {'col1:suf': [1, 7, 3, 6], 'col2': [3, 4, 9, 1]}
df... | [
"The colon : is a special character in SQL queries. You need to enclose it in backticks.\nTry this :\nout = df.query('`col1:suf` > col2')\n\nOutput :\nprint(out)\n\n col1:suf col2\n1 7 4\n3 6 1\n\n",
"According to ValentinFFM's comment on this issue, you need to put a backtick quote aro... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074638814_dataframe_pandas_python.txt |
Q:
Reduce edges in a MultiDiGraph
I've a MultiDiGraph in which there are some edges that I need remove.
import networkx as ntx
import matplotlib.pyplot as plt
edges = [
(6, 7), (7, 6), (7, 11), (11, 7), (11, 8), (8, 11), (8, 9), (9, 8), (9, 5), (5, 9),
(5, 10), (10, 5), (10, 2), (2, 10),
(2, 1), (1, 2), ... | Reduce edges in a MultiDiGraph | I've a MultiDiGraph in which there are some edges that I need remove.
import networkx as ntx
import matplotlib.pyplot as plt
edges = [
(6, 7), (7, 6), (7, 11), (11, 7), (11, 8), (8, 11), (8, 9), (9, 8), (9, 5), (5, 9),
(5, 10), (10, 5), (10, 2), (2, 10),
(2, 1), (1, 2), (1, 0), (0, 1),
(0, 12), (12, 0)... | [
"Firstly, for the bidirectional edges, it's pretty much the same as the one for Graph but we add another edge in the opposite direction to make it bidirectional:\n# Select all nodes with only 2 neighbors\nnodes_to_remove_bidirectional = [n for n in G.nodes if len(list(G.neighbors(n))) == 2]\n# For each of those nod... | [
1
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0074638719_networkx_python.txt |
Q:
Reading NLP models from Azure blob container
I have uploaded the sentence transformer model on my blob container. The idea is to load the model into a Python notebook from the blob container. To do this I do the following:
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
service = Blob... | Reading NLP models from Azure blob container | I have uploaded the sentence transformer model on my blob container. The idea is to load the model into a Python notebook from the blob container. To do this I do the following:
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
service = BlobServiceClient(account_url="https://<name_of_my_blo... | [
"I tried in my environment and got below results:\n\n'BlobServiceClient' object has no attribute 'get_blob_to_path'\n\nThe above error tells that BlobServiceClient is not longer supporting get_blob_to_path method. because Blockblobservice is the library is using get_blob_to_path.\nExample:\nfrom azure.storage.blob ... | [
0
] | [] | [] | [
"azure",
"azure_blob_storage",
"azure_python_sdk",
"python",
"sentence_transformers"
] | stackoverflow_0074614336_azure_azure_blob_storage_azure_python_sdk_python_sentence_transformers.txt |
Q:
How to get time in '2022-12-01T09:13:45Z' this format?
from datetime import datetime
import pytz
# local datetime to ISO Datetime
iso_date = datetime.now().replace(microsecond=0).isoformat()
print('ISO Datetime:', iso_date)
This doesn't give me the required format i want
2022-05-18T13:43:13
I wanted to get the ... | How to get time in '2022-12-01T09:13:45Z' this format? | from datetime import datetime
import pytz
# local datetime to ISO Datetime
iso_date = datetime.now().replace(microsecond=0).isoformat()
print('ISO Datetime:', iso_date)
This doesn't give me the required format i want
2022-05-18T13:43:13
I wanted to get the time like '2022-12-01T09:13:45Z'
| [
"The time format that you want is known as Zulu time format, the following code changes UTC to Zulu format.\nExample 1\nimport datetime\nnow = datetime.datetime.now(datetime.timezone.utc)\nprint(now)\n\nOutput\n#2022-12-01 10:07:06.552326+00:00\n\nExample 2 (Hack)\nimport datetime\nnow = datetime.datetime.now(datet... | [
1,
0
] | [] | [] | [
"datetime",
"python",
"pytz"
] | stackoverflow_0074638856_datetime_python_pytz.txt |
Q:
Aggregate by unique values & their counts using pandas
I have a df:
# create generic df with 1 date column and 2 value columns
df = pd.DataFrame({'date': pd.date_range('2020-01-01', '2020-01-31', freq='D'), \
'value1': np.random.randint(0, 10, 31), \
'value2': np.random.randint(0, 100, 31),\
'value3': ... | Aggregate by unique values & their counts using pandas | I have a df:
# create generic df with 1 date column and 2 value columns
df = pd.DataFrame({'date': pd.date_range('2020-01-01', '2020-01-31', freq='D'), \
'value1': np.random.randint(0, 10, 31), \
'value2': np.random.randint(0, 100, 31),\
'value3': np.random.randint(0, 1000, 31)})
I want to group by this df... | [
"Convert values to dictionaries with lambda function:\ndf = df.groupby(pd.Grouper(key='date', freq='W'))\\\n .agg({'value1': 'mean', 'value2': 'mean', \n 'value3': lambda x: x.value_counts().to_dict()})\\\n .reset_index()\nprint (df)\n date value1 value2 \\\n0 2020-01-05 3.200000 41.... | [
4
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074639048_group_by_pandas_python.txt |
Q:
Python lightblue : "AttributeError: module 'lightblue' has no attribute 'finddevices'"
.
Hi everyone, hope you're doing well!
I am trying to write a Python (3.8.9) script so that my computer detects every Bluetooth device it can find and provides me with the list of devices it has found.
Then, I installed pybluez ... | Python lightblue : "AttributeError: module 'lightblue' has no attribute 'finddevices'" | .
Hi everyone, hope you're doing well!
I am trying to write a Python (3.8.9) script so that my computer detects every Bluetooth device it can find and provides me with the list of devices it has found.
Then, I installed pybluez and lightblue with
pip3 install pybluez
and
pip3 install python-lightblue
python-lightbl... | [
"I think the problem is in 3-year old latest version in pip registry.\nTry to install from master from GitHub\n\npip install git+https://github.com/pybluez/pybluez.git\n\nThis will solve your problem\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0071840588_python.txt |
Q:
Serious anaconda error :failed with repodata from current_repodata.json
I got fatal problem with using anaconda.
When I use conda update, conda install
Always arise failed with repodata from current_repodata.json, will retry with next repodata source.
And It take several "HOUR" then fail to search packages.
Even I... | Serious anaconda error :failed with repodata from current_repodata.json | I got fatal problem with using anaconda.
When I use conda update, conda install
Always arise failed with repodata from current_repodata.json, will retry with next repodata source.
And It take several "HOUR" then fail to search packages.
Even I cannot do:
conda update --all OR conda update -n base conda
I don't know wha... | [
"I had the same issue and have been trying to fix for hours. Setting channel priority to false seems to be the thing that has worked best so far. In the end, to get things working I:\n\nDeleted all traces of conda and did fresh install\nStarted with: conda config --set channel_priority false\nThen: conda update con... | [
0
] | [] | [] | [
"anaconda",
"python"
] | stackoverflow_0072422453_anaconda_python.txt |
Q:
How do I set a variable with the value being a random range, with variables set to have a random range?
I have this variable called "number" with the range being the variables "a" and "b". These range variables are ranges themselves.
from random import *
a = randint(1, 99)
b = randint(2, 100)
number = randint(a,... | How do I set a variable with the value being a random range, with variables set to have a random range? | I have this variable called "number" with the range being the variables "a" and "b". These range variables are ranges themselves.
from random import *
a = randint(1, 99)
b = randint(2, 100)
number = randint(a, b)
print(number)
When I try to enter this code, I occasionally receive an integer or get this error:
Traceb... | [
"You need to ensure that the first parameter passed to randint is less than or equal to the second parameter. How about:\nfrom random import randint\n\na = randint(1, 99)\nb = randint(a, 100)\nnumber = randint(a, b)\nprint(number)\n\n...which is equivalent to:\nfrom random import randint\n\nnumber = randint(1, 100)... | [
3,
1,
0
] | [
"Using this it seems to do the job you asked.\nimport random\n\na = random.randint(1, 99)\nb = random.randint(2, 100)\n\nnumber = random.randint(a, b)\nprint(number)\n\nI don't have any error running this.\n"
] | [
-2
] | [
"module",
"python",
"python_3.x",
"random"
] | stackoverflow_0074638985_module_python_python_3.x_random.txt |
Q:
Date out of range pymongo
I am trying to retrive date from mongodb but it's out of the range date in python.
I tried setting the min and max but the problel still occurs. Can anyone help please ?
A:
I am filtering data of whole one day, hope this will work
from datetime import datetime, timedelta
import pymongo
... | Date out of range pymongo | I am trying to retrive date from mongodb but it's out of the range date in python.
I tried setting the min and max but the problel still occurs. Can anyone help please ?
| [
"I am filtering data of whole one day, hope this will work\nfrom datetime import datetime, timedelta\nimport pymongo\nclient = pymongo.MongoClient(\"mongodb\", 27017)\ndb = client[\"attendance\"]\ndaily = db.daily\nfy,fm,fd=request.json[\"from_date\"].split(\"-\")\nfy,fm,fd=int(fy),int(fm),int(fd)\nty,tm,td=request... | [
0
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0074638981_mongodb_pymongo_python.txt |
Q:
how to change the out_features of densenet121 model?
How to change the out_features of densenet121 model?
I am using the code below to train the model:
from torch.nn.modules.dropout import Dropout
class Densnet121(nn.Module):
def __init__(self):
super(Densnet121, self).__init__()
self.cnn... | how to change the out_features of densenet121 model? | How to change the out_features of densenet121 model?
I am using the code below to train the model:
from torch.nn.modules.dropout import Dropout
class Densnet121(nn.Module):
def __init__(self):
super(Densnet121, self).__init__()
self.cnn1 = nn.Conv2d(in_channels=3 , out_channels=64 , kernel_siz... | [
"Your first conv layer outputs a tensor of shape (b, 64, h, w) while the following layer, the densenet model expects 3 channels. Hence the error that was raised:\n\n\"expected input [...] to have 3 channels, but got 64 channels instead\"\n\nUnfortunately, this value is hardcoded in the source of the Densenet class,... | [
1
] | [] | [] | [
"densenet",
"python",
"pytorch"
] | stackoverflow_0074633673_densenet_python_pytorch.txt |
Q:
Poetry and Pyenv versioning issue
Can someone explain to me what is going on here?
I'm trying to get pyenv and poetry to place nice together. I am on an AWS instance of Ubuntu 20.04 which has python 3.8.10 installed. (I have removed all traces of python2 from the system). I would like to use python 3.10 but I can'... | Poetry and Pyenv versioning issue | Can someone explain to me what is going on here?
I'm trying to get pyenv and poetry to place nice together. I am on an AWS instance of Ubuntu 20.04 which has python 3.8.10 installed. (I have removed all traces of python2 from the system). I would like to use python 3.10 but I can't just upgrade to that (thank you very ... | [
"Poetry can't handle the Python dependency for you. That is, it can't install the correct Python version for you; it can only handle Python package dependencies correctly for you. But it will check for the correct Python version.\nSince Poetry itself depends on Python, and in this case that's an older version (3.8)... | [
0
] | [
"You have python 3.10 install when is great, but the system version of python still exist. What you have to do now is to switch the python version you have just installed.\nyou can run\npyenv global 3.10 this will switch to the 3.10 version you just installed\nAfter that you can run your poetry command and it will ... | [
-1
] | [
"pyenv",
"python",
"python_poetry"
] | stackoverflow_0074635227_pyenv_python_python_poetry.txt |
Q:
how to modify grouped data in pandas
i would like to modify grouped data in pandas. I wrote a shortcode that doesn't work. unfortunately outside of the loop when I use gr.get_group('Audi') the data remains unchanged. How to modify grouped daraframes and how to return from grouped data to dataframes later.
import ... | how to modify grouped data in pandas | i would like to modify grouped data in pandas. I wrote a shortcode that doesn't work. unfortunately outside of the loop when I use gr.get_group('Audi') the data remains unchanged. How to modify grouped daraframes and how to return from grouped data to dataframes later.
import pandas as pd
import numpy as np
d = {'car... | [
"Try to pd.concat the val in each for loop to with the df_new like below\nimport pandas as pd\nimport numpy as np\n\nd = {'car' : [\"Audi\", \"Audi\", \"Audi\", \"BMW\", \"BMW\", \"BMW\", \"FIAT\", \"FIAT\", \"FIAT\", \"FIAT\"],\n 'year' : [2000, 2001, 1995, 1992, 2003, 2003, 2011, 1982, 1997, 2002]}\n\ndf = pd.... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074639029_pandas_python.txt |
Q:
using arrays of different sizes within a function
I'm trying to write a function that will take a set of arguments from the rows of a 2d array and use them in conjunction with all the elements of a longer 1d array:
x = np.linspace(-10,10,100)
abc = np.array([[1,2,1],
[1,3,5],
[12.5,-6.4,-1.25],
[... | using arrays of different sizes within a function | I'm trying to write a function that will take a set of arguments from the rows of a 2d array and use them in conjunction with all the elements of a longer 1d array:
x = np.linspace(-10,10,100)
abc = np.array([[1,2,1],
[1,3,5],
[12.5,-6.4,-1.25],
[4,2,1]])
def quadratic(a, b, c, x):
return a*(x *... | [
"In numpy the operation x * y is performed element wise where one or both values can be expanded to make them compatible. This is called broadcasting.\nIn the example above your arrays have different dimensions (100,0) and (4,3), hence the error.\nWhen multiplying matrixes you should be using dot instead.\nimport n... | [
1,
1
] | [] | [] | [
"arrays",
"broadcast",
"function",
"numpy",
"python"
] | stackoverflow_0074637231_arrays_broadcast_function_numpy_python.txt |
Q:
Cannot import name 'available_if' from 'sklearn.utils.metaestimators'
While importing "from imblearn.over_sampling import SMOTE", getting import error. Please check and help.
I tried upgrading sklearn, but the upgrade was undone with 'OSError'.
Firsty installed imbalance-learn through pip.
!pip install -U imbalanc... | Cannot import name 'available_if' from 'sklearn.utils.metaestimators' | While importing "from imblearn.over_sampling import SMOTE", getting import error. Please check and help.
I tried upgrading sklearn, but the upgrade was undone with 'OSError'.
Firsty installed imbalance-learn through pip.
!pip install -U imbalanced-learn
Using jupyter notebook
Windows 10
sklearn version - 0.24.1
nu... | [
"IF in jupyter , restart the kernel.This fixed!\n",
"I believe the issue is with python versioning of scikit-learn. I was able to resolve by reinstalling the Python3 version:\npip uninstall scikit-learn -y\n\npip3 install scikit-learn \n\nRemember to restart terminal/notebook after package updates.\nThis gives me... | [
7,
2,
0,
0,
0,
0
] | [] | [] | [
"imbalanced_data",
"imblearn",
"jupyter_notebook",
"python",
"smote"
] | stackoverflow_0069602057_imbalanced_data_imblearn_jupyter_notebook_python_smote.txt |
Q:
Python DataFrames - Help needed with creating a new column based on several conditionals
I have a challenges DataFrame from the Great British Baking Show. Feel free to download the dataset:
pd.read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-10-25/challenges.csv")
I've... | Python DataFrames - Help needed with creating a new column based on several conditionals | I have a challenges DataFrame from the Great British Baking Show. Feel free to download the dataset:
pd.read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-10-25/challenges.csv")
I've cleaned up the table and now have columns of series (1 through 10), episode (6 through 10), b... | [
"You could try the following (df your dataframe):\nm = df[\"result\"].eq(\"OUT\")\ndf[\"final_score\"] = (\n df.groupby(\"series\")[\"baker\"].transform(\"nunique\")\n - df[m].groupby(\"series\")[\"baker\"].cumcount()\n)\ndf[\"final_score\"] = df[m].groupby([\"series\", \"episode\"])[\"final_score\"].transfor... | [
0
] | [] | [] | [
"dataframe",
"loops",
"pandas",
"python"
] | stackoverflow_0074625061_dataframe_loops_pandas_python.txt |
Q:
Better way of excuting a always running app?
Good day.
I have a question about the correct way of implemting code that needs to run every 5 minutes.
Is it better to:
A - Inside the code have a timeloop that starts after 5 minutes, and
executes.
B - Have a script that runs every 5 minutes and executes your
applica... | Better way of excuting a always running app? | Good day.
I have a question about the correct way of implemting code that needs to run every 5 minutes.
Is it better to:
A - Inside the code have a timeloop that starts after 5 minutes, and
executes.
B - Have a script that runs every 5 minutes and executes your
application.
C - Other?
BG: This will be running on a wi... | [
"B.) The script is named Windows Task Scheduler and comes with permission management etc.. A Windows server admin can tell you about it.\nWhy?\n\nYour app might have memory leaks (well, Python not so much) and it runs more stable when it's restarted every time.\nAn app that sleeps still uses memory, which may be sw... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0074639118_python.txt |
Q:
AttributeError: 'DataFrameWriter' object has no attribute 'start'
I am trying to write a code using Kafka, Python and SparK
The problem statement is: Read data from XML and the data consumed will be in the binary format. This data has to be stored in a data frame.
I am getting below error:
Error:
File "C:/Users/HP... | AttributeError: 'DataFrameWriter' object has no attribute 'start' | I am trying to write a code using Kafka, Python and SparK
The problem statement is: Read data from XML and the data consumed will be in the binary format. This data has to be stored in a data frame.
I am getting below error:
Error:
File "C:/Users/HP/PycharmProjects/xml_streaming/ConS.py", line 55, in
.format("console"... | [
"I don't have a lot of experience with kafka, but at the end you're using the start() method on the result of book_DF.write.format(\"console\"), which is a DataFrameWriter object. This does not have a start() method.\nDo you want to write this as a stream? Then you'll probably need to use something like the writeSt... | [
0
] | [] | [] | [
"apache_kafka",
"apache_spark",
"consumer",
"python",
"python_3.x"
] | stackoverflow_0074638593_apache_kafka_apache_spark_consumer_python_python_3.x.txt |
Q:
Python given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A in O(n) time complexity
For example:
input: A = [ 6 4 3 -5 0 2 -7 1 ]
output: 5
Since 5 is the smallest positive integer that does not occur in the array.
I have written two solutions to that ... | Python given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A in O(n) time complexity | For example:
input: A = [ 6 4 3 -5 0 2 -7 1 ]
output: 5
Since 5 is the smallest positive integer that does not occur in the array.
I have written two solutions to that problem. The first one is good but I don't want to use any external libraries + its O(n)*log(n) complexity. The second solution "In which I need yo... | [
"Testing for the presence of a number in a set is fast in Python so you could try something like this:\ndef minpositive(a):\n A = set(a)\n ans = 1\n while ans in A:\n ans += 1\n return ans\n\n",
"Fast for large arrays.\ndef minpositive(arr):\n if 1 not in arr: # protection from error if ( max... | [
80,
5,
3,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"I just modified the answer by @najeeb-jebreel and now the function gives an optimal solution.\ndef solution(A):\n sorted_set = set(sorted(A))\n sol = 1\n for x in sorted_set:\n if x == sol:\n sol += 1\n else:\n break\n return sol\n\n",
"I reduced the length of set ... | [
-1,
-1,
-1,
-1,
-2
] | [
"algorithm",
"python",
"python_3.x",
"time_complexity"
] | stackoverflow_0049224022_algorithm_python_python_3.x_time_complexity.txt |
Q:
ValueError: You are trying to load a weight file containing 293 layers into a model with 147 layers
If you are getting this error while following the code from this tutorial
https://pixellib.readthedocs.io/en/latest/image_ade20k.html
ValueError: You are trying to load a weight file containing 293 layers into a mod... | ValueError: You are trying to load a weight file containing 293 layers into a model with 147 layers | If you are getting this error while following the code from this tutorial
https://pixellib.readthedocs.io/en/latest/image_ade20k.html
ValueError: You are trying to load a weight file containing 293 layers into a model with 147 layers
| [
"The issue can be solved by installing these versions*\n!pip3 install tensorflow==2.6.0\n!pip3 install keras==2.6.0\n!pip3 install imgaug\n!pip3 install pillow==8.2.0\n!pip install pixellib==0.5.2\n!pip install labelme2coco==0.1.2\n\n",
"I got it working by changing some imports in pixellib/semantic/deeplab.py.\n... | [
0,
0
] | [] | [] | [
"keras",
"pixellib",
"python",
"tensorflow"
] | stackoverflow_0073084941_keras_pixellib_python_tensorflow.txt |
Q:
Why PyList_Append is called each time a list is evaluated?
I'm working with CPython3.11.0a3+. I added a break point at PyList_Append and modified the function to stop when the newitem is a dict. The original function:
int
PyList_Append(PyObject *op, PyObject *newitem)
{
if (PyList_Check(op) && (newitem != NULL... | Why PyList_Append is called each time a list is evaluated? | I'm working with CPython3.11.0a3+. I added a break point at PyList_Append and modified the function to stop when the newitem is a dict. The original function:
int
PyList_Append(PyObject *op, PyObject *newitem)
{
if (PyList_Check(op) && (newitem != NULL))
return app1((PyListObject *)op, newitem);
PyErr_B... | [
"dict.__repr__ uses the CPython-internal Py_ReprEnter and Py_ReprLeave functions to stop infinite recursion for recursively nested data structures, and Py_ReprEnter appends the dict to a list of objects currently having their repr evaluated in the running thread.\n"
] | [
2
] | [] | [] | [
"c",
"cpython",
"gdb",
"python",
"python_internals"
] | stackoverflow_0074639259_c_cpython_gdb_python_python_internals.txt |
Q:
Pandas filter by comparing columns
I have a dataframe like this:
Description keyword
1 plays the piano plays
2 plays the piano write
3 plays the piano piano
4 knows how to write the
5 knows how to write to
I want to filter it so that I keep the rows where the keyword is in the description. So he... | Pandas filter by comparing columns | I have a dataframe like this:
Description keyword
1 plays the piano plays
2 plays the piano write
3 plays the piano piano
4 knows how to write the
5 knows how to write to
I want to filter it so that I keep the rows where the keyword is in the description. So here I would like to keep:
Description ... | [
"Assuming your dataframe is called df:\ndf[df.apply(lambda x: x['keyword'] in x['Description'], axis=1)]\n\n"
] | [
1
] | [] | [] | [
"filter",
"pandas",
"python"
] | stackoverflow_0074639249_filter_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.