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: why does my output show (False, "only", 1, "left") i wanted it without brakets, commas and quotation When I write vote_count = 99 target = vote_count == 100, "only", 100 - vote_count, "left" print(target) the output shows (False, 'only', 1, 'left') my expectation was False only 1 left I tried everything, but i...
why does my output show (False, "only", 1, "left") i wanted it without brakets, commas and quotation
When I write vote_count = 99 target = vote_count == 100, "only", 100 - vote_count, "left" print(target) the output shows (False, 'only', 1, 'left') my expectation was False only 1 left I tried everything, but it just wouldn't want to work
[ "Pass the target as args to print.\nprint(*target)\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074352281_python.txt
Q: function with different types of variable I have a little question. I am writing a mini game and I have a problem. I want to create function which returns a random number from range 100-990 given by user. I got error 'invalid literal for int() with base 10: 'Get number'. How to change this code to get around this ...
function with different types of variable
I have a little question. I am writing a mini game and I have a problem. I want to create function which returns a random number from range 100-990 given by user. I got error 'invalid literal for int() with base 10: 'Get number'. How to change this code to get around this problem. I know I can split this into 2 functio...
[ "Just do the input first and then check that value:\ndef get_int_number_of_first_player(message: str, r_min: int, r_max: int):\n user_value = int(input(f'{message}:\\n'))\n if not (r_min <= user_value <= r_max):\n raise ValueError('Incorrect number')\n return user_value \n\nNote that if the user ent...
[ 0 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0074352185_function_list_python.txt
Q: Python, printing multiple string lengths for strings within a list Using a for loop, how can a list generated by the input function display each string length in the order that they have been input? example: Please enter a list of numbers separated by a comma. one,two,three,four,five The length of the string one i...
Python, printing multiple string lengths for strings within a list
Using a for loop, how can a list generated by the input function display each string length in the order that they have been input? example: Please enter a list of numbers separated by a comma. one,two,three,four,five The length of the string one is 3. The length of the string two is 3. The length of the string three i...
[ "Use split to split the input string into a list, and then you can iterate over that list with a for loop and print the len of each element.\n>>> for s in input(\"Please enter a comma-separated list: \").split(\",\"):\n... print(f\"The length of {s} is {len(s)}\")\n...\nPlease enter a comma-separated list: one,...
[ 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074352324_for_loop_python.txt
Q: i am getting a nonetype for this def talk(text): engine.say(text) engine.runAndWait() listener = sr.Recognizer() engine = pyttsx3.init() def take_command(): try: with sr.Microphone() as source: talk('listening') voice = listener.listen(source) command = lis...
i am getting a nonetype for this
def talk(text): engine.say(text) engine.runAndWait() listener = sr.Recognizer() engine = pyttsx3.init() def take_command(): try: with sr.Microphone() as source: talk('listening') voice = listener.listen(source) command = listener.recognize_google(voice) ...
[ "If you run this:\ncommand = take_command()\nprint(command)\n\ncommand have to be None because your function (take_command) does not return anything, so None is returned by default.\n" ]
[ 0 ]
[]
[]
[ "nonetype", "python", "string" ]
stackoverflow_0074352230_nonetype_python_string.txt
Q: How can I check my python version in cmd? I has downloaded python in python.org, and I wanted to check my python version, so I wrote python --version in cmd, but it said just Python, without version. Is there any other way to find out python version? A: A way to do it is to actually start the python interpreter...
How can I check my python version in cmd?
I has downloaded python in python.org, and I wanted to check my python version, so I wrote python --version in cmd, but it said just Python, without version. Is there any other way to find out python version?
[ "A way to do it is to actually start the python interpreter.\nYou can do that with python command. This will start the repl and you will be able to see in the first line something like:\nPython 2.7.18 (default, Mar 8 2021, 13:02:45) \n\nOr\nPython 3.8.5 (default, Jan 27 2021, 15:41:15) \n\nPlease check in the comm...
[ 1, 0 ]
[]
[]
[ "python", "version" ]
stackoverflow_0067978968_python_version.txt
Q: Traffic Congestion Simulation using OSMNX in Python I'm trying to do traffic flow simulation visualization using OSMnx to extract data from OpenStreetMaps using Python. I'm trying to do macroscopic traffic simulation regarding to agent-based congestion analysis. I tried the below code to find the shortest path an...
Traffic Congestion Simulation using OSMNX in Python
I'm trying to do traffic flow simulation visualization using OSMnx to extract data from OpenStreetMaps using Python. I'm trying to do macroscopic traffic simulation regarding to agent-based congestion analysis. I tried the below code to find the shortest path and it works well. import osmnx as ox import networkx as nx...
[ "The short answer is that OSMnx is not a traffic analysis or flow simulation package. You can either 1) update the graph edge weights to represent new impedance values given traffic conditions then re-solve paths, or 2) save your OSMnx network model and import it into a traffic simulation tool for further analysis....
[ 0, 0 ]
[]
[]
[ "openstreetmap", "osmnx", "python", "traffic_simulation" ]
stackoverflow_0073227015_openstreetmap_osmnx_python_traffic_simulation.txt
Q: Is another loop required to print the reverse with different conditions? I have the following program that prints even numbers in a provided range. However, I'd like to make it so that if the second number is smaller than the 1st number, e.g. end < start, then print the even numbers but in reverse order. I'm think...
Is another loop required to print the reverse with different conditions?
I have the following program that prints even numbers in a provided range. However, I'd like to make it so that if the second number is smaller than the 1st number, e.g. end < start, then print the even numbers but in reverse order. I'm thinking we would need two separate loops for each condition based on what I have h...
[ "you just need to invert the range order to achieve what you want:\nstart = int (input(\"1st number: \")) ...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074351969_python.txt
Q: how to teleport player to the other side of the screen when he touches the screen border? I am new to pygame (and coding) and can't figure out how to move my player from one side of the screen to the other, like the side gates in pacman, here's my code i hope someone can help me cuz it's seems like it's something ...
how to teleport player to the other side of the screen when he touches the screen border?
I am new to pygame (and coding) and can't figure out how to move my player from one side of the screen to the other, like the side gates in pacman, here's my code i hope someone can help me cuz it's seems like it's something easy but i just can't think of a solution yet import pygame white=(255,255,255) yellow=(255,25...
[ "When a player tries to move left, check if their new x-position puts them off the left edge of the screen. If it is, update their x-position to put them on the right side of the screen. Try updating your movement function like this:\ndef movement(keys_pressed,player):\n if keys_pressed[pygame.K_a]:\n new...
[ 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074352270_pygame_python.txt
Q: how to use nested for loops, with ranges (includes string index) to clean up a long multiplication code line I wrote some code to solve project Eulers #8. I have seen a few other solutions to this problem on line, but I do not understand how they create the nested loop, or it is a different method. Problem OVERVIE...
how to use nested for loops, with ranges (includes string index) to clean up a long multiplication code line
I wrote some code to solve project Eulers #8. I have seen a few other solutions to this problem on line, but I do not understand how they create the nested loop, or it is a different method. Problem OVERVIEW: Find the thirteen adjacent digits in the 1000-digit number(string with no delimitator) that have the greatest p...
[ "You need to assign product_13 = 1 instead of 0. This is because any number multiplied by 0 will give a result of 0 only.\n", "I tried this question on my laptop and I came up with this solution\nIn your solution, the product seems to be static that may create problem.\nAlso a suggestion, to multiple number in th...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074352251_python.txt
Q: Problem mixer.music.get_pos() after set position by mixer.music.set_pos() I use the pygame.mixer module for my music player While doing the project, I came across a problem that I realized was from the pygame.mixer module When I set the new position inside the set_pos() function get_pos() function does not output ...
Problem mixer.music.get_pos() after set position by mixer.music.set_pos()
I use the pygame.mixer module for my music player While doing the project, I came across a problem that I realized was from the pygame.mixer module When I set the new position inside the set_pos() function get_pos() function does not output the new position and outputs the initial position from time import sleep from p...
[ "\nAccording to the docs for set_pos():\n\n\nThis sets the position in the music file where playback will start. The meaning of \"pos\", a float (or a number that can be converted to a float), depends on the music format.\nFor MOD files, pos is the integer pattern number in the module. For OGG it is the absolute po...
[ 0 ]
[]
[]
[ "pygame", "pygame_mixer", "python" ]
stackoverflow_0073089784_pygame_pygame_mixer_python.txt
Q: Python function to get or count the number of days between two years in a pandas data frame I need a function to count the total number of days in the 'days' column between a start date of 1st Jan 1995 and an end date of 31st Dec 2019 in a dataframe taking Leapyears into account as well For example: 1st Jan 1995 ...
Python function to get or count the number of days between two years in a pandas data frame
I need a function to count the total number of days in the 'days' column between a start date of 1st Jan 1995 and an end date of 31st Dec 2019 in a dataframe taking Leapyears into account as well For example: 1st Jan 1995 - Day 1 1st Feb 1995 - Day 32 2nd Feb 1995 - Day 33... And so on all the way to 31st Dec 2019. ...
[ "Convert types\nFirst of all, make sure that the days column is the proper type. Use df.days.dtype and it should be datetime64. If you get object type that means you have a string containing a date and you need to convert the type using\ndf.days = pd.to_datetime(df.days)\n\nCalculate difference\ndf['days_diff'] = (...
[ 1 ]
[ "I finally got it to work by doing this:\ndef date_difference(last_day):\n last_day = pd.to_datetime(last_day, dayfirst = True)\n first_day = pd.to_datetime(\"01/01/1995\", dayfirst = True)\n diff = last_day - first_day\n\nprices['days'] = prices['days'].apply(date_difference)\n\n" ]
[ -1 ]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074351428_dataframe_pandas_python.txt
Q: TypeError: Can't pack data into an AEDesc (unsupported type): Decimal('13.3400') I'm trying to use xlwings to write data from an SQL query to a .xlsm file so that I can run a VBA macro on it. I'm using psycopg2 for the SQL query and the data returned is being stored into a variable (data) as a list of tuples conta...
TypeError: Can't pack data into an AEDesc (unsupported type): Decimal('13.3400')
I'm trying to use xlwings to write data from an SQL query to a .xlsm file so that I can run a VBA macro on it. I'm using psycopg2 for the SQL query and the data returned is being stored into a variable (data) as a list of tuples containing many decimals stored like that shown below: ...Decimal('182.10'), Decimal('84.88...
[ "Found the solution. It appears that psycopyg (at least in the latest version: 3) had a method for this:\nconn.adapters.register_loader(\"numeric\", psycopg.types.numeric.FloatLoader)\n\nref: psycopg documents\n" ]
[ 0 ]
[]
[]
[ "psycopg2", "python", "xlwings" ]
stackoverflow_0074350488_psycopg2_python_xlwings.txt
Q: How to do md5 checksum verification on files after download from ftp server using pysftp I am new to pysftp I am trying to do the following task Connect to ftp server and download the files Generate md5 checksum on files and making sure they are not tampered with Can someone help me with this script? I tried con...
How to do md5 checksum verification on files after download from ftp server using pysftp
I am new to pysftp I am trying to do the following task Connect to ftp server and download the files Generate md5 checksum on files and making sure they are not tampered with Can someone help me with this script? I tried connecting to the server but I am unsure how to go about downloading the files and generating a c...
[ "The psftp get() method is documented here.\nThe python hashlib module is documented here.\nIt provides many hash algorithms including MD5 and SHA256.\nExample :\nimport hashlib\n\ncontent = \"header\\foobar\\nfooter\\n\" # your file content as a string\nh = hashlib.sha256(content.encode())\n\ntampered_content = \...
[ 0 ]
[]
[]
[ "ftp", "ftp_server", "pysftp", "python" ]
stackoverflow_0074351812_ftp_ftp_server_pysftp_python.txt
Q: TypeError: Expected a job store instance or a string, got NoneType instead Why I am getting this error?? I am trying to apscheduler in my django project. But the function is working very well. After sending some email it turns off automatically. here is my code : import logging from django.conf import settings fro...
TypeError: Expected a job store instance or a string, got NoneType instead
Why I am getting this error?? I am trying to apscheduler in my django project. But the function is working very well. After sending some email it turns off automatically. here is my code : import logging from django.conf import settings from apscheduler.schedulers.blocking import BlockingScheduler from django.core.mana...
[ "After taking a quick glance at the documentation, I think this is the fix:\n def handle(self, *args, **kwargs):\n scheduler = BlockingScheduler(timezone=settings.TIME_ZONE)\n scheduler.add_jobstore(DjangoJobStore(), \"d\")\n scheduler.add_job( # I'm guessing you want to add a job\n ...
[ 1 ]
[]
[]
[ "automation", "django", "python" ]
stackoverflow_0074352240_automation_django_python.txt
Q: Pandas interpretes string as scientific notation When I create a dataframe from a excel file, it has a string value '2098E10'. But pandas interpret the letter E on string as scientific notation converting the value to 20980000000000. How can I suppress this panda's behavior to keep the values '2098E10' as string? ...
Pandas interpretes string as scientific notation
When I create a dataframe from a excel file, it has a string value '2098E10'. But pandas interpret the letter E on string as scientific notation converting the value to 20980000000000. How can I suppress this panda's behavior to keep the values '2098E10' as string? I have tried to convert the values to string, but the ...
[ "You should use pandas.read_csv with the correct dtype argument (str for you), e.g.\npd.read_csv('data/data_7.csv',\n dtype={\n 'Name': str,\n 'Grade': int\n })\n\nHint taken from this blog post #5.\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074352392_pandas_python.txt
Q: extracting words from text , ValueError: invalid literal for int() with base 10: '' I try to extract words from a text. So I have this text: "[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT nr. : NL851703884B01 Nederland\nFa...
extracting words from text , ValueError: invalid literal for int() with base 10: ''
I try to extract words from a text. So I have this text: "[' \n\na)\n\n \n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr. : 71201 Koopliedenweg 33\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT nr. : NL851703884B01 Nederland\nFactuur datum : 10-12-21\nAantal Omschrijving Prijs Bedrag\nOrder number : 77553 Loading da...
[ "you need to change the regexp to allow an optional = or ~= between the number and fruit.\ndef total_amount_fruit_regex(format_=re.escape):\n return r\"(\\d*(?:\\.\\d+)*)\\s*(?:=|~=)?\\s*(\" + '|'.join(\n format_(word) for word in fruit_words) + ')'\n\n" ]
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074352421_python_regex.txt
Q: Lists in dictionary using Pandas I am trying to create new dataframe out of the dictionary which includes lists. It looks like something like that: {'prices': [[1574121600000, 1.000650588888066], [1574208000000, 0.9954110116644869]... Those are UNIX date and price of stablecoins, however the columns are not named...
Lists in dictionary using Pandas
I am trying to create new dataframe out of the dictionary which includes lists. It looks like something like that: {'prices': [[1574121600000, 1.000650588888066], [1574208000000, 0.9954110116644869]... Those are UNIX date and price of stablecoins, however the columns are not named properly as it is all under 'prices' ...
[ "You can use pd.Dataframe directly and then pass a list of column names to the parameter columns\nimport pandas as pd\n\na = {'prices': [[1574121600000, 1.000650588888066], [1574208000000, 0.9954110116644869]]}\n\ndf = pd.DataFrame(a['prices'], columns=['Date', 'Price'])\nprint(df)\n# prints\n Date P...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074352416_dataframe_pandas_python.txt
Q: Add new column based on two conditions I have the following table in python: Country Year Date Spain 2020 2020-08-10 Germany 2020 2020-08-10 Italy 2019 2020-08-11 Spain 2019 2020-08-20 Spain 2020 2020-06-10 I would like to add a new column that gives 1 if it's the first date of the year in a country and 0 i...
Add new column based on two conditions
I have the following table in python: Country Year Date Spain 2020 2020-08-10 Germany 2020 2020-08-10 Italy 2019 2020-08-11 Spain 2019 2020-08-20 Spain 2020 2020-06-10 I would like to add a new column that gives 1 if it's the first date of the year in a country and 0 if it's not the first date. I've...
[ "There are many ways to achieve this. Let's create a groupby object to get the min index of each country so we can do some assignment using .loc\nAs an aside, using if with pandas is usually an anti pattern - there are native functions in pandas that help you achieve the same thing whilst taking advantage of the ve...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074352527_pandas_python.txt
Q: How to check different rows values of a column within the same group and return a specific value? I have the following code that generates the two columns. import pandas as pd data = {'Group': ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3...
How to check different rows values of a column within the same group and return a specific value?
I have the following code that generates the two columns. import pandas as pd data = {'Group': ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4',], 'Test1': ['ABC', 'CDE', 'EFG', 'GHI',...
[ "Update, per updated question and comments below:\ndf[['Test1','Test2']].merge(df.groupby('Group')['Value'].apply(lambda x: x.iloc[-3:].mul(x.iloc[-3:].min(), level=0))\\\n .reset_index(), left_index=True, right_on='level_1').drop('level_1', axis=1)\n\nOutput:\n Test1 Test2 Group Value\n0 GHI 1112 1 Fa...
[ 2 ]
[]
[]
[ "data_science_experience", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074352490_data_science_experience_dataframe_group_by_pandas_python.txt
Q: vs code not display debug call stack and variables In the debug left side panel, VS Code does not display the call stack, neither the variables and watch (picture below). Someone knows how to display them ? A: There should be a ... button at the top of the sidebar. Click on it to bring up a menu, and make sure V...
vs code not display debug call stack and variables
In the debug left side panel, VS Code does not display the call stack, neither the variables and watch (picture below). Someone knows how to display them ?
[ "There should be a ... button at the top of the sidebar. Click on it to bring up a menu, and make sure Variables, Watch, Call Stack, and Breakpoints are checked.\n", "There is also a dialog from the View/Open View ... menu.\nUsing that you can search for the panels that are missing.\n" ]
[ 2, 1 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074352507_python_visual_studio_code.txt
Q: is it possible to automate the Python scripts each time when returning an error? I want to automate the python to re-run the code when it returns error, is it possible and how can I do it? I have a script and each time that returns an error I have to run it again. The error does not interfere in the process, so it...
is it possible to automate the Python scripts each time when returning an error?
I want to automate the python to re-run the code when it returns error, is it possible and how can I do it? I have a script and each time that returns an error I have to run it again. The error does not interfere in the process, so it can't be a problem re-run.
[ "When you face an error, typically, the program will halt.\nThat's why there are error handlers in place to not let that happen.\nLook at some already answered examples here\nSo, lets say you want the user to input integer values and it shouldn't halt, so you could use a loop and break it when the entered value is ...
[ 1 ]
[]
[]
[ "automation", "python" ]
stackoverflow_0074352166_automation_python.txt
Q: Python program to give me numbers on the left with their sum on the right while having interchanged symbols in each line up to n (n=6) Here's the picture of the program/ how it should work, it should display 1*1 then 12$3 < 3 is the sum of 1+2.. we only got to for loop. I have tried a lot of solutions and this is ...
Python program to give me numbers on the left with their sum on the right while having interchanged symbols in each line up to n (n=6)
Here's the picture of the program/ how it should work, it should display 1*1 then 12$3 < 3 is the sum of 1+2.. we only got to for loop. I have tried a lot of solutions and this is what i got to at the end, for some reason i can't copy and paste it here without the code deleting whatever i had here.. also the output cu...
[ "I would implement this idea this way:\ndef func(n: int):\n for i in range(1, n + 1):\n nsum = 0 # Sum of numbers in nested loop.\n last = 0 # Last number added to 'nsum'.\n string = '' # Final string which is then printed.\n for j in range(1, i + 1):\n nsum += j # Ad...
[ 0 ]
[]
[]
[ "output", "python", "sorting", "sum", "variables" ]
stackoverflow_0074352470_output_python_sorting_sum_variables.txt
Q: Replace values in one column based on the value of another column using a dictionary I have shrunk down my dictionary and data frame. If it was only two entries, I know I can use if-then statements. My dictionary is as follows: region_rename = {"Gambia": "Sub-Saharan Africa", "North Macedonia": "Central and Easter...
Replace values in one column based on the value of another column using a dictionary
I have shrunk down my dictionary and data frame. If it was only two entries, I know I can use if-then statements. My dictionary is as follows: region_rename = {"Gambia": "Sub-Saharan Africa", "North Macedonia": "Central and Eastern Europe"} My data frame, called data_2019, look like this: **Country** **R...
[ "here is one way to do it using mask\n# check if map exists, and when it does, do the mapping\n\nsample[\"**Country**\"] = sample[\"**Country**\"].mask(sample[\"**Country**\"].map(region_rename).notna(), \n sample[\"**Country**\"].map(region_rename))\n\nOR\n# using loc\n\nsampe.loc[sample[...
[ 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074352579_dictionary_pandas_python.txt
Q: How to return the best team from a dictionary taking into account the total points and if two teams are tied the goal difference? I need to return the name of the best team from several teams inserted in a dictionary taking into account the number of points ("wins"*3 + "draws") and if there are two teams tied I wa...
How to return the best team from a dictionary taking into account the total points and if two teams are tied the goal difference?
I need to return the name of the best team from several teams inserted in a dictionary taking into account the number of points ("wins"*3 + "draws") and if there are two teams tied I want to return the one with the best goal difference ("scored" - "conceded") I tried to do it like that but te function returned Barcelon...
[ "max() will not return an array of teams, just a single result. What you need is sorting the list according to a tuple of quantities (points, goal_difference). The following code:\nla_liga = [\n {\n \"name\": \"Sevilha\",\n \"wins\": 18,\n \"loss\": 10,\n \"draws\": 10,\n \"scored\": 60,...
[ 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074352541_dictionary_python.txt
Q: Check the total number of parameters in a PyTorch model How do I count the total number of parameters in a PyTorch model? Something similar to model.count_params() in Keras. A: PyTorch doesn't have a function to calculate the total number of parameters as Keras does, but it's possible to sum the number of elemen...
Check the total number of parameters in a PyTorch model
How do I count the total number of parameters in a PyTorch model? Something similar to model.count_params() in Keras.
[ "PyTorch doesn't have a function to calculate the total number of parameters as Keras does, but it's possible to sum the number of elements for every parameter group:\npytorch_total_params = sum(p.numel() for p in model.parameters())\n\nIf you want to calculate only the trainable parameters:\npytorch_total_params =...
[ 239, 67, 14, 7, 7, 6, 3, 0, 0, 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0049201236_python_pytorch.txt
Q: Got a `TypeError` when calling `Post.objects.create()`. This may be because you have a writable field on the serializer class that is Writing a Django app which has a post table that has a recursive relationship to itself. This means that post CAN have a parent post (allows for replies). I want to ensure that a po...
Got a `TypeError` when calling `Post.objects.create()`. This may be because you have a writable field on the serializer class that is
Writing a Django app which has a post table that has a recursive relationship to itself. This means that post CAN have a parent post (allows for replies). I want to ensure that a post can have a null for the parent post attribute - this would denote the "root" post. However, when I implement the views, model and serial...
[ "In serializers:\nI think your fields should be begin and close with [] brackets.\nchange this:\nfields = ('id', 'title', 'body', 'author', 'time_stamp')\n\nTo this:\nfields = ['id', 'title', 'body', 'author', 'time_stamp']\nread_only_fields = ['id'] #also add this\n\nIn views:\nclass PostList(generics.ListCreateAP...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "django_serializer", "python" ]
stackoverflow_0074342444_django_django_models_django_rest_framework_django_serializer_python.txt
Q: conditional statement in pandas Not working I am trying to check for the value and assign the data to new_col using pandas if condition but getting ValueError, tried multiple ways df['new_col'] = np.where((df.rec_type == 'ABC' or df.rec_type == 'XYZ'), df.col1, df.col2) ValueError: The truth value of a Series is ...
conditional statement in pandas Not working
I am trying to check for the value and assign the data to new_col using pandas if condition but getting ValueError, tried multiple ways df['new_col'] = np.where((df.rec_type == 'ABC' or df.rec_type == 'XYZ'), df.col1, df.col2) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any...
[ "np.where(((df.rec_type == 'ABC') | (df.rec_type == 'XYZ')), df.col1, df.col2)\n\nIt gets confused about the logical order in which you mean things. This fixes it.\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074352731_pandas_python.txt
Q: Pytest with async tests: test setup before and after I'm having a problem with my test setup config using pytest fixture: @pytest.fixture(autouse=True) async def run_around_tests(elastic_api, catalog): es_index_mapping = open('test/resources/es_index_mapping.json') es_index_mapping_dict = json.load(es_inde...
Pytest with async tests: test setup before and after
I'm having a problem with my test setup config using pytest fixture: @pytest.fixture(autouse=True) async def run_around_tests(elastic_api, catalog): es_index_mapping = open('test/resources/es_index_mapping.json') es_index_mapping_dict = json.load(es_index_mapping) es_cars = open('test/resources/es_cars.json...
[ "What are you using to drive the async fixtures/tests? pytest does not work out of the box with asyncio. If you're using pytest-asyncio, then you need to decorate your fixtures with @pytest_asyncio.fixture rather than the standard @pytest.fixture.\nA good way to test that your fixture is working as expected is to u...
[ 0 ]
[]
[]
[ "pytest", "python", "python_asyncio" ]
stackoverflow_0074351637_pytest_python_python_asyncio.txt
Q: How can I use Flask WTForms and CSRF without session cookie? I have a very simple app that has no user management or any Flask-Login auth needs. It has forms, WTForms. All I want to do is collect some data submitted by the form. I could technically disable CSRF validation but Flask WTForms really urges me not to. ...
How can I use Flask WTForms and CSRF without session cookie?
I have a very simple app that has no user management or any Flask-Login auth needs. It has forms, WTForms. All I want to do is collect some data submitted by the form. I could technically disable CSRF validation but Flask WTForms really urges me not to. I'd like to disable flask session cookie in the browser because it...
[ "I found out from the code base of WTForms: https://github.com/wtforms/flask-wtf/blob/565a63d9b33bf6eb141839f03f0032c03894d866/src/flask_wtf/csrf.py#L56\nBasically, session['csrf_token'] is stored in the session and compared against the form.hidden() tag (or form.csrf_token) in the HTML body.\nThis is not clearly e...
[ 1, 1 ]
[]
[]
[ "cookies", "flask", "flask_wtforms", "python", "session_cookies" ]
stackoverflow_0071181279_cookies_flask_flask_wtforms_python_session_cookies.txt
Q: Can't run any matplotlib plot I try to run the following simple code on Python importing Matplotlib: import matplotlib.pyplot as plt import numpy as np # Data for plotting t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage...
Can't run any matplotlib plot
I try to run the following simple code on Python importing Matplotlib: import matplotlib.pyplot as plt import numpy as np # Data for plotting t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simp...
[ "Create a virtual environment with Numpy and Matplotlib only and see if it works. You could be dealing with hairy package dependency issues here and trust me you don't want to waste your time untangling the mess...\nLinux/MacOs, open a new terminal:\nuser@macbook % mkdir my_matplotlib_project\nuser@macbook % cd my_...
[ 1 ]
[]
[]
[ "matplotlib", "python", "windows_subsystem_for_linux" ]
stackoverflow_0074351319_matplotlib_python_windows_subsystem_for_linux.txt
Q: problem with reading partitioned parquet files created by Snowflake with pandas or arrow ArrowInvalid: Unable to merge: Field X has incompatible types: string vs dictionary<values=string, indices=int32, ordered=0> ArrowInvalid: Unable to merge: Field X has incompatible types: decimal vs int32 I am trying to writ...
problem with reading partitioned parquet files created by Snowflake with pandas or arrow
ArrowInvalid: Unable to merge: Field X has incompatible types: string vs dictionary<values=string, indices=int32, ordered=0> ArrowInvalid: Unable to merge: Field X has incompatible types: decimal vs int32 I am trying to write the result of a snowflake query on disk and then query that data using arrow and duckdb. I h...
[ "The only work around I found that works is this:\nimport pyarrow.dataset as ds\ndataset = ds.dataset('/path/to/parquet/', format=\"parquet\", partitioning=\"hive\")\n\nthen you can query directly using duckdb:\nimport duckdb\ncon = duckdb.connect()\npandas_df = con.execute(\"Select * from dataset\").df()\n\nAlso i...
[ 0 ]
[]
[]
[ "duckdb", "parquet", "pyarrow", "python", "snowflake_cloud_data_platform" ]
stackoverflow_0074352815_duckdb_parquet_pyarrow_python_snowflake_cloud_data_platform.txt
Q: How to conditionally replace a value with a value from the same row in a different column using pandas? Say I have a data frame: ID X Y Z 1 3 5 3 2 1 4 1 3 5 3 5 4 0 7 7 I want column Z to equal column X, unless column X is equal to 0. In that case, I would want column ...
How to conditionally replace a value with a value from the same row in a different column using pandas?
Say I have a data frame: ID X Y Z 1 3 5 3 2 1 4 1 3 5 3 5 4 0 7 7 I want column Z to equal column X, unless column X is equal to 0. In that case, I would want column Z to equal column Y. Is there a way to do this without a for loop using pandas?
[ "You can try using np.where():\ndf['Z'] = np.where(df['X'] == 0,df['Y'],df['X'])\n\nBasically this translates to \"If X = 0 then use the corresponding value for column Y, else (different than 0) use column X\"\n", "Use a conditional with numpy.where:\ndf['Z'] = np.where(df['X'].eq(0), df['Y'], df['X'])\n\nOr Seri...
[ 3, 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074352777_pandas_python.txt
Q: Tensorflow Lite model maker: training chart possible? i am using the Tensorflow Lite Model Maker library to train an efficient model for object detection. It works well, but I don’t know how to get graphs of the training process. It prints just the loss values per epoch on the console. Is it possible to get a char...
Tensorflow Lite model maker: training chart possible?
i am using the Tensorflow Lite Model Maker library to train an efficient model for object detection. It works well, but I don’t know how to get graphs of the training process. It prints just the loss values per epoch on the console. Is it possible to get a chart with for example accuracy, recall, precision, f1,…(for ev...
[ "Late :) .. i hope to help any one else\nyou can use Tensorpoard:\ntensorboard --logdir training_events_path\n\nto find Training event path:\nWhen you start the training, the Tensorflow Lite Model Maker library create temp folder to save training files.\nI found it on C:\\Users\\User\\AppData\\Local\\Temp\\tmpvu_xi...
[ 1 ]
[ "when you do model.train(...) the function return history json object\nhistory = model.train(...)\n\nyou can list all data in history\nprint(history.history.keys())\n\nTo plot the history accuracy:\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.yl...
[ -1 ]
[ "deep_learning", "object_detection", "python", "tensorflow", "tensorflow_lite" ]
stackoverflow_0071178273_deep_learning_object_detection_python_tensorflow_tensorflow_lite.txt
Q: Returning a df as NoneType after function is ran under except statement I am having trouble with returning a DataFrame after some exception handling. What I'm doing is checking for a FileNotFoundError when reading in an excel file, if found then I am printing an error message and then re-running the function and t...
Returning a df as NoneType after function is ran under except statement
I am having trouble with returning a DataFrame after some exception handling. What I'm doing is checking for a FileNotFoundError when reading in an excel file, if found then I am printing an error message and then re-running the function and trying to return the df then. However, on the second run, even if the file is ...
[ "Move return df to the end of the function (or move it to else block), and make read_wb() call return value:\ndef read_wb():\n try:\n wb_name = input(\"What is the name of your workbook (add .xlsx): \")\n df = pd.read_excel(wb_name)\n except FileNotFoundError:\n print(\"Ooops... It looks ...
[ 2 ]
[]
[]
[ "custom_error_handling", "dataframe", "error_handling", "pandas", "python" ]
stackoverflow_0074352734_custom_error_handling_dataframe_error_handling_pandas_python.txt
Q: Handling user-requests while executing a microservice I'm creating a microservice and need some guidance in deciding the architecture. I have a "create" operation that can take up to an hour, and needs to be able to handle a "cancel" request from a user. The only way I can think of to achieve this (in Python) is ...
Handling user-requests while executing a microservice
I'm creating a microservice and need some guidance in deciding the architecture. I have a "create" operation that can take up to an hour, and needs to be able to handle a "cancel" request from a user. The only way I can think of to achieve this (in Python) is call an async helper function to run the main functionality...
[ "The trick here is to understand that your request is a persistent piece of state that needs to be tracked outside the currently executing thread. As such, you really want to externalize it like you would any other piece of state. As external state, it should be persistent, atomic, and scalable.\nThis could be a ...
[ 0 ]
[]
[]
[ "architecture", "event_handling", "microservices", "python" ]
stackoverflow_0074308788_architecture_event_handling_microservices_python.txt
Q: Resizing numpy array from (32,32,3) to (224,224,3) I'm working wirth keras "cifar10" dataset, which gives you a set of RGB images as numpy array in the shape (32,32,3). I'm trying to resize that RGB image to (224,224,3), but every time I try to do it with the reshape function, the following error shows up: test = ...
Resizing numpy array from (32,32,3) to (224,224,3)
I'm working wirth keras "cifar10" dataset, which gives you a set of RGB images as numpy array in the shape (32,32,3). I'm trying to resize that RGB image to (224,224,3), but every time I try to do it with the reshape function, the following error shows up: test = x_train[0].reshape(224,224,3) EROR: cannot reshape array...
[ "Reshaping an array with shape (32,32,3) into an array with shape (224,224,3) cannot be done using np.reshape since it would require additional data to be created or existing data to be interpolated, which is not how np.reshape works.\nIf you want to resize an image, use OpenCV:\nimport cv2\n\ntest = cv2.resize(x_t...
[ 3 ]
[]
[]
[ "keras", "numpy", "python", "rgb" ]
stackoverflow_0074352793_keras_numpy_python_rgb.txt
Q: Python - Construct DF From Nested XML Response What would be the best way to construct a DF from the below nested XML data? Each "properties" element has three "property" elements nested containing the "name" and "value" of our data. I tried doing two for loops, pandas read_xml option, and a few other pieces but h...
Python - Construct DF From Nested XML Response
What would be the best way to construct a DF from the below nested XML data? Each "properties" element has three "property" elements nested containing the "name" and "value" of our data. I tried doing two for loops, pandas read_xml option, and a few other pieces but haven't quite gotten the nested logic figured out. My...
[ "Since <Property> sits at a shallow part of the XML, simply call pandas.read_xml narrowing in on that set of nodes while acknowledging the default namespace (http://exacttarget.com/wsdl/partnerAPI):\nproperty_df = pd.read_xml(\n \"Input.xml\", \n xpath = \".//rrm:Property\",\n namespaces = {\"rrm\": \"http...
[ 2 ]
[]
[]
[ "pandas", "python", "python_3.x", "xml" ]
stackoverflow_0074350398_pandas_python_python_3.x_xml.txt
Q: FastAPI - "TypeError: issubclass() arg 1 must be a class" with modular imports When working with modular imports with FastAPI and SQLModel, I am getting the following error if I open /docs: TypeError: issubclass() arg 1 must be a class Python 3.10.6 pydantic 1.10.2 fastapi 0.85.2 sqlmodel 0.0.8 macOS 12.6 Here ...
FastAPI - "TypeError: issubclass() arg 1 must be a class" with modular imports
When working with modular imports with FastAPI and SQLModel, I am getting the following error if I open /docs: TypeError: issubclass() arg 1 must be a class Python 3.10.6 pydantic 1.10.2 fastapi 0.85.2 sqlmodel 0.0.8 macOS 12.6 Here is a reproducible example. user.py from typing import List, TYPE_CHECKING, Optional...
[ "TL;DR\nYou need to call User.update_forward_refs(Item=Item) before the OpenAPI setup.\n\nExplanation\nSo, this is actually quite a bit trickier and I am not quite sure yet, why this is not mentioned in the docs. Maybe I am missing something. Anyway...\nIf you follow the traceback, you'll see that the error occurs ...
[ 1 ]
[]
[]
[ "fastapi", "pydantic", "python", "sqlalchemy", "sqlmodel" ]
stackoverflow_0074346565_fastapi_pydantic_python_sqlalchemy_sqlmodel.txt
Q: Python Durable Function doesn't call Activity I have 3 Azure Functions where I am trying to orchestrate. For some reason, the activity function isn't getting invoked. The flow is as below F1 (Service Bus) -> F2 (Orchestrator) -> F3 (Activity) F1 This is the function invoked by Service Bus message. This is working ...
Python Durable Function doesn't call Activity
I have 3 Azure Functions where I am trying to orchestrate. For some reason, the activity function isn't getting invoked. The flow is as below F1 (Service Bus) -> F2 (Orchestrator) -> F3 (Activity) F1 This is the function invoked by Service Bus message. This is working fine. import logging import json import azure.funct...
[ "When I try to run this code, I get a warning on the terminal reading\n[2022-11-07T20:56:23.947Z] The 'F3' function is in error: The binding name input_json is invalid. Please assign a valid name to the binding.\n\nSo I think the issue is that the parameter name input_json is not a valid identifier in Azure Functio...
[ 0 ]
[]
[]
[ "azure", "azure_durable_functions", "azure_functions", "python" ]
stackoverflow_0074324378_azure_azure_durable_functions_azure_functions_python.txt
Q: can not get the variable output in tkinter checkbutton I am new to tkinter and learning to use the widget "CheckButton". I have encountered a problem, whatever I select, the code prints 0. Wanted: print 1 if selected print 0 if not selected MWE import tkinter as tk win = tk.Tk() win.title('My Window') win.geome...
can not get the variable output in tkinter checkbutton
I am new to tkinter and learning to use the widget "CheckButton". I have encountered a problem, whatever I select, the code prints 0. Wanted: print 1 if selected print 0 if not selected MWE import tkinter as tk win = tk.Tk() win.title('My Window') win.geometry('100x100') l = tk.Label(win, width=20, text='MultipleR...
[ "You're calling get on var_cb1 pretty much immediately after setting it to 0, and then printing that value. You're not waiting for the checkbutton to change states and then printing the value. Define a function that gets called when the CheckButton changes state, then get the value there\nimport tkinter as tk\n\n\n...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074352750_python_tkinter.txt
Q: Regex to match a url/link with line breaks I want match url from references.But some url has line brakes in it. Example text = Yale Project on Climate Change Communication. New Haven, CT: xxx University and George Mason University; 2015. p. 1–62. Available from: https://example.xxx.edu/wp-content/ uploads/2015/04/...
Regex to match a url/link with line breaks
I want match url from references.But some url has line brakes in it. Example text = Yale Project on Climate Change Communication. New Haven, CT: xxx University and George Mason University; 2015. p. 1–62. Available from: https://example.xxx.edu/wp-content/ uploads/2015/04/Global-Warming-CCAM-March-2015.pdf. want to matc...
[ "Try (Regex demo.)\ntxt = \"\"\"\\\nYale Project on Climate Change Communication. New Haven, CT: xxx University and George\nMason University; 2015. p. 1–62. Available from: https://example.xxx.edu/wp-content/\nuploads/2015/04/Global-Warming-CCAM-March-2015.pdf. This is another text just for example\"\"\"\n\n\nimpor...
[ 0 ]
[]
[]
[ "python", "regex", "url" ]
stackoverflow_0074352789_python_regex_url.txt
Q: I have a Code like this and I want to shorten it number output the square of the difference of the numbers. For example, if the given number is 352, then it is the maximum number made from the digits of this number 532 and the minimum number is 235. The square of their difference is (532-235)(532-235) =297*297 = 8...
I have a Code like this and I want to shorten it
number output the square of the difference of the numbers. For example, if the given number is 352, then it is the maximum number made from the digits of this number 532 and the minimum number is 235. The square of their difference is (532-235)(532-235) =297*297 = 88209. The code is working but I need this code abbrevi...
[ "Don't write code which expects three digits. Write code which expects any number of digits. Your code will be more reusable and it will be simpler:\ndigits = str(number)\nordered = sorted(digits)\nsmall = int(''.join(ordered))\nbig = int(''.join(ordered[::-1]))\n\n", "I abbreviated your code as follows:\nn = inp...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074352433_python.txt
Q: How to make mysql ```UNIX_TIMESTAMP()``` return custom timestamp? For simplicity pytest launches my_server and mysql_server (inside docker). my_server connects to mysql_server (over host network), then he gets value of SELECT UNIX_TIMESTAMP(); from mysql_server process it to day of week, then prints number accordi...
How to make mysql ```UNIX_TIMESTAMP()``` return custom timestamp?
For simplicity pytest launches my_server and mysql_server (inside docker). my_server connects to mysql_server (over host network), then he gets value of SELECT UNIX_TIMESTAMP(); from mysql_server process it to day of week, then prints number according to day of week: ('mon', 1667768400), # print 1 ('tue', 1667854800), ...
[ "I dare to suggest the idea of MySQL-proxy for modifying queries transmitted to the SQL server. You can look at this as a starting point: https://github.com/mysql/mysql-proxy\n" ]
[ 1 ]
[]
[]
[ "mysql", "pytest", "python" ]
stackoverflow_0074350461_mysql_pytest_python.txt
Q: How to generate the set of all permutations of a list in Python without repetition Take the list [1,2,3], I would like to be able to find all ordered combinations of this list without repetition that are the same length as this list. In my case, I need to be able to generate (1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2)...
How to generate the set of all permutations of a list in Python without repetition
Take the list [1,2,3], I would like to be able to find all ordered combinations of this list without repetition that are the same length as this list. In my case, I need to be able to generate (1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,1,2),(3,2,1). How can I go about doing this? I cannot seem to find a function within itertoo...
[ "itertools.permutations is your friend:\n>>> from itertools import permutations\n>>> list(permutations([1,2,3]))\n[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074352927_python.txt
Q: Create dictionary using JSON data I have a JSON file that has movie data in it. I want to create a dictionary that has the movie title as the key and a count of how many actors are in that movie as the value. An example from the JSON file is below: { "title": "Marie Antoinette", "year": "2006",...
Create dictionary using JSON data
I have a JSON file that has movie data in it. I want to create a dictionary that has the movie title as the key and a count of how many actors are in that movie as the value. An example from the JSON file is below: { "title": "Marie Antoinette", "year": "2006", "genre": "Drama", "sum...
[ "You show json that only contains a dictionary, yet you seem to process it as if it were a list of dictionaries with the structure you have shown. Pending clarification, I am answering here as if the latter is true -- you have a list of dictionaries, since you would be asking a different question about a different ...
[ 0 ]
[ "def actor_count(json_data):\n newD = dict()\n with open(\"movies_db.json\", 'r') as file:\n data = json.load(file)\n for t in data:\n if t == 'title':\n title_ = json_data[t]\n newD[ title_ ] = 0\n if t == 'actors':\n newD[ titl...
[ -1 ]
[ "python" ]
stackoverflow_0074341848_python.txt
Q: In detectron2 there are class IDs instead of class names I finished training model for instance segmentation in detectron2 when I test images in training files there is no problem class names(apple,banana,orange) are written on the image but I downloaded some fruit images from the internet and class names are not ...
In detectron2 there are class IDs instead of class names
I finished training model for instance segmentation in detectron2 when I test images in training files there is no problem class names(apple,banana,orange) are written on the image but I downloaded some fruit images from the internet and class names are not written on the photos. There are class ID's. cfg.MODEL.WEIGHTS...
[ "After searching for an easy solution, I came with this, which is the easiest IMO.\nCreate a new Metadata class\nClass Metadata:\n def get(self, _):\n return ['apple','banana','orange','etc'] #your class labels\n\nthen, provide Metadata in the Visualizer line\nv = Visualizer(im[:, :, ::-1], Metadata, scal...
[ 2, 0, 0 ]
[]
[]
[ "detectron", "image_segmentation", "python" ]
stackoverflow_0071717980_detectron_image_segmentation_python.txt
Q: Why am I getting 'Open method of Workbooks class failed' error when trying to open Excel file using pywin32? So, I am using openpyxl and pandas to open an excel file, and write in data. Then, I'm attempting to use pywin32 to open the same file and run a macro to parse the data. But, I'm getting this error when att...
Why am I getting 'Open method of Workbooks class failed' error when trying to open Excel file using pywin32?
So, I am using openpyxl and pandas to open an excel file, and write in data. Then, I'm attempting to use pywin32 to open the same file and run a macro to parse the data. But, I'm getting this error when attempting to open the file with pywin32: pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft E...
[ "Sometimes this error occured when path to file is too long. So you should try this code with file with shorter path\n" ]
[ 0 ]
[]
[]
[ "excel", "python", "pywin32" ]
stackoverflow_0071071737_excel_python_pywin32.txt
Q: Pandas - head to head score counting I have a tennis data frame and I am trying to get some statistics from the data. I would like to be able to see the head to head score of the players whether they are player 1 or player 2 and also the same score but on each surface. It will have to have a shift(1) as I want to ...
Pandas - head to head score counting
I have a tennis data frame and I am trying to get some statistics from the data. I would like to be able to see the head to head score of the players whether they are player 1 or player 2 and also the same score but on each surface. It will have to have a shift(1) as I want to check the score before the game starts Thi...
[ "I think this can be a good a starting place for you.\nimport pandas as pd\n\ndata = [\n [ 'Murray', 'Nadal', 'Hard', 1, 0 ],\n [ 'Nadal', 'Murray', 'Clay', 1, 0 ],\n [ 'Nadal', 'Murray', 'Hard', 0, 1 ],\n [ 'Murray', 'Federer', 'Clay', 1, 0 ]\n]\n\ndf = pd.DataFrame( data, columns=['p1_name', 'p2_name'...
[ 2 ]
[]
[]
[ "pandas", "python", "statistics" ]
stackoverflow_0074352633_pandas_python_statistics.txt
Q: writing to value in list skips items I have a python list with dicts from where I pull the price variable such as: def pricing(): for index,i in enumerate(data): price = i['functions']['price'] data['price'] = price return data I further do some calculations based on other values in th...
writing to value in list skips items
I have a python list with dicts from where I pull the price variable such as: def pricing(): for index,i in enumerate(data): price = i['functions']['price'] data['price'] = price return data I further do some calculations based on other values in the list, for I. But the Price variable only...
[ "data = [1, 2, 4, \"\",\"\"]\nfor i, item in enumerate(data):\n if item == \"\":\n data[i] = 0\n\n\nI have not a simple data but i hope it is solution for your problem.\n\n\nYou can change the where price == \"\" to int 0.\nThis way you get rid of unnecessary data. Your list could be clearer.\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074316768_dictionary_list_python.txt
Q: Exporting Results from Linear Optimization in PuLP to Excel I'm new to Python and the PuLP package in general, and have some results in the terminal of my Jupyter Notebook I'd like to export to Excel if possible. I did not create a data frame initially-- but was wondering if it is possible to create a data frame f...
Exporting Results from Linear Optimization in PuLP to Excel
I'm new to Python and the PuLP package in general, and have some results in the terminal of my Jupyter Notebook I'd like to export to Excel if possible. I did not create a data frame initially-- but was wondering if it is possible to create a data frame for results after they have printed. My output is below: Service_(...
[ "Welcome to the site.\nYou do not need to use a data frame to do this, unless you have another purpose for the data frame. I think it is just as easy to write out the results to a datafile and use that.\nI'd suggest just writing your own \"CSV\" files (comma separated value). It is a standard format and fairly un...
[ 0 ]
[]
[]
[ "linear_programming", "pulp", "python" ]
stackoverflow_0074351055_linear_programming_pulp_python.txt
Q: Reverse vowels in a string using nested for loops I have a program to reverse the vowels in a string. I've seen many solutions however none of them are solutions with nested for loops. Is it possible to implement nested for loops into my code (which works), and if so, how would I code this? Thanks def reverse_vowe...
Reverse vowels in a string using nested for loops
I have a program to reverse the vowels in a string. I've seen many solutions however none of them are solutions with nested for loops. Is it possible to implement nested for loops into my code (which works), and if so, how would I code this? Thanks def reverse_vowels(word): vowels = "aeiou" string = list(word) ...
[ "Here's how I would do it. The answer does not involve nested loops, but has two sequential for loops.\ndef reverse(word, ref_vowels='aeiouAEIOU'):\n\n # hello Hank Hill --> hilla Honk Hell\n\n vowels = []\n\n ll = 0\n for letter in word:\n if letter in ref_vowels:\n vowels.append(word[ll])\n\...
[ 0 ]
[]
[]
[ "nested_loops", "python" ]
stackoverflow_0074352996_nested_loops_python.txt
Q: Running django tests with selenium in docker For executing tests I usually run a separate container with: docker-compose run --rm web /bin/bash Where web is a container with django. From a shell I execute py.test from time to time. In order to be able to reach selenium from a container with django and to allow th...
Running django tests with selenium in docker
For executing tests I usually run a separate container with: docker-compose run --rm web /bin/bash Where web is a container with django. From a shell I execute py.test from time to time. In order to be able to reach selenium from a container with django and to allow the browser from selenium container to reach django'...
[ "Here is how I do it. The basic problem is that docker-compose run will generate a different hostname (project_container_run_x) where x is hard to know for sure. I ended up just going off of ip address. I'm also ensuring DEBUG is False otherwise I get a bad request.\nI'm using StaticLiveServerTestCase like this:\ni...
[ 8, 4, 1, 0, 0 ]
[]
[]
[ "django", "python", "selenium" ]
stackoverflow_0032408429_django_python_selenium.txt
Q: Issue getting access_key and secret_access_key from Lambda function I am running a python script in a lambda function that retrieves both the access_key and secret_access_key. However when I use them later (to copy s3 data to redshift) I get the following error: "errorMessage": "S3ServiceException:The AWS Access ...
Issue getting access_key and secret_access_key from Lambda function
I am running a python script in a lambda function that retrieves both the access_key and secret_access_key. However when I use them later (to copy s3 data to redshift) I get the following error: "errorMessage": "S3ServiceException:The AWS Access Key Id you provided does not exist in our records.,Status 403,Error Inval...
[ "You do not need to call boto3 get_credentials(). In Lambda, you will have environment variables already available that you can use:\nhttps://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime\nIt contains:\nAWS_ACCESS_KEY_ID\nAWS_SECRET_ACCESS_KEY and\nAWS_SESSION_TOKEN\n...
[ 0 ]
[]
[]
[ "amazon_iam", "amazon_redshift", "amazon_s3", "aws_lambda", "python" ]
stackoverflow_0074351518_amazon_iam_amazon_redshift_amazon_s3_aws_lambda_python.txt
Q: Pycharm: Struggling to properly structure project folders First of all, the doc related to my problem is here but it's not that helpful I created a very simple project that I want to package with poetry. It contains: A library, named mylib, that contains a single package, tools, that contains a single module, list...
Pycharm: Struggling to properly structure project folders
First of all, the doc related to my problem is here but it's not that helpful I created a very simple project that I want to package with poetry. It contains: A library, named mylib, that contains a single package, tools, that contains a single module, lists.py According to Pycharm doc, the library is put under an src ...
[ "poetry defaults to expecting a flat layout (one without src). If you want to use a src layout then you have to tell poetry where to find each top-level package (it will discover subpackages from there on in. For example:\npackages = [\n { include = \"mylib\", from = \"src\" },\n]\n\nSee here for a more detailed...
[ 1 ]
[]
[]
[ "pycharm", "python", "python_poetry", "structure" ]
stackoverflow_0074352751_pycharm_python_python_poetry_structure.txt
Q: Does the number belong in the fibonacci sequence? A Ke-number is an integer 10≤n≤99 such that, if we start a Fibonacci sequence with its digits, the sequence contains n. For example, 47 is a Ke-number because the sequence starts like this: 4,7,11,18,29,47, coming to the number itself. I'm trying to define the recu...
Does the number belong in the fibonacci sequence?
A Ke-number is an integer 10≤n≤99 such that, if we start a Fibonacci sequence with its digits, the sequence contains n. For example, 47 is a Ke-number because the sequence starts like this: 4,7,11,18,29,47, coming to the number itself. I'm trying to define the recursive function ke_number that takes a two-digit integer...
[ "Recursive solution:\nTry it online!\ndef ke_number(n, a = None, b = None):\n if a is None:\n return ke_number(n, n // 10, n % 10)\n if a < n:\n return ke_number(n, b, a + b)\n return a == n\n\nprint(ke_number(47))\nprint(ke_number(46))\n\nOutput:\nTrue # for 47\nFalse # for 46\n\n\nWith...
[ 2, 1 ]
[]
[]
[ "function", "python", "recursion" ]
stackoverflow_0074352892_function_python_recursion.txt
Q: How to access contents of a SimpleArrayField in Python Django I am currently working with a form class in Django. I need to be able to access data contained in a SimpleArrayField. class SignUps(forms.Form) people = SimpleArrayField(forms.EmailField(), label="name") Let's say a user fills out the form with the na...
How to access contents of a SimpleArrayField in Python Django
I am currently working with a form class in Django. I need to be able to access data contained in a SimpleArrayField. class SignUps(forms.Form) people = SimpleArrayField(forms.EmailField(), label="name") Let's say a user fills out the form with the names "John Smith," "Jane Smith", "Mike Smith". I need to be able to ...
[ "The SimpleArrayField is intended to allow you to encode a list of values together as a single string (e.g. the value \"1,2,3,4\" could represent the array of integers [1,2,3,4]). You have specified that the values in the array are forms.EmailField(), so it's expecting that the value will be something like \"foo@ba...
[ 1 ]
[]
[]
[ "arrays", "django", "forms", "list", "python" ]
stackoverflow_0074353078_arrays_django_forms_list_python.txt
Q: Finding the average of column of 2-D list in python after removing the smallest element I am trying to make a function computeAverage which, given the table ratings and a column number, computes and returns a shuttle maker’s (column’s) average rating after after dropping the minimum rating. what i am doing is tra...
Finding the average of column of 2-D list in python after removing the smallest element
I am trying to make a function computeAverage which, given the table ratings and a column number, computes and returns a shuttle maker’s (column’s) average rating after after dropping the minimum rating. what i am doing is traversing through ratings list and print the average of all columns(after removing the smallest...
[ "Because for example in last list of ratings [80,90,75,65,75,60,80] there are two 75. So expression i.index(j) == _column will return True two times for each of 75, because i.index(j) will return the first index of list member, so for two 75 it will be 2\nYou can change in following your function to get expectecte...
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074352674_python.txt
Q: pymongo.errors.BulkWriteError: batch op errors occurred (MongoDB 3.4.2, pymongo 3.4.0, python 2.7.13) I am migrating several hundred million tweets of the format {'id_str': , 'created_at': , 'text': } from text files into MongoDB using pymongo. A collection is created for each user to store his/her tweets. The ins...
pymongo.errors.BulkWriteError: batch op errors occurred (MongoDB 3.4.2, pymongo 3.4.0, python 2.7.13)
I am migrating several hundred million tweets of the format {'id_str': , 'created_at': , 'text': } from text files into MongoDB using pymongo. A collection is created for each user to store his/her tweets. The insertion method I am using is insert_many(). It often runs into BulkWriteError. Traceback (most recent call l...
[ "sorry for the delay.\n1) I replicated the error. The following is close to the end of the mongod.log.\nI - [ftdc] Assertion: 13538:couldn't open [/proc/5774/stat] errno:24 Too many open\nfiles\nW FTDC [ftdc] Uncaught exception in 'Location13538: couldn't open [/proc/5774/stat] \nerrno:24 Too many open f...
[ 3, 2, 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0043073956_mongodb_pymongo_python.txt
Q: PySpark create dataframe with column type dictionary I want to create a simple pyspark dataframe with 1 column that is JSON. I created the schema for the groups column and created 1 row. schema = T.StructType([ T.StructField( 'groups', T.ArrayType( T.StructType([ ...
PySpark create dataframe with column type dictionary
I want to create a simple pyspark dataframe with 1 column that is JSON. I created the schema for the groups column and created 1 row. schema = T.StructType([ T.StructField( 'groups', T.ArrayType( T.StructType([ T.StructField("types", T.ArrayType(T.StringType(), Fa...
[ "This worked for me:\nfrom pyspark.sql import types as T\n\nschema = T.StructType([\n T.StructField('groups', \n T.ArrayType(\n T.StructType([\n T.StructField('label', T.StringType(), True), \n T.StructField('types', \n ...
[ 1, 0 ]
[]
[]
[ "apache_spark", "dataframe", "pyspark", "python" ]
stackoverflow_0074352694_apache_spark_dataframe_pyspark_python.txt
Q: web.py and lighttpd error: Connection refused, child exited: 1 I'm running web.py with lighttpd with very similar config to what's suggested on the website. When I run it with /etc/init.d/lighttpd start I get these errors in the logs: 2022-11-07 21:30:59: (gw_backend.c.528) connect /tmp/fastcgi.socket-0: Connectio...
web.py and lighttpd error: Connection refused, child exited: 1
I'm running web.py with lighttpd with very similar config to what's suggested on the website. When I run it with /etc/init.d/lighttpd start I get these errors in the logs: 2022-11-07 21:30:59: (gw_backend.c.528) connect /tmp/fastcgi.socket-0: Connection refused 2022-11-07 21:30:59: (gw_backend.c.371) child exited: 1 un...
[ "The program was failing because environment variables weren't being passed. I don't love the current resolution, and I plan on coming back to it later. For now, I set environment variables in lighttpd.conf. In /etc/lighttpd/lighttpd.conf (good links for reference webpy.org ongspxm.gitlab.io):\nfastcgi.server = (\n...
[ 0 ]
[]
[]
[ "lighttpd", "python", "web.py", "webserver" ]
stackoverflow_0074353296_lighttpd_python_web.py_webserver.txt
Q: What is the easiest way to read and plot coordinates from an airfoil coordinates file? I have downloaded an airfoil from Airfoil Tools. I want to load it into Python to plot it and make some calculations from the geometry. Edit: example file To read the file I've tried using this: with open(filename) as file: ...
What is the easiest way to read and plot coordinates from an airfoil coordinates file?
I have downloaded an airfoil from Airfoil Tools. I want to load it into Python to plot it and make some calculations from the geometry. Edit: example file To read the file I've tried using this: with open(filename) as file: lines = [line.rstrip() for line in file] However I encountered many problems because the da...
[ "You should really embrace Python libraries to perform certain tasks for which code is already tested and neatly packaged into a library. For your purposes (importing data, array manipulation and operations and plotting) libraries such as Pandas, Numpy and Matplotlib are very common and powerful, there are a bunch ...
[ 2 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074353195_list_python_string.txt
Q: How to works pickle dataframe inside I wonder how the module "pickle" save and load objects. I saved a file with a dataframe object on the disk, import pandas as pd import pickle df = pd.read_excel(r".\test.xlsx") with open("o.pkl", "wb") as file: pickle.dump(df, file) then I uninstalled pandas and tried to...
How to works pickle dataframe inside
I wonder how the module "pickle" save and load objects. I saved a file with a dataframe object on the disk, import pandas as pd import pickle df = pd.read_excel(r".\test.xlsx") with open("o.pkl", "wb") as file: pickle.dump(df, file) then I uninstalled pandas and tried to load the object dataframe from file, but ...
[ "Pickle by default will go and import the class.\nIn this case, if you do not have pandas installed when you run the second snippet, it won't work by default (see below for more info on that default behaviour).\nQuick primer on pickling\nEssentially, everything in Python is an instance of a class, in some shape or ...
[ 0, 0 ]
[]
[]
[ "pandas", "pickle", "python" ]
stackoverflow_0074352442_pandas_pickle_python.txt
Q: How to generate equation code representing tensors and their covariant derivatives for LaTeX and UnicodeMath using Python How to generate equation code representing tensors and their covariant derivatives for LaTeX and UnicodeMath using Python? (I'm not used to doing the whole "Answer your own question" thing. Fee...
How to generate equation code representing tensors and their covariant derivatives for LaTeX and UnicodeMath using Python
How to generate equation code representing tensors and their covariant derivatives for LaTeX and UnicodeMath using Python? (I'm not used to doing the whole "Answer your own question" thing. Feel free to edit this part so it's less horrible.)
[ "I have doing math regarding tensors and covariant derivatives lately and writing them out is a pain. As such, I made code to do it for me. You can tell it to output the code in LaTeX(like if you wanted to write a question on stackexchange or a research paper) or UnicodeMath(like if you wanted to manipulate the equ...
[ 2 ]
[]
[]
[ "equation", "latex", "python", "python_3.x", "unicode" ]
stackoverflow_0074353397_equation_latex_python_python_3.x_unicode.txt
Q: How to add quotes to dictionary keys with missing quotes in kafka messages I'm consuming messages from kafka which are in byte format. But the quotes in the messages are missing and I need to process the key and value separately. When I try "json.loads(msg.value().decode()", it throws error as below. What I have: ...
How to add quotes to dictionary keys with missing quotes in kafka messages
I'm consuming messages from kafka which are in byte format. But the quotes in the messages are missing and I need to process the key and value separately. When I try "json.loads(msg.value().decode()", it throws error as below. What I have: # a short example of the message msg.value() = b'{time:"2022-10-23 06:55:00.000...
[ "Your shown data isn't valid JSON. JSON keys also need quotes. E.g. \"time\" and \"name\". Thus why any parser will fail.\n\nIf you cannot edit how the data is coming, then you will need to to first strip outer {}, then split on unquoted commas, then split on (also unquoted) colons to get key-value pairs.\nOr, you ...
[ 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074345594_json_python.txt
Q: Variable don't get update on a for loop web scrapping selenium I'm traying to filter web data but my variables don't update! for i in range(len(links)): cupons = recupTahmin(links[i]) try: for j in range(len(cupons)): eventName = cupons[j].find_element(by=By.XPATH, value="//a[@class='ev...
Variable don't get update on a for loop web scrapping selenium
I'm traying to filter web data but my variables don't update! for i in range(len(links)): cupons = recupTahmin(links[i]) try: for j in range(len(cupons)): eventName = cupons[j].find_element(by=By.XPATH, value="//a[@class='eventName ']").text eventDate = cupons[j].find_element(by=...
[ "Looks like you have to make your XPath relative. This done by adding a dot . in front of the XPath expression, as following.\nWithout that dot driver will each time search for a match from the top of the page while when you use this dot making the XPath relative it will start searching from the current element, cu...
[ 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074353164_python_selenium_selenium_webdriver_xpath.txt
Q: Hexdump not displaying international characters I am trying to decode network data where I have set the password as pas$w0rd@1ħ213₹. I would like to see this entire password string in the output of hexdump but it seems its limited to ASCII range of characters only. Here is an example output using Linux' hexdump: h...
Hexdump not displaying international characters
I am trying to decode network data where I have set the password as pas$w0rd@1ħ213₹. I would like to see this entire password string in the output of hexdump but it seems its limited to ASCII range of characters only. Here is an example output using Linux' hexdump: hexdump hexd.hex -C -L 00000...
[ "As some people already have pointed out in the comments, this does not really work because a hexdump just gives you the bytes. For ASCII characters this is not a problem as they are one byte large, but all non-ASCII characters are larger than a byte and thus get split up when being displayed using a hexdump.\nYou ...
[ 0 ]
[]
[]
[ "hexdump", "python", "unicode" ]
stackoverflow_0074353256_hexdump_python_unicode.txt
Q: Trying to Understand this bit of Python code on the topic of decorators for some readability and searchability, here is the typed out code def counter(func): def wrapper(*args, **kwargs): wrapper.count += 1 return func (*args, **kwargs) wrapper.count = 0 return wrapper @counter def foo(...
Trying to Understand this bit of Python code on the topic of decorators
for some readability and searchability, here is the typed out code def counter(func): def wrapper(*args, **kwargs): wrapper.count += 1 return func (*args, **kwargs) wrapper.count = 0 return wrapper @counter def foo(): print('calling foo()') foo() foo() print('foo() was called {} times.'...
[ "In python, functions are first-class objects, which means that functions themselves are objects, and can be treated as such -- you can assign them to a variable, you can set attributes, etc.\nSo the line wrapper.count = 0 sets the count attribute for the wrapper object to the integer 0. The fact that wrapper is a ...
[ 1, 0 ]
[]
[]
[ "closures", "decorator", "python" ]
stackoverflow_0074352958_closures_decorator_python.txt
Q: How to plot uptime of an application using downtime and dates? In a CSV file, I have dates, downtime, and incident numbers of my application. Based on the below data I have to plot a graph of my application uptime using Python. Uptime for the last 7 days, Uptime for the last 30 days, and uptime for the last 90 da...
How to plot uptime of an application using downtime and dates?
In a CSV file, I have dates, downtime, and incident numbers of my application. Based on the below data I have to plot a graph of my application uptime using Python. Uptime for the last 7 days, Uptime for the last 30 days, and uptime for the last 90 days. date downtime(hrs) incident 2022-10-05 2 abc123 2022-1...
[ "One way of doing it is creating a second dataset to track uptime, complementary to your current dataset which tracks downtime.\nimport pandas as pd\nimport numpy as np\nfrom io import StringIO\nimport plotly.express as px\n\ndf = pd.read_csv(StringIO('''date downtime(hrs) incident\n2022-10-05 2 abc123\n2022...
[ 1, 0 ]
[]
[]
[ "matplotlib", "pandas", "plotly", "python", "python_3.8" ]
stackoverflow_0074353163_matplotlib_pandas_plotly_python_python_3.8.txt
Q: SQLAlchemy IN clause I'm trying to do this query in sqlalchemy SELECT id, name FROM user WHERE id IN (123, 456) I would like to bind the list [123, 456] at execution time. A: How about session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all() edit: Without the ORM, it would be session.execute( ...
SQLAlchemy IN clause
I'm trying to do this query in sqlalchemy SELECT id, name FROM user WHERE id IN (123, 456) I would like to bind the list [123, 456] at execution time.
[ "How about \nsession.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()\n\nedit: Without the ORM, it would be \nsession.execute(\n select(\n [MyUserTable.c.id, MyUserTable.c.name], \n MyUserTable.c.id.in_((123, 456))\n )\n).fetchall()\n\nselect() takes two parameters, the first one i...
[ 536, 187, 55, 15, 10, 2, 0 ]
[ "Just an addition to the answers above. \nIf you want to execute a SQL with an \"IN\" statement you could do this: \nids_list = [1,2,3]\nquery = \"SELECT id, name FROM user WHERE id IN %s\" \nargs = [(ids_list,)] # Don't forget the \"comma\", to force the tuple\nconn.execute(query, args)\n\nTwo points: \n\nThere i...
[ -2 ]
[ "in_clause", "python", "sqlalchemy" ]
stackoverflow_0008603088_in_clause_python_sqlalchemy.txt
Q: Pass array as parameter python I am trying to pass all the arrays such as molecularWeight(concentration,time) ` concentration_time = np.array([[0,83], [0.04,89], [0.06,95], [0.08,104], [0.1,1...
Pass array as parameter python
I am trying to pass all the arrays such as molecularWeight(concentration,time) ` concentration_time = np.array([[0,83], [0.04,89], [0.06,95], [0.08,104], [0.1,114], ...
[ "Lists in python do not support addition/subtraction/other mathematical operations.\nYou need to either use numpy, or explicitly do the operations within a list-comprehension (or loop) over the zipped element pairs...\nFor instance:\nimport numpy as np\n\ndef molecularWeight(c,t):\n c = np.array(c)\n t = np.a...
[ 0, 0 ]
[ "This is probably what you want, if I'm understanding correctly.\nYou are correctly giving the list to the function as an input, but not iterating over it correctly.\ndef molecularWeight(inputs):\n answers = []\n\n for c, t in inputs: \n answer = ((t/t0)-1)/c\n answers.append(answer)\n\n retu...
[ -1 ]
[ "arrays", "numpy", "pandas", "python" ]
stackoverflow_0074352839_arrays_numpy_pandas_python.txt
Q: Sending Float Values from Python to Arduino - Data in buffer but no values read I am trying to send float values from Python on Windows to an Arduino. The first problem I encounter is that I cannot view the serial monitor when I think I am sending data from my Python script. I have read online that this is becuase...
Sending Float Values from Python to Arduino - Data in buffer but no values read
I am trying to send float values from Python on Windows to an Arduino. The first problem I encounter is that I cannot view the serial monitor when I think I am sending data from my Python script. I have read online that this is becuase only one application can manage the port at once: https://forum.arduino.cc/t/serial-...
[ "Unfortunately, you aren't able to connect more than two devices to the serial connection. However, using Python you should be able to read a response from your arduino and then print that to the python Terminal (or a file) and take a look at that.\nThe easiest way to do that would be to use pySerial and either ser...
[ 0 ]
[]
[]
[ "arduino", "arduino_c++", "python", "serial_communication" ]
stackoverflow_0074350821_arduino_arduino_c++_python_serial_communication.txt
Q: Pandas - Expand Name & Value Columns I'm not sure what the technical name of the desired operation is, but I have data in the following format where my field names are a column and the corresponding values are a column. Currently, I filtered a new df to each field name and then concat all three back together which...
Pandas - Expand Name & Value Columns
I'm not sure what the technical name of the desired operation is, but I have data in the following format where my field names are a column and the corresponding values are a column. Currently, I filtered a new df to each field name and then concat all three back together which is clunky and not ideal (I'm sure there i...
[ "Looks like you want to do a .groupby() on the field names and collect the field values in a list:\ng = dummy_df.groupby('Field_Names')['Field_Values'].apply(list)\ndesired_output = pd.DataFrame({i:g.loc[i] for i in g.index.to_list()}\n\nUpdate: My mistake that was only part of the solution. I've updated the code a...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074353456_dataframe_pandas_python_python_3.x.txt
Q: Exponential Smoothing - how to choose alpha, beta, gamma I am trying to do exponential smoothing in python with statsmodels.tsa.api Exonential Smoothing and Holt (Triple and Double). I was wondering how to choose my smoothing_level, smoothing_slope and smoothing_seasonal (alpha, beta, gamma). So far I manually put...
Exponential Smoothing - how to choose alpha, beta, gamma
I am trying to do exponential smoothing in python with statsmodels.tsa.api Exonential Smoothing and Holt (Triple and Double). I was wondering how to choose my smoothing_level, smoothing_slope and smoothing_seasonal (alpha, beta, gamma). So far I manually put different values in the fit function, run the model and compa...
[ "Yes, you can find the \"correct\" alpha, beta, and gamma for your model using scipy.optimize.minimize.\nExample:\nimport pandas as pd\nfrom statsmodels.tsa.api import ExponentialSmoothing\nfrom scipy.optimize import minimize\n\nseries = pd.Series([10.21,23.01,10.97,14.59,29.4,16.8,18.86,38.9,18.61,24.2,48.9,22.78]...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0060250557_python.txt
Q: How to get the Name of the Class a Function is in with Python 3.11 So, i have a class like this: class Test: def test69(): print(classname) and That function (test69()) prints the Name of the Class that it is in. Like, a Function is in a Class, and the Function prints the Name of the Class that it is ...
How to get the Name of the Class a Function is in with Python 3.11
So, i have a class like this: class Test: def test69(): print(classname) and That function (test69()) prints the Name of the Class that it is in. Like, a Function is in a Class, and the Function prints the Name of the Class that it is in to the Console. I am working on Python 3.11, if that Helps any. Does ...
[ "It is available via the __class__ reference:\nclass Test:\n def test69():\n print(__class__.__name__)\n\n" ]
[ 1 ]
[]
[]
[ "class", "function", "python", "python_3.11" ]
stackoverflow_0074353515_class_function_python_python_3.11.txt
Q: Variable not being set in function I am trying to set a variable in a function to false. I have it so the parameters contain the variable I wish to set to false but it always returns as True. test1 = "item1" item1 = True britems = [test1] inventory = [] def itemtake(item,iflag,roomit): if iflag == True: pri...
Variable not being set in function
I am trying to set a variable in a function to false. I have it so the parameters contain the variable I wish to set to false but it always returns as True. test1 = "item1" item1 = True britems = [test1] inventory = [] def itemtake(item,iflag,roomit): if iflag == True: print("You take the", item) inventory.a...
[ "TL;DR: Return your boolean value from your function, and set it outside:\ndef itemtake(item,iflag,roomit):\n ...\n return iflag\n\n\n# Later, when you call the function:\nitem1 = itemtake(test1, item1, britems) \n# Now item1 is set to what you returned from the function\n\n\n\nThe global keyword denotes that...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074353431_python.txt
Q: Plotly: how to fill the background of a contour plot when the axes have been resized? I draw a contour plot of two sets of 2d points and wish to show the distribution of each sets side by side using the same scale for the axes. For plotting the distribution I use go.Histogram2dContour. The problem is that when I r...
Plotly: how to fill the background of a contour plot when the axes have been resized?
I draw a contour plot of two sets of 2d points and wish to show the distribution of each sets side by side using the same scale for the axes. For plotting the distribution I use go.Histogram2dContour. The problem is that when I rescale the axes, areas outside (what I assume was) the original contour plots are left bare...
[ "I think your best option would be:\nfig.update_layout(paper_bgcolor='white',\n plot_bgcolor='white')\n\nPlot\n\n" ]
[ 0 ]
[]
[]
[ "plotly", "plotly_python", "python" ]
stackoverflow_0074316948_plotly_plotly_python_python.txt
Q: How do I call the binary search 10 times? #I want to call the binary search 10 times (make the function run 10 times). Im supposed to that and then make a graph out of the result, which I know how to do. I just cant make the function run 10 times to get the information for the graph. import matplotlib.pyplot as p...
How do I call the binary search 10 times?
#I want to call the binary search 10 times (make the function run 10 times). Im supposed to that and then make a graph out of the result, which I know how to do. I just cant make the function run 10 times to get the information for the graph. import matplotlib.pyplot as plt import random import operator import sys de...
[ "To run some code a specific number of times, use a for-loop on a range:\nfor _ in range(10):\n binary_search(params)\n\n" ]
[ 1 ]
[]
[]
[ "binary_search", "python" ]
stackoverflow_0074353547_binary_search_python.txt
Q: Why is the client program not running when the localHost IP address is not used? I am writing a Bulletin Board as a client server program using socket programming. The server side code is as follows: import time from socketserver import * from socketserver import BaseRequestHandler, TCPServer SENDING_COOLDOWN = 0....
Why is the client program not running when the localHost IP address is not used?
I am writing a Bulletin Board as a client server program using socket programming. The server side code is as follows: import time from socketserver import * from socketserver import BaseRequestHandler, TCPServer SENDING_COOLDOWN = 0.3 BUFFER_SIZE = 4096 class EchoHandler(BaseRequestHandler): postSwitch = False ...
[ "I think there are a few misconceptions that I'll try to clear up.\nSpecifying ('', 16011) for the server address means that your listener should bind to port 16011 for all network interfaces on your machine. This includes the local loopback interface (at 127.0.0.1) as well as other network interfaces your machine ...
[ 0 ]
[]
[]
[ "python", "sockets", "socketserver" ]
stackoverflow_0074353334_python_sockets_socketserver.txt
Q: Adjust size and position of bounding boxes while keeping it somewhat centered I have a bunch of images with respective bounding box co-ordinates (x,y,w,h). Some of the bounding boxes are rectangular, so firstly I want to make them square while still centered on the region of interest. Using the following example o...
Adjust size and position of bounding boxes while keeping it somewhat centered
I have a bunch of images with respective bounding box co-ordinates (x,y,w,h). Some of the bounding boxes are rectangular, so firstly I want to make them square while still centered on the region of interest. Using the following example of an apple, with a bounding box on the stalk, I'd want to expand the box to a squar...
[ "I use this image to do the same effects:\n\n\nThe code and the comment(as description):\n#!/usr/bin/python3\n# 2017.11.25 17:10:34 CST\n# 2017.12.01 11:23:02 CST\n\nimport cv2\nimport numpy as np\n\n## Read and copy \nimg = cv2.imread(\"cat.jpg\")\ncanvas = img.copy()\n\n## set and crop the ROI \nx,y,w,h = bbox = ...
[ 4, 0, 0 ]
[]
[]
[ "image", "image_processing", "opencv", "python" ]
stackoverflow_0047580887_image_image_processing_opencv_python.txt
Q: "list index out of range" error when setting a string variable in for-loop instead of string directly? I am just trying to loop through certain letters in a json-message and then extract a new json-message out of it and it doesn't work but it should! json_message = ast.literal_eval( f"{ { 'B': [{'a': 'A', 'f': '...
"list index out of range" error when setting a string variable in for-loop instead of string directly?
I am just trying to loop through certain letters in a json-message and then extract a new json-message out of it and it doesn't work but it should! json_message = ast.literal_eval( f"{ { 'B': [{'a': 'A', 'f': '1', 'l': '0.00000000'}, {'a': 'B', 'f': '2', 'l': '0.00000000'}, {'a': 'C', 'f': '3', 'l': '0.00000000'}]} }...
[ "aaa includes the single quotes as part of the string itself. The line that doesn't work is equivalent to\nmsg = [y for y in json_message['B'] if y['a'] == \"'A'\"]\n\nYou can see this if you do print(repr(aaa)), which (for most objects) prints the code you would type to get that exact object. So print(repr('\"foo\...
[ 0 ]
[]
[]
[ "json", "list", "python" ]
stackoverflow_0074311108_json_list_python.txt
Q: python webscraping pricing and hidden elements with selenium part2 So this is a continuation of my previous question, which, with the help of Prophet, I was able to get it working. Until last week. Basically: on this website, each listing has a MLS number and I am trying to scrap that. Now the changes since the or...
python webscraping pricing and hidden elements with selenium part2
So this is a continuation of my previous question, which, with the help of Prophet, I was able to get it working. Until last week. Basically: on this website, each listing has a MLS number and I am trying to scrap that. Now the changes since the original question is mostly a new logic to handle a random popup via a try...
[ "You can try the next example:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nimport time\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--no-sandbox\")\noptions.add_argument('--disable-blink-features=AutomationCon...
[ 3, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074352926_python_selenium.txt
Q: Python: Convert 2D array to seperate arrays I have read in a numpy.ndarray that looks like this: [[1.4600e-01 2.9575e+00 6.1580e+02] [5.8600e-01 4.5070e+00 8.7480e+02]] Let's assume that this array I am reading will not always have a length of 2. (e.g. It could have a length of 1,3, 456, etc.) I would like to se...
Python: Convert 2D array to seperate arrays
I have read in a numpy.ndarray that looks like this: [[1.4600e-01 2.9575e+00 6.1580e+02] [5.8600e-01 4.5070e+00 8.7480e+02]] Let's assume that this array I am reading will not always have a length of 2. (e.g. It could have a length of 1,3, 456, etc.) I would like to separate this to two separate arrays that look like...
[ "Since you want to extract the rows, you can just index them. So suppose your array is stored in the variable x. x[0] will give you the first row: [1.4600e-01 2.9575e+00 6.1580e+02], while x[1] will give you the second row: [5.8600e-01 4.5070e+00 8.7480e+02], etc.\nYou can also iterate over the rows doing something...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074353543_python.txt
Q: Understanding pytest fixtures parametrization I have the following piece of code that works fine: import pytest class Person: def __init__(self, name, age=None, height=None, lots_of_properties=None): self.name = name if age is not None: self.age = age if height is not None:...
Understanding pytest fixtures parametrization
I have the following piece of code that works fine: import pytest class Person: def __init__(self, name, age=None, height=None, lots_of_properties=None): self.name = name if age is not None: self.age = age if height is not None: self.height = height if lots_o...
[ "To do this using @pytest.mark.parametrize, all you need is to define the parameters that are expected to be received in the fixture as function parameters and make sure to define them in the @pytest.mark.parametrize of the test. Like the parameters person_name and person_age.\nimport pytest\n\n\nclass Person:\n ...
[ 1, 0 ]
[]
[]
[ "fixtures", "pytest", "python" ]
stackoverflow_0074353269_fixtures_pytest_python.txt
Q: AWS SageMaker Jupyter Notebook: Images not Showing I'm currently trying to display some images using AWS SageMaker making use of its Jupyter Notebook app. However, all I'm trying to do is show the loaded images. I have written a function to do this but all I'm left with is the images index and image name on callin...
AWS SageMaker Jupyter Notebook: Images not Showing
I'm currently trying to display some images using AWS SageMaker making use of its Jupyter Notebook app. However, all I'm trying to do is show the loaded images. I have written a function to do this but all I'm left with is the images index and image name on calling the function. The function: import glob import random ...
[ "You have to add line to the first cell (or before the first plt.show() call) of the notebook:\n%matplotlib inline\n\nThis a is a magic function in IPython.\nAccording to documentation:\n\nWith this backend, the output of plotting commands is displayed inline\nwithin frontends like the Jupyter notebook, directly be...
[ 1 ]
[]
[]
[ "amazon_sagemaker", "jupyter_notebook", "python" ]
stackoverflow_0074352961_amazon_sagemaker_jupyter_notebook_python.txt
Q: How can I incorporate modulo arithmetic to allow my tiles to skip over other tiles? def main(): global FPSCLOCK, DISPLAYSURF, BASICFONT, RESET_SURF, RESET_RECT, NEW_SURF, NEW_RECT, SOLVE_SURF, SOLVE_RECT pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDT...
How can I incorporate modulo arithmetic to allow my tiles to skip over other tiles?
def main(): global FPSCLOCK, DISPLAYSURF, BASICFONT, RESET_SURF, RESET_RECT, NEW_SURF, NEW_RECT, SOLVE_SURF, SOLVE_RECT pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Slide Puzzle') BASICFONT = pygame.f...
[ "You don't really need the modulo to check for \"wrap around\" blank slots.\nBased on the comments in the function getStartingBoard():\n# returns [[1, 4, 7], [2, 5, 8], [3, 6, BLANK]]\n\nIt seems a board is a two dimensional list, where the cell at (x,y) would be board[y][x].\nSo say we have a board of some BOARD_W...
[ 0 ]
[]
[]
[ "loops", "modulo", "pygame", "python", "tiles_game" ]
stackoverflow_0074352849_loops_modulo_pygame_python_tiles_game.txt
Q: I want to create a back button in a tkinter program to recreate a filled form. How do I reopen a withdrawn root window? Is there a way I can reopen a withdrawn window? I know it is impossible with the destroy function, but I would imagine it would be possible to do so after using the the withdraw function. I creat...
I want to create a back button in a tkinter program to recreate a filled form. How do I reopen a withdrawn root window?
Is there a way I can reopen a withdrawn window? I know it is impossible with the destroy function, but I would imagine it would be possible to do so after using the the withdraw function. I created a root1 loop and a root2 loop which opens after the root1 is closed. I have a back button on the second window, and I am t...
[ "\nIs there a way I can reopen a withdrawn window?\n\nYou do that by calling the deiconify method.\nroot = tk.Tk()\nroot.withdraw()\n...\nroot.deiconify()\n\n" ]
[ 0 ]
[]
[]
[ "python", "root", "tkinter", "user_interface" ]
stackoverflow_0074353709_python_root_tkinter_user_interface.txt
Q: msal ConfidentialClientApplication Sucessfully Obtains Bearer Token; Authorization_RequestDenied Despite Full Privileges Granted Thank you in advance for your help. I am trying to access email messages for a specific email account for an organization that uses Microsoft Graph. The Python app I am creating needs to...
msal ConfidentialClientApplication Sucessfully Obtains Bearer Token; Authorization_RequestDenied Despite Full Privileges Granted
Thank you in advance for your help. I am trying to access email messages for a specific email account for an organization that uses Microsoft Graph. The Python app I am creating needs to read and forward email messages that are in this specific email account at "someuser@myorganization.com". (I previously successfully ...
[ "The problem is your trying to use the client credentials flow but all your permission are delegate permissions which aren't valid for that flow. You need to assign App permission and consent to them eg something like\n\nBy default this will give you access to every mailbox in the tenant as you mentioned you only w...
[ 1 ]
[]
[]
[ "microsoft_graph_api", "msal", "python" ]
stackoverflow_0074336738_microsoft_graph_api_msal_python.txt
Q: Parse word doc using python to find all words with _ I am looking to parse a word document in python and I want to load that in a DataFrame (DF) to print all the words in that DF that contains a _(underscore). Any sample code on this would be great? I have tried multiple doc libraries but all seem to have some iss...
Parse word doc using python to find all words with _
I am looking to parse a word document in python and I want to load that in a DataFrame (DF) to print all the words in that DF that contains a _(underscore). Any sample code on this would be great? I have tried multiple doc libraries but all seem to have some issue or the other to do it cleanly.
[ "This did the job:\nimport docx2python as docp\n\nimport re\n\ndoc = docp.docx2pthon('test.docx')\n\nbodyText = doc.text\n\nlist1 = re.findall('[a-zA-Z0-9_]asterisk symbol_[a-zA-Z0-9_]*', bodyText)\n\n" ]
[ 1 ]
[]
[]
[ "data_analysis", "pandas", "python" ]
stackoverflow_0074241229_data_analysis_pandas_python.txt
Q: creating a dictionary out of a file, and then somehow adding a 2nd value to one of the keys Say I got a file that is 1 hchen 50 2 vryzhikov 60 3 kmannock 74 4 vryzhikov 53 I make a dictionary of the names as keys and the scores as the values. If someone has 2 different scores, both scores would come out with that...
creating a dictionary out of a file, and then somehow adding a 2nd value to one of the keys
Say I got a file that is 1 hchen 50 2 vryzhikov 60 3 kmannock 74 4 vryzhikov 53 I make a dictionary of the names as keys and the scores as the values. If someone has 2 different scores, both scores would come out with that name. Something like this: hchen 50 vryzhikov 53 60 kmannock 74 infile= open("students.txt", "r...
[ "To open a file and read it to the dictionary you can use:\nout = {}\nwith open(\"students.txt\", \"r\") as f_in:\n for line in map(str.strip, f_in):\n if line == \"\":\n continue\n _, key, val = line.split()\n out.setdefault(key, []).append(val)\n\nprint(out)\n\nPrints:\n{\"hchen...
[ 1, 1, 0 ]
[]
[]
[ "dictionary", "file", "python" ]
stackoverflow_0074353152_dictionary_file_python.txt
Q: Python - Issues with Unicode String from API Call I'm using Python to call an API that returns the last name of some soccer players. One of the players has a "ć" in his name. When I call the endpoint, the name prints out with the unicode attached to it: >>> last_name = (json.dumps(response["response"][2]["player"]...
Python - Issues with Unicode String from API Call
I'm using Python to call an API that returns the last name of some soccer players. One of the players has a "ć" in his name. When I call the endpoint, the name prints out with the unicode attached to it: >>> last_name = (json.dumps(response["response"][2]["player"]["lastname"])) >>> print(last_name) "Mitrovi\u0107" ...
[ "Count the number of characters in your string & I'll bet you'll notice that the result of json is 13 characters:\n\"M-i-t-r-o-v-i-\\-u-0-1-0-7\", or \"Mitrovi\\\\u0107\"\nWhen you copy \"Mitrovi\\u0107\" you're coping 8 characters and the '\\u0107' is a single unicode character.\nThat would suggest the endpoint is...
[ 1, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0074353424_python_unicode.txt
Q: How to debug PySpark in local mode from test class I'm writing an aggregation in pysaprk To this project, I'm also adding test, where I create a session, put some data, and then run my aggregation, and check the results The code looks like as following: def mapper_convert_row(row): #... specific of business lo...
How to debug PySpark in local mode from test class
I'm writing an aggregation in pysaprk To this project, I'm also adding test, where I create a session, put some data, and then run my aggregation, and check the results The code looks like as following: def mapper_convert_row(row): #... specific of business logic code, eventually return one string value return ...
[ "pyspark is a conduit to the spark runtime that runs on the jvm / is written in scala. The connection is through py4j that provides a tcp-based socket from the python executable to the jvm. Unfortunately that means\n\nNo local debugging\n\nI'm no more happy about it than you. I might just write/maintain a parallel...
[ 0 ]
[]
[]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0060026318_apache_spark_pyspark_python.txt
Q: ECDSA signature verification mismatch I see a strange behaviour on ECDSA signature verification from the nodejs's secp256k1 package that sometimes fails the signature check. I use the following public key: 33 2E 16 0F 4C 24 1F 50 0B 5A 67 13 EB E1 52 52 D1 E2 BA A0 0A B9 7B 54 6E 5C CD 32 E4 FE 26 2A B5 51 5A BF...
ECDSA signature verification mismatch
I see a strange behaviour on ECDSA signature verification from the nodejs's secp256k1 package that sometimes fails the signature check. I use the following public key: 33 2E 16 0F 4C 24 1F 50 0B 5A 67 13 EB E1 52 52 D1 E2 BA A0 0A B9 7B 54 6E 5C CD 32 E4 FE 26 2A B5 51 5A BF CA EF D5 9D FD 35 AA 3A 4B 23 1C 7C 1A 2E...
[ "Bitcoin and the secp256k1 library use canonical signatures, while this constraint does not apply to the ecdsa library (and presumably not to X-CUBE-CRYPTOLIB).\nCanonical signature: In general, if (r, s) is a valid signature, then (r, -s) = (r, n - s) is also a valid signature (n: order of the base point). A canon...
[ 1 ]
[]
[]
[ "ecdsa", "node.js", "python", "secp256k1", "stm32" ]
stackoverflow_0074338846_ecdsa_node.js_python_secp256k1_stm32.txt
Q: .getboolean() NoOptionError I was trying to read a boolean value using config parser, It finds the section fine but it fails finding the option for some reason. configparser.NoOptionError: No option 'firsttime' in section: 'DEFAULT' In the INI i have: [DEFAULT] "firsttime" = "true" And in my main folder i have: ...
.getboolean() NoOptionError
I was trying to read a boolean value using config parser, It finds the section fine but it fails finding the option for some reason. configparser.NoOptionError: No option 'firsttime' in section: 'DEFAULT' In the INI i have: [DEFAULT] "firsttime" = "true" And in my main folder i have: import configparser config = con...
[ "ConfigParser() constructs the configuration parsing object, but doesn't read in any configuration file. To do that you have to invoke its read method, e.g. config.read(<your_config_file>). So if your config file was named example.ini, your code would look like:\nimport configparser\n\nconfig = configparser.ConfigP...
[ 0 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0074353536_configparser_python.txt
Q: How to quickly randomly update values in an np array? So I have a large 3D array (~ 2000 x 1000 x 1000). I want to update each value in the array to a random integer value between 1 and the current max such that all values = x are updated to the same random integer. I want to keep zeros unchanged. Also there can'...
How to quickly randomly update values in an np array?
So I have a large 3D array (~ 2000 x 1000 x 1000). I want to update each value in the array to a random integer value between 1 and the current max such that all values = x are updated to the same random integer. I want to keep zeros unchanged. Also there can't be any repeats, i.e. different values in the original arr...
[ "If your current values are in a continuous range, and you want another continuous range, you're in luck! At that point, you aren't really generating 2 billion random numbers: you're just permuting 9000 or so integers. For example:\narr = np.random.randint(9001, size=(10, 20, 20))\np = np.arange(arr.max(None) + 1)\...
[ 2, 1 ]
[]
[]
[ "arrays", "numpy", "python", "random" ]
stackoverflow_0074353105_arrays_numpy_python_random.txt
Q: python random mouse movements I would like to make random mouse movements in specified rectangle area (limited with coordinates x1, y1, x2, y2, x3, y3, x4, y4). Movements should be smooth, random, not just straight lines, go randomly up/down/left/right/etc for specified time duration. Could you give me a hand or...
python random mouse movements
I would like to make random mouse movements in specified rectangle area (limited with coordinates x1, y1, x2, y2, x3, y3, x4, y4). Movements should be smooth, random, not just straight lines, go randomly up/down/left/right/etc for specified time duration. Could you give me a hand or working example I can learn from? ...
[ "This code works on Windows only. You can experiment with the parameters inside the random_movement function to get better results. Good luck!\nimport ctypes\nimport random\nimport time\nimport math\n\ndef move_mouse(pos):\n x_pos, y_pos = pos\n screen_size = ctypes.windll.user32.GetSystemMetrics(0), ctypes.w...
[ 4, 1, 0, 0 ]
[ "For performing the movements there is a third-party package call PyUserInput that will allow you to control mouse or keyboard, and it is cross-platform. Install it using pip:\n$ pip install PyUserInput\n\nFor doing smooth movements you can try what 9000 proposes in his answer.\n" ]
[ -1 ]
[ "python", "python_2.7" ]
stackoverflow_0022784341_python_python_2.7.txt
Q: Python Copy Data From Source Files and Paste In The Most Recent Destination File in Subfolders I am trying to copy data from .xlsx source files and paste in the most recent corresponding .xlsm destination files in sub folders. The source files are all in one folder 'c:/users/me/afolder/sourcefolder/' with naming c...
Python Copy Data From Source Files and Paste In The Most Recent Destination File in Subfolders
I am trying to copy data from .xlsx source files and paste in the most recent corresponding .xlsm destination files in sub folders. The source files are all in one folder 'c:/users/me/afolder/sourcefolder/' with naming convention ABC_Report.xlsx, DEF_Report.xlsx etc The destination files are in sub folders and each sub...
[ "Here is a proposition based on your code:\nimport os\nfrom pathlib import Path\nimport openpyxl\nfrom openpyxl import load_workbook\n\ndef most_recent(a_dir, a_cat):\n lst_of_paths = list(Path(a_dir).glob(f\"{a_cat}/*.xlsm\"))\n return max(lst_of_paths, key=os.path.getctime)\n\nsrc_dir= r\"C:\\Users\\ohmandy...
[ 1 ]
[]
[]
[ "openpyxl", "python" ]
stackoverflow_0074351911_openpyxl_python.txt
Q: pandas.DataFrame - Set column width I want to set the column width equal to the max string length in that column, actually I want to adjust the width of the column. Here is my code: styler = df.style for column in df: column_length = df[column].astype(str).str.len().max() #styler.set_properties(subset=[co...
pandas.DataFrame - Set column width
I want to set the column width equal to the max string length in that column, actually I want to adjust the width of the column. Here is my code: styler = df.style for column in df: column_length = df[column].astype(str).str.len().max() #styler.set_properties(subset=[column], **{'width': '200px'}) styler.s...
[ "You can use pandas.options.display.max_colwidth = ... and set the max length.\nTo set the exported excel column width, see this stackoverflow page here.\n", "If anyone has the same problem here is the solution:\nwriter = pd.ExcelWriter('C:/Users/test.xlsx')\n\nstyler.to_excel(writer, sheet_name='report', index=...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074353197_dataframe_pandas_python.txt
Q: How do i reference a dictionary using a list as the key? So I want to reference a dictionary using a list as the key. import random gradePoints = {"A":4,"B":3,"C":2,"D":1,"F":0} courseList = ["CST 161","Mat 144","ENG 201","PSY 101","HIS 101"] gradeList = ["A","B","C","D","F"] creditList = [3,4] totalCredits=0 ...
How do i reference a dictionary using a list as the key?
So I want to reference a dictionary using a list as the key. import random gradePoints = {"A":4,"B":3,"C":2,"D":1,"F":0} courseList = ["CST 161","Mat 144","ENG 201","PSY 101","HIS 101"] gradeList = ["A","B","C","D","F"] creditList = [3,4] totalCredits=0 qualityPoints=0 print("Course..Grade..Value Per Course") for...
[ "Try:\nimport random\ngradePoints = {\"A\":4,\"B\":3,\"C\":2,\"D\":1,\"F\":0}\ncourseList = [\"CST 161\",\"Mat 144\",\"ENG 201\",\"PSY 101\",\"HIS 101\"]\ngradeList = [\"A\",\"B\",\"C\",\"D\",\"F\"]\ncreditList = [3,4]\ntotalCredits=0\nqualityPoints=0\nprint(\"Course..Grade..Value Per Course\")\ngpa = 0\nfor i in r...
[ 0 ]
[]
[]
[ "dictionary", "list", "loops", "python" ]
stackoverflow_0074353826_dictionary_list_loops_python.txt
Q: Regexp pattern to remove spaces next to brackets and replace any spaces between words/characters inside the brackets with single comma I have strings on similar format hello this is an example [ a b c ] hello this is another example [ cat bird dog elephant ] Which I want to transform to hello this is an ex...
Regexp pattern to remove spaces next to brackets and replace any spaces between words/characters inside the brackets with single comma
I have strings on similar format hello this is an example [ a b c ] hello this is another example [ cat bird dog elephant ] Which I want to transform to hello this is an example [a,b,c] hello this is another example [cat,bird,dog,elephant] But I don't understand how to create a regexp pattern that removes any s...
[ "You can use a negated character class with a single capture group, and then replace 1 or more spaces with a single comma in group 1 and wrap the result in between square brackets.\n\\[\\s*([^][]*?)\\s*]\n\nThe pattern matches:\n\n\\[ Match [\n\\s* Match optional leading whitespace chars\n( Capture group 1\n\n[^][]...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074342830_python_regex.txt
Q: How to set individual bar plot's color in matplotlib? I am trying to change the color of each individual bar in my figure here. The code that I used it down below. Instead of each bar changing to the color that I have set in c, there are several colors within each bar. I have included a screenshot of this. How can...
How to set individual bar plot's color in matplotlib?
I am trying to change the color of each individual bar in my figure here. The code that I used it down below. Instead of each bar changing to the color that I have set in c, there are several colors within each bar. I have included a screenshot of this. How can I fix this? Thank you all in advance! Clusters is just a c...
[ "Here is a script that does what you seem to be looking for based on your edits and comment.\nNote that I do not assume that all clusters have the same size in this context; if that is the case, this approach can be simplified.\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n# sample da...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074353324_matplotlib_python.txt