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: Use Python to get value from element in XML file I'm writing a program in Python that looks at an XML file that I get from an API and should return a list of users' initials to a list for later use. My XML file looks like this with about 60 users: <ArrayOfuser xmlns="WebsiteWhereDataComesFrom.com" xmlns:i="http://...
Use Python to get value from element in XML file
I'm writing a program in Python that looks at an XML file that I get from an API and should return a list of users' initials to a list for later use. My XML file looks like this with about 60 users: <ArrayOfuser xmlns="WebsiteWhereDataComesFrom.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <user> ...
[ "As this is xml with namespace, you can have like\nimport xml.etree.ElementTree as ET\nroot = ET.fromstring(xml_in_qes)\nmy_ns = {'root': 'WebsiteWhereDataComesFrom.com'}\nmyUser=[]\nfor eachUser in root.findall('root:user',my_ns):\n rep=eachUser.find(\"root:rep\",my_ns)\n print(rep.text)\n myUser.append(r...
[ 1, 0, 0 ]
[]
[]
[ "json", "python", "xml" ]
stackoverflow_0074659126_json_python_xml.txt
Q: Why does Python installed via Homebrew not include Tkinter I've installed Python via Homebrew on my Mac. brew install python After that I checked my Python version as 2.7.11, then I tried to perform import Tkinter I got following error message: Traceback (most recent call last): File "<stdin>", line 1, in <mod...
Why does Python installed via Homebrew not include Tkinter
I've installed Python via Homebrew on my Mac. brew install python After that I checked my Python version as 2.7.11, then I tried to perform import Tkinter I got following error message: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.f...
[ "I am running MacOS Big Sur (11.2.3).\nWith python2, I have Tkinter built-in.\nWith python3, it has to be installed manually and it's very simple, just run:\n$ brew install python-tk\n\nTo run python2 in a terminal, execute python file.py.\nTo run python3 in a terminal, execute python3 file.py.\n", "Based on the ...
[ 61, 25, 11, 11, 9, 6, 4, 3, 3, 0, 0 ]
[]
[]
[ "macos", "python", "python_3.x", "tkinter" ]
stackoverflow_0036760839_macos_python_python_3.x_tkinter.txt
Q: Dynamically Edit PDF File I have a PDF template containing some text, the PDF file has a name repeated many times, I want to write a code that takes the {name} as input, then dynamically changes all appearance of the name in the pdf to the value I have entered then output the file after the changes. I have tried t...
Dynamically Edit PDF File
I have a PDF template containing some text, the PDF file has a name repeated many times, I want to write a code that takes the {name} as input, then dynamically changes all appearance of the name in the pdf to the value I have entered then output the file after the changes. I have tried to build a pdf from the begging ...
[ "PyFPDF has a template designer for alignment etc. however it is not the same as Acrobat or other FDF editors where a field can be copy pasted multiple times as numbered increments. It uses a different csv methodology where you would need to add each repeated name as a line entry in the data file.\n\nFor the tutori...
[ 0 ]
[]
[]
[ "automation", "pdf", "pyfpdf", "python" ]
stackoverflow_0074656772_automation_pdf_pyfpdf_python.txt
Q: Is there any Gson similar libraries for Python I am new to python .I was trying to create json responses for my android app. I was wondering if there is any library similar to GSON for python. http://nullege.com/codes/search/com.google.gson.Gson at this link i saw Gson the usage. Can anyone please tell me if there...
Is there any Gson similar libraries for Python
I am new to python .I was trying to create json responses for my android app. I was wondering if there is any library similar to GSON for python. http://nullege.com/codes/search/com.google.gson.Gson at this link i saw Gson the usage. Can anyone please tell me if there is GSON libary for python , or any other similar li...
[ "You can use Pykson, JSON Serializer and Deserializer for Python which is somehow like Gson. It supports lists of objects and serialization names.\nSimply define your object model as JsonObject, and use Pykson to convert it back and forth to JSON.\nclass Student(JsonObject):\n first_name = StringField(serialized...
[ 4, 1, 0 ]
[]
[]
[ "gson", "json", "python" ]
stackoverflow_0034805435_gson_json_python.txt
Q: How to calculate distance from a player to a dynamic collision point I'm trying to create sensors for a car to keep track of the distances from the car to the borders of the track. My goal is to have 5 sensors (see image below) and use them to train a machine learning algorithm. But I can't figure out a way to cal...
How to calculate distance from a player to a dynamic collision point
I'm trying to create sensors for a car to keep track of the distances from the car to the borders of the track. My goal is to have 5 sensors (see image below) and use them to train a machine learning algorithm. But I can't figure out a way to calculate these distances. For now, I just need a sample of code and a logica...
[ "Thank you for the comments, I solved my problem using the idea of firing sensors so I can get the point on the wall when the \"bullet\" hits it.\n\nAs we can see when the bullet hits the wall we can create a line that connects the point to the car. This is not the best solution, as it takes time for the bullet to ...
[ 0 ]
[]
[]
[ "euclidean_distance", "geometry", "math", "python", "raycasting" ]
stackoverflow_0074616569_euclidean_distance_geometry_math_python_raycasting.txt
Q: numpy.ndarray.data attribute buffer object I create different numpy arrays as follows: import numpy as np a = np.array([[1,2,3],[1,2,3]]) # 2d array of integers b = np.array([[1,2,3],[1,2,5.0]]) # 2d array of floats c = np.array([1,2,3,4,5,6,7,8,9]) # 1d array of integers d = np.array([10,20,30]) #...
numpy.ndarray.data attribute buffer object
I create different numpy arrays as follows: import numpy as np a = np.array([[1,2,3],[1,2,3]]) # 2d array of integers b = np.array([[1,2,3],[1,2,5.0]]) # 2d array of floats c = np.array([1,2,3,4,5,6,7,8,9]) # 1d array of integers d = np.array([10,20,30]) # different 1d array of integers # python buffe...
[ "They aren't sharing the same memory. .data creates a memoryview object every time the attribute is accessed.\nYou can see from this session that it's a different address every time:\n>>> d.data\n<memory at 0x6ffff70bddc0>\n>>> d.data\n<memory at 0x6ffff70bdb80>\n>>> d.data\n<memory at 0x6ffff70bd1c0>\n\nIn your ca...
[ 2, 1 ]
[]
[]
[ "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074661127_numpy_numpy_ndarray_python.txt
Q: Run code for every subset starting by filtering data with df.loc I am trying to run some experiments with my Python code. The input of my code is based on a DataFrame. To filter my DataFrame I use df.loc. Before running my code I filter the DataFrame for the instance I want to run my code. I have the following lis...
Run code for every subset starting by filtering data with df.loc
I am trying to run some experiments with my Python code. The input of my code is based on a DataFrame. To filter my DataFrame I use df.loc. Before running my code I filter the DataFrame for the instance I want to run my code. I have the following list of instances: instance = ['A', 'B', 'C', 'D'] (These instances are ...
[ "I think you want to use pandas.Series.apply which\n\nInvoke[s] function on values of Series.\n\nIt takes each value from the series, in your case df[\"Instance\"] and passes it through a function. Your function only needs to check whether the instance is in the element of subsets you're currently working on:\nfor ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074661188_dataframe_pandas_python.txt
Q: Pandas groupby two columns get earliest date This is the dataset: ` data = {'id': ['1','1','1','1','2','2','2','2','2','3','3','3','3','3','3','3'], 'status': ['Active','Active','Active','Pending Action','Pending Action','Pending Action','Active','Pending Action','Active','Draft','Active','Dr...
Pandas groupby two columns get earliest date
This is the dataset: ` data = {'id': ['1','1','1','1','2','2','2','2','2','3','3','3','3','3','3','3'], 'status': ['Active','Active','Active','Pending Action','Pending Action','Pending Action','Active','Pending Action','Active','Draft','Active','Draft','Draft','Draft','Active','Draft'], ...
[ "Try:\ndf[\"desired_output\"] = df.groupby(\"id\")[\"status\"].transform(\n lambda x: df.loc[x.index, \"calc_date_id\"][(x != x.shift(-1)).idxmax()]\n)\nprint(df)\n\nPrints:\n id status calc_date_id desired_output\n0 1 Active 2022-07-05 2021-08-31\n1 1 Active 2022-06-07 ...
[ 0, 0 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python", "sorting" ]
stackoverflow_0074660690_dataframe_group_by_pandas_python_sorting.txt
Q: Newbie question about return keyword in Python functions I am currently working in codecademy on a Python course and while trying to define a function that takes in a list and returns a list with the length of that same list added to the list I realized I keeping getting "None" instead of a full list and was wonde...
Newbie question about return keyword in Python functions
I am currently working in codecademy on a Python course and while trying to define a function that takes in a list and returns a list with the length of that same list added to the list I realized I keeping getting "None" instead of a full list and was wondering why. I was able figure out the correct solution but for m...
[ "lst.append always returns None. It modifies lst in place, so all you need to do is return lst itself.\ndef append_size(lst):\n lst.append(len(lst))\n return lst\n\n\nThis is a violation, though, of the usually conventional (followed by list.append itself) that a function or method should either modify an arg...
[ 0 ]
[]
[]
[ "function", "python", "return" ]
stackoverflow_0074661327_function_python_return.txt
Q: How to convert text into structured data, taking into account missing fields, in Python? First, apologies if this sounds too basic. I have the following semi-structured data in text format, I need to parse these into a structured format: example: Name Alex Address 14 high street London Color blue red Name Bob ...
How to convert text into structured data, taking into account missing fields, in Python?
First, apologies if this sounds too basic. I have the following semi-structured data in text format, I need to parse these into a structured format: example: Name Alex Address 14 high street London Color blue red Name Bob Color black **Note that Alex has two colors, while Bob does not have an address. ** I want so...
[ "Try:\ns = \"\"\"\\\nName\nAlex\n\nAddress\n14 high street\nLondon\n\nColor\nblue\nred\n\nName\n\nBob\nColor\nblack\"\"\"\n\n\nimport pandas as pd\nfrom itertools import groupby\n\ncolnames = [\"Name\", \"Address\", \"Color\"]\n\n\ncol1, col2 = [], []\nfor k, g in groupby(\n (l for l in s.splitlines() if l.strip...
[ 2, 0 ]
[]
[]
[ "dataframe", "python", "python_re", "string" ]
stackoverflow_0074661015_dataframe_python_python_re_string.txt
Q: How to install telegram api 'aiogram' I just tried to install telegram api 'aiogram' and it didn't work building 'yarl._quoting_c' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] ...
How to install telegram api 'aiogram'
I just tried to install telegram api 'aiogram' and it didn't work building 'yarl._quoting_c' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subpro...
[ "It looks like you are trying to install the aiogram library for Python, but you are encountering an error related to Microsoft Visual C++ 14.0 or greater. This error is occurring because the aiogram library has a dependency on the yarl library, which requires Microsoft Visual C++ 14.0 or greater to be installed on...
[ 0 ]
[]
[]
[ "aiogram", "python", "telegram_bot" ]
stackoverflow_0074661367_aiogram_python_telegram_bot.txt
Q: checking a variable against a record in a sqlite3 database to see if data entered is unique so I am trying to create a function that allows a user to create a profile with personal information, in this they will enter a username that will act as primary key and requires to be unique, so when entering this username...
checking a variable against a record in a sqlite3 database to see if data entered is unique
so I am trying to create a function that allows a user to create a profile with personal information, in this they will enter a username that will act as primary key and requires to be unique, so when entering this username I am trying to check the data entered to see if it already exists in the sqlite3 database, if it...
[ "It looks like you're trying to check if the username already exists in the database. To do this, you can use an SQL SELECT query to check if the username exists in the users table. If the query returns a result, then the username already exists and you can prompt the user to enter a different username.\nHere's one...
[ 1 ]
[]
[]
[ "python", "sql", "validation" ]
stackoverflow_0074661361_python_sql_validation.txt
Q: How to define different layers in neural network with MLPRegressor I am trying to set up a neural network model using MLPRegressor, I have been told to do so using the following structure: The network must have two different hidden layer node layouts: the first with one hidden layer with 100 nodes, the second wit...
How to define different layers in neural network with MLPRegressor
I am trying to set up a neural network model using MLPRegressor, I have been told to do so using the following structure: The network must have two different hidden layer node layouts: the first with one hidden layer with 100 nodes, the second with three hidden layers with 100 nodes each. Use the neural network fittin...
[ "To use two different hidden layer node layouts and two activation functions with the MLPRegressor class, you can specify the hidden layer node layouts and activation functions as a list. For example:\nfrom sklearn.neural_network import MLPRegressor\n\n# Define the hidden layer node layout\nhidden_layer_sizes = (10...
[ 1 ]
[]
[]
[ "artificial_intelligence", "deep_learning", "neural_network", "python", "scikit_learn" ]
stackoverflow_0074661342_artificial_intelligence_deep_learning_neural_network_python_scikit_learn.txt
Q: Extract date from string in date format, add n number of days. to then replace with that modified data another substring within the original string import re, datetime, time input_text = "tras la aparicion del objeto misterioso el 2022-12-30 visitamos ese sitio nuevamente revisando detras de los arboles pero reci...
Extract date from string in date format, add n number of days. to then replace with that modified data another substring within the original string
import re, datetime, time input_text = "tras la aparicion del objeto misterioso el 2022-12-30 visitamos ese sitio nuevamente revisando detras de los arboles pero recien tras 3 dias ese objeto aparecio de nuevo tras 2 arboles" #example 1 input_text = "luego el 2022-11-15 fuimos nuevamente a dicho lugar pero nada ocurri...
[ "Here is a regex solution you could use:\n([12]\\d{3}-[01]\\d-[0-3]\\d)(\\D*?)(?:(?:luego de|pasados|tras)(?: ya)?(?: unos)? (\\d+) dias|(\\d+) dias (?:despues|luego))\n\nThis regex requires that there are no other digits between the date and the days. It also is a bit loose on grammar. It would also match \"luego ...
[ 1 ]
[]
[]
[ "datetime", "python", "python_3.x", "regex", "regex_group" ]
stackoverflow_0074660456_datetime_python_python_3.x_regex_regex_group.txt
Q: Merge 2 dataframes and update column with lists using condtions I have 2 dataframes with same columns and indexes. a a 1 [] 1 [5,2,7] 2 [1,2,3] 2 [1,2,3,4] 3 [7] 3 [7,5] I want to merge them using condition, when length of list is <=1 then take value and add it t...
Merge 2 dataframes and update column with lists using condtions
I have 2 dataframes with same columns and indexes. a a 1 [] 1 [5,2,7] 2 [1,2,3] 2 [1,2,3,4] 3 [7] 3 [7,5] I want to merge them using condition, when length of list is <=1 then take value and add it to 1st data frame, else left old value. So after that result is: ...
[ "for i, (x,y) in enumerate(zip(dfa['a'], dfb['b'])):\n # apply your logic - 'when length of list is <=1 then take value...' and save it in dfa['a'][i]\n if len(x) <= 1:\n dfa.loc[i]['a'] = y\n\n", "Here is an approach using pandas.DataFrame.mask.\nFirst, make sure that the values of each dataframe/co...
[ 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074661219_pandas_python.txt
Q: Unable to convert a pandas Dataframe to a list using literal_eval I have been trying to convert a pandas Dataframe column to a list as the data in the column is being read as a str by default. Sample data in the dataframe 'movie' column 'genres' is [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"...
Unable to convert a pandas Dataframe to a list using literal_eval
I have been trying to convert a pandas Dataframe column to a list as the data in the column is being read as a str by default. Sample data in the dataframe 'movie' column 'genres' is [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}] ...
[ "pandas.DataFrames are composed of Series objects (where a Series is simply a column. Series are container objects similar to Python lists and can actually be converted into a list by using their Series.tolist method.\nast.literal_eval is being applied on each element inside of your Series, converting them a string...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074661236_pandas_python.txt
Q: WatchDog Library is only running once I am new to coding and python, and I am struggling to use this WatchDog library to run this data_analysis function when a file is added to a folder. While it runs, i notice that pasting this function makes the watchdog only detect an added file once. Without, it will keep runn...
WatchDog Library is only running once
I am new to coding and python, and I am struggling to use this WatchDog library to run this data_analysis function when a file is added to a folder. While it runs, i notice that pasting this function makes the watchdog only detect an added file once. Without, it will keep running. Anyone know why? I have tried searchin...
[ "class Handler(watchdog.events.PatternMatchingEventHandler):\n def __init__(self):\n watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=['*.pdf'],\n ignore_patterns = None,\n ...
[ 0 ]
[]
[]
[ "python", "python_watchdog", "tkinter" ]
stackoverflow_0074480624_python_python_watchdog_tkinter.txt
Q: How do I make a post request work after using get_queryset? I would like to have a list of a user's devices with a checkbox next to each one. The user can select the devices they want to view on a map by clicking on the corresponding checkboxes then clicking a submit button. I am not including the mapping portion ...
How do I make a post request work after using get_queryset?
I would like to have a list of a user's devices with a checkbox next to each one. The user can select the devices they want to view on a map by clicking on the corresponding checkboxes then clicking a submit button. I am not including the mapping portion in this question, because I plan to work that out later. The step...
[ "I think you're better off using a function based view with the typical \"if request.method = POST\" logic, this isn't really what the generic list view is for.\n@loginrequired\ndef device_list_view(request):\n context = {}\n if request.method = POST:\n form = SelectForm(request.POST)\n if form....
[ 0 ]
[]
[]
[ "django", "post", "python" ]
stackoverflow_0074659563_django_post_python.txt
Q: Does Bert model need text? Does Bert models need pre-processed text (Like removing special characters, stopwords, etc.) or I can directly pass my text as it is to Bert models. (HuggigFace libraries). note: Follow up question to: String cleaning/preprocessing for BERT A: Cleaning the input text for transformer mo...
Does Bert model need text?
Does Bert models need pre-processed text (Like removing special characters, stopwords, etc.) or I can directly pass my text as it is to Bert models. (HuggigFace libraries). note: Follow up question to: String cleaning/preprocessing for BERT
[ "Cleaning the input text for transformer models is not required. Removing stop words (which are considered as noise in conventional text representation like bag-of-words or tf-idf) can and probably will worsen the predictions of your BERT model.\nSince BERT is making use of the self-attention mechanism these 'stop ...
[ 1, 0, 0 ]
[]
[]
[ "bert_language_model", "data_preprocessing", "nlp", "python", "text_classification" ]
stackoverflow_0070649831_bert_language_model_data_preprocessing_nlp_python_text_classification.txt
Q: Program python that launch when start Windows I know, it's a lot of similar questions, but i don't understand how i can make a python program what launch when you start pc, so please learn me that. I want to get a code in python what explain me how to create a program what start when you lanch the pc A: This typ...
Program python that launch when start Windows
I know, it's a lot of similar questions, but i don't understand how i can make a python program what launch when you start pc, so please learn me that. I want to get a code in python what explain me how to create a program what start when you lanch the pc
[ "This type of execution in programs/script is usually done through the task scheduler\nA simple tutorial would be following the next steps:\n1: At the windows search box, type: task scheduler\n2: Open Task scheduler\n3: From Action menu select Create Task.\n4: At General tab, type a name for the task. e.g. \"StartP...
[ 0 ]
[]
[]
[ "app_startup", "python" ]
stackoverflow_0074661287_app_startup_python.txt
Q: Pandas equivelt of pyspark reduce and add? I have a dataframe in the following where Day_1, Day_2, Day_3 are the number of impressions in the past 3 days. df = pd.DataFrame({'Day_1': [2, 4, 8, 0], 'Day_2': [2, 0, 0, 0], 'Day_3': [1, 1, 0, 0], index=['user1', ...
Pandas equivelt of pyspark reduce and add?
I have a dataframe in the following where Day_1, Day_2, Day_3 are the number of impressions in the past 3 days. df = pd.DataFrame({'Day_1': [2, 4, 8, 0], 'Day_2': [2, 0, 0, 0], 'Day_3': [1, 1, 0, 0], index=['user1', 'user2', 'user3', 'user4']) df Day_1 Day_2...
[ "IIUC, you can use numpy.where with pandas.DataFrame.sum.\nTry this :\ndf[\"impression\"] = np.where(df.sum(axis=1).gt(0), 1, 0)\n\n# Output :\nprint(df)\n​\n Day_1 Day_2 Day_3 impression\nuser1 2 2 1 1\nuser2 4 0 1 1\nuser3 8 0 0 1...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074661465_dataframe_pandas_python.txt
Q: Background color of bokeh layout I'm playing around with the Bokeh sliders demo (source code here), and I'm trying to change the background color of the entire page. Though changing the color of the figure is easy using background_fill_color and border_fill_color, the rest of the layout still appears on top of a w...
Background color of bokeh layout
I'm playing around with the Bokeh sliders demo (source code here), and I'm trying to change the background color of the entire page. Though changing the color of the figure is easy using background_fill_color and border_fill_color, the rest of the layout still appears on top of a white background. Is there an attribute...
[ "There's not currently any Python property that would control the HTML background color. HTML and CSS is vast territory, so instead of trying to make a corresponding Python property for every possible style option, Bokeh provides a general mechanism for supplying your own HMTL templates so that any standard familia...
[ 6, 3, 1, 0 ]
[ "From Bokeh documentation:\n\nThe background fill style is controlled by the background_fill_color\n and background_fill_alpha properties of the Plot object:\nfrom bokeh.plotting import figure, output_file, show\n\noutput_file(\"background.html\")\n\np = figure(plot_width=400, plot_height=400)\np.background_fill_c...
[ -1 ]
[ "bokeh", "python" ]
stackoverflow_0044607084_bokeh_python.txt
Q: how do i remove buttons off a message? button = Button(style = discord.ButtonStyle.green, emoji = ":arrow_backward:", custom_id = "button1") button2 = Button(style = discord.ButtonStyle.green, emoji = ":arrow_up_small:", custom_id = "button2") button3 = Button(style = discord.ButtonStyle.green, emoji = ":arrow_for...
how do i remove buttons off a message?
button = Button(style = discord.ButtonStyle.green, emoji = ":arrow_backward:", custom_id = "button1") button2 = Button(style = discord.ButtonStyle.green, emoji = ":arrow_up_small:", custom_id = "button2") button3 = Button(style = discord.ButtonStyle.green, emoji = ":arrow_forward:", custom_id = "button3") view = View()...
[ "Set view=None in your message.edit function call to remove all of the buttons.\n" ]
[ 0 ]
[]
[]
[ "discord", "pycord", "python" ]
stackoverflow_0074607302_discord_pycord_python.txt
Q: Calculate co-occurrences without any overlap in pandas I have the following dataframe import pandas as pd df = pd.DataFrame({'TFD' : ['AA', 'SL', 'BB', 'D0', 'Dk', 'FF'], 'Snack' : [1, 0, 1, 1, 0, 0], 'Trans' : [1, 1, 1, 0, 0, 1], 'Dop' : [1, 0, 1, 0, 1, ...
Calculate co-occurrences without any overlap in pandas
I have the following dataframe import pandas as pd df = pd.DataFrame({'TFD' : ['AA', 'SL', 'BB', 'D0', 'Dk', 'FF'], 'Snack' : [1, 0, 1, 1, 0, 0], 'Trans' : [1, 1, 1, 0, 0, 1], 'Dop' : [1, 0, 1, 0, 1, 1]}).set_index('TFD') df Snack Trans Dop TFD ...
[ "Managed to shrink it to one \"for\" loop. I am using \"any\" and \"all\" in combination with \"mask\".\nimport pandas as pd\nimport itertools\n\n\ndf = pd.DataFrame({'TFD': ['AA', 'SL', 'BB', 'D0', 'Dk', 'FF'],\n 'Snack': [1, 0, 1, 1, 0, 0],\n 'Trans': [1, 1, 1, 0, 0, 1],\n ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074641437_pandas_python.txt
Q: Virtualenv not compatible with this system or executable Simply trying to create a virtual environment on my mac OSX 10.10.05 Running from the Terminal, already successfully made VirtualEnv on linux and windows OS on other computers. Tried troubleshooting this by adding a WORK_ON path to my bash profile, did not r...
Virtualenv not compatible with this system or executable
Simply trying to create a virtual environment on my mac OSX 10.10.05 Running from the Terminal, already successfully made VirtualEnv on linux and windows OS on other computers. Tried troubleshooting this by adding a WORK_ON path to my bash profile, did not resolve. Online forums doesn't seem to address this, suggestion...
[ "My limited undestanding is that my python interpreter and packages are managed under Anaconda using Conda package manager, and my virtualenv was originally installed using pip..\nuninstalling virtualenv with pip and re-installing with conda fixed the issue\npip uninstall virtualenv\n\nconda install virtualenv\n\n"...
[ 34, 0 ]
[]
[]
[ "bash", "python", "virtualenv" ]
stackoverflow_0044575994_bash_python_virtualenv.txt
Q: Keep observations with two or more consecutive years of data by group I have a dataset consisting of directorid, match_id, and calyear. I would like to keep only observations by director_id and match_id that have at least 2 consecutive years of data. I have tried a few different ways to do this, and haven't been a...
Keep observations with two or more consecutive years of data by group
I have a dataset consisting of directorid, match_id, and calyear. I would like to keep only observations by director_id and match_id that have at least 2 consecutive years of data. I have tried a few different ways to do this, and haven't been able to get it quite right. The few different things I have tried have also ...
[ "Yes you need to groupby 'director_id', 'match_id' and then do a transform but the transform just needs to look at the difference between next element in both directions. In one direction you need to see if it equals 1 and in another -1 and then subset using the resulting True/False values.\ndf = df[\n df.groupb...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074661298_pandas_python.txt
Q: Print output includes 'None' def backwards_alphabet(curr_letter): if curr_letter == 'a': print(curr_letter) else: print(curr_letter) prev_letter = chr(ord(curr_letter) - 1) backwards_alphabet(prev_letter) starting_letter = input() print (backwards_alphabet(starting_letter)...
Print output includes 'None'
def backwards_alphabet(curr_letter): if curr_letter == 'a': print(curr_letter) else: print(curr_letter) prev_letter = chr(ord(curr_letter) - 1) backwards_alphabet(prev_letter) starting_letter = input() print (backwards_alphabet(starting_letter)) #this is the code i wrote The o...
[ "The function print takes a parameter - you are giving it the result of backwards_alphabet(starting_letter).\nSince you aren't explicit about what backwards_alphabet() returns - which you do would with by including return 'this is what I am returning', it will return None by default.\nSo, you are calling print(Non...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074661626_python.txt
Q: Simplify Python array retrieval of values I have the following code at the moment which works perfectly:- my_array = [ ['var1', 1], ['var2', 2], ['var3', 3], ['var4', 4], ['var5', 5] ] for i in range(len(my_array)): if my_array[i][0] == "var1": var_a = my_array[i][1] elif my_array[i][0] == "va...
Simplify Python array retrieval of values
I have the following code at the moment which works perfectly:- my_array = [ ['var1', 1], ['var2', 2], ['var3', 3], ['var4', 4], ['var5', 5] ] for i in range(len(my_array)): if my_array[i][0] == "var1": var_a = my_array[i][1] elif my_array[i][0] == "var2": var_b = my_array[i][1] elif my...
[ "You can convert my_array to dict to simplify the retrieval of values:\nmy_array = [[\"var1\", 1], [\"var2\", 2], [\"var3\", 3], [\"var4\", 4], [\"var5\", 5]]\n\ndct = dict(my_array)\n\n# print var1\nprint(dct[\"var1\"])\n\nPrints:\n1\n\n" ]
[ 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074661638_list_python_python_3.x.txt
Q: Dynamic Importing with Pyinstaller Executable I’m trying to write a script that dynamically imports and uses any modules a user places in a folder. The dynamic importing works fine when I’m running it via python, but when I try to compile it into a Pyinstaller executable, it breaks down and throws me a ModuleNotFo...
Dynamic Importing with Pyinstaller Executable
I’m trying to write a script that dynamically imports and uses any modules a user places in a folder. The dynamic importing works fine when I’m running it via python, but when I try to compile it into a Pyinstaller executable, it breaks down and throws me a ModuleNotFoundError, saying it can't find a module with the sa...
[ "I was working on a similar functionality to implement a Plugin Architecture and ran into the same issue. Quoting @Gao Yuan from a similar question :-\n\nPyinstaller (currently v 3.4) can't detect imports like importlib.import_module(). The issue and solutions are detailed in Pyinstaller's documentation, which I pa...
[ 0 ]
[]
[]
[ "dynamic_import", "pyinstaller", "python" ]
stackoverflow_0071162951_dynamic_import_pyinstaller_python.txt
Q: Merge lists within dictionaries with the same keys I have the following three dictionaries within a list like so: dict1 = {'key1':'x', 'key2':['one', 'two', 'three']} dict2 = {'key1':'x', 'key2':['four', 'five', 'six']} dict3 = {'key1':'y', 'key2':['one', 'two', 'three']} list = [dict1, dict2, dict3] I'd like ...
Merge lists within dictionaries with the same keys
I have the following three dictionaries within a list like so: dict1 = {'key1':'x', 'key2':['one', 'two', 'three']} dict2 = {'key1':'x', 'key2':['four', 'five', 'six']} dict3 = {'key1':'y', 'key2':['one', 'two', 'three']} list = [dict1, dict2, dict3] I'd like to merge the dictionaries that have the same value for k...
[ "With the help of itertools.groupby and itertools.chain, your goal can be achieved in a single line:\nfrom itertools import groupby\nfrom itertools import chain\n\ndict1 = {'key1':'x', 'key2':['one', 'two', 'three']}\ndict2 = {'key1':'x', 'key2':['four', 'five', 'six']}\ndict3 = {'key1':'y', 'key2':['one', 'two', '...
[ 2, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074661388_dictionary_list_python.txt
Q: Can FastAPI guarantee a sync handler will never block the main application thread? I have the following FastAPI application: from fastapi import FastAPI import socket app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} @app.get("/healthcheck") def health_check(): result = s...
Can FastAPI guarantee a sync handler will never block the main application thread?
I have the following FastAPI application: from fastapi import FastAPI import socket app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} @app.get("/healthcheck") def health_check(): result = some_network_operation() return result def some_network_operation(): HOST = "...
[ "Yes, if you try to do sync work in a async method it will block FastAPI, something like this:\n@router.get(\"/healthcheck\")\nasync def health_check():\n result = some_network_operation()\n return result\n\nWhere some_network_operation() is blocking the event loop because it is a synchronous method.\n", "I...
[ 0, 0 ]
[]
[]
[ "fastapi", "python", "sockets", "tcp" ]
stackoverflow_0074636003_fastapi_python_sockets_tcp.txt
Q: import custom python module in azure ml deployment environment I have an sklearn k-means model. I am training the model and saving it in a pickle file so I can deploy it later using azure ml library. The model that I am training uses a custom Feature Encoder called MultiColumnLabelEncoder. The pipeline model is de...
import custom python module in azure ml deployment environment
I have an sklearn k-means model. I am training the model and saving it in a pickle file so I can deploy it later using azure ml library. The model that I am training uses a custom Feature Encoder called MultiColumnLabelEncoder. The pipeline model is defined as follow : # Pipeline kmeans = KMeans(n_clusters=3, random_st...
[ "In fact, the solution was to import my customized class MultiColumnLabelEncoder as a pip package (You can find it through pip install multilllabelencoder==1.0.5).\nThen I passed the pip package to the .yml file or in the InferenceConfig of the azure ml environment.\nIn the score.py file, I imported the class as fo...
[ 4, 4, 0 ]
[]
[]
[ "azure_machine_learning_service", "azure_machine_learning_studio", "pickle", "python" ]
stackoverflow_0059176241_azure_machine_learning_service_azure_machine_learning_studio_pickle_python.txt
Q: how can I count the occurrences > than a value for each year of a data frame I have a data frame with the values of precipitations day per day. I would like to do a sort of resample, so instead of day per day the data is collected year per year and every year has a column that contains the number of times it raine...
how can I count the occurrences > than a value for each year of a data frame
I have a data frame with the values of precipitations day per day. I would like to do a sort of resample, so instead of day per day the data is collected year per year and every year has a column that contains the number of times it rained more than a certain value. Date Precipitation 2000-01-01 1 2000-01-03 ...
[ "@Tatthew you can do this with GroupBy.apply:\nimport pandas as pd\ndf = pd.DataFrame({'Date': ['2000-01-01', '2000-01-03',\n '2000-01-03', '2001-01-01',\n '2001-01-02', '2001-01-03',\n '2002-01-01', '2002-01-02',\n ...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074659756_dataframe_pandas_python.txt
Q: I am having trouble trying to fix TypeError: string indices must be integers Grades.txt file I am currently trying to finish a assignment but I am confused on how to fix this error. I am creating a program that will analyzes grades from a file and should calculate the average score for each distinct section (given...
I am having trouble trying to fix TypeError: string indices must be integers
Grades.txt file I am currently trying to finish a assignment but I am confused on how to fix this error. I am creating a program that will analyzes grades from a file and should calculate the average score for each distinct section (given). I receive the error for sections[sec]["total"] = grade[grade] grades = {'A': 10...
[ "It looks like you are trying to access the value of the grade dictionary by using the value of the grade variable as a key. This won't work because the keys of the grade dictionary are strings (e.g. 'A', 'B', 'C'), but the value of the grade variable is also a string (e.g. 'A', 'B', 'C'), so you are trying to use ...
[ 0, 0 ]
[ "Welcome to SO\nThe error message you are getting is because you are trying to use the grade as a key to access the value in the grades dictionary. However, the grade variable contains the actual grade (e.g. 'A', 'B', etc.), not the key. To fix this, you need to use the grade variable to access the corresponding va...
[ -1 ]
[ "python" ]
stackoverflow_0074661176_python.txt
Q: how to automatically change IP got from proxy api to use for selenium from selenium import webdriver from selenium.webdriver.common.proxy import * from selenium.webdriver.common.by import By from time import sleep import requests response = requests.get("http://proxy.tinsoftsv.com/api/changeProxy.php?key=mykey_ap...
how to automatically change IP got from proxy api to use for selenium
from selenium import webdriver from selenium.webdriver.common.proxy import * from selenium.webdriver.common.by import By from time import sleep import requests response = requests.get("http://proxy.tinsoftsv.com/api/changeProxy.php?key=mykey_apiG&location=0") print(response.json()) proxy_url = "127.0.0.1:9009" proxy ...
[ "The code appears to be correctly importing the necessary modules and using them to create a Proxy object and a webdriver.Chrome object.\nHowever, there are a few issues with the code that may cause it to not work as expected:\nThe proxy_url variable is set to \"127.0.0.1:9009\", which is the localhost IP address a...
[ 0, 0 ]
[]
[]
[ "api", "python", "python_3.x", "selenium", "selenium_webdriver" ]
stackoverflow_0074661524_api_python_python_3.x_selenium_selenium_webdriver.txt
Q: 'DataFrame' object does not support item assignment I imported a df into Databricks as a pyspark.sql.dataframe.DataFrame. Within this df I have 3 columns (which I have verified to be strings) that I wish to concatenate. I have tried to use a simple "+" function first, eg. df["fullname"] = df["firstname"] + df["mid...
'DataFrame' object does not support item assignment
I imported a df into Databricks as a pyspark.sql.dataframe.DataFrame. Within this df I have 3 columns (which I have verified to be strings) that I wish to concatenate. I have tried to use a simple "+" function first, eg. df["fullname"] = df["firstname"] + df["middlename"] + df["lastname"] But I keep receiving the erro...
[ "The error message you are getting suggests that the DataFrame object you are trying to modify is immutable, which means that it cannot be changed. To solve this problem, you will need to create a new DataFrame object that contains the concatenated column. You can do this using the withColumn method, which creates ...
[ 1 ]
[]
[]
[ "databricks", "dataframe", "pandas", "pyspark", "python" ]
stackoverflow_0074661704_databricks_dataframe_pandas_pyspark_python.txt
Q: BeautifulSoup find partial string in section I am trying to use BeautifulSoup to scrape a particular download URL from a web page, based on a partial text match. There are many links on the page, and it changes frequently. The html I'm scraping is full of sections that look something like this: <section class="one...
BeautifulSoup find partial string in section
I am trying to use BeautifulSoup to scrape a particular download URL from a web page, based on a partial text match. There are many links on the page, and it changes frequently. The html I'm scraping is full of sections that look something like this: <section class="onecol habonecol"> <a href="https://longGibberishDow...
[ "I believe you are overthinking. Just remove the regular expression part, take the text and you will be fine.\nimport requests\nfrom bs4 import BeautifulSoup\n\nreqs = requests.get(url)\nsoup = BeautifulSoup(reqs.text, 'html.parser')\nresult = soup.find('section', attrs={'class':'onecol habonecol'}).text\nprint(res...
[ 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "html", "partial", "python" ]
stackoverflow_0074648666_beautifulsoup_html_partial_python.txt
Q: My code is not doing what I want it to do and I cant get it out of the while loop. Please explain why it's like that val = [*range(1,51)] print("Now, I need aaato know how many state Capitals you would like to practice") user = input("chose a number from 1 to 50") while user not in val: print("There are 50 St...
My code is not doing what I want it to do and I cant get it out of the while loop. Please explain why it's like that
val = [*range(1,51)] print("Now, I need aaato know how many state Capitals you would like to practice") user = input("chose a number from 1 to 50") while user not in val: print("There are 50 States in the United States. You need to pick a number between 1-50. If you want to exit the game, type \"EXIT\"") user ...
[ "You want user.upper(), not user.capitalize().\nFrom the help-text:\n>>> help(str.capitalize)\nHelp on method_descriptor:\n\ncapitalize(self, /)\n Return a capitalized version of the string.\n\n More specifically, make the first character have upper case and the rest lower\n case.\n\n>>> help(str.upper)\nH...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074661763_python.txt
Q: Pass whole row to DB function as an argument SQLAlchemy I need to implement following SQL expression using SQLAlchemy 1.4.41, Postgres 13.6 SELECT book.name, my_func(book) AS func_result FROM book WHERE book.name = 'The Adventures of Tom Sawyer'; Is there a way to implement such SQL expression? Function is...
Pass whole row to DB function as an argument SQLAlchemy
I need to implement following SQL expression using SQLAlchemy 1.4.41, Postgres 13.6 SELECT book.name, my_func(book) AS func_result FROM book WHERE book.name = 'The Adventures of Tom Sawyer'; Is there a way to implement such SQL expression? Function is the following and I'm not supposed to change it: create func...
[ "In PostgreSQL, you would do this by passing a row object to the function. For example, row_to_json is a function that accepts a row and returns JSON, so given this table\n Table \"public.users\"\n Column │ Type │ Collation │ Nullable │ Default ...
[ 1 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0074654755_python_sql_sqlalchemy.txt
Q: AWS Python Glue Job Not Importing Numeric Columns into RDS I have a glue job that takes a csv file from an s3 bucket and imports the data into a postgres rds table. It connects to the db with a jdbc connection. The string/varchar columns are being imported, but the numeric columns are not. Here is the postgres rds...
AWS Python Glue Job Not Importing Numeric Columns into RDS
I have a glue job that takes a csv file from an s3 bucket and imports the data into a postgres rds table. It connects to the db with a jdbc connection. The string/varchar columns are being imported, but the numeric columns are not. Here is the postgres rds column types: And here is the python glue script: def __st...
[ "Figured it out. I needed to typecast those columns to the long type first because the Dynamic frame is unsure about the data type.\ndynamicFrame_dept_summary = dynamicFrame_dept_summary.resolveChoice( specs =[('VOLUME','cast:long')]).resolveChoice( specs = [('MINUTES','cast:long')]).resolveChoice( specs = [('PLAN_...
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_glue", "postgresql", "python" ]
stackoverflow_0074659315_amazon_s3_amazon_web_services_aws_glue_postgresql_python.txt
Q: Telethon New Message Event Handler waits minute Telethon event handler waits 1 minute before sending out a burst of messages at the same time. I tried removing functions from other souces as I thought that could be it and it did not work. code: ` from telethon import TelegramClient, events import logging import ti...
Telethon New Message Event Handler waits minute
Telethon event handler waits 1 minute before sending out a burst of messages at the same time. I tried removing functions from other souces as I thought that could be it and it did not work. code: ` from telethon import TelegramClient, events import logging import time #from main import add logging.basicConfig(format='...
[ "Try uninstall and reinstall Telethon again\nI also Can't login!\n", "form me work ok and i have testet\npython need to run all time\n\n\n#exit()\nimport sys\nfrom telethon import TelegramClient, events\nimport logging\nimport time\nimport telethon.tl.functions as _fn \n\n\nlogging.basicConfig(format='[%(levelnam...
[ 0, 0 ]
[]
[]
[ "python", "telegram", "telethon" ]
stackoverflow_0074257571_python_telegram_telethon.txt
Q: Linking multiple lists with a variable I'm trying to link multiple lists with a variable. With the output being an item from one of the 'multiple' lists. The variable needs to have the name of the list. So that the index of the item in the one list is the same as the index of the item in one of the others. Sorry i...
Linking multiple lists with a variable
I'm trying to link multiple lists with a variable. With the output being an item from one of the 'multiple' lists. The variable needs to have the name of the list. So that the index of the item in the one list is the same as the index of the item in one of the others. Sorry if it's a duplicate, but I couln't find anyth...
[ "Use dictionaries and zip:\ncreatures = {'easy': ['slime', 'dog', 'chicken'],\n 'medium': ['orc', 'wolf'],\n 'hard': ['dragon', 'golem', 'vampire']}\n\nattacks = {'easy': ['spits juice', 'bites', 'pecks'],\n 'medium': ['slams', 'howls'],\n 'hard': ['breaths fire', 'throws...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074661760_python.txt
Q: What is the fastest way to check if a substring is in a string as an entire word or term, like RegEx with boundaries? I have a problem to find the fastest way to check if a substring is in a string as an entire word or term. Currently, I'm using RegEx, but I need to perform thousands of verifications and RegEx is ...
What is the fastest way to check if a substring is in a string as an entire word or term, like RegEx with boundaries?
I have a problem to find the fastest way to check if a substring is in a string as an entire word or term. Currently, I'm using RegEx, but I need to perform thousands of verifications and RegEx is being VERY slow. There are many ways to respond to this. The easier way to verify is substring in string: substring = "prog...
[ "Simply loop through the string and splice the string according to the substring length and compare the splice string with the substring if it is equal return True.\nIllustration*\nstrs = \"Coding\"\nsubstr = \"ding\"\nslen = 4\ni = 0\n\ncheck = strs[i:slen+i]==substr\n\n# 1st iteration\nstrs[0:4+0] == ding\ncodi =...
[ 1, 1, 1 ]
[]
[]
[ "contains", "python", "regex", "string", "substring" ]
stackoverflow_0074426371_contains_python_regex_string_substring.txt
Q: Problem with virtualenv in Mac OS X I've installed virtualenv via pip and get this error after creating a new environment: selenium:~ auser$ virtualenv new New python executable in new/bin/python ERROR: The executable new/bin/python is not functioning ERROR: It thinks sys.prefix is u'/System/Library/Framewo...
Problem with virtualenv in Mac OS X
I've installed virtualenv via pip and get this error after creating a new environment: selenium:~ auser$ virtualenv new New python executable in new/bin/python ERROR: The executable new/bin/python is not functioning ERROR: It thinks sys.prefix is u'/System/Library/Frameworks/Python.framework/ Versions/2.6' (s...
[ "Just in case there's someone still seeking for the answer.\nI ran into this same problem just today and realized since I already have Anaconda installed, I should not have used pip install virtualenv to install virtual environment as this would give me the error message when trying to initiate it later. Instead, I...
[ 109, 6, 5, 4, 3, 1, 1, 0, 0, 0, 0, 0, 0, -3 ]
[ "Open terminal and type /Library/Frameworks/Python.framework/Versions/\nthen type ls /Library/Frameworks/Python.framework/Versions/2.7/bin/\n if you are using Python2(or any other else).\nEdit ~/.bash_profile and add the following line:\nexport PATH=$PATH:/Library/Frameworks/Python.framework/Versions/2.7/bin/\ncat...
[ -1 ]
[ "macos", "operating_system", "python", "virtualenv" ]
stackoverflow_0005904319_macos_operating_system_python_virtualenv.txt
Q: pybind11: How to organize pybind module under a namespace package In the below example of the pybind tutorial, a dynamic library is build. setup.py in https://github.com/pybind/python_example: ext_modules = [ Pybind11Extension("python_example", ["src/main.cpp"], ... ), ] setup( ext...
pybind11: How to organize pybind module under a namespace package
In the below example of the pybind tutorial, a dynamic library is build. setup.py in https://github.com/pybind/python_example: ext_modules = [ Pybind11Extension("python_example", ["src/main.cpp"], ... ), ] setup( ext_modules=ext_modules, ... ) It can be imported like this: import p...
[ "One can add a namespace in front of the module name.\nPybind11Extension(\"mypackage.python_example\",\n [\"src/main.cpp\"],\n ...\n)\n\nBut the name in PYBIND11_MODULE should stay as it is.\nPYBIND11_MODULE(python_example, m) {\n\nThis will add a folder during the build: mypackage/python_example.cpython-38-x...
[ 0 ]
[]
[]
[ "c++", "packaging", "pybind11", "python" ]
stackoverflow_0074660906_c++_packaging_pybind11_python.txt
Q: Trying to create a sliding window that checks for repeats in a DNA sequence I'm trying to write a bioinformatics code that will check for certain repeats in a given string of nucleotides. The user inputs a certain patter, and the program outputs how many times something is repeated, or even highlights where they a...
Trying to create a sliding window that checks for repeats in a DNA sequence
I'm trying to write a bioinformatics code that will check for certain repeats in a given string of nucleotides. The user inputs a certain patter, and the program outputs how many times something is repeated, or even highlights where they are. I've gotten a good start on it, but could use some help. Below is my code so ...
[ "One possibility is to use re.findall:\nimport re\ntext = 'AGACGCCTGGGAACTGCGGCCGCGGGCTCGCGCTCCTCGCCAGGCCCTGCCGCCGGGCTGCCATCCTTGCCCTGCCATGTCTCGCCGGAAGCCTGCGTCGGGCGGCCTCGCTGCCTCCAGCTCAGCCCCTGCGAGGCAAGCGGTTTTGAGCCGATTCTTCCAGTCTACGGGAAGCCTGAAATCCACCTCCTCCTCCACAGGTGCAGCCGACCAGGTGGACCCTGGCGCTgcagcggctgcagcggccgcagcggccg...
[ 1, 0, 0 ]
[]
[]
[ "bioinformatics", "biopython", "dna_sequence", "python", "repeat" ]
stackoverflow_0074659092_bioinformatics_biopython_dna_sequence_python_repeat.txt
Q: Command not found - installing ganache-cli with yarn on Visual Studio I've installed nodeJS in the terminal of Visual Studio version : v16.13.1 Yarn 1.22.17 Ganache-cli MacBook:web3_py_simple_storage myName$ yarn global add ganache-cli warning ../package.json: No license field [1/4] Resolving packages... [2/4] ...
Command not found - installing ganache-cli with yarn on Visual Studio
I've installed nodeJS in the terminal of Visual Studio version : v16.13.1 Yarn 1.22.17 Ganache-cli MacBook:web3_py_simple_storage myName$ yarn global add ganache-cli warning ../package.json: No license field [1/4] Resolving packages... [2/4] Fetching packages... [3/4] Linking dependencies... [4/4] Building fres...
[ "I encountered the same issue earlier today, got it solved by typing this command in my visual studio terminal\nnpm install -g ganache-cli\n(Note: You must have Nodejs already installed)\nAfter the installation simply run the command below\nganache-cli --version\nto check if it was installed properly\n", "I used ...
[ 2, 0, 0 ]
[]
[]
[ "ganache", "installation", "python", "terminal", "visual_studio" ]
stackoverflow_0070599723_ganache_installation_python_terminal_visual_studio.txt
Q: I want to read this csv file with pandas and display the first 5 records but I keep getting this error I keep getting an error when i use df.head() on my dataframe I read in. When I read in my CSV file and attempt to display The first 5 records, I use these lines df=pd.read_csv('US_Accidents_Dec21.csv') df.head() ...
I want to read this csv file with pandas and display the first 5 records but I keep getting this error
I keep getting an error when i use df.head() on my dataframe I read in. When I read in my CSV file and attempt to display The first 5 records, I use these lines df=pd.read_csv('US_Accidents_Dec21.csv') df.head() But I Get the following error and I want to know how to fix it. File ~\anaconda3\lib\site-packages\IPython\...
[ "The error message gives the following exception: KeyError: ';,'.\nI suggest verifying that your CSV-file doesn't contain any errors first. Are you able to open it in e.g. Excel? If yes: are you using the correct separator and delimiter? (See the sep and delimiter parameters in the documentation)\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074661778_pandas_python.txt
Q: What is the difference between a = ListNode(-1), b = ListNode(-1) and a = b = ListNode(-1) in python In python: what's the difference between a = ListNode(-1), b = ListNode(-1) and a = b = ListNode(-1) A: In python, when you create a new instance of an object, you are creating a new object in memory. For example...
What is the difference between a = ListNode(-1), b = ListNode(-1) and a = b = ListNode(-1) in python
In python: what's the difference between a = ListNode(-1), b = ListNode(-1) and a = b = ListNode(-1)
[ "In python, when you create a new instance of an object, you are creating a new object in memory. For example:\na = ListNode(-1)\nb = ListNode(-1)\n\nIn this case, you are creating two separate ListNode objects, a and b, which are stored in different locations in memory.\nOn the other hand, when you use the assignm...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074661831_python.txt
Q: Flask server timeouts at 30 sec with gunicorn Here is the minimal example of the code. curl request curl http://127.0.0.1:5000/get_zip/my_zip.zip -o my_zip.zip should send user the file archive/my_zip.zip It works correctly without gunicorn and disconnects after 30 seconds, when the server is launched with gunico...
Flask server timeouts at 30 sec with gunicorn
Here is the minimal example of the code. curl request curl http://127.0.0.1:5000/get_zip/my_zip.zip -o my_zip.zip should send user the file archive/my_zip.zip It works correctly without gunicorn and disconnects after 30 seconds, when the server is launched with gunicorn. from os import path from flask import Flask, re...
[ "30 seconds is default timeout value for gunicorn.\nTo increase it use --timeout <seconds> parameter on your gunicorn config.\nAlso if you run gunicorn under nginx, don't forget to manage nginx's settings:\nproxy_connect_timeout <seconds>s;\nproxy_read_timeout <seconds>s;\n\nUPDATE:\nit's better and safer to send f...
[ 3 ]
[]
[]
[ "flask", "gunicorn", "python" ]
stackoverflow_0074661482_flask_gunicorn_python.txt
Q: List of quarter hours between two timestamps in python I have two timestamps in python and I need to get all quarter hours between those timestamps. Any idea how to do this? A: To get a list of all quarter hours between two timestamps in Python, you can use the dateutil.rrule module to create a dateutil.rrule.rr...
List of quarter hours between two timestamps in python
I have two timestamps in python and I need to get all quarter hours between those timestamps. Any idea how to do this?
[ "To get a list of all quarter hours between two timestamps in Python, you can use the dateutil.rrule module to create a dateutil.rrule.rrule object with the freq argument set to dateutil.rrule.MINUTELY and the interval argument set to 15 to generate a list of datetime objects separated by 15 minute intervals. You c...
[ 0 ]
[]
[]
[ "python", "timestamp" ]
stackoverflow_0074661759_python_timestamp.txt
Q: Reading the last line of an empty file on python I have this function on my code that is supposed to read a files last line, and if there is no file create one. My issue is when it creates the files and tries to read the last line it comes up as an error. with open(HIGH_SCORES_FILE_PATH, "w+") as file: las...
Reading the last line of an empty file on python
I have this function on my code that is supposed to read a files last line, and if there is no file create one. My issue is when it creates the files and tries to read the last line it comes up as an error. with open(HIGH_SCORES_FILE_PATH, "w+") as file: last_line = file.readlines()[-1] if last_line == ...
[ "Opening a file in \"w+\" erases any content in the file. readlines() returns an empty list and trying to get value results in an IndexError. You can test for a file's existence with os.path.exists or os.path.isfile, or you could use an exception handler to deal with that case.\nStart with last_line set to a sentin...
[ 1, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0074661682_file_python.txt
Q: Why is my exit statement not working properly? the goal is to move between rooms in this simplified version of a text base game. The code works exactly as planned except for if you try and input 'exit' directly after inputting 'instructions'. after inputting 'instructions' the first 'exit' get ran in the else inva...
Why is my exit statement not working properly?
the goal is to move between rooms in this simplified version of a text base game. The code works exactly as planned except for if you try and input 'exit' directly after inputting 'instructions'. after inputting 'instructions' the first 'exit' get ran in the else invalid statement then the second 'exit' input exits the...
[ "After your line\nmove = input('\\nWhat will you do next?\\n>').split() # next move input\n\nYou should jump back to the beginning of the loop, using continue.\n", "while True:\n if len(move) < 2: # for one word inputs\n # handle the input in various ways\n move = input('\\nWhat will you do nex...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074661877_python.txt
Q: How to combine streams in anyio? How to iterate over multiple steams at once in anyio, interleaving the items as they appear? Let's say, I want a simple equivalent of annotate-output. The simplest I could make is #!/usr/bin/env python3 import dataclasses from collections.abc import Sequence from typing import Typ...
How to combine streams in anyio?
How to iterate over multiple steams at once in anyio, interleaving the items as they appear? Let's say, I want a simple equivalent of annotate-output. The simplest I could make is #!/usr/bin/env python3 import dataclasses from collections.abc import Sequence from typing import TypeVar import anyio import anyio.abc im...
[ "This should be more safe and idiomatic.\nclass CtxObj:\n \"\"\"\n Add an async context manager that calls `_ctx` to run the context.\n\n Usage::\n class Foo(CtxObj):\n @asynccontextmanager\n async def _ctx(self):\n yield self # or whatever\n\n async with ...
[ 1 ]
[]
[]
[ "anyio", "python", "python_trio" ]
stackoverflow_0074661106_anyio_python_python_trio.txt
Q: Tell pylint that a given decorator is a classmethod How can I modify my pylintrc so that a given decorator is interpreted as a classmethod. pydantic defines a validator decorator to allow for attribute validation of model classes and operates as a class method. pylint throws a E0213: Method 'has_risk_assigned' sh...
Tell pylint that a given decorator is a classmethod
How can I modify my pylintrc so that a given decorator is interpreted as a classmethod. pydantic defines a validator decorator to allow for attribute validation of model classes and operates as a class method. pylint throws a E0213: Method 'has_risk_assigned' should have "self" as first argument (no-self-argument) fo...
[ "To configure pylint to interpret a decorator as defining a class method, you can add the following to your pylintrc file:\n[TYPECHECK]\nignored-decorators=validator\n\nThis will tell pylint to ignore the validator decorator when checking for the first argument of a method. Note that this will not affect other chec...
[ 1 ]
[]
[]
[ "class_method", "pylint", "pylintrc", "python" ]
stackoverflow_0074661891_class_method_pylint_pylintrc_python.txt
Q: PermissionError: [Errno 13] Permission denied when trying to play mp3 with python I'm trying to play an mp3 with pydub, and I keep getting the error File "c:\Users\ryanc\Desktop\codefiles\python\audio player.py", line 5, in <module> play(song) File "C:\Users\ryanc\AppData\Local\Programs\Python\Python39\lib...
PermissionError: [Errno 13] Permission denied when trying to play mp3 with python
I'm trying to play an mp3 with pydub, and I keep getting the error File "c:\Users\ryanc\Desktop\codefiles\python\audio player.py", line 5, in <module> play(song) File "C:\Users\ryanc\AppData\Local\Programs\Python\Python39\lib\site-packages\pydub\playback.py", line 71, in play _play_with_ffplay(audio_segment...
[ "So it seems that 'pydub' library by default is not able to play .mp3 songs. You will neeed to convert it into .wav format and then execute the command again.\nSo here is your code with some minor modifications:\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\nsong = AudioSegment.from_mp3(\"C:\\\...
[ 1, 0, 0, 0 ]
[]
[]
[ "pydub", "python" ]
stackoverflow_0069323707_pydub_python.txt
Q: Why doesn't the abort function in Flask take the handlers? I am developing a REST API with python and flask, I leave the project here Github project I added error handlers to the application but when I run an abort function, it gives me a default message from Flask, not the structure I am defining. I will leave th...
Why doesn't the abort function in Flask take the handlers?
I am developing a REST API with python and flask, I leave the project here Github project I added error handlers to the application but when I run an abort function, it gives me a default message from Flask, not the structure I am defining. I will leave the path to the handlers and where I run the abort from. Handlers ...
[ "Ok, the solution was told to me that it could be in another question.\nWhat to do is to overwrite the handler function of the Flask Api object.\nWith that, you can configure the format with which each query will be answered, even the ones that contain an error.\ndef response_structure(code_status: int, response=No...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074650833_flask_python.txt
Q: C# and Python result difference - basic Math So I have tried the same math in c# and python but got 2 different answer. can someone please explain why is this happening. def test(): l = 50 r = 3 gg= l + (r - l) / 2 mid = l + (r - l) // 2 print(mid) print(gg) public void test() { var l = 50; va...
C# and Python result difference - basic Math
So I have tried the same math in c# and python but got 2 different answer. can someone please explain why is this happening. def test(): l = 50 r = 3 gg= l + (r - l) / 2 mid = l + (r - l) // 2 print(mid) print(gg) public void test() { var l = 50; var r = 3; var gg = l + (r - l) / 2; ...
[ "In C#, the / operator performs integer division (ignores the fractional part) when both values are type int. For example, 3 / 2 = 1, since the fractional part (0.5) is dropped.\nAs a result, in your equation, the operation (r - l) / 2 is evaluating to -23, since (3 - 50) / 2 = -47 / 2 = -23 (again, the fractional ...
[ 0 ]
[]
[]
[ "c#", "floor_division", "math", "python" ]
stackoverflow_0074501942_c#_floor_division_math_python.txt
Q: Insert rows in Python dataframe with conditions I have a large data file as shown below. I wanted to add two new columns (E and F) next to column D and move the suite # when applicable and City/State data in cell D3 and D4 to E2 and F2, respectively. The challenge is not every entry has the suite number. I would ...
Insert rows in Python dataframe with conditions
I have a large data file as shown below. I wanted to add two new columns (E and F) next to column D and move the suite # when applicable and City/State data in cell D3 and D4 to E2 and F2, respectively. The challenge is not every entry has the suite number. I would need to insert a row first for those entries that don...
[ "This is how I would do it. I don't recommend looping when using pandas. There are a lot of tools that it is often not needed. Some caution on this. Your spreadsheet has NaN and I think that is actually numpy np.nan equivalent. You also have blanks I am thinking that it is a \"\" equivalent.\n# dictionary of your ...
[ 0 ]
[]
[]
[ "conditional_statements", "dataframe", "insert", "pandas", "python" ]
stackoverflow_0074661308_conditional_statements_dataframe_insert_pandas_python.txt
Q: Toggle Boolean value based on a triple state filter I'm having a brain melting time with this. For some reason I thought it would be easier, but I'm struggling with this. I have an application that a user can config before running based on desired parameters the user wants to test. There are 3 filters that the use...
Toggle Boolean value based on a triple state filter
I'm having a brain melting time with this. For some reason I thought it would be easier, but I'm struggling with this. I have an application that a user can config before running based on desired parameters the user wants to test. There are 3 filters that the user can either turn on, turn off, or toggle. If the user wa...
[ "This gives the same output with less complication. itertools.product is a function that gives you all the combinations of each state listed. A TOGGLE filter can be zero or one, while a FALSE or TRUE state only provides a zero or one state, respectively.\nDoes this manage the states you want?\nimport itertools\n\...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074661476_python.txt
Q: Remove Columns with missing values above a threshold pandas I am doing data preprocessing and want to remove features/columns which have more than say 10% missing values. I have made the below code: df_missing=df.isna() result=df_missing.sum()/len(df) result Default 0.010066 Income 0.142857 A...
Remove Columns with missing values above a threshold pandas
I am doing data preprocessing and want to remove features/columns which have more than say 10% missing values. I have made the below code: df_missing=df.isna() result=df_missing.sum()/len(df) result Default 0.010066 Income 0.142857 Age 0.109090 Name 0.047000 Gender ...
[ "Because division of sum by length is mean, you can instead df_missing.sum()/len(df) use df_missing.mean():\nresult = df.isna().mean()\n\nThen filter by DataFrame.loc with : for all rows and columns by mask:\ndf = df.loc[:,result > .1]\n\n", "it should be df = df.loc[:,result < .1] as the user only want to keep t...
[ 4, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0060450808_pandas_python.txt
Q: How to generate a list with every monday, between two dates, and exclude that some a specific list using pandas I want to generate a dataframe with pandas where one of the columns is filled with all mondays between to dates. But I need to exclude some mondays that are in a specific list. I could generate the colum...
How to generate a list with every monday, between two dates, and exclude that some a specific list using pandas
I want to generate a dataframe with pandas where one of the columns is filled with all mondays between to dates. But I need to exclude some mondays that are in a specific list. I could generate the column with the mondays, but I could find how to remove that mondays in the given list. I generate the mondays using: impo...
[ "IIUC, you can use a negative pandas.Index.isin :\na1= a1[~a1.isin(fer)]\n\n# Output :\nprint(a1)\n​\nDatetimeIndex(['2022-08-22', '2022-08-29', '2022-09-05', '2022-09-12',\n '2022-09-19', '2022-09-26', '2022-10-03', '2022-10-10',\n '2022-10-17', '2022-10-24', '2022-10-31', '2022-11-07',...
[ 1, 1 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074661985_datetime_pandas_python.txt
Q: flask template not rendering as expected Expected output is 'not detected' but I get 'no error' on get and post. Why? index.html {% if error %} <p>{{ error }}</p> {% else %} <p>no error</p> {% endif %} main.py @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'GET': pr...
flask template not rendering as expected
Expected output is 'not detected' but I get 'no error' on get and post. Why? index.html {% if error %} <p>{{ error }}</p> {% else %} <p>no error</p> {% endif %} main.py @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'GET': print('get') return render_template('ind...
[ "The problem is with your js code. As I can see, you make fetch call providing parameters and not providing callback for response processing.\nIt should be:\nfetch(`${window.origin}/`, {\n method: 'POST',\n headers: {'content-type': 'application/json'},\n body: JSON.stringify({\n 'message': false\n }...
[ 1, 0 ]
[]
[]
[ "flask", "post", "python" ]
stackoverflow_0074651348_flask_post_python.txt
Q: Replace value at i in Dictionary I am trying to loop through a dictionary and if it meets a requirement, the requirements being distinction >=70, merit>=60, pass>=50, and fail less than 50 then the value that is currently being passed through the loop will be replaced by the correct classification. For example, th...
Replace value at i in Dictionary
I am trying to loop through a dictionary and if it meets a requirement, the requirements being distinction >=70, merit>=60, pass>=50, and fail less than 50 then the value that is currently being passed through the loop will be replaced by the correct classification. For example, the first value being passed through is ...
[ "The problem is that you're trying to access a field in a dictionary by its value. You are also trying to return a new dictionary, but you are changing the original dictionary. You should create a separate dictionary and use dict.items() instead. Like this:\ndef classifyMarks(marks):\n result = {}\n for (subj...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074662028_python_python_3.x.txt
Q: Selenium cannot scrape all elements with same xpath, don't know if the page is not fully loaded? I am trying to scrape this page the title and the price, https://magnumbikes.com/collections/e-bikes?sort_by=best-selling, but only half of the products can be collected (it stops at product Metro X), not sure if it is...
Selenium cannot scrape all elements with same xpath, don't know if the page is not fully loaded?
I am trying to scrape this page the title and the price, https://magnumbikes.com/collections/e-bikes?sort_by=best-selling, but only half of the products can be collected (it stops at product Metro X), not sure if it is the page is not fully loaded, Please let me know or correct me thank you! Here is my code: URL='https...
[ "Here is a way to get that information using Requests:\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074660079_python_selenium_selenium_webdriver_web_scraping.txt
Q: Spotify API (Obtaining Authorization Code) using Python My goal is to connect to the Spotify API using pure Python and I have been able to figure out how to obtain the authorization token given the authorization code but I am unable to get the authorization code itself. Note: I have not provided the client_id and ...
Spotify API (Obtaining Authorization Code) using Python
My goal is to connect to the Spotify API using pure Python and I have been able to figure out how to obtain the authorization token given the authorization code but I am unable to get the authorization code itself. Note: I have not provided the client_id and client_secret for obvious reasons and you can assume that all...
[ "You'll need to extract the code from your callback URL. If authentication is successful, Spotify will make a request to your redirect_uri with the code in the query (e.g http://localhost:7777/callback?code=...).\nThe easiest way to do that is probably spin up a Flask server (or equivalent) with a GET callback endp...
[ 1 ]
[]
[]
[ "authorization", "python", "spotify" ]
stackoverflow_0074661575_authorization_python_spotify.txt
Q: Python: Sum up list of objects I am working with a number of custom classes X that have __add__(self), and when added together return another class, Y. I often have iterables [of various sizes] of X, ex = [X1, X2, X3] that I would love to add together to get Y. However, sum(ex) throws an int error, because sum ...
Python: Sum up list of objects
I am working with a number of custom classes X that have __add__(self), and when added together return another class, Y. I often have iterables [of various sizes] of X, ex = [X1, X2, X3] that I would love to add together to get Y. However, sum(ex) throws an int error, because sum starts at 0 which can't be added to ...
[ "You can specify the starting point for a sum by passing it as a parameter. For example, sum([1,2,3], 10) produces 16 (10 + 1 + 2 + 3), and sum([[1], [2], [3]], []) produces [1,2,3].\nSo if you pass an appropriate (\"zero-like\") X object as the second parameter to your sum, ie sum([x1, x2, x3,...], x0) you should ...
[ 4 ]
[ "Assuming that you can add an X to a Y (i.e. __add__ is defined for Y and accepts an object of class X), then you can use\nreduce from functools, a generic way to apply an operation to a number of objects, either with or without a start value.\nfrom functools import reduce\n\nxes = [x1, x2, x3]\ny = reduce(lambda a...
[ -1, -1 ]
[ "python" ]
stackoverflow_0074661819_python.txt
Q: why does numpy matrix multiply computation time increase by an order of magnitude at 100x100? When computing A @ a where A is a random N by N matrix and a is a vector with N random elements using numpy the computation time jumps by an order of magnitude at N=100. Is there any particular reason for this? As a compa...
why does numpy matrix multiply computation time increase by an order of magnitude at 100x100?
When computing A @ a where A is a random N by N matrix and a is a vector with N random elements using numpy the computation time jumps by an order of magnitude at N=100. Is there any particular reason for this? As a comparison the same operation using torch on the cpu has a more gradual increase Tried it with python3.1...
[ "numpy tries to use threads when multiplying matricies of size 100 or larger, and the default CBLAS implementation of threaded multiplication is ... sub optimal, as opposed to other backends like intel-MKL or ATLAS.\nif you force it to use only 1 thread using the answers in this post you will get a continuous line ...
[ 7 ]
[]
[]
[ "linear_algebra", "numerical_computing", "numpy", "python" ]
stackoverflow_0074661959_linear_algebra_numerical_computing_numpy_python.txt
Q: 'jt' is not recognized as an internal or external command Trying to change theme of Jupyter notebook but running into difficulty after successful install. I run: jt-t chesterish 'jt' is not recognized as an internal or external command, operable program or batch file. I know its related to not setting the env...
'jt' is not recognized as an internal or external command
Trying to change theme of Jupyter notebook but running into difficulty after successful install. I run: jt-t chesterish 'jt' is not recognized as an internal or external command, operable program or batch file. I know its related to not setting the environmental path somehow. But I have tried using SETX PATH but s...
[ "Even if ı have installed the jupyterthemes and upgrade it, ı have the same issue when ı write down the command (!jt -t [themename]) into one of the jupyter notebook's cells. The solution that ı have found is open up the Anaconda prompt and after installing the jupyterthemes, write the command (jt -t exampletheme) ...
[ 1, 0 ]
[]
[]
[ "jupyter", "path", "python" ]
stackoverflow_0054411892_jupyter_path_python.txt
Q: Place a Window behind desktop icons using PyQt on Ubuntu/GNOME I'm trying to develop a simple cross-platform Wallpaper manager, but I am not able to find any method to place my PyQt Window between the current wallpaper and the desktop icons using XLib (on windows and macOS it's way easier and works perfectly). Thi...
Place a Window behind desktop icons using PyQt on Ubuntu/GNOME
I'm trying to develop a simple cross-platform Wallpaper manager, but I am not able to find any method to place my PyQt Window between the current wallpaper and the desktop icons using XLib (on windows and macOS it's way easier and works perfectly). This works right on Cinnamon (with a little workround just simulating a...
[ "Eureka!!! Last Ubuntu version (22.04) seems to have brought the solution by itself. It now has a \"layer\" for desktop icons you can interact with. This also gave me the clue to find a smarter solution on Mint/Cinnamon (testing in other OS is still pending). This is the code which seems to work OK, for those with ...
[ 1 ]
[]
[]
[ "gnome", "pyqt5", "python", "ubuntu", "xlib" ]
stackoverflow_0071241339_gnome_pyqt5_python_ubuntu_xlib.txt
Q: Plotting two variable in the same bar plot I have a dataset having gdp of countries and their biofuel production named "Merging2". I am trying to plot a bar chart of top 5 countries in gdp and in the same plot have the bar chart of their biofuel_production. I plotted the top gdp's using : yr=Merging2.groupby(by='Y...
Plotting two variable in the same bar plot
I have a dataset having gdp of countries and their biofuel production named "Merging2". I am trying to plot a bar chart of top 5 countries in gdp and in the same plot have the bar chart of their biofuel_production. I plotted the top gdp's using : yr=Merging2.groupby(by='Years') access1=yr.get_group(2019) sorted=access1...
[ "Do you want two subplots, or do you want both bars next to each other? Either way, check out this other thread which should give you the answer to both. In the second case, you would want a secondary Y-axis (as illustrated in the post)\n" ]
[ 0 ]
[]
[]
[ "data_cleaning", "data_science", "pandas", "python" ]
stackoverflow_0074662109_data_cleaning_data_science_pandas_python.txt
Q: How to make input text bold in console? I'm looking for a way to make the text that the user types in the console bold input("Input your name: ") If I type "John", I want it to show up as bold as I'm typing it, something like this Input your name: John A: They are called ANSI escape sequence. Basically you out...
How to make input text bold in console?
I'm looking for a way to make the text that the user types in the console bold input("Input your name: ") If I type "John", I want it to show up as bold as I'm typing it, something like this Input your name: John
[ "They are called ANSI escape sequence. Basically you output some special bytes to control how the terminal text looks. Try this:\nx = input('Name: \\u001b[1m') # anything from here on will be BOLD\n\nprint('\\u001b[0m', end='') # anything from here on will be normal\nprint('Your input is:', x)\n\n\\u001b[1m tells...
[ 4, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0059122173_python_python_3.x.txt
Q: TS SS Vector similarity using matrices I have two sets of vectors A,B and I want to compute the TS-SS similarity for each vector in A compared to every vector in B. I have an implementation (from https://github.com/taki0112/Vector_Similarity) used for 2 vectors, however when I tried using it for matrices (function...
TS SS Vector similarity using matrices
I have two sets of vectors A,B and I want to compute the TS-SS similarity for each vector in A compared to every vector in B. I have an implementation (from https://github.com/taki0112/Vector_Similarity) used for 2 vectors, however when I tried using it for matrices (function "compute_matrix_sim") - it is very ineffici...
[ "import numpy as np\nimport torch\n\n\nclass TS_SS:\n def __init__(self):\n self.thetaval = 0\n self.vecnorm1 = 0\n self.vecnorm2 = 0\n\n def Theta(self, vec1, vec2):\n return (torch.arccos(torch.mm(vec1,vec2.T)/(self.vecnorm1*self.vecnorm2.T))\n + np.radians(10))\n\...
[ 0 ]
[]
[]
[ "cosine_similarity", "nlp", "python", "similarity", "vectorization" ]
stackoverflow_0068338024_cosine_similarity_nlp_python_similarity_vectorization.txt
Q: Why doesn't this conversion to utf8 work? I have a subprocess command that outputs some characters such as '\xf1'. I'm trying to decode it as utf8 but I get an error. s = '\xf1' s.decode('utf-8') The above throws: UnicodeDecodeError: 'utf8' codec can't decode byte 0xf1 in position 0: unexpected end of data It wo...
Why doesn't this conversion to utf8 work?
I have a subprocess command that outputs some characters such as '\xf1'. I'm trying to decode it as utf8 but I get an error. s = '\xf1' s.decode('utf-8') The above throws: UnicodeDecodeError: 'utf8' codec can't decode byte 0xf1 in position 0: unexpected end of data It works when I use 'latin-1' but shouldn't utf8 wor...
[ "You have confused Unicode with UTF-8. Latin-1 is a subset of Unicode, but it is not a subset of UTF-8. Avoid like the plague ever thinking about individual code units. Just use code points. Do not think about UTF-8. Think about Unicode instead. This is where you are being confused.\nSource Code for Demo Pro...
[ 9, 4, 1, 1, 0 ]
[]
[]
[ "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0007163485_encoding_python_unicode_utf_8.txt
Q: Implementing the Fibonacci sequence for the last n elements: The nBonacci sequence I was curious about how I can implement the Fibonacci sequence for summing the last n elements instead of just the last 2. So I was thinking about implementing a function nBonacci(n,m) where n is the number of last elements we gotta...
Implementing the Fibonacci sequence for the last n elements: The nBonacci sequence
I was curious about how I can implement the Fibonacci sequence for summing the last n elements instead of just the last 2. So I was thinking about implementing a function nBonacci(n,m) where n is the number of last elements we gotta sum, and m is the number of elements in this list. The Fibonacci sequence starts with 2...
[ "The nBonacci sequence will always have to start with n ones, or the sequence could never start. Therefore, we can just take advantage of the range() function and slice the existing list:\ndef nfib(n, m):\n lst = [1] * n\n for i in range(n, m):\n lst.append(sum(lst[i-n:i]))\n return lst\n\n\nprint(n...
[ 1, 1 ]
[]
[]
[ "fibonacci", "iteration", "python" ]
stackoverflow_0074662150_fibonacci_iteration_python.txt
Q: "input expected at most 1 arguments, got 2" I'm trying to create a function that will prompt the user to give a radius for each circle that they have designated as having, however, I can't seem to figure out how to display it without running into the TypeError: input expected at most 1 arguments, got 2 def GetRadi...
"input expected at most 1 arguments, got 2"
I'm trying to create a function that will prompt the user to give a radius for each circle that they have designated as having, however, I can't seem to figure out how to display it without running into the TypeError: input expected at most 1 arguments, got 2 def GetRadius(): NUM_CIRCLES = eval(input("Enter the num...
[ "That's because you gave it a second argument. You can only give it the string you want to see displayed. This isn't a free-form print statement. Try this:\nRadius = eval(input(\"Enter the radius of circle #\" + str(i + 1)))\n\nThis gives you a single string value to send to input.\nAlso, be very careful with us...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0043243627_python_python_3.x.txt
Q: How to classify unknown/unseen data as anomaly I trained a CNN model with 6 different classes (labels are 0-5) and I am getting more than 90% accuracy out of it. It can correctly classify the classes. I am actually trying to detect anomaly with it. So what I want is, if any data comes which my model has never seen...
How to classify unknown/unseen data as anomaly
I trained a CNN model with 6 different classes (labels are 0-5) and I am getting more than 90% accuracy out of it. It can correctly classify the classes. I am actually trying to detect anomaly with it. So what I want is, if any data comes which my model has never seen before or never been trained on similar data then i...
[ "Interesting problem but I think your method does not work.\nWhen your model's entropy is high, i.e. it is unsure which class to choose for that particular sample input, it does not necessarily mean that that sample is an anomaly, it just means that the model is perhaps struggling to select the correct normal class...
[ 2 ]
[]
[]
[ "anomaly_detection", "conv_neural_network", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074662022_anomaly_detection_conv_neural_network_machine_learning_python_tensorflow.txt
Q: Unable to import nonsense from Nostril I am trying to import nonsense from Nostril ( from nostril import nonsense) but I get this error; ImportError Traceback (most recent call last) Cell In [12], line 1 ----> 1 from nostril import nonsense ImportError: cannot import name 'nonsense' ...
Unable to import nonsense from Nostril
I am trying to import nonsense from Nostril ( from nostril import nonsense) but I get this error; ImportError Traceback (most recent call last) Cell In [12], line 1 ----> 1 from nostril import nonsense ImportError: cannot import name 'nonsense' from 'nostril' (c:\Users\GithuaG\AppData\Loc...
[ "You most probably did pip install nostril before you installed the actual nostril package that you needed (just like I did). This would have caused another package that is used for testing to be installed alongside. You can either uninstall both nostril packages and then re-install just the nostril package you nee...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074386232_python.txt
Q: Python TkInter: How can I get the canvas coordinates of the visible area of a scrollable canvas? I need to find out what the visible coordinates of a vertically scrollable canvas are using python and tkinter. Let's assume I have a canvas that is 800 x 5000 pixels, and the visible, vertically scrollable window is 8...
Python TkInter: How can I get the canvas coordinates of the visible area of a scrollable canvas?
I need to find out what the visible coordinates of a vertically scrollable canvas are using python and tkinter. Let's assume I have a canvas that is 800 x 5000 pixels, and the visible, vertically scrollable window is 800x800. If I am scrolled all the way to the top of the canvas, I would like to have a function that, w...
[ "The methods canvasx and canvasy of the Canvas widget will convert screen pixels (ie: what's visible on the screen) into canvas pixels (the location in the larger virtual canvas).\nYou can feed it an x or y of zero to get the virtual pixel at the top-left of the visible window, and you can give it the width and hei...
[ 1 ]
[]
[]
[ "canvas", "python", "scroll", "tkinter", "visible" ]
stackoverflow_0074661864_canvas_python_scroll_tkinter_visible.txt
Q: Recursively iterate trough Pydantic Model Lets say I have a model and I want to do some preprocessing on it. (for this problem it does not matter it this is pydantic model, or some kid of nested iterable, its a general question). def preprocess(string): # Accepts some preprocessing and returnes that string cl...
Recursively iterate trough Pydantic Model
Lets say I have a model and I want to do some preprocessing on it. (for this problem it does not matter it this is pydantic model, or some kid of nested iterable, its a general question). def preprocess(string): # Accepts some preprocessing and returnes that string class OtherModel(BaseModel): other_id:int s...
[ "If you are actually dealing with Pydantic models, I would argue this is one of the use cases for validators.\nThere is not really any need for recursion because you can just define the validator on your own base model, if you want it to apply to all models (that inherit from it):\nfrom pydantic import BaseModel as...
[ 2 ]
[]
[]
[ "pydantic", "python", "python_3.x", "recursion" ]
stackoverflow_0074657576_pydantic_python_python_3.x_recursion.txt
Q: Twisted sending files. python I'm trying to transfer images and other files over the network using Twisted. I use for this the class "FileSender" and in particular the method "beginFileTransfer", which I use on the server. But the file is not fully received by the client and I can't open it. At the same time, if I...
Twisted sending files. python
I'm trying to transfer images and other files over the network using Twisted. I use for this the class "FileSender" and in particular the method "beginFileTransfer", which I use on the server. But the file is not fully received by the client and I can't open it. At the same time, if I send a small file it comes. So the...
[ "Twisted uses non-blocking socket operations: data written to or read from sockets are just enough to not block. Filesender in effect sends chunks of data until all are sent and you need to buffer them until they are complete.\nI would write the server part as:\nclass TestServer(Protocol):\n \n def connection...
[ 0 ]
[]
[]
[ "networking", "python", "twisted" ]
stackoverflow_0073391864_networking_python_twisted.txt
Q: Python's range() analog in Common Lisp How to create a list of consecutive numbers in Common Lisp? In other words, what is the equivalent of Python's range function in Common Lisp? In Python range(2, 10, 2) returns [2, 4, 6, 8], with first and last arguments being optional. I couldn't find the idiomatic way to cr...
Python's range() analog in Common Lisp
How to create a list of consecutive numbers in Common Lisp? In other words, what is the equivalent of Python's range function in Common Lisp? In Python range(2, 10, 2) returns [2, 4, 6, 8], with first and last arguments being optional. I couldn't find the idiomatic way to create a sequence of numbers, though Emacs Lis...
[ "There is no built-in way of generating a sequence of numbers, the canonical way of doing so is to do one of:\n\nUse loop\nWrite a utility function that uses loop\n\nAn example implementation would be (this only accepts counting \"from low\" to \"high\"):\n(defun range (max &key (min 0) (step 1))\n (loop for n fr...
[ 41, 19, 6, 4, 2, 1, 1, 0, 0, 0 ]
[ "Recursive solution:\n(defun range(min max &optional (step 1))\n (if (> min max)\n ()\n (cons min (range (+ min step) max step))))\n\nExample:\n(range 1 10 3)\n(1 4 7 10)\n\n" ]
[ -1 ]
[ "common_lisp", "number_sequence", "python" ]
stackoverflow_0013937520_common_lisp_number_sequence_python.txt
Q: Get maximum rows from all subgroups with groupby method (Python) I have this data frame, inside of it I have 3 columns 'Region', 'State or Province', 'Sales' I already grouped by Regions and State or Province and wanted to get values in sales. But I want to get maximum State from every Region!how can I get that? s...
Get maximum rows from all subgroups with groupby method (Python)
I have this data frame, inside of it I have 3 columns 'Region', 'State or Province', 'Sales' I already grouped by Regions and State or Province and wanted to get values in sales. But I want to get maximum State from every Region!how can I get that? sales_by_state = df_n.groupby(['Region', 'State or Province'])['Sales']...
[ "To get the maximum value of sales for each region, you can use the 'idxmax()' function on the groupby object. This will return the index of the maximum value for each group, which you can then use to index into the original data frame to get the corresponding rows.\nHere is an example:\n# Get the maximum sales for...
[ 1 ]
[]
[]
[ "dataframe", "group_by", "max", "pandas", "python" ]
stackoverflow_0074662271_dataframe_group_by_max_pandas_python.txt
Q: Python can't locate .so shared library with ctypes.CDLL - Windows I am trying to run a C function in Python. I followed examples online, and compiled the C source file into a .so shared library, and tried to pass it into the ctypes CDLL() initializer function. import ctypes cFile = ctypes.CDLL("libchess.so") At t...
Python can't locate .so shared library with ctypes.CDLL - Windows
I am trying to run a C function in Python. I followed examples online, and compiled the C source file into a .so shared library, and tried to pass it into the ctypes CDLL() initializer function. import ctypes cFile = ctypes.CDLL("libchess.so") At this point python crashes with the message: Could not find module 'C:\Us...
[ "Solved:\nDetailed explanation here: https://stackoverflow.com/a/64472088/16044321\nThe issue is specific to how Python performs a DLL/SO search on Windows. While the ctypes docs do not specify this, the CDLL() function requires the optional argument winmode=0 to work correctly on Windows when loading a .dll or .so...
[ 0 ]
[]
[]
[ "ctypes", "python", "shared_libraries" ]
stackoverflow_0074655061_ctypes_python_shared_libraries.txt
Q: Overlapping Text in Animation in Python I'm making Terror Attacks analysis using Python. And I wanted make an animation. I made it but I have a problem the text above the animation overlaps in every frame. How can I fix it? fig = plt.figure(figsize = (7,4)) def animate(Year): ax = plt.axes() ax.clear() ...
Overlapping Text in Animation in Python
I'm making Terror Attacks analysis using Python. And I wanted make an animation. I made it but I have a problem the text above the animation overlaps in every frame. How can I fix it? fig = plt.figure(figsize = (7,4)) def animate(Year): ax = plt.axes() ax.clear() ax.set_title('Terrorism In Turkey\n'+ str(Ye...
[ "@JohanC's Answer:\nDid you consider creating the axes the usual way, as in fig, ax = plt.subplots(figsize = (7,4)) (in the main code, not inside the animate function)? And leaving out the call to plt.axes()?\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "matplotlib_basemap", "python" ]
stackoverflow_0074640564_matplotlib_matplotlib_basemap_python.txt
Q: Sample python code provided by GCP - service variable undefined The following sample code is provided by GCP to use the restAPI to list out group membership when you provide the group_id. Code sample can be found here. I can run the sample directly from the URI given, but when trying to run it from Python with t...
Sample python code provided by GCP - service variable undefined
The following sample code is provided by GCP to use the restAPI to list out group membership when you provide the group_id. Code sample can be found here. I can run the sample directly from the URI given, but when trying to run it from Python with the sample code provided. My IDE intellisense says that service in th...
[ "Ok, it appears what is missing from the code samples provided by GCP are the steps to build and use a service object.\nDocumentation on that can be found here: https://github.com/googleapis/google-api-python-client/blob/main/docs/start.md#building-and-calling-a-service\nSo for my sample above the last line would a...
[ 1 ]
[]
[]
[ "gcloud", "google_cloud_platform", "google_iam", "python" ]
stackoverflow_0074662133_gcloud_google_cloud_platform_google_iam_python.txt
Q: Opening and Reading files in Python For some reason I am unable to open my .txt file within python. I have the .py and .txt file within a folder. Both files are stored Workspace -> Folder(Crash Course) -> Folder(Lessons) -> Folder(Ch 10)-> both files within this Ch 10 Folder. I am getting FileNotFoundError: [Err...
Opening and Reading files in Python
For some reason I am unable to open my .txt file within python. I have the .py and .txt file within a folder. Both files are stored Workspace -> Folder(Crash Course) -> Folder(Lessons) -> Folder(Ch 10)-> both files within this Ch 10 Folder. I am getting FileNotFoundError: [Errno 2] No such file or directory: 'pi_digi...
[ "This is less for the person that asked the question but more for people like myself that come here from Python Crash Course with the same question and don't get the answer they were looking for:\nIf, like me, you were running the code from your text editor (in my case VS Code), it's possible that the terminal wind...
[ 2, 2, 0, 0, 0 ]
[ "You might have to enable \"Execute in file dir\"\nvscode setting\n", "The comment that Travis1797 posted is much better for VS code users that are just starting out with learning python.\nClick on the cog icon in the bottom left hand of corner of vscode\nThen click settings.\nThen type: execute in file dir\n(WAR...
[ -1, -1 ]
[ "python" ]
stackoverflow_0055695410_python.txt
Q: Exception has occurred: NoSuchElementException Message: no such element: Unable to locate element: I'm trying to make a script in python that fills out the form on this website: (https://freesim.vodafone.co.uk/check-out-payasyougo-campaign) multiple times. However, I get this error when running the program : Excep...
Exception has occurred: NoSuchElementException Message: no such element: Unable to locate element:
I'm trying to make a script in python that fills out the form on this website: (https://freesim.vodafone.co.uk/check-out-payasyougo-campaign) multiple times. However, I get this error when running the program : Exception has occurred: NoSuchElementException Message: no such element: Unable to locate element: from selen...
[ "It looks like you're using the webdriver.Chrome() syntax to create a new instance of the Chrome web driver, but this is incorrect. Instead, you need to use the webdriver.Chrome(ChromeDriverManager().install()) syntax to create a new instance of the Chrome web driver and automatically download and install the appro...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074662400_python.txt
Q: Using user input function in Classes I am making a simple game with multiple players, which each player can insert their first name, last name and each player is assigned 100 poins at the begging. In my code once I am done with coding the "essential" information, but when it comes to user input it does not work. T...
Using user input function in Classes
I am making a simple game with multiple players, which each player can insert their first name, last name and each player is assigned 100 poins at the begging. In my code once I am done with coding the "essential" information, but when it comes to user input it does not work. The "base" for the player class: (this par...
[ "Your function to build a new instance from user input should be a classmethod or a staticmethod, since you want to call it to create a new instance.\nI'd also suggest using @dataclass so you don't need to copy and paste all the variable names in __init__, and using an f-string in your full_info function so you don...
[ 2, 0 ]
[]
[]
[ "input", "object", "oop", "python" ]
stackoverflow_0074662334_input_object_oop_python.txt
Q: Find new blobs comparing two different binary images I have two images taken on same sample at t=0 and t=t. There are few new blobs present in image taken at t. I need to find these new blobs (new blobs are the blobs which are present in new XY location at t=t). I am wondering if someone can help? I tried OR,AND,X...
Find new blobs comparing two different binary images
I have two images taken on same sample at t=0 and t=t. There are few new blobs present in image taken at t. I need to find these new blobs (new blobs are the blobs which are present in new XY location at t=t). I am wondering if someone can help? I tried OR,AND,XOR, reconstructions but the issue is the blobs which are s...
[ "Instead of using OR,AND,XOR, we may sum the two images.\nBefore summing the images, replace the 255 values with 100 (keeping the range of uint8 [0, 255]).\nIn the summed image, there are going to be three values:\n\n0 - Background\n100 - Non-overlapping area\n200 - Overlapping area\n\nWe may assume that pixels wit...
[ 3 ]
[]
[]
[ "computer_vision", "matlab", "object_tracking", "opencv", "python" ]
stackoverflow_0074657074_computer_vision_matlab_object_tracking_opencv_python.txt
Q: How to count number of occurrences per day over a large data set? I have a dataset that looks something like this but much larger, over 1000 unique products: | Hour | Date || Pallet ID| PRODUCT || Move Type| | -------- | -------- || -------- | -------- || -------- | | 1 PM | 10/01 || 101 | Sho...
How to count number of occurrences per day over a large data set?
I have a dataset that looks something like this but much larger, over 1000 unique products: | Hour | Date || Pallet ID| PRODUCT || Move Type| | -------- | -------- || -------- | -------- || -------- | | 1 PM | 10/01 || 101 | Shoes || Storage | | 1 PM | 10/01 || 202 | Pants || Loa...
[ "You should be able to use df.groupby() with .size() to get the counts for moves of the same date/time/pallet id/product/move type.\ndf.groupby(['Hour','Date','PALLET_ID','PROD_CODE','CASE_QTY','Move Type']).size().reset_index(name='Total Moves')\n\nSource: Get statistics for each group (such as count, mean, etc) u...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074662368_python.txt
Q: python2 can't file a file in current folder For the next file info: [jzun@hscd8a25e93f9vm dates]$ pwd /home/jzun/vivo_mod_samples/dates [jzun@hscd8a25e93f9vm dates]$ ls date_def.json dates_add.rdf dates.bak dates.rdf dates_sub.rdf dates.txt datetime_precision_enum.txt gen_date_rdf.py gen_date_rdf.py...
python2 can't file a file in current folder
For the next file info: [jzun@hscd8a25e93f9vm dates]$ pwd /home/jzun/vivo_mod_samples/dates [jzun@hscd8a25e93f9vm dates]$ ls date_def.json dates_add.rdf dates.bak dates.rdf dates_sub.rdf dates.txt datetime_precision_enum.txt gen_date_rdf.py gen_date_rdf.py.bak gen_dates.py gen_dates.py.bak get.txt RE...
[ "Try passing the full path of the file dates.txt:\ncwd = os.getcwd()\nfile_name = \"dates.txt\"\nfile_path = os.path.join(cwd, file_name)\n\n# Double check that file exist\nassert os.path.isfile(file_path) is True\n\nwith open(file_path, 'rU') as fp:\n data = read_csv_fp(fp, skip, delimiter)\n fp.close()\n\n"...
[ 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0074660016_python_python_2.7.txt
Q: Matrix multiplication of a 2d numpy array to cpp using ctypes What is a correct way to do the matrix multiplication using ctype ? in my current implementation data going back and forth consuming lots of time, is there any way to do it optimally ? by passing array address and getting pointer in return instead of ge...
Matrix multiplication of a 2d numpy array to cpp using ctypes
What is a correct way to do the matrix multiplication using ctype ? in my current implementation data going back and forth consuming lots of time, is there any way to do it optimally ? by passing array address and getting pointer in return instead of generating entire array using .contents method. cpp_function.cpp comp...
[ "One reason for the time consumption is not using an ndpointer for the return value and copying it into a Python list. Instead use the following restype. You won't need the later reshape as well. But take the commenters' advice and don't reinvent the wheel.\ndef mult_matrix_cpp(a, b):\n shape = a.shape[0] * a...
[ 1, 0 ]
[]
[]
[ "c++", "ctypes", "numpy", "python" ]
stackoverflow_0074612029_c++_ctypes_numpy_python.txt
Q: how to update a variable in a text file I have a program that opens an account and there are several lines but i want it to update this one line credits = 0 Whenever a purchase is made I want it to add one more to the amount this is what the file looks like ['namef', 'namel', 'email', 'adress', 'city', 'state', '...
how to update a variable in a text file
I have a program that opens an account and there are several lines but i want it to update this one line credits = 0 Whenever a purchase is made I want it to add one more to the amount this is what the file looks like ['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2'] credits = 0 this ...
[ "The below code snippet should give you an idea on how to go about. This code updates, the value of the counter variable present within a file counter_file.txt\nimport os\n\ncounter_file = open(r'./counter_file.txt', 'r+')\ncontent_lines = []\n\nfor line in counter_file:\n if 'counter=' in line:\n ...
[ 4, 1, 0 ]
[]
[]
[ "file", "python", "python_3.x", "variables" ]
stackoverflow_0018040596_file_python_python_3.x_variables.txt
Q: Reversing a txt File in python Assume you are given a file called newText.txt which contains the lines: line 1 line 2 line 3 Write a python program that reads the data from newText.txt and writes a new file called newerText.txt in the following format: line 3 Python Inserted a new line line 2 line 1 I can get it r...
Reversing a txt File in python
Assume you are given a file called newText.txt which contains the lines: line 1 line 2 line 3 Write a python program that reads the data from newText.txt and writes a new file called newerText.txt in the following format: line 3 Python Inserted a new line line 2 line 1 I can get it reversed but the line 2 and line 3 ar...
[ "If you look into what text.txt actually is, it's probably something like this:\nline1\\nline2\\nline3\n\nNotice how each line is divided by a new line character (\\n). This means the last line doesn't have a new line at the end of it, so when you write it to newText.txt, it won't have a newline.\nWhat you can do i...
[ 1 ]
[]
[]
[ "append", "python", "reverse" ]
stackoverflow_0074662524_append_python_reverse.txt
Q: Appending a list with a dictionary key that contains multiple values from a json response I'm traversing a json response in which stats are grouped by games played. I want to gather all of the values from the set and assign a single dictionary key to them. Currently every value has its own key. Here is a sample of...
Appending a list with a dictionary key that contains multiple values from a json response
I'm traversing a json response in which stats are grouped by games played. I want to gather all of the values from the set and assign a single dictionary key to them. Currently every value has its own key. Here is a sample of the json response: {'data': [{'ast': 9, 'blk': 0, 'dreb': 4, ...
[ "Based the comment from Kenny Ostrom\n output = {\"Assists per game\": [game_info['ast'] for game_info in result['data']]}\n\nwhich is going to result like you asked\n {'Assists per game': [9, 8]}\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "json", "list", "python", "python_3.x" ]
stackoverflow_0074661957_dictionary_json_list_python_python_3.x.txt
Q: Inverse of a complicated matrix not working in Sympy/ Python So I was trying to formulate some matrix out of another matrix's elements using sympy. But while the taking the inverse it didn't work I believe cause of the complicity of the matrix I am taking the inverse of. x0, x1, x2, x3 = smp.symbols('x^0 x^1 x^2 x...
Inverse of a complicated matrix not working in Sympy/ Python
So I was trying to formulate some matrix out of another matrix's elements using sympy. But while the taking the inverse it didn't work I believe cause of the complicity of the matrix I am taking the inverse of. x0, x1, x2, x3 = smp.symbols('x^0 x^1 x^2 x^3') COORDS = [x0, x1, x2, x3] N = len(COORDS) g00 = smp.Function(...
[ "A fully symbolic matrix has a complicated expression for its inverse (shown below). Feel free to substitute whatever you like for the entries of the matrix but it's unlikely that you can do anything useful with such an expression.\nHere is the inverse of a fully symbolic 4x4 matrix (computed in less than a second)...
[ 2 ]
[]
[]
[ "matrix", "python", "sympy", "tensor" ]
stackoverflow_0074658912_matrix_python_sympy_tensor.txt
Q: python + psycopg2.errors.SyntaxError: syntax error at end of input I'm getting this error message cursor.execute(query, variables) psycopg2.errors.SyntaxError: syntax error at end of input My code data = { 'country': data['country'][x], 'year': data['year'][x].astype(float), 'month': data['month'][x]...
python + psycopg2.errors.SyntaxError: syntax error at end of input
I'm getting this error message cursor.execute(query, variables) psycopg2.errors.SyntaxError: syntax error at end of input My code data = { 'country': data['country'][x], 'year': data['year'][x].astype(float), 'month': data['month'][x].astype(float) } db_connection.execute( f""" INSERT INTO my_tabl...
[ "You're missing a conflict_action in your sql statement. See https://www.postgresql.org/docs/current/sql-insert.html#:~:text=ON%20CONFLICT%20DO%20NOTHING%20simply,can%20perform%20unique%20index%20inference. for details.\nEG You might want ON CONFLICT (country, year, month) DO NOTHING\n" ]
[ 2 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0074662600_postgresql_python.txt
Q: How do I add images to a PyPI readme (that works on GitHub)? In my readme on GitHub I have several images that are present there in my project's source tree which I reference successfully with directives like .. image:: ./doc/source/_static/figs/moon_probe.png I would also like to have these images appear when th...
How do I add images to a PyPI readme (that works on GitHub)?
In my readme on GitHub I have several images that are present there in my project's source tree which I reference successfully with directives like .. image:: ./doc/source/_static/figs/moon_probe.png I would also like to have these images appear when this same readme is generated in PyPi. How do I (a) ensure that imag...
[ "PyPI will not read your package distributions for the image. You have to use the image's external link, for example:\n.. image:: https://raw.githubusercontent.com/greyli/flask-share/master/images/demo.png\n\nIf you are using Markdown description, use this:\n![](https://raw.githubusercontent.com/greyli/flask-share/...
[ 34, 8, 3, 3, 0 ]
[]
[]
[ "github", "pypi", "python", "readme", "restructuredtext" ]
stackoverflow_0041983209_github_pypi_python_readme_restructuredtext.txt
Q: unusual result from joining two Data Frames I have two tables: first name A id x 1 123 2 456 3 789 second name B: id y 1 4 3 5 3 6 I need join tables A and B with result: id x y 1 123 4 2 456 3 789 5 3 6 Of course instead of x and y columns I have a lot of columns and tables have a lot of rows, so...
unusual result from joining two Data Frames
I have two tables: first name A id x 1 123 2 456 3 789 second name B: id y 1 4 3 5 3 6 I need join tables A and B with result: id x y 1 123 4 2 456 3 789 5 3 6 Of course instead of x and y columns I have a lot of columns and tables have a lot of rows, so the solution ...
[ "Use Pandas merge\nimport pandas as pd\n\n# load the data from the two tables into pandas dataframes\ndf1 = pd.read_csv('A.csv')\ndf2 = pd.read_csv('B.csv')\n\n# merge the df using 'id' column\nmerged_df = pd.merge(df1, df2, on='id')\n\nprint(merged_df)\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074662569_pandas_python.txt