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 make the tkinter objects appear live? i am creating the balls like this from tkinter import * import random import time colors = ["red", "blue", "purple", "green", "violet", "black"] tk = Tk() tk.title("Random balls") canvas = Canvas(tk, width = 600, height = 600, bg = "white") for i in range(10): x0...
How to make the tkinter objects appear live?
i am creating the balls like this from tkinter import * import random import time colors = ["red", "blue", "purple", "green", "violet", "black"] tk = Tk() tk.title("Random balls") canvas = Canvas(tk, width = 600, height = 600, bg = "white") for i in range(10): x0 = random.randint(0, 600) y0 = random.rand...
[ "You can tell your tkinter application to call a function after x time in milliseconds. This function can contain the code for creating the circles:\nfrom tkinter import *\nimport random \nimport time\n\ndef create_circles():\n for i in range(10):\n x0 = random.randint(0, 600) \n y0 = random.randi...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074344128_python_tkinter.txt
Q: why do I get an "AttributeError: 'NoneType' object has no attribute 'group' while doing language translation using googletrans? While trying to translate any language to English using googletrans I am getting an error stating "AttributeError: 'NoneType' object has no attribute 'group" Below is the code for refere...
why do I get an "AttributeError: 'NoneType' object has no attribute 'group' while doing language translation using googletrans?
While trying to translate any language to English using googletrans I am getting an error stating "AttributeError: 'NoneType' object has no attribute 'group" Below is the code for reference: from googletrans import Translator import pandas as pd translator = Translator() df = pd.DataFrame({'Spanish':['piso','cama']}) ...
[ "It is due to a bug in version 3.0.0. To make it work, you can either upgrade to the latest pre-release version 4.0.0rc1:\npip install --upgrade googletrans==4.0.0rc1\n\nor use another library such as google_trans_new:\npip install google-trans-new\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074344115_python.txt
Q: Can't Access configparser environment variables from env.ini file in faust (kafka streaming) My Project is on FastAPI and the structure goes like this. - project - app - kafka_layer - faustworker.py - core - configs.py - env.ini My env.ini file goes like this [DEFAULT] DATABASE_URL=...
Can't Access configparser environment variables from env.ini file in faust (kafka streaming)
My Project is on FastAPI and the structure goes like this. - project - app - kafka_layer - faustworker.py - core - configs.py - env.ini My env.ini file goes like this [DEFAULT] DATABASE_URL=url_to_db I've tried adding this code in configs.py import configparser config = configparser.Co...
[ "I was trying to run faust worker in a docker container going to the folder\neg:\ncd app\ncd kafka_layer\nfaust -A faust_worker\n\nBut What I needed to do is\nfaust -A app.kafka_layer.faust_worker\n\nIt works totally fine now. :)\n" ]
[ 0 ]
[]
[]
[ "configparser", "environment_variables", "fastapi", "faust", "python" ]
stackoverflow_0074318059_configparser_environment_variables_fastapi_faust_python.txt
Q: how to iterate over each row in pyspark dataframe I have a dataframe like: name address result rishi los angeles true tushar california false keerthi texas false I want to iterate through each row of the dataframe and check if result value is "true" or "false" if true i want to cop...
how to iterate over each row in pyspark dataframe
I have a dataframe like: name address result rishi los angeles true tushar california false keerthi texas false I want to iterate through each row of the dataframe and check if result value is "true" or "false" if true i want to copy the address to another address new column and if fals...
[ "This line should work to filter the data:\nnew_df = df[df['result'] == True]\n\nIn terms of the new address, a list comprehension could be used.\ndf['address_new'] = [df.loc[i]['address'] if df.loc[i] == True else None for i in range(df.shape[0])]\n\n", "You can use when() for this purpose, I'd suggest reading u...
[ 1, 0 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074344241_pyspark_python.txt
Q: Getting blocked trying to scrape google search results I am using python and BeautifulSoup to scrape through google search results. But I run into captchas as soon as I make more than 10 requests. I tried using python requests library and passing user agent, giving proxy, sleeps, verify=False, and every imaginable...
Getting blocked trying to scrape google search results
I am using python and BeautifulSoup to scrape through google search results. But I run into captchas as soon as I make more than 10 requests. I tried using python requests library and passing user agent, giving proxy, sleeps, verify=False, and every imaginable thing just to get rid of these captchas but they just don't...
[ "If you are making a large number of requests for web scraping a website, it's a good idea to make each request look random by sending a different set of HTTP headers (user-agent rotation) to make it look like the request is coming from different computers/different browser:\nimport requests, random\n\nuser_agent_l...
[ 2 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074235199_python_web_scraping.txt
Q: Python: How to convert a long datetime string to required format I have this time here : 2017-08-05T05:21:10.6582942Z And I want to convert it into %Y-%m-%d %H:%M:%S I can do that using some funky methods such as : date = "2017-08-05T05:21:10.6582942Z" new_date = date[:11] + " " + date[12:][:-9] But is there any ...
Python: How to convert a long datetime string to required format
I have this time here : 2017-08-05T05:21:10.6582942Z And I want to convert it into %Y-%m-%d %H:%M:%S I can do that using some funky methods such as : date = "2017-08-05T05:21:10.6582942Z" new_date = date[:11] + " " + date[12:][:-9] But is there any way I can do something cleaner with datetime or some libraries made fo...
[ "Using the datetime library with the strptime method (for parsing) and the strftime method (for formatting), this can be accomplished with no splits and limited slicing as:\nfrom datetime import datetime as dt\n\ndate = '2017-08-05T05:21:10.6582942Z'\noutput = dt.strptime(date[:-2], '%Y-%m-%dT%H:%M:%S.%f').strftime...
[ 1, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074344124_datetime_python.txt
Q: How to sum two columns and assign the value to another column in Django models I have a Stock table in models and I want to add the sum of two columns(thus, balance b/d and received) and assign the value to another column(thus, total bal) for each item, and use it for another calculation. Please can someone help m...
How to sum two columns and assign the value to another column in Django models
I have a Stock table in models and I want to add the sum of two columns(thus, balance b/d and received) and assign the value to another column(thus, total bal) for each item, and use it for another calculation. Please can someone help me? I tried this in models.py: class Stock(models.Model): # user = models.Foreign...
[ "My proposition is to use computed properties instead of model attributes.\nThe difference between the two is that computed properties are NOT stored as a DB table column and are calculated in the Python code every time you access them. Regular model attributes represent table columns and are stored in the DB.\nIf ...
[ 0 ]
[]
[]
[ "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074326513_django_forms_django_models_django_views_python.txt
Q: Unable to access the shared mailbox after authenticated - User is authenticated but not connected I am trying to create a daemon app that reads a shared mailbox. The app is registered in Azure and I am getting an access token, but when I try to access the inbox, I am getting the following error. 26:14.88 < b'CKLI1...
Unable to access the shared mailbox after authenticated - User is authenticated but not connected
I am trying to create a daemon app that reads a shared mailbox. The app is registered in Azure and I am getting an access token, but when I try to access the inbox, I am getting the following error. 26:14.88 < b'CKLI1 OK AUTHENTICATE completed.' 26:14.88 > b'CKLI2 SELECT inbox' 26:14.88 < b'CKLI2 BAD User is authentica...
[ "The error \"User is Authenticated but not Connected\" usually occurs if the user doesn't have permissions to access the server by IMAP or if the MFA is enabled.\nCheck whether the IMAP protocol is enabled for the user like below:\n\nAnd check whether the user have required licenses to access IMAP.\nI tried to repr...
[ 0 ]
[]
[]
[ "azure", "oauth_2.0", "python" ]
stackoverflow_0074318775_azure_oauth_2.0_python.txt
Q: Extracting all values from the numpy.ndarray in python I have a numpy.ndarray as a result below [[0.13291089 0.02370989 0.00735158 ... 0.00724766 0.00437995 0.05021806] [0.12048984 0.02036897 0.01536853 ... 0.01494439 0.01646584 0.05641633] [0.22271137 0.10474296 0.10984567 ... 0.09325695 0.11456841 0.18628386] ...
Extracting all values from the numpy.ndarray in python
I have a numpy.ndarray as a result below [[0.13291089 0.02370989 0.00735158 ... 0.00724766 0.00437995 0.05021806] [0.12048984 0.02036897 0.01536853 ... 0.01494439 0.01646584 0.05641633] [0.22271137 0.10474296 0.10984567 ... 0.09325695 0.11456841 0.18628386] ... [0.8874626 0.70929044 0.6762439 ... 0.51335114 0.590...
[ "You can use .flatten() for this:\nIn [1]: arr\nOut[1]: \narray([[1, 2],\n [3, 4]])\n\nIn [2]: arr.flatten()\nOut[2]: array([1, 2, 3, 4])\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074344551_python.txt
Q: Open-Cv dnn error for python while using Yolov3. Using open-cv ver(4.2.0) cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\dnn\src\darknet\darknet_io.cpp:677: error: (-212:Parsing error) Unknown layer type: in function 'cv::dnn::darknet::ReadDarknetFromCfgStream Code: import cv2 import numpy as ...
Open-Cv dnn error for python while using Yolov3. Using open-cv ver(4.2.0)
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\dnn\src\darknet\darknet_io.cpp:677: error: (-212:Parsing error) Unknown layer type: in function 'cv::dnn::darknet::ReadDarknetFromCfgStream Code: import cv2 import numpy as np # Load Yolo path =r"D:\yolov3-coco" weight = path+r"\yolov3.weights" cfg = ...
[ "Maybe yolo3-coco cfg and weight do not match so Unknown layer type error.\n", "You seem to be passing *.weights first and *.cfg later. If takes *.cfg first, then the darknet weights file. Reference for readNetFromDarknet,\nhttps://docs.opencv.org/master/d6/d0f/group__dnn.html#gafde362956af949cce087f3f25c6aff0d\n...
[ 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "opencv", "python", "yolo" ]
stackoverflow_0061969311_opencv_python_yolo.txt
Q: Copy PySpark Dataframe to MySQL I am trying to load a dataframe created with PySpark in DataBricks to MySql but it tells me: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure df_videojuegos.select("Nombre", "Plataforma", "Año", "Genero", "Editorial", "Ventas NA", "Ventas EU", "Ven...
Copy PySpark Dataframe to MySQL
I am trying to load a dataframe created with PySpark in DataBricks to MySql but it tells me: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure df_videojuegos.select("Nombre", "Plataforma", "Año", "Genero", "Editorial", "Ventas NA", "Ventas EU", "Ventas JP", "Ventas Otros", "Ventas Glob...
[ "Ok, the error was a newbie, I was trying to connect from DataBricks to a localhost! :C\n" ]
[ 1 ]
[]
[]
[ "mysql", "pyspark", "python" ]
stackoverflow_0074320481_mysql_pyspark_python.txt
Q: Why am i getting the result expected in scapy? import scapy.all as scapy p = scapy.sniff(filter='tcp', count=1) d = p.show() print(scapy.hexraw(d)) RESULT: AttributeError: module 'scapy.all' has no attribute 'hexraw' Why am i getting this error A: hexraw is a method of the PacketList class not a function of ...
Why am i getting the result expected in scapy?
import scapy.all as scapy p = scapy.sniff(filter='tcp', count=1) d = p.show() print(scapy.hexraw(d)) RESULT: AttributeError: module 'scapy.all' has no attribute 'hexraw' Why am i getting this error
[ "hexraw is a method of the PacketList class not a function of scapy.all. Moreover, the show method of the Packet class returns None: it prints something to the standard output but does not return anything. So doing d = p.show() does not make any sense. I don't know what your goal initially was, but you could try...
[ 0 ]
[]
[]
[ "python", "scapy" ]
stackoverflow_0074326301_python_scapy.txt
Q: Replace specific data frame rows with consecutive list values I can't find the solution to this apparently simple problem. I have a large dataframe. Every time a 0 appears in the index column it means that the data comes from a different source. I would like to substitute the first '0' with the first element of m...
Replace specific data frame rows with consecutive list values
I can't find the solution to this apparently simple problem. I have a large dataframe. Every time a 0 appears in the index column it means that the data comes from a different source. I would like to substitute the first '0' with the first element of my list until the next '0'. The second '0' with the second list elem...
[ "This answer assumes that sessions_list is same length as the no of 0 in index column.\n>>> import pandas as pd\n>>>\n>>>\n>>> d = {\n... \"Index\": [\"0\", \"1\", \"0\", \"1\", \"0\", \"1\", \"2\", \"3\"],\n... \"user_id\": [\"id11\", \"id54\", \"id544\", \"id659\", \"id18\", \"id549\", \"id59\", \"id59\"...
[ 0, 0 ]
[]
[]
[ "dataframe", "list", "python", "replace" ]
stackoverflow_0074344323_dataframe_list_python_replace.txt
Q: Django REST Framework - Separate permissions per methods I am writing an API using Django REST Framework and I am wondering if can specify permissions per method when using class based views. Reading the documentation I see that is quite easy to do if you are writing function based views, just using the @permissio...
Django REST Framework - Separate permissions per methods
I am writing an API using Django REST Framework and I am wondering if can specify permissions per method when using class based views. Reading the documentation I see that is quite easy to do if you are writing function based views, just using the @permission_classes decorator over the function of the views you want to...
[ "Permissions are applied to the entire View class, but you can take into account aspects of the request (like the method such as GET or POST) in your authorization decision.\nSee the built-in IsAuthenticatedOrReadOnly as an example:\nSAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']\n\nclass IsAuthenticatedOrReadOnly(BaseP...
[ 74, 54, 20, 14, 6, 6, 6, 2, 1, 0 ]
[]
[]
[ "django", "django_rest_framework", "permissions", "python", "rest" ]
stackoverflow_0019773869_django_django_rest_framework_permissions_python_rest.txt
Q: How do I raise a FileNotFoundError properly? I use a third-party library that's fine but does not handle inexistant files the way I would like. When giving it a non-existant file, instead of raising the good old FileNotFoundError: [Errno 2] No such file or directory: 'nothing.txt' it raises some obscure message:...
How do I raise a FileNotFoundError properly?
I use a third-party library that's fine but does not handle inexistant files the way I would like. When giving it a non-existant file, instead of raising the good old FileNotFoundError: [Errno 2] No such file or directory: 'nothing.txt' it raises some obscure message: OSError: Syntax error in file None (line 1) I do...
[ "Pass in arguments:\nimport errno\nimport os\n\nraise FileNotFoundError(\n errno.ENOENT, os.strerror(errno.ENOENT), filename)\n\nFileNotFoundError is a subclass of OSError, which takes several arguments. The first is an error code from the errno module (file not found is always errno.ENOENT), the second the erro...
[ 173, 0 ]
[]
[]
[ "file_not_found", "python", "python_3.x" ]
stackoverflow_0036077266_file_not_found_python_python_3.x.txt
Q: convert into number of years based on experience in string using python I have a column with data like 9 years 3 months 22 days. How to convert it into =9+(3/12)+(22/365) =9.31 I want output as 9.31. How to do the same in python? Please anyone can help me out? A: If leaps years are not important extract values b...
convert into number of years based on experience in string using python
I have a column with data like 9 years 3 months 22 days. How to convert it into =9+(3/12)+(22/365) =9.31 I want output as 9.31. How to do the same in python? Please anyone can help me out?
[ "If leaps years are not important extract values by Series.str.extract and count new column by multiple with dictionary and sum values:\ndf = pd.DataFrame({'col': ['9 years 3 months 22 days',\n '3 YEARS 6 MONTHS', \n '4 YEARS', \n '3 YEAR...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074343895_pandas_python.txt
Q: Unable to match desired schema for api Im unable to formulate accurately enough this PUT request to the GoDaddy v1 domains api to update my A record. The only data point that needs to be updated is the ip address...... Im using python. My code and error are reproduced below. Also. Another question I have is whethe...
Unable to match desired schema for api
Im unable to formulate accurately enough this PUT request to the GoDaddy v1 domains api to update my A record. The only data point that needs to be updated is the ip address...... Im using python. My code and error are reproduced below. Also. Another question I have is whether I should be passing all the form values fo...
[ "What worked for me was within the Mulesoft API Designer, under Data Types, setting required to False.\nHow to set Data Types to not required\n\n" ]
[ 0 ]
[]
[]
[ "api", "dictionary", "dns", "python" ]
stackoverflow_0071627558_api_dictionary_dns_python.txt
Q: Hide gridlines with the Google Sheets API in Python I want to remove all the gridlines in my google sheet. I think I need to use batchupdate in combination with a JSON request that sets the hideGridlines in gridProperties to True but I can't seem to get it to work. Anyone knows how to do this? This is what I have ...
Hide gridlines with the Google Sheets API in Python
I want to remove all the gridlines in my google sheet. I think I need to use batchupdate in combination with a JSON request that sets the hideGridlines in gridProperties to True but I can't seem to get it to work. Anyone knows how to do this? This is what I have so far but it gives an error about not having a sheet nam...
[ "I thought that in your showing request body, it is required to modify the value of fields as follows.\nFrom:\n\"fields\": \"*\",\n\nTo:\n\"fields\": \"gridProperties.hideGridlines\",\n\nReference:\n\nUpdateSheetPropertiesRequest\n\n" ]
[ 0 ]
[]
[]
[ "google_sheets", "google_sheets_api", "gspread", "gspread_formatting", "python" ]
stackoverflow_0074343823_google_sheets_google_sheets_api_gspread_gspread_formatting_python.txt
Q: After copying Quill editor contents into hidden field, how to access value with flask request? Trying to use Quill.js. But cannot seem to retrieve contents of editor using flask request. Here is the relevant HTML <form class='form-horizontal' method='POST' id="inputform" action="/page/update/{{ data._...
After copying Quill editor contents into hidden field, how to access value with flask request?
Trying to use Quill.js. But cannot seem to retrieve contents of editor using flask request. Here is the relevant HTML <form class='form-horizontal' method='POST' id="inputform" action="/page/update/{{ data._id }}"> . . . <div class="form-group"> <div id="edit...
[ "From the code,\nvar form = document.getElementById('inputform');\nform.onsubmit = function() {\n// Populate hidden form on submit\nvar hiddenBody = document.querySelector('hiddenArea');\nvar html = document.querySelector('.ql-editor').innerHTML;\nhiddenBody.value = html;\n\non line 4,\nchange var hiddenBody = docu...
[ 0 ]
[]
[]
[ "flask", "html", "javascript", "python", "quill" ]
stackoverflow_0074070876_flask_html_javascript_python_quill.txt
Q: Match keys in json file with csv files I'm new to programing and I'm currently working on my thesis. I'm working with multiple csv files and a json file containing genes with amino acid changes involved in antibiotic resistance. The csv files are formatted like this: Gene_Aminoacids Filename gyrA_S95T SRR9851427...
Match keys in json file with csv files
I'm new to programing and I'm currently working on my thesis. I'm working with multiple csv files and a json file containing genes with amino acid changes involved in antibiotic resistance. The csv files are formatted like this: Gene_Aminoacids Filename gyrA_S95T SRR9851427 tlyA_L11L SRR9851427 katG_R463L SRR98514...
[ "Let me introduce you to Pandas\n\npandas is a software library written for the Python programming\nlanguage for data manipulation and analysis\n\nHere is the approch\n*#step0 ---> raeding csv file\n#step1 -->reading json in text file\n#step2 --->merging csv & Json\n#step3 ---> filling empty values with above val...
[ 0 ]
[]
[]
[ "key", "match", "python" ]
stackoverflow_0074344427_key_match_python.txt
Q: matplotlib - plt.figure() freezes I have function that renders some plot and then saves it to png file. Simplified code: def render_plot(self, parameter1, parameter2): dates = get_my_dates() values = get_my_values() fig = plt.figure() # freezes here when calling render_plot for the 2nd or 3rd time! ...
matplotlib - plt.figure() freezes
I have function that renders some plot and then saves it to png file. Simplified code: def render_plot(self, parameter1, parameter2): dates = get_my_dates() values = get_my_values() fig = plt.figure() # freezes here when calling render_plot for the 2nd or 3rd time! ax = fig.add_subplot(111) ... # ...
[ "fig = plt.figure() will cause the freeze for my PyQt5 as well.\nI don't exactly know the reasons, but I have found a nice workaround that works for me.\nWorkaround:\nfrom matplotlib. Figure import Figure\nfig1 = Figure()\nax1 = fig1.add_subplot()\n" ]
[ 0 ]
[ "This is probably not the reason but first, you do not need \nax=fig.add_subplot(111)\n\nTry just \nax = plt.gca()\n\nThen, comment \nplt.close()\n\nIt may help. Just a guess.\n" ]
[ -1 ]
[ "matplotlib", "python", "python_3.3" ]
stackoverflow_0024110556_matplotlib_python_python_3.3.txt
Q: Loading a .sav file in google collab Im creating a simple python program in google colab wherein i have to import/load a .sav file in the code which is saved at my google drive. i tried mounting google drive locally, installing pyreadstat, but it still shows the error "PyreadstatError: File /sales.sav does not ex...
Loading a .sav file in google collab
Im creating a simple python program in google colab wherein i have to import/load a .sav file in the code which is saved at my google drive. i tried mounting google drive locally, installing pyreadstat, but it still shows the error "PyreadstatError: File /sales.sav does not exist!" my code: # Machine Problem 2 impor...
[ "Unfortunately Pyreadstat cannot read files on remote drives, network drives, etc. You will need to somehow move the file to a local drive.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074214114_python.txt
Q: Generate a simulated dataset in pandas I would like to generate pandas dataframes with simulated data. There should be x sets of columns. Each set corresponds to y number of columns. Each set should have a value, a, in z number of rows. The value, a, is a float. However, z may be different for the different sets o...
Generate a simulated dataset in pandas
I would like to generate pandas dataframes with simulated data. There should be x sets of columns. Each set corresponds to y number of columns. Each set should have a value, a, in z number of rows. The value, a, is a float. However, z may be different for the different sets of column sets. The remaining columns will ha...
[ "Use numpy.random.choice:\nN = 5 #No of rows\nx = 3 #(set1, set2, set3) \ny = 2 #(col1, col2 for each set) \na = 0.5 \nz = 1 #(for all column sets)\nb = 0.1 \n\n#names of sets\nsets = [f'set{w+1}' for w in range(x)]\n#names of columns\ncols = [f'col{w+1}' for w in range(y)]\n#MultiIndex by product\nmux = pd.Mul...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074344218_pandas_python.txt
Q: pyplot plot freezes (not responding) I am struggling with pyplot from the matlpotlib library. The figure freezes already when I try to create the plot: plt.figure() plt.ion() ax1 = plt.subplot(211) #Here it freezes plt.title('test', fontsize=8) plt.xlim(-1700, 1700) plt.ylabel('x-axis') plt.xlabel('y-axis') plt.gr...
pyplot plot freezes (not responding)
I am struggling with pyplot from the matlpotlib library. The figure freezes already when I try to create the plot: plt.figure() plt.ion() ax1 = plt.subplot(211) #Here it freezes plt.title('test', fontsize=8) plt.xlim(-1700, 1700) plt.ylabel('x-axis') plt.xlabel('y-axis') plt.grid() plt.show() ...do something else I ha...
[ "Is this one working as you want it?\nimport matplotlib.pyplot as plt\n\nplt.figure()\nplt.ion()\nax1 = plt.subplot(211) #Here it freezes\nplt.title('test', fontsize=8)\nplt.xlim(-1700, 1700)\nplt.ylabel('x-axis')\nplt.xlabel('y-axis')\nplt.grid()\nplt.draw() # draw the plot\nplt.pause(5) # show it for 5 seconds\np...
[ 3, 2, 0, 0 ]
[]
[]
[ "freeze", "matplotlib", "plot", "python" ]
stackoverflow_0044262242_freeze_matplotlib_plot_python.txt
Q: How can I solve attribute error for Pandas : "AttributeError: module 'pandas' has no attribute 'Float64Dtype"? I am trying to read a .sav file. For this, I have installed pyreadstat using conda install -c conda-forge pyreadstat but when I run the following line of code (before even getting to reading the file): i...
How can I solve attribute error for Pandas : "AttributeError: module 'pandas' has no attribute 'Float64Dtype"?
I am trying to read a .sav file. For this, I have installed pyreadstat using conda install -c conda-forge pyreadstat but when I run the following line of code (before even getting to reading the file): import pyreadstat I get this error: "AttributeError: module 'pandas' has no attribute 'Float64Dtype' ". Any ideas on...
[ "Pyreadstat requires Pandas 1.2.0 at the very minimum. Please try updating pandas to a newer version.\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "pandas", "python" ]
stackoverflow_0074102025_attributeerror_pandas_python.txt
Q: os.path.getmtime when file doesn't exist How do I set a variable to None or null when the file doesn't exist for example: lastModified = os.path.getmtime("/xyz.csv") if os.path.getmtime("/xyz.csv") is not None else null So I would like lastModified variable to be the time the file was last modified when the file ...
os.path.getmtime when file doesn't exist
How do I set a variable to None or null when the file doesn't exist for example: lastModified = os.path.getmtime("/xyz.csv") if os.path.getmtime("/xyz.csv") is not None else null So I would like lastModified variable to be the time the file was last modified when the file exists else to be null when it doesn't exist. ...
[ "Use exists function from os.path module:\nfrom os.path import getmtime, exists\n\nfile_path = './file.txt'\nlast_mod = getmtime(file_path) if exists(file_path) else None\nprint(last_mod)\n\n", "from os.path import exists\n\nfile_exists = exists(path_to_file)\nif file_exists:\n lastModified = os.path.getmtime(...
[ 5, 3 ]
[]
[]
[ "os.path", "python" ]
stackoverflow_0074344819_os.path_python.txt
Q: except* fails on unhashable exceptions - documented behaviour or a bug? Consider the following code block: class MyException(Exception): __hash__ = None try: raise ExceptionGroup("Foo", [ MyException("Bar") ]) except* Exception: pass The except* should catch any number of exceptions of an...
except* fails on unhashable exceptions - documented behaviour or a bug?
Consider the following code block: class MyException(Exception): __hash__ = None try: raise ExceptionGroup("Foo", [ MyException("Bar") ]) except* Exception: pass The except* should catch any number of exceptions of any kind, thrown together as an ExceptionGroup (or a single exception of any ki...
[ "This was reported at https://github.com/python/cpython/issues/99181 and we have a PR to fix it. Should be fixed in 3.11.1.\n" ]
[ 1 ]
[ "I wouldn't really call it a bug; it's the programmer fault for breaking the promise Exception class makes (implementing __hash__ method); therefore it's programmer who is responsible for making sure things work as intended after doing this. After all, would you call following snippet a \"bug\" or \"programmer mist...
[ -2 ]
[ "exception", "python", "python_3.11", "python_3.x" ]
stackoverflow_0074313762_exception_python_python_3.11_python_3.x.txt
Q: Fine-tuning SentenceTransformer on text classification task Wish to fine-tune SentenceTransformer model with multi-class labeled dataset for text classification. Tutorials seen so far need a specific format as a training data, such as list of positive triplets such as (senetnce1, sentence2, 1) and list of negative...
Fine-tuning SentenceTransformer on text classification task
Wish to fine-tune SentenceTransformer model with multi-class labeled dataset for text classification. Tutorials seen so far need a specific format as a training data, such as list of positive triplets such as (senetnce1, sentence2, 1) and list of negative triplets such as (senetnce1, senetnce3, 0). A typical classifica...
[ "If you have small number of samples, ie. for few-shots-training, SetFit can be used\nIf you have large number of samples for fine-tuning, there is unsupervised way called TSDAE.\n" ]
[ 0 ]
[]
[]
[ "huggingface_transformers", "nlp", "python", "sentence_transformers", "text_classification" ]
stackoverflow_0074261744_huggingface_transformers_nlp_python_sentence_transformers_text_classification.txt
Q: Plotly Colorbar orientation not changing I used the code of the solution of the following stackoverflow question but the colorbar does not rotate. It only changes the position. The line fig.update_traces(colorbar = dict(orientation='h', y = -0.25, x = 0.5)) should not only change the position of the colorbar but a...
Plotly Colorbar orientation not changing
I used the code of the solution of the following stackoverflow question but the colorbar does not rotate. It only changes the position. The line fig.update_traces(colorbar = dict(orientation='h', y = -0.25, x = 0.5)) should not only change the position of the colorbar but also make it horizontal, which is also stated i...
[ "Answering my own question so people with the same problem get a solution.\nI was using Jupyter Lab, which apparently was the reason for this. A quick fix is to change the renderer in fig.show() to png or else. I havent tried all of the renderers, but fig.show(renderer='png') worked for me. See the documentation fo...
[ 0 ]
[]
[]
[ "plot", "plotly", "python", "python_3.x" ]
stackoverflow_0072278374_plot_plotly_python_python_3.x.txt
Q: "AttributeError: module 'asyncio' has no attribute 'coroutine'." in Python 3.11.0 When I ran the code below with @asyncio.coroutine decorator on Python 3.11.0: import asyncio @asyncio.coroutine # Here def test(): print("Test") asyncio.run(test()) I got the error below: AttributeError: module 'asyncio' has ...
"AttributeError: module 'asyncio' has no attribute 'coroutine'." in Python 3.11.0
When I ran the code below with @asyncio.coroutine decorator on Python 3.11.0: import asyncio @asyncio.coroutine # Here def test(): print("Test") asyncio.run(test()) I got the error below: AttributeError: module 'asyncio' has no attribute 'coroutine'. Did you mean: 'coroutines'? I find @asyncio.coroutine decora...
[ "Generator-based Coroutines which contains @asyncio.coroutine decorator is removed since Python 3.11 so asyncio module doesn't have @asyncio.coroutine decorator as the error says:\n\nNote: Support for generator-based coroutines is deprecated and is removed in Python 3.11.\n\nSo instead, you need to use async keywor...
[ 1 ]
[]
[]
[ "asynchronous", "python", "python_3.x", "python_asyncio", "python_decorators" ]
stackoverflow_0074345065_asynchronous_python_python_3.x_python_asyncio_python_decorators.txt
Q: JavaScript equivalent of Python's format() function? Python has this beautiful function to turn this: bar1 = 'foobar' bar2 = 'jumped' bar3 = 'dog' foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1 # The lazy dog jumped over the foobar Into this: bar1 = 'foobar' bar2 = 'jumped' bar3 = 'dog' foo = 'The la...
JavaScript equivalent of Python's format() function?
Python has this beautiful function to turn this: bar1 = 'foobar' bar2 = 'jumped' bar3 = 'dog' foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1 # The lazy dog jumped over the foobar Into this: bar1 = 'foobar' bar2 = 'jumped' bar3 = 'dog' foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1) # The lazy ...
[ "Another approach, using the String.prototype.replace method, with a \"replacer\" function as second argument:\nString.prototype.format = function () {\n var i = 0, args = arguments;\n return this.replace(/{}/g, function () {\n return typeof args[i] != 'undefined' ? args[i++] : '';\n });\n};\n\nvar bar1 = 'fo...
[ 66, 59, 31, 11, 7, 6, 4, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "format", "javascript", "python" ]
stackoverflow_0004974238_format_javascript_python.txt
Q: How can I get a Pandas Dataframe out of the Codeforces API? I would like to use the CODEFORCERS API for some Analytics (in Python / SQL / even XLS...). I tried to get a sufficient Pandas Dataframe but I get a Dataframe with 0 Rows and 13644 columns. I have no clue how to get a usable Dataframe out of the API. What...
How can I get a Pandas Dataframe out of the Codeforces API?
I would like to use the CODEFORCERS API for some Analytics (in Python / SQL / even XLS...). I tried to get a sufficient Pandas Dataframe but I get a Dataframe with 0 Rows and 13644 columns. I have no clue how to get a usable Dataframe out of the API. What I want to do with the data: Analyse different aspects like score...
[ "My earlier answer was wrong. I made an assumption that the data on your URL was in CSV format (and that Pandas wouldn't support reading from an HTTP endpoint on read_csv... which it does!).\nThe data on that URL is not in CSV format.\nIt is in JSON format.\nTherefore:\ncontest_list = pd.read_json(\"https://codefor...
[ 0 ]
[]
[]
[ "analytics", "api", "dataframe", "python" ]
stackoverflow_0074345079_analytics_api_dataframe_python.txt
Q: Creating a column in my dataframe, which has two date conditions, in python? How do I create a column in my dataframe called 'Yes Or No', where a '1' is input into each row where the "Date" column is between 01/01/2022 and 31/03/2022 and the "Datefield 2" column cannot be empty. I have started with the code below,...
Creating a column in my dataframe, which has two date conditions, in python?
How do I create a column in my dataframe called 'Yes Or No', where a '1' is input into each row where the "Date" column is between 01/01/2022 and 31/03/2022 and the "Datefield 2" column cannot be empty. I have started with the code below, but it doesn't produce the right output. df['Yes Or No'] = (df['Datefield 2'] !=...
[ "Convert both columns to datetimes and test:\nd1 = pd.to_datetime(df['Date'], dayfirst=True)\nd2 = pd.to_datetime(df['Datefield 2'], dayfirst=True)\n\ndf['Yes Or No'] = (d2.notna() & d1.between('2022-03-31', '2023-01-01')).astype(int)\n\n", "you can use numpy.where():\nimport numpy as np\ndf['Date']=pd.to_datetim...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074345084_dataframe_pandas_python.txt
Q: Why am i getting TemplateDoesNotExist at /rapport/? i would like to view my home page/ index view but i keep getting this error, what do i need to do to get rid of this error message below? Any help would be appreciated. Here is the error message: TemplateDoesNotExist at /rapport/ rapport/index.html, rapport/descr...
Why am i getting TemplateDoesNotExist at /rapport/?
i would like to view my home page/ index view but i keep getting this error, what do i need to do to get rid of this error message below? Any help would be appreciated. Here is the error message: TemplateDoesNotExist at /rapport/ rapport/index.html, rapport/description_list.html Request Method: GET Request URL: http...
[ "Change this:\n'DIRS': [BASE_DIR/\"templates\"],\n\nTo this:\n'DIRS': [os.path.join(BASE_DIR,'rapport','templates')],\n\nNote: your templates folder must be inside in your project or app.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0074344770_django_python_templates.txt
Q: Google Analytics reports API - Insufficient Permission 403 I am trying to access data from google-analytics. I am following the guide and is able to gauthorize my user and get the code from oauth. When I try to access data from GA I only get 403 Insufficient Permission back. Do I somehow have to connect my projec...
Google Analytics reports API - Insufficient Permission 403
I am trying to access data from google-analytics. I am following the guide and is able to gauthorize my user and get the code from oauth. When I try to access data from GA I only get 403 Insufficient Permission back. Do I somehow have to connect my project in Google API console to my analytics project? How would I do ...
[ "Had the same problem, but now is solved.\nUse View ID Not account ID, the 'View ID', can be found in the Admin->Profiles->Profile Settings tab\nUPDATE\nnow, if you have more a account , you must go: Admin -> Select account -> under View-> click on View Settings \n", "I had the same problem; sounds as simple as...
[ 10, 0, 0, 0 ]
[]
[]
[ "django", "google_analytics_api", "http_status_code_403", "python", "python_2.7" ]
stackoverflow_0023128964_django_google_analytics_api_http_status_code_403_python_python_2.7.txt
Q: Can't animate quiver plot using the Player class for animation I'm using the Player class for animation as defined here. It's pretty nice insofar as it includes a playback button console, and I've used it to accomplish a variety of settings, e.g. animating heatmaps. However, I'm having problems animating vectors c...
Can't animate quiver plot using the Player class for animation
I'm using the Player class for animation as defined here. It's pretty nice insofar as it includes a playback button console, and I've used it to accomplish a variety of settings, e.g. animating heatmaps. However, I'm having problems animating vectors created using quiver. I won't load all the code that defines the clas...
[ "The following should do the trick. Note that:\n\nI plotted the quiver giving it the initial direction. The error message was telling you exactly that: x, y and u, v must have the same size.\nax.quiver returns only a single handle, hence no comma before the equal sign.\nI added a few keyword arguments to better vis...
[ 1 ]
[]
[]
[ "animation", "matplotlib", "python" ]
stackoverflow_0074340730_animation_matplotlib_python.txt
Q: Python - Creating Zip in stream that exceeds RAM I'm trying to create a zip file on the fly of a directory and return it to the user over a Flask App. The below works great for smaller directories but I'd also like to achieve this with large directories full of images (>20GB). def return_zip(): dir_to_send = '...
Python - Creating Zip in stream that exceeds RAM
I'm trying to create a zip file on the fly of a directory and return it to the user over a Flask App. The below works great for smaller directories but I'd also like to achieve this with large directories full of images (>20GB). def return_zip(): dir_to_send = '/dir/to/the/files' base_path = pathlib.Path(dir_to...
[ "You can use Ubuntu's zip command by invoking it from python:\nimport subprocess\n\ncommand_args = ['zip', '-r', '-j', '-v', '<dest_file>.zip', '<source_file/source_folder>']\nprocess = subprocess.Popen(\n command_args,\n start_new_session=True,\n universal_newlines=True,\n stdout=subprocess.PIPE,\n ...
[ 0 ]
[]
[]
[ "flask", "python", "python_zipfile", "stringio", "zip" ]
stackoverflow_0074341239_flask_python_python_zipfile_stringio_zip.txt
Q: How to install paddlepaddle with no-avx core I am trying to use paddleocr in a docker container and keep getting the error below: Dockerfile FROM paddlecloud/paddleocr:2.5-gpu-cuda10.2-cudnn7-85d7d5 In docker container after building it: In [1]: from paddleocr import PaddleOCR /bin/grep: warning: GREP_OPTIONS is ...
How to install paddlepaddle with no-avx core
I am trying to use paddleocr in a docker container and keep getting the error below: Dockerfile FROM paddlecloud/paddleocr:2.5-gpu-cuda10.2-cudnn7-85d7d5 In docker container after building it: In [1]: from paddleocr import PaddleOCR /bin/grep: warning: GREP_OPTIONS is deprecated; please use an alias or script /bin/gre...
[ "If your machine does not support avx, you need to install the Paddle package of noavx, you can use the following command to install,noavx version paddle wheel only support python3.8:\nFirst use the following command to download the wheel package to the local, and then use python -m pip install [name].whl to instal...
[ 0 ]
[]
[]
[ "docker", "paddle_paddle", "paddleocr", "python" ]
stackoverflow_0074319979_docker_paddle_paddle_paddleocr_python.txt
Q: how to get time of video during video in opencv I have made a motion detection with cv2 which get video as input and as output it returns a csv file contain the time of the motions that happend during the video. the problem is, I have used datetime.now() for the time that the motion happening but the speed of the ...
how to get time of video during video in opencv
I have made a motion detection with cv2 which get video as input and as output it returns a csv file contain the time of the motions that happend during the video. the problem is, I have used datetime.now() for the time that the motion happening but the speed of the video is much more faster. I don't have problem with ...
[ "To calculate in video time you have to know video FPS and curent frame number.\n fps = float(self.stream.get(CAP_PROP_FPS))\n\nThen try to calculate in video time (in seconds) with last frame number :\n videotime_s = last_frame_num/fps\n\nOr change it to timedelta if you need\n videotime_td = timedelta...
[ 0 ]
[]
[]
[ "motion_detection", "opencv", "pandas", "python", "timer" ]
stackoverflow_0074345039_motion_detection_opencv_pandas_python_timer.txt
Q: Tweepy get_followed_lists not returning results Has anyone got a working example of how to use Tweepy, Twiter API v2 to bring back a list of people that a user follows? Here is my attempt but I keep getting empty results back: import tweepy import numpy as np import pandas as pd import time from datetime import d...
Tweepy get_followed_lists not returning results
Has anyone got a working example of how to use Tweepy, Twiter API v2 to bring back a list of people that a user follows? Here is my attempt but I keep getting empty results back: import tweepy import numpy as np import pandas as pd import time from datetime import date from datetime import datetime token='<i...
[ "Ok I figured it out. Should have been using get_users_following instead of get_followed_lists. Hope that helps someone else!\n" ]
[ 1 ]
[]
[]
[ "python", "tweepy" ]
stackoverflow_0074345128_python_tweepy.txt
Q: Python 3 type hinting for dynamic attributes through __getattr__ To wrap all function calls of a module and access it via an wrapper class's __getattr__ method, I tried to use typing library but I could not figure out on how to do this correctly. import interface """ >>> print(interface.__all__) ['execute_foo_ope...
Python 3 type hinting for dynamic attributes through __getattr__
To wrap all function calls of a module and access it via an wrapper class's __getattr__ method, I tried to use typing library but I could not figure out on how to do this correctly. import interface """ >>> print(interface.__all__) ['execute_foo_operation', ...] """ class InterfaceWrapper(object): def __init__(se...
[ "Usually, __getattr__ can return anything. So you could use Typing.Any\nFrom Typing import Any\n\ndef __getattr__(self, name: str) -> Any:\n ...\n\nBut it looks like your implementation of __getattr__ is to return a callable\nFrom Typing import Callable\n\ndef __getattr__(self, name: str) -> Callable:\n ...\n...
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_decorators", "type_hinting" ]
stackoverflow_0055722768_python_python_3.x_python_decorators_type_hinting.txt
Q: Aggregate data by groups of elements I have 2 files: First looks like this: ID1;ID2;ID3;VALUE 1000;100;01;12 1000;100;02;4129 1000;100;03;128 1000;100;04;412 1000;100;05;12818 1000;100;06;4129 1000;100;07;546 1000;100;08;86 1000;100;09;12818 1000;100;10;754 1000;100;11;2633 1000;100;12;571 1000;200;01;13 1000;20...
Aggregate data by groups of elements
I have 2 files: First looks like this: ID1;ID2;ID3;VALUE 1000;100;01;12 1000;100;02;4129 1000;100;03;128 1000;100;04;412 1000;100;05;12818 1000;100;06;4129 1000;100;07;546 1000;100;08;86 1000;100;09;12818 1000;100;10;754 1000;100;11;2633 1000;100;12;571 1000;200;01;13 1000;200;02;319 1000;200;03;828 1000;200;04;46 10...
[ "import pandas as pd\n\ndf1 = pd.read_csv('df1.txt', sep =';', header=0)\ndf2 = pd.read_csv('df2.txt', header=None)\ndf1['preliminary'] = 0\ndf1['test'] = 0\nprint(df1)\nprint(df2)\n\naaa = df2.index[-1]\n\n\ndef my_func(x):\n ind = x.index[x.index > aaa]\n bbb = 0\n if len(ind) > 0:\n bbb = df2[x.i...
[ 0 ]
[]
[]
[ "aggregate", "find", "group_by", "python" ]
stackoverflow_0074320517_aggregate_find_group_by_python.txt
Q: Passing an array of values to a python flask server using JS I am trying to send an array of module names and an array of marks to a function running on a python flask server. function getClassification() { const modulesArray = [ document.getElementById('module_1').value, document.getElementByI...
Passing an array of values to a python flask server using JS
I am trying to send an array of module names and an array of marks to a function running on a python flask server. function getClassification() { const modulesArray = [ document.getElementById('module_1').value, document.getElementById('module_2').value, document.getElementById('module_3').val...
[ "This is because you are sending data as a query argument ( www.example.com?arg1=val1&arg2=val2 )which can only be sent as a string since they are part of the url. To preserve a list you should create a json object to be sent in the body of the POST request.\nAt the same time the request must be handled correctly o...
[ 0 ]
[]
[]
[ "flask", "javascript", "python" ]
stackoverflow_0074345245_flask_javascript_python.txt
Q: Getting number of childs of an element with no ID with beatifulsoup So basically I'm trying to scrape a webpage with Python and I'm getting stucked at finding the number of childs of one element in a list using BeautifulSoup, the HTML of the list follows this: <table id="MyTable"> <thead> <tr>...</tr> ...
Getting number of childs of an element with no ID with beatifulsoup
So basically I'm trying to scrape a webpage with Python and I'm getting stucked at finding the number of childs of one element in a list using BeautifulSoup, the HTML of the list follows this: <table id="MyTable"> <thead> <tr>...</tr> </thead> <tfoot> <tr>...</tr> </tfoot> <tbody> <tr>....
[ "You could check the len() of your resultSet from selecting all <tr> in the <tbody>:\nlen(soup.select('#MyTable > tbody tr'))\n\nExample\nfrom bs4 import BeautifulSoup\n\nhtml='''\n<table id=\"MyTable\">\n <thead>\n <tr>...</tr>\n </thead>\n <tfoot>\n <tr>...</tr>\n </tfoot>\n <tbody>\n <tr...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074345296_beautifulsoup_python_web_scraping.txt
Q: how to compare two pyspark dataframe with multiple values in first dataframe? I have a scenario where I have to do comparison between two dataframes. But the values in on the data frame is in such a way that one to one mapping is not possible. First data frame(df1) has below sample row values. canada canada canada...
how to compare two pyspark dataframe with multiple values in first dataframe?
I have a scenario where I have to do comparison between two dataframes. But the values in on the data frame is in such a way that one to one mapping is not possible. First data frame(df1) has below sample row values. canada canada canada.Italy.Rome canada.USA.Brazil USA.Brazil canada.Rome Note: The vertical sequence i...
[ "Question is vague. A sample of the expected output would make it clear. This is how I have understood it though. Let me know if this works for you.\nBasically, split the names by . in df1 and eliminate any name that is not canada. Store this in a new column.\nData\ndf1 = sqlContext.createDataFrame([(\"canada\",1),...
[ 0 ]
[]
[]
[ "pyspark", "python", "python_3.x" ]
stackoverflow_0074344474_pyspark_python_python_3.x.txt
Q: Pandas group check if timestamp for certain value is earlier than timestamp for other certain value I'm looking at a dataframe full of orders, which have timestamps, order is and an operation status for inserting/updating/canceling the order. The dataframe looks as follows: Index TIMESTAMP ORDER_ID OPERATION 0 2...
Pandas group check if timestamp for certain value is earlier than timestamp for other certain value
I'm looking at a dataframe full of orders, which have timestamps, order is and an operation status for inserting/updating/canceling the order. The dataframe looks as follows: Index TIMESTAMP ORDER_ID OPERATION 0 2022-09-01 13:49:00.000 123 INSERT 1 2022-09-01 13:49:25.000 123 UPDATE 2 2022-09-01 13:49:37.00...
[ "Convert column to datetimes, replace not matched datimes to missing values in Series.where and get minimal datetime per groups, last compare both columns:\ndf['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])\n\ndf1 = (df.assign(s1 = df['TIMESTAMP'].where(df['OPERATION'].eq('INSERT')),\n s2 = df['TIME...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074344778_pandas_python.txt
Q: Matplotlib: TypeError: can't draw a chart I'm a beginner programmer and I am trying to fit a linear line of best fit to my matplotlib graph. I keep getting the error that x and y do not have the same first dimension. Does anyone know that how to solve this error? import matplotlib.pyplot as plt import numpy as np ...
Matplotlib: TypeError: can't draw a chart
I'm a beginner programmer and I am trying to fit a linear line of best fit to my matplotlib graph. I keep getting the error that x and y do not have the same first dimension. Does anyone know that how to solve this error? import matplotlib.pyplot as plt import numpy as np for z in range(0, 10100, 100): p = 1013 * p...
[ "In your code p is just a number, you may have wanted to append it to a list. Moreover, the plot has to be outside the loop. Here you have a working example:\np = []\nfor z in range(0, 10100, 100):\n y = 1013 * pow((1 - ((z/1000) / 45.846)),5.263)\n p.append(y)\n x = np.linspace(0, 10000, 101)\nplt.plot(p,...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074345308_python.txt
Q: I'm trying to replace/convert all the A's and B's in a particular column to 1 and O in a csv file This is the error i'm getting TypeError Traceback (most recent call last) Input In [141], in <cell line: 2>() 1 repl = {'Y':'1', 'N':'0'} ----> 2 prices_dataframe['col_state'] = p...
I'm trying to replace/convert all the A's and B's in a particular column to 1 and O in a csv file
This is the error i'm getting TypeError Traceback (most recent call last) Input In [141], in <cell line: 2>() 1 repl = {'Y':'1', 'N':'0'} ----> 2 prices_dataframe['col_state'] = prices_dataframe['col_state'].replace(repl, regex=True) TypeError: 'bool' object is not subscriptable ...
[ "The replace() method is unique to strings, and at some point the value you are trying to replace is being a boolean (True or False). If you still want to replace it, you can transform the value into a string:\nprices_dataframe['col_state'] = str(prices_dataframe['col_state']).replace(repl, regex=True)\n\n" ]
[ 0 ]
[]
[]
[ "drop", "python", "replace" ]
stackoverflow_0074345210_drop_python_replace.txt
Q: Python script runs in Thonny but Errors in terminal I am able to get my script to work when I manually run it in the Thonny IDE, but I cannot trigger it in the Terminal window with sudo python /home/pi/myscript.py I receive this error: Traceback (most recent call last): File "/home/pi/myscript.py", line 14, in ...
Python script runs in Thonny but Errors in terminal
I am able to get my script to work when I manually run it in the Thonny IDE, but I cannot trigger it in the Terminal window with sudo python /home/pi/myscript.py I receive this error: Traceback (most recent call last): File "/home/pi/myscript.py", line 14, in <module> MESSAGE1_B = bytes(MESSAGE1, 'utf-8') TypeEr...
[ "\"You appear to be running your code with two different Python versions - 3.x in Thonny, 2.x in the terminal.\n– jasonharper\nOct 8, 2020 at 20:49\"\n", "use python3 /home/pi/myscript.py\nI had similar issues until I used the same Python as Thonny\n" ]
[ 0, 0 ]
[]
[]
[ "python", "terminal" ]
stackoverflow_0064270102_python_terminal.txt
Q: numbers in row count How to count how many times even numbers in row? For example: 3, 6, 8, 1, 4, 7, 3, 7, 4, 2 (should be '2' = two times even numbers in row - 6,8 and 4,2. s = [3, 6, 8, 1, 4, 7, 3, 7, 4, 2] print(len([i for i in s if i % 2 == 0])) This one gives how many times (5) even numbers in general. But n...
numbers in row count
How to count how many times even numbers in row? For example: 3, 6, 8, 1, 4, 7, 3, 7, 4, 2 (should be '2' = two times even numbers in row - 6,8 and 4,2. s = [3, 6, 8, 1, 4, 7, 3, 7, 4, 2] print(len([i for i in s if i % 2 == 0])) This one gives how many times (5) even numbers in general. But need how many times even nu...
[ "Here's a simple approach using zip() and sum()\ns = [3, 6, 8, 1, 4, 7, 3, 7, 4, 2]\n\ncount = sum(x % 2 + y % 2 == 0 for x, y in zip(s, s[1:]))\n\nprint(count)\n\nOutput:\n2\n\n" ]
[ 0 ]
[ "you can use itertools.groupby #### i used groupby to check more than two consecutive even numbers\nfrom itertools import groupby\ns = [3, 6, 8, 1, 4, 7, 3, 7, 4, 2]\nlen(list(filter(lambda x: (not x[0]%2) and (len(list(x[1]))>1),groupby(s, key=lambda x: x%2))))\n# output : 2\n\nworking: groupby with group the list...
[ -1 ]
[ "count", "numbers", "python" ]
stackoverflow_0074345261_count_numbers_python.txt
Q: why I must reshape one image to [n,height,width,channel] in CNN I try to apply a convolutional layer to a picture of shape [256,256,3] a have an error when I user the tensor of the image directly conv1 = conv2d(input,W_conv1) +b_conv1 #<=== error error message: ValueError: Shape must be rank 4 but is rank 3 f...
why I must reshape one image to [n,height,width,channel] in CNN
I try to apply a convolutional layer to a picture of shape [256,256,3] a have an error when I user the tensor of the image directly conv1 = conv2d(input,W_conv1) +b_conv1 #<=== error error message: ValueError: Shape must be rank 4 but is rank 3 for 'Conv2D' (op: 'Conv2D') with input shapes: [256,256,3], [3,3,3,1]...
[ "The first dimension is the batch size. If you are feeding 1 image at a time you can simply make the first dimension 1 and it doesn't change your data any, just changes the indexing to 4D:\nx_image = tf.reshape(input, [1, 256, 256, 3])\n\nIf you reshape it with a -1 in the first dimension what you are doing is sayi...
[ 10, 0 ]
[]
[]
[ "conv_neural_network", "python", "reshape", "tensor", "tensorflow" ]
stackoverflow_0048509419_conv_neural_network_python_reshape_tensor_tensorflow.txt
Q: local sphinx generates autodoc members from docstrings, readthedocs does not I have a small project at github. The package does not have external dependencies, and all the source is included in a single __init__.py file. In the ./docs folder, I just have 2 rst files: an index.rst with some intro and a nix_shell_ut...
local sphinx generates autodoc members from docstrings, readthedocs does not
I have a small project at github. The package does not have external dependencies, and all the source is included in a single __init__.py file. In the ./docs folder, I just have 2 rst files: an index.rst with some intro and a nix_shell_utils.rst file where the package members are automatically described from their docs...
[ "\nHowever, when I tried to do the same in readthedocs.org, the build\nprocess terminates OK, but when clicking on the nix_shell_utils link\nat the documentation index, I just get a page with the title, \"Module\nContents\" header, and nothing else. Readthedocs does not render the\ndocumentation of the package memb...
[ 1 ]
[]
[]
[ "autodoc", "python", "python_sphinx", "read_the_docs" ]
stackoverflow_0074335281_autodoc_python_python_sphinx_read_the_docs.txt
Q: How to access file/tables in dbfs storage of one ADB workspace from a totally different ADB Workspace I want to access some files stored in dbfs location of ADB-1(Azure databricks) workspace from ADB-2 workspace. Just wanted to understand if its possible to query another workspace dbfs storage. I tried googling th...
How to access file/tables in dbfs storage of one ADB workspace from a totally different ADB Workspace
I want to access some files stored in dbfs location of ADB-1(Azure databricks) workspace from ADB-2 workspace. Just wanted to understand if its possible to query another workspace dbfs storage. I tried googling this question a lot but so far no luck. Please help!! For example - in ADB-1 workspace i have file store in /...
[ "There is an API in Databricks i.e., DBFS 2.0 where there is a GET method. But there are few limitations.\n\nLook at the following demonstration. Let's say dbfs1 is where the required files are present. You can use the below code to read the file from 2nd Databricks notebook.\n\nimport requests\nimport json\n\nmy_j...
[ 1 ]
[]
[]
[ "azure", "azure_databricks", "databricks", "python" ]
stackoverflow_0074341017_azure_azure_databricks_databricks_python.txt
Q: How to rolling sum for specific intervals in time series data I have time series data and I want to create another column that sums the value for each day. For example: df timestamp val sum 2022-10-10 00:00:00 50 50 2022-10-10 00:01:00 10 60 2022-10-10 00:02:00 20 80 ... 2022-10...
How to rolling sum for specific intervals in time series data
I have time series data and I want to create another column that sums the value for each day. For example: df timestamp val sum 2022-10-10 00:00:00 50 50 2022-10-10 00:01:00 10 60 2022-10-10 00:02:00 20 80 ... 2022-10-10 23:59:00 10 2300 2022-10-11 00:00:00 20 20 ... Ho...
[ "Use GroupBy.cumsum per dates:\ndf['sum'] = df.groupby(df['timestamp'].dt.date)['val'].cumsum()\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074345577_dataframe_pandas_python.txt
Q: Replace columns with the same value between two dataframes I have two dataframes df1 Date RPM 0 0 0 1 1 0 2 2 0 3 3 0 4 4 0 5 5 0 6 6 0 7 7 0 and df2 Date RPM 0 0 0 1 2 2 2 4 4 3 6 6 I want to replace the RPM in df1 with the RPM in df2 where they have...
Replace columns with the same value between two dataframes
I have two dataframes df1 Date RPM 0 0 0 1 1 0 2 2 0 3 3 0 4 4 0 5 5 0 6 6 0 7 7 0 and df2 Date RPM 0 0 0 1 2 2 2 4 4 3 6 6 I want to replace the RPM in df1 with the RPM in df2 where they have the same Date I tried with replace but it didn't work out
[ "Use Series.map by Series created from df2 and then replace misisng valeus by original column by Series.fillna:\ndf1['RPM'] = df1['Date'].map(df2.set_index('Date')['RPM']).fillna(df1['RPM'])\n\n", "You could merge() the two frames on the Date column to get the new RPM against the corresponding date row:\ndf = df1...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074345575_dataframe_pandas_python.txt
Q: How to write path to VS folder in pystencils config file? I've installed pystencils in python on windows, but it has the error when I try to import. "Visual Studio not found. Write path to VS folder in pystencils config". I've installed Visual Studio, and have opened the pystencils config file, but how exactly do ...
How to write path to VS folder in pystencils config file?
I've installed pystencils in python on windows, but it has the error when I try to import. "Visual Studio not found. Write path to VS folder in pystencils config". I've installed Visual Studio, and have opened the pystencils config file, but how exactly do I write the path: C:\Program Files\Microsoft Visual Studio to t...
[ "According to the documentation, the pystencils config file is a text file in JSON format, where on Windows it can have a key\n\n‘msvc_version’: either a version number, year number, ‘auto’ or ‘latest’ for automatic detection of latest installed version or ‘setuptools’ for setuptools-based detection. Alternatively ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074257872_python.txt
Q: How to find Duplicates in an 3 Dimensional list Hello i want to build a Highscore List with the Attributes [Position,Name,Points]. If they have the same Points, they should share the Position. ex. [[1,John,55],[2,Anna,35],[2,Mike,35],[3,Tom,15]]. First I tried to sort the List after the Points, my next Step is to ...
How to find Duplicates in an 3 Dimensional list
Hello i want to build a Highscore List with the Attributes [Position,Name,Points]. If they have the same Points, they should share the Position. ex. [[1,John,55],[2,Anna,35],[2,Mike,35],[3,Tom,15]]. First I tried to sort the List after the Points, my next Step is to rewrite the Position ` l = [[4,Anna,35], [2,John,55],...
[ "You want to sort by the last element of each list (score) and then update the first element of each list (position) to match the index in the outer list?\nAll that's needed:\nl = [\n [4, 'Anna', 35], \n [2, 'John', 55], \n [1, 'Tom', 15], \n [3, 'Mike', 35], \n [5, 'Sepp', 35]\n]\nl = sorted(l, key=...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074345604_list_python.txt
Q: What is and How to fix this error in discord.py? I was using replit (maybe because replit doesnt work?) tryoing to make some code for a Discord bot when I saw this: Type error: __init__ missing 1 required keyword-only argument: "intents" Im not really sure what is means Heres my code (BTW i used pip install discor...
What is and How to fix this error in discord.py?
I was using replit (maybe because replit doesnt work?) tryoing to make some code for a Discord bot when I saw this: Type error: __init__ missing 1 required keyword-only argument: "intents" Im not really sure what is means Heres my code (BTW i used pip install discord in shell) ` import discord token = "mytoken (not r...
[ "Replace\nclient = discord.Client()\n\nwith\nclient = discord.Client(intents=discord.Intents.default())\n\n", "As per recently(-ish), you need to specify the intents your bot uses when login to the API, so you should populate the Client argument with an intent object.\nCalling the default intents, if you don't pl...
[ 1, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074340413_discord.py_python.txt
Q: Named colors in matplotlib What named colors are available in matplotlib for use in plots? I can find a list on the matplotlib documentation that claims that these are the only names: b: blue g: green r: red c: cyan m: magenta y: yellow k: black w: white However, I've found that these colors can also be used, at...
Named colors in matplotlib
What named colors are available in matplotlib for use in plots? I can find a list on the matplotlib documentation that claims that these are the only names: b: blue g: green r: red c: cyan m: magenta y: yellow k: black w: white However, I've found that these colors can also be used, at least in this context: scatter(...
[ "I constantly forget the names of the colors I want to use and keep coming back to this question =)\nThe previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplo...
[ 434, 335, 148, 18, 0 ]
[ "You can use this dictionary which have most of colors.\nz = { 'Black' : (0,0,0) ,\n'White' : (255,255,255),\n'Red' : (255,0,0),\n'Lime': (0,255,0),\n'Blue': (0,0,255),\n'Yellow': (255,255,0),\n'Cyan' :(0,255,255),\n'Fuchsia': (255,0,255),\n'Silver' : (192,192,192),\n'Gray' : (...
[ -1 ]
[ "colors", "matplotlib", "python" ]
stackoverflow_0022408237_colors_matplotlib_python.txt
Q: Merge content of two csv files in alternate rows I have two CSV files csv1: header a b c csv2:\ header e f g I want to merge these two files to another CSV in alternate rows like output.csv: header a e b f c g Can this be done? Thanks in advance A: Assuming csv 1 read into df1 Assuming csv 2 read into df2 df1...
Merge content of two csv files in alternate rows
I have two CSV files csv1: header a b c csv2:\ header e f g I want to merge these two files to another CSV in alternate rows like output.csv: header a e b f c g Can this be done? Thanks in advance
[ "Assuming csv 1 read into df1\nAssuming csv 2 read into df2\ndf1 = pd.DataFrame({'header': ['a', 'b', 'c']})\ndf2 = pd.DataFrame({'header': ['d', 'e', 'f']})\n\nprint(pd.concat(\n [df1, df2], axis=1\n).stack().reset_index(1, drop=True))\n\noutput #\n0 a\n0 d\n1 b\n1 e\n2 c\n2 f\n\n", "Will de...
[ 1, 0, 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074344829_csv_dataframe_pandas_python.txt
Q: oauth 1 not working with httpx and authlib i am currently making oauth 1 signed requests using the requests-oauthlib library. from requests_oauthlib import OAuth1Session self.session = OAuth1Session( OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, oauth_token, oauth_token_secret, signature_type='auth_heade...
oauth 1 not working with httpx and authlib
i am currently making oauth 1 signed requests using the requests-oauthlib library. from requests_oauthlib import OAuth1Session self.session = OAuth1Session( OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, oauth_token, oauth_token_secret, signature_type='auth_header', realm='http://api.twitter.com' ) self...
[ "I'm working on a similar solution, you should import AsyncOAuth1Client and not OAuth1Client when using httpx.\n" ]
[ 0 ]
[]
[]
[ "authlib", "httpx", "oauth", "python", "python_requests" ]
stackoverflow_0072697836_authlib_httpx_oauth_python_python_requests.txt
Q: Python - df.groupby.sum() returns NaN I have a dataset of about 27,00,000 rows as a dataframe in python. The dataframe has two columns temperature and time spent at that temperature. I want to groupby temperature and sum the time spent at each temperature. I used the following code. df_copy = df.groupby(['Temperat...
Python - df.groupby.sum() returns NaN
I have a dataset of about 27,00,000 rows as a dataframe in python. The dataframe has two columns temperature and time spent at that temperature. I want to groupby temperature and sum the time spent at each temperature. I used the following code. df_copy = df.groupby(['Temperature']).sum() I am getting the summed values...
[ "Found the issue.\nThere were some inf values in time_spent column.\nRectified those things. Now it is working.\n" ]
[ 0 ]
[]
[]
[ "group_by", "python" ]
stackoverflow_0074343700_group_by_python.txt
Q: Python Input Text into The Next Empty Cell of an Excel Sheet Column for Multiple Workbooks I have 30 workbooks with naming convention (myfile1.xlsm, myfile2.xlsm, myfile3.xlsm etc) I would like to input a text into the next empty cell of a specific column(Q) of a specific worksheet(sheet1) for all 30 workbooks. Th...
Python Input Text into The Next Empty Cell of an Excel Sheet Column for Multiple Workbooks
I have 30 workbooks with naming convention (myfile1.xlsm, myfile2.xlsm, myfile3.xlsm etc) I would like to input a text into the next empty cell of a specific column(Q) of a specific worksheet(sheet1) for all 30 workbooks. The code below works perfect for one workbook but I need to do same thing for all 30 workbooks so ...
[ "If your .xlsm files are located in the same directory (in your case, \"C:/Users/me/randomfolder\"), you can then use Path.glob to return their paths and pass them as a parameter of openpyxl.load_workbook one by one in a for loop.\nTry this :\nfrom pathlib import Path\nimport openpyxl\nfrom openpyxl import Workbook...
[ 1 ]
[]
[]
[ "openpyxl", "python" ]
stackoverflow_0074341097_openpyxl_python.txt
Q: Extremely slow Postgres inserts after switching to Hetzner servers I've got a python script that fetches data from an API, processes it and stores it in Postgres using SQLAlchemy. On my local machine, I can insert 120 rows in a few milliseconds using vanilla postgres 14. On my current web host, insertion perform...
Extremely slow Postgres inserts after switching to Hetzner servers
I've got a python script that fetches data from an API, processes it and stores it in Postgres using SQLAlchemy. On my local machine, I can insert 120 rows in a few milliseconds using vanilla postgres 14. On my current web host, insertion performance is similar. This instance of postgres runs in a docker container a...
[ "That's network latency. Each INSERT is a client-server round trip and costs at least twice the network latency. See this article for a description and a proof of concept.\nYou have two options:\n\nUse fewer statements. For example, you could insert the 120 rows with a single COPY statement.\n\nUse pipelining so th...
[ 1 ]
[]
[]
[ "database_performance", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0074345507_database_performance_postgresql_python_sqlalchemy.txt
Q: why my Function isn't giving the required output I'm trying to write a program that generates all two-character combinations of the alphabet from 'a' to 'z', and if the permutations include both 'x' and 'z', print them and break import itertools def gen2(n): alplist = list(map(chr,list(range(ord('a'),ord('z')+1))...
why my Function isn't giving the required output
I'm trying to write a program that generates all two-character combinations of the alphabet from 'a' to 'z', and if the permutations include both 'x' and 'z', print them and break import itertools def gen2(n): alplist = list(map(chr,list(range(ord('a'),ord('z')+1)))) for combi in itertools.product(alplist,*([alplist]...
[ "The code has five issues:\n\nreturn gen2(2) inside the main for-loop prevents the execution of the code. Also this freezes the code, since the recursive calls are nested indefinitely.\n\nif \"x\" and \"z\" in combi: does not work properly. Python will interpret this as only if \"z\" in combi: because \"x\" is alwa...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074345771_python.txt
Q: aggregate based on if column values exist I have a dataframe and would like to aggregate based on if some values in column Result exist or not. So if for any ìndex1 and ìndex2 there is an A then my total_result column should be A. If there is no A but there is a B then my total_result column should be B, etc. Belo...
aggregate based on if column values exist
I have a dataframe and would like to aggregate based on if some values in column Result exist or not. So if for any ìndex1 and ìndex2 there is an A then my total_result column should be A. If there is no A but there is a B then my total_result column should be B, etc. Below I have some working code but I was wondering ...
[ "Solution if always match at least one value - First create helper columns and then aggregate DataFrameGroupBy.any, for first match column name use DataFrame.idxmax:\ndf1 = (df.assign(A = (df.Result == 'A') | (df.Result == 'As'),\n B = (df.Result == 'B'),\n C = (df.Result == 'C'),\n ...
[ 1 ]
[]
[]
[ "aggregate", "aggregate_functions", "pandas", "python" ]
stackoverflow_0074345881_aggregate_aggregate_functions_pandas_python.txt
Q: Python: How do I add a Legend with Top 10 Countries in my Bokeh GeoData Plot? I want to add a Legend on the white space on the left of my Wolrd_Data with the top 10 countries and their respective Data. Something like in this plot I found on Reddit --> Link: https://www.reddit.com/r/MapPorn/comments/yog129/europes_...
Python: How do I add a Legend with Top 10 Countries in my Bokeh GeoData Plot?
I want to add a Legend on the white space on the left of my Wolrd_Data with the top 10 countries and their respective Data. Something like in this plot I found on Reddit --> Link: https://www.reddit.com/r/MapPorn/comments/yog129/europes_impressive_agriculture_exports_in_2000/ I created my Plot with Bokeh, sadly I am no...
[ "Here is a solution unsing geopandas. The idea is, to loop over each country and create a single source for each. This way the legend_label can be set individually.\nimport geopandas\n\nfrom bokeh.io import output_notebook, show, output_file\nfrom bokeh.models import GeoJSONDataSource, LinearColorMapper, ColorBar\n...
[ 0 ]
[]
[]
[ "bokeh", "geojson", "geopandas", "python" ]
stackoverflow_0074343618_bokeh_geojson_geopandas_python.txt
Q: python syntax to access multiple names in the same namespace without repeating the name (like "using" in some languages is there a way in python to tell the interpretes a bunch of statements should all be executed on the same object/namespace? In some other languages you have constructs like using myObject{ .a...
python syntax to access multiple names in the same namespace without repeating the name (like "using" in some languages
is there a way in python to tell the interpretes a bunch of statements should all be executed on the same object/namespace? In some other languages you have constructs like using myObject{ .a = 1; .b = 2; .c = 3; } as shorthand notation for myObject.a = 1; myObject.b = 2; myObject.c = 3; Is there anything...
[ "you could manually update the dict attributes which hold all the attributes\nattr = {'target': MyObject,'result1': test1(),'result2': test2()}\ntestmodule.__dict__.update(attr)\n\nhowever this is kind of hack, better to add a method inside you testmodule which gets this as input (like dic) and update (setattr) to ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074345657_python.txt
Q: Django: Object of type QuerySet is not JSON serializable I am trying to remove items from cart using Jquery and Django, i have written the logic to do this but i keep getting this errror that says Object of type QuerySet is not JSON serializable, i can seem to know what the problem is because i have tried converti...
Django: Object of type QuerySet is not JSON serializable
I am trying to remove items from cart using Jquery and Django, i have written the logic to do this but i keep getting this errror that says Object of type QuerySet is not JSON serializable, i can seem to know what the problem is because i have tried converting the code below to list using list() method in django and al...
[ "As the error mentions, queryset is not JSON serializable. Hence you can make it into JSON using Django's serializers and pass it to JsonResponse class initiation:\nfrom django.core import serializers\n....\nqs_json = serializers.serialize('json', wishlist)\nreturn JsonResponse({'data':t,'wishlist':qs_json})\n\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074345639_django_python.txt
Q: Editing Text in tkinter So I've passed a create_text variable to "text1" text1 = UseCanvas(self.window, "text", width = 100, height = 100, text = "Goodbye") Using: self.create_text(20,25 width=100, anchor="center", text =self.text, tags= self.tag1) after passing it to another class. How do I edit that text wid...
Editing Text in tkinter
So I've passed a create_text variable to "text1" text1 = UseCanvas(self.window, "text", width = 100, height = 100, text = "Goodbye") Using: self.create_text(20,25 width=100, anchor="center", text =self.text, tags= self.tag1) after passing it to another class. How do I edit that text widget? I want it to say "Hello"...
[ "You should use the itemconfig method of the canvas to modify the text attribute. You have to give to it an id of one or more canvas items. Here is a small working example that lets you change the text of one text object:\n# use 'tkinter' instead of 'Tkinter' if using python 3.x\nimport Tkinter as tk \n\nclass Exam...
[ 14, 0 ]
[]
[]
[ "python", "text", "tkinter" ]
stackoverflow_0015193330_python_text_tkinter.txt
Q: how to sum an array in dictionary i have a dictionary , and i want to sum for every array in every key dictionary example : {'Ancolmekar': array([1]), 'Cidurian': array([1]), 'dayeuhkolot': array([1]), 'Hantap': array([1]), 'Kertasari': array([1]), 'Meteolembang': array([1]), 'Sapan': array([1]), } the value 1 i...
how to sum an array in dictionary
i have a dictionary , and i want to sum for every array in every key dictionary example : {'Ancolmekar': array([1]), 'Cidurian': array([1]), 'dayeuhkolot': array([1]), 'Hantap': array([1]), 'Kertasari': array([1]), 'Meteolembang': array([1]), 'Sapan': array([1]), } the value 1 is example not a real calculated. what i...
[ "You can use reduce function as below:\nfrom functools import reduce\ndict2 = {}\nfor k, v in dict.items():\n dict2[k] = reduce(lambda a, b: a+b, v)\n\nprint(dict2)\n\n" ]
[ 1 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074345492_arrays_python.txt
Q: How to use remote server's database? I want to insert username, filename and Hex_format into remote server's SQLite database: #!/usr/bin/python import socket import urllib import urllib2 import paramiko import sqlite3 username = "e100075" filename = "screenshot.png" Hex_format = "FSGDSFDSSFGRSSCD" ssh = paramiko...
How to use remote server's database?
I want to insert username, filename and Hex_format into remote server's SQLite database: #!/usr/bin/python import socket import urllib import urllib2 import paramiko import sqlite3 username = "e100075" filename = "screenshot.png" Hex_format = "FSGDSFDSSFGRSSCD" ssh = paramiko.SSHClient() ssh.set_missing_host_key_poli...
[]
[]
[ "def sql(sql):\n try:\n ssh = SSHClient()\n #ssh.load_system_host_keys()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(hostname='ip', username='user', password='pass')\n sleep(0.5)\n stdin, stdout, stderr = ssh.exec_command(sql)\n resul...
[ -1 ]
[ "python", "python_2.7", "sqlite" ]
stackoverflow_0020286032_python_python_2.7_sqlite.txt
Q: Unable to find installation candidates for nvidia-cudnn-cu11 when trying to install kornia I'm trying to install kornia using poetry. System details Python 3.8.5 (I have to use this version) poetry 1.1.13 (upgrading to v1.2 is not an option) I've previously installed kornia (poetry add kornia) but for some unkno...
Unable to find installation candidates for nvidia-cudnn-cu11 when trying to install kornia
I'm trying to install kornia using poetry. System details Python 3.8.5 (I have to use this version) poetry 1.1.13 (upgrading to v1.2 is not an option) I've previously installed kornia (poetry add kornia) but for some unknown reason I'm now getting the following traceback: RuntimeError Unable to find installation can...
[ "could this be related to this problem?\n\nhttps://github.com/python-poetry/poetry/issues/6939\nhttps://github.com/pytorch/pytorch/issues/88049\n\nI had a similar issue and was able to fix it by making the torch dependency explicit and install torch version < 1.13:\n[tool.poetry.dependencies]\n...\ntorch = \"~1.12....
[ 2 ]
[]
[]
[ "kornia", "nvidia", "python", "python_poetry" ]
stackoverflow_0074321090_kornia_nvidia_python_python_poetry.txt
Q: Using If statement in python comparing time to a value I am trying to write a simple code in python which working on the Raspberry pi. This code is working but I want to make a better code when I turb on LED in different time. such as 5minutes later turn on the first led and another 5minutes later second led .... ...
Using If statement in python comparing time to a value
I am trying to write a simple code in python which working on the Raspberry pi. This code is working but I want to make a better code when I turb on LED in different time. such as 5minutes later turn on the first led and another 5minutes later second led .... The problem is when I changing the dlay time such as 5minute...
[ "You could go with a basic state machine.\nKeep just sleep periods. No need anymore to deal with dates.\nExample :\nimport time\n\ni = 0\nstate = 0\nwhile True:\n time.sleep(5)\n state = i%3\n if state == 0:\n print(\"light on led A\")\n elif state == 1:\n print(\"light on led B\")\n el...
[ 1 ]
[]
[]
[ "if_statement", "python", "raspberry_pi", "time" ]
stackoverflow_0074345844_if_statement_python_raspberry_pi_time.txt
Q: Statsmodels ARIMA: how to get confidence/prediction interval? How to generate "lower" and "upper" predictions, not just "yhat"? import statsmodels from statsmodels.tsa.arima.model import ARIMA assert statsmodels.__version__ == '0.12.0' arima = ARIMA(df['value'], order=order) model = arima.fit() Now I can genera...
Statsmodels ARIMA: how to get confidence/prediction interval?
How to generate "lower" and "upper" predictions, not just "yhat"? import statsmodels from statsmodels.tsa.arima.model import ARIMA assert statsmodels.__version__ == '0.12.0' arima = ARIMA(df['value'], order=order) model = arima.fit() Now I can generate "yhat" predictions yhat = model.forecast(123) and get confidenc...
[ "In general, the forecast and predict methods only produce point predictions, while the get_forecast and get_prediction methods produce full results including prediction intervals.\nIn your example, you can do:\nforecast = model.get_forecast(123)\nyhat = forecast.predicted_mean\nyhat_conf_int = forecast.conf_int(al...
[ 9, 0, 0 ]
[]
[]
[ "arima", "python", "statsmodels" ]
stackoverflow_0064277905_arima_python_statsmodels.txt
Q: How to get all instances in a subnet using boto3 I was wondering how can you get all ec2 in a subnet when you a subnet Id import boto3 ec2 = session.resource('ec2') instance = ec2.Instance('subnet_id') This is as far as I can go but I get errors as it is only expecting an instance id A: You can use filters for...
How to get all instances in a subnet using boto3
I was wondering how can you get all ec2 in a subnet when you a subnet Id import boto3 ec2 = session.resource('ec2') instance = ec2.Instance('subnet_id') This is as far as I can go but I get errors as it is only expecting an instance id
[ "You can use filters for this...\nec2 = boto3.resource('ec2')\n\ninstances = ec2.instances.filter(Filters=[{\n 'Name': 'SubnetID',\n 'Values': [subnet_id]}])\n\n" ]
[ 3 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074345996_amazon_ec2_amazon_web_services_boto3_python.txt
Q: Why i get these errors when i "kill" the program while its runing? This is my code from tkinter import * import random import time def create_circles(): for i in range(10): x0 = random.randint(50, 550) y0 = random.randint(50, 550) i=40 colors = ["red", "blue", "purple", "gre...
Why i get these errors when i "kill" the program while its runing?
This is my code from tkinter import * import random import time def create_circles(): for i in range(10): x0 = random.randint(50, 550) y0 = random.randint(50, 550) i=40 colors = ["red", "blue", "purple", "green", "violet", "black"] for o in range(5): ...
[ "The program tries to continue to draw circles even after you kill the program. And as there is no tkinter window to draw in, it produces the following error.\nMake something like this to prevent the error.\nfrom tkinter import *\n\ndef exit_program(event):\n if event.char == \"e\":\n win.quit()\n ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074345442_python.txt
Q: Can I implement Singleton pattern partially? I want to get one instance if identical arguments are passed. And different - if at least one argument is different instance1 = someClass(arg1, arg2, arg3) instance2 = someClass(arg1, arg4, arg5) instance3 = someClass(arg1, arg2, arg3) print(id(instance1) == id(instance...
Can I implement Singleton pattern partially?
I want to get one instance if identical arguments are passed. And different - if at least one argument is different instance1 = someClass(arg1, arg2, arg3) instance2 = someClass(arg1, arg4, arg5) instance3 = someClass(arg1, arg2, arg3) print(id(instance1) == id(instance2)) # should print False print(id(instance1) == i...
[ "Instead of singleton you can use functools.lru_cache as suggested by @luk2305 in comments\nfrom functools import lru_cache\n\n@lru_cache(maxsize=None)\nclass someClass:\n def __init__(self, a, b, c):\n pass\n\na = someClass(2,3,4)\nprint(a) # different id\nb = someClass(2,3,5)\nprint(b) # different id\nc = som...
[ 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0074346067_class_python.txt
Q: How to split a string into two sub-stings using a string matching in a data frame I have a dataframe with the sentences column and a column with a word present in the sentences.I want to string match the word to the word in the sentences column and create a data frame by splitting the sentences into two different ...
How to split a string into two sub-stings using a string matching in a data frame
I have a dataframe with the sentences column and a column with a word present in the sentences.I want to string match the word to the word in the sentences column and create a data frame by splitting the sentences into two different sentences and placing them into separate columns as mentioned below. I have df1 Sen...
[ "you could use regex and create your new dataframe:\ndf2 = {\"Sentence\":[], \"word\":[], \"source\":[] ,\"target\":[]}\n\nfor d in df.iterrows() :\n source,_ ,target = re.findall(f'(.*) ({d[1].word})(.*)', d[1].Sentence)[0]\n df2['Sentence'].append(d[1].Sentence)\n df2['word'].append(d[1].word)\n df2['...
[ 1, 1 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0074345907_python_split_string.txt
Q: Display Confirmation Popup in Odoo How can I display a confirmation popup in Odoo15 through code and get the result if confirmed (true) or not confirmed(false) and continue my python code based on this result. I want to be able to show this dialog whenever i want through any python function. I don't want to use wi...
Display Confirmation Popup in Odoo
How can I display a confirmation popup in Odoo15 through code and get the result if confirmed (true) or not confirmed(false) and continue my python code based on this result. I want to be able to show this dialog whenever i want through any python function. I don't want to use wizard since Wizard it can only be called ...
[ "Example py for wizard\nclass TestModelWizard(models.TransientModel):\n _name = 'salesperson.bulkassign'\n \n name = fields.Char(related = 'users.name')\n users = fields.Many2one(\"res.users\")\n def action_apply(self):\n #perform your confirm action here\n\nExample XML for wizard\n<record mo...
[ 0 ]
[]
[]
[ "javascript", "odoo", "odoo_15", "python" ]
stackoverflow_0074343612_javascript_odoo_odoo_15_python.txt
Q: How to decode attribute cirrilic values use 'lxml xslt encode' from xml doc? After the conversion, there is a problem with the encoding of attribute values. Standard conversion does not help. import lxml.etree as ET data = '<Response> <ОргМн Наим="ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ"> <Орг НаимЮЛПолн="НАИМЕ...
How to decode attribute cirrilic values use 'lxml xslt encode' from xml doc?
After the conversion, there is a problem with the encoding of attribute values. Standard conversion does not help. import lxml.etree as ET data = '<Response> <ОргМн Наим="ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ"> <Орг НаимЮЛПолн="НАИМЕНОВАНИЕ 5087"> <ГРНДата ГРН="5087" ДатаЗаписи="2008-11-18"/> </Орг> </ОргМн> </Res...
[ "I have now tested with Python 3 and lxml 4.9.1 that using\nrools = '<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"> <xsl:output encoding=\"UTF-8\"/> <xsl:template match=\"/\"> <xsl:copy-of select=\"*\" /> </xsl:template> </xsl:stylesheet>'\n\nplus then simply\nroot = ET.fromstri...
[ 1 ]
[]
[]
[ "lxml", "python", "xml", "xslt" ]
stackoverflow_0074344180_lxml_python_xml_xslt.txt
Q: python regex relace for a string I am trying to apply regex on python for following code. I want replace usa_f1_t1 with usa. for ex: my input would be usa_f1, usa_tt1_f1_v1, usa_us_t1_v1 , us_us_v1 for all these cases i would want to ignore string part where anything coming numeric usa_tt1_f1_v1 - it should give ...
python regex relace for a string
I am trying to apply regex on python for following code. I want replace usa_f1_t1 with usa. for ex: my input would be usa_f1, usa_tt1_f1_v1, usa_us_t1_v1 , us_us_v1 for all these cases i would want to ignore string part where anything coming numeric usa_tt1_f1_v1 - it should give usa as result usa_us_t1_v1 - it should...
[ "Without any regex:\n'_'.join([x for x in s.split('_') if x.isalpha()])\n\nSee the Python demo online.\nWhat does it it do?\n\ns.split('_') - splits the string with underscores\nthen the list comprehension keeps only those chunks (x) that fully consist of letters (.isalpha() does that check).\n\n" ]
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074303405_python_regex.txt
Q: Don't know why the plot() function is not working in this code import matplotlib.pyplot as plt y=10 sy=2 x=10 while x<=100: draw_line(x,0,x,y) y=sy*y x=x+10 plt.plot(x,y) plt.show() Basically I used scatter function to get through the exam but plot is not working at all. when ran it wa...
Don't know why the plot() function is not working in this code
import matplotlib.pyplot as plt y=10 sy=2 x=10 while x<=100: draw_line(x,0,x,y) y=sy*y x=x+10 plt.plot(x,y) plt.show() Basically I used scatter function to get through the exam but plot is not working at all. when ran it was a blank screen. I tried to find solutions online and checked ...
[ "To draw a curve, you need to collect all the x and all the y value into a list (or a numpy array) and then call plot once. plot by default, tries to draw a line. If you just call plt.plot(x,y) where x and y are single values, no line can be drawn.\nAlso, plt.show() should only be called once, at the end of the co...
[ 0 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0074343070_matplotlib_plot_python.txt
Q: Install MetaTrader5 using pip 22.3.1 and python 3.11.0 error I am trying to install MetaTrader5 on windows using pip. python --version Python 3.11.0 pip --version pip 22.3.1 pip install MetaTrader5 ERROR: Could not find a version that satisfies the requirement MetaTrader5 (from versions: none) ERROR: No matching...
Install MetaTrader5 using pip 22.3.1 and python 3.11.0 error
I am trying to install MetaTrader5 on windows using pip. python --version Python 3.11.0 pip --version pip 22.3.1 pip install MetaTrader5 ERROR: Could not find a version that satisfies the requirement MetaTrader5 (from versions: none) ERROR: No matching distribution found for MetaTrader5 I have seen similar questions...
[ "The current latest version MetaTrader5 5.0.43 provides wheels for Python 3.6-3.10. Not for 3.11 and no source code.\nDowngrade your Python to 3.10. Make sure to install 64-bit version.\n" ]
[ 0 ]
[]
[]
[ "metatrader5", "pip", "python" ]
stackoverflow_0074346030_metatrader5_pip_python.txt
Q: elasticsearch-dsl in python: How can I return the "inner hits" for my query? I am currently exploring elasticsearch in python using the elasticsearch_dsl library. I am aware that my Elasticsearch knowledge is currently limited. I have created a model like so: class Post(InnerDoc): text = Text() id = Intege...
elasticsearch-dsl in python: How can I return the "inner hits" for my query?
I am currently exploring elasticsearch in python using the elasticsearch_dsl library. I am aware that my Elasticsearch knowledge is currently limited. I have created a model like so: class Post(InnerDoc): text = Text() id = Integer() class User(Document): name = Text() posts = Object(doc_class=Posts) ...
[ "I updated my model to this:\nclass Post(InnerDoc):\n text = Text(analyzer=\"snowball\")\n id = Integer()\n\n\nclass User(Document):\n name = Text()\n posts = Nested(doc_class=Posts)\n signed_up_at = Date()\n\nThis allows me to do the following query:\nGET users/_search\n{\n \"query\": {\n \"nest...
[ 0 ]
[]
[]
[ "elasticsearch", "elasticsearch_dsl", "elasticsearch_dsl_py", "python" ]
stackoverflow_0074319548_elasticsearch_elasticsearch_dsl_elasticsearch_dsl_py_python.txt
Q: How to stop DRF's ModelSerializer to use model field's default value? I'm stucked with this strange bug(?) with BooleanField. While partial_update, serializer is always set all boolean values to false, if it is not set in request. My models.py class User(AbstractUser): agree_email = BooleanField(blank=True) ...
How to stop DRF's ModelSerializer to use model field's default value?
I'm stucked with this strange bug(?) with BooleanField. While partial_update, serializer is always set all boolean values to false, if it is not set in request. My models.py class User(AbstractUser): agree_email = BooleanField(blank=True) agree_sms = BooleanField(blank=True) serializers.py class UserChangeSeri...
[ "Maybe you can set current value as default value when request data does not have the field.\nclass UserChangeSerializer(serializers.ModelSerializer):\n class Meta:\n model = AZUser\n fields = (\"first_name\", \"agree_email\", \"agree_sms\")\n def validate(self, attrs):\n if self.instance...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074346319_django_django_rest_framework_python.txt
Q: How come the global variable is not returned despite keyword global being used I have accessed a global variable called counter using the keyword global however the function does not return the global variable. Oddly, print works but not return. FYI: The function below is recursive and is supposed to take as input...
How come the global variable is not returned despite keyword global being used
I have accessed a global variable called counter using the keyword global however the function does not return the global variable. Oddly, print works but not return. FYI: The function below is recursive and is supposed to take as input any integer and output the number of steps required to reduce it to 0, depending on...
[]
[]
[ "As pointed out by @tripleee this is a duplicate of this post\nIn short, Python implicitly returns None if a return statement is not added.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074346337_python.txt
Q: How can i distinguish between square and circular shapes from accelerometer and gyroscope sensor data using python? I have xyz axis for gyro and accelerometer data, and i want to detect between whether the travel path was circular or square Have not tried anything, want initial ideas
How can i distinguish between square and circular shapes from accelerometer and gyroscope sensor data using python?
I have xyz axis for gyro and accelerometer data, and i want to detect between whether the travel path was circular or square Have not tried anything, want initial ideas
[]
[]
[ "The way I would approach this would be:\nFirst compute some characteristics about my data such as:\n\ncentroid of my points\nmax distance between two points\n...\n\nThen create reference shapes with that data, for example a circle with its center being the computed centroid of my points, and its diameter being the...
[ -1 ]
[ "matplotlib", "python" ]
stackoverflow_0074346346_matplotlib_python.txt
Q: how to print items of two lists in a same line in python. can't use any pre-defined functions except basic ones players_list = [a,b,c,d,e] scores_list = [1,2,3,4,5] I want the output to be like: "-a_____________1-" "-b_____________2-" "-c_____________3_" and so on I have tried using a nested loop, 2 loops and...
how to print items of two lists in a same line in python. can't use any pre-defined functions except basic ones
players_list = [a,b,c,d,e] scores_list = [1,2,3,4,5] I want the output to be like: "-a_____________1-" "-b_____________2-" "-c_____________3_" and so on I have tried using a nested loop, 2 loops and text formatting and lots of stuff but still can't figure out.
[ "players_list = ['a','b','c','d','e']\nscores_list = [1,2,3,4,5]\nfor p, s in zip(players_list, scores_list):\n print(f\"-{p}_____________{s}-\")\n\n", "You can use zip function to combine multiple lists:\nplayers_list = ['a','b','c','d','e']\nscores_list = [1,2,3,4,5]\n\nfor player, score in zip(players_list,...
[ 1, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074346432_loops_python.txt
Q: Is there a difference between resizing and rescaling an image in computer vision? I have a research paper to implement. The author has used words rescale and resize in the context of an image. Are these two different operations or both mean the same thing. A: Resizing: "Resizing an object changes only the objec...
Is there a difference between resizing and rescaling an image in computer vision?
I have a research paper to implement. The author has used words rescale and resize in the context of an image. Are these two different operations or both mean the same thing.
[ "Resizing:\n\n\"Resizing an object changes only the object's dimensions (width and\n height). For example, when you resize an object that has a specific\n stroke thickness, the stroke thickness stays the same when the object\n resizes.\"\n\nScaling:\n\n\"Scaling applies a transform to the object that resizes the...
[ 3, 0 ]
[]
[]
[ "computer_vision", "image_processing", "python" ]
stackoverflow_0040819502_computer_vision_image_processing_python.txt
Q: Reshape your data either using array.reshape(-1, 1) during model.predict()? I'm trying to run a number of classification models, but all of them keep throwing the reshape error. I think it has to do with the calculation of model.score or model.predict but i've tried running some reshape commands (on X_valid and Y_...
Reshape your data either using array.reshape(-1, 1) during model.predict()?
I'm trying to run a number of classification models, but all of them keep throwing the reshape error. I think it has to do with the calculation of model.score or model.predict but i've tried running some reshape commands (on X_valid and Y_valid) with no success Code: X = train.drop("Survived", axis=1) # features Y = tr...
[ "Try making X and Y using double brackets, this is the easiest way to turn a series into a dataframe; should remove the error too:\nX = train[['Age']]\nY = train[['Survived']]\n\n" ]
[ 0 ]
[]
[]
[ "model", "python", "reshape", "train_test_split" ]
stackoverflow_0072010335_model_python_reshape_train_test_split.txt
Q: Import "django.urls" could not be resolved from source I am expecting the solve please help me I m new at that. I tried searching but I could not find anything. A: Try to restart your code editor and instead of running django.url in your terminal, try running python manage.py runserver.
Import "django.urls" could not be resolved from source
I am expecting the solve please help me I m new at that. I tried searching but I could not find anything.
[ "Try to restart your code editor and instead of running django.url in your terminal, try running python manage.py runserver.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074346423_django_python.txt
Q: ValueError: time data 'test_str' does not match format '%m/%d/%Y' Traceback (most recent call last): File "C:\pythoneg\q2.py", line 8, in <module> print(datetime.datetime.strptime("test_str", "%m/%d/%Y").strftime("%Y-%m-%d") ) raise ValueError("time data %r does not match format %r" % I tried to read th...
ValueError: time data 'test_str' does not match format '%m/%d/%Y'
Traceback (most recent call last): File "C:\pythoneg\q2.py", line 8, in <module> print(datetime.datetime.strptime("test_str", "%m/%d/%Y").strftime("%Y-%m-%d") ) raise ValueError("time data %r does not match format %r" % I tried to read the user entered date as the input and display it in the format as i desi...
[ "You have to make an input in the same format \"%m/%d/%Y\", otherwise it wont work.\nTry it:\nimport datetime\ntest_str=input(\"Enter date\")\nformat= \"%m/%d/%Y\"\ntry :\n res= bool(datetime.strptime(test_str,format)) \n print(datetime.datetime.strptime(\"test_str\", \"%m/%d/%Y\").strftime(\"%Y-%m-%d\") )\...
[ 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074346502_datetime_python.txt
Q: How do I use python session variables in gcloud appengine I need global variables to use in a Flask Web app. Currently, I am trying to use session variables and they work just fine on the local development machine. However, when I upload the code to gcloud appengine, I find that the value of the session variable...
How do I use python session variables in gcloud appengine
I need global variables to use in a Flask Web app. Currently, I am trying to use session variables and they work just fine on the local development machine. However, when I upload the code to gcloud appengine, I find that the value of the session variable does not persist. Here is my code regarding the session varia...
[ "You've set up sessions to use the file system:\napp.config['SESSION_TYPE'] = 'filesystem'\n\nApp Engine doesn't let you write to disk. You should use cookies for storing the session.\n" ]
[ 1 ]
[]
[]
[ "flask", "gcloud", "google_app_engine", "python", "session_variables" ]
stackoverflow_0074344729_flask_gcloud_google_app_engine_python_session_variables.txt
Q: Retrieving randomically values in a dictionary with specific conditions in Python I want to extract one key out of my dictionary where the value is >= 0.05. My dictionary looks like this {'Bed_to_Toilet': 0.5645161290322581, 'Sleep': 0.016129032258064516, 'Morning_Meds': 0.03225806451612903, 'Watch_TV': 0.0, '...
Retrieving randomically values in a dictionary with specific conditions in Python
I want to extract one key out of my dictionary where the value is >= 0.05. My dictionary looks like this {'Bed_to_Toilet': 0.5645161290322581, 'Sleep': 0.016129032258064516, 'Morning_Meds': 0.03225806451612903, 'Watch_TV': 0.0, 'Kitchen_Activity': 0.04838709677419355, 'Chores': 0.0, 'Leave_Home': 0.03225806451612...
[ "1st, get a list of reference keys that match your criteria:\ncandidate_list = [k for k,v in startActModel.items() if v >= 0.05]\n\nThen you can random.choice from that list:\nmykey = random.choice(candidate_list)\n\nAt which point, if wanted, you can go back and access the value chosen:\nmyval = startActModel[myke...
[ 1, 0 ]
[]
[]
[ "choice", "dictionary", "python", "python_3.x", "random" ]
stackoverflow_0074346397_choice_dictionary_python_python_3.x_random.txt
Q: The auditorium of the theater on the heat map I need to display the most popular seats in the auditorium on the heat map. I have a list of rows and seats and the number of tickets purchased for a period of 1 year. The task is trivial if not for one thing. The auditorium has the shape of a trapezoid. The number of ...
The auditorium of the theater on the heat map
I need to display the most popular seats in the auditorium on the heat map. I have a list of rows and seats and the number of tickets purchased for a period of 1 year. The task is trivial if not for one thing. The auditorium has the shape of a trapezoid. The number of seats in the last rows is less than in the first, s...
[ "This assignment is an assignment in the realm of pandas, not plotly. I'm sure there are other smarter ways, but I would find the number of columns excluding NA for each row, subtract the number of columns obtained from the maximum number of columns, and divide that by 2 to get a symmetrical form. Combine that into...
[ 0 ]
[]
[]
[ "heatmap", "plotly", "python" ]
stackoverflow_0074344705_heatmap_plotly_python.txt
Q: Best structure for nested dataset in python a have an NLP problem at hand, where I need to create a nested dataset. I'm looking for a structure for my dataset that makes it easy for me to navigate through the dataset while coding. My dataset consists of a context that will be divided into sub-contexts. Each sub-co...
Best structure for nested dataset in python
a have an NLP problem at hand, where I need to create a nested dataset. I'm looking for a structure for my dataset that makes it easy for me to navigate through the dataset while coding. My dataset consists of a context that will be divided into sub-contexts. Each sub-context will then be divided into sentences. And fo...
[ "If you want to process those kind of dataset in the python file, your idea is one of the solution. But, if you want to save those NL dataset for future, you might consider save it to XML or JSON formatting (into file [.xml] or [.json]).\n<data>\n <part 1> text\n <context> text\n <sentences> te...
[ 0 ]
[]
[]
[ "dataset", "nlp", "python" ]
stackoverflow_0074346137_dataset_nlp_python.txt
Q: Microsoft 365 Graph API - how to read mail box of all users I have a Microsoft 365 admin user. I try to read other users’ emails using the Microsoft 365 graph API. I adopted the following from github based on a Microsoft tutorial: import requests graph_endpoint = 'https://graph.microsoft.com/v1.0{0}' def make_ap...
Microsoft 365 Graph API - how to read mail box of all users
I have a Microsoft 365 admin user. I try to read other users’ emails using the Microsoft 365 graph API. I adopted the following from github based on a Microsoft tutorial: import requests graph_endpoint = 'https://graph.microsoft.com/v1.0{0}' def make_api_get_call(url, token, parameters=None): headers = { ...
[ "\nI have a Microsoft 365 admin user. I try to read other users’ emails using the Microsoft 365 graph API.\n\nAdmin users don't have the permission to read other people mailboxes eg if you tried to do this in OWA or Outlook you would get the same issue. You need explicitly delegate access to a Mailbox using somethi...
[ 0, 0 ]
[]
[]
[ "api", "microsoft_graph_api", "microsoft_graph_mail", "office365", "python" ]
stackoverflow_0069167086_api_microsoft_graph_api_microsoft_graph_mail_office365_python.txt
Q: How do I write a python pandas.DataFrame to a file using aligned space chacarcters? I want to store a pandas.DataFrame to a text file that has the columns aligned using whitespace characters. If this is my sample DataFrame: In [1]: import numpy as np In [2]: import pandas as pd In [3]: df = pd.DataFrame(np.linspa...
How do I write a python pandas.DataFrame to a file using aligned space chacarcters?
I want to store a pandas.DataFrame to a text file that has the columns aligned using whitespace characters. If this is my sample DataFrame: In [1]: import numpy as np In [2]: import pandas as pd In [3]: df = pd.DataFrame(np.linspace(0,1,9).reshape(3,3)) In [4]: df Out[4]: 0 1 2 0 0.000 0.125 0.250...
[ "How about this\nimport numpy as np\nimport pandas as pd\nimport csv\n\ndf = pd.DataFrame(np.linspace(0,1,9).reshape(3,3))\ndf.to_csv('test.txt', \n float_format='%10.3f', sep=\" \", \n quoting=csv.QUOTE_NONE, escapechar=\" \")\n\nIt produces:\n 0 1 2\n0 0.000 0.125 0...
[ 4, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0029243323_pandas_python.txt
Q: Calling functions by array index in Python I have a bunch of functions in Python out1, out2, out3 etc. and would like to call them based on an integer I pass in. def arryofPointersToFns (value): #call outn where n = value Is there an easy way to do this? A: tl;dr: Write an out(n) function rather than out1...
Calling functions by array index in Python
I have a bunch of functions in Python out1, out2, out3 etc. and would like to call them based on an integer I pass in. def arryofPointersToFns (value): #call outn where n = value Is there an easy way to do this?
[ "tl;dr: Write an out(n) function rather than out1(), out2(), ..., outN() and don't bother with this hack.\nI cannot imagine a reasonable scenario where this question would come up in practice. Please reconsider the architecture of the problem; there is likely to be a much better way to do this (because storing them...
[ 51, 4, 2, 1 ]
[ " def array(ar=[]):\n ar = np.array(ar)\n return ar\n\n" ]
[ -3 ]
[ "delegates", "python" ]
stackoverflow_0005707589_delegates_python.txt