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 handle asynchronous file loading with events in Python So I am a little confused on how to use events in Python. I have an API for a program I use that recently changed its file loading method to be asynchronous. These files can take a while to load and in the past the file loading method would halt executi...
How to handle asynchronous file loading with events in Python
So I am a little confused on how to use events in Python. I have an API for a program I use that recently changed its file loading method to be asynchronous. These files can take a while to load and in the past the file loading method would halt execution until the file was loaded. Now it immediately goes on to the nex...
[ "You can use something like\nimport asyncio\n\nloop = asyncio.get_event_loop()\nfileLoader = loop.run_until_complete(API.FileLoader())\nloop.run_until_complete(fileLoader.LoadFile('path/to/file'))\n\nto be sure that you will load the file before the code pass to the next line\n", "If this API is working the way I...
[ 0, 0 ]
[]
[]
[ "asynchronous", "event_handling", "python" ]
stackoverflow_0074483839_asynchronous_event_handling_python.txt
Q: Generating values based on mean and std listed in a dataframe I have a data frame of this format: import pandas as pd df = pd.DataFrame({ 1: {'mean': 1.0, 'std': 0.8}, 2: {'mean': 0.5, 'std': 0.2}, 3: {'mean': 0.2, 'std': 0.1}, 4: {'mean': 0.1, 'std': 0.1}, 5: {'mean': 0.6, 'std': 0.2} }) df ...
Generating values based on mean and std listed in a dataframe
I have a data frame of this format: import pandas as pd df = pd.DataFrame({ 1: {'mean': 1.0, 'std': 0.8}, 2: {'mean': 0.5, 'std': 0.2}, 3: {'mean': 0.2, 'std': 0.1}, 4: {'mean': 0.1, 'std': 0.1}, 5: {'mean': 0.6, 'std': 0.2} }) df 1 2 3 4 5 mean 1.0 0.5 0.2 0.1 0.6 std 0...
[ "To create what you want I would suggest iterating over the dataframe df one column at a time (to do so first transpose the dataframe and then use iterrows).\nFor each column you can generate a numpy array of the lenght you desire from a normal distribution using the mean and std from the column.\nAt the end you ca...
[ 2, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074492252_dataframe_numpy_pandas_python.txt
Q: euler problem 3 unrepresentative answer in different number so. i've been trying to solve a Euler's problem #3 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? my knowledge is low. so i came here and found a perfect solution which takes only 140ms for t...
euler problem 3 unrepresentative answer in different number
so. i've been trying to solve a Euler's problem #3 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? my knowledge is low. so i came here and found a perfect solution which takes only 140ms for the number in the problem (600851475143) my guess was that for the...
[ "The reason the code appends a 1 at the end for 6859 is that the last prime factor is contained multiple times and so the inner while loop runs until n == 1\nYou could fix the code by adding a check if n is different from 1 before you add it like so:\nn = 6859\ni = 2\nb = []\nwhile i * i < n:\n while n % i == 0:...
[ 0 ]
[]
[]
[ "primes", "python" ]
stackoverflow_0074492370_primes_python.txt
Q: Python: Create list from variables as long as they are not None How do I add multiple variables to a list as long as they are not None? If either one of them is None, then only the other one should be added to the list. a = "A" b = None list_items = [a + b] Gives: TypeError: ("cannot concatenate 'str' and 'None...
Python: Create list from variables as long as they are not None
How do I add multiple variables to a list as long as they are not None? If either one of them is None, then only the other one should be added to the list. a = "A" b = None list_items = [a + b] Gives: TypeError: ("cannot concatenate 'str' and 'NoneType' objects", u'occurred at index 0') In the above example, the ...
[ "You could create a function that takes arbitrary number of arguments and filters out the ones which are None:\ndef create_list(*args):\n return [a for a in args if a is not None]\n\nprint create_list(1, 4, None, 'a', None, 'b')\n\nOutput:\n[1, 4, 'a', 'b']\n\n", "You can query the variable directly for None:\...
[ 3, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0036129834_list_python.txt
Q: Writing into an external file with streamlit I am currently working on a ML project using streamlit in the "streamlit cloud". For model fitting, no problem, I can do it independent of streamlit and store the trained model in a pickle file. After that, the pickle file is added to the streamlit project. For several ...
Writing into an external file with streamlit
I am currently working on a ML project using streamlit in the "streamlit cloud". For model fitting, no problem, I can do it independent of streamlit and store the trained model in a pickle file. After that, the pickle file is added to the streamlit project. For several reasons, I have to write into a file inside the st...
[ "To add a file to your app programmatically, you'll want to use the GitHub API since Streamlit Community Cloud pulls your app from a GitHub repository.\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "python", "streamlit" ]
stackoverflow_0074415363_machine_learning_python_streamlit.txt
Q: django .objects.values_list how to exlude None value I'm using django .objects.values_list to get all the values of a filed of Model: def gen_choice(filed): return list(Mymodel.objects.values_list(filed, flat=True).distinct()) I want to exclude all the None value in the above query set : Mymodel.objects....
django .objects.values_list how to exlude None value
I'm using django .objects.values_list to get all the values of a filed of Model: def gen_choice(filed): return list(Mymodel.objects.values_list(filed, flat=True).distinct()) I want to exclude all the None value in the above query set : Mymodel.objects.values_list(filed, flat=True).distinct() Or the list: lis...
[ "You can pass this as kwargs, so:\ndef gen_choice(flield):\n return list(\n Mymodel.objects.exclude(**{field: None})\n .values_list(field, flat=True)\n .distinct()\n )\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "django_queryset", "django_views", "python" ]
stackoverflow_0074492527_django_django_models_django_queryset_django_views_python.txt
Q: how to access min_entries in Flask WTF, in another file? please tell me how to access min_entries correctly, I need it to generate fields for the form. My codes: forms.py: class ToSend(FlaskForm): send = FieldList(FormField(AddEquipment), min_entries=()) equipment_add.py: @app.route('/equipment_add', methods=...
how to access min_entries in Flask WTF, in another file?
please tell me how to access min_entries correctly, I need it to generate fields for the form. My codes: forms.py: class ToSend(FlaskForm): send = FieldList(FormField(AddEquipment), min_entries=()) equipment_add.py: @app.route('/equipment_add', methods=['GET', 'POST']) def addEquipment(): update = 0 if re...
[ "The problem arises because you didn't specify an integer as the value for the minimum number when defining the FieldList, but a pair of brackets.\nIf you don't enter a value here, the default value of 0 will be used automatically.\nAs I understand your code, you want to dynamically add form fields depending on the...
[ 0 ]
[]
[]
[ "flask", "flask_wtforms", "python", "python_3.x" ]
stackoverflow_0074488076_flask_flask_wtforms_python_python_3.x.txt
Q: Is there a database independent way to filter by "None"/"NaN"? The following code is database specific: import sqlalchemy # ... ergebnis = session.query( my_object.attr1).filter(sa.and_( my_object.attr2 != 'NaN')).all() # PostgreSQL """ my_object.attr2 != None)).all() # sQLite "...
Is there a database independent way to filter by "None"/"NaN"?
The following code is database specific: import sqlalchemy # ... ergebnis = session.query( my_object.attr1).filter(sa.and_( my_object.attr2 != 'NaN')).all() # PostgreSQL """ my_object.attr2 != None)).all() # sQLite """ With PostgreSQL it is "'NaN'", with SQLite "None" (without singl...
[ "If you want to compare against the 'NaN' (\"not a number\") float value, then do an explicit cast to float: float('NaN'). In this case SQLAlchemy should do the same conversion.\n", "This seems to work for Postgres, but I don't know how database-independent it is:\nimport sqlalchemy as sqla\n\n...\n\nmyobject.att...
[ 0, 0 ]
[]
[]
[ "postgresql", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0005401455_postgresql_python_sqlalchemy_sqlite.txt
Q: Looping through variables in Python I've written a program to randomly assign teams to four people for a World Cup sweepstakes. The code works fine, but it's ugly. How do I shuffle the variables Seed1, Seed2, ... Seed8 with a loop? How do I print which teams have been assigned to each player with more professional...
Looping through variables in Python
I've written a program to randomly assign teams to four people for a World Cup sweepstakes. The code works fine, but it's ugly. How do I shuffle the variables Seed1, Seed2, ... Seed8 with a loop? How do I print which teams have been assigned to each player with more professional looking code? import random Teams = ["A...
[ "I would suggest putting the seeds is a list:\nimport random\n\nteams = [\"Alice\", \"Bob\", \"Charlie\", \"Delilah\"]\nrandom.shuffle(teams)\n\nseeds = [\n [\"Brazil\", \"Argentina\", \"France\", \"Spain\"],\n [\"England\", \"Germany\", \"Netherlands\", \"Portugal\"],\n [\"Belgium\", \"Denmark\", \"Urugua...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074492557_python.txt
Q: How to improve Column Validation For Dataframes Pyspark I have a function that validates if the dataframe passed has a few columns and if it does not it creates them and fills the values with 0.0. This takes a bit of time to run and has several if statements. Is there any way this function can be improved? In trut...
How to improve Column Validation For Dataframes Pyspark
I have a function that validates if the dataframe passed has a few columns and if it does not it creates them and fills the values with 0.0. This takes a bit of time to run and has several if statements. Is there any way this function can be improved? In truth, I run this for multiple dataframes but at the moment I nee...
[ "For a single dataframe, you can use a for-loop just to improve code understandability. You need to pass a list of columns to the function.\ndef validate_columns(df, cols_of_interest):\n \n for c in cols_of_interest:\n if c not in df.columns:\n df = df.withColumn(c, lit(0.0))\n \n result = df.select(*co...
[ 1 ]
[]
[]
[ "dataframe", "loops", "pyspark", "python", "validation" ]
stackoverflow_0074492086_dataframe_loops_pyspark_python_validation.txt
Q: how to replace Unicode Hex Character Code my_string = "smart watch Xiaomi &#x2F; Smart watches for women, men, children" How can I get the character "/". i do this: my_string.replace("&#x2F;", "/") But I don't want to use this method. A: html — HyperText Markup Language support html.unescape(s) Convert all nam...
how to replace Unicode Hex Character Code
my_string = "smart watch Xiaomi &#x2F; Smart watches for women, men, children" How can I get the character "/". i do this: my_string.replace("&#x2F;", "/") But I don't want to use this method.
[ "html — HyperText Markup Language support\n\nhtml.unescape(s)\nConvert all named and numeric character references (e.g. &gt;,\n&#62;, &#x3e;) in the string s to the corresponding Unicode\ncharacters. This function uses the rules defined by the HTML 5\nstandard for both valid and invalid character references, and th...
[ 1 ]
[]
[]
[ "hex", "python", "unicode" ]
stackoverflow_0074492044_hex_python_unicode.txt
Q: convert columns of pyspark data frame to lowercase I have a dataframe in pyspark which has columns in uppercase like ID, COMPANY and so on I want to make these column names to id company and so on. Bacially convert all the columns to lowercase or uppercase depending on the requirement. I want to do in such away th...
convert columns of pyspark data frame to lowercase
I have a dataframe in pyspark which has columns in uppercase like ID, COMPANY and so on I want to make these column names to id company and so on. Bacially convert all the columns to lowercase or uppercase depending on the requirement. I want to do in such away that the data types of the columns remain the same. How ca...
[ "Use columns field from DataFrame\ndf = // load\nfor col in df.columns:\n df = df.withColumnRenamed(col, col.lower())\n\nOr, as @zero323 suggested:\ndf.toDF(*[c.lower() for c in df.columns])\n\n", "Could also use select with alias (be sure pyspark.sql.functions are imported as \"f\"):\ndf.select([f.col(col).al...
[ 47, 0 ]
[]
[]
[ "apache_spark", "pyspark", "python", "spark_dataframe" ]
stackoverflow_0043005744_apache_spark_pyspark_python_spark_dataframe.txt
Q: Copy TTree to Other File I'm trying to extract cycles/revisions ("TreeName;3" etc) from one root file and make them their own trees in a new one. I tried doing it by creating a new file and assigning it to a new name, but I get an error telling me that TTree is not writable with uproot.open("old_file.root") as in_...
Copy TTree to Other File
I'm trying to extract cycles/revisions ("TreeName;3" etc) from one root file and make them their own trees in a new one. I tried doing it by creating a new file and assigning it to a new name, but I get an error telling me that TTree is not writable with uproot.open("old_file.root") as in_file: with uproot.recreate...
[ "I decided to give a complete working example (following up on comments, above), but found that there are a lot of choices to be made. All you want to do is to copy the input TTree—you don't want to make choices—so you really want a high-level \"copy whole TTree\" function, but such a function does not exist. (That...
[ 0 ]
[]
[]
[ "python", "root", "uproot" ]
stackoverflow_0074490023_python_root_uproot.txt
Q: i need help to shorten this code a lot preferable id like to make the month selection a function but cant due to having to call in different csv files i need help to shorten this code a lot im trying to make the month selection witch is repeating shorter or into a function preferable but cant make it work, id like...
i need help to shorten this code a lot preferable id like to make the month selection a function but cant due to having to call in different csv files
i need help to shorten this code a lot im trying to make the month selection witch is repeating shorter or into a function preferable but cant make it work, id like to make the month selection a function but cant due to having to call in different csv files what you guys got? csv files (https://send.tresorit.com/a#1NoM...
[ "You can do:\nif a in range(1,13):\n c = df8.loc[a-1]\n print(c)\nelse:\n print(\"Invalid choice\")\n\n", "Look at the pattern of your if statements. The value of c is set to an element located at a certain point in df8. All of your if statements check a and then find the location of the element using th...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074492599_python.txt
Q: python request does not return what was requested Yo! I am learning requests in python and i get a problem! when i try to get status code from the url i dont receive answer When I run the program, it doesn't finish or return anything. Below is a picture of the terminal and my code. import requests import socket o...
python request does not return what was requested
Yo! I am learning requests in python and i get a problem! when i try to get status code from the url i dont receive answer When I run the program, it doesn't finish or return anything. Below is a picture of the terminal and my code. import requests import socket old_getaddrinfo = socket.getaddrinfo def new_getaddrinf...
[ "Your code keeps waiting for a response. Try adding timeout in your request.\nres = requests.get('https://www.americanas.com.br/', timeout=5)\n\nUsing this, your request will last for only 5 seconds before throw and exception.\n", "It seems like the server is not responding without a user agent header.\nJust set ...
[ 0, 0 ]
[]
[]
[ "get", "http", "python", "python_requests", "web_scraping" ]
stackoverflow_0074492431_get_http_python_python_requests_web_scraping.txt
Q: Python- replace last n chars of a specific section of a specific row found in a text file I have 1000s of text files where I want to replace a very specific section of text with a predefined string. These files contain data like this: Type Basemap 20221118202211 QSNGA...
Python- replace last n chars of a specific section of a specific row found in a text file
I have 1000s of text files where I want to replace a very specific section of text with a predefined string. These files contain data like this: Type Basemap 20221118202211 QSNGAGL1 20221120209912300111111 1B Bus O QO1290BOB203871145 T1 QI1290BO...
[ "Try (regex demo):\nimport re\n\npat = re.compile(r\"(^\\s*QS\\S+\\s*)(\\d+?)\\d{7}\\b\")\n\nwith open(\"input.txt\", \"r\") as f_in, open(\"fixed_output.txt\", \"w\") as f_out:\n for line in f_in:\n line = pat.sub(r\"\\g<1>\\g<2>1111100\", line)\n f_out.write(line)\n\nIf input.txt contains the tex...
[ 2 ]
[]
[]
[ "pandas", "python", "python_re", "replace" ]
stackoverflow_0074492488_pandas_python_python_re_replace.txt
Q: 'Prophet' object has no attribute 'stan_backend' and there is no answer for me I want to use Facebook's prophet,however when I try to create a model: model = prt.Prophet(stan_backend='CMDSTANPY') It occurs mistake like this: Traceback (most recent call last): File "C:\Users\UserName\IdeaProjects\station-simulat...
'Prophet' object has no attribute 'stan_backend' and there is no answer for me
I want to use Facebook's prophet,however when I try to create a model: model = prt.Prophet(stan_backend='CMDSTANPY') It occurs mistake like this: Traceback (most recent call last): File "C:\Users\UserName\IdeaProjects\station-simulate\stcd-predict.py", line 24, in <module> model = prt.Prophet(stan_backend='CMDST...
[ "Now I changed another computer and created a new conda environment,solved this.\n" ]
[ 0 ]
[]
[]
[ "facebook", "facebook_prophet", "intellij_idea", "python" ]
stackoverflow_0074085683_facebook_facebook_prophet_intellij_idea_python.txt
Q: Python argparse with optional nargs ath the end of multiple subparsers I'm trying to achieve the following command definition with argparse, but I can't seem to figure it out: script.py {scan,list} ... [targets [targets...]] I've gone through the complete documentation and checked multiple different questions whic...
Python argparse with optional nargs ath the end of multiple subparsers
I'm trying to achieve the following command definition with argparse, but I can't seem to figure it out: script.py {scan,list} ... [targets [targets...]] I've gone through the complete documentation and checked multiple different questions which were somewhat related, however, I can't find a resource which seems to add...
[ "Subparsers is a relatively simple, and modular, addition to the basic parsing. Most of the work is done by a custom Action subclass. So there isn't a lot of flexibility, in setup, parsing, or help, beyond what's documented.\nTo clarify how subparsers works, and expand on my comments, let's define a parser:\nIn [...
[ 1 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0074385918_argparse_python.txt
Q: how i can replace different values in a column to category based on their values enter image description here pls see attached image I have different values in a column, for example, if I have the word 'car' in any values I want to change these values to car ... if I have the word wedding in the value I want to ch...
how i can replace different values in a column to category based on their values
enter image description here pls see attached image I have different values in a column, for example, if I have the word 'car' in any values I want to change these values to car ... if I have the word wedding in the value I want to change the value to the wedding... pls help to write the code in python I tried this cod...
[ "You could try first detecting if the substring you are looking for is in the string, and if it is you replace the value for what you want, like this:\ncredit_scoring = credit_scoring.fillna('')\n\nfor i in range(0,len(credit_scoring)):\n if \"car\" in credit_scoring.loc[i, \"purpose\"]:\n credit_scoring....
[ 1 ]
[]
[]
[ "group_by", "pandas", "python", "replace", "string" ]
stackoverflow_0074492472_group_by_pandas_python_replace_string.txt
Q: scipy.stats.multivariate_normal error: input matrix must be symmetric positive definite i'm trying to compute the cumulative distribution function of a multivariate normal using scipy. i'm having trouble with the "input matrix must be symmetric positive definite" error. to my knowledge, a diagonal matrix with posi...
scipy.stats.multivariate_normal error: input matrix must be symmetric positive definite
i'm trying to compute the cumulative distribution function of a multivariate normal using scipy. i'm having trouble with the "input matrix must be symmetric positive definite" error. to my knowledge, a diagonal matrix with positive diagonal entries is positive definite (see page 1 problem 2) However, for different (rel...
[ "Examining the stack trace you will see that it assumes the condition number as\n1e6*np.finfo('d').eps ~ 2.2e-10 in _eigvalsh_to_eps\nIn your example the difference the smaller eigenvalue is 5e-6**2 times smaller than the largest eigenvalue so it will be treated as zero.\nYou can pass allow_singular=True to get it ...
[ 0 ]
[]
[]
[ "python", "scipy", "scipy.stats" ]
stackoverflow_0074491826_python_scipy_scipy.stats.txt
Q: Is the to_delete parameter required in my code to extract from BigQuery to GCS? I have written some code to extract from BigQuery to a GCS Bucket, using the Google Cloud Docs, and I am unsure whether the to_delete parameter is required in my code. I have not tried anything yet, as I am unsure what I would replace ...
Is the to_delete parameter required in my code to extract from BigQuery to GCS?
I have written some code to extract from BigQuery to a GCS Bucket, using the Google Cloud Docs, and I am unsure whether the to_delete parameter is required in my code. I have not tried anything yet, as I am unsure what I would replace the parameter with. This is my code: def extract_table(client, to_delete): bucket...
[ "If you only want to export a BigQuery table to GCS, I think no need a param like to_delete.\nYou may also use a built in Airflow operator to execute the same code as you shown in your question but with BigQueryToGCSOperator operator :\nfrom airflow.providers.google.cloud.transfers.bigquery_to_gcs import BigQueryTo...
[ 1 ]
[]
[]
[ "airflow", "directed_acyclic_graphs", "google_bigquery", "google_cloud_platform", "python" ]
stackoverflow_0074490752_airflow_directed_acyclic_graphs_google_bigquery_google_cloud_platform_python.txt
Q: Column Does not Show Up in Pandas? Here is the code we're working with; basically just takes data from multiple scrapped datasets and then concatenates them. import pandas as pd import numpy as np # for numeric python functions from pylab import * # for easy matplotlib plotting from bs4 import BeautifulSoup import...
Column Does not Show Up in Pandas?
Here is the code we're working with; basically just takes data from multiple scrapped datasets and then concatenates them. import pandas as pd import numpy as np # for numeric python functions from pylab import * # for easy matplotlib plotting from bs4 import BeautifulSoup import requests url1='http://openinsider.com/s...
[ "The problem is that the character between Insider & Name is not 'space'.\nTry:\nprint(All['Insider\\xa0Name'])\n\nThis will fix the issue:\nAll.rename(columns={\"Insider\\xa0Name\": \"Insider Name\"}, inplace=True)\n\n" ]
[ 1 ]
[]
[]
[ "data_science", "pandas", "python", "web_scraping" ]
stackoverflow_0074492647_data_science_pandas_python_web_scraping.txt
Q: Add notes using openpyxl everyone. I'm looking for a way to make notes in excel worksheet, using python. Found a way to add comments, but I need notes like on screenshot. Is there an easy way to add them using openpyxl or any other lib? screenshot of a note A: I've been trying to accomplish the same thing. Appar...
Add notes using openpyxl
everyone. I'm looking for a way to make notes in excel worksheet, using python. Found a way to add comments, but I need notes like on screenshot. Is there an easy way to add them using openpyxl or any other lib? screenshot of a note
[ "I've been trying to accomplish the same thing. Apparently that \"note\" is the same as data validation as described in the docs.\nSo what you do is:\nfrom openpyxl import load_workbook\nfrom openpyxl.worksheet.datavalidation import DataValidation\n\nwb = load_workbook('my_sheets.xlsx')\n\n# Create 'note'\ndv = Dat...
[ 0, 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0066680916_excel_openpyxl_python.txt
Q: "TypeError: is not a generic class" when importing the plotly.express library I want to create a simple plotly chart from a .csv file that I fetched from an API. I import the library, pass the dataframe, and get the error: TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class code: ...
"TypeError: is not a generic class" when importing the plotly.express library
I want to create a simple plotly chart from a .csv file that I fetched from an API. I import the library, pass the dataframe, and get the error: TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class code: import plotly.express as px df=pd.read_csv('file.csv') What might be the problem, ...
[ "I got the same error, it is dependency issue, plotly.express (5.9.0) is not working with numpy==1.20, if you upgrade numpy==1.21.6 it will solve your error.\npip install numpy==1.21.6\n\n", "I was having same issue when I updated xarray. I tried updating numpy but conda environment was restricting it. Updating t...
[ 5, 1, 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0073286085_plotly_python.txt
Q: Numpy is not saving csv properly I have a simple numpy array made of floats and integers array_to_save=np.array([shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]) I would like to save this numpy array, appending it to an existing csv file by doing the following. with open('frames_stats.cs...
Numpy is not saving csv properly
I have a simple numpy array made of floats and integers array_to_save=np.array([shutter_time,int(nb_frames),np.mean(intensities),np.std(intensities)]) I would like to save this numpy array, appending it to an existing csv file by doing the following. with open('frames_stats.csv','a') as csvfile: np.s...
[ "Use pandas DataFrame append and DataFrame to_csv\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.append.html\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html\n", "You are saving a one dimension array (1 column) but you are expecting the result of a 2 dimensions array with...
[ 2, 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074492328_numpy_python.txt
Q: Discord Bot Not Responding to Commands (Python) I've just gotten into writing discord bots. While trying to follow online instructions and tutorials, my bot would not respond to commands. It responded perfectly fine to on_message(), but no matter what I try it won't respond to commands. I'm sure it's something sim...
Discord Bot Not Responding to Commands (Python)
I've just gotten into writing discord bots. While trying to follow online instructions and tutorials, my bot would not respond to commands. It responded perfectly fine to on_message(), but no matter what I try it won't respond to commands. I'm sure it's something simple, but I would appreciate the help. import discord ...
[ "I made the same mistake at first.\n@bot.event\nasync def on_message(message):\n if message.content == 'test':\n await message.channel.send('Testing 1 2 3')\n\nThis function overiding the on_message event so it is never sent to bot.command()\nTo fix it you just have to add await bot.process_commands(messa...
[ 15, 0, 0 ]
[]
[]
[ "bots", "command", "discord", "python" ]
stackoverflow_0064692669_bots_command_discord_python.txt
Q: How to make parent boxes so that data is not visible untill clicked?(Treemap, plotly) fig = px.treemap(Data, path=[Year,AC_NAME,PARTY], values=Vote_Share, color=PARTY,title='Sales/Profit Overview', ) When I use this code I get something like this: H...
How to make parent boxes so that data is not visible untill clicked?(Treemap, plotly)
fig = px.treemap(Data, path=[Year,AC_NAME,PARTY], values=Vote_Share, color=PARTY,title='Sales/Profit Overview', ) When I use this code I get something like this: How do I make two-parent boxes like this : Now when someone clicks on 2016 he gets 2016 stu...
[ "You can set the maxdepth parameter in px.Treemap() to achieve this.\nFor example setting maxdepth = 1 in your example would produce the second figure, and then once you click on one of them, the partitioning would show up.\nHope this helps! Was trying to figure this out myself.\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "plotly", "python", "treemap" ]
stackoverflow_0066776806_jupyter_notebook_plotly_python_treemap.txt
Q: Compare 2 list columns in a pandas dataframe. Remove value from one list if present in another Say I have 2 list columns like below: group1 = [['John', 'Mark'], ['Ben', 'Johnny'], ['Sarah', 'Daniel']] group2 = [['Aya', 'Boa'], ['Mab', 'Johnny'], ['Sarah', 'Peter']] df = pd.DataFrame({'group1':group1, 'group2':gro...
Compare 2 list columns in a pandas dataframe. Remove value from one list if present in another
Say I have 2 list columns like below: group1 = [['John', 'Mark'], ['Ben', 'Johnny'], ['Sarah', 'Daniel']] group2 = [['Aya', 'Boa'], ['Mab', 'Johnny'], ['Sarah', 'Peter']] df = pd.DataFrame({'group1':group1, 'group2':group2}) I want to compare the two list columns and remove the list elements from group1 if they are p...
[ "You need to zip the two Series. I'm using a set here for efficiency (this is not critical if you have only a few items per list):\ndf['group1'] = [[x for x in a if x not in S]\n for a, S in zip(df['group1'], df['group2'].apply(set))]\n\nOutput:\n group1 group2\n0 [John, Mark] ...
[ 3, 2, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074486315_dataframe_pandas_python.txt
Q: Using a for loop to find a username and password in a dictionary I am trying to ask the user to enter the username and password and if it is wrong, the programme must repeatedly ask the user to enter the username and password until the correct ones are entered users = { 'admin': {'password': 'adm1n'}, 'man...
Using a for loop to find a username and password in a dictionary
I am trying to ask the user to enter the username and password and if it is wrong, the programme must repeatedly ask the user to enter the username and password until the correct ones are entered users = { 'admin': {'password': 'adm1n'}, 'man': {'password': 'thing'}, 'cool': {'password': 'guy'} } while Tru...
[ "For this kind of problem, using the \"in\" statement is really useful. It checks whether something exists within a dictionary rather than your having to directly check each item. I think this code does what you are looking for.\nusers = {\n 'admin': {'password': 'adm1n'},\n 'man': {'password': 'thing'},\n ...
[ 0 ]
[]
[]
[ "dictionary", "for_loop", "python", "while_loop" ]
stackoverflow_0074491256_dictionary_for_loop_python_while_loop.txt
Q: Why does passing a dictionary as part of *args give us only the keys? The setup Let's say I have a function: def variadic(*args, **kwargs): print("Positional:", args) print("Keyword:", kwargs) Just for experiment's sake, I call it with the following: variadic({'a':5, 'b':'x'}, *{'a':4, 'b':'y'}, **{'a':3,...
Why does passing a dictionary as part of *args give us only the keys?
The setup Let's say I have a function: def variadic(*args, **kwargs): print("Positional:", args) print("Keyword:", kwargs) Just for experiment's sake, I call it with the following: variadic({'a':5, 'b':'x'}, *{'a':4, 'b':'y'}, **{'a':3, 'b':'z'}) Output: Positional: ({'a': 5, 'b': 'x'}, 'a', 'b') Keyword: {'a...
[ "In a function call, an argument prefixed with a * must be an iterable value. Each value produced by iterating over the argument is provided to the function as a separate positional argument. (Note that this is independent of a paraemter prefixed with a *, which collects positional arguments not assigned to any oth...
[ 1 ]
[]
[]
[ "dictionary", "function", "python", "variadic", "variadic_functions" ]
stackoverflow_0074492691_dictionary_function_python_variadic_variadic_functions.txt
Q: Restrict negative lookahead to be between substrings regex In my regex pattern, I would like to make sure a certain substring only occurs once in between two other substrings. So, let's take for example these strings: string_a = “this and that” string_b = "this and and that" I want to return a match for string_a ...
Restrict negative lookahead to be between substrings regex
In my regex pattern, I would like to make sure a certain substring only occurs once in between two other substrings. So, let's take for example these strings: string_a = “this and that” string_b = "this and and that" I want to return a match for string_a but not for string_b, because 'and' occurs twice there between t...
[ "You can use another tempered greedy token to temper the .* inside the lookahead:\nthis(?:(?!this|that|and(?:(?!that).)*?and).)*?that\n\nSee the regex demo.\nDetails:\n\nthis - a fixed string\n(?:(?!this|that|and(?:(?!that).)*?and).)*? - any char other than line break chars, zero or more but as few as possible occu...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074492814_python_regex.txt
Q: Using several csv files of different sizes to build a CNN model in Python I would like to create a CNN model in Python and I have organized my data in such a way that I have 100 csv files with different sizes (all of them have 141 colunms but some have 33 rows and others have 70 rows). All of those files can be ca...
Using several csv files of different sizes to build a CNN model in Python
I would like to create a CNN model in Python and I have organized my data in such a way that I have 100 csv files with different sizes (all of them have 141 colunms but some have 33 rows and others have 70 rows). All of those files can be categorized in 6 different categories. All the examples that I have seen so far f...
[ "It depends on the reason that the data are separated in different files in the first place and what you want to achieve.\nIf each file contains observations for a different entity AND you want to predict observations about EACH specific known entity, you can build a model for each entity. In this case, the entitie...
[ 0 ]
[]
[]
[ "conv_neural_network", "python", "pytorch", "tensorflow" ]
stackoverflow_0074457562_conv_neural_network_python_pytorch_tensorflow.txt
Q: How to use scipy's dijkstra function in special matrix? I have some code that let's me transform an unweighed graph into a weighed one, where some nodes have weights 1 and some have weights 0. The final result is a matrix. I would like to know how to use this matrix with the Djikstra scipy implementation but don't...
How to use scipy's dijkstra function in special matrix?
I have some code that let's me transform an unweighed graph into a weighed one, where some nodes have weights 1 and some have weights 0. The final result is a matrix. I would like to know how to use this matrix with the Djikstra scipy implementation but don't fully understand the documentation and there are not a lot o...
[ "That function will compute the full distance matrix, so you can get your distance with\ndef dijkstra_algorithm(matrix, s_id, t_id):\n transitive_matrix = scipy.sparse.csgraph.dijkstra(matrix)\n return transitive_matrix[s_id, t_id]\n\nIt mentions the dijkstra algorithm with Fibonacci heaps (python heapq I ass...
[ 0 ]
[]
[]
[ "algorithm", "dijkstra", "graph", "python", "scipy" ]
stackoverflow_0074483593_algorithm_dijkstra_graph_python_scipy.txt
Q: How to return tuple with max and its index Function named minmax_index has two parameters: one of type list and another type bool. If the Boolean parameter refers to True, the function returns a tuple containing the minimum and its index; and if it refers to False, it returns a tuple containing the maximum and its...
How to return tuple with max and its index
Function named minmax_index has two parameters: one of type list and another type bool. If the Boolean parameter refers to True, the function returns a tuple containing the minimum and its index; and if it refers to False, it returns a tuple containing the maximum and its index. eg: minmax_index([1,2,3,4],False) (4,3) ...
[ "itertae through the list and keep record of minimum and maximum element and their index\ndef mimax(lst, b):\n if not lst: \n return []\n min_val, min_index = lst[0], 0\n max_val, max_index = lst[0], 0\n\n\n for i, v in enumerate(lst):\n if min_val > v:\n min_val = v\n ...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074492803_python.txt
Q: "Exit code: 1" in anaconda navigator after reinstalling anaconda After reinstalling Anaconda, I get the error message "Exit code: 1" when I start apps using the Anaconda Navigator. e.g. "jupyter notebook" or "CMD.exe" When I use the CMD (base) via Env. or start from the windows start bar, it works. Jupyter also r...
"Exit code: 1" in anaconda navigator after reinstalling anaconda
After reinstalling Anaconda, I get the error message "Exit code: 1" when I start apps using the Anaconda Navigator. e.g. "jupyter notebook" or "CMD.exe" When I use the CMD (base) via Env. or start from the windows start bar, it works. Jupyter also runs when I start it directly from the start bar. I only get the error...
[ "Spent a few hours on this :\nYou need to run this in command prompt --> conda install ipykernel --update-deps --force-reinstall\nThere are 2 Errors popped for me for you it may be something else:\n\nWrong System-path[in my case --> C:/Windows/System32 and C:/Windows/System] PATH in Env. variables\nIf you get chcp...
[ 3, 2, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "anaconda", "exit", "jupyter", "navigator", "python" ]
stackoverflow_0070133591_anaconda_exit_jupyter_navigator_python.txt
Q: Assign values based on duplicated value of another column and length of the list of another column Pandas I have a dataframe like this: df: Collection ID 0 [{'tom': 'one'}, {'tom': 'two'}] 10 1 [{'nick': 'one'}] 10 2 [{'julie': 'one'}] 14 Wh...
Assign values based on duplicated value of another column and length of the list of another column Pandas
I have a dataframe like this: df: Collection ID 0 [{'tom': 'one'}, {'tom': 'two'}] 10 1 [{'nick': 'one'}] 10 2 [{'julie': 'one'}] 14 When the 'ID' column has duplicated values, for whichever entry of duplicates, the length of the list value of th...
[ "A possible solution:\ndf['status'] = df['Collection'].map(len)\n\ndf['status'] =(df.groupby('ID', sort=False)\n .apply(lambda g: 1*g['status'].eq(max(g['status'])))\n .reset_index(drop=True))\n\nOutput:\n Collection ID status\n0 [{'tom': 'one'}, {'tom': 'two'}...
[ 0, 0 ]
[]
[]
[ "dataframe", "list", "numpy", "pandas", "python" ]
stackoverflow_0074492302_dataframe_list_numpy_pandas_python.txt
Q: Getting the "videoId" from a YouTube video using YouTubeV3-API As the title suggests I am trying to get the "videoId" from a YouTube video. Currently this is my code, it can be replicated. import requests channel_id = "UCfjTZZ3iqy24oSg-bmi2waw" api_key = "" api_url = f"https://www.googleapis.com/youtube/v3/searc...
Getting the "videoId" from a YouTube video using YouTubeV3-API
As the title suggests I am trying to get the "videoId" from a YouTube video. Currently this is my code, it can be replicated. import requests channel_id = "UCfjTZZ3iqy24oSg-bmi2waw" api_key = "" api_url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channel_id}&maxResults=1&order=date&type=v...
[ "You need to parse the received JSON and to precise the path of the entry you are looking for, see the code below:\nimport requests, json\n\nchannel_id = \"UCfjTZZ3iqy24oSg-bmi2waw\"\napi_key = \"\"\n\napi_url = f\"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channel_id}&maxResults=1&order=d...
[ 0 ]
[]
[]
[ "http", "python", "python_requests", "youtube_api" ]
stackoverflow_0074492836_http_python_python_requests_youtube_api.txt
Q: CatBoostError: cat_features must be integer or string, real number values and NaN values should be converted to string I have a dataset with 122 columns which looks like: train.head() SK_ID_CURR TARGET NAME_CONTRACT_TYPE CODE_GENDER FLAG_OWN_CAR FLAG_OWN_REALTY CNT_CHILDREN AMT_INCOME_TOTAL AMT_CREDIT...
CatBoostError: cat_features must be integer or string, real number values and NaN values should be converted to string
I have a dataset with 122 columns which looks like: train.head() SK_ID_CURR TARGET NAME_CONTRACT_TYPE CODE_GENDER FLAG_OWN_CAR FLAG_OWN_REALTY CNT_CHILDREN AMT_INCOME_TOTAL AMT_CREDIT AMT_ANNUITY ... FLAG_DOCUMENT_18 FLAG_DOCUMENT_19 FLAG_DOCUMENT_20 FLAG_DOCUMENT_21 AMT_REQ_CREDIT_BUREAU_HOUR...
[ "You are trying to use a column with dtype float for categorical column. To fix the error convert it to an int; \ntrain[\"a\"] = train[\"a\"].astype(np.int) \n\nhowever, in your case 118975.5 doesn't look like a valid category, so you might want to double check if you want to use that column as categorical.\nHere i...
[ 7, 2, 1, 0 ]
[]
[]
[ "machine_learning", "numpy", "pandas", "python", "scikit_learn" ]
stackoverflow_0057534739_machine_learning_numpy_pandas_python_scikit_learn.txt
Q: Python selenium not working for css attribute selector I have this code: driver = webdriver.Chrome() driver.get('https://xxx') input() # pause to do some stuff like login, then manually unpause driver.find_element(By.CSS_SELECTOR, '*[data-xyz="valImLookingFor"]') If I inspect element in chrome (the same chrome ta...
Python selenium not working for css attribute selector
I have this code: driver = webdriver.Chrome() driver.get('https://xxx') input() # pause to do some stuff like login, then manually unpause driver.find_element(By.CSS_SELECTOR, '*[data-xyz="valImLookingFor"]') If I inspect element in chrome (the same chrome tab that selenium opened) and type into console document.query...
[ "Try:\ndriver.find_element(By.CSS_SELECTOR, '[data-xyz*=\"valImLookingFor\"]')\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074493025_python_selenium_web_scraping.txt
Q: How to make a custom class which inherits from Sklearn's RandomForestRegressor? I'd like to take a regression algorithm from sklearn, let's say a RandomForestRegressor: from sklearn import ensemble clf = ensemble.RandomForestRegressor(max_depth=None) class model(clf): def __init__(self): clf.__init_...
How to make a custom class which inherits from Sklearn's RandomForestRegressor?
I'd like to take a regression algorithm from sklearn, let's say a RandomForestRegressor: from sklearn import ensemble clf = ensemble.RandomForestRegressor(max_depth=None) class model(clf): def __init__(self): clf.__init__(self) def inSampleAccuracy(self): print('\"accuracy is calculated\"') ...
[ "As @Dr. Snoopy and @juanpa.arrivillaga pointed out, I fallaciously attempted to to inherit from an instance of an object from a class in the examples given in my question.\nThe syntax for inheritance from a python module object looks more like this:\nfrom sklearn import ensemble\n\nclf = ensemble.RandomForestRegre...
[ 0 ]
[]
[]
[ "oop", "python", "random_forest", "scikit_learn" ]
stackoverflow_0074453434_oop_python_random_forest_scikit_learn.txt
Q: How to do dot/cross multiplication of Vectors with Sympy I would like to know how to do dot multiplication cross multiplication add/sub of vectors with the sympy library. I have tried looking into the official documentation but I have had no luck or It was too complicated. Can anyone help me out on this? I was...
How to do dot/cross multiplication of Vectors with Sympy
I would like to know how to do dot multiplication cross multiplication add/sub of vectors with the sympy library. I have tried looking into the official documentation but I have had no luck or It was too complicated. Can anyone help me out on this? I was trying to do this simple operation a · b = |a| × |b| × cos(θ)...
[ "To do vector dot/cross product multiplication with sympy, you have to import the basis vector object CoordSys3D. Here is a working code example below:\nfrom sympy.vector import CoordSys3D\nN = CoordSys3D('N')\nv1 = 2*N.i+3*N.j-N.k\nv2 = N.i-4*N.j+N.k\nv1.dot(v2)\nv1.cross(v2)\n#Alternately, can also do\nv1 & v2 \n...
[ 4, 4, 2, 2, 2, 0 ]
[]
[]
[ "math", "python", "sympy" ]
stackoverflow_0022126133_math_python_sympy.txt
Q: How to nicely print a dictionary that has a list as the value and a String for a key [PYTHON] Basically, I would like to print a phone book and I am having a hard time printing all the info, I wanted it to look like this: Name Company Phone Number Name 1 ...
How to nicely print a dictionary that has a list as the value and a String for a key [PYTHON]
Basically, I would like to print a phone book and I am having a hard time printing all the info, I wanted it to look like this: Name Company Phone Number Name 1 Company 1 Number 1 Name 2 Company 2 ...
[ "You can try something like this:\ndict1 = {\"Name 1\": [\"Company 1\",\"Number 1\"], \"Name 2\": [\"Company 2\", \"Number 2\"], \"Name 3\": [\"Company 3\", \"Number 3\"]}\n\n# Print the names of the columns.\nprint(\"{:<10} {:<10} {:<10}\".format('NAME', 'COMPANY', 'PHONE NUMBER'))\n\n# print each data item.\nfor ...
[ 0 ]
[]
[]
[ "dictionary", "list", "printing", "python" ]
stackoverflow_0074492964_dictionary_list_printing_python.txt
Q: Is there an elegant way to pass down an argument from function1() down to a function2(), that takes several arguments? I have the following situation: def func1(a = 0, b = 0): return a + b**2 def func2(x): if x == 'a': return func1(a = 2) elif x == 'b': return func2(b = 2) print(func2...
Is there an elegant way to pass down an argument from function1() down to a function2(), that takes several arguments?
I have the following situation: def func1(a = 0, b = 0): return a + b**2 def func2(x): if x == 'a': return func1(a = 2) elif x == 'b': return func2(b = 2) print(func2('a')) Is there a way to just pass a not as a String and get rid of the if statements?
[ "Construct a dict and use that with the mapping unpacking syntax.\ndef func2(x):\n return func1(**{x: 2})\n\nYou might still want an if statement to verify that the value of x is the name of a valid parameter to func1. As shown here, a call like func2('c') will produce a TypeError when attempting to call func1 u...
[ 5 ]
[]
[]
[ "arguments", "function", "if_statement", "python" ]
stackoverflow_0074493079_arguments_function_if_statement_python.txt
Q: Beginner: Why am I getting this error: IndexError: list assignment index out of range I'm a beginner with Python and wanted to make a script to collect some basketball stats from basketball-reference.com and sort the list based on a certain stat. I understand this error is thrown when you try to reference an index...
Beginner: Why am I getting this error: IndexError: list assignment index out of range
I'm a beginner with Python and wanted to make a script to collect some basketball stats from basketball-reference.com and sort the list based on a certain stat. I understand this error is thrown when you try to reference an index in a list where that index does not exist. But I've tried creating both a completely empty...
[ "player = [] is an empty list. If you want to assign values to this list you have to use append or any other method. This method will give you error:\nfor x in range(5):\n player[x] = player_first_name[x] + \" \" + player_last_name[x]\n\n#IndexError: list assignment index out of range\n\nYou cannot simply do a ...
[ 1, 0 ]
[]
[]
[ "indexing", "list", "python", "python_3.x" ]
stackoverflow_0074492912_indexing_list_python_python_3.x.txt
Q: How to display image data returned from dreambooth / stable-diffusion model? I'm querying a dreambooth model from Hugging Face using the inference API and am getting a huge data response string back which starts with: ����çx00çx10JFIFçx00çx01çx01çx00çx00çx01çx0... Content-type is: image/jpeg How do I decode this a...
How to display image data returned from dreambooth / stable-diffusion model?
I'm querying a dreambooth model from Hugging Face using the inference API and am getting a huge data response string back which starts with: ����çx00çx10JFIFçx00çx01çx01çx00çx00çx01çx0... Content-type is: image/jpeg How do I decode this and display it as an image in javascript?
[ "Not 100% sure but I suppose something similar to that should do it.\nfor (var e = atob(\"����çx00çx10JFIFçx00çx01çx01çx00çx00çx01çx0...\"), t = new Array(e.length), r = 0; r < e.length; r++) t[r] = e.charCodeAt(r);\nvar n = new Uint8Array(t),\n a = new Blob([n], {\n type: \"image/jpeg\"\n }),\n x =...
[ 0, 0 ]
[]
[]
[ "huggingface", "huggingface_transformers", "javascript", "python", "stable_diffusion" ]
stackoverflow_0074484424_huggingface_huggingface_transformers_javascript_python_stable_diffusion.txt
Q: Run Python script on CPANEL I am absolutely not able to figure this out myself, please give me a hint before I go crazy :) My ultimate goal is to execute a python script daily automatically. I have never done anything like this before and am completely lost. I happen to have a Webhosting from Bluehost and have lea...
Run Python script on CPANEL
I am absolutely not able to figure this out myself, please give me a hint before I go crazy :) My ultimate goal is to execute a python script daily automatically. I have never done anything like this before and am completely lost. I happen to have a Webhosting from Bluehost and have learned that I might use this. Then ...
[ "\nbtw the cgi-bin didn't yet exist?\n\nYou will need to check if your apache has support for python (see bottom line notes). If you don't have it , you might need module for implementing mod_Python to be installed (ask Bluehost). In case you already have had \"/cgi-bin/\" folder, you should have support and in tha...
[ 0, 0, 0 ]
[]
[]
[ "cpanel", "cron", "python", "web_hosting" ]
stackoverflow_0064670002_cpanel_cron_python_web_hosting.txt
Q: Python change calculator I need to create a program that will input a money amount in the form of a floating point number. The program will then calculate which dollars and coins to make this amount. Coins will be preferred in the least number of coins. If any of the values is zero, I need to not output the value....
Python change calculator
I need to create a program that will input a money amount in the form of a floating point number. The program will then calculate which dollars and coins to make this amount. Coins will be preferred in the least number of coins. If any of the values is zero, I need to not output the value. IE: if the change is 26 cents...
[ "I ended up solving it\n if doll >= 1:\n lst.append(doll)\n mon.append(\"dollars\")\n \n if quart >= 1:\n lst.append(quart)\n mon.append(\"quarters\")\n if dimes >= 1:\n lst.append(dimes)\n mon.append(\"dimes\")\n if nick >= 1:\n lst.append(\"nickles\...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074492883_python.txt
Q: TypeError: 'module' object is not callable - while using UMAP import umap as UMAP import umap retarget = {df_train['target'].value_counts().reset_index()['index'][i]: i for i in range(len(df_train['target'].value_counts()))} retarget2 = {i: k for k, i in retarget.items()} df_train['target'] = df_train['target']....
TypeError: 'module' object is not callable - while using UMAP
import umap as UMAP import umap retarget = {df_train['target'].value_counts().reset_index()['index'][i]: i for i in range(len(df_train['target'].value_counts()))} retarget2 = {i: k for k, i in retarget.items()} df_train['target'] = df_train['target'].map(retarget) umap = umap(n_components = 2, n_neighbors = 10, min...
[ "You need to install umap-learn\npip uninstall umap\npip install umap-learn\n\nand then\nimport umap\numap = umap.UMAP(n_components = 2, n_neighbors = 10, min_dist = 0.99).fit_transform(df_train.drop('target', axis = 1).sample(15000, random_state = 228), df_train['target'].sample(15000, random_state = 228))\n\n" ]
[ 2 ]
[]
[]
[ "data_science", "python", "runumap" ]
stackoverflow_0074493144_data_science_python_runumap.txt
Q: Django add fields to createsuperuser command I have several database tables that I use in Django. Now I want to design everything around the database not in the Django ORM but in the rational style of my MySQL database. This includes multiple tables for different information. I have made a drawing of what I mean. ...
Django add fields to createsuperuser command
I have several database tables that I use in Django. Now I want to design everything around the database not in the Django ORM but in the rational style of my MySQL database. This includes multiple tables for different information. I have made a drawing of what I mean. I want the createsuperuser command to query once f...
[ "https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/#module-django.core.management\nYou can create django custom commands which will looks like:\npython manage.py createsuperuser2 (or similar name)\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n username = input(\...
[ 1, 0 ]
[]
[]
[ "database", "django", "django_orm", "python" ]
stackoverflow_0066801663_database_django_django_orm_python.txt
Q: How to create multi-part paths with FastAPI I'm working on a FastAPI application, and I want to create multi-part paths. What I mean by this is I know how to create a path like this for all the REST methods: /api/people/{person_id} but what's a good way to create this: /api/people/{person_id}/accounts/{account_id...
How to create multi-part paths with FastAPI
I'm working on a FastAPI application, and I want to create multi-part paths. What I mean by this is I know how to create a path like this for all the REST methods: /api/people/{person_id} but what's a good way to create this: /api/people/{person_id}/accounts/{account_id} I could just keep adding routes in the "people...
[ "In addition to what I have mentioned in the comments, would something like this be of use?\nfrom fastapi import FastAPI, APIRouter\n\napp = FastAPI()\n\npeople_router = APIRouter(prefix='/people')\naccount_router = APIRouter(prefix='/{person_id}/accounts')\n\n\n@people_router.get('/{person_id}')\ndef get_person_id...
[ 1 ]
[]
[]
[ "fastapi", "path", "python", "url" ]
stackoverflow_0074463116_fastapi_path_python_url.txt
Q: Calculate Distance Metric between Homomorphic Encrypted Vectors Is there a way to calculate a distance metric (euclidean or cosine similarity or manhattan) between two homomorphically encrypted vectors? Specifically, I'm looking to generate embeddings of documents (using a transformer), homomorphically encrypting ...
Calculate Distance Metric between Homomorphic Encrypted Vectors
Is there a way to calculate a distance metric (euclidean or cosine similarity or manhattan) between two homomorphically encrypted vectors? Specifically, I'm looking to generate embeddings of documents (using a transformer), homomorphically encrypting those embeddings, and wanting to calculate a distance metric between ...
[ "[Credit goes to ibarrond - answer found here: https://github.com/ibarrond/Pyfhel/issues/155]\nThere is indeed! You just need to rely on a few tricks to overcome the limitations of supported operations in CKKS/BFV schemes (mainly additions and multiplications):\nCosine Similarity: Formulated as CS(x, y) = (sum(xᵢ *...
[ 0 ]
[]
[]
[ "cosine_similarity", "embedding", "euclidean_distance", "homomorphic_encryption", "python" ]
stackoverflow_0074397028_cosine_similarity_embedding_euclidean_distance_homomorphic_encryption_python.txt
Q: How to scrape text between tags with BeautifulSoup? I'm trying to extract text string from a <p> tag, the text string I'm interested in is separated by a <br> tag. <div id="foo"> <p> " Data 1 : Lorem" <br> <br> " Data 2 : Ipsum" <br> </p> <div> Desired output : Lorem Using bs4, I'm stuck at : collec...
How to scrape text between tags with BeautifulSoup?
I'm trying to extract text string from a <p> tag, the text string I'm interested in is separated by a <br> tag. <div id="foo"> <p> " Data 1 : Lorem" <br> <br> " Data 2 : Ipsum" <br> </p> <div> Desired output : Lorem Using bs4, I'm stuck at : collection1 = soup.select('div#foo > p:-soup-contains("Data 1 : ...
[ "Here is one way of getting that data:\nfrom bs4 import BeautifulSoup as bs\n\nhtml = '''\n<div id=\"foo\">\n <p>\n \" Data 1 : Lorem\"\n <br>\n <br>\n \" Data 2 : Ipsum\"\n <br>\n </p>\n<div>\n'''\n\nsoup = bs(html, 'html.parser')\ndesired_data = soup.select_one('div[id=\"foo\"] p').contents[0].split(':')[1]....
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x", "web_scraping" ]
stackoverflow_0074492447_beautifulsoup_python_python_3.x_web_scraping.txt
Q: Python where clause in for index, row in df1.iterrows(): How can I do a where clause for C3? I want to do in the scenario below: df1 = pd.read_excel(path) for index, row in df1.iterrows(): C1 = row[2] C2 = row[7] C3 = if (row[12]) == 0 then 'blue' else 'green' List.append([C1, C2, C_3]) C3 = if (r...
Python where clause in for index, row in df1.iterrows():
How can I do a where clause for C3? I want to do in the scenario below: df1 = pd.read_excel(path) for index, row in df1.iterrows(): C1 = row[2] C2 = row[7] C3 = if (row[12]) == 0 then 'blue' else 'green' List.append([C1, C2, C_3]) C3 = if (row[12]) == 0 then 'blue' else 'green' it is not working. I nee...
[ "Try to avoid loops with pandas.\nex.\ndf1 = pd.read_excel(path)\nC1 = df1.iloc[:, 2] # [rows, columns]\nC2 = df1.iloc[:, 7] \nC3 = numpy.where(df1.iloc[:, 12]==0, 'blue', 'green')\nList = pd.concat([C1, C2, C3], axis=1)\n\n" ]
[ 0 ]
[]
[]
[ "python", "where_clause" ]
stackoverflow_0074493169_python_where_clause.txt
Q: What exactly is Stop in this question and how do I get the sum? Problem Statement Edit: I have transcribed the image as suggested although I think some terms are better shown in the picture if anything is unclear here; This function takes in a positive integer n and returns the sum of the following series Sn, as ...
What exactly is Stop in this question and how do I get the sum?
Problem Statement Edit: I have transcribed the image as suggested although I think some terms are better shown in the picture if anything is unclear here; This function takes in a positive integer n and returns the sum of the following series Sn, as long as the absolute value of each term is larger than stop. Sn= 1 −...
[ "The key is \"alternating\". You can just increment the current denominator one at a time. If it is odd, you add. Otherwise, you subtract. abs is not really required; I'm not sure why they would mention it.\ndef alternating_while(stop):\n total = 0\n denom = 1\n while 1/denom > stop:\n if denom ...
[ 0, 0, 0, 0 ]
[]
[]
[ "math", "python", "while_loop" ]
stackoverflow_0074485791_math_python_while_loop.txt
Q: How would I go about removing duplicate draws from this card drawing program? #Imports random method import random #Gets the value of the card def getCard(): global cards,cardSelect #List of possible cards in an array cards = ["Ace",2,3,4,5,6,7,8,9,10,"Jack","Queen","King"] #Selects a card car...
How would I go about removing duplicate draws from this card drawing program?
#Imports random method import random #Gets the value of the card def getCard(): global cards,cardSelect #List of possible cards in an array cards = ["Ace",2,3,4,5,6,7,8,9,10,"Jack","Queen","King"] #Selects a card cardSelect = random.choice(cards) #Gets the suit of the card def getSuit(): glob...
[ "Consider building your deck first (non-randomly) and then shuffling the deck.\nimport random\ncards = [\"Ace\",2,3,4,5,6,7,8,9,10,\"Jack\",\"Queen\",\"King\"]\nsuits = [\"Hearts\",\"Spades\",\"Clubs\",\"Diamonds\"]\n\ndeck=[]\nfor card in cards:\n for suit in suits:\n deck.append( ( card, suit ))\n\nrandom.shu...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074493163_python.txt
Q: Stratified Sampling in Pandas I've looked at the Sklearn stratified sampling docs as well as the pandas docs and also Stratified samples from Pandas and sklearn stratified sampling based on a column but they do not address this issue. Im looking for a fast pandas/sklearn/numpy way to generate stratified samples of...
Stratified Sampling in Pandas
I've looked at the Sklearn stratified sampling docs as well as the pandas docs and also Stratified samples from Pandas and sklearn stratified sampling based on a column but they do not address this issue. Im looking for a fast pandas/sklearn/numpy way to generate stratified samples of size n from a dataset. However, fo...
[ "Use min when passing the number to sample. Consider the dataframe df\ndf = pd.DataFrame(dict(\n A=[1, 1, 1, 2, 2, 2, 2, 3, 4, 4],\n B=range(10)\n ))\n\ndf.groupby('A', group_keys=False).apply(lambda x: x.sample(min(len(x), 2)))\n\n A B\n1 1 1\n2 1 2\n3 2 3\n6 2 6\n7 3 7\n9 4 9\n8 ...
[ 103, 16, 10, 2, 0 ]
[]
[]
[ "numpy", "pandas", "python", "scikit_learn" ]
stackoverflow_0044114463_numpy_pandas_python_scikit_learn.txt
Q: Swagger / OpenAPI spec featuring file upload rejected by Google Endpoints My goal is to set up a simple API for uploading a file via Google Endpoints. This is my simplified OpenAPI specification which is valid according to Swagger validation: swagger: "2.0" info: title: "JSON Ingester" description: "Receive JS...
Swagger / OpenAPI spec featuring file upload rejected by Google Endpoints
My goal is to set up a simple API for uploading a file via Google Endpoints. This is my simplified OpenAPI specification which is valid according to Swagger validation: swagger: "2.0" info: title: "JSON Ingester" description: "Receive JSON files, transform and load them." version: "1.0.0" host: "project-id.appsp...
[ "Looks like it requires at least some authentication: https://cloud.google.com/endpoints/docs/openapi/authentication-method\nI also think that Cloud Endpoints don't support type: file, so you have to use type: string and use equivalent to curl -X POST -F \"file_upload=@file.txt\" http://myservice.com/endpoint to up...
[ 1, 0, 0 ]
[]
[]
[ "google_cloud_platform", "openapi", "python", "swagger_2.0" ]
stackoverflow_0056854100_google_cloud_platform_openapi_python_swagger_2.0.txt
Q: Choose Specific Date Range on X-axis I have a dataframe that shows my total_Sales, Total_cost & Total_profit over a period of time. My graph only plots the dates on which changes occur in my dataframe. I'm wondering if I can change that to show monthly data from the first transaction to today. Date Ticker ...
Choose Specific Date Range on X-axis
I have a dataframe that shows my total_Sales, Total_cost & Total_profit over a period of time. My graph only plots the dates on which changes occur in my dataframe. I'm wondering if I can change that to show monthly data from the first transaction to today. Date Ticker Total_Sales Total_Cost Profit 01/11/2...
[ "I think I was able to fix it by adding the following lines of code:\n\nplt2['Date'] = pd.to_datetime(plt2['Date'])\n\nWhich resulted in the dataframe handling the date column as an actual date.\nThen for the graph I added this code:\nmonths = mdates.MonthLocator() \nfig = plt.figure(figsize=(16,4))\nax = fig.add_s...
[ 0 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "python" ]
stackoverflow_0074493082_dataframe_matplotlib_pandas_python.txt
Q: Python Password Checker Incorrect Output I am trying to Implement the function _isValid() in password_checker.py that returns True if the given password string meets the following requirements, and False otherwise: Is at least eight characters long Contains at least one digit (0-9) Contains at least one uppercase...
Python Password Checker Incorrect Output
I am trying to Implement the function _isValid() in password_checker.py that returns True if the given password string meets the following requirements, and False otherwise: Is at least eight characters long Contains at least one digit (0-9) Contains at least one uppercase letter Contains at least one lowercase letter...
[ "You have the answer in your own comment:\nelif c.isalnum():\n # If c is not alphanumeric, set corresponding flag to True.\n\nTherefore this should be:\nelif not c.isalnum():\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074493316_python.txt
Q: Cannot get collection of event from showclix using their api I am trying to get collection of all events from the showclix api. They have listed the api endpoint here: https://technically.showclix.com/events.html#events-events-get here is my code: def func2(self): Headers = { 'X-API-Token ': '<...
Cannot get collection of event from showclix using their api
I am trying to get collection of all events from the showclix api. They have listed the api endpoint here: https://technically.showclix.com/events.html#events-events-get here is my code: def func2(self): Headers = { 'X-API-Token ': '<1234989898>', 'Accept': 'application/vnd.api+json', ...
[ "Their API documentation is pretty bad, the actual API endpoint is:\nhttps://showclix.com/api/events\n" ]
[ 0 ]
[]
[]
[ "api", "python", "rest" ]
stackoverflow_0072727818_api_python_rest.txt
Q: ordering by multiply columns pandas - 'values' is not ordered, please explicitly specify the categories order by passing in a categories argument I have the dataframe 'rankedvariableslist', with the index 'Sleepvariables' being the sleep variable of interest, and the two columns being the R-squared and P-value of ...
ordering by multiply columns pandas - 'values' is not ordered, please explicitly specify the categories order by passing in a categories argument
I have the dataframe 'rankedvariableslist', with the index 'Sleepvariables' being the sleep variable of interest, and the two columns being the R-squared and P-value of that model and variable respectively. I am trying to sort the data in ascending order by 'P-value', then by 'R-squared value', but I keep getting the e...
[ "Your code works when I run it, it returns the below result.\n Sleepvariables R-squared value P-value\n0 hours_of_sleep 0.026 0.413\n1 frequency_of_alarm_usage 0.026 0.491\n2 sleepiness_bed 0.026 ...
[ 0, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074489047_dataframe_jupyter_notebook_pandas_python.txt
Q: os.path.exists works with an integer Today, I was writing a code that checks if a file exists before doing anything with it. To do so, I use os.path.exists( filename ) By mistake, I gave to filename an integer value instead of a string value. E.g. os.path.exists( 15 ) To my great surprise, it did not raised a Ty...
os.path.exists works with an integer
Today, I was writing a code that checks if a file exists before doing anything with it. To do so, I use os.path.exists( filename ) By mistake, I gave to filename an integer value instead of a string value. E.g. os.path.exists( 15 ) To my great surprise, it did not raised a TypeError but returned True (it actually ret...
[ "From the documentation\n\nChanged in version 3.3: path can now be an integer: True is returned if it is an open file descriptor, False otherwise.\n\nWhen I try it, it only returns True for a couple of low numbers:\n>>> [os.path.exists(n) for n in range(50)]\n[True, True, True, False, False, False, False, False, Fa...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074493341_python.txt
Q: Code for correct indexation in tuple. Python I'm very new to python and currently I'm trying to write code to find average height in tuple/list. But everytime I get stuck at the same place. The thing is I need to divide people by sex. Ж- for female Ч- for male. Don't pay attention to another language , adding code...
Code for correct indexation in tuple. Python
I'm very new to python and currently I'm trying to write code to find average height in tuple/list. But everytime I get stuck at the same place. The thing is I need to divide people by sex. Ж- for female Ч- for male. Don't pay attention to another language , adding code in case it's necessary and mistake I get all the ...
[ "In your tuple, K the index of 'Ж' is 0 and the index of 'Ч' is 1. That means in your for loop indexPerson is always 0. I'm not sure why you need a list to hold max M height, or person name.\nMaybe try this:\nK = (\"Ж\", \"Ч\")\nG = [\n \"Іванов І.І. Ч 1951 172\",\n \"Петрова П.І. Ж 1975 165\",\n \"Сидоров...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074491183_python_python_3.x.txt
Q: float() argument must be a string or a number, not 'Cell' - cannot solve issue I have the following code below. I am trying to store the R-squared values and P-values from an OLS regression output in a dataframe 'rankedvariableslist' and then sort this dataframe, first by the P-values, then by the R-squared values...
float() argument must be a string or a number, not 'Cell' - cannot solve issue
I have the following code below. I am trying to store the R-squared values and P-values from an OLS regression output in a dataframe 'rankedvariableslist' and then sort this dataframe, first by the P-values, then by the R-squared values. However, I am getting the error: 'float() argument must be a string or a number, n...
[ "The following code worked - instead of converting the model summary output to a dataframe, I converted the model summary output to a html file).\ncorrespondantsleepvariable = []\ncorrespondantpvalue = []\ncorrespondantpvalue = [] \n\nresults_as_html = resultmodeldistancevariation2sleepsummary.tables[0].as_html()\n...
[ 0 ]
[]
[]
[ "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074491328_jupyter_notebook_pandas_python.txt
Q: How to compare all rows from a Data frame with each other and alter values, in a timely manner? I have a pandas Dataframe of tennis games with 70,000 games (rows) with two issues: Every game is duplicated, because for every game between player A and B, there's a row when A plays with B and a row when B plays with...
How to compare all rows from a Data frame with each other and alter values, in a timely manner?
I have a pandas Dataframe of tennis games with 70,000 games (rows) with two issues: Every game is duplicated, because for every game between player A and B, there's a row when A plays with B and a row when B plays with A. This happens because I extracted all games played for each player, so I have all games that Nadal...
[ "Try with merge:\ndf = pd.merge(left=df, right=df, on=['Tourn.','Round','Year'])\n\nThen remove duplicates:\ndf.drop_duplicates(subset=['Tourn.','Round','Year'], inplace=True)\n\nAfter you just need to rename the column names\nYou can then leave only rows with the same playerA & playerB:\ndf = df[df['Player A_x'] =...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074493224_dataframe_pandas_python.txt
Q: Troubles installing mysqlclient with pip3 I'm trying to set up a python 3.6 environment with Django. The installation instructions say I should install mysqlclient to be able to connect to mySQL. I get this: dennis@django:~$ sudo -H pip3 install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.10....
Troubles installing mysqlclient with pip3
I'm trying to set up a python 3.6 environment with Django. The installation instructions say I should install mysqlclient to be able to connect to mySQL. I get this: dennis@django:~$ sudo -H pip3 install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python ...
[ "If you're using Mac OS, try this:\nbrew install mysql\nIf you're using Ubuntu14/16, try this:\nsudo apt install libmysqlclient-dev\nand one more:\npip3 can be updated with sudo pip3 install -U pip\n", "LDFLAGS=-L/usr/local/opt/openssl/lib pip install mysqlclient\n\n", "In my case the issue was solved by doing ...
[ 32, 10, 6, 3, 3, 0, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0042640924_django_mysql_python.txt
Q: Slicing a string based on user input printing the characters on each line So basically, i need to get the user to input some type of string and then get the user to input a number and slice the string depending on the users number and print on a new line every time it sliced. I don't think that made since so here ...
Slicing a string based on user input printing the characters on each line
So basically, i need to get the user to input some type of string and then get the user to input a number and slice the string depending on the users number and print on a new line every time it sliced. I don't think that made since so here is an example Welcome to the jungle. 5 Welco me to the jungl e. I understand h...
[ "You can use the input string as the loop control variable. That is, keep looping while there is still something left in the input string. Here's a suggestion:\ny=input('enter a sentence ')\nx=int(input('enter a number '))\nwhile len(y):\n print(y[0:x])\n y=y[x:]\n\nAnd here's an example run:\nenter a sentence We...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074493057_python_python_3.x.txt
Q: cleanest way to concatenate a single string to many other element contained in a list What I have: string = "string" range_list = list(range(10)) What I want: ['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9'] What I usually do: import pandas a...
cleanest way to concatenate a single string to many other element contained in a list
What I have: string = "string" range_list = list(range(10)) What I want: ['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9'] What I usually do: import pandas as pd (string+pd.Series(range_list).astype(str)).tolist() What I would like to do: obtain t...
[ "You can do this using list comprehension and f-string.\n[f\"{string}{idx}\" for idx in range_list]\n\n", "You can use map with a function or a lambda to avoid using a loop.\ndef get_string(x):\n return f'string{x}'\n\nlist(map(get_string, range(10)))\n\nor with a lambda:\nlist(map(lambda x: f'string{x}', rang...
[ 1, 1, 1, 0 ]
[]
[]
[ "list", "python", "string", "string_concatenation" ]
stackoverflow_0074491184_list_python_string_string_concatenation.txt
Q: Print string of information from dataset using index I am trying to code so that it will take the index of a dish, that was inputed by a user, in a dataset then print everything from that row that contains information about the dish. I am stumbling when it comes to getting the index to select the information from ...
Print string of information from dataset using index
I am trying to code so that it will take the index of a dish, that was inputed by a user, in a dataset then print everything from that row that contains information about the dish. I am stumbling when it comes to getting the index to select the information from the data set This is the code I have so far import csv my...
[ "I strongly suggest using pandas for this. It is tailored to work with tables (dataframes) of data like this. I had to replicate your dataset for a few examples because it was in picture form, so you should not have to use some of the code I have. If you can get your data into a dataframe, which there is plenty of ...
[ 0 ]
[]
[]
[ "csv", "dataframe", "indexing", "python" ]
stackoverflow_0074484866_csv_dataframe_indexing_python.txt
Q: How can I bind a key-event to a Python tkinter canvas item? I want to bind a key event to a Python tkinter canvas item, for example to a rectangle. I am able to bind a key to the canvas itself (see example code, key "a", "b", "c"), but not to a canvas-item as a rectangle (see example code, key "r", "s", "t"). What...
How can I bind a key-event to a Python tkinter canvas item?
I want to bind a key event to a Python tkinter canvas item, for example to a rectangle. I am able to bind a key to the canvas itself (see example code, key "a", "b", "c"), but not to a canvas-item as a rectangle (see example code, key "r", "s", "t"). What am I doing wrong? I tried it in this way, but I get only a react...
[ "It's not possible to bind keyboard events to canvas objects, except for text items. From the canonical documentation for the focus method of the canvas:\n\"Set the keyboard focus for the canvas widget to the item given by tagOrId. If tagOrId refers to several items, then the focus is set to the first such item in ...
[ 1 ]
[]
[]
[ "key_bindings", "python", "tkinter", "tkinter_canvas" ]
stackoverflow_0074493213_key_bindings_python_tkinter_tkinter_canvas.txt
Q: How to write multiple lists into a dataframe using loop I have several lists that are generated from a get_topic() function. That is, list1 = get_topic(1) list2 = get_topic(2) and another dozens of lists. # The list contains something like [('A', 0.1),('B', 0.2),('C',0.3)] I am trying to write a loop so that al...
How to write multiple lists into a dataframe using loop
I have several lists that are generated from a get_topic() function. That is, list1 = get_topic(1) list2 = get_topic(2) and another dozens of lists. # The list contains something like [('A', 0.1),('B', 0.2),('C',0.3)] I am trying to write a loop so that all different lists can be saved to different columns in a data...
[ "df = pd.DataFrame()\nfor i in range(1, number):\n df[f'List {i}'], df[f'Number {i}'] = zip(*get_topic(i))\n\n", "I reconstruct a hypothetical get_topic() function that simply fetches a list from a list of lists.\nThe idea is to use pd.concat() in order to concatenate dataframes at each iteration.\nimport pand...
[ 2, 0, 0 ]
[]
[]
[ "for_loop", "loops", "pandas", "python" ]
stackoverflow_0074492934_for_loop_loops_pandas_python.txt
Q: How to sum second array in python I want to sum a 2d list. Example: x==[[1, 2],[3, 4],[5, 6]] a solution should lool like: sum_2d = [3, 7, 11] I tried this: y = sum(sum(x,[])) but that sums all the numbers. Thanks for any advice. A: x=[[1, 2],[3, 4],[5, 6]] [sum(y) for y in x] #output [3, 7, 11] using list co...
How to sum second array in python
I want to sum a 2d list. Example: x==[[1, 2],[3, 4],[5, 6]] a solution should lool like: sum_2d = [3, 7, 11] I tried this: y = sum(sum(x,[])) but that sums all the numbers. Thanks for any advice.
[ "x=[[1, 2],[3, 4],[5, 6]]\n\n[sum(y) for y in x]\n\n#output\n[3, 7, 11]\n\nusing list comprehension\n", "You can use a for loop to iterate over x, and use sum() at each row of x:\nx = [[1, 2], [3, 4], [5, 6]]\n\nsum_2d = []\n\nfor i in x:\n sum_2d += [sum(i)]\n \nprint(sum_2d)\n\n" ]
[ 1, 0 ]
[]
[]
[ "2d", "arrays", "list", "python", "sum" ]
stackoverflow_0074493441_2d_arrays_list_python_sum.txt
Q: Problem with missing and unexpected keys while loading my model in Pytorch I'm trying to load the model using this tutorial: https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-for-inference . Unfortunately I'm very beginner and I face some problems. I have created checkpoint: c...
Problem with missing and unexpected keys while loading my model in Pytorch
I'm trying to load the model using this tutorial: https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-for-inference . Unfortunately I'm very beginner and I face some problems. I have created checkpoint: checkpoint = {'epoch': epochs, 'model_state_dict': model.state_dict(), 'optimizer...
[ "So your Network is essentially the classifier part of AlexNet and you're looking to load pretrained AlexNet weights into it. The problem is that the keys in state_dict are \"fully qualified\", which means that if you look at your network as a tree of nested modules, a key is just a list of modules in each branch, ...
[ 6, 0 ]
[]
[]
[ "conv_neural_network", "machine_learning", "neural_network", "python", "pytorch" ]
stackoverflow_0053907073_conv_neural_network_machine_learning_neural_network_python_pytorch.txt
Q: other way than using if-condition im sitting on a code were I want to analyse data from a Racetrack. Right now im trying to figure out how to getting the winner. I have 4 cars and have an Lapcounter from each car and there best and last time. My first idea is this one: winnerlist.extend((Lapcounter1,Lapcounter2,La...
other way than using if-condition
im sitting on a code were I want to analyse data from a Racetrack. Right now im trying to figure out how to getting the winner. I have 4 cars and have an Lapcounter from each car and there best and last time. My first idea is this one: winnerlist.extend((Lapcounter1,Lapcounter2,Lapcounter3,Lapcounter4)) winnerlist.sort...
[ "rank= (\"first\", \"second\", \"third\", \"fourth\")\nfor k in range(len(winnerlist)):\n print(\"Car\", k+1, \"is\", rank[sum(Lap < winnerlist[k] for Lap in winnerlist)])\n\n" ]
[ 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074492959_if_statement_python.txt
Q: I need to make a scatter plot of Mass Spectrometry data on Python The graph should look like this: This is the plot I want: But I got this graph instead, with the following error message: My current Plot I'm getting this Pycharm message in red after running my program: MatplotlibDeprecationWarning: The resize_eve...
I need to make a scatter plot of Mass Spectrometry data on Python
The graph should look like this: This is the plot I want: But I got this graph instead, with the following error message: My current Plot I'm getting this Pycharm message in red after running my program: MatplotlibDeprecationWarning: The resize_event function was deprecated in Matplotlib 3.6 and will be removed two mi...
[ "If you want to plot the figure on first image you don't need scatter plot, it's a traditional continuous line plot. Just keep the default setting for plotting the figure without specifying attributes\nmarker ='o', c ='black', yticks(), it will give you same result as the first image:\nplt.title(\"Spectra\")\nplt.x...
[ 0 ]
[]
[]
[ "python", "scatter_plot" ]
stackoverflow_0074493344_python_scatter_plot.txt
Q: How do I split a grouped bar chart into sub-groups? I have this dataset- group sub_group value date 0 Animal Cats 12 today 1 Animal Dogs 32 today 2 Animal Goats 38 today 3 ...
How do I split a grouped bar chart into sub-groups?
I have this dataset- group sub_group value date 0 Animal Cats 12 today 1 Animal Dogs 32 today 2 Animal Goats 38 today 3 Animal Fish 1 today ...
[ "I think your code will draw the intended graph except for the color settings, but if you want to separate each stacked graph by color, you will need to do some tricks. There may be another way to do this, but create two express graphs by date and reuse that data. To create that x-axis, add a column with the code t...
[ 2, 1 ]
[ "I didn't see your expected Output so I followed my prediction. Try to see if you got it right:\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nfig = make_subplots(rows = 1, cols = 2)\n\nfig.add_trace(go.Bar(x=[tuple(df[df['date'] == 'today']['group']),\n tuple(...
[ -1, -1 ]
[ "dashboard", "plotly", "plotly_dash", "plotly_python", "python" ]
stackoverflow_0074330739_dashboard_plotly_plotly_dash_plotly_python_python.txt
Q: How can I access "static" class variables within methods? If I have the following code: class Foo(object): bar = 1 def bah(self): print(bar) f = Foo() f.bah() It complains NameError: global name 'bar' is not defined How can I access class/static variable bar within method bah? A: Ins...
How can I access "static" class variables within methods?
If I have the following code: class Foo(object): bar = 1 def bah(self): print(bar) f = Foo() f.bah() It complains NameError: global name 'bar' is not defined How can I access class/static variable bar within method bah?
[ "Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.\n", "Define class method:\nclass Foo(object):\n bar = 1\n @classmethod\n def bah(cls): \n print cls.bar\n\nNow if bah() has to be instance met...
[ 229, 112, 21, 14, 2, 0 ]
[]
[]
[ "oop", "python", "static_variables" ]
stackoverflow_0000707380_oop_python_static_variables.txt
Q: configparser.NoSectionError: No section: 'general_info' I have created an exe file from .py file and within that code, i retrieve a value from config.ini file. When i convert the .py to .exe file and double click on it, it works fine. But when create a task scheduler to run that exe file on windows start up, i rec...
configparser.NoSectionError: No section: 'general_info'
I have created an exe file from .py file and within that code, i retrieve a value from config.ini file. When i convert the .py to .exe file and double click on it, it works fine. But when create a task scheduler to run that exe file on windows start up, i receive an error: configparser.NoSectionError: No section: 'gene...
[ "issue solved by placing the config.ini file in C:/Windows , as the task scheduler somehow is reading from relative path which in C:/Windows\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0073819154_python.txt
Q: Top 10 largest values in one column and smallest in another column, Dataframe python I want to do a new dataframe with Top 10 teams with largest goal average and smalest matches played, i need to filter all the dataframe new_df = mundialestotales_df.nlargest(10, ['Prom. de Gol']) Here i get the largest but i can'...
Top 10 largest values in one column and smallest in another column, Dataframe python
I want to do a new dataframe with Top 10 teams with largest goal average and smalest matches played, i need to filter all the dataframe new_df = mundialestotales_df.nlargest(10, ['Prom. de Gol']) Here i get the largest but i can't join with the smalest matches played Y try to do a 2 news dataframes and join them, but ...
[ "See dummy data below, you can tweak to your dataset since none was provided. We can create our large / small dataframes and then concat them back together.\nimport pandas as pd\n\ndata = {\n 'State':['MO','IA','KS','NE','AL','KY','OH','IL'],\n 'Pop':[1000,5000,8950,10000,12500,800,15000,30000],\n}\ndf = pd.D...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074493531_dataframe_pandas_python.txt
Q: Python OOP class method Book Book.No_Pages() missing 2 required positional arguments: 'Words' and 'Font_size' the error comes in line 14 The code is:- class Book(): def __init__ (b1,Font_size=12,Words=300): b1.Words = Words pass b1.Font_size = Font_size pass def No_Pages(b...
Python OOP class method Book
Book.No_Pages() missing 2 required positional arguments: 'Words' and 'Font_size' the error comes in line 14 The code is:- class Book(): def __init__ (b1,Font_size=12,Words=300): b1.Words = Words pass b1.Font_size = Font_size pass def No_Pages(b1,Words,Font_size): return...
[ "So No_pages isn't using those parameters (Words and Font_size) - it's getting them from the b1 parameter (which would conventionally be called self, btw.) Essentially you're handing it an entire container, b1, and it's getting everything it needs from there - but you've also told it it should be explicitly handed ...
[ 0, 0, 0 ]
[]
[]
[ "class", "methods", "object", "python" ]
stackoverflow_0074493515_class_methods_object_python.txt
Q: Python3.8 asyncio: RuntimeWarning: coroutine was never awaited I am new with async functions and i'm trying to make multiple calls from an external API. concurrent.Futures is not quite enough to retrieve the responses so i tried with asyncio and httpx but the process is throwing an error unknown and difficult to d...
Python3.8 asyncio: RuntimeWarning: coroutine was never awaited
I am new with async functions and i'm trying to make multiple calls from an external API. concurrent.Futures is not quite enough to retrieve the responses so i tried with asyncio and httpx but the process is throwing an error unknown and difficult to debug for me. It seems that the coroutine is having an empty value or...
[ "When you want to run asynchronous functions from synchronous functions, you have to use the asyncio library to run them. Your last function should look like this.\ndef products_processor_concurrent(data_parser):\n from asyncio import run\n return run(async_get_products(data_parser))\n\n" ]
[ 0 ]
[]
[]
[ "api", "httpx", "pandas", "python", "python_asyncio" ]
stackoverflow_0074493625_api_httpx_pandas_python_python_asyncio.txt
Q: How to take difference of 2 time rows? import pandas as pd df=pd.read_excel('/content/Haoling peak time data (1).xlsx') df['Difference'] = df['ORDER END TIME']-df['ORDER START TIME'] error: TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' A: Times have to be converted to date ...
How to take difference of 2 time rows?
import pandas as pd df=pd.read_excel('/content/Haoling peak time data (1).xlsx') df['Difference'] = df['ORDER END TIME']-df['ORDER START TIME'] error: TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
[ "Times have to be converted to date times in order to work. You can do it with something like this.\nfrom datetime import datetime, timedelta, date\n\ndef daytime(time):\n return datetime.combine(date.min, time)\n\ndf['Difference'] = df['ORDER END TIME'].apply(daytime) - df['ORDER START TIME'].apply(daytime)\n\n...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074482205_dataframe_pandas_python_python_3.x.txt
Q: I am trying to take and input from an html form and have it update in the flask database, whats the simplest way to do it? I am trying to take and input from an html form and have it update in the flask database. The age is specific to the user id. Here is my html <div> <form method="POST"> ...
I am trying to take and input from an html form and have it update in the flask database, whats the simplest way to do it?
I am trying to take and input from an html form and have it update in the flask database. The age is specific to the user id. Here is my html <div> <form method="POST"> <div class="form-group"> <label for="">New age</label> <input ...
[ "try form need action to your route\n<form action='/profile' method=\"POST\">\n\n" ]
[ 0 ]
[]
[]
[ "flask", "flask_sqlalchemy", "html", "python", "sqlalchemy" ]
stackoverflow_0074492917_flask_flask_sqlalchemy_html_python_sqlalchemy.txt
Q: Systemd: Start operation timed out. Terminating I'm trying to create an autostart service for my python-flask-socketio server. I need to start a python script through systemd. Here's my service code: [Unit] Description=AppName [Service] Type=forking ExecStart=/usr/bin/python3 /opt/myapp/app.py [Install] WantedBy...
Systemd: Start operation timed out. Terminating
I'm trying to create an autostart service for my python-flask-socketio server. I need to start a python script through systemd. Here's my service code: [Unit] Description=AppName [Service] Type=forking ExecStart=/usr/bin/python3 /opt/myapp/app.py [Install] WantedBy=multi-user.target If I try to start it manually us...
[ "Your type seems wrong, forking is for programs that detach immediately by themselves. Flask does not, it stays attached to your console. \nYour service type should probably be simple\n", "Set a larger start timeout:\n[Service]\nTimeoutStartSec=300\n\nIn case your service would actually need more time to complete...
[ 23, 4, 0, 0 ]
[]
[]
[ "flask", "flask_socketio", "python", "systemd", "ubuntu" ]
stackoverflow_0045012415_flask_flask_socketio_python_systemd_ubuntu.txt
Q: I do not succeed in trapping an OperationalError from SQLAlchemy This is my first question here, I hope I do it in the right way. If not, please tell me so I can improve. I have an SqlAlchemy database with my books. I made an python application with a tkinter GUI. In that GUI it is also possible to enter your own ...
I do not succeed in trapping an OperationalError from SQLAlchemy
This is my first question here, I hope I do it in the right way. If not, please tell me so I can improve. I have an SqlAlchemy database with my books. I made an python application with a tkinter GUI. In that GUI it is also possible to enter your own query. The query should then be excecuted and the result is shown with...
[ "from sqlalchemy.exc import OperationalError\n...\nexcept OperationalError:\n\nhttps://www.fullstackpython.com/sqlalchemy-exc-operationalerror-examples.html\n" ]
[ 0 ]
[]
[]
[ "error_handling", "python", "sqlalchemy" ]
stackoverflow_0061236335_error_handling_python_sqlalchemy.txt
Q: Django passing context in JsonResponse I am developing a webpage with filters to filter the results on the page. A Ajax is called, which sends the filters to my Django back-end. The results are filtered and the data should be passed back to the front-end. So now I need to pass my results of the models with context...
Django passing context in JsonResponse
I am developing a webpage with filters to filter the results on the page. A Ajax is called, which sends the filters to my Django back-end. The results are filtered and the data should be passed back to the front-end. So now I need to pass my results of the models with context to the front-end. This leads to some proble...
[ "django template tag work on rendering html content and you can not pass argument after render page so after loading page you can not use\n{% for a in ads %}\n {% a %}\n{% endfor %}\n\nif you have not pass that arguments\nyou can use api and js for this work\ni suggest you read about drf\nyou can do this work w...
[ 0 ]
[]
[]
[ "ajax", "django", "jquery", "python" ]
stackoverflow_0074493663_ajax_django_jquery_python.txt
Q: Unable to delete PowerPoint Slides using Python-pptx I am trying to delete PowerPoint slides containing a specific keywords using Python-pptx. If the keyword is present anywhere in the slide then that slide will be deleted. My code is given below: from pptx import Presentation String = 'Macro' ppt = Presentation...
Unable to delete PowerPoint Slides using Python-pptx
I am trying to delete PowerPoint slides containing a specific keywords using Python-pptx. If the keyword is present anywhere in the slide then that slide will be deleted. My code is given below: from pptx import Presentation String = 'Macro' ppt = Presentation('D:\\Shaon\\pptss\\Regional.pptx') for slide in ppt.slid...
[ "You can delete a slide with a specific index value with the following code using the pptx library:\nfrom pptx import Presentation\n# create slides ------\npresentation = Presentation('new.pptx') \n\nxml_slides = presentation.slides._sldIdLst \nslides = list(xml_slides)\nxml_slides.remove(slides[index]) \n\nSo to...
[ 1, 1, 0 ]
[]
[]
[ "powerpoint", "python", "python_3.x", "python_pptx" ]
stackoverflow_0054945022_powerpoint_python_python_3.x_python_pptx.txt
Q: Pythonnet dotnet core 'No module named' I am trying to use a .NET Core library inside a Jupyter Notebook python script by using PythonNet. Support for .NET Core was added recently (see https://github.com/pythonnet/pythonnet/issues/984#issuecomment-778786164) but I am still getting a No module named 'TestAppCore' e...
Pythonnet dotnet core 'No module named'
I am trying to use a .NET Core library inside a Jupyter Notebook python script by using PythonNet. Support for .NET Core was added recently (see https://github.com/pythonnet/pythonnet/issues/984#issuecomment-778786164) but I am still getting a No module named 'TestAppCore' error. I don't have an issue using a .NET Fram...
[ "I suspect that you are getting the DLL path wrong.\nThis worked for me:\nfrom clr_loader import get_coreclr\nfrom pythonnet import set_runtime\nset_runtime(get_coreclr(\"pythonnetconfig.json\"))\nimport clr\nclr.AddReference(\"C:/Path/To/Interface.dll\")\n\nfrom Interface import Foo\nfoo = Foo()\n\nUsing\nPython 3...
[ 0, 0, 0 ]
[]
[]
[ "c#", "python", "python.net" ]
stackoverflow_0067970591_c#_python_python.net.txt
Q: Func for temporary text in many tkinter Entry widget? I want to put a temporary text in more than 1 entry with tkinter, but my func is not working. I have this situation: def temp_text_entry_delete(e): self.id_entry.delete(0, 'end') self.id_entry = tk.Entry(borderwidth=2, width=10) self.id_entry.insert(0, "ex...
Func for temporary text in many tkinter Entry widget?
I want to put a temporary text in more than 1 entry with tkinter, but my func is not working. I have this situation: def temp_text_entry_delete(e): self.id_entry.delete(0, 'end') self.id_entry = tk.Entry(borderwidth=2, width=10) self.id_entry.insert(0, "ex:001") self.id_entry.pack() self.id_entry.bind("<FocusIn>"...
[ "The event object will have a reference to the widget that received the event. You can use that to insert or delete text:\ndef temp_text_entry_delete(e):\n e.widget.delete(0, 'end')\n\n", "Here's a PlaceholderEntry widget that should to what you want\nimport tkinter as tk\nfrom tkinter import ttk\n\n\nclass Pl...
[ 1, 0 ]
[]
[]
[ "function", "python", "tkinter" ]
stackoverflow_0074493398_function_python_tkinter.txt
Q: AttributeError Issue: module 'selenium.webdriver' has no attribute 'Chrome' I have just started Selenium using Python. And I'm facing the Attribute error issue. Have Installed Python 3.6.5 and installed the latest selenium packages(selenium-3.11.0) Have also added Scripts and Python folder path in the Environment...
AttributeError Issue: module 'selenium.webdriver' has no attribute 'Chrome'
I have just started Selenium using Python. And I'm facing the Attribute error issue. Have Installed Python 3.6.5 and installed the latest selenium packages(selenium-3.11.0) Have also added Scripts and Python folder path in the Environment variable:PATH. Downloaded the chromedriver.exe and have added the respective fil...
[ "from selenium import webdriver\n\ndriver = webdriver.Chrome()\n\nThis is the correct way how to write that code, also if u want to use firefox or something else then change chrome to firefox ... also read 1st a documentation and look for some examples, then put it here if u find nothing\nAlso use pip install selen...
[ 4, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ "I had the same problem and we solved it!! I installed the newest version of python which is 3.9.\nI ran it and it yelled at me for selenium.\nSo I went into command prompt and did :\npip install selenium\n\nIt installed selenium. I ran it, and it worked.\n" ]
[ -1 ]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0050113232_python_selenium_selenium_webdriver.txt
Q: How to save a list in a pandas dataframe cell to a HDF5 table format? I have a dataframe that I want to save in the appendable format to a hdf5 file. The dataframe looks like this: column1 0 [0, 1, 2, 3, 4] And the code that replicates the issue is: import pandas as pd test = pd.DataFrame({"column1":[list(r...
How to save a list in a pandas dataframe cell to a HDF5 table format?
I have a dataframe that I want to save in the appendable format to a hdf5 file. The dataframe looks like this: column1 0 [0, 1, 2, 3, 4] And the code that replicates the issue is: import pandas as pd test = pd.DataFrame({"column1":[list(range(0,5))]}) test.to_hdf('test','testgroup',format="table") Unfortunately...
[ "Python Lists present a challenge when writing to HDF5 because they may contain different types. For example, this is a perfectly valid list: [1, 'two', 3.0]. Also, if I understand your Pandas 'column1' dataframe, it may contain different length lists. There is no (simple) way to represent this as an HDF5 dataset.\...
[ 1 ]
[]
[]
[ "dataframe", "hdf5", "pandas", "pytables", "python" ]
stackoverflow_0074489101_dataframe_hdf5_pandas_pytables_python.txt
Q: Generating a text representation of Python's AST With Clang we can do: clang -cc1 -ast-dump j.c TranslationUnitDecl 0x7fbcfc00f608 <<invalid sloc>> <invalid sloc> |-TypedefDecl 0x7fbcfc00fea0 <<invalid sloc>> <invalid sloc> implicit __int128_t '__int128' | `-BuiltinType 0x7fbcfc00fba0 '__int128' |-TypedefDecl 0x7f...
Generating a text representation of Python's AST
With Clang we can do: clang -cc1 -ast-dump j.c TranslationUnitDecl 0x7fbcfc00f608 <<invalid sloc>> <invalid sloc> |-TypedefDecl 0x7fbcfc00fea0 <<invalid sloc>> <invalid sloc> implicit __int128_t '__int128' | `-BuiltinType 0x7fbcfc00fba0 '__int128' |-TypedefDecl 0x7fbcfc00ff08 <<invalid sloc>> <invalid sloc> implicit __...
[ "Update for Python 3.9+: The ast.dump function in the standard library now has an optional keyword argument indent for pretty-printing of Python ASTs. You pass either an integer for the number of spaces, or a string.\n\nThe astpretty library seems to be suitable for your purpose. This library has a pretty-print fun...
[ 6, 0 ]
[]
[]
[ "abstract_syntax_tree", "python" ]
stackoverflow_0058924031_abstract_syntax_tree_python.txt
Q: How to make a condition when the ssm parameter does not exist I'm creating a python code to insert multiple parameters to the parameter store. The code I have already works as I wish, but I need to make a condition that if the parameter already exists it simply tells me that it already exists and I don't know what...
How to make a condition when the ssm parameter does not exist
I'm creating a python code to insert multiple parameters to the parameter store. The code I have already works as I wish, but I need to make a condition that if the parameter already exists it simply tells me that it already exists and I don't know what to put in the response condition import json import boto3 s3 = bo...
[ "When you put a parameter to an existing one, it overwrites it only if you set the overwrite option to True. But this option is False by default. In your code, you haven't set it to True, so it doesn't overwrite and that's why, it renders the error message.\nIf you do not need to avoid overwriting, set the option t...
[ 0 ]
[]
[]
[ "aws_lambda", "aws_parameter_store", "boto3", "python" ]
stackoverflow_0074493431_aws_lambda_aws_parameter_store_boto3_python.txt
Q: Extract format dates from dataframe column I have a dataframe in python containing various dates. df = pd.DataFrame({"Date":["2020-01-27 welcome ! offer","Space ! offer 2020-02-27","new | 2020-03-27"], "A_item":[2, 8, 0], "B_item":[1, 7, 10], "C_item":[9, 2,...
Extract format dates from dataframe column
I have a dataframe in python containing various dates. df = pd.DataFrame({"Date":["2020-01-27 welcome ! offer","Space ! offer 2020-02-27","new | 2020-03-27"], "A_item":[2, 8, 0], "B_item":[1, 7, 10], "C_item":[9, 2, 9], }) and i need to get t...
[ "You can try the following code:\ndef extract_date(x):\n pattern = \"[0-9]+-[0-9]+-[0-9]+\"\n match = re.findall(pattern, x)\n return match[0]\n\ndf[\"new_column\"] = df[\"first_colum\"].apply(extract_date)\n\nfirst_column is the source column.\nThen you should get the output below:\n\n", "df['Extracted ...
[ 0, 0 ]
[]
[]
[ "dataframe", "date", "python", "regex" ]
stackoverflow_0074493455_dataframe_date_python_regex.txt
Q: Can't change owner of file into a shared drive I want to change the "owner" of a file into a shared drive. However I have no permissions to do that since it says, I can't do that in shared files. This is the approach I have done so far: param_perm = {} param_perm['emailAddress'] = 'john@xxx.nl' ...
Can't change owner of file into a shared drive
I want to change the "owner" of a file into a shared drive. However I have no permissions to do that since it says, I can't do that in shared files. This is the approach I have done so far: param_perm = {} param_perm['emailAddress'] = 'john@xxx.nl' param_perm['type'] = 'user' param_p...
[ "Ownership transfer is not supported for files and folders within shared drives. As mentioned in this Drive API Guide\n\nAn organization that owns a shared drive owns the files within it. Therefore, ownership transfers are not supported for files and folders in shared drives. Organizers of a shared drive can move i...
[ 0 ]
[]
[]
[ "google_drive_api", "python" ]
stackoverflow_0074487132_google_drive_api_python.txt
Q: I can't read data from json in excel I'm trying to read data from a json file and translate it to excel, but I get an error. Thank you in advance. Error: Traceback (most recent call last): File "C:\Users\kryto\Desktop\csgo\xx.py", line 20, in sheet[row][0].value = hui['price'] File "C:\Users\kryto\AppData\Local\P...
I can't read data from json in excel
I'm trying to read data from a json file and translate it to excel, but I get an error. Thank you in advance. Error: Traceback (most recent call last): File "C:\Users\kryto\Desktop\csgo\xx.py", line 20, in sheet[row][0].value = hui['price'] File "C:\Users\kryto\AppData\Local\Programs\Python\Python310\lib\site-packages...
[ "The error is because the hui['price'] data type cannot be converted to an excel data type.\nBy example, the next line will produce the same error:\nsheet[row][0].value = []\n\nas openpyxl can not convert a list to an excel data type.\nReview the data source or debug your code (ie. print hui['price'] before assigni...
[ 0 ]
[]
[]
[ "json", "openpyxl", "python" ]
stackoverflow_0074493337_json_openpyxl_python.txt
Q: glVertexAttribPointer() can't find valid context on Wayland environment? I try to draw colorized triangle. I want to use modern OpenGL and translate data via vertex attrib array. Vertex shader and Fragment shader just pass color from input to output and don't contain any interesting code pg.init() triangle = np.a...
glVertexAttribPointer() can't find valid context on Wayland environment?
I try to draw colorized triangle. I want to use modern OpenGL and translate data via vertex attrib array. Vertex shader and Fragment shader just pass color from input to output and don't contain any interesting code pg.init() triangle = np.array( triangle, dtype=np.float32 ) triangle_buffer = glGenBuffers( 1 ) glBind...
[ "It's need to swich Wayland to Xorg at login time! On Wayland you can add env variable PYOPENGL_PLATFORM=x11.\n" ]
[ 1 ]
[]
[]
[ "opengl", "pyopengl", "python", "wayland", "xorg" ]
stackoverflow_0072705777_opengl_pyopengl_python_wayland_xorg.txt
Q: I am trying to add more variables automatically, which i don't know I want to automate and add more of (atr1,2,3,4,etc) and (karatr1,2,3,4,etc) I would be happy if you helped. <3 giriş = float(input("Giriş yapma anı: ")) atr = float(input("Girişteki atr değeri: ")) atr1= (atr) atr2= (atr*2) atr3= (atr*3) atr4= (a...
I am trying to add more variables automatically, which i don't know
I want to automate and add more of (atr1,2,3,4,etc) and (karatr1,2,3,4,etc) I would be happy if you helped. <3 giriş = float(input("Giriş yapma anı: ")) atr = float(input("Girişteki atr değeri: ")) atr1= (atr) atr2= (atr*2) atr3= (atr*3) atr4= (atr*4) atr5= (atr*5) atr6= (atr*6) atr7= (atr*7) atr8= (atr*8) atr9= (atr*...
[]
[]
[ "First dont use Turkish characters in variable names.\nTry this :\ngiriş = float(input(\"Giriş yapma anı: \"))\natr = float(input(\"Girişteki atr değeri: \"))\n\natrcnt=10\n\natrlist=[item * atr for item in list(range(0,atrcnt))]\nkaratrlist=[item + giriş for item in atrlist]\n#and then if you want\nkaratr1,karatr2...
[ -1 ]
[ "python" ]
stackoverflow_0074493854_python.txt
Q: Increment Big integer by 1 in Jython I have an attribute which has value stored in Big Integer and would like to increment it to 1. For example A = 2,000 B = A +1 I tried the following however resulted in syntax error. B = int(A) + 1 B = type(A)+1 Please note that 2,000 is a system generated number and ...
Increment Big integer by 1 in Jython
I have an attribute which has value stored in Big Integer and would like to increment it to 1. For example A = 2,000 B = A +1 I tried the following however resulted in syntax error. B = int(A) + 1 B = type(A)+1 Please note that 2,000 is a system generated number and we cannot modify the same
[ "A = 2,000\n\nThis is not the number two thousand. Because of the comma, it is a tuple (2, 0).\nDon't use commas as a thousands separator.\nAssign the value without any separators:\nA = 2000\n\nOr you can use _ as a separator:\nA = 2_000\n\nHowever, be aware that using _ as a separator is purely cosmetic. If you ...
[ 1 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0074493893_jython_python.txt
Q: In Django, How do I get escaped html in HttpResponse? The following code in one of my views returns unescaped html string which cannot be parsed in frontend since it is an Ajax request. return render_to_response(template_name, { 'form': form, redirect_field_name: redirect_to, 'site': curren...
In Django, How do I get escaped html in HttpResponse?
The following code in one of my views returns unescaped html string which cannot be parsed in frontend since it is an Ajax request. return render_to_response(template_name, { 'form': form, redirect_field_name: redirect_to, 'site': current_site, 'site_name': current_site.name, }, cont...
[ "Lakshman Prasad's answer is technically correct, but a bit cumbersome. A better way to escape text would be (as suggested in a comment by miku above):\nfrom django.utils.html import escape\nreturn HttpResponse(escape(some_string))\n\n", "To return just plain HTML to the client from within your view, use django.h...
[ 33, 6, 1, 0, 0 ]
[]
[]
[ "django", "django_templates", "escaping", "httpresponse", "python" ]
stackoverflow_0001946281_django_django_templates_escaping_httpresponse_python.txt