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: Pandas groupby cumulative sum start from 0 I have the following pandas DataFrame (without the last column): name day show-in-appointment previous-missed-appointments 0 Jack 2020/01/01 show 0 1 Jack 2020/01/02 no-show 0 2 Jill 2020/...
Pandas groupby cumulative sum start from 0
I have the following pandas DataFrame (without the last column): name day show-in-appointment previous-missed-appointments 0 Jack 2020/01/01 show 0 1 Jack 2020/01/02 no-show 0 2 Jill 2020/01/02 no-show 0 3 ...
[ "import pandas as pd\n\ndf.name = df.name.str.capitalize()\ndf['order'] = df.index\ndf.day = pd.to_datetime(df.day)\ndf['noshow'] = df['show-in-appointment'].map({'show': 0, 'no-show': 1})\ndf = df.sort_values(by=['name', 'day'])\ndf['previous-missed-appointments'] = df.groupby('name').noshow.cumsum()\ndf.loc[df.no...
[ 1, 0 ]
[]
[]
[ "cumsum", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074467226_cumsum_dataframe_group_by_pandas_python.txt
Q: Using variables in multiple python files I am trying to use variables created in one file and still use them in another file without having to run all of the code from the first file. Would I be better off saving the variables to a text file and calling the text file in my second python file? Ex. File #1 name = in...
Using variables in multiple python files
I am trying to use variables created in one file and still use them in another file without having to run all of the code from the first file. Would I be better off saving the variables to a text file and calling the text file in my second python file? Ex. File #1 name = input('What is your name') job = input('How do y...
[ "I think the answer depends on the nature of the variables you want to share between files.\nFor your case, I think a reasonable solution might be to import one module into another, e.g.\n# File1.py\n# ...\ndef name_input():\n name = input('What is your name')\n return name\n\ndef job_input():\n job = input('How...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074463992_python_python_3.x.txt
Q: Join a list of strings in python and wrap each string in quotation marks I've got: words = ['hello', 'world', 'you', 'look', 'nice'] I want to have: '"hello", "world", "you", "look", "nice"' What's the easiest way to do this with Python? A: Update 2021: With f strings in Python3 >>> words = ['hello', 'world', ...
Join a list of strings in python and wrap each string in quotation marks
I've got: words = ['hello', 'world', 'you', 'look', 'nice'] I want to have: '"hello", "world", "you", "look", "nice"' What's the easiest way to do this with Python?
[ "Update 2021: With f strings in Python3\n>>> words = ['hello', 'world', 'you', 'look', 'nice']\n>>> ', '.join(f'\"{w}\"' for w in words)\n'\"hello\", \"world\", \"you\", \"look\", \"nice\"'\n\nOriginal Answer (Supports Python 2.6+)\n>>> words = ['hello', 'world', 'you', 'look', 'nice']\n>>> ', '.join('\"{0}\"'.form...
[ 279, 69, 55, 8, 4, 1, 0, 0 ]
[ "# Python3 without for loop\nconc_str = \"'{}'\".format(\"','\".join(['a', 'b', 'c']))\nprint(conc_str) \n\n# \"'a', 'b', 'c'\"\n\n" ]
[ -1 ]
[ "list", "python", "string" ]
stackoverflow_0012007686_list_python_string.txt
Q: coverting list of string coordinates into list of coordinates without string I have a list flat_list =['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9', '53714.5,-50762.8'] How can I convert it into [[53295,-46564.2], [53522.6,-46528.4], [54792.9,-46184], [55258.7,-46...
coverting list of string coordinates into list of coordinates without string
I have a list flat_list =['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9', '53714.5,-50762.8'] How can I convert it into [[53295,-46564.2], [53522.6,-46528.4], [54792.9,-46184], [55258.7,-46512.9], [55429.4,-48356.9], [53714.5,-50762.8]] I tried l = [i.strip("'") for i i...
[ "Why complicate things?\nWithout any builtins such as map and itertools, this approach with a nested list comprehension should be a relatively simple and efficient one.\nflat_list = ['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9',\n '53714.5,-50762.8']\n\n...
[ 6, 2, 0 ]
[]
[]
[ "arraylist", "list", "python", "python_3.x" ]
stackoverflow_0074467682_arraylist_list_python_python_3.x.txt
Q: Check if shape is already in space (overlapping issue) So I’m doing a tic tac toe using the the CMU course in python and I want to figure out If there is already a shape either circle or rectangle. How can you stop your mouse when you click on a box/space that already has a shape inside. If you look in the picture...
Check if shape is already in space (overlapping issue)
So I’m doing a tic tac toe using the the CMU course in python and I want to figure out If there is already a shape either circle or rectangle. How can you stop your mouse when you click on a box/space that already has a shape inside. If you look in the picture. I clicked on the square already there and it put a red cir...
[ "From what I can tell by the image you have attached, you are effectively using a dictionary for storing the game state. The keys are tuples with x and y coordinates, and values are string \"red\", \"blue\" or \"\" (empty)\nSo, regarding the question you pose, you may want something like this:\ndef click(x, y, colo...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074467706_python.txt
Q: How to prevent auto-start of animation created using the Player class that subclasses FuncAnimation? I'm using the Player class as found at Managing dynamic plotting in matplotlib Animation module to create an animation and can't figure out how to modify the initial values to prevent the animation from starting au...
How to prevent auto-start of animation created using the Player class that subclasses FuncAnimation?
I'm using the Player class as found at Managing dynamic plotting in matplotlib Animation module to create an animation and can't figure out how to modify the initial values to prevent the animation from starting automatically. Below is the code for Player, along with a simple example, where I graph the unit circle and ...
[ "You could initiate your self.runs variable to False and modify the play methods such that it yields the current position when self.runs=False:\ndef play(self):\n while not self.runs:\n yield self.i\n while self.runs:\n self.i = self.i+self.forwards-(not self.forwards)\n if self.i > self....
[ 1 ]
[]
[]
[ "animation", "matplotlib", "python" ]
stackoverflow_0074462964_animation_matplotlib_python.txt
Q: Can we make the values in pandas.pivot_table() a count of column? pd.pivot_table(df, index = col1, columns = col2, value = ?) I want the values to be the count of values in col 1.The values in col 1 are all strings. I basically want to imitate what is happening in the excel file pictured below Id be open to using...
Can we make the values in pandas.pivot_table() a count of column?
pd.pivot_table(df, index = col1, columns = col2, value = ?) I want the values to be the count of values in col 1.The values in col 1 are all strings. I basically want to imitate what is happening in the excel file pictured below Id be open to using other functions than pd.pivot_table() if that would make things easier...
[ "Try to use pd.crosstab. To make the total columns use .sum() (with proper axis=)\nx = pd.crosstab(df.Col1, df.Col2)\nx[\"Grand Total\"] = x.sum(axis=1)\nx = pd.concat([x, x.sum().to_frame().rename(columns={0: \"Grand Total\"}).T])\nx.columns.name, x.index.name = None, None\n\nprint(x.to_markdown())\n\nPrints:\n\n\...
[ 2 ]
[]
[]
[ "pandas", "pivot", "python" ]
stackoverflow_0074467730_pandas_pivot_python.txt
Q: How to use a for loop to print every other item in a list? I have a list named "ul_children", I need to use a for loop to print every other item in that list starting with the second item or the index[1]. I am new to for loops in python and I am struggling with this. I have tried a few different things I thought w...
How to use a for loop to print every other item in a list?
I have a list named "ul_children", I need to use a for loop to print every other item in that list starting with the second item or the index[1]. I am new to for loops in python and I am struggling with this. I have tried a few different things I thought would work, but I have been unsuccessful so far. Any help would b...
[ "You can do it like this:\nul_children = [\"r\",\"a\",\"t\",\"o\",\"n\"]\n\nfor i in ul_children[1:]:\n\n print(i)\n\n" ]
[ 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074467827_for_loop_python.txt
Q: How to compare different dataframes by column and row? I have two csv files with 200 columns each. The two files have the exact same numbers in rows and columns. I want to compare each columns separately. The idea would be to compare column 1 value of file "a" to column 1 value of file "b" and check the difference...
How to compare different dataframes by column and row?
I have two csv files with 200 columns each. The two files have the exact same numbers in rows and columns. I want to compare each columns separately. The idea would be to compare column 1 value of file "a" to column 1 value of file "b" and check the difference and so on for all the numbers in the column (there are 100 ...
[ "I suggest you use the iloc attribute of a DataFrame:\nimport pandas as pd\n\ndk = pd.read_csv('C:/Users/D/1_top_a.csv', sep=',', header=None)\ndk = dk.dropna(how='all')\ndk = dk.dropna(how='all', axis=1)\nprint(dk.head())\n\ndl = pd.read_csv('C:/Users/D/1_top_b.csv', sep=',', header=None)\ndl = dl.dropna(how='all'...
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "pandas", "python" ]
stackoverflow_0074467738_dataframe_for_loop_pandas_python.txt
Q: Manipulate Dataframe Lets say I'm working on a dataset: # dummy dataset import pandas as pd data = pd.DataFrame({"Name_id" : ["John","Deep","Julia","John","Sandy",'Deep'], "Month_id" : ["December","March","May","April","May","July"], "Colour_id" : ["Red",'Purple','Green','...
Manipulate Dataframe
Lets say I'm working on a dataset: # dummy dataset import pandas as pd data = pd.DataFrame({"Name_id" : ["John","Deep","Julia","John","Sandy",'Deep'], "Month_id" : ["December","March","May","April","May","July"], "Colour_id" : ["Red",'Purple','Green','Black','Yellow','Orange']}...
[ "Probably you should try pivot\ndata['Rowid'] = data.groupby('Name_id').cumcount()+1\nd = data.pivot(index='Name_id', columns='Rowid',values = ['Month_id','Colour_id'])\nd.reset_index(inplace=True)\nd.columns = ['Name_id','Month_id1', 'Colour_id1', 'Month_id2', 'Colour_id2']\n\nwhich gives\n Name_id Month_id1 Colo...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074467693_pandas_python.txt
Q: I can't find a method to prevent my program slowing down as it loads more sprites python I have created a simple simulation to show evolution. It works through a simuple window that contains many squares representing single-celled organisms. The screen looks like this: The single-celled organisms (dubbed amoebae ...
I can't find a method to prevent my program slowing down as it loads more sprites python
I have created a simple simulation to show evolution. It works through a simuple window that contains many squares representing single-celled organisms. The screen looks like this: The single-celled organisms (dubbed amoebae for conciseness) move around randomly. If they collide with another amoebae they produce an of...
[ "Too many nested loops and unneeded data structures. I did some cleanup and it's faster now. And it seems that the mutation constant was far to high. I changed the value from 254 to 25.\nimport pygame\nimport random\nimport time\nimport itertools\n\nfrom pygame.locals import (\n QUIT\n)\n\nSCREEN_WIDTH = 500\nSC...
[ 2 ]
[]
[]
[ "lag", "oop", "pygame", "python", "simulation" ]
stackoverflow_0074466865_lag_oop_pygame_python_simulation.txt
Q: Find all objects of a certain class that do not have any active links with other objects I have a class A which is used as a Foreign Key in many other classes. class A(models.Model): pass class B(models.Model): a: A = ForeignKey(A) class C(models.Model): other_name: A = ForeignKey(A) Now I have a database...
Find all objects of a certain class that do not have any active links with other objects
I have a class A which is used as a Foreign Key in many other classes. class A(models.Model): pass class B(models.Model): a: A = ForeignKey(A) class C(models.Model): other_name: A = ForeignKey(A) Now I have a database with a huge table of A objects and many classes like B and C who reference A (say potentially...
[ "You can filter with:\nA.objects.filter(b=None, c=None).delete()\nThis will make proper JOINs and thus determine the items in a single querying, without having to fetch all other model records from the database.\nBut this will be expensive anyway, since the triggers are done by Django that will thus \"collect\" all...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074467841_django_python.txt
Q: Python Pandas: Joining Dataframes I have table A and Table B. I want to join them to get Table C. I tried the following code. But it is not giving me the result that I want. C = pd.merge(A, B, how = 'inner', left_on = ['ID1', 'ID2', 'ID3'], right_on = ['IDA', 'IDB', 'IDC']) Table A ID1 ID2 ID3 Color Flag A 1 1 ...
Python Pandas: Joining Dataframes
I have table A and Table B. I want to join them to get Table C. I tried the following code. But it is not giving me the result that I want. C = pd.merge(A, B, how = 'inner', left_on = ['ID1', 'ID2', 'ID3'], right_on = ['IDA', 'IDB', 'IDC']) Table A ID1 ID2 ID3 Color Flag A 1 1 White Y B 1 2 Black Y A 1 3 G...
[ "here is one way to do it\n# do a left merge and rop the null rows\nout=(pd.merge(df, df2, \n how = 'left', \n left_on = ['ID1', 'ID2', 'ID3'], \n right_on = ['IDA', 'IDB', 'IDC'])\n .dropna()\n .drop(columns=['IDA', 'IDB','IDC']))\n\n\nID1 ID2 ID3 Color Flag\n0 A 1 1 ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074467734_dataframe_pandas_python.txt
Q: How to create list of urls from csv file to iterate? I am working on a webscrape code, he work fine, now I want replace the url, with a CSV file who containt thousand of url, it's like this : url1 url2 url3 . . .urlX my first line web scrape code is a basic : from bs4 import BeautifulSoup import requests from csv...
How to create list of urls from csv file to iterate?
I am working on a webscrape code, he work fine, now I want replace the url, with a CSV file who containt thousand of url, it's like this : url1 url2 url3 . . .urlX my first line web scrape code is a basic : from bs4 import BeautifulSoup import requests from csv import writer url= "HERE THE URL FROM EACH LINE OF THE C...
[ "If this is just a list of urls, you don't really need the csv module. But here is a solution assuming the url is in column 0 of the file. You want a csv reader, not writer, and then its a simple case of iterating the rows and taking action.\nfrom bs4 import BeautifulSoup\nimport requests\nimport csv\n\nwith open(\...
[ 2 ]
[]
[]
[ "list", "loops", "python", "web_scraping" ]
stackoverflow_0074467955_list_loops_python_web_scraping.txt
Q: Setting up env variables in github actions workflow yml So I'm trying to set up an env variable, and print it to see if it actually is set up. Bellow is only an example on how I m trying to set the env vars, in realiy I'm trying to set secrets as env variables but it dosent work. I use the env variables in python ...
Setting up env variables in github actions workflow yml
So I'm trying to set up an env variable, and print it to see if it actually is set up. Bellow is only an example on how I m trying to set the env vars, in realiy I'm trying to set secrets as env variables but it dosent work. I use the env variables in python scripts, but they are not being set os.getenv("key") returns ...
[ "You're setting two environment variables (one globally, and one specific to the \"Setup env vars\" task. In both cases, they're working correctly: if you were to modify your \"Setup env vars\" task like this...\n steps:\n - name: \"Setup env vars\"\n run: |\n echo \"$SERVICE_NAME\"\n echo ...
[ 0 ]
[]
[]
[ "github_actions", "python" ]
stackoverflow_0074467400_github_actions_python.txt
Q: How to multiply a tensor row-wise by a vector in PyTorch? When I have a tensor m of shape [12, 10] and a vector s of scalars with shape [12], how can I multiply each row of m with the corresponding scalar in s? A: You need to add a corresponding singleton dimension: m * s[:, None] s[:, None] has size of (12, 1)...
How to multiply a tensor row-wise by a vector in PyTorch?
When I have a tensor m of shape [12, 10] and a vector s of scalars with shape [12], how can I multiply each row of m with the corresponding scalar in s?
[ "You need to add a corresponding singleton dimension:\nm * s[:, None]\n\ns[:, None] has size of (12, 1) when multiplying a (12, 10) tensor by a (12, 1) tensor pytorch knows to broadcast s along the second singleton dimension and perform the \"element-wise\" product correctly.\n", "You can broadcast a vector to a ...
[ 32, 3, 0, 0 ]
[]
[]
[ "python", "pytorch", "scalar", "tensor" ]
stackoverflow_0053987906_python_pytorch_scalar_tensor.txt
Q: Return variables on the same line - Python I've got a for loop which iterates through three elements in a list: ["123", "456", "789"]. So, with the first iteration, it will perform a calculation on each digit within the first element, then add the digits back up. This repeats for the other two elements. The output...
Return variables on the same line - Python
I've got a for loop which iterates through three elements in a list: ["123", "456", "789"]. So, with the first iteration, it will perform a calculation on each digit within the first element, then add the digits back up. This repeats for the other two elements. The outputs are then converted into strings and outputted....
[ "you can append each variable on a list using a_list.append('variable') and print it using ' '.join(a_list)\nwhenever needed.\n", "The problem is that you are creating the list and returning the result inside the for instead of outside. You only make a single calculation and return.\ndef foo(digits):\n results...
[ 0, 0 ]
[]
[]
[ "list", "python", "return" ]
stackoverflow_0074467867_list_python_return.txt
Q: Can i rewrite this code to make it work faster? Is it actually possible to make this run faster? I need to get half of all possible grids (all elements can be either -1 or 1) of size 4*Lx (for counting energies in Ising model). def get_grid(Lx): a = list() count = 0 t = list(product([1,-1], repeat=Lx))...
Can i rewrite this code to make it work faster?
Is it actually possible to make this run faster? I need to get half of all possible grids (all elements can be either -1 or 1) of size 4*Lx (for counting energies in Ising model). def get_grid(Lx): a = list() count = 0 t = list(product([1,-1], repeat=Lx)) for i in range(len(t)): for j in range(l...
[ "First of all, Numba does not like lists. If you want an efficient code, then you need to operate on arrays (except when you really do not know the size at runtime and estimating it is hard/slow). Here the size of the output array is already known so it is better to preallocate it and then fill it. Numba does not l...
[ 2 ]
[]
[]
[ "loops", "performance", "python" ]
stackoverflow_0074465691_loops_performance_python.txt
Q: How to extract and store x, z coordinates associated to a specific y coordinate on a UnstructuredGrid in Python? Starting from an image I did some processing (like thresholding) and I obtained its representation as UnstructuredGrid using VTK and PyVista. I would like to create an array of shape (n, 3) filled with ...
How to extract and store x, z coordinates associated to a specific y coordinate on a UnstructuredGrid in Python?
Starting from an image I did some processing (like thresholding) and I obtained its representation as UnstructuredGrid using VTK and PyVista. I would like to create an array of shape (n, 3) filled with x, y, z coordinates associated with a specific y coordinate of which I know the value, but not the position of corresp...
[ "Most of the tooling you need is the UnstructuredGrid.extract_cells() filter, which lets you select cells based on a boolean mask array or integer indices. Building such a mask is fairly easy if you compare the y coordinates of cell centers with the specific value you are looking for:\nimport pyvista as pv\nfrom py...
[ 0 ]
[]
[]
[ "coordinates", "python", "pyvista", "vtk" ]
stackoverflow_0074428715_coordinates_python_pyvista_vtk.txt
Q: RuntimeError: main thread is not in main loop When I call self.client = ThreadedClient() in my Python program, I get the error "RuntimeError: main thread is not in main loop" I have already done some googling, but I am making an error somehow ... Can someone please help me out? Full error: Exception in thre...
RuntimeError: main thread is not in main loop
When I call self.client = ThreadedClient() in my Python program, I get the error "RuntimeError: main thread is not in main loop" I have already done some googling, but I am making an error somehow ... Can someone please help me out? Full error: Exception in thread Thread-1: Traceback (most recent call last):...
[ "You're running your main GUI loop in a thread besides the main thread. You cannot do this.\nThe docs mention offhandedly in a few places that Tkinter is not quite thread safe, but as far as I know, never quite come out and say that you can only talk to Tk from the main thread. The reason is that the truth is somew...
[ 55, 19, 17, 4, 2, 2, 1, 0 ]
[]
[]
[ "multithreading", "python", "tkinter" ]
stackoverflow_0014694408_multithreading_python_tkinter.txt
Q: how to install Mediapipe when calling Python script with Streamlit? I am trying to call a python script using Streamlit. I have a requirements.txt file that installs the libraries used in the script: ... mediapipe==0.8.10.1 ... All the libraries successfully download but the Mediapipe library does not install no ...
how to install Mediapipe when calling Python script with Streamlit?
I am trying to call a python script using Streamlit. I have a requirements.txt file that installs the libraries used in the script: ... mediapipe==0.8.10.1 ... All the libraries successfully download but the Mediapipe library does not install no matter what I do and gives me this error: ERROR: No matching distribution...
[ "This has happened to me as well. I fixed by using a VPN(Try https://1.1.1.1).\nIronically that package was getting blocked by my ISP.\n" ]
[ 0 ]
[]
[]
[ "mediapipe", "python", "streamlit" ]
stackoverflow_0074468009_mediapipe_python_streamlit.txt
Q: Control after changing format date Pandas I want to control a date after changing date format df["Date start"] = pd.to_datetime(df["Date start"]) df["Date start"] = df["Date start"].dt.strftime('%d/%m/%Y') df = df[df["Date start"] > "01/01/2022"] But I do have an error like this UserWarning: Parsing '16/04/2012' ...
Control after changing format date Pandas
I want to control a date after changing date format df["Date start"] = pd.to_datetime(df["Date start"]) df["Date start"] = df["Date start"].dt.strftime('%d/%m/%Y') df = df[df["Date start"] > "01/01/2022"] But I do have an error like this UserWarning: Parsing '16/04/2012' in DD/MM/YYYY format. Provide format or specify...
[ "for date comparison, make the date as yyyy-mm-dd (without or without hyphens). This ensures the dates being compared are in chronological order\nwhen you have day as first in a date when comparing. it will group all months and all year with the day 1, before day 2 and so on\n# inline conversion of date to yyyy-mm-...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074468077_pandas_python.txt
Q: sqlite error: no such column: (and whatever the arguement is) so i am making a discord bot with using sqlite and discord.py thats the command that gives the error: @bot.command() @commands.has_permissions(administrator=True) async def set_ip(ctx, arg=None): if arg == None: await ctx.send("You must type...
sqlite error: no such column: (and whatever the arguement is)
so i am making a discord bot with using sqlite and discord.py thats the command that gives the error: @bot.command() @commands.has_permissions(administrator=True) async def set_ip(ctx, arg=None): if arg == None: await ctx.send("You must type the IP adress next to the command!") elif arg.endswith('.atern...
[ "You are passing the column name as a string:\nconn.execute(f'''INSERT INTO guild_{id} (\"ip\") VALUES ({arg})''')\n\nshould be:\nconn.execute(f'''INSERT INTO guild_{id} (ip) VALUES ({arg})''')\n\n" ]
[ 0 ]
[]
[]
[ "discord.py", "python", "python_3.x", "sql", "sqlite" ]
stackoverflow_0074467950_discord.py_python_python_3.x_sql_sqlite.txt
Q: Converting json data in dataframe I'm analyzing club participation. Getting data as json through url request. This is the json I get and load with json_loads: df = [{"club_id":"1234", "sum_totalparticipation":227, "level":1, "idsubdatatable":1229, "segment": "club_id==1234;eventName==national%2520participation,eve...
Converting json data in dataframe
I'm analyzing club participation. Getting data as json through url request. This is the json I get and load with json_loads: df = [{"club_id":"1234", "sum_totalparticipation":227, "level":1, "idsubdatatable":1229, "segment": "club_id==1234;eventName==national%2520participation,eventName==local%2520partipation,eventName...
[ "If you want to see the details of the subtable field (which is another list of dictionaries itself), then you can do the following:\n...\n \ndf = pd.DataFrame(*data)\n\nfor i in range(len(df)):\n df.loc[i, 'label'] = df.loc[i, 'subtable']['label']\n df.loc[i, 'sum_events_totalevents'] = df.loc[i, 'subtabl...
[ 0 ]
[ "The data you show us after your json.load looks quite dirty, some quotes look missing, especially after \"segment\":\"club_id==1234\", and the ; separator at the beginning does not fit the keys separator inside a dict.\nNonetheless, let's consider the data you get is supposed to look like this (a list of dictionar...
[ -1 ]
[ "json", "pandas", "python" ]
stackoverflow_0074467178_json_pandas_python.txt
Q: Pythona, create 2D Numpy array and append data vertically I have an SQL query that creates an array with 9 entries, I want to create a table with Numpy and append data as rows The following code gives me an error ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 d...
Pythona, create 2D Numpy array and append data vertically
I have an SQL query that creates an array with 9 entries, I want to create a table with Numpy and append data as rows The following code gives me an error ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s) How can...
[]
[]
[ "Turns out I cannot simply append SQL row as a numpy array, had to fix it this way:\ntable_array = numpy.append(\n table_array, numpy.array([[row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]]]), axis=0)\n\n", "Don't repeatedly append to a numpy array in a loop. Since numpy arrays are cont...
[ -1, -1 ]
[ "python", "sql" ]
stackoverflow_0074467833_python_sql.txt
Q: Strip file names from files and open recursively? Saving previous strings? - PYTHON I have a question about reading in a .txt rile and taking the string from inside to be used later on in the code. If I have a file called 'file0.txt' and it contains: file1.txt file2.txt The rest of the files either contain more s...
Strip file names from files and open recursively? Saving previous strings? - PYTHON
I have a question about reading in a .txt rile and taking the string from inside to be used later on in the code. If I have a file called 'file0.txt' and it contains: file1.txt file2.txt The rest of the files either contain more string file names or are empty. How can I save both of these strings for later use. What ...
[ "Using read() or readlines() will help. e.g.\ninfile = open(file, 'r')\nlines = infile.readlines()\nprint list(lines)\n\ngives\n['file1.txt\\n', 'file2.txt\\n']\n\nor \ninfile = open(file, 'r')\nlines = infile.read()\nprint list(lines.split('\\n'))\n\ngives\n['file1.txt', 'file2.txt']\n\n", "Readline only gets on...
[ 1, 0, 0, 0 ]
[]
[]
[ "function", "python", "recursion" ]
stackoverflow_0022009254_function_python_recursion.txt
Q: How to run Python commands in VS Code Terminal I have installed latest Python Latest Python 3 (python-3.11.0-amd64) and latest VS Code (VSCodeUserSetup-x64-1.73.1). I also installed the Python Extension for Visual Studio Code. I have selected the interpreter as: But I am not able to run any Python Command in the ...
How to run Python commands in VS Code Terminal
I have installed latest Python Latest Python 3 (python-3.11.0-amd64) and latest VS Code (VSCodeUserSetup-x64-1.73.1). I also installed the Python Extension for Visual Studio Code. I have selected the interpreter as: But I am not able to run any Python Command in the terminal even as an administrator. No error and no c...
[ "Has Python been added to your path? There's a checkbox for this in the dialogue when you install it, but if you didn't check that box, then its possible that Python hasn't been added to your path.\nsystem properties\n\nedit path\n", "Have you checked python path?\n\nsystem properties--->environment variables--->...
[ 2, 1 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074468107_python_visual_studio_code.txt
Q: xarray mask outside list of coordinates I have an Xarray DataArray with values over rectangular 2D grid, and a list of points (pairs of coordinate values) from an arbitrary subset of that grid contained in a pandas Dataframe. How do I mask out values (i.e. set equal to NaN) in the DataArray whose grid coordinates ...
xarray mask outside list of coordinates
I have an Xarray DataArray with values over rectangular 2D grid, and a list of points (pairs of coordinate values) from an arbitrary subset of that grid contained in a pandas Dataframe. How do I mask out values (i.e. set equal to NaN) in the DataArray whose grid coordinates do not appear in the list points? e.g. consid...
[ "You can convert the dataframe to an xarray object by setting the x and y coordinates as the index, then using to_xarray. since you don't have any data left, I'll just assign a \"flag\" variable:\nIn [20]: flag = (\n ...: coords.assign(flag=1)\n ...: .set_index([\"x_coord\", \"y_coord\"])\n ...: ...
[ 1 ]
[]
[]
[ "netcdf", "python", "python_xarray" ]
stackoverflow_0074467216_netcdf_python_python_xarray.txt
Q: Bar plot not appearing normally using df.plot.bar() I have the following code. I am trying to loop through variables (dataframe columns) and create bar plots. I have attached below an example of a graph for the column newerdf['age']. I believe this should produce 3 bars (one for each option - male (value = 1), fem...
Bar plot not appearing normally using df.plot.bar()
I have the following code. I am trying to loop through variables (dataframe columns) and create bar plots. I have attached below an example of a graph for the column newerdf['age']. I believe this should produce 3 bars (one for each option - male (value = 1), female (value = 2), other(value = 3)). However, the graph be...
[ "The data are not grouped into categories yet, so a value count is needed before calling the plotting method:\nfor var in listedvariables: \n ax = newerdf[var].value_counts().plot.bar(figsize=(30,20))\n ax.tick_params(axis='x', labelsize=40)\n ax.tick_params(axis='y', labelsize=40)\n plt.tight_layout()\...
[ 1 ]
[]
[]
[ "bar_chart", "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074466260_bar_chart_dataframe_jupyter_notebook_pandas_python.txt
Q: If statement in for loop, index out of range with one additional condition? I'm trying to create an if statement in a for loop to look at an element in a list and compare it to the next element with enumerate(). arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] liste = [] for idx,i in enumerate(ar...
If statement in for loop, index out of range with one additional condition?
I'm trying to create an if statement in a for loop to look at an element in a list and compare it to the next element with enumerate(). arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"] liste = [] for idx,i in enumerate(arr): if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or (i == 'SOUTH' and arr[idx+...
[ "When you reach your last element, idx+1 is out of bounds for the array. You would want to keep that in mind in your logic. One way to resolve is to enumerate over the length-1 of the array so it is never trying to access an index out of bounds.\nFor example:\narr = [\"NORTH\", \"SOUTH\", \"SOUTH\", \"EAST\", \"WES...
[ 1, 0, 0 ]
[]
[]
[ "enumerate", "for_loop", "list", "python" ]
stackoverflow_0074468140_enumerate_for_loop_list_python.txt
Q: Convert a number to Excel’s base 26 OK, I'm stuck on something seemingly simple. I am trying to convert a number to base 26 (ie. 3 = C, 27 = AA, ect.). I am guessing my problem has to do with not having a 0 in the model? Not sure. But if you run the code, you will see that numbers 52, 104 and especially numbers ar...
Convert a number to Excel’s base 26
OK, I'm stuck on something seemingly simple. I am trying to convert a number to base 26 (ie. 3 = C, 27 = AA, ect.). I am guessing my problem has to do with not having a 0 in the model? Not sure. But if you run the code, you will see that numbers 52, 104 and especially numbers around 676 are really weird. Can anyone giv...
[ "The problem when converting to Excel’s “base 26” is that for Excel, a number ZZ is actually 26 * 26**1 + 26 * 26**0 = 702 while normal base 26 number systems would make a 1 * 26**2 + 1 * 26**1 + 0 * 26**0 = 702 (BBA) out of that. So we cannot use the usual ways here to convert these numbers.\nInstead, we have to r...
[ 14, 0, 0, 0 ]
[]
[]
[ "base", "numbers", "python" ]
stackoverflow_0048983939_base_numbers_python.txt
Q: In a bash script, parsing arguments as variables does not work when calling a python script I am trying to parse arguments as bash variables when calling a python script. #!/bin/bash var="--circular True" python python_script.py --input input_file "$var" I got this error: python_script.py: error: unrecognized arg...
In a bash script, parsing arguments as variables does not work when calling a python script
I am trying to parse arguments as bash variables when calling a python script. #!/bin/bash var="--circular True" python python_script.py --input input_file "$var" I got this error: python_script.py: error: unrecognized arguments: --circular True However, if I don't use a variable for the --circular flag, the script r...
[ "\"$var\" expands the value of variable var to a single shell word. The result is not subject to word splitting in the context in which the epxansion takes place. This is why with ...\n\nvar=\"--circular True\"\npython python_script.py --input input_file \"$var\"\n\n\n... Python sees a single argument --circular ...
[ 2 ]
[]
[]
[ "bash", "parsing", "python", "variables" ]
stackoverflow_0074467160_bash_parsing_python_variables.txt
Q: How to use relative import to import a function from a script in the parent folder How can I import a function in a script, where the function is defined in the parent's child folder? In the following folder structure, I would like to use root_folder/ utils_folder: __init__.py helper_functions....
How to use relative import to import a function from a script in the parent folder
How can I import a function in a script, where the function is defined in the parent's child folder? In the following folder structure, I would like to use root_folder/ utils_folder: __init__.py helper_functions.py (where Function_A is defined) module_A_folder: Script_A.py (Function_A wi...
[ "Try:\nfrom utils_folder.helper_functions import Function_A\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074468241_python_python_3.x.txt
Q: Search in multiple models in Django I have many different models in Django and I want to search for a keyword in all of them. For example, if you searched "blah", I want to show all of the products with "blah", all of the invoices with "blah", and finally all of the other models with "blah". I can develop a view a...
Search in multiple models in Django
I have many different models in Django and I want to search for a keyword in all of them. For example, if you searched "blah", I want to show all of the products with "blah", all of the invoices with "blah", and finally all of the other models with "blah". I can develop a view and search in all of the models separately...
[ "I've run into this situation a few times and one solution is to use model managers, and create distinct search methods for single and multi-word queries. Take the following example models below: Each has its own custom Model Manager, with two separate query methods. search will query single-word searches against...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074419771_django_django_rest_framework_python.txt
Q: numpy.linalg.det returns very small numbers instead of 0 I calculated the determinant of matrix using np.linalg.det(matrix) but it returns weird values. For example, it gives 1.1012323e-16 instead of 0. Of course, I can round the result with numpy.around, but is there any option to set some "default" rounding for ...
numpy.linalg.det returns very small numbers instead of 0
I calculated the determinant of matrix using np.linalg.det(matrix) but it returns weird values. For example, it gives 1.1012323e-16 instead of 0. Of course, I can round the result with numpy.around, but is there any option to set some "default" rounding for results of all numpy methods, including numpy.linalg.det?
[ "The value of the determinant looking \"weird\" is due to the floating point arithmetic, you can look it up.\nRegarding your question, I believe numpy.set_printoptions is what you are looking for. Please, see Docs\n" ]
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074468282_numpy_python.txt
Q: Regex to find some special match of characters Hi guys i have this text US Championships ---------------- [Event "ch-USA sf"] [Site "Denver USA"] [Date "1998.11.10"] [Round "01"] [White "Shaked,T"] [Black "DeFirmian,N"] [Result "1/2-1/2"] [ECO "A30"] [WhiteElo "2490"] [BlackElo "2605"] 1. c4 c5 2. Nf3 Nc6 3. Nc...
Regex to find some special match of characters
Hi guys i have this text US Championships ---------------- [Event "ch-USA sf"] [Site "Denver USA"] [Date "1998.11.10"] [Round "01"] [White "Shaked,T"] [Black "DeFirmian,N"] [Result "1/2-1/2"] [ECO "A30"] [WhiteElo "2490"] [BlackElo "2605"] 1. c4 c5 2. Nf3 Nc6 3. Nc3 Nf6 4. g3 b6 5. Bg2 Bb7 6. O-O e6 7. e4 d6 8. d4 c...
[ "Try (text is your text from the question) regex demo:\nimport re\n\npat = re.compile(r\"^.*\\n-+$\", flags=re.M)\n\nfor m in pat.findall(text):\n print(m)\n\nPrints:\nUS Championships\n----------------\n7th Monarch Assurance\n---------------------\n\n" ]
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074468306_python_regex.txt
Q: Is there a way to speed up the Save method with PIL? I have an API that saves an the image to S3 bucket and returns the S3 URL but the saving part of the PIL image is slow. Here is a snippet of code: from PIL import Image import io import boto3 BUCKET = '' s3 = boto3.resource('s3') def convert_fn(args): pil_im...
Is there a way to speed up the Save method with PIL?
I have an API that saves an the image to S3 bucket and returns the S3 URL but the saving part of the PIL image is slow. Here is a snippet of code: from PIL import Image import io import boto3 BUCKET = '' s3 = boto3.resource('s3') def convert_fn(args): pil_image = Image.open(args['path']).convert('RGBA') . . ....
[ "Compressing image data to PNG takes time - CPU time. There might be a better performant lib to that than PIL, but you'd have to interface it with Python, and it still would take sometime.\n\"Returning bytes\" make no sense - you either want to have image files saved on S3 or don't. And the \"bytes\" will only rep...
[ 2, 0 ]
[]
[]
[ "amazon_sagemaker", "computer_vision", "image", "python", "python_imaging_library" ]
stackoverflow_0074464037_amazon_sagemaker_computer_vision_image_python_python_imaging_library.txt
Q: Python dictionary inside function not getting updated with new values I'm trying to replace an inputed dictionary with new values. I don't understand why the value of the dictionary doesn't change outside of the function. It's weird because I remember this working earlier... ` def multiply_by_term(poly, term): ...
Python dictionary inside function not getting updated with new values
I'm trying to replace an inputed dictionary with new values. I don't understand why the value of the dictionary doesn't change outside of the function. It's weird because I remember this working earlier... ` def multiply_by_term(poly, term): new_values = [] for key in poly: new_values.append(poly[key] ...
[ "By writing poly = dict(zip(new_key_assign, new_values)), you will make it a different object from what it was when entering the function. So to keep the same id of your dict you just need to clear it before amending it:\ndef multiply_by_term(poly: dict, term: list):\n new_values = [poly[key] * term[1] for key i...
[ 1 ]
[]
[]
[ "dictionary", "function", "python" ]
stackoverflow_0074468000_dictionary_function_python.txt
Q: Tricky update values across a dataset if the sum of the row equals a certain threshold I have a dataset where if the numerical columns sum is less than 1.0, these fields will update to 0. Data ID type Q1 24 Q2 24 Q3 24 Q4 24 AA hey 2.0 1.2 0.5 0.6 AA hello 0.7 2.0 0.6 0.6 ...
Tricky update values across a dataset if the sum of the row equals a certain threshold
I have a dataset where if the numerical columns sum is less than 1.0, these fields will update to 0. Data ID type Q1 24 Q2 24 Q3 24 Q4 24 AA hey 2.0 1.2 0.5 0.6 AA hello 0.7 2.0 0.6 0.6 AA hi 0.1 0.1 0.1 0.1 AA good 0.3 0.4 0.2 0.2 ...
[ "# Use loc update the columns where their sum is less than zero\ndf.loc[df.iloc[:,2:].sum(axis=1)<1, ['Q124','Q224','Q324','Q424']]=0\ndf\n\nID type Q124 Q224 Q324 Q424\n0 AA hey 2.0 1.2 0.5 0.6\n1 AA hello 0.7 2.0 0.6 0.6\n2 AA hi 0.0 0.0 0.0 0.0\n3 ...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074468347_numpy_pandas_python.txt
Q: changing format of dataframe saying we have a data frame looking like this : with x,y,z the value we are interested in. Year1 year2 year3 canada. x1 x2 x3 shape we have can we transform it to a data frame 2 looking like the following : Country Year Value Canada Year1 x1 Canada Year2 ...
changing format of dataframe
saying we have a data frame looking like this : with x,y,z the value we are interested in. Year1 year2 year3 canada. x1 x2 x3 shape we have can we transform it to a data frame 2 looking like the following : Country Year Value Canada Year1 x1 Canada Year2 x2 Canada Year3 x3 shape wan...
[ "here is one way to do it\nAssuming, in your given DF, country is an index field\n# stack and reindex, then rename the columns\ndf.stack().reset_index().rename(columns={'level_0': 'Country', 'level_1': 'Year', 0:'Value'})\n\nCountry Year Value\n0 canada. Year1 x1\n1 canada. year2 x2\n2 cana...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074468190_dataframe_pandas_python.txt
Q: SQLAchemy scoped_session issue After long time work with I still have questions about sqlalchemy scoped session that I cannot figure out. For instance, I have decorator for functions that provides it with session def db_session_provider(commit=True, rollback=True, reraise=True): def decorator(func: typing.Call...
SQLAchemy scoped_session issue
After long time work with I still have questions about sqlalchemy scoped session that I cannot figure out. For instance, I have decorator for functions that provides it with session def db_session_provider(commit=True, rollback=True, reraise=True): def decorator(func: typing.Callable): @functools.wraps(func...
[ "Base = declarative_base()\n\nengine = create_engine(f\"postgresql+psycopg2://{username}:{password}@/{db}\", echo=False)\n\nclass Client(Base):\n __tablename__ = \"clients\"\n id = Column(\n Integer, nullable=False, primary_key=True\n )\n name = Column(Text)\n\nBase.metadata.create_all(engine)\n\...
[ 0 ]
[]
[]
[ "python", "session", "sqlalchemy" ]
stackoverflow_0074462772_python_session_sqlalchemy.txt
Q: Pygame freezes on startup I'm using pygame to try and get better with python but it just doesn't respond. I don't know why, as I have similar code that works just fine. import pygame import random import time width = 500 height = 500 snake = [[width / 2,height / 2]] direction = "right" pygame.init() move_increment...
Pygame freezes on startup
I'm using pygame to try and get better with python but it just doesn't respond. I don't know why, as I have similar code that works just fine. import pygame import random import time width = 500 height = 500 snake = [[width / 2,height / 2]] direction = "right" pygame.init() move_increment = 0.1 screen = pygame.display....
[ "pygame.draw.rect(screen,(0,0,0),[0,0,width,height])\npygame.display.flip()\nKeys()\n \nfor event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\nThis code needs to be indented more. It's currently outside the while loop, and therefore never being run\n" ]
[ 1 ]
[]
[]
[ "freeze", "pygame", "python", "python_3.x" ]
stackoverflow_0074468452_freeze_pygame_python_python_3.x.txt
Q: Django form is never valid and hence doesnt save to database I am creating a registration model which has date,time(charfield with choices),customer and restaurant .I need some help on why my instance is not saved even when I fill out my model form models.py class reservation(models.Model): TIMESLOTS = [ ...
Django form is never valid and hence doesnt save to database
I am creating a registration model which has date,time(charfield with choices),customer and restaurant .I need some help on why my instance is not saved even when I fill out my model form models.py class reservation(models.Model): TIMESLOTS = [ ('11:00-1:00', '11:00-1:00'), ('01:00-3:00', '01:00-0...
[ "Your form will never be valid because you are supplying an empty form. You need to add the request.POST data to that form before you validate it:\ndef reservationcreator(request):\n form=Reservationform(request.POST or None)\n\n if form.is_valid():\n res.customer=request.user\n res=form.save()...
[ 3, 3 ]
[]
[]
[ "django", "django_models", "python", "web" ]
stackoverflow_0074468354_django_django_models_python_web.txt
Q: How can I get the list of selected values in an excel ListBox object using xlwings? I'm trying to know which items of my excel ListBox is being selected using xlwings. What works: sheet = xw.sheets.active sheet.api.Shapes('ListBox11').ControlFormat.ListCount #returns 17 because 17 items in my ListBox What I tried...
How can I get the list of selected values in an excel ListBox object using xlwings?
I'm trying to know which items of my excel ListBox is being selected using xlwings. What works: sheet = xw.sheets.active sheet.api.Shapes('ListBox11').ControlFormat.ListCount #returns 17 because 17 items in my ListBox What I tried and fails with error (com_error: (-2147352570, 'Unknown name.', None, None)) : sheet.api...
[ "You can try the following;\nThis code is using an Active X Listbox\n...\nsheet = xw.sheets.active\n\nlb_obj = sheet.api.OLEObjects(\"ListBox11\").Object\nlist_count = lb_obj.ListCount\n\nfor x in range(list_count):\n if lb_obj.Selected(x) == True:\n print(lb_obj.List[x])\n\n" ]
[ 1 ]
[]
[]
[ "excel", "python", "xlwings" ]
stackoverflow_0074461842_excel_python_xlwings.txt
Q: Why does my while loop continue to call my menu function even after receiving different instruction I have a simple Python program with multiple functions that displays a menu, takes an input, loops through and formats a CSV file then outputs information from that CSV file based on the user's input. The Menu optio...
Why does my while loop continue to call my menu function even after receiving different instruction
I have a simple Python program with multiple functions that displays a menu, takes an input, loops through and formats a CSV file then outputs information from that CSV file based on the user's input. The Menu options look like 1: Call menu again 2: Create a default Report 3: More specified report 4: More specified Rep...
[ "while True:\n ...\n\nis an infinite loop that will run until it hits a break statement.\nAll your break statements are inside an if/elif branch, but not all the branches have a break. The logical reasons for not exiting the loop is then either (i) none of the if-tests match, or (ii) none of the branches with a ...
[ 0 ]
[ "This is likely because you are not resetting the value of choice. At the start of the loop you set it to menu() and then continued to do this each time, I'm not sure what menu() does but I'm guessing that it will be returning a 1 every time which is not what you would like.\nEither make sure the value received fro...
[ -1 ]
[ "python" ]
stackoverflow_0074468369_python.txt
Q: Python Categorize Dataframe Column Conditionally Using Regular Expression I have a dataframe: group id A 009x A 010x B 009x B 002x C 002x C 003x How do I make a new column new that categorizes conditionally under the following three conditions by group: If all id values consist of ONLY 009x and 010...
Python Categorize Dataframe Column Conditionally Using Regular Expression
I have a dataframe: group id A 009x A 010x B 009x B 002x C 002x C 003x How do I make a new column new that categorizes conditionally under the following three conditions by group: If all id values consist of ONLY 009x and 010x, then categorize as g1 If the id value is one of 009x or 010x AND another id ...
[ "I hope I've understood your question right. You can use .groupby() + custom function:\ndef categorize_fn(x):\n tmp = x[\"id\"].isin([\"009x\", \"010x\"])\n\n if tmp.all():\n x[\"new\"] = \"g1\"\n elif tmp.any():\n x[\"new\"] = \"g2\"\n else:\n x[\"new\"] = x[\"id\"]\n\n return x...
[ 1 ]
[]
[]
[ "pandas", "python", "regex" ]
stackoverflow_0074468470_pandas_python_regex.txt
Q: How to retrieve the status of a Stripe Subscription I am trying to get the status of customers subscriptions using the Stripe API for example: print(subscriptionStatusFunctionAPI(subscriptionID)) *"returns subscription status (e.g. active, past_due, canceled, unpaid, etc)"* below is the current pseudocode im...
How to retrieve the status of a Stripe Subscription
I am trying to get the status of customers subscriptions using the Stripe API for example: print(subscriptionStatusFunctionAPI(subscriptionID)) *"returns subscription status (e.g. active, past_due, canceled, unpaid, etc)"* below is the current pseudocode import stripe stripe.api_key = 'rk_test_XXX' ### retrieve...
[ "The Subscription object has a status property. When you call the Retrieve Subscription API, you get back that Subscription object as a class in stripe-python. At that point you have access to all the properties of that object directly.\nYou can access the status like this:\nretrieve_sub = stripe.Subscription.retri...
[ 1 ]
[]
[]
[ "python", "stripe_payments" ]
stackoverflow_0074468494_python_stripe_payments.txt
Q: coverting list of string coordinates into list of lists coordinates without string I have a list of list of strings, but each string a coordinate separated by commas, I want to convert into list of lists of coordinates without string my_list =['44324,-34244', '44885.1,-33445.6', '45373.1,-32849.8', '45380.1,-32625...
coverting list of string coordinates into list of lists coordinates without string
I have a list of list of strings, but each string a coordinate separated by commas, I want to convert into list of lists of coordinates without string my_list =['44324,-34244', '44885.1,-33445.6', '45373.1,-32849.8', '45380.1,-32625.6', '44635.7,-32285.6', '44635.7,-32285.6'] I want to convert into [[44324,-34244], [4...
[ "Wrap map(...) in list(...) like so:\ncoords = [list(map(float,i.split(\",\"))) for i in my_list]\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074468590_python_python_3.x.txt
Q: python selenium, find out when a download has completed? I've used selenium to initiate a download. After the download is complete, certain actions need to be taken, is there any simple method to find out when a download has complete? (I am using the FireFox driver) A: I came across this problem recently. I was ...
python selenium, find out when a download has completed?
I've used selenium to initiate a download. After the download is complete, certain actions need to be taken, is there any simple method to find out when a download has complete? (I am using the FireFox driver)
[ "I came across this problem recently. I was downloading multiple files at once and had to build in a way to timeout if the downloads failed. \nThe code checks the filenames in some download directory every second and exits once they are complete or if it takes longer than 20 seconds to finish. The returned download...
[ 51, 29, 13, 7, 5, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0034338897_python_selenium.txt
Q: Select specific columns with cast using SQLAlchemy I'm using SQLAlchemy (Version: 1.4.44) and I'm having some unexpected results when trying to select columns and using cast on those columns. First, most of the examples and even current documentation suggests column selection should work by passing an array to the...
Select specific columns with cast using SQLAlchemy
I'm using SQLAlchemy (Version: 1.4.44) and I'm having some unexpected results when trying to select columns and using cast on those columns. First, most of the examples and even current documentation suggests column selection should work by passing an array to the select function like this: s = select([table.c.col1]) ...
[ "I don't think table.select() is common usage. SQLAlchemy is in a big transition right now on its way to 2.0. In 1.4 (and in 2) the following syntax should work, use whatever session handling you already have working I just mean the select(...):\nfrom sqlalchemy.sql import select, cast\nfrom sqlalchemy.dialects.p...
[ 1 ]
[]
[]
[ "casting", "python", "select", "sqlalchemy" ]
stackoverflow_0074461385_casting_python_select_sqlalchemy.txt
Q: Scraping: run for loop n number of times I am using instaloader to scrape instagram posts as part of a study project. To avoid getting shut down by instagram, I use sleep function to sleep between 1-20 sec between each round. This works well. I don't want to have to go through all posts each time I scrape, and the...
Scraping: run for loop n number of times
I am using instaloader to scrape instagram posts as part of a study project. To avoid getting shut down by instagram, I use sleep function to sleep between 1-20 sec between each round. This works well. I don't want to have to go through all posts each time I scrape, and therefore i want the loop to run 5 times. Which w...
[ "The problem is that the inner for loop runs download_post twice (range(2)) on the same post, and then the outer loop breaks. If POSTS is a list, you can use slicing to loop only over the first 5 items like so: for post in POSTS[:5]:. A safer method though would be to count the posts as you go, which should work fo...
[ 0 ]
[]
[]
[ "for_loop", "instagram", "instaloader", "python" ]
stackoverflow_0074467018_for_loop_instagram_instaloader_python.txt
Q: How to autoincrement values checkbox with jinja2 (Django) with reset I need to autoincrement value in my checkbox and reset value when I generated new massive of checkbox forloop.count dont reset {% for ans in Answ %} {% if ans.question_id_id == Questions.id %} <input type="hidden" value="{{ Question...
How to autoincrement values checkbox with jinja2 (Django) with reset
I need to autoincrement value in my checkbox and reset value when I generated new massive of checkbox forloop.count dont reset {% for ans in Answ %} {% if ans.question_id_id == Questions.id %} <input type="hidden" value="{{ Questions.id }}" name="id"> <div class="form-check" ><label><input type="ch...
[ "This is one of the many reasons why you should not do filtering in the template. Another very important one is performance: as the number of answers will grow, eventually the template rendering will take a lot of time.\nYou can filter in the view with:\nclass AnswerQuestionView(LoginRequiredMixin, DetailView):\n ...
[ 1 ]
[]
[]
[ "django", "jinja2", "python" ]
stackoverflow_0074468595_django_jinja2_python.txt
Q: NLP: pre-processing dataset into a new dataset I need help with processing an unsorted dataset. Sry, if I am a complete noob. I never did anything like that before. So as you can see, each conversation is identified by a dialogueID which consists of multiple rows of "from" & "to", as well as text messages. I woul...
NLP: pre-processing dataset into a new dataset
I need help with processing an unsorted dataset. Sry, if I am a complete noob. I never did anything like that before. So as you can see, each conversation is identified by a dialogueID which consists of multiple rows of "from" & "to", as well as text messages. I would like to concatenate the text messages from the sam...
[ "Edit 1\nAccording to your clarification, this is what I believe you're looking for.\nCreate an aggregation function which basically concats your string values with a line-break character. Then group by dialogueID and apply your aggregation.\nd = {}\nd['from'] = '\\n'.join\nd['to'] = '\\n'.join\nnew_df = dialogue_d...
[ 1, 0 ]
[]
[]
[ "data_preprocessing", "data_science", "dataframe", "nlp", "python" ]
stackoverflow_0074468471_data_preprocessing_data_science_dataframe_nlp_python.txt
Q: regex to get value and it's proper unit i use the following regex to extract values that appear before certain units: ([.\d]+)\s*(?:kg|gr|g) What i want, is to include the unit of that specific value for example from this string : "some text 5kg another text 3 g more text 11.5gr end" i should be getting : ["5kg"...
regex to get value and it's proper unit
i use the following regex to extract values that appear before certain units: ([.\d]+)\s*(?:kg|gr|g) What i want, is to include the unit of that specific value for example from this string : "some text 5kg another text 3 g more text 11.5gr end" i should be getting : ["5kg", "3 g", "11.5gr"] can't wrap my head on how...
[ "import re\n\np = re.compile('(?<!\\d|\\.)\\d+(?:\\.\\d+)?\\s*?(?:gr|kg|g)(?!\\w)')\nprint(p.findall(\"some text 5kg another text 3 g more text 11.5gr end\"))\n\n", "Other solution (regex demo):\n(?i)\\b\\d+\\.?\\d*\\s*(?:kg|gr?)\\b\n\n\n(?i) - case insensitive\n\\b - word boundary\n\n\\d+\\.?\\d* - match the amo...
[ 2, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0074468594_python_regex_string.txt
Q: Is there a way to use an array as an index in Python? I'm trying to speed up my code and right now I have a "for" loop to sum numbers in an array. It's set up like this: a1=np.zeros(5) a2=[1,2,3,4,5,6,7,8,9,10] And what I want to do is sum the values of a2[:5] + a2[5:], to end up with a1=[7,9,11,13,15] So I've m...
Is there a way to use an array as an index in Python?
I'm trying to speed up my code and right now I have a "for" loop to sum numbers in an array. It's set up like this: a1=np.zeros(5) a2=[1,2,3,4,5,6,7,8,9,10] And what I want to do is sum the values of a2[:5] + a2[5:], to end up with a1=[7,9,11,13,15] So I've made a loop that goes: for ii in range(2): a1+=a2[5*ii:5...
[ "It looks like you would like to add the first half of the list to its second half. This can be accomplished by reshaping the 1D list into a 2D array (2x5) and summing it along the horizontal axis.\nnp.array(a2).reshape(2,5).sum(axis=0)\n# array([ 7, 9, 11, 13, 15])\n\n", "Depends on what you really want to achi...
[ 2, 0 ]
[]
[]
[ "arrays", "indexing", "numpy", "performance", "python" ]
stackoverflow_0074468124_arrays_indexing_numpy_performance_python.txt
Q: Notify us if a QlineEdit is clicked while being in ReadOnly State and change a button Color depending if QlineEdit is in ReadOnly state or not I have a Pyqt Widget containing 3 buttons, 1 QlineEdit and 1 statusbar. One of the buttons makes the qlineedit in Read Only state, another one to disable the qlineedit Read...
Notify us if a QlineEdit is clicked while being in ReadOnly State and change a button Color depending if QlineEdit is in ReadOnly state or not
I have a Pyqt Widget containing 3 buttons, 1 QlineEdit and 1 statusbar. One of the buttons makes the qlineedit in Read Only state, another one to disable the qlineedit Readonly state and the last one to show the values of the Qlineedit in the status bar message. I would like to build an event that is triggered when the...
[ "There is no need to create additional slots for the same signal, you can simply change the color of the button inside the methods that toggle the readOnly setting. In fact you actually don't even need two separate buttons for the view and edit methods... you could just have a single button that toggles readOnly b...
[ 0 ]
[]
[]
[ "pyqt", "pyqt5", "python", "signals", "user_interface" ]
stackoverflow_0074463359_pyqt_pyqt5_python_signals_user_interface.txt
Q: Normalize the espicific rows of an array I have an array with size ( 61000) I want to normalize it based on this rule: Normalize the rows 0, 6, 12, 18, 24, ... (6i for i in range(1000)) based on the formulation which I provide. Dont change the values of the other rows. Here is an example: def normalize(array): ...
Normalize the espicific rows of an array
I have an array with size ( 61000) I want to normalize it based on this rule: Normalize the rows 0, 6, 12, 18, 24, ... (6i for i in range(1000)) based on the formulation which I provide. Dont change the values of the other rows. Here is an example: def normalize(array): minimum = np.expand_dims(np.min(array, axis=1...
[ "You have to set up a second function having the step argument:\ndef normalize_with_step(array, step):\n \n b = normalize(array[::step])\n a, b = list(array), list(b)\n \n for i in range(0, len(a), step):\n a[i] = b[int(i/step)]\n \n a = np.array(a)\n return a\n\nLet's try it with...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074468506_numpy_python.txt
Q: Generate json schema from argparse CLI I have a CLI written with argparse and I was wondering if there was a way to produce a JSON schema from the ArgumentParser? The thought behind this being to distribute the JSON schema to extensions interfacing with the application, thus removing the need for each extension to...
Generate json schema from argparse CLI
I have a CLI written with argparse and I was wondering if there was a way to produce a JSON schema from the ArgumentParser? The thought behind this being to distribute the JSON schema to extensions interfacing with the application, thus removing the need for each extension to write and maintain their own schema. My ide...
[ "The solution that I came up with was to access the private variable _actions from ArgumentParser and convert that to a schema using pydantic. In my specific case it was quite easy to do since all the arguments in argparse were optional. If not, a bit more thought has to be put when creating the model with pydantic...
[ 1 ]
[]
[]
[ "argparse", "json", "python" ]
stackoverflow_0072718138_argparse_json_python.txt
Q: Rotate point about another point in degrees python If you had a point (in 2d), how could you rotate that point by degrees around the other point (the origin) in python? You might, for example, tilt the first point around the origin by 10 degrees. Basically you have one point PointA and origin that it rotates aroun...
Rotate point about another point in degrees python
If you had a point (in 2d), how could you rotate that point by degrees around the other point (the origin) in python? You might, for example, tilt the first point around the origin by 10 degrees. Basically you have one point PointA and origin that it rotates around. The code could look something like this: PointA=(200,...
[ "The following rotate function performs a rotation of the point point by the angle angle (counterclockwise, in radians) around origin, in the Cartesian plane, with the usual axis conventions: x increasing from left to right, y increasing vertically upwards. All points are represented as length-2 tuples of the form ...
[ 120, 40, 9, 5, 4, 0 ]
[]
[]
[ "degrees", "math", "python" ]
stackoverflow_0034372480_degrees_math_python.txt
Q: How to pad given number of spaces between words in a string? Details: Given a string s that contains words. I am also given spaces which specifies the number of extra spaces to add between words. The number of spots will be len(words)-1. If spaces/spots is an odd number then the left slot gets more spaces. Exa...
How to pad given number of spaces between words in a string?
Details: Given a string s that contains words. I am also given spaces which specifies the number of extra spaces to add between words. The number of spots will be len(words)-1. If spaces/spots is an odd number then the left slot gets more spaces. Example1: s = "This is an" spaces = 6 Ans = "This is an" #Ex...
[ "Calculate the number of spaces needed between the words and the remainder, split the words, join with the even spacing, then replace the first spaces from the left with the larger spacing if needed.\ns = 'The quick brown fox jumped over the lazy dog.'\nspaces = 20\n\nwords = s.split()\nspace_count, extra_count = d...
[ 2, 1 ]
[]
[]
[ "algorithm", "data_structures", "list", "python", "python_3.x" ]
stackoverflow_0074468709_algorithm_data_structures_list_python_python_3.x.txt
Q: Unable to hide Chromedriver console with CREATE_NO_WINDOW Python 3.11 ChromeDriver 107.0.5304.62 Chrome 107.0.5304.107 Selenium 4.6.0 Chromedriver console always shows when I try to build exe with pyinstaller. from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeSe...
Unable to hide Chromedriver console with CREATE_NO_WINDOW
Python 3.11 ChromeDriver 107.0.5304.62 Chrome 107.0.5304.107 Selenium 4.6.0 Chromedriver console always shows when I try to build exe with pyinstaller. from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from subprocess import CREATE_NO_WINDOW chr...
[ "It doesn't work with selenium 4.6.0 version. It work with selenium 4.5.0\n" ]
[ 1 ]
[]
[]
[ "python", "selenium_chromedriver", "subprocess" ]
stackoverflow_0074461847_python_selenium_chromedriver_subprocess.txt
Q: Optimize python pattern matching in nucleotide sequences I'm currently working on a bioinformatic and modelling project where I need to do some pattern matching. Let's say I have a DNA fragment as follow 'atggcgtatagagc' and I split that fragment in micro-sequences of 8 nucleotides so that I have : 'atggcgta' 'tgg...
Optimize python pattern matching in nucleotide sequences
I'm currently working on a bioinformatic and modelling project where I need to do some pattern matching. Let's say I have a DNA fragment as follow 'atggcgtatagagc' and I split that fragment in micro-sequences of 8 nucleotides so that I have : 'atggcgta' 'tggcgtat' 'ggcgtata' 'gcgtatag' 'cgtataga' 'gtatagag' 'tatagagc'...
[ "I would not recommend using regex for repetitive simple pattern matching. Outright comparison is expected to perform better. I did some basic testing and came up with the demo below.\nimport time\nimport re\nimport random\n\n\ndef compare(r1, r2, microseq_len, test_condition=1):\n # condition 1: make microseqs/...
[ 0 ]
[]
[]
[ "bioinformatics", "dna_sequence", "python", "regex" ]
stackoverflow_0074467529_bioinformatics_dna_sequence_python_regex.txt
Q: Pandas Dataframe Remove all Rows with Letters in Certain Column I have a pandas dataframe in python that I want to remove rows that contain letters in a certain column. I have tried a few things, but nothing has worked. Input: A B C 0 9 1 a 1 8 2 b 2 7 cat c 3 6 4 d I w...
Pandas Dataframe Remove all Rows with Letters in Certain Column
I have a pandas dataframe in python that I want to remove rows that contain letters in a certain column. I have tried a few things, but nothing has worked. Input: A B C 0 9 1 a 1 8 2 b 2 7 cat c 3 6 4 d I would then remove rows that contained letters in column 'B'... Expecte...
[ "Assuming the B column be string type, we can use str.contains here:\ndf[~df[\"B\"].str.contains(r'^[A-Za-z]+$', regex=True)]\n\n", "here is another way to do it\n# use isalpha to check if value is alphabetic\n# use negation to pick where value is not alphabetic\n\ndf=df.loc[~df['B'].str.isalpha()]\n\ndf\n\n A...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074468646_dataframe_pandas_python.txt
Q: send data from html field(Not Form) using AJAX to python cgi I am trying to solve a problem, where I am suppose to send data using programmatic form which is not to use the form field itself to a backend python cgi script. However, I have no idea how to receive that text using python. With form I could use "form =...
send data from html field(Not Form) using AJAX to python cgi
I am trying to solve a problem, where I am suppose to send data using programmatic form which is not to use the form field itself to a backend python cgi script. However, I have no idea how to receive that text using python. With form I could use "form = cgi.FieldStorage()". However, for now, I am trying to send the da...
[ "So basically in python program you would receive the data from asyncRequest.send() which is combination of your input field creating a query param which is essentially sent via asyncRequest.send(\"Query Param\"); Then using the variable name used in JS you would get value within your python script.\n <!DOCTYPE ...
[ 0 ]
[]
[]
[ "ajax", "javascript", "python" ]
stackoverflow_0074453105_ajax_javascript_python.txt
Q: Difficulties adding a new blank line every 10 lines of text in Python I am working on a python script that will format books that I input from the internet for school. Currently both section one and section three are functional. The book is able to have all blank lines removed, and it is outputted into a plain tex...
Difficulties adding a new blank line every 10 lines of text in Python
I am working on a python script that will format books that I input from the internet for school. Currently both section one and section three are functional. The book is able to have all blank lines removed, and it is outputted into a plain text file. The issue I'm having is with section two. After all of the blank li...
[ "Instead of:\nfor i in finalBook:\n if i % 10 == 0 and i != 0: \n finalBook = finalBook + \"\\n\"\n\nYou will want something like:\nn = 10\nfinalBook = [\n line for block in (\n finalBook[i:i + n] + ['\\n'] for i in range(0, len(finalBook), n)\n ) for line in block\n]\n\nFor example:\nfinalBo...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074468802_python_python_3.x.txt
Q: Find all occurrences of a character in a String I'm really new to python and trying to build a Hangman Game for practice. I'm using Python 3.6.1 The User can enter a letter and I want to tell him if there is any occurrence of that letter in the word and where it is. I get the total number of occurrences by using ...
Find all occurrences of a character in a String
I'm really new to python and trying to build a Hangman Game for practice. I'm using Python 3.6.1 The User can enter a letter and I want to tell him if there is any occurrence of that letter in the word and where it is. I get the total number of occurrences by using occurrences = currentWord.count(guess) I have firstL...
[ "One way to do this is to find the indices using list comprehension:\ncurrentWord = \"hello\"\n\nguess = \"l\"\n\noccurrences = currentWord.count(guess)\n\nindices = [i for i, a in enumerate(currentWord) if a == guess]\n\nprint indices\n\noutput:\n[2, 3]\n\n", "I would maintain a second list of Booleans indicatin...
[ 8, 0, 0 ]
[]
[]
[ "python", "python_3.6", "string" ]
stackoverflow_0044307988_python_python_3.6_string.txt
Q: Ragged list to dataframe I have a non-uniform list as follows: [['E', 'A', 'P'], ['E', 'A', 'X', 'P'], ['E', 'A', 'P'], ['P'], ['E', 'A', 'X', 'P'], ['E', 'A', 'P'], ['A', 'X', 'P'], ['E', 'A', 'P'], ['E', 'A', 'P'], ['E', 'A', 'X', 'P'], ['E', 'A', 'P'], ['E', 'A', 'P'], ['A', 'X', 'P'], I would like...
Ragged list to dataframe
I have a non-uniform list as follows: [['E', 'A', 'P'], ['E', 'A', 'X', 'P'], ['E', 'A', 'P'], ['P'], ['E', 'A', 'X', 'P'], ['E', 'A', 'P'], ['A', 'X', 'P'], ['E', 'A', 'P'], ['E', 'A', 'P'], ['E', 'A', 'X', 'P'], ['E', 'A', 'P'], ['E', 'A', 'P'], ['A', 'X', 'P'], I would like to create a data frame from t...
[ "I would recommend MultiLabelBinarizer from sklearn\nfrom sklearn.preprocessing import MultiLabelBinarizer\n \nmlb = MultiLabelBinarizer()\ndf = pd.DataFrame(mlb.fit_transform(l),columns=mlb.classes_)\nOut[170]: \n A E P X\n0 1 1 1 0\n1 1 1 1 1\n2 1 1 1 0\n3 0 0 1 0\n4 1 1 1 1\n5 1 ...
[ 2, 1 ]
[]
[]
[ "dataframe", "list", "pandas", "python", "ragged" ]
stackoverflow_0074468869_dataframe_list_pandas_python_ragged.txt
Q: Dealing with 2 arrays in python, how would I return values for grades based on student name? Array 1 is called 'students', with 'Alex', 'Rich', 'Anthony', 'Len', 'Mark' as values. Array 2 is called 'grades' with [85, 44], [63, 19], [47, 95], [30, 67], [33, 16] as values. I need to select all rows from 'grades' whe...
Dealing with 2 arrays in python, how would I return values for grades based on student name?
Array 1 is called 'students', with 'Alex', 'Rich', 'Anthony', 'Len', 'Mark' as values. Array 2 is called 'grades' with [85, 44], [63, 19], [47, 95], [30, 67], [33, 16] as values. I need to select all rows from 'grades' where 'students' is either 'Alex' or 'Mark' Do I need to combine the arrays? I am new to python and s...
[ "students = ['Alex', 'Rich', 'Anthony', 'Len', 'Mark']\ngrades = [[85, 44], [63, 19], [47, 95], [30, 67], [33, 16]]\nstudentgrades = dict(zip(students, grades))\nprint(studentgrades)\n\n\n{'Alex': [85, 44],'Rich': [63, 19],'Anthony': [47, 95],'Len': [30, 67],'Mark': [33, 16]}\n\n\nprint(studentgrades['Alex'])\n\n\n...
[ 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074466039_arrays_numpy_python.txt
Q: convert PSUTIL Process output to object/dict? I am currently running the following script to get the system_md status of each host. Its working but the output I am getting is a Process Class and I am not sure how to parse the following params to a usable dict. I do not use python much so any help would be great. ...
convert PSUTIL Process output to object/dict?
I am currently running the following script to get the system_md status of each host. Its working but the output I am getting is a Process Class and I am not sure how to parse the following params to a usable dict. I do not use python much so any help would be great. convert: psutil.Process(pid=1153, name='sssd', st...
[ "And I resolved it with the following code outputs pretty pretty json with the service and status name:\n#!/usr/bin/env python\n\nimport re\nimport psutil\nimport json\n\n\ndef log_running_services():\n known_cgroups = set()\n result = []\n # print(psutil.pids)\n for pid in psutil.pids():\n try:\...
[ 0 ]
[]
[]
[ "psutil", "python", "python_2.x", "scripting", "systemctl" ]
stackoverflow_0074468431_psutil_python_python_2.x_scripting_systemctl.txt
Q: What is the best way to query a pytable column with many values? I have a 11 columns x 13,470,621 rows pytable. The first column of the table contains a unique identifier to each row (this identifier is always only present once in the table). This is how I select rows from the table at the moment: my_annotations_t...
What is the best way to query a pytable column with many values?
I have a 11 columns x 13,470,621 rows pytable. The first column of the table contains a unique identifier to each row (this identifier is always only present once in the table). This is how I select rows from the table at the moment: my_annotations_table = h5r.root.annotations # Loop through table and get rows that ma...
[ "Another approach to consider is combining 2 functions: Table.get_where_list() with Table.read_coordinates()\n\nTable.get_where_list(): gets the row coordinates fulfilling the given condition.\nTable.read_coordinates(): Gets a set of rows given their coordinates (in a list), and returns as a (record) array.\n\nThe ...
[ 1, 0 ]
[]
[]
[ "pytables", "python" ]
stackoverflow_0074451862_pytables_python.txt
Q: ValueError: too many values to unpack (expected 2) on a simple Python function I'm coding this password manager program and keep getting this error message when I use the view function: File "c:\Users\user\Desktop\password_manager.py", line 7, in view user, passw = data.split("|") ValueError: too many valu...
ValueError: too many values to unpack (expected 2) on a simple Python function
I'm coding this password manager program and keep getting this error message when I use the view function: File "c:\Users\user\Desktop\password_manager.py", line 7, in view user, passw = data.split("|") ValueError: too many values to unpack (expected 2) This is the program so far: master_pwd = input("What is t...
[ "The .split() function is returning more than 2 values in a list and therefore cannot be unpacked into only 2 variables. Maybe you have a password or username with a | in it which would cause that.\nI suggest to simply print(data.split('|')) for a visual of what is happening. It will probably print out a list with ...
[ 2, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074468338_python_python_3.x.txt
Q: Navigating between tkinter frames in multiple modules I'm new to Python. Trying to create two modules (.py files) which can be navigated to & fro, without having to create two windows. So, 1st module will have window & frame 1, 2nd module will have just a frame 2. On button click, the frame shown should be switche...
Navigating between tkinter frames in multiple modules
I'm new to Python. Trying to create two modules (.py files) which can be navigated to & fro, without having to create two windows. So, 1st module will have window & frame 1, 2nd module will have just a frame 2. On button click, the frame shown should be switched. Not sure if the below is the right way to do it, but I'm...
[ "When testnew is imported inside switch_to_first(), the following code inside testnew.py will be executed again to create another instance of Tk():\nroot = Tk()\nroot.title(\"Hello world\")\nroot.geometry(\"500x500\")\nmain_frame = main(root)\nroot.mainloop()\n\nSo there will be two windows shown. The mentioned ex...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074468656_python_tkinter.txt
Q: Python3 dictionary: remove duplicate values in alphabetical order Let's say I have the following dictionary: full_dic = { 'aa': 1, 'ac': 1, 'ab': 1, 'ba': 2, ... } I normally use standard dictionary comprehension to remove dupes like: t = {val : key for (key, val) in full_dic.items()} cleaned_dic = {val...
Python3 dictionary: remove duplicate values in alphabetical order
Let's say I have the following dictionary: full_dic = { 'aa': 1, 'ac': 1, 'ab': 1, 'ba': 2, ... } I normally use standard dictionary comprehension to remove dupes like: t = {val : key for (key, val) in full_dic.items()} cleaned_dic = {val : key for (key, val) in t.items()} Calling print(cleaned_dic) outputs...
[ "You should use the OrderectDict class.\nimport collections\nfull_dic = {\n 'aa': 1,\n 'ac': 1,\n 'ab': 1\n}\nod = collections.OrderedDict(sorted(full_dic.items()))\n\nIn this way you will be sure to have sorted dictionary (Original code: StackOverflow).\nAnd then:\nresult = {}\nfor k, vin od.items():\n if va...
[ 1, 1, 1 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074468789_dictionary_python_python_3.x.txt
Q: Python flask not working with url containing "?" I am new to flask and I was trying to make GET request for url containing "?" symbol but it look like my program is just skipping work with it. I am working with flask-sql alchemy, flask and flask-restful. Some simplified look of my program looks like this: fields_l...
Python flask not working with url containing "?"
I am new to flask and I was trying to make GET request for url containing "?" symbol but it look like my program is just skipping work with it. I am working with flask-sql alchemy, flask and flask-restful. Some simplified look of my program looks like this: fields_list = ['id'] db = SQLAlchemy(app) class User(db.Mode...
[ "In order to get the information after ?, you have to use request.args. This information is Query Parameters, which are part of the Query String: a section of the URL that contains key-value parameters.\nIf your route is:\napi.add_resource(GetSorted, '/api/customers?sort=<field>&sort_type=<type>')\n\nYour key-value...
[ 0, 0 ]
[]
[]
[ "flask", "flask_restful", "python" ]
stackoverflow_0074468668_flask_flask_restful_python.txt
Q: How do I check if a user has a role in nextcord? I am using nextcord and I am trying to check if a user has a role when they run a command. I have no idea how to do this so I cannot provide an MRE. I imagine that the code will be something like this: @client.slash_command(name="test") async def test(interaction:ne...
How do I check if a user has a role in nextcord?
I am using nextcord and I am trying to check if a user has a role when they run a command. I have no idea how to do this so I cannot provide an MRE. I imagine that the code will be something like this: @client.slash_command(name="test") async def test(interaction:nextcord.Interaction): if interaction.user.has_role("Co...
[ "To do this, you will need to get the role first, and then check if a specific member is in that role. Here is an example, however I believe this is not the only way to do this:\nfrom nextcord.utils import get\n\nrole = get(ctx.guild.roles, name='search for role by name')\n\nif interaction.user in role:\n do so...
[ 1, 0 ]
[]
[]
[ "discord", "nextcord", "python" ]
stackoverflow_0074439793_discord_nextcord_python.txt
Q: Python Unittest: No tests discovered in Visual Studio Code I'm trying to make the self-running feature of Visual Studio Code unit tests work. I recently made a change in the directory structure of my Python project that was previously like this: myproje\ domain\ __init__.py repositories\ tests\...
Python Unittest: No tests discovered in Visual Studio Code
I'm trying to make the self-running feature of Visual Studio Code unit tests work. I recently made a change in the directory structure of my Python project that was previously like this: myproje\ domain\ __init__.py repositories\ tests\ __init__.py guardstest.py utils\ __...
[ "The problem was that I was using relative imports in the test module (from ..utils import guards). \nI just changed it to absolute import (from app.utils import guards) and it all worked again.\n", "There are 2 reasons that this might not work:\nThere is an error in the tests\nThe python Testing plugin won't fin...
[ 8, 5, 4, 0 ]
[]
[]
[ "python", "visual_studio_code", "vscode_settings" ]
stackoverflow_0051198860_python_visual_studio_code_vscode_settings.txt
Q: A code to decide whether, or not, a given number of different coins possible to form an exact given amount of dollars (Using loops or recursion), I'm trying to write a python function where the user enters an amount of dollars (say:1.25) and number of coins (say:6), then the function decides whether, or not, it is...
A code to decide whether, or not, a given number of different coins possible to form an exact given amount of dollars
(Using loops or recursion), I'm trying to write a python function where the user enters an amount of dollars (say:1.25) and number of coins (say:6), then the function decides whether, or not, it is possible to form the exact amount of dollars using the exact given number of coins, assuming that the coins are quarters (...
[ "Here's a working solution without recursion, but does use list comprehension. Not sure how large your coin set is expected to grow to and since this calculates the sum for all combinations it won't scale nicely.\nfrom itertools import combinations_with_replacement\n\nlist_of_coins = [0.1, 0.05, 0.25] # dimes, nick...
[ 0, 0, 0 ]
[]
[]
[ "currency", "python", "recursion" ]
stackoverflow_0074465732_currency_python_recursion.txt
Q: for loops within dictionaries vs dictionaries within for loops? Hi I have a question about iterating through a list and adding items and their frequency within the list to a dictionary. i = ['apple','pear','red','apple','red','red','pear','pear','pear'] d = {x:i.count(x) for x in i} print (d) outputs {'pear': 4...
for loops within dictionaries vs dictionaries within for loops?
Hi I have a question about iterating through a list and adding items and their frequency within the list to a dictionary. i = ['apple','pear','red','apple','red','red','pear','pear','pear'] d = {x:i.count(x) for x in i} print (d) outputs {'pear': 4, 'apple': 2, 'red': 3} However i = ['apple','pear','red','apple','r...
[ "The problem is that you must add key:value pairs in the second loop instead of overwriting d with every loop.\ni = ['apple','pear','red','apple','red','red','pear','pear','pear']\nd = {}\n\nfor x in i:\n d[x] = i.count(x)\n\nprint(d)\n\nwill output the same as your first function.\n{'pear': 4, 'apple': 2, 'red'...
[ 2, 0, 0 ]
[ "varLs = ['apple','pear','red','apple','red','red','pear','pear','pear']\n\ndef frequency(varLs): \n counters = {}\n\n for item in varLs:\n if item not in counters:\n counters[item] = 1\n else:\n counters[item]+= 1\n return counters\n\nprint(frequency(varLs))\n\nreturns...
[ -1 ]
[ "dictionary", "for_loop", "python", "python_3.x" ]
stackoverflow_0074468784_dictionary_for_loop_python_python_3.x.txt
Q: This little script I wrote to monitor my plex sever freezes whenever there's an update I have this python script running on a raspberry pi thats plugged up to a monitor so I can passively monitor my plex server. It displays the current streams, how many of them are transcode streams, and if there's a plex update a...
This little script I wrote to monitor my plex sever freezes whenever there's an update
I have this python script running on a raspberry pi thats plugged up to a monitor so I can passively monitor my plex server. It displays the current streams, how many of them are transcode streams, and if there's a plex update available. Whenever there's an update available, the whole thing gets stuck and no longer upd...
[ "I'm an idiot!\nI copied over from a previous section of code the part that changes the text when an update is available, and forgot to change which section of text it's changing.\nHere's what I changed\nfrom:\n update_avail['text']=update_avail.delete(\"1.0\", \"end\")\n if plex.isLatest() != True:\n upd...
[ 1 ]
[]
[]
[ "plex", "python", "tkinter" ]
stackoverflow_0074469003_plex_python_tkinter.txt
Q: Python Socket Programming: sending and receiving int data between server and client? I'm working on some code which establishes a client and server using socket for python. I want to take user input in my client, send that data over to my server, and then have the server send that info back into my client and stor...
Python Socket Programming: sending and receiving int data between server and client?
I'm working on some code which establishes a client and server using socket for python. I want to take user input in my client, send that data over to my server, and then have the server send that info back into my client and store it as an int Here is my server code: import socket s = socket.socket(socket.AF_INET, so...
[ "It was pretty close to working. On the server side choice = s.recv(2048) should be choice = conn.recv(2048). Also s.listen() and conn, addr = s.accept() should be outside the loop.\n#the server\nimport socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((socket.gethostname(), 8890))\n\ns.listen...
[ 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0074468725_python_sockets.txt
Q: Scipy.integrate.odeint TypeError: Float object is not callable I am new to Python, and am trying to solve this differential equation using scipy.interpolate.odeint. However, I keep getting a TypeError. I have looked, and cannot find how to fix this issue to get the odeint module to work. Below is my code: import p...
Scipy.integrate.odeint TypeError: Float object is not callable
I am new to Python, and am trying to solve this differential equation using scipy.interpolate.odeint. However, I keep getting a TypeError. I have looked, and cannot find how to fix this issue to get the odeint module to work. Below is my code: import pandas as pd import matplotlib.pyplot as plt import numpy as np from ...
[ "halflife = alpha - (beta(-delta+gamma*om))\n\nYou're trying to use typical math notation a(b) to multiply a * b, but that's not how Python syntax works. You have to explicitly use the symbol * to perform multiplication.\nTo Python, beta(-delta+gamma*om) looks like a function call.\nUse this instead:\nhalflife = a...
[ 3 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0074469055_python_scipy.txt
Q: Is it possible to be better than O(N+M) for Codility lesson MaxCounters using python? This is the code I am using for the Codility lesson: MaxCounters def solution(N, A): counters = [0] * N max_c = 0 for el in A: if el >= 1 and el <= N: counters[el-1] += 1 max_c = max(co...
Is it possible to be better than O(N+M) for Codility lesson MaxCounters using python?
This is the code I am using for the Codility lesson: MaxCounters def solution(N, A): counters = [0] * N max_c = 0 for el in A: if el >= 1 and el <= N: counters[el-1] += 1 max_c = max(counters[el-1], max_c) elif el > N: counters = [max_c] * N return cou...
[ "EDIT: following up on the discussion in the comments to this answer, tracking the last operation to avoid unnecessarily resetting the array in successive max_counter operations was the key to achieving the goal. Here's what the different solutions (one keeping track of the max and the second calculating the max on...
[ 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0058854370_python.txt
Q: Why can I assign elements to a list that I doesn't have a setter? I've been working on a school OOP python project and I stumbled upon this problem: class AList: def __init__(self, l): self.__a_private_attribute = l @property def l(self): return self.__a_private_attribute if __name__ ...
Why can I assign elements to a list that I doesn't have a setter?
I've been working on a school OOP python project and I stumbled upon this problem: class AList: def __init__(self, l): self.__a_private_attribute = l @property def l(self): return self.__a_private_attribute if __name__ == '__main__': li = AList([0]) li.l[0] = "this shouldn't work"...
[ "\nHow am I able to call methods on a list that does only have a getter and no setter\n\nBecause you never tried to set the list. You got the list, and then changed its first element. This is similar to doing:\nsome_var = li.l\nsome_var[0] = \"this shouldn't work\"\n\nIt works because lists are mutable, and you can...
[ 3 ]
[]
[]
[ "encapsulation", "oop", "python", "python_3.x" ]
stackoverflow_0074469038_encapsulation_oop_python_python_3.x.txt
Q: Why do I need to run the second loop to get the sigle value in django? The project was to create a filter page where users can filter the model data based on their chosen criteria. The whole thing is working but a specific part is not clear and not making sense. Here is my model- class Author(models.Model): n...
Why do I need to run the second loop to get the sigle value in django?
The project was to create a filter page where users can filter the model data based on their chosen criteria. The whole thing is working but a specific part is not clear and not making sense. Here is my model- class Author(models.Model): name=models.CharField(max_length=30) def __str__(self): return ...
[ "You haven't defined ForeignKey.related_name so you should use default so:\n\n\n<table class=\"three\">\n <tr>\n <th>Title</th>\n <th>Author</th>\n <th>Category</th>\n <th>Views</th>\n <th>Date Published</th>\n \n \n </tr>\n \n {% for journal in queryset ...
[ 1 ]
[]
[]
[ "django", "django_queryset", "django_templates", "django_views", "python" ]
stackoverflow_0074468833_django_django_queryset_django_templates_django_views_python.txt
Q: why am I not able to input the data I was learning python as a beginner through YouTube. In the video I was following the output was shown in terminal, but not in my case. It doesn't even accept taking in data for the variable. What am I doing wrong? the code was simply : a = input("Enter name") print(a) but the ...
why am I not able to input the data
I was learning python as a beginner through YouTube. In the video I was following the output was shown in terminal, but not in my case. It doesn't even accept taking in data for the variable. What am I doing wrong? the code was simply : a = input("Enter name") print(a) but the output would only show the text, but wont...
[ "You code should be working fine. Maybe, you are trying to edit the text Enter name, which is not possible in the terminal.\nTry typing the name and pressing <Enter> when the text Enter name shows up.\nYou can test it here: https://pythonsandbox.com/code/pythonsandbox_u20054_20A4kkNBC961W5aZFb2NJCBW_v0.py\nBut keep...
[ 0, 0 ]
[]
[]
[ "input", "python", "visual_studio_code" ]
stackoverflow_0074460575_input_python_visual_studio_code.txt
Q: When trying to apply a simple function I am getting this error "The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item()...." I have a dataframe with tick data that is below and I am trying to apply a simple function that will allow me to compare whether or not the last price was at the bid or ask...
When trying to apply a simple function I am getting this error "The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item()...."
I have a dataframe with tick data that is below and I am trying to apply a simple function that will allow me to compare whether or not the last price was at the bid or ask and thus representing aggressive buying or selling. However when I apply the function I receive the error "The truth value of a Series is ambiguous...
[ "The problem is that in this if statement if x > ES_Data['Bid'] the result of x > ES_Data['Bid'] is a False/True series comparing the given x to the each element in ES_Data['Bid']. That is why you are getting the error telling you that the if statement is being applied to a full series.\nIf you are trying to apply ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074469043_python.txt
Q: FastAPI, SQLalchemy; By using Postman I can't post raw JSON body request correctly. It works fine with params not with raw JSON body My @router.post is like this: @router.post("/filter/filtering") async def filter_test(skip: int = 0, limit: int = 100, company_name: str = None, db: Session = Depends(get_db)): _...
FastAPI, SQLalchemy; By using Postman I can't post raw JSON body request correctly. It works fine with params not with raw JSON body
My @router.post is like this: @router.post("/filter/filtering") async def filter_test(skip: int = 0, limit: int = 100, company_name: str = None, db: Session = Depends(get_db)): _audits = crud.filter_test(db, company_name) return Response(status="Ok", code="200", message="Success fetch all data", result=_audits)...
[ "You either need to define a pydantic model as the body, or else use Body which is fine in your case as you're only accepting one value:\nfrom typing import Optional\nfrom fastapi import Body # not mentioning all the other fastapi imports here for brevity\n\n@router.post(\"/filter/filtering\")\nasync def filter_te...
[ 1 ]
[]
[]
[ "database", "fastapi", "postgresql", "postman", "python" ]
stackoverflow_0074463307_database_fastapi_postgresql_postman_python.txt
Q: How can I access specific columns from a CSV file and add it to a list without using external modules? def loadCSVData(filename): list = [] fileContent = open(filename, 'r', encoding = 'utf8') for line in fileContent: # HERE fileContent.close() return list If I were to have a...
How can I access specific columns from a CSV file and add it to a list without using external modules?
def loadCSVData(filename): list = [] fileContent = open(filename, 'r', encoding = 'utf8') for line in fileContent: # HERE fileContent.close() return list If I were to have a csv file that has 3 columns: name job pay 1 2 3 4 how can I access the name column and add the content...
[ "You can split the columns in each row yourself - at your own risk. Assuming this is a traditional CSV file, you could\ndef loadCSVData(filename):\n with open(filename) as fileobj:\n header = next(fileobj).strip().split(\",\")\n if header != [\"name\", \"job\", \"pay\"]:\n raise ValueErr...
[ 0 ]
[]
[]
[ "excel", "for_loop", "list", "python", "python_3.x" ]
stackoverflow_0074468559_excel_for_loop_list_python_python_3.x.txt
Q: How can I shift columns based on certain row? My datatable is below. menu_nm dtl rcp 0 sandwich amazing sandwich!!! bread 10g 1 hamburger bread 20g, vegetable 10g ??? 2 salad fresh salad!!! apple sauce 10g, banana 40g, cucumber 5g 3 juice sweet juice!! orange 50g, water 100ml 4 fruits strawberry 10g, grape 2...
How can I shift columns based on certain row?
My datatable is below. menu_nm dtl rcp 0 sandwich amazing sandwich!!! bread 10g 1 hamburger bread 20g, vegetable 10g ??? 2 salad fresh salad!!! apple sauce 10g, banana 40g, cucumber 5g 3 juice sweet juice!! orange 50g, water 100ml 4 fruits strawberry 10g, grape 20g, melon 10g ??? and I want to get ...
[ "assumption: rcp column contains \"???\" that needs to be replaced with the a values from dtl\n# create a filter where value under rcp is \"???\"\nm=df['rcp'].eq('???')\n\n# using loc, shift the values\n\ndf.loc[m, 'rcp'] = df['dtl']\ndf.loc[m, 'dtl'] = \"\"\ndf\n\n menu_nm dtl rcp\n0 ...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074469073_pandas_python.txt
Q: Jupyter Notebooks not running on VS Code Python extension I have installed latest Python 3 (python-3.11.0-amd64) and latest VS Code (VSCodeUserSetup-x64-1.73.1). I also installed the "Python Extension for Visual Studio Code". which as you can see it claimed that it comes with Jupyter Notebooks feature to Create ...
Jupyter Notebooks not running on VS Code Python extension
I have installed latest Python 3 (python-3.11.0-amd64) and latest VS Code (VSCodeUserSetup-x64-1.73.1). I also installed the "Python Extension for Visual Studio Code". which as you can see it claimed that it comes with Jupyter Notebooks feature to Create and edit Jupyter Notebooks I have selected the interpreter: an...
[ "The error prompt actually tells you how to solve the problem. Click install can solve it.\nThe Jupyter Notebook is an extension which needs jupyter package. So you have to install jupyter package by using command\npip install jupyter notebook.\nThe use steps in github also specify: Install Anaconda/Miniconda or an...
[ 0 ]
[]
[]
[ "jupyter_notebook", "python", "visual_studio_code" ]
stackoverflow_0074466717_jupyter_notebook_python_visual_studio_code.txt
Q: How to escape characters in Pango markup? My program has a gtk.TreeView which displays a gtk.ListStore. The gtk.ListStore contains strings like this: "<span size='medium'><b>"+site_title+"</b></span>"+"\n"+URL Where URL is (obviously) a URL string. Sometimes there are characters in URL that cause pango to fail t...
How to escape characters in Pango markup?
My program has a gtk.TreeView which displays a gtk.ListStore. The gtk.ListStore contains strings like this: "<span size='medium'><b>"+site_title+"</b></span>"+"\n"+URL Where URL is (obviously) a URL string. Sometimes there are characters in URL that cause pango to fail to parse the markup. Is there a way to escape U...
[ "glib.markup_escape_text may be a more canonical approach when using GTK.\n", "You need to escape the values. I'm not sure what exact format Pango requires, but it looks like HTML and the cgi.escape function may be all you need.\nimport cgi\nprint \"<span size='medium'><b>%s</b></span>\\n%s\" %\n (cgi.escap...
[ 22, 2, 0 ]
[]
[]
[ "gtk", "pango", "pygtk", "python" ]
stackoverflow_0001760070_gtk_pango_pygtk_python.txt
Q: Mapping two different together on columns or index I want to ask a question that how can I mapping one dataframe into another dataframe. The idea is like this, I have two dataframes, one have around 1,500 pools, and other dataframe contains around 25 rows. I want to match the price from second dataframe, into the ...
Mapping two different together on columns or index
I want to ask a question that how can I mapping one dataframe into another dataframe. The idea is like this, I have two dataframes, one have around 1,500 pools, and other dataframe contains around 25 rows. I want to match the price from second dataframe, into the first dataframe, by using the rate range as a factor. Cu...
[ "With the minimal description and no examples provided. I think what you are searching for is merge. What you would do will look something like this:\n# given df1, and df2\nshared_col_name = 'rate range'\n\ndf1.merge(df2, how='left', on=shared_col_name )\n\n\nYou can refer to documentation for more details.\nhttps:...
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074469117_dataframe_python.txt
Q: How to add input in the middle of a string? I'm very new to programming, only started learning python ~4 days ago and I'm having trouble figuring out how to print a user input as a string, in between other strings on the same line. Being so new to programming, I feel like the answer is staring me right in the face...
How to add input in the middle of a string?
I'm very new to programming, only started learning python ~4 days ago and I'm having trouble figuring out how to print a user input as a string, in between other strings on the same line. Being so new to programming, I feel like the answer is staring me right in the face but I don't have the tools or the knowledge to f...
[ "you can try this code:\n# Python3 code to demonstrate working of\n# Add Phrase in middle of String\n# Using split() + slicing + join()\n \n# initializing string\ntest_str = 'Wow that\\'s cool!'\n \n# printing original string\nprint(\"The original string is : \" + str(test_str))\n \n# initializing mid string\nmid_s...
[ 4, 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074468954_python.txt
Q: Strange behavior assigning builtin methods as class attributes I encountered a strange behavior that I cannot explain when assigning builtin methods as attributes to a class in Python. If I run the following python file: class A: a = bin b = lambda x: bin(x) print(A().a(2)) print(A().b(2)) The call t...
Strange behavior assigning builtin methods as class attributes
I encountered a strange behavior that I cannot explain when assigning builtin methods as attributes to a class in Python. If I run the following python file: class A: a = bin b = lambda x: bin(x) print(A().a(2)) print(A().b(2)) The call to A().a(2) returns a byte string, but the call to A().b(2) raises: T...
[ "The answer you've referenced is correct.\nIn the counter-example you gave the two built-in functions are indeed treated the same, that is no bound method object is created:\nB(1).d(2) == round(2) # not round(B(1), 2)\nB(1).c(2) == pow(2) # not pow(B(1), 2)\n\nthe issue arises from passing only one argument to po...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074469027_python.txt
Q: Python IndexError: list index out of range... Student Records Project, At a loss trying to trace the error I've cleaned up my code a bit according to some great recommendations from the community. However I still get the error. All of my close disclosing the error message is posted below the error message. Hopeful...
Python IndexError: list index out of range... Student Records Project, At a loss trying to trace the error
I've cleaned up my code a bit according to some great recommendations from the community. However I still get the error. All of my close disclosing the error message is posted below the error message. Hopefully this is correctly formatted; I greatly appreciate the help of this community. DELETING STUDENT INFORMATION : ...
[ "When adding a phone number in add_student_information there is a check if the number is too short. If it is, a message is displayed but a new number is not retried, so the length of student_mobile_number will get out of sync with the rest of the arrays. The delete function operates by the index of the student's la...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074468662_python.txt
Q: creating list from a string and than change that new list Hy guys this is my first time here.I am a beginner and i wantend to check how can i from a given string (which is: string="5,93,14,2,33" ) make a list, after that to get the square of each number from the list and than to return that list (with a squared va...
creating list from a string and than change that new list
Hy guys this is my first time here.I am a beginner and i wantend to check how can i from a given string (which is: string="5,93,14,2,33" ) make a list, after that to get the square of each number from the list and than to return that list (with a squared values) in to string? input should to be: string = "5,93,14,2,33"...
[ "Yes you started correctly.\n# First, let's split into a list:\nlist_of_str = your_list.split(',') # '2,3,3,4,5' -> ['2','3','4','5']\n\n# Then, with list comprehension, we transform each string into integer \n# (assuming there will only be integers)\nlist_of_numbers = [int(number) for number in list_of_str]\n\nNow...
[ 1, 1 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074469207_list_python_string.txt
Q: pycharm not showing anything on my laptop enter image description here every time I open my pycharm it is no doing anything just this screen It is not even showing my files I tried reinstalling after deleting allthe files A: I'm new too but I believe all you have to do is create a new .py by right-clicking on pr...
pycharm not showing anything on my laptop
enter image description here every time I open my pycharm it is no doing anything just this screen It is not even showing my files I tried reinstalling after deleting allthe files
[ "I'm new too but I believe all you have to do is create a new .py by right-clicking on project, then new, then new .py\n" ]
[ 0 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0074469176_pycharm_python.txt
Q: Issue with new isort extension installed as from VS-Code Update October 2022 (version 1.73) I'm using VS-Code version 1.73.1, with MS Python extension v2022.18.2, on Windows 10 Pro, Build 10.0.19045. After installing the October 2022 update of VS Code, when writing Python code I noticed nagging error diagnostics b...
Issue with new isort extension installed as from VS-Code Update October 2022 (version 1.73)
I'm using VS-Code version 1.73.1, with MS Python extension v2022.18.2, on Windows 10 Pro, Build 10.0.19045. After installing the October 2022 update of VS Code, when writing Python code I noticed nagging error diagnostics being issued by the isort extension about the import order of modules. Previously, I had never enc...
[ "Upgrade the isort extension version to latest(v2022.8.0).\n\n" ]
[ 3 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074461394_python_visual_studio_code.txt
Q: Creating a List and maintaining integer value I am new to python a bit. I am trying to convert a dataframe to list after changing the datatype of a particular column to integer. The funny thing is when converted to list, the column still has float. There are three columns in the dataframe, first two is float and I...
Creating a List and maintaining integer value
I am new to python a bit. I am trying to convert a dataframe to list after changing the datatype of a particular column to integer. The funny thing is when converted to list, the column still has float. There are three columns in the dataframe, first two is float and I want the last to be integer, but it still comes as...
[ "Yes, you are correct pandas is converting int to float when you use data.values\nYou can convert your float to int by using the below list comprehension:\ndata_to_List = [[x[0],x[1],int(x[2])] for x in data.values.tolist()]\n\nprint(data_to_List)\n\n[[1.53, 3.13, 0],\n [0.58, 2.83, 0],\n [0.28, 2.69, 0],\n [1.14, ...
[ 1 ]
[]
[]
[ "list", "pandas", "python" ]
stackoverflow_0074469122_list_pandas_python.txt
Q: How to summarize pytorch model Hello I am building a DQN model for reinforcement learning on cartpole and want to print my model summary like keras model.summary() function Here is my model class. class DQN(): ''' Deep Q Neural Network class. ''' def __init__(self, state_dim, action_dim, hidden_dim=64, lr=...
How to summarize pytorch model
Hello I am building a DQN model for reinforcement learning on cartpole and want to print my model summary like keras model.summary() function Here is my model class. class DQN(): ''' Deep Q Neural Network class. ''' def __init__(self, state_dim, action_dim, hidden_dim=64, lr=0.05): super(DQN, self)....
[ "Your DQN should be a subclass of nn.Module\nclass DQN(nn.Module):\n def __init__(self, state_dim, action_dim, hidden_dim=64, lr=0.05):\n ...\n\n" ]
[ 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074464424_python_pytorch.txt