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 call Python pip in VSCode? After upgrading pip i can't call pip in VSCode. If it's not 'pip' or 'pip3' then what is it? PS C:\Users\dyhli\OneDrive\Рабочий стол\Python\Python> pip install pandas pip : The name "pip" is not recognized as the name of a cmdlet, function, script file, or executable. the progra...
How to call Python pip in VSCode?
After upgrading pip i can't call pip in VSCode. If it's not 'pip' or 'pip3' then what is it? PS C:\Users\dyhli\OneDrive\Рабочий стол\Python\Python> pip install pandas pip : The name "pip" is not recognized as the name of a cmdlet, function, script file, or executable. the program being taken. Check the spelling of th...
[ "You need to add the path of your pip installation to your PATH system variable.\nBy default, pip is installed to C:\\Python34\\Scripts\\pip (pip now comes bundled with new versions of python), so the path \"C:\\Python34\\Scripts\" needs to be added to your PATH variable.\nTo check if it is already in your PATH var...
[ 1 ]
[]
[]
[ "pip", "python", "visual_studio_code" ]
stackoverflow_0074456998_pip_python_visual_studio_code.txt
Q: Python - Convert JPG to text file Good morning all, I've made a Python script that adds text on top of images, based on a preset template. I'm now developing a template editor that will let the user edit the template in GUI, then save the template as a config file. The idea is that one user can create a template, ...
Python - Convert JPG to text file
Good morning all, I've made a Python script that adds text on top of images, based on a preset template. I'm now developing a template editor that will let the user edit the template in GUI, then save the template as a config file. The idea is that one user can create a template, export it, send it to a new user on a s...
[ "Sounds questionable that you want to ship an image as text file (it's easy, base64 is supplied with python, but it drastically increases the amount of bytes. I'd strongly recommend not doing that).\nI'd rather take the text and embed it in the image metadata! That way, you would still have a valid image file, but ...
[ 1, 0 ]
[]
[]
[ "config", "python" ]
stackoverflow_0074458732_config_python.txt
Q: SSL errors when sending file from Azure databricks to SharePoint We are working in a Python notebook on Databricks and want to send a file to a SharePoint site. To achieve this, we obtained a client_id and client_secret from https://<SP_domain>.sharepoint.com/sites/<my_site_name>/_layouts/15/appregnew.aspx Locally...
SSL errors when sending file from Azure databricks to SharePoint
We are working in a Python notebook on Databricks and want to send a file to a SharePoint site. To achieve this, we obtained a client_id and client_secret from https://<SP_domain>.sharepoint.com/sites/<my_site_name>/_layouts/15/appregnew.aspx Locally, I can successfully send a file to SharePoint using these secrets. On...
[ "We got it working.\nThe network configuration of databricks was configured with a firewall that blocked both these URLs which are both needed:\n\nhttps://<tenant name>.sharepoint.com/\nhttps://accounts.accesscontrol.windows.net\n\nThen it worked flawlessly.\nI didn't figure out why the error is shown like this:\nA...
[ 0 ]
[]
[]
[ "azure_databricks", "python", "sharepoint", "ssl" ]
stackoverflow_0074377680_azure_databricks_python_sharepoint_ssl.txt
Q: Mysql connector python error violation of protocol (_ssl.c:2483) Im running an application running React, python and MySQL with a docker compose, When I run the application everything works fine, but when a pettition to the database (from the frontend with axios) is made multiple times, the connection breaks and t...
Mysql connector python error violation of protocol (_ssl.c:2483)
Im running an application running React, python and MySQL with a docker compose, When I run the application everything works fine, but when a pettition to the database (from the frontend with axios) is made multiple times, the connection breaks and the following error appears. Everything is running locally "2055: Lost ...
[ "This looks like an error I faced some time ago. In my case, it was due to a client initiating a secured connection to a non-secured server.\nThe error message indicates that the client has initiated a SSL/TLS connection and is expecting to receive more data than the server has sent during the handshake procedure.\...
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0074416286_mysql_python.txt
Q: Example of jqgrid with python So I've cloned this https://bitbucket.org/romildo/django-jqgrid-demo.git as I am looking for a working example of jqgrid with django. I've been updating the code (as this seems like it was written for a version 2 of django and I'm workng on 4.1) I'm completely stumped by the lines fro...
Example of jqgrid with python
So I've cloned this https://bitbucket.org/romildo/django-jqgrid-demo.git as I am looking for a working example of jqgrid with django. I've been updating the code (as this seems like it was written for a version 2 of django and I'm workng on 4.1) I'm completely stumped by the lines from jqgrid import JqGrid giving me t...
[ "Simply you can install this library:\npip install js.jqgrid\n\nAnd now your above error will solve\n" ]
[ 0 ]
[]
[]
[ "django", "jqgrid", "python" ]
stackoverflow_0074458777_django_jqgrid_python.txt
Q: Structure Folder Path with Repository path Cloud Composer DAG I need to run the DAG with the repository folder name, and I need to call the other modules from another directory from another path repository deployed. So, I have a cloudbuild.yaml that will deploy the script into DAG folder and Plugins folder, but I ...
Structure Folder Path with Repository path Cloud Composer DAG
I need to run the DAG with the repository folder name, and I need to call the other modules from another directory from another path repository deployed. So, I have a cloudbuild.yaml that will deploy the script into DAG folder and Plugins folder, but I still didn't know, how to get the other modules from the other path...
[ "You can put every modules in the Cloud Composer DAG folder, example :\ncloud-composer-bucket/\n dags/\n github_my_repository_deployed-testing/\n test_dag.py\n planning/\n modules_1.py\n \n setup.py\n\nOn the DAG Python code, you can import your module with the f...
[ 1 ]
[]
[]
[ "airflow", "google_cloud_composer", "google_cloud_storage", "python" ]
stackoverflow_0074458726_airflow_google_cloud_composer_google_cloud_storage_python.txt
Q: Finding the most likely correct string from multiple OCR results of the same text in Python I have run EasyOCR in Python over a large number of black and white images of the text on soldered components, with the goal of collecting the writing on each of them. The results are mostly good, but there are some inconsi...
Finding the most likely correct string from multiple OCR results of the same text in Python
I have run EasyOCR in Python over a large number of black and white images of the text on soldered components, with the goal of collecting the writing on each of them. The results are mostly good, but there are some inconsistent results that I would like to filter out. I have used multiple pictures of the same componen...
[ "You can find the Levenshtein distance (or edit distance) for each pair of guesses, and then select the one which is closer to all other.\nThere are many libraries implementing Levenshtein distance, for this example I'll use editdistance (there may be better implementations with more parameters to tune, this is one...
[ 0, 0 ]
[]
[]
[ "ocr", "pandas", "python", "text_recognition" ]
stackoverflow_0073427276_ocr_pandas_python_text_recognition.txt
Q: How to use tabulate library with zip_longest? I am trying to use tabulate with the zip_longest function. So I have it like this: from __future__ import print_function from tabulate import tabulate from itertools import zip_longest import itertools import locale import operator import re verdi50 ="[' \n\na)\n\n \n...
How to use tabulate library with zip_longest?
I am trying to use tabulate with the zip_longest function. So I have it like this: from __future__ import print_function from tabulate import tabulate from itertools import zip_longest import itertools import locale import operator import re verdi50 ="[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. :...
[ "You should be passing a single table to the tabulate() function, passing multiple lists results in the TypeError: tabulate() got multiple values for argument 'headers' you are seeing.\nUpdating your return statement -\ndef show_extracted_data_from_file():\n regexes = [\n verdi_total_number_fruit_regex(),\...
[ 1 ]
[]
[]
[ "python", "tabulate" ]
stackoverflow_0074458320_python_tabulate.txt
Q: How to resize a table with xlwings? I am trying to figure out how to resize a table using xlwings but can't figure out how. I have tried using the resize(range) property but I am getting getting the following error : AttributeError: 'str' object has no attribute 'api' This is the code I got the error with : impor...
How to resize a table with xlwings?
I am trying to figure out how to resize a table using xlwings but can't figure out how. I have tried using the resize(range) property but I am getting getting the following error : AttributeError: 'str' object has no attribute 'api' This is the code I got the error with : import xlwings as xw tableau = xw.books['test...
[ "Shouldn't need to, the table is resized automatically.\nThis is the code I ran for your previous question using an Excel file with a table, 'Table1' consisting of 3 columns and 3 rows with header row so the table range is A1:C4. The code adds two additional rows as individual cells and as a tuple. As each row is a...
[ 1 ]
[]
[]
[ "python", "python_3.x", "xlwings" ]
stackoverflow_0074458079_python_python_3.x_xlwings.txt
Q: How to round the minute of a datetime object I have a datetime object produced using strptime(). >>> tm datetime.datetime(2010, 6, 10, 3, 56, 23) What I need to do is round the minute to the closest 10th minute. What I have been doing up to this point was taking the minute value and using round() on it. min = rou...
How to round the minute of a datetime object
I have a datetime object produced using strptime(). >>> tm datetime.datetime(2010, 6, 10, 3, 56, 23) What I need to do is round the minute to the closest 10th minute. What I have been doing up to this point was taking the minute value and using round() on it. min = round(tm.minute, -1) However, as with the above exam...
[ "This will get the 'floor' of a datetime object stored in tm rounded to the 10 minute mark before tm.\ntm = tm - datetime.timedelta(minutes=tm.minute % 10,\n seconds=tm.second,\n microseconds=tm.microsecond)\n\nIf you want classic rounding to the nearest 10 mi...
[ 161, 112, 21, 20, 14, 13, 3, 3, 3, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "datetime", "python", "rounding" ]
stackoverflow_0003463930_datetime_python_rounding.txt
Q: How to analyze only .py files in SonarQube properties file? I am using SonarQube for my work project. We have a repository with a lot of files and folders in our project. I want to filter out only the python files (.py files). My goal is to analyze only the .py files in the folder repo/src. I tried using the wildc...
How to analyze only .py files in SonarQube properties file?
I am using SonarQube for my work project. We have a repository with a lot of files and folders in our project. I want to filter out only the python files (.py files). My goal is to analyze only the .py files in the folder repo/src. I tried using the wildcards, but to no avail. Here are the two things I tried : sonar.so...
[ "Try specifying sonar.exclusions in addition to sonar.sources.\nBefore, there was sonar.language, which you could set to py for Python:\n\nSet the language of the source code to analyze. Browse the Plugin Library page to get the list of all available languages. If not set, a multi-language analysis will be triggere...
[ 1 ]
[]
[]
[ "python", "sonarqube" ]
stackoverflow_0074452047_python_sonarqube.txt
Q: Applying a function that inverts column values using pandas I'm hoping to get someone's advice on a problem I'm running into trying to apply a function over columns in a dataframe I have that inverses the values in the columns. For example, if the observation is 0 and the max of the column is 7, I subtract the abs...
Applying a function that inverts column values using pandas
I'm hoping to get someone's advice on a problem I'm running into trying to apply a function over columns in a dataframe I have that inverses the values in the columns. For example, if the observation is 0 and the max of the column is 7, I subtract the absolute value of the max from the observation: abs(0 - 7) = 7, so t...
[ "apply is slow. It is better to use vectorized approaches as below.\naxis=1 means that your function will work column wise, if you do not specify it will work row wise. When you get key error it means pandas is searching for a column name and it cannot find it. If you really must use apply try searching for a few ...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074458144_pandas_python.txt
Q: Right to left text in tkinter I'm using a RTL language and I need my text to be RTL. Is there a way to do it? And How can I justify my text? Example: from tkinter import * from tkinter.constants import * root = Tk() text = Text(root,,font=('Tahoma',8))#I need RTL and Right justified text! text.grid() scrl = Scroll...
Right to left text in tkinter
I'm using a RTL language and I need my text to be RTL. Is there a way to do it? And How can I justify my text? Example: from tkinter import * from tkinter.constants import * root = Tk() text = Text(root,,font=('Tahoma',8))#I need RTL and Right justified text! text.grid() scrl = Scrollbar(root, command=text.yview) text....
[ "i modified your code and it's worked!..\nfrom tkinter import *\nfrom tkinter.constants import *\nroot = Tk()\ntext = Text(root,,font=('Tahoma',8))#I need RTL and Right justified text!\n\ntext.tag_configure('tag-right', justify='right')\ntext.insert('end', 'text ' * 10, 'tag-right')\ntext.grid()\n\nscrl = Scrollbar...
[ 2, 0, 0 ]
[]
[]
[ "python", "text", "tkinter" ]
stackoverflow_0020306726_python_text_tkinter.txt
Q: pythonanywhere - issues with JavaScript files loading in admin console having issues with js files loading in the admin console, hindering the activities of the admin console. Errors attached. Tried entering the static file path under the static section on the pythonanywhere. home/<username>/<name of the app>/st...
pythonanywhere - issues with JavaScript files loading in admin console
having issues with js files loading in the admin console, hindering the activities of the admin console. Errors attached. Tried entering the static file path under the static section on the pythonanywhere. home/<username>/<name of the app>/static/js
[ "If you search for \"static\" in the PythonAnywhere help pages, you will find a number of help pages about setting up static files and debugging issues with them.\n" ]
[ 1 ]
[]
[]
[ "django", "javascript", "python", "pythonanywhere" ]
stackoverflow_0074455219_django_javascript_python_pythonanywhere.txt
Q: How to encode string to hex for sending downlink to iot devices? According to this document I need to send downlink of type 080100ff to open the supply of the socket. However, I can not send 080100ff since I got this error The payload field is not a valid hexadecimal payload in upper case. Here is my so far works...
How to encode string to hex for sending downlink to iot devices?
According to this document I need to send downlink of type 080100ff to open the supply of the socket. However, I can not send 080100ff since I got this error The payload field is not a valid hexadecimal payload in upper case. Here is my so far works in python '080100ff'.encode('utf-8').hex() -> 3038303130306666 I can ...
[ "In your example you are converting a hexadecimal string (080100ff) into hexadecimal value. You already have the hexadecimal value, it is: 080100ff\nWould that work?\nbytes.fromhex('080100ff')\n\n", "Could be maybe you need to try, 080100FF\n" ]
[ 1, 0 ]
[]
[]
[ "hex", "iot", "python" ]
stackoverflow_0074458800_hex_iot_python.txt
Q: Why does this code detects images as video and how can I fix it? This method is detecting .jpg pictures as video. Why is that? How can I fix it? def is_video(self) -> bool: try: res = self.video_metadata['codec_type'] == 'video' logger.info(f"Video.is_video() -> {res}") return res e...
Why does this code detects images as video and how can I fix it?
This method is detecting .jpg pictures as video. Why is that? How can I fix it? def is_video(self) -> bool: try: res = self.video_metadata['codec_type'] == 'video' logger.info(f"Video.is_video() -> {res}") return res except: return False I'm getting the metadata with ffmpeg.prob...
[ "Check for number of frames greater than 1 to distinguish between image and video.\ndef is_video(self) -> bool:\n try:\n res = (self.video_metadata['codec_type'] == 'video'\n and int(self.video_metadata['nb_frames']) > 1)\n logger.info(f\"Video.is_video() -> {res}\")\n return r...
[ 1 ]
[]
[]
[ "ffmpeg", "python", "video" ]
stackoverflow_0074437759_ffmpeg_python_video.txt
Q: How I add to a list same number multiple times by count? I've got 2 problems here. my first problem is that the code shows me only one time a factor even though it's multiple x times by the same factor. I don't know how to add it to the factor list. Another problem is I'm not sure in print - how the sep works and ...
How I add to a list same number multiple times by count?
I've got 2 problems here. my first problem is that the code shows me only one time a factor even though it's multiple x times by the same factor. I don't know how to add it to the factor list. Another problem is I'm not sure in print - how the sep works and how can I write "*" only between elements of factor list. I ca...
[ "The problem is that in your second 'for' loop you evaluate if there is a prime number in your number, but not how many times it is present.\nTo do this you need to repeat the cycle every time you find a prime number and divide the initial number by the prime number. this way you will get to 1 and get all the facto...
[ 0 ]
[]
[]
[ "list", "prime_factoring", "python" ]
stackoverflow_0074453084_list_prime_factoring_python.txt
Q: How to keep the same style for a table using openpyxl and python? So my goal was to add data in an already existing table using openpyxl and python. I did it by using .cell(row, column).value method. After doing this I had a problem because the table I was writing the data in was not expanding correctly. So i foun...
How to keep the same style for a table using openpyxl and python?
So my goal was to add data in an already existing table using openpyxl and python. I did it by using .cell(row, column).value method. After doing this I had a problem because the table I was writing the data in was not expanding correctly. So i found this method and it worked fine : from openpyxl import load_workbook ...
[ "Using xlwings helps to keep the same format (including justifications, formulas) of a table.\nWhen inserting data, the table will automatically expand. See example below :\nimport xlwings as xw\nwb = xw.Book('test_book.xlsx')\n\ntableau = wb.sheets[0].tables[0]\nsheet = wb.sheets[0]\n\ntableau.name = 'new'\nsheet....
[ 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0074432531_excel_openpyxl_python.txt
Q: Pandas concat is adding unnamed index When I concat two dataframes which are both 337 columns and then export to CSV, the result become 338 columns with each time a new unnamed index being added. df1 Out[141]: datecreated 1 2 3 4 5 ... 331 332 333 334 335 336 0 2022-11-14 4000...
Pandas concat is adding unnamed index
When I concat two dataframes which are both 337 columns and then export to CSV, the result become 338 columns with each time a new unnamed index being added. df1 Out[141]: datecreated 1 2 3 4 5 ... 331 332 333 334 335 336 0 2022-11-14 4000 3900 3850 3810 3790 ... 5520 5300 ...
[ "The unnamed index is the row index of the dataframe. If you do not want this, you can use index=False as one of the arguments such that :\nd5.to_csv(csv_buffer,index=False)\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074458652_pandas_python.txt
Q: Walking average based on two matching columns I have a dataframe df of the following format: team1 team2 score1 score2 0 1 2 1 0 1 3 4 3 0 2 1 3 1 1 3 2 4 0 2 4 1 2 3 2 What I want to do is to create a new colu...
Walking average based on two matching columns
I have a dataframe df of the following format: team1 team2 score1 score2 0 1 2 1 0 1 3 4 3 0 2 1 3 1 1 3 2 4 0 2 4 1 2 3 2 What I want to do is to create a new column that will return rolling average of the score1 c...
[ "Not sure what is your exact expected output, but you can first reshape the DataFrame to a long format:\n(pd.wide_to_long(df.reset_index(), ['team', 'score'], i='index', j='x')\n .groupby('team')['score']\n .rolling(3, min_periods=1).mean()\n)\n\nOutput:\nteam index x\n1 0 1 1.0\n 2 1 ...
[ 0, 0 ]
[]
[]
[ "lambda", "pandas", "python" ]
stackoverflow_0074458608_lambda_pandas_python.txt
Q: Android apk with buildozer problem while compiling I'm trying to compile a python file into an apk on android with Buildozer. I am using the KivyMD library. However, when I run the command "buildozer -v android debug", I get this error: # Check configuration tokens # 1 error(s) found in the buildozer.spec [app] "o...
Android apk with buildozer problem while compiling
I'm trying to compile a python file into an apk on android with Buildozer. I am using the KivyMD library. However, when I run the command "buildozer -v android debug", I get this error: # Check configuration tokens # 1 error(s) found in the buildozer.spec [app] "orientation" have an invalid value I've done this before...
[ "You have an incorrect blank space in front of author.\n", ".spec files are very strict about spaces.\nWhen hiding the comments, the critical part of the .spec file looks like this:\norientation = portrait\n\n author = author\n\nosx.python_version = 3\n\nAs one can see, the author has a blank space in front leadi...
[ 0, 0 ]
[]
[]
[ "android", "apk", "buildozer", "kivymd", "python" ]
stackoverflow_0073601412_android_apk_buildozer_kivymd_python.txt
Q: fastapi: mapping sqlalchemy database model to pydantic geojson feature I just started playing with FastAPI, SQLAlchemy, Pydantic and I'm trying to build a simple API endpoint to return the rows in a postgis table as a geojson feature collection. This is my sqlalchemy model: class Poi(Base): __tablename__ = 'po...
fastapi: mapping sqlalchemy database model to pydantic geojson feature
I just started playing with FastAPI, SQLAlchemy, Pydantic and I'm trying to build a simple API endpoint to return the rows in a postgis table as a geojson feature collection. This is my sqlalchemy model: class Poi(Base): __tablename__ = 'poi' id = Column(Integer, primary_key=True) name = Column(Text, nulla...
[ "You want to return the PoiCollection schema (response_model=schemas.PoiCollection) except that you return your database response directly without any formatting. So you have to convert your crud response into your schema response.\n# Different function for translate db response to Pydantic response according to yo...
[ 3 ]
[]
[]
[ "fastapi", "geojson", "pydantic", "python", "sqlalchemy" ]
stackoverflow_0067419454_fastapi_geojson_pydantic_python_sqlalchemy.txt
Q: How can I use context vars in other file in python 3.7 or above? I have a context var in in file a.py and I want to use it in b.py. a.py: import contextvars cntx = contextvars.ContextVar("abcd") b.py: from .a import cntx print(cntx.get()) Error: Traceback (most recent call last): File "/home/user/Desktop/b.p...
How can I use context vars in other file in python 3.7 or above?
I have a context var in in file a.py and I want to use it in b.py. a.py: import contextvars cntx = contextvars.ContextVar("abcd") b.py: from .a import cntx print(cntx.get()) Error: Traceback (most recent call last): File "/home/user/Desktop/b.py", line 1, in <module> from .a import cntx ImportError: attempted...
[ "The ImportError that you are getting is because of the invalid file name. .a is a valid file name and would work if you had a file with filename being .a.py\nThe reason you are getting the LookupError: <ContextVar name='abcd' at 0x7f7d6209c5e0> is because you are trying to get() the context which hasn't been set y...
[ 1 ]
[]
[]
[ "error_handling", "importerror", "python", "python_3.x", "python_contextvars" ]
stackoverflow_0074458949_error_handling_importerror_python_python_3.x_python_contextvars.txt
Q: pandas - dynamically fill the missing row of group by(create a duplicate row if required based on previous record) Need to fill the data accrding to the stage and last stage is the maximum date Input: RecordID ChangeDate Stage 17764 31-08-2021 New 17764 02-09-2021 inprogress 17764 05-09-2021 won 70382 04-01-2...
pandas - dynamically fill the missing row of group by(create a duplicate row if required based on previous record)
Need to fill the data accrding to the stage and last stage is the maximum date Input: RecordID ChangeDate Stage 17764 31-08-2021 New 17764 02-09-2021 inprogress 17764 05-09-2021 won 70382 04-01-2022 new 70382 06-01-2022 hold 70382 07-01-2022 lost Expceted output: RecordID ChangeDate Stage ...
[ "You can use a groupby.resample:\ndf['ChangeDate'] = pd.to_datetime(df['ChangeDate'], dayfirst=True)\n\n(df.set_index('ChangeDate')\n .groupby('RecordID', as_index=False)\n .resample('1d').ffill()\n .reset_index('ChangeDate')\n)\n\nOutput:\n ChangeDate RecordID Stage\n0 2021-08-31 17764 Ne...
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074458068_pandas_python.txt
Q: Get a Variable directly from function Python i want to work with the variable "sets" after the function has been called. How can i do this? sets = 0 def search_str(monatsabrechnung, d1): with open(monatsabrechnung, 'r') as file: content = file.read() if lastDay == he...
Get a Variable directly from function Python
i want to work with the variable "sets" after the function has been called. How can i do this? sets = 0 def search_str(monatsabrechnung, d1): with open(monatsabrechnung, 'r') as file: content = file.read() if lastDay == heute and ja == 1: sets = 1 ...
[ "IIUC, you are trying to modify a variable in a function, which is originally defined outside a function. This is a variable scoping problem. Do check this awesome article to get an understanding of how variable scopes work in python.\nBack to your code, the issue here is that even though you run the function to mo...
[ 1, 0 ]
[]
[]
[ "function", "python", "variables" ]
stackoverflow_0074459125_function_python_variables.txt
Q: Truncate by the minimum of another DataFrame by columns Be the following python pandas DataFrame (df): age money time 10 300 10 8 200 20 20 1800 80 15 200 50 I want to extract the minimum value for each column: age money time 8 200 10 Given this other new dataframe (new_df): age money time 30 -100 15 1...
Truncate by the minimum of another DataFrame by columns
Be the following python pandas DataFrame (df): age money time 10 300 10 8 200 20 20 1800 80 15 200 50 I want to extract the minimum value for each column: age money time 8 200 10 Given this other new dataframe (new_df): age money time 30 -100 15 10 100 50 -2 1800 -20 18 -50 5...
[ "You can use min to get the min of df, then clip to clip the values of new_df:\nout = new_df.clip(lower=df.min(), axis=1)\n\nOutput:\n age money time\n0 30 200 15\n1 10 200 50\n2 8 1800 10\n3 18 200 52\n\nRestricting to a subset of columns:\ncols = ['age', 'time']\nout = new_df[c...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074459291_dataframe_pandas_python.txt
Q: Day 9 Secret Auction Program from 100 Days of Code with Dr. Angela Yu Can someone help me with this? What am I doing wrong? I checked Dr. Angela Yu's solution. She solves the problem in a different way but I am not able to understand where I am making mistakes. This program should print the name and the bid of the...
Day 9 Secret Auction Program from 100 Days of Code with Dr. Angela Yu
Can someone help me with this? What am I doing wrong? I checked Dr. Angela Yu's solution. She solves the problem in a different way but I am not able to understand where I am making mistakes. This program should print the name and the bid of the highest bidder. However, when I run this code, the console prints the bid ...
[ "You are not considering the value of bid that was stored in the dict bids. You just need to get that value as you are iterating:\nfor bidder, bid in bids.items():\n if bid > highest_bid:\n highest_bid = bid\n winner = bidder\nprint(f\"The winner is {winner} with a bid of ${highest_bid}\")\n\nBy using bids.i...
[ 2 ]
[]
[]
[ "dictionary", "python", "replit" ]
stackoverflow_0074459214_dictionary_python_replit.txt
Q: After clicking the button the user should jump to a specific message in another text channel I have a problem. I have created a button, if the user presses this button the user should jump to a certain message in another text channel. How do I do that? There is jump_url but how do I refer from the button to the me...
After clicking the button the user should jump to a specific message in another text channel
I have a problem. I have created a button, if the user presses this button the user should jump to a certain message in another text channel. How do I do that? There is jump_url but how do I refer from the button to the messages and that the user jumps? class MyView(discord.ui.View): # Create a class called MyView that...
[ "I already answered this question in your other post. There is a special type of button for links, and you can set the url to the jump_url of the message.\nOther than that, you can send an embed with the link in it. If you don't want either of those then there's no other option.\nOfficial example: https://github.co...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074458604_discord_discord.py_python.txt
Q: aiohttp asyncio parsing works fine for a time, then without any error gets no data I need to parse html from list of domains (only main pages) Script works well for a period of time, then it's getting no data with very high speed. Looks like requests doesn't even send. My code: import asyncio import time import ai...
aiohttp asyncio parsing works fine for a time, then without any error gets no data
I need to parse html from list of domains (only main pages) Script works well for a period of time, then it's getting no data with very high speed. Looks like requests doesn't even send. My code: import asyncio import time import aiohttp import pandas as pd import json from bs4 import BeautifulSoup df = pd.read_excel(...
[ "That was timeout error.\n'resp': str(e)\n\nThis code prints only error exception message. TimeOut Error has no exception message, so str(e) = empty string.\nstr(repr(e)) helps to see an Error.\n" ]
[ 0 ]
[]
[]
[ "aiohttp", "python", "python_asyncio" ]
stackoverflow_0074429069_aiohttp_python_python_asyncio.txt
Q: Python - get number of folder in list if file was found How i can get number of folder in my list when folder was found? - For example: [Folder1, Folder2, Folder3] I open all folders contained in this list by: for root, dirs, files in os.walk(path): pass And in this folders i have something to find, example: ...
Python - get number of folder in list if file was found
How i can get number of folder in my list when folder was found? - For example: [Folder1, Folder2, Folder3] I open all folders contained in this list by: for root, dirs, files in os.walk(path): pass And in this folders i have something to find, example: file name in Folder2 -> xxx.png When i was found this i wanna...
[ "Use this example:\nimport os\n\n# folder path\ndir_path = r'E:\\account'\ncount = 0\n# Iterate directory\nfor path in os.listdir(dir_path):\n # check if current path is a file\n if os.path.isfile(os.path.join(dir_path, path)):\n count += 1\nprint('File count:', count)\n\n" ]
[ 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074459268_for_loop_python.txt
Q: ModuleNotFoundError: No module named 'pytest' After installing the pytest module in a virtual environment, I used the python code to call and run the prompt to find the pytest module. I installed the pytest module outside the virtual environment. I can call it normally with python. import pytest def test_main(): ...
ModuleNotFoundError: No module named 'pytest'
After installing the pytest module in a virtual environment, I used the python code to call and run the prompt to find the pytest module. I installed the pytest module outside the virtual environment. I can call it normally with python. import pytest def test_main(): assert 5!=5 if __name__ == "__main__": py...
[ "TLDR: I suspect you installed pytest within your system level python site-packages so when you try to run pytest, within your virtualenv, it's throwing a ModuleNotFoundError since it doesn't have this dependency installed within your virtualenv. Virtual environments give you a sandboxed environment so you can expe...
[ 34, 5, 0, 0 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0055652866_pytest_python.txt
Q: Problem installing Python 3.6.5 on macOS 12.6 Monterey with Intel chip I get the following error when I use pyenv to install python version 3.6.5 using the command pyenv install 3.6.5: Error - configure: error: internal configure error for the platform triplet, please file a bug report I've also tried the suggesti...
Problem installing Python 3.6.5 on macOS 12.6 Monterey with Intel chip
I get the following error when I use pyenv to install python version 3.6.5 using the command pyenv install 3.6.5: Error - configure: error: internal configure error for the platform triplet, please file a bug report I've also tried the suggestion in this stackoverflow post, however I ran into the same issue. Command - ...
[ "After researching the question I could not install python 3.6, the solution I found was that only a few versions could be installed, which is described here https://github.com/pyenv/pyenv/issues/2112, version 3.7.13 was installed without problems\n" ]
[ 0 ]
[]
[]
[ "macos", "pyenv", "python", "python_3.x" ]
stackoverflow_0073890842_macos_pyenv_python_python_3.x.txt
Q: Extracting date from another column to use for partition I am uploading some CSV files into a big query table. There is a column called filename which is in this format:sales_2021-09-09T21-27-05_010555Z I am trying to upload the data from google cloud storage into a partitioned table in the big query. Could you he...
Extracting date from another column to use for partition
I am uploading some CSV files into a big query table. There is a column called filename which is in this format:sales_2021-09-09T21-27-05_010555Z I am trying to upload the data from google cloud storage into a partitioned table in the big query. Could you help me to create the field below there is no date column and I ...
[ "To insert a date field, with the Python BigQuery client, you can pass a String date with the following format : 2022-09-09 :\nimport re\nfrom datetime import datetime\ntext = 'sales_2022-09-09T21-27-05_010555Z'\nmatch = re.search(r'\\d{4}-\\d{2}-\\d{2}', text)\nres_date = datetime.strptime(match.group(), '%Y-%m-%d...
[ 0 ]
[]
[]
[ "extract", "google_bigquery", "google_cloud_platform", "python" ]
stackoverflow_0074458776_extract_google_bigquery_google_cloud_platform_python.txt
Q: Weird python issue - increasing CPU usage overtime? I am making a video player using pygame, it takes numpy arrays of frames from a video file and streams them to a pygame window using a buffer. I'm getting a weird issue where CPU usage is increasing (program is slowing down) over time, then CPU usage is sharply d...
Weird python issue - increasing CPU usage overtime?
I am making a video player using pygame, it takes numpy arrays of frames from a video file and streams them to a pygame window using a buffer. I'm getting a weird issue where CPU usage is increasing (program is slowing down) over time, then CPU usage is sharply decreasing (program is speeding up). Memory usage stays pr...
[ "Ok, so i could reproduce what you describe (which was very easy with the sources you provided).\nRemoving the GC also did nothing for me, as you already observed.\nNow i did the following test: instead of getting each frame in order, i got a random frame from the video and recorded those times.\nHere's the (trivia...
[ 1, 1 ]
[]
[]
[ "opencv", "pygame", "python" ]
stackoverflow_0074445827_opencv_pygame_python.txt
Q: Not scrolling down in a website having dynamic scroll I'm scraping news-articles from a website where there is no load-more button in a specific category page, the news article links are being generated as I scroll down. I wrote a function which take input category_page_url and limit_page(how many times I want to ...
Not scrolling down in a website having dynamic scroll
I'm scraping news-articles from a website where there is no load-more button in a specific category page, the news article links are being generated as I scroll down. I wrote a function which take input category_page_url and limit_page(how many times I want to scroll down) and return me back all the links of the news a...
[ "Instead of scrolling using per body scrollHeight property, I checked to see if there was any appropriate element after the list of articles to scroll to. I noticed this appropriately named div:\n<div class=\"topic-content__load-more-anchor\" data-v-db98a5c0=\"\"></div>\n\nAccordingly, I primarily changed the while...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "selenium_webdriver", "web_crawler" ]
stackoverflow_0074443689_beautifulsoup_python_selenium_selenium_webdriver_web_crawler.txt
Q: Getting NULL values only from get_json_object in PySpark I have a Spark Dataframe (in Palantir Foundry) with the column "c_temperature". This column contains a JSON string in each row with the following schema: {"TempCelsiusEndAvg":"24.33","TempCelsiusEndMax":"null","TempCelsiusEndMin":"null","TempCelsiusStartAvg"...
Getting NULL values only from get_json_object in PySpark
I have a Spark Dataframe (in Palantir Foundry) with the column "c_temperature". This column contains a JSON string in each row with the following schema: {"TempCelsiusEndAvg":"24.33","TempCelsiusEndMax":"null","TempCelsiusEndMin":"null","TempCelsiusStartAvg":"22.54","TempCelsiusStartMax":"null","TempCelsiusStartMin":"n...
[ "You are don't need to do anything, since the column is already a struct. You can create those columns by accessing them with a .\n df = df.withColumn(\"TempCelsiusEndAvg\", F.col(\"c_temperature.TempCelsiusEndAvg\"))\n df = df.withColumn(\"TempCelsiusStartAvg\", F.col(\"c_temperature.TempCelsiusStartAvg\"))\n\n" ]
[ 3 ]
[]
[]
[ "dataframe", "json", "palantir_foundry", "pyspark", "python" ]
stackoverflow_0074457628_dataframe_json_palantir_foundry_pyspark_python.txt
Q: Improve an exponential curve fit of nearly exponential data I have recorded some data about the color of an LED that varies with the 8bit signal sent to the LED driver, the signal can vary between 0 and 255. Exponential curve fitting seems to work very well to represent the LED's behavior. I have had good results ...
Improve an exponential curve fit of nearly exponential data
I have recorded some data about the color of an LED that varies with the 8bit signal sent to the LED driver, the signal can vary between 0 and 255. Exponential curve fitting seems to work very well to represent the LED's behavior. I have had good results with the following formula: x * signal ** ex y * signal ** ey z...
[ "The data shows two steps in the log-log plot so I used an approach already used here.\nCode is as follows:\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import curve_fit\nsignal = np.array( [\n 3.0, 3.0, 3.0,\n 5.0, 5.0, 5.0,\n 7.0, 7.0, 7.0,\n 10.0, 10., 10.,\n...
[ 1 ]
[]
[]
[ "colors", "curve_fitting", "exponential", "led", "python" ]
stackoverflow_0074440462_colors_curve_fitting_exponential_led_python.txt
Q: How to use modify_transaction after send_raw_transaction in web3.py I am using Infura node, thus I had to sign the transaction with w3.eth.account.sign_transaction and then send it with w3.eth.send_raw_transaction. The gas that I used was too low apparently, and the transaction is pending for 8 hours now. By looki...
How to use modify_transaction after send_raw_transaction in web3.py
I am using Infura node, thus I had to sign the transaction with w3.eth.account.sign_transaction and then send it with w3.eth.send_raw_transaction. The gas that I used was too low apparently, and the transaction is pending for 8 hours now. By looking in the docs I noticed there are two methods that could help me w3.eth....
[ "You can use local account signing middleware with Web3.py so you do not need to use send_raw_transaction.\n", "Example of manually bumping up gas with Web3.py 5\nfrom web3.exceptions import TransactionNotFound\n\ntx, receipt = None, None\ntry: tx = w3.eth.get_transaction (tx_hash) # Not 100% reliable!\nexcept ...
[ 1, 0 ]
[]
[]
[ "ethereum", "python", "web3py" ]
stackoverflow_0072294891_ethereum_python_web3py.txt
Q: Add sufix on duplicates in pandas dataframe Python i am writing a script to download images. I'm reading a excel file as a pandas dataframe Column A -url links Column B - Name downloaded images will have this name, example "A.jpeg" There will be duplicates in Column B[Name] in that case i would like to add a suffi...
Add sufix on duplicates in pandas dataframe Python
i am writing a script to download images. I'm reading a excel file as a pandas dataframe Column A -url links Column B - Name downloaded images will have this name, example "A.jpeg" There will be duplicates in Column B[Name] in that case i would like to add a suffix on the image name. so the output will be A.jpeg A-1.Jp...
[ "You can try:\nimport requests\nimport pandas as pd\n\ndf = pd.read_excel(r\"C:\\Users\\exdata1.xlsx\")\ncnt = {}\n\nfor index, row in df.iterrows():\n name = row[\"name\"]\n if name not in cnt:\n cnt[name] = 0\n name = f\"{name}.jpeg\"\n else:\n cnt[name] += 1\n name = f\"{name...
[ 1 ]
[]
[]
[ "dataframe", "duplicates", "pandas", "python", "python_requests" ]
stackoverflow_0074457738_dataframe_duplicates_pandas_python_python_requests.txt
Q: Psycopg2 : Insert multiple values if not exists in the table I need to insert multiple values into a table after checking if it doesn't exist using psycopg2. The query am using: WITH data(name,proj_id) as ( VALUES ('hello',123),('hey',123) ) INSERT INTO keywords(name,proj_id) SELECT d.name,d.proj_id FROM data ...
Psycopg2 : Insert multiple values if not exists in the table
I need to insert multiple values into a table after checking if it doesn't exist using psycopg2. The query am using: WITH data(name,proj_id) as ( VALUES ('hello',123),('hey',123) ) INSERT INTO keywords(name,proj_id) SELECT d.name,d.proj_id FROM data d WHERE NOT EXISTS (SELECT 1 FROM keywords u2 WHERE u2.name=d.nam...
[ "As suggested in the comment, assuming that your connection is already established as conn one of the ways would be:\nfrom typing import Iterator, Dict, Any\n\ndef insert_execute_values_iterator(connection, keywords: Iterator[Dict[str, Any]], page_size: int = 1000) -> None:\n with connection.cursor() as cursor:\...
[ 1 ]
[ "insert_query = \"\"\"WITH data(name, proj_id) as (\n VALUES (%s,%s)\n ) \n INSERT INTO keywords(name, proj_id) \n SELECT d.name,d.proj_id FROM data d \n WHERE NOT EXISTS (\n SELECT 1 FROM keywords u2 \n ...
[ -1 ]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0074450641_postgresql_psycopg2_python.txt
Q: Multiple comparisons on an array of ints I have an array of ints mypos = np.array([10, 20, 30, 40, 50]) and a list of start & end positions, like this: mydelims = [[5, 12], [15,31], [12,16], [22,69]] I'd like to loop through mydelims and count how many positions are within eac...
Multiple comparisons on an array of ints
I have an array of ints mypos = np.array([10, 20, 30, 40, 50]) and a list of start & end positions, like this: mydelims = [[5, 12], [15,31], [12,16], [22,69]] I'd like to loop through mydelims and count how many positions are within each pair. Instinctively, I would write it like t...
[ "You were pretty close and looking for np.logical_and:\nimport numpy as np\n\nmypos = np.array([10, 20, 30, 40, 50])\n\nmydelims = [[5, 12],\n [15, 31],\n [12, 16],\n [22, 69]]\n\nresult = {\n tuple(mypair): sum(np.logical_and(mypos > mypair[0], mypos < mypair[1])) \n for mypa...
[ 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074459479_arrays_python.txt
Q: Matrix[i][j] index out of range for the 2D Matrix 1. Given A of size 4 × 3 and K = 1 with bird habitats at (0, 0), (2, 2) and (3, 1) the function should return 3. Wind turbines can be built in three locations: (0, 2), (1, 1) and (2, 0). In my code i have got an error of index out of range what should i can do to g...
Matrix[i][j] index out of range for the 2D Matrix
1. Given A of size 4 × 3 and K = 1 with bird habitats at (0, 0), (2, 2) and (3, 1) the function should return 3. Wind turbines can be built in three locations: (0, 2), (1, 1) and (2, 0). In my code i have got an error of index out of range what should i can do to get my desired output.in the given case out put should b...
[ "In Solution with the code you are making tuples for row and col...\n row=len(Matrix),\n col=len(Matrix[0]),\n K = K +1;\n\nChange your Code to actually save only the length as an int in your variable\nrow=len(Matrix)\ncol=len(Matrix[0])\nK = K +1\n\nNext Let's focus on this Part of your Mistake... This only works ...
[ 1, 0 ]
[]
[]
[ "list", "matrix", "python", "python_3.x", "tuples" ]
stackoverflow_0074445124_list_matrix_python_python_3.x_tuples.txt
Q: How to remove NaN values from pivot table only if each column has more than x NaN values? I have a pivot table that I create with the line pivot_table = pd.pivot_table(df, values='trip_duration', index=['day_of_month', 'hour'], columns='location_pair_id', aggfunc=np.mean, dropna=True), which looks like this: pivo...
How to remove NaN values from pivot table only if each column has more than x NaN values?
I have a pivot table that I create with the line pivot_table = pd.pivot_table(df, values='trip_duration', index=['day_of_month', 'hour'], columns='location_pair_id', aggfunc=np.mean, dropna=True), which looks like this: pivot table For each column, I want to impute the NaN values, but only if the entire column has les...
[ "You can count number of NaN values in each column, and filter out the column if the number is above 10 (or another value)\ncols = [col for col, no_na in pivot_table.isna().sum().items() if no_na <= 10]\npivot_table = pivot_table[cols]\n\n" ]
[ 0 ]
[]
[]
[ "imputation", "nan", "pandas", "pivot_table", "python" ]
stackoverflow_0074459390_imputation_nan_pandas_pivot_table_python.txt
Q: Can't change system default SQLite binary Using Django and SQLite I want to run most recent SQLite version; most recent SQLite binary, not the SQLite Python library. I have an SQLite binary that is not the system default and can't change the default version. I'm not using Django's ORM but replaced it with a standa...
Can't change system default SQLite binary
Using Django and SQLite I want to run most recent SQLite version; most recent SQLite binary, not the SQLite Python library. I have an SQLite binary that is not the system default and can't change the default version. I'm not using Django's ORM but replaced it with a standalone SQLAlchemy version. Related (but has to do...
[ "The simplest option if you just need a recent version of SQLite from python is now to install the pysqlite3 package:\npip install pysqlite3-binary\n\nThis comes with a recent version of SQLite statically-linked. You can use it in a venv without affecting any other package.\nYou can use it like this:\nfrom pysqlite...
[ 1, 0, 0 ]
[]
[]
[ "python", "sqlalchemy", "sqlite" ]
stackoverflow_0029282380_python_sqlalchemy_sqlite.txt
Q: How to subtract time in python? I'm using Python 3.10 and I'm trying to subtract two time values from each other. Now I have tried bunch of ways to do that but getting errors. day_time = timezone.now() day_name = day_time.strftime("%Y-%m-%d %H:%M:%S") end_Time = datetime.strptime(latest_slots.end_hour, '%Y-%m-%d %...
How to subtract time in python?
I'm using Python 3.10 and I'm trying to subtract two time values from each other. Now I have tried bunch of ways to do that but getting errors. day_time = timezone.now() day_name = day_time.strftime("%Y-%m-%d %H:%M:%S") end_Time = datetime.strptime(latest_slots.end_hour, '%Y-%m-%d %H:%M:%S') print(end_Time- day_name) ...
[ "Your second approach is almost right, but you should use\nday_time = datetime.now()\n\nWhen you subtract you will get a a datetime.timedelta object\nI think the issue with your second approach is that by using timezone you also have the timezone as part of the datetime, instead of just the date and time.\n", "Yo...
[ 0, 0, 0 ]
[]
[]
[ "python", "time" ]
stackoverflow_0074459253_python_time.txt
Q: How can I create and initialize a dictionary/JSON equivalent data structure in JSP? I have the following sample data: { "2022-37" : "2022-09-17 00:00:00.0", "2022-38" : "2022-09-24 00:00:00.0", "2022-39" : "2022-10-01 00:00:00.0", "2022-40" : "2022-10-08 00:00:00.0" } If this was python, I would c...
How can I create and initialize a dictionary/JSON equivalent data structure in JSP?
I have the following sample data: { "2022-37" : "2022-09-17 00:00:00.0", "2022-38" : "2022-09-24 00:00:00.0", "2022-39" : "2022-10-01 00:00:00.0", "2022-40" : "2022-10-08 00:00:00.0" } If this was python, I would create a dictionary like this, week_to_date_dict = { "2022-37" : "2022-09-17 00:00:00....
[ "You can initialze a HashMap and - only in a JSP - use it the same way:\nvar week_to_date_dict = new java.util.HashMap<String, String>() {\n {\n put(\"2022-37\", \"2022-09-17 00:00:00.0\");\n put(\"2022-38\", \"2022-09-24 00:00:00.0\");\n put(\"2022-39\", \"2022-10-01 00:00:00.0\");\n put(\"2022-40\", ...
[ 1 ]
[]
[]
[ "dictionary", "java", "json", "jsp", "python" ]
stackoverflow_0074457914_dictionary_java_json_jsp_python.txt
Q: How to continue a loop while being in a nested loop? I'm using a loop and a nested loop, and i need the outer loop to stop whenever the second reaches a certain value. for first in range(0,10): for second in range(0,10): print(first + second) But i want it to skip to the next 'first' value if the second val...
How to continue a loop while being in a nested loop?
I'm using a loop and a nested loop, and i need the outer loop to stop whenever the second reaches a certain value. for first in range(0,10): for second in range(0,10): print(first + second) But i want it to skip to the next 'first' value if the second value is odd. I tried to do something like this: odd = [1,3,5...
[ "break breaks out of the inner loop only, which jumps to the after the inner loop. Assuming that there’s no code immediately after the inner loop, then the current iteration of the outer loop will end and the next one will start.\nSo I think using break instead of continue should do exactly what you want.\n", "To...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074459602_python_python_3.x.txt
Q: Convert rows to columns and enter 0 and 1 for matches in python I have a pandas data frame like this: and I need to convert it into the below: So, the unique values in column 'camps' part of the original data set, gets turned into columns with values 0 and 1 for each id. How can I achieve this using Pandas or an...
Convert rows to columns and enter 0 and 1 for matches in python
I have a pandas data frame like this: and I need to convert it into the below: So, the unique values in column 'camps' part of the original data set, gets turned into columns with values 0 and 1 for each id. How can I achieve this using Pandas or anything else in Python? Any help is greatly appreciated. Thanks Below ...
[ "A possible solution, based on pd.crosstab:\npd.crosstab(cust_df.id, cust_df.camps)\n\nOutput:\ncamps :_Camp1_AS07_DS0722204H_DD02 ... :_Camp1_Over_EO4022202A_BD16\nid ... \n170365 1 ... 0\n2...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "pivot", "python" ]
stackoverflow_0074459402_dataframe_pandas_pivot_python.txt
Q: How skip a header in the next loop of writing data in csv file - Python I writting a script, where I dowload a data from json file (about temperature and data from datetime) and I want save the data i csv file. The script has a schedule set every minute to download new data from json. I have a problem with one thi...
How skip a header in the next loop of writing data in csv file - Python
I writting a script, where I dowload a data from json file (about temperature and data from datetime) and I want save the data i csv file. The script has a schedule set every minute to download new data from json. I have a problem with one thing. Running the code causes the data to write correctly, but each time with ...
[ "You need to write the header before the first row. So check the existence of the file to decide on writing the header.\n\nimport os \n\nfile_exists = os.path.exists('Temp.csv')\n\nwith open('Temp.csv', 'a', newline='') as file:\n fieldnames = ['Date', 'Temp']\n writer = csv.DictWriter(file, fieldnames=fieldn...
[ 0 ]
[]
[]
[ "csv", "python", "schedule" ]
stackoverflow_0074453744_csv_python_schedule.txt
Q: python3 dataclass with **kwargs(asterisk) Currently I used DTO(Data Transfer Object) like this. class Test1: def __init__(self, user_id: int = None, body: str = None): self.user_id = user_id self.body = body Example code is very small, But when object scale growing up, I have ...
python3 dataclass with **kwargs(asterisk)
Currently I used DTO(Data Transfer Object) like this. class Test1: def __init__(self, user_id: int = None, body: str = None): self.user_id = user_id self.body = body Example code is very small, But when object scale growing up, I have to define every variable. While digging into it...
[ "The basic use case for dataclasses is to provide a container that maps arguments to attributes. If you have unknown arguments, you can't know the respective attributes during class creation.\nYou can work around it if you know during initialization which arguments are unknown by sending them to a catch-all attribu...
[ 21, 10, 4, 1, 1, 0, 0 ]
[]
[]
[ "python", "python_3.7", "python_dataclasses" ]
stackoverflow_0055099243_python_python_3.7_python_dataclasses.txt
Q: youtube upload video, 403 when requesting None returned "Request had insufficient authentication scopes." I am trying to upload a video to youtube using python. Using the example code from https://developers.google.com/youtube/v3/docs/videos/insert I am getting an error while uploading. class YTService(): def _...
youtube upload video, 403 when requesting None returned "Request had insufficient authentication scopes."
I am trying to upload a video to youtube using python. Using the example code from https://developers.google.com/youtube/v3/docs/videos/insert I am getting an error while uploading. class YTService(): def __init__(self, credentials): # Youtube Credential self._YOUTUBE_SERVICE = build( YOUTUBE_API_SER...
[ "\nRequest had insufficient authentication scopes.\n\nMeans that your application has not requested the proper consent from the user\nThe videos.insert method requires that your application use an access token which has been authorized with one of the following scopes\n\nNow you have stated that you have those scop...
[ 0 ]
[]
[]
[ "python", "youtube_api", "youtube_data_api" ]
stackoverflow_0074459159_python_youtube_api_youtube_data_api.txt
Q: Python arrays for solving equations I am writing a simple solver for the heat equation to get used to the python programming language. The code I have is the following: for i in range(1,m): c=gamma*p*(q[i-1]+q[i]) rhs=np.matmul(B,np.transpose(u[i-1,:]))+np.transpose(c) sol=np.linalg.solve(A,rhs[0]) ...
Python arrays for solving equations
I am writing a simple solver for the heat equation to get used to the python programming language. The code I have is the following: for i in range(1,m): c=gamma*p*(q[i-1]+q[i]) rhs=np.matmul(B,np.transpose(u[i-1,:]))+np.transpose(c) sol=np.linalg.solve(A,rhs[0]) u[i,:]=np.transpose(sol) print('Simulati...
[ "in numpy you can define column vectors, row vectors and 2D matrices.\neg:\n>>> np.ones((1,4))\narray([[1., 1., 1., 1.]])\n\n>>> np.ones((4,1))\narray([[1.],\n [1.],\n [1.],\n [1.]])\n\n>>> np.ones((4,4))\narray([[1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1., 1., 1.],\n [1., 1....
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074459636_arrays_numpy_python.txt
Q: How minimize more equality constraints than independant variables in scipy I have this minimization problem: import numpy as np from scipy.optimize import Bounds, minimize, fmin_cobyla, linprog A = \ np.array([[ 0.106667, 0.1333, 0.1333, 0.01], [ 0.02, 0.6667, 0.1333, 0.12], [0.0933, 0....
How minimize more equality constraints than independant variables in scipy
I have this minimization problem: import numpy as np from scipy.optimize import Bounds, minimize, fmin_cobyla, linprog A = \ np.array([[ 0.106667, 0.1333, 0.1333, 0.01], [ 0.02, 0.6667, 0.1333, 0.12], [0.0933, 0.06667, 0.6, 0.01]]) B = \ np.array([[27], [57], [28]]) l...
[ "First of all, please note that all your vectors B, l, u, x0 have\ndimension 2 and should have dimension 1 instead. That's the same mistake\nas in your last question. Using np.arrays with wrong dimensions for vectors\nwill lead to surprising results due to numpy's broadcasting, so please\ntry to keep an eye on your...
[ 0 ]
[]
[]
[ "constraints", "minimize", "optimization", "python", "scipy" ]
stackoverflow_0074454084_constraints_minimize_optimization_python_scipy.txt
Q: How to get data from requests-cache I have CachedSession(backend='memory', expire_after=timedelta(days=1)) in my code. It works fine. But I want to use data from my cache, which contain in my memory. I looked for in doc, but unfortunately get nothing. Anybody know how to get cache-data? A: You can use the method...
How to get data from requests-cache
I have CachedSession(backend='memory', expire_after=timedelta(days=1)) in my code. It works fine. But I want to use data from my cache, which contain in my memory. I looked for in doc, but unfortunately get nothing. Anybody know how to get cache-data?
[ "You can use the methods of the CachedSession object(cache_session.cache.url) to loop through all the urls which are currently cached.\n\nYou can use CachedSession.cache.urls to see all URLs currently in the cache:\n\nsession = CachedSession()\nprint(session.cache.urls)\n>>> ['https://httpbin.org/get', 'https://htt...
[ 0 ]
[]
[]
[ "python", "python_requests", "request" ]
stackoverflow_0074459073_python_python_requests_request.txt
Q: Pandas and ValueError: time data '0' does not match format I can not figure out why I get the error "ValueError: time data '0' does not match format '%d.%m.%Y %H:%M' (match)" (or ..'%d.%m.%Y'). So, I have a test dataframe: Date DateCP Time kWh DT 0 01.11.2022 01.11.2022 01:00...
Pandas and ValueError: time data '0' does not match format
I can not figure out why I get the error "ValueError: time data '0' does not match format '%d.%m.%Y %H:%M' (match)" (or ..'%d.%m.%Y'). So, I have a test dataframe: Date DateCP Time kWh DT 0 01.11.2022 01.11.2022 01:00 0.693 01.11.2022 01:00 1 01.11.2022 01.11.2022 02:00 0.6...
[ "Because wrong data. Here is mixed datetimes with number 0, so if add errors='coerce' parameter pandas convert column to datetimes with NaT for not parseable dates.\nYou can check it:\nprint (df)\n Date DateCP Time kWh DT\n0 01.11.2022 01.11.2022 01:00 0.693 01.11.2022 01:00\n1...
[ 0 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074459574_dataframe_datetime_pandas_python.txt
Q: Change data cutoff frequency over time I have data with this structure Is there a way to change data cutoff frequency over time (on python side, not SQL) from 30-min slice to 1 hour, with an obligatory condition when changing slices, sum the value in the columns 'starts' and 'scooter_on_parking', but the rest of ...
Change data cutoff frequency over time
I have data with this structure Is there a way to change data cutoff frequency over time (on python side, not SQL) from 30-min slice to 1 hour, with an obligatory condition when changing slices, sum the value in the columns 'starts' and 'scooter_on_parking', but the rest of the values ​​should not change. Basic comman...
[ "Since after groupby you need an aggregation operation, the easiest way to apply a function to only some columns would be to use merge after groupby:\nnew_df = ( df.groupby(pd.Grouper(freq='1H', key='time_')).agg({'starts':'sum', \n 'scooters_on_parking':'sum'}).reset_index() )\nnew_df...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074459581_dataframe_pandas_python.txt
Q: Install Detectron2 on Windows 10 I try to install Facebook's Detectron2 followed this official repo. Following that repo, detectron2 can only install on linux. However, I'm working on a server run on Windows operator. Anybody know how to install it on Windows? A: Answer found through this issue: https://github.c...
Install Detectron2 on Windows 10
I try to install Facebook's Detectron2 followed this official repo. Following that repo, detectron2 can only install on linux. However, I'm working on a server run on Windows operator. Anybody know how to install it on Windows?
[ "Answer found through this issue: https://github.com/facebookresearch/detectron2/issues/9\nThese steps worked for me on my RTX 3070.\n\nInstall Anaconda https://docs.anaconda.com/anaconda/install/windows/\nCreate a environment.yml file containing the following code.\n\nname: detectron2\nchannels:\n - pytorch\n - ...
[ 8, 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "deep_learning", "object_detection_api", "python", "python_3.x", "pytorch" ]
stackoverflow_0060631933_deep_learning_object_detection_api_python_python_3.x_pytorch.txt
Q: How to convert a row of csv file into column using python I have this: There are six rows in csv file and I need to convert in this formate: convert into columns I tried convert a column into rows and I got successfully import pandas as pd x = pd.read_csv('source.csv', header=None) #reading it as csv for now colum...
How to convert a row of csv file into column using python
I have this: There are six rows in csv file and I need to convert in this formate: convert into columns I tried convert a column into rows and I got successfully import pandas as pd x = pd.read_csv('source.csv', header=None) #reading it as csv for now columns = x[0] #convert questions label column to list columns.tolis...
[ "As per the comment, try Transpose...\nimport pandas as pd\n\ndf = pd.read_csv('source.csv', header=None)\ndf.T\n\nOutputs:\n 0 1 2 3 4 5\n0 1 1-Jan-21 31-Jan-21 2021 31 FY21\n1 2 1-Feb-21 28-Feb-21 2021 28 FY22\n2 3 1-Mar-21 31-Mar-21 2021 31 ...
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074455614_csv_pandas_python.txt
Q: How to use Tweepy to retweet with a comment So i am stuck trying to figure out how to retweet a tweet with a comment, this was added to twitter recently. this is when you click retweet and add a comment to the retweet and retweet it. basically this is what i am talking about : i was looking at the api and count ...
How to use Tweepy to retweet with a comment
So i am stuck trying to figure out how to retweet a tweet with a comment, this was added to twitter recently. this is when you click retweet and add a comment to the retweet and retweet it. basically this is what i am talking about : i was looking at the api and count find a method dedicated to this. And even the ret...
[ "Tweepy doesn't have functionality to retweet with your own text, but what you can do is make a url like this https://twitter.com/<user_displayname>/status/<tweet_id> and include it with the text you want comment. It's not a retweet but you are embedding the tweet in your new tweet. \nuser_displayname - display nam...
[ 16, 4, 0 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0033619971_python_tweepy_twitter.txt
Q: how do you run pytest either from a notebook or command line on databricks? I have created some classes each of which takes a dataframe as a parameter. I have imported pytest and created some fixtures and simple assert methods. I can call pytest.main([.]) from a notebook and it will execute pytest from the rootdir...
how do you run pytest either from a notebook or command line on databricks?
I have created some classes each of which takes a dataframe as a parameter. I have imported pytest and created some fixtures and simple assert methods. I can call pytest.main([.]) from a notebook and it will execute pytest from the rootdir (databricks/driver). I have tried passing the notebook path but it says not foun...
[ "I've explained the reason why you can't run pytest on Databricks notebooks (unless you export them, and upload them to dbfs as regular .py files, which is not what you want) in the link at the bottom of this post.\nHowever, I have been able to run doctests in Databricks, using the doctest.run_docstring_examples me...
[ 2, 0 ]
[]
[]
[ "databricks", "pytest", "python", "unit_testing" ]
stackoverflow_0055119153_databricks_pytest_python_unit_testing.txt
Q: How to solve an equation that contains sigma sum to find the upper limit of sigma in Python I want to find an integer value from a sigma contained equation with two variables like this post where x (a real decimal value) range is between two limits e.g. known_xmin_value <= x < known_xmax_value. 1 is the lower lim...
How to solve an equation that contains sigma sum to find the upper limit of sigma in Python
I want to find an integer value from a sigma contained equation with two variables like this post where x (a real decimal value) range is between two limits e.g. known_xmin_value <= x < known_xmax_value. 1 is the lower limit of k (which is the integer) but don't know the upper limit (which is the goal to be derived fr...
[ "Since you are looking for a numerical solution, a naive approach would be a brute force over a set of integer_unknown_limit and use numerical root finding algorithms. For example:\nfrom sympy import *\nfrom scipy.optimize import root\nimport matplotlib.pyplot as plt\n\nx, k, integer_unknown_limit = symbols(\"x, k,...
[ 1, 1 ]
[]
[]
[ "equation_solving", "python", "solver", "sympy" ]
stackoverflow_0074456819_equation_solving_python_solver_sympy.txt
Q: scikit-learn train and test split returns NaNs my sample data looks like below customer_id revenue_m10 revenue_m9 revenue_m8 target 1 1234 1231 1256 1239 2 5678 3425 3255 2345 I am trying to split my dataset into train and test bas...
scikit-learn train and test split returns NaNs
my sample data looks like below customer_id revenue_m10 revenue_m9 revenue_m8 target 1 1234 1231 1256 1239 2 5678 3425 3255 2345 I am trying to split my dataset into train and test based on scikit-learn's train_test_split module. So, I ...
[ "y_test is a pandas Series, printing it displays its index and the data. It seems that sample_set_df has NaNs in its index.\nHaving NaNs in the index does not affect how train_test_split splits the data. You might have an issue with the actual data though. The target is 0 when you have NaNs.\n" ]
[ 1 ]
[]
[]
[ "data_mining", "machine_learning", "pandas", "python", "scikit_learn" ]
stackoverflow_0074456312_data_mining_machine_learning_pandas_python_scikit_learn.txt
Q: Getting 'Invalid query' error when doing name='test' to Google Drive API I am using PyDrive to fetch list of file names from a Google Drive folder from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = r"client_secrets.json" gauth = GoogleAut...
Getting 'Invalid query' error when doing name='test' to Google Drive API
I am using PyDrive to fetch list of file names from a Google Drive folder from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = r"client_secrets.json" gauth = GoogleAuth(settings_file='settings.yaml') drive = GoogleDrive(gauth) folder_id = "fol...
[ "When I saw the script of pydrive, it seems that Drive API v2 is used. Ref In the case of Drive API v2, the metadata of filename is title. I thought that this might be the reason of your current issue of Invalid query. So, how about the following modification?\nFrom:\n'q': \"name = 'test'\",\n\nTo:\n\"q\": \"title ...
[ 1 ]
[]
[]
[ "google_drive_api", "pydrive", "python" ]
stackoverflow_0074458200_google_drive_api_pydrive_python.txt
Q: im quite a beginner and i i got this error: RuntimeWarning: overflow encountered in exp y = A*np.exp(-1*B*x**2) import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def GaussFit(): xdata_raw = [0,24,22,20,18,16,14,12,10,8,6,4,2,-24,-22,-20,-18,-16,-14,-12,-10,-8,-6,-4,-2] ...
im quite a beginner and i i got this error: RuntimeWarning: overflow encountered in exp y = A*np.exp(-1*B*x**2)
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def GaussFit(): xdata_raw = [0,24,22,20,18,16,14,12,10,8,6,4,2,-24,-22,-20,-18,-16,-14,-12,-10,-8,-6,-4,-2] ydata_raw =[0.398,0.061,0.066,0.076,0.095,0.115,0.148,0.183,0.211,0.270,0.330,0.361,0.391,0.061,0.066,0.076,0.095,...
[ "y = A*np.exp(-1*B*x**2)\n\nMaybe try\ny = A*np.exp(-1*B*np.square(x))\n\nOr look at Python RuntimeWarning: overflow encountered in long scalars for a similar exception. Might be that you have to use a 64 bit type for y.\n", "Okay its solved, it wasnt the issue in the exp-funktion in particular.\nThe problem is s...
[ 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074446025_numpy_python.txt
Q: How to compress WAV file in python? I have converted MP3 files to WAV format but how can I compress WAV file to very small size less or same size that of MP3 size without changing the file format from pydub import AudioSegment import os # files ...
How to compress WAV file in python?
I have converted MP3 files to WAV format but how can I compress WAV file to very small size less or same size that of MP3 size without changing the file format from pydub import AudioSegment import os # files src_folder = "D:/projects/data/mp3" d...
[ "s1.export(\"output.mp3\", format='mp3', parameters=[\"-ac\",\"2\",\"-ar\",\"8000\"])\nThe line of code managed to reduce my audio size by half its previous size. Hope this is helpful to someone\n" ]
[ 0 ]
[]
[]
[ "mp3", "python", "wav" ]
stackoverflow_0074459969_mp3_python_wav.txt
Q: How to print the numbers for 0 to 10 in python and skip 5 and 8 between them I want to print a program using while loop in python numbers start from 0 to 10 but i want to skip 5 and 8 so the final result should be 0,1,2,3,4,6,7,9,10 i=0 while i<=10 : print(i) if i==5 or i==8 : break print(i) ...
How to print the numbers for 0 to 10 in python and skip 5 and 8 between them
I want to print a program using while loop in python numbers start from 0 to 10 but i want to skip 5 and 8 so the final result should be 0,1,2,3,4,6,7,9,10 i=0 while i<=10 : print(i) if i==5 or i==8 : break print(i) i+=1 i have tried this code but not successfully working
[ "You will continue your while loop instead of break, therefore you can use continue:\ni=0 \nwhile i<=10 :\n if i==5 or i==8 :\n i += 1\n continue\n print(i)\n i+=1\n\n" ]
[ 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074460047_python_while_loop.txt
Q: How to add timedelta on a subset of a dataframe I am trying to add a timedelta of 1 hour to a subset of my dataframe. I use df['2022-06-01 02:00:00':'2022-06-01 04:00:00'] to slice it and add + pd.Timedelta(hours=1) but I get an error. I want to add a timedelta only on `2022-06-01 02:00:00':'2022-06-01 04:00:00'. ...
How to add timedelta on a subset of a dataframe
I am trying to add a timedelta of 1 hour to a subset of my dataframe. I use df['2022-06-01 02:00:00':'2022-06-01 04:00:00'] to slice it and add + pd.Timedelta(hours=1) but I get an error. I want to add a timedelta only on `2022-06-01 02:00:00':'2022-06-01 04:00:00'. How can I achieve that? Solution can be either as dat...
[ "Solutions for DatetimeIndex:\nYou can create mask and rename values of index by Index.where:\nmask = (df.index >= '2022-06-01 02:00:00') & (df.index <= '2022-06-01 04:00:00')\ndf.index = df.index.where(~mask, df.index + pd.Timedelta(hours=1))\n\nOr get indices and use DataFrame.rename by dictionary:\ni = df['2022-...
[ 1 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074460066_datetime_pandas_python.txt
Q: Text file Converter (replacing unknown words) I started playing with Python and programming in general like 3 weeks ago so be gentle ;) What i try to do is convert text files the way i want them to be, the text files have same pattern but the words i want to replace are unknown. So the program must first find them...
Text file Converter (replacing unknown words)
I started playing with Python and programming in general like 3 weeks ago so be gentle ;) What i try to do is convert text files the way i want them to be, the text files have same pattern but the words i want to replace are unknown. So the program must first find them, set a pattern and then replace them to words i wa...
[ "welcome to the world of Python!\nI believe you are on the right track and are very close to the correct solution, however I see a couple of potential issues which may cause your program to not run as expected.\n\nIf you are trying to see if a string equals another, I would use == instead of is (see this answer for...
[ 0 ]
[]
[]
[ "converters", "python", "replace", "text" ]
stackoverflow_0074459798_converters_python_replace_text.txt
Q: How to turn a cell of dataframe into list of list, when another cell does not equals to a certain value? I have the following pandas dataframe Consideration_level | Consideration_value ------------------------------------------------- Car_ID 00111 Car_ID 00222 Car_...
How to turn a cell of dataframe into list of list, when another cell does not equals to a certain value?
I have the following pandas dataframe Consideration_level | Consideration_value ------------------------------------------------- Car_ID 00111 Car_ID 00222 Car_type, Location Jeep, NYC Car_Color, Location Pink, BOS I want to turn it into Considerat...
[ "You can refer below answers :\ni have used map and lambda function\nSolution\nimport pandas as pd\nimport numpy as np\nConsideration_level=['Car_ID','Car_ID','Car_type, Location','Car_type, Location']\nConsideration_value=['00111','00222','Jeep, NYC','Pink, BOS']\ndata_dict = {'Consideration_level':Consideration_l...
[ 0 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074453260_dataframe_list_pandas_python.txt
Q: tqdm format remaining time I'm running a very long process, and iterating by with tqdm(total=N) as pbar: time.sleep(1) pbar.update(1) displays something like 0%| | 528912/1.1579208923731618e+77 [00:05<320918211271131291051900907686223146304413317191111137850058393514584:44:48, 100226.38it/s ...
tqdm format remaining time
I'm running a very long process, and iterating by with tqdm(total=N) as pbar: time.sleep(1) pbar.update(1) displays something like 0%| | 528912/1.1579208923731618e+77 [00:05<320918211271131291051900907686223146304413317191111137850058393514584:44:48, 100226.38it/s [Quite a big combinatorial pro...
[ "It's been a while, but for the sake of completiness, here it goes:\nclass TqdmExtraFormat(tqdm):\n @property\n def format_dict(self):\n d = super(TqdmExtraFormat, self).format_dict\n rate = d[\"rate\"]\n remaining_secs = (d[\"total\"] - d[\"n\"]) / rate if...
[ 0, 0 ]
[]
[]
[ "customization", "python", "tqdm" ]
stackoverflow_0070035937_customization_python_tqdm.txt
Q: UVa 458 - The Decoder: Python runtime error Here's my code while True: try: a = input() except EOFError: break print(''.join([chr(ord(i) - 7) for i in a])) I saw the same question in this website before. This is the link: UVa problem 458 - The Decoder python runtime error But it seems...
UVa 458 - The Decoder: Python runtime error
Here's my code while True: try: a = input() except EOFError: break print(''.join([chr(ord(i) - 7) for i in a])) I saw the same question in this website before. This is the link: UVa problem 458 - The Decoder python runtime error But it seems doesn't work. I've tried every thing I know. It ...
[ "So the Python runtime error comes from chr(ord(i) - 7) as ord(i) - 7 might become negative. If you limit the values to the range (0, 128), this should not produce the error.\nI'd assume that encoding is mod128-based, so chr((ord(i) - 7) % 128). Unfortunately, this gives a \"Wrong answer\" on \"online judge\".\nThe...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074459570_python.txt
Q: How to convert jpg file to tiff file in python? The conversion of .jpg file to .tiff file in python. I have tried the following two approaches but while using the output tiff file in my project, it doesn't support it. import aspose.words as aw doc = aw.Document() builder = aw.DocumentBuilder(doc) shape = builder...
How to convert jpg file to tiff file in python?
The conversion of .jpg file to .tiff file in python. I have tried the following two approaches but while using the output tiff file in my project, it doesn't support it. import aspose.words as aw doc = aw.Document() builder = aw.DocumentBuilder(doc) shape = builder.insert_image("0.jpg") shape.image_data.save("/TIFFs/...
[ "If you go to the PIL documentation about TIFF format\nhttps://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#tiff\nYou will notice that it says:\nNote\n\nBeginning in version 5.0.0, Pillow requires libtiff to read or write compressed files. \nPrior to that release, Pillow had buggy support for re...
[ 0 ]
[]
[]
[ "file_conversion", "jpeg", "python", "tiff" ]
stackoverflow_0074459609_file_conversion_jpeg_python_tiff.txt
Q: Extract Json Data with Python My Jason Data looks like this: { "componentId": "SD1:1100047938", "componentType": "Device", "name": "WR50MS15-7938 (WR 33)", "product": "SB 5000TL", "productTagId": 9037, "pvPower": 886, "serial": "1100047938", "specWhOutToday": 3.0909803921568626,...
Extract Json Data with Python
My Jason Data looks like this: { "componentId": "SD1:1100047938", "componentType": "Device", "name": "WR50MS15-7938 (WR 33)", "product": "SB 5000TL", "productTagId": 9037, "pvPower": 886, "serial": "1100047938", "specWhOutToday": 3.0909803921568626, "specWhOutYesterday": 2.924313...
[ "import requests\nimport json\nimport urllib3\nimport sys\nimport requests\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\nfehler = '\"state\": 35'\nurltoken = \"https://172.16.63.100/api/v1/token\"\nurldaten = \"https://172.16.63.100/api/v1/overview/Plant:1/devices?todayDate=2022-10-17T12...
[ 1, 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074098501_json_python.txt
Q: How can I intergrate my django app to an alredy made database, probably from a PHP app this is part of the database. The extention is .sql -- phpMyAdmin SQL Dump -- version 3.2.0.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: May 20, 2011 at 05:08 PM -- Server version: 5.1.36 -- PHP Versi...
How can I intergrate my django app to an alredy made database, probably from a PHP app
this is part of the database. The extention is .sql -- phpMyAdmin SQL Dump -- version 3.2.0.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: May 20, 2011 at 05:08 PM -- Server version: 5.1.36 -- PHP Version: 5.2.9-2 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=...
[ "Django can read legacy databases and even auto-generate the models for them,\nconnect to the db from settings and then run this command from your terminal\npython manage.py inspectdb\n\nit will print the models and you can use it as normal Django models\n", "To interpret these values in django you must look care...
[ 1, 0 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0074453409_database_django_mysql_python.txt
Q: AWS Glue Job : An error occurred while calling getCatalogSource. None.get I was using Password/Username in my aws glue conenctions and now I switched to Secret Manager. Now I get this error when I run my etl job : An error occurred while calling o89.getCatalogSource. None.get Even tho the connections and crawler...
AWS Glue Job : An error occurred while calling getCatalogSource. None.get
I was using Password/Username in my aws glue conenctions and now I switched to Secret Manager. Now I get this error when I run my etl job : An error occurred while calling o89.getCatalogSource. None.get Even tho the connections and crawlers works : The Connection Image. (I added the connection to the job details) ...
[ "I have faced a similar issue. In my case it was not able to find the table at specified location. It looks to be same, Try checking the entities you have provided like db-name, table name etc. Should work !!\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_glue", "aws_glue_data_catalog", "data_lake", "python" ]
stackoverflow_0073778532_amazon_web_services_aws_glue_aws_glue_data_catalog_data_lake_python.txt
Q: How do I split a string into separate lists? I am given this as a string: Orville Wright 21 July 1988 \n Rogelio Holloway 13 September 1988 \n Marjorie Figueroa 9 October 1988 \n I need to separate the names from the dates and print it like this: Birthdate: 21 July 1988 \n 13 September 1988 \n 9 October 1988 \n e...
How do I split a string into separate lists?
I am given this as a string: Orville Wright 21 July 1988 \n Rogelio Holloway 13 September 1988 \n Marjorie Figueroa 9 October 1988 \n I need to separate the names from the dates and print it like this: Birthdate: 21 July 1988 \n 13 September 1988 \n 9 October 1988 \n etc.. I tried to save the string into a variable a...
[ "You can use regex for this problem:\nimport re\nstr = 'Orville Wright 21 July 1988 \\n Rogelio Holloway 13 September 1988 \\n Marjorie Figueroa 9 October 1988 \\n'\nBirthdate = re.findall(r'(\\d+ \\w+ \\d+)', str)\n>>> ['21 July 1988', '13 September 1988', '9 October 1988']\n\n", "Assuming this is how the conten...
[ 1, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0074460056_python_split.txt
Q: How to load SQL file into dbt macro using jinja include command? I have a dbt macro where I am trying to load a stand-alone sql file. I would then like to execute the SQL statement that I loaded by calling my macro. I am attempting to use jinja's include statement. # test_sql_macro.sql {% macro test_sql_macro() -...
How to load SQL file into dbt macro using jinja include command?
I have a dbt macro where I am trying to load a stand-alone sql file. I would then like to execute the SQL statement that I loaded by calling my macro. I am attempting to use jinja's include statement. # test_sql_macro.sql {% macro test_sql_macro() -%} {%- if execute -%} {%- call statement('do_stuff', fetch_resul...
[ "dbt doesn't support jinja's include tag.\nAs a workaround, you can use a macro to \"import\" other sql statements into the jinja context.\nFor example:\nUse a macro to hold arbitrary sql statements.\n{% macro my_query() %}\n\n drop table if exists films cascade;\n\n create table films (\n film_id inte...
[ 2 ]
[]
[]
[ "dbt", "jinja2", "python", "snowflake_cloud_data_platform", "sql" ]
stackoverflow_0074453543_dbt_jinja2_python_snowflake_cloud_data_platform_sql.txt
Q: What is the difference between radd() and add( ) method of data frames in pandas? import pandas as pd student = {'unit test-1':[5,6,8,3,10],'unit Test-2':[7,8,9,6,15]} student1 = {'unit test-1':[3,3,6,6,8],'unit Test-2':[5,9,8,10,5]} print(ds.radd(ds1)) print(ds.add(ds1)) When I am performing addition operation ...
What is the difference between radd() and add( ) method of data frames in pandas?
import pandas as pd student = {'unit test-1':[5,6,8,3,10],'unit Test-2':[7,8,9,6,15]} student1 = {'unit test-1':[3,3,6,6,8],'unit Test-2':[5,9,8,10,5]} print(ds.radd(ds1)) print(ds.add(ds1)) When I am performing addition operation on dataframe by using add() and radd() methods then output is same of both methods. uni...
[ "The result is equivalent. You can say 'A' is added to 'B' or you can say 'B' is added to 'A'. It's really a convenience function depending on how you visualize the element-wise addition taking place.\nLinks to the Panda's Documentation: .add, .radd\n", "Firstly i got confused with these methods too.\nThe real ...
[ 3, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0066182815_pandas_python.txt
Q: PLC , DIGITAL COUNTER newbie here. I work in a factory that produce electric cables. I'm trying to build a web application that will handle production processes. For this i need some real time data. There are multiple types of machines , some of them are older and uses a lot of digital counters like this on: https...
PLC , DIGITAL COUNTER
newbie here. I work in a factory that produce electric cables. I'm trying to build a web application that will handle production processes. For this i need some real time data. There are multiple types of machines , some of them are older and uses a lot of digital counters like this on: https://mirror2.mixtronica.com/4...
[ "From what I understand you want to read and send data to the machines, correct? Because there are some simpler approaches than having to build an IoT application from scratch.\nRecently I've been studying solutions like this and the best alternative I've looked at is using Thingsboard (which can be installed local...
[ 0 ]
[]
[]
[ "automation", "counter", "digital", "plc", "python" ]
stackoverflow_0074459148_automation_counter_digital_plc_python.txt
Q: I want to remove ' from numpy I want to remove the value of '' while creating the numpy array In the following situation, how can I remove the quotation mark that comes out by multiplying the 'character' by 0 and leave only 'character'? import numpy as np array = np.array(['character'*1,'character'*0]) Expected ...
I want to remove ' from numpy
I want to remove the value of '' while creating the numpy array In the following situation, how can I remove the quotation mark that comes out by multiplying the 'character' by 0 and leave only 'character'? import numpy as np array = np.array(['character'*1,'character'*0]) Expected array(['character'], dtype='<U9') n...
[ "You can solve this in different ways,\nhere is one example:\nimport numpy as np\n\narray = np.array([ele for ele in ['character'*1,'character'*0] if len(ele) > 0])\n# or\narray = np.array([ele for ele in ['character'*1,'character'*0] if ele != ''])\n\nAnd to get your method working:\narray = np.delete(array, array...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074460299_numpy_python.txt
Q: How to convert current time from a specific format to epoch time in python? My current time format is in "Wednesday, November 16, 2022 4:21:33.082 PM GMT+05:30" format. How can I convert this to epoch time using python? Here in this case the epoch time should be "1668595893082" Note: I always want to get my curren...
How to convert current time from a specific format to epoch time in python?
My current time format is in "Wednesday, November 16, 2022 4:21:33.082 PM GMT+05:30" format. How can I convert this to epoch time using python? Here in this case the epoch time should be "1668595893082" Note: I always want to get my current time format in the above format and then convert that to epoch. Please guide me...
[ "I have used dateutil in the past, it can parse textual dates into datetime.datetime objects (from the inbuilt datetime package)\nFirst you need to install it:\npip install python-dateutil\nThen you can use it like so:\nfrom dateutil import parser\n\n# extract datetime object from string\ndttm = parser.parse('Wedne...
[ 1, 1 ]
[]
[]
[ "epoch", "python" ]
stackoverflow_0074460090_epoch_python.txt
Q: convert sentences in a column to list in pandas dataframe My current dataframe looks like this A header Another header First i like apple Second alex is friends with jack I am expecting A header Another header First [i, like, apple] Second [alex, is, friends, with, jack] How can I accomplish this efficient...
convert sentences in a column to list in pandas dataframe
My current dataframe looks like this A header Another header First i like apple Second alex is friends with jack I am expecting A header Another header First [i, like, apple] Second [alex, is, friends, with, jack] How can I accomplish this efficiently?
[ "You can use standard str operations on the column:\ndf['Another header'] = df['Another header'].str.split()\n\n", "Use Series.str.split:\ndf['Another header'] = df['Another header'].str.split()\n\n", "You can use map with a lambda function\ndf['Another header'] = list(map(lambda x: x.split(' '), df['Another he...
[ 2, 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074460346_dataframe_pandas_python_python_3.x.txt
Q: subsetting anndata on basis of louvain clusters I want to subset anndata on basis of clusters, but i am not able to understand how to do it. I am running scVelo pipeline, and in that i ran tl.louvain function to cluster cells on basis of louvain. I got around 32 clusters, of which cluster 2 and 4 is of my interest...
subsetting anndata on basis of louvain clusters
I want to subset anndata on basis of clusters, but i am not able to understand how to do it. I am running scVelo pipeline, and in that i ran tl.louvain function to cluster cells on basis of louvain. I got around 32 clusters, of which cluster 2 and 4 is of my interest, and i have to run the pipeline further on these clu...
[ "If your adata.obs has a \"louvain\" column that I'd expect after running tl.louvain, you could do the subsetting as\nadata[adata.obs[\"louvain\"] == \"2\"]\nif you want to obtain one cluster and\nadata[adata.obs['louvain'].isin(['2', '4'])]\nfor obtaining cluster 2 & 4.\n", "Feel free to use this function I wrot...
[ 3, 0 ]
[]
[]
[ "python", "rna_seq", "scanpy" ]
stackoverflow_0063916137_python_rna_seq_scanpy.txt
Q: How to display csv data in tabular form in Flask Python? I'm making a web app using the Flask framework with python, I want to make the web able to upload csv without saving and displaying data in a table with the template I made, I've added the syntax for uploading and processing the data until it's in a table vi...
How to display csv data in tabular form in Flask Python?
I'm making a web app using the Flask framework with python, I want to make the web able to upload csv without saving and displaying data in a table with the template I made, I've added the syntax for uploading and processing the data until it's in a table view, but after running the website it goes to the 404 not found...
[ "If you are requesting /upload and getting a 404. This is natural. You have added a handler for /upload endpoint:\n@app.route('/upload', methods=['POST', 'GET'])\ndef uploadFile():\n ...\n\nBut uploadFile only supports POST requests. When you enter localhost/upload into the browser, the browser sends a GET requ...
[ 1 ]
[]
[]
[ "flask", "html", "pandas", "python", "read.csv" ]
stackoverflow_0074458071_flask_html_pandas_python_read.csv.txt
Q: How do I get a value from a json array using a key I'm reading a json and want to get the label field with a specific id. What I currently have is: with open("local_en.json") as json_file: parsed_dict = json.load(json_file) print(parsed_dict) # works print(parsed_dict["interface...
How do I get a value from a json array using a key
I'm reading a json and want to get the label field with a specific id. What I currently have is: with open("local_en.json") as json_file: parsed_dict = json.load(json_file) print(parsed_dict) # works print(parsed_dict["interface"]) # works print(parsed_dict["interface"...
[ "You can \"find\" the element in the interface list via a list-comprehension, and fetch the label from that element. For instance:\nlabel = [x['label'] for x in parsed_dict['interface'] if x['id'] == 'testkey'][0]\n\nIf you cannot assume that the relevant id exists, then you can wrap this in a try-except, or you ca...
[ 1, 1 ]
[]
[]
[ "arrays", "json", "python" ]
stackoverflow_0074460376_arrays_json_python.txt
Q: Conda command not found I've installed Miniconda and have added the environment variable export PATH="/home/username/miniconda3/bin:$PATH" to my .bashrc and .bash_profile but still can't run any conda commands in my terminal. Am I missing another step in my setup? I'm using zsh by the way. A: If you're using zsh...
Conda command not found
I've installed Miniconda and have added the environment variable export PATH="/home/username/miniconda3/bin:$PATH" to my .bashrc and .bash_profile but still can't run any conda commands in my terminal. Am I missing another step in my setup? I'm using zsh by the way.
[ "If you're using zsh and it has not been set up to read .bashrc, you need to add the Miniconda directory to the zsh shell PATH environment variable. Add this to your .zshrc:\nexport PATH=\"/home/username/miniconda/bin:$PATH\"\n\nMake sure to replace /home/username/miniconda with your actual path.\nSave, exit the te...
[ 249, 79, 41, 29, 28, 17, 16, 11, 7, 5, 4, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ "MacOSX: cd /Users/USER_NAME/anaconda3/bin && ./activate \n" ]
[ -1 ]
[ "anaconda", "miniconda", "python", "zsh" ]
stackoverflow_0035246386_anaconda_miniconda_python_zsh.txt
Q: Python Module To Convert JUnit XML Report to Pretty Console Output I am running android gradle tests which outputs a generic JUnit XML Report as shown below. I am trying to ideally find a Python extension or easy method to also print these results to console. I am capable of converting the XML to html with Python ...
Python Module To Convert JUnit XML Report to Pretty Console Output
I am running android gradle tests which outputs a generic JUnit XML Report as shown below. I am trying to ideally find a Python extension or easy method to also print these results to console. I am capable of converting the XML to html with Python plugins which is useful in certain scenarios. But this is not ideal as i...
[ "Write custom code to handle this situation\ndef main(xml_path):\n tree = ET.parse(xml_path)\n root = tree.getroot()\n\n for child in root.iter():\n\n if child.tag == \"testsuite\":\n # Add code for all cases, via `child.attrib or child.text`\n\n\n" ]
[ 0 ]
[]
[]
[ "junit", "python", "python_3.x", "xml" ]
stackoverflow_0074424877_junit_python_python_3.x_xml.txt
Q: Python Selenium, checking if element is present. and if it was present I want it to return a boolean value of TRUE Python Selenium, checking if element is present. and if it was present I want it to return a boolean value of TRUE Here is the HTML Code: <td data-id="329083" data-property="status" xe-field="status" ...
Python Selenium, checking if element is present. and if it was present I want it to return a boolean value of TRUE
Python Selenium, checking if element is present. and if it was present I want it to return a boolean value of TRUE Here is the HTML Code: <td data-id="329083" data-property="status" xe-field="status" class="readonly" data-content="Status" style="width: 8%; display: none;" title=" FULL: 0 of 20 seats remain."><div class...
[ "The element attribute containing desired data is title.\nSo, the first code can be fixed as following:\nstatus = driver.find_element(By.XPATH,\"/html/body/main/div[3]/div/div[2]/div/div[1]/div/div[2]/div[3]/div[2]/div[1]/div[1]/div[1]/div/table/tbody/tr/td[11]\").text\nstatus.get_attribute(\"title\")\nif \"FULL\" ...
[ 0 ]
[]
[]
[ "automation", "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074460352_automation_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: How to consecutively chain `dropna()` and `to_datetime()` in pandas, accounting for `SettingWithCopyWarning`? In a pandas DataFrame, I'd like to accomplish two clean-up steps: Drop any row with missing values; and Convert a date column from DD.MM.YYYY pattern to standard YYYY-MM-DD I do know the answer for each ...
How to consecutively chain `dropna()` and `to_datetime()` in pandas, accounting for `SettingWithCopyWarning`?
In a pandas DataFrame, I'd like to accomplish two clean-up steps: Drop any row with missing values; and Convert a date column from DD.MM.YYYY pattern to standard YYYY-MM-DD I do know the answer for each step separately: dropping missing values can be achieved with pandas.dropna() converting DD.MM.YYYY string to YYYY...
[ "Use DataFrame.assign for chain to_datetime with DataFrame.dropna:\ndf = my_df.dropna().assign(dob = lambda x: pd.to_datetime(x['dob'], format='%d.%m.%Y'))\nprint (df)\n name dob\n0 John 2001-12-20\n1 Melinda 1991-03-11\n2 Greg 1999-12-31\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074460147_dataframe_datetime_pandas_python.txt
Q: regex : how to keep relevant words and remove other? The original output looks like this: JOBS column: {"/j/03k50": "Waitress Job", "/j/055qm": "Programmer Job", "/j/02h40lc": "Marketing Job"} {"/j/03k50": "Waitress Job", "/j/055qm": "Programmer Job", "/j/02h40lc": "Marketing Job"} {"/j/055qm": "Programmer Job", "...
regex : how to keep relevant words and remove other?
The original output looks like this: JOBS column: {"/j/03k50": "Waitress Job", "/j/055qm": "Programmer Job", "/j/02h40lc": "Marketing Job"} {"/j/03k50": "Waitress Job", "/j/055qm": "Programmer Job", "/j/02h40lc": "Marketing Job"} {"/j/055qm": "Programmer Job", "/j/02h40lc": "Marketing Job"} ` And I want something lik...
[ "As per the comment...there are far better ways of doing this. However, as a rough example direct to the question asked...\nimport pandas as pd\n\ndata = ['{\"/j/03k50\": \"Waitress Job\", \"/j/055qm\": \"Programmer Job\", \"/j/02h40lc\": \"Marketing Job\"}',\n'{\"/j/03k50\": \"Waitress Job\", \"/j/055qm\": \"Prog...
[ 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074453314_json_pandas_python.txt
Q: Django Get Last Object for each Value in List I have a model called Purchase, with two fields, User and amount_spent. This is models.py: class Purchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount_spent = models.IntegerField() created_at = models.DateTimeField(auto_now...
Django Get Last Object for each Value in List
I have a model called Purchase, with two fields, User and amount_spent. This is models.py: class Purchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount_spent = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) I want to get the last purchases from a...
[ "try this:\nPurchase.objects.filter(user__in=list_of_users).values(\"user_id\", \"amount_spent\").order_by(\"-id\").distinct(\"user_id\")\n\n", "You can annotate the Users with the last_purchase_pks and then fetch these and adds that to these users:\nfrom django.db.models import OuterRef, Subquery\n\nusers = User...
[ 2, 1 ]
[]
[]
[ "django", "django_database", "django_models", "python" ]
stackoverflow_0074460191_django_django_database_django_models_python.txt
Q: Creating sum of date ranges in Pandas I have the following DataFrame, with over 3 million rows: VALID_FROM VALID_TO VALUE 0 2022-01-01 2022-01-02 5 1 2022-01-01 2022-01-03 2 2 2022-01-02 2022-01-04 7 3 2022-01-03 2022-01-06 3 I want to create one large date_range with a sum of the values fo...
Creating sum of date ranges in Pandas
I have the following DataFrame, with over 3 million rows: VALID_FROM VALID_TO VALUE 0 2022-01-01 2022-01-02 5 1 2022-01-01 2022-01-03 2 2 2022-01-02 2022-01-04 7 3 2022-01-03 2022-01-06 3 I want to create one large date_range with a sum of the values for each timestamp. For the DataFrame above t...
[ "If performance is important use Index.repeat with DataFrame.loc for new rows, create date colun with counter by GroupBy.cumcount and last aggregate sum:\ndf['VALID_FROM'] = pd.to_datetime(df['VALID_FROM'])\ndf['VALID_TO'] = pd.to_datetime(df['VALID_TO'])\n\ndf1 = df.loc[df.index.repeat(df['VALID_TO'].sub(df['VALID...
[ 3, 1 ]
[]
[]
[ "dataframe", "date_range", "datetime", "pandas", "python" ]
stackoverflow_0074460294_dataframe_date_range_datetime_pandas_python.txt
Q: How to pull any cells from a table/dataframe into a column if they contain specific string? I am using Python in CoLab and I am trying to find something that will allow me to move any cells from a subset of a data frame into a new/different column in the same data frame OR sort the cells of the dataframe into the ...
How to pull any cells from a table/dataframe into a column if they contain specific string?
I am using Python in CoLab and I am trying to find something that will allow me to move any cells from a subset of a data frame into a new/different column in the same data frame OR sort the cells of the dataframe into the correct columns. The original column in the CSV looked like this: and using Users[['Motorbike', '...
[ "Use list comprehension with split for dictionaries, then pass to DataFrame constructor:\nL = [dict([y.split() for y in x.split(',')])\n for x in df['What distance did you travel in the last month by:']]\n\ndf = pd.DataFrame(L)\nprint (df)\n Taxi Motorbike Car Train Bus Tram\n...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "sorting" ]
stackoverflow_0074459952_dataframe_pandas_python_sorting.txt
Q: How to release GPU memory in tensorflow? (opposite of `allow_growth` → `allow_shrink`?) I'm using a GPU to train quite a lot of models. I want to tune the architecture of the network, so I train different models sequentially to compare their performances (I'm using keras-tuner). The problem is that some models are...
How to release GPU memory in tensorflow? (opposite of `allow_growth` → `allow_shrink`?)
I'm using a GPU to train quite a lot of models. I want to tune the architecture of the network, so I train different models sequentially to compare their performances (I'm using keras-tuner). The problem is that some models are very small, and some others are very large. I don't want to allocate all the GPU memory to m...
[ "You can try by limiting GPU memory growth using this code:\nimport tensorflow as tf\ngpus = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(gpus[0], True)\n\nThe second method is to configure a virtual GPU device with tf.config.set_logical_device_configuration and set ...
[ 0 ]
[]
[]
[ "gpu", "gpu_managed_memory", "python", "tensorflow" ]
stackoverflow_0074190403_gpu_gpu_managed_memory_python_tensorflow.txt
Q: Understanding exception handling in with statement in python I am trying to understand the with statement in python but I don't get how it does exception handling. For example, we have this code file = open('file-path', 'w') try: file.write('Lorem ipsum') finally: file.close() and then this code with...
Understanding exception handling in with statement in python
I am trying to understand the with statement in python but I don't get how it does exception handling. For example, we have this code file = open('file-path', 'w') try: file.write('Lorem ipsum') finally: file.close() and then this code with open('file_path', 'w') as file: file.write('hello world !') ...
[ "When using with statements, __exit__ will be called whenever we leave the with block, regardless of if we leave it due to exception or if we just finished executing contained code normally.\nIf any code contained in the with block causes an exception, it will cause the __exit__ to run and then propagate the except...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074460466_python.txt
Q: where can I see algorithms/codes used for wavelet transforms in the PyWavelets module? I would like a clear description of algorithms in pywavelets for several decompositions (transfo & inverse transfo if not obvious). Does anyone know or know where to find that ? update november, 17, 2022 sorry I wasn't clear en...
where can I see algorithms/codes used for wavelet transforms in the PyWavelets module?
I would like a clear description of algorithms in pywavelets for several decompositions (transfo & inverse transfo if not obvious). Does anyone know or know where to find that ? update november, 17, 2022 sorry I wasn't clear enough : I need to try several transformations in fortran. That's why I was hoping a CLEAR des...
[ "You can find them here:\nhttps://github.com/PyWavelets/pywt\nI am not sure if this is what you meant and if you are using this version.\n" ]
[ 0 ]
[]
[]
[ "python", "pywavelets" ]
stackoverflow_0074431540_python_pywavelets.txt
Q: Assigning node names to a graph in networkx I'm trying to generate a networkx graph from a dataframe using the code below: import pandas as pd import numpy as np import networkx as nx data = [[0,0,0,1], [1,0,0,1], [1,0,0,1], [0,0,0,0]] df = pd.DataFrame(data, columns=['S1', 'S2', 'S3', 'S4']) df.index = ['S1', 'S...
Assigning node names to a graph in networkx
I'm trying to generate a networkx graph from a dataframe using the code below: import pandas as pd import numpy as np import networkx as nx data = [[0,0,0,1], [1,0,0,1], [1,0,0,1], [0,0,0,0]] df = pd.DataFrame(data, columns=['S1', 'S2', 'S3', 'S4']) df.index = ['S1', 'S2', 'S3', 'S4'] G = nx.DiGraph(df.values, with_l...
[ "The renaming should be a mapping that has old node identifiers as keys and new node identifier as values (a dictionary, basically):\nmapping = {0: \"S1\", 1: \"S2\", 2: \"S3\", 3: \"S4\"}\nH = nx.relabel_nodes(G, mapping)\nprint(H.nodes)\n# ['S1', 'S2', 'S3', 'S4']\n\n" ]
[ 1 ]
[]
[]
[ "networkx", "numpy", "pandas", "python", "python_3.x" ]
stackoverflow_0074459925_networkx_numpy_pandas_python_python_3.x.txt
Q: Copy a Azure table (SAS) to a db on Microsoft SQL Server Just that: Is there a way to copy a azure table (with SAS connection) to a db on Microsoft SQL Server? It could be possible with python? Thank you all! I've tried on SSIS visual studio 2019 with no success A: You can use **azure data factory ** or azure sy...
Copy a Azure table (SAS) to a db on Microsoft SQL Server
Just that: Is there a way to copy a azure table (with SAS connection) to a db on Microsoft SQL Server? It could be possible with python? Thank you all! I've tried on SSIS visual studio 2019 with no success
[ "You can use **azure data factory ** or azure synapse to copy the data from azure table storage to azure SQL database. Refer MS document on Introduction to Azure Data Factory - Azure Data Factory | Microsoft Learn if you are new to data factory.\nRefer MS document on Copy data to and from Azure Table storage - Azur...
[ 0 ]
[]
[]
[ "azure", "python", "sql_server" ]
stackoverflow_0074307453_azure_python_sql_server.txt
Q: Pytest dependency - make one function to be dependent on the other @pytest.mark.parametrize('feed', ['C', 'D']) @pytest.mark.parametrize('file', ['foo.txt', 'boo.txt', 'doo.txt']) def test_1(feed: Path, file: str): assert (Path(feed / file).is_file()), 'Not file' @pytest.mark.parametrize('feed_C, feed_D', [('...
Pytest dependency - make one function to be dependent on the other
@pytest.mark.parametrize('feed', ['C', 'D']) @pytest.mark.parametrize('file', ['foo.txt', 'boo.txt', 'doo.txt']) def test_1(feed: Path, file: str): assert (Path(feed / file).is_file()), 'Not file' @pytest.mark.parametrize('feed_C, feed_D', [('C', 'D')]) @pytest.mark.parametrize('file', ['foo.txt', 'boo.txt', 'doo...
[ "You don't need a separate test just two check if the paths are valid, you can do it in the same test. You also shouldn't create dependency between tests\n@pytest.mark.parametrize('feed_C, feed_D', [('C:', 'D:')])\n@pytest.mark.parametrize('file', ['foo.txt', 'boo.txt', 'doo.txt'])\ndef test(feed_C: Path, feed_D: P...
[ 0 ]
[]
[]
[ "dependencies", "pytest", "python" ]
stackoverflow_0074460436_dependencies_pytest_python.txt
Q: How do I use python to find a number of unique groups such that each subset within the group has at most X elements from a given array of Y? This is the problem but I do not fully understand what I need to do, especially the functions of n and m I have tried looking for the patterns to use but I am stuck So far I ...
How do I use python to find a number of unique groups such that each subset within the group has at most X elements from a given array of Y?
This is the problem but I do not fully understand what I need to do, especially the functions of n and m I have tried looking for the patterns to use but I am stuck So far I have written def howManyGroups (n,m): if n >= 2: Return 2 else: This is my first time posting a question so I am sorr...
[ "You could try the following:\ndef how_many_groups(n, m):\n m = min(m, n)\n if n == 0 or m <= 1:\n return 1\n return how_many_groups(n, m - 1) + how_many_groups(n - m, m)\n\nThe logic, as far as I understand the requirement:\n\nBase cases: (1) If there are no elements then there's only one way (n ==...
[ 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074458831_python_recursion.txt