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: Python: How is the docstring code running and is this the correct way to code a menu? Errors for this codeI don't understand how the code under the docstring is running. I am trying to make a main menu. I also keep getting errors under the comments def main_menu(): # Function for the interface where the user i...
Python: How is the docstring code running and is this the correct way to code a menu?
Errors for this codeI don't understand how the code under the docstring is running. I am trying to make a main menu. I also keep getting errors under the comments def main_menu(): # Function for the interface where the user is presented with a menu and given the options requiring the user's input choice = input...
[ "You are using triple quotes in the input function that takes it as a string!\nand for the menu it is correct but also checkout the case function newly launched in python version 3.11\n", "\nYou are using triple quotes in the input function that takes it as a string! and for the menu it is correct but also checko...
[ 0, 0 ]
[]
[]
[ "docstring", "function", "mainmenu", "python" ]
stackoverflow_0074535377_docstring_function_mainmenu_python.txt
Q: Google Or Tools Prefer more vehicles than saving cost I had total of 8 vehicles and have travel time, weight as cost parameter for route calculation. Below image is showing the plans created and Google OR-Tools has created plans for only five vehicles. If you note the green plan that is created, it is sending vehi...
Google Or Tools Prefer more vehicles than saving cost
I had total of 8 vehicles and have travel time, weight as cost parameter for route calculation. Below image is showing the plans created and Google OR-Tools has created plans for only five vehicles. If you note the green plan that is created, it is sending vehicle on left side and then on the right side serving the loc...
[ "Here are some helpful links for Global_Span which could be useful if you want to utilize more vehicles by setting it on distance dimension for example.\n /// Sets a cost proportional to the *global* dimension span, that is the\n /// difference between the largest value of route end cumul variables and\n /// the...
[ 1 ]
[]
[]
[ "google_visualization", "or_tools", "python" ]
stackoverflow_0074518518_google_visualization_or_tools_python.txt
Q: How to drop duplicates columns from a pandas dataframe, based on columns' values (columns don't have the same name)? I want to drop columns if the values inside of them are the same as other columns. From DF, it should yields DF_new: DF = pd.DataFrame(index=[1,2,3,4], columns = ['col1', 'col2','col3','col4','col5'...
How to drop duplicates columns from a pandas dataframe, based on columns' values (columns don't have the same name)?
I want to drop columns if the values inside of them are the same as other columns. From DF, it should yields DF_new: DF = pd.DataFrame(index=[1,2,3,4], columns = ['col1', 'col2','col3','col4','col5']) x = np.random.uniform(size=4) DF['col1'] = x DF['col2'] = x+2 DF['col3'] = x DF ['col4'] = x+2 DF['col5'] = [5,6,7,8] d...
[ "You can use:\ndf = df.T.drop_duplicates().T\n\n\nStep by step:\ndf2 = df.T # T = transpose (convert rows to columns)\n\n 1 2 3 4\ncol1 0.67075 0.707864 0.206923 0.168023\ncol2 2.67075 2.707864 2.206923 2.168023\ncol3 0.67075 0.707864 0.206923 0.168023\ncol4 2.67075 ...
[ 2, 0 ]
[]
[]
[ "duplicates", "pandas", "python" ]
stackoverflow_0074534831_duplicates_pandas_python.txt
Q: How to disable inline labels in django inline admin? In my Django admin, I want to disable the below-shown paragraph. Please help me out. I am new to changing djano admin. Link to Image Here is my current admin.py class ImageInlineAdmin(admin.StackedInline): model = Image max_num = 1 class BlogAdmin(admi...
How to disable inline labels in django inline admin?
In my Django admin, I want to disable the below-shown paragraph. Please help me out. I am new to changing djano admin. Link to Image Here is my current admin.py class ImageInlineAdmin(admin.StackedInline): model = Image max_num = 1 class BlogAdmin(admin.ModelAdmin): inlines = [ParagraphInlineAdmin, ImageI...
[ "You need to remove the str function from the model that will solve the problem\n", "I removed it via css trick as follow:\nclass MyClassAdmin(admin.modelAdmin):\n \n inlines = [MyTabularAdmin]\n\n class Media:\n css = {\n 'custom': ('css/custom_admin.css',),\n }\n\nthe css is:\n...
[ 0, 0, 0, 0 ]
[]
[]
[ "django", "django_admin", "django_ckeditor", "python" ]
stackoverflow_0067940490_django_django_admin_django_ckeditor_python.txt
Q: Select rows from SQL table based on multiple LIKE I am connecting to some SQL table through sqlserver within Python environment. I have an SQL table like this one but instead of 6 rows it has thousands of rows with several combinations of deal names and Loan IDs. Loan IDs follow a specific pattern with four digits...
Select rows from SQL table based on multiple LIKE
I am connecting to some SQL table through sqlserver within Python environment. I have an SQL table like this one but instead of 6 rows it has thousands of rows with several combinations of deal names and Loan IDs. Loan IDs follow a specific pattern with four digits followed by underscore and then the actual Loan ID. ...
[ "Thanks for your responses. I managed to resolve this issue by doing the following:\nI first extracted the loan id from the given table by doing:\nRIGHT(unique_id, 8) AS id\nI then looked-up to the given list of IDs by doing:\nWHERE id IN {tuple(loan_idlist)}\n" ]
[ 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0074532823_python_sql.txt
Q: How can I load an image into a tkinter window/canvas? I am trying to have an image show up on a tkinter window. I have managed to do so in the past, but somehow my current attempt is failing at every step. Hopefully someone can guide me to the proper way and help me fix it. I'm currently trying with this code. The...
How can I load an image into a tkinter window/canvas?
I am trying to have an image show up on a tkinter window. I have managed to do so in the past, but somehow my current attempt is failing at every step. Hopefully someone can guide me to the proper way and help me fix it. I'm currently trying with this code. The error I'm getting is _tkinter.TclError: image "paco_img" d...
[ "As very well explained in comments by @JRiggles, first you need a Python library to handle the image.\nOf course, you can install it with pip:\npip install Pillow\n\nThen, using the tkinter hello-world-program as base, all you need to do is load the necessary libraries, load your image and to display it use either...
[ 0 ]
[]
[]
[ "image", "python", "python_3.x", "tkinter", "tkinter_canvas" ]
stackoverflow_0074535657_image_python_python_3.x_tkinter_tkinter_canvas.txt
Q: remove \n from a line in python I have a txt file that I need to convert into a table. If I have a case like this: --------------------------------------------- |apple|very good|every day|fruit |chocolate|not so good|just\n some times|snack |bread|good|every day|whole|carbs --------------------------------------- ...
remove \n from a line in python
I have a txt file that I need to convert into a table. If I have a case like this: --------------------------------------------- |apple|very good|every day|fruit |chocolate|not so good|just\n some times|snack |bread|good|every day|whole|carbs --------------------------------------- I splitted the file on the '|' but t...
[ "Sometimes the \\n is actually \\r\\n under the hood\ntry this if it helps\nnew_list.append(line.replace('\\n', ' ').replace('\\r\\n', ' ').split('|'))\n\n", "If you are trying to remove a literal newline, then just use two backslashes: replace('\\\\n', ' '). Python uses the backslash as an escape character and s...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "newline", "python", "trailing_newline" ]
stackoverflow_0074535122_newline_python_trailing_newline.txt
Q: Python - [Errno 111] Connection refused on client side of the connection I'm trying to create a chat between client and server written in Python, using SSL protocols with mutual authentication (i.e: server authenticates client and client authenticates server using certificates). My host machine is being used as th...
Python - [Errno 111] Connection refused on client side of the connection
I'm trying to create a chat between client and server written in Python, using SSL protocols with mutual authentication (i.e: server authenticates client and client authenticates server using certificates). My host machine is being used as the server, and my laptop is the client. When attempting to connect to my host i...
[ "I found what was wrong: I was trying to connect to my public IP address (which I found by searching for \"What is my ip\" on Google), but instead what should be done is to connect to the private IP address (I guess that's the correct name), and you can see yours using ifconfig on Linux and Mac and ipconfig on Wind...
[ 0 ]
[]
[]
[ "connection", "python", "sockets" ]
stackoverflow_0074519698_connection_python_sockets.txt
Q: Logging in Python Django: INFO not logging onto file I have setup a logger in my Django project for 4 different cases: info messages, debug messages, error messages, ad gunicorn logging. Here is the content of my settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { ...
Logging in Python Django: INFO not logging onto file
I have setup a logger in my Django project for 4 different cases: info messages, debug messages, error messages, ad gunicorn logging. Here is the content of my settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "main_formatter": { "format": "{asctim...
[ "I don't know anything about Django's logging. But it sticks out to me that your loggers dictionary appears to specify the main key 3 times. I would expect that each one overwrites the previous and so your DEBUG and INFO settings are being lost/replaced with your ERROR settings.\n" ]
[ 0 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0074536177_django_logging_python.txt
Q: Update Python dictionary with appended list value I have a dataframe with price quotes for a variety of parts and makers. ~10k parts and 10 makers, so my dataset contains up to 100k rows, looking roughly like this: Part Maker Price 1 Alpha 1.00 2 Alpha 1.30 3 Alpha 1.25 1 Bravo 1.10 2 Bravo 1.02 3 Bravo 1....
Update Python dictionary with appended list value
I have a dataframe with price quotes for a variety of parts and makers. ~10k parts and 10 makers, so my dataset contains up to 100k rows, looking roughly like this: Part Maker Price 1 Alpha 1.00 2 Alpha 1.30 3 Alpha 1.25 1 Bravo 1.10 2 Bravo 1.02 3 Bravo 1.15 4 Bravo 1.19 1 Charlie .99 2 Charli...
[ "In your original code, the actual problem was on line 9 of the first fragment: you set vale to a string, not to a list. Also, calling list(some_string) dos not what you expect: it creates a list of single chars, not a [some_string].\nI took the liberty to improve the overall readability by extracting common keys t...
[ 1, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074535973_dictionary_python.txt
Q: Determine Shortest Distance between two moving points Im am trying to produce the shortest distance between the two orbiting points (Earth and Jupiter) created by this orbital model. I'vebeen working on this for quite some time but have been struggling. Could someone sugest a way to create this output or possibly ...
Determine Shortest Distance between two moving points
Im am trying to produce the shortest distance between the two orbiting points (Earth and Jupiter) created by this orbital model. I'vebeen working on this for quite some time but have been struggling. Could someone sugest a way to create this output or possibly create a line connecting the two points and display their d...
[ "The connection line between Jupiter and the Earth can be drawn using the arrow method of matplotlib. This allows to add arrow heads if desired. The distance can be added as a normal label.\nannotation = ax.arrow(0, AU, 0, (5.2 - 1) * AU)\ntext_a = ax.text(0, (5.2 + 1) / 2 * AU, '', ha='center', backgroundcol...
[ 0 ]
[]
[]
[ "animation", "matplotlib", "matplotlib_animation", "physics", "python" ]
stackoverflow_0074535579_animation_matplotlib_matplotlib_animation_physics_python.txt
Q: Python JSON assign data from API I have a py file to read data from Wordpress API and pass values to another fields of other API. When values are singles, i have no problem, but i don't know how make that: When i read one field from the API, the states values, comes with code instead the text value. For example, w...
Python JSON assign data from API
I have a py file to read data from Wordpress API and pass values to another fields of other API. When values are singles, i have no problem, but i don't know how make that: When i read one field from the API, the states values, comes with code instead the text value. For example, when the text value in Wordpress is Bar...
[ "Make sure to convert to a JSON object before accessing fields (data = json.loads(json_str))\nresponse = { \"billing\": { \"address_1\": \"C/GUSTAVO ADOLFO BECQUER, 4\", \"city\": \"SEVILLA\", \"state\": \"SE\"}}\n\nprint(response[\"billing\"].get(\"address_1\", None))\n\n" ]
[ 0 ]
[]
[]
[ "json", "python", "wordpress" ]
stackoverflow_0074535916_json_python_wordpress.txt
Q: Django save form with foreign key I am currently trying to create a form where users get to fill in their details after creating an account. The idea is that every user, after registration, gets redirected to this form page to fill it out. To achieve this, i'm using foreign keys.However it doesn't save to database...
Django save form with foreign key
I am currently trying to create a form where users get to fill in their details after creating an account. The idea is that every user, after registration, gets redirected to this form page to fill it out. To achieve this, i'm using foreign keys.However it doesn't save to database. models.py class User(AbstractUser): ...
[ "You need to exclue user field from ModelForm like this\nform.py\nclass Details(forms.ModelForm):\n class Meta:\n model = Detail\n fields = \"__all__\"\n exclude =[\"user\"]\n\nviews.py\ndef details(request):\n if request.method ==\"POST\":\n form = Details(request.POST)\n if form.is_val...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0074535952_django_django_forms_django_models_python.txt
Q: How to create Great Expectations checkpoint for Pandas dataframe? My datasource config looks like: datasource_config = { "name": "example_datasource", "class_name": "Datasource", "module_name": "great_expectations.datasource", "execution_engine": { "module_name": "great_expectations.executi...
How to create Great Expectations checkpoint for Pandas dataframe?
My datasource config looks like: datasource_config = { "name": "example_datasource", "class_name": "Datasource", "module_name": "great_expectations.datasource", "execution_engine": { "module_name": "great_expectations.execution_engine", "class_name": "PandasExecutionEngine", }, "...
[ "Great expectations has multiple execution engines. You are specifying the PandasExecutionEngine. The execution engine should be changed to SparkDFExecutionEngine or you should cast your dataframe to Pandas.\n" ]
[ 0 ]
[]
[]
[ "great_expectations", "pandas", "python", "validation" ]
stackoverflow_0069495245_great_expectations_pandas_python_validation.txt
Q: I want to run a python script via integrated terminal using Ctrl + Enter in Visual Studio Code Suppose I have foo.py. I have to right click foo.py -> Open as Integrated Terminal -> (in terminal, python foo.py) Is there a way to Ctrl + Enter and it does the above. And can you select a single function and run only t...
I want to run a python script via integrated terminal using Ctrl + Enter in Visual Studio Code
Suppose I have foo.py. I have to right click foo.py -> Open as Integrated Terminal -> (in terminal, python foo.py) Is there a way to Ctrl + Enter and it does the above. And can you select a single function and run only that a bit like Jupyter notebook.
[ "See the docs: Keyboard Shortcuts editor\nThe commands you're looking for are:\n\nPython: Run Python File in Terminal (python.execInTerminal)\nPython: Run Selection/Line in Python Terminal (python.execSelectionInTerminal)\n\nAlthough note that they work differently: the first runs the file like you want, and the se...
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074536293_python_visual_studio_code.txt
Q: Web Page Icon's Changing Problem in Multiple Page App Version: Streamlit 1.13.0 Structure: Main folder > 1__main.py in pages folder > 2_❌_project.py In 1__main.py: st.set_page_config( page_title= “Multipage App”, page_icon=) When I press ❌ in the sidebar, icon is disappearing in the header tab. Streamlit theme c...
Web Page Icon's Changing Problem in Multiple Page App
Version: Streamlit 1.13.0 Structure: Main folder > 1__main.py in pages folder > 2_❌_project.py In 1__main.py: st.set_page_config( page_title= “Multipage App”, page_icon=) When I press ❌ in the sidebar, icon is disappearing in the header tab. Streamlit theme comes instead. How Can I solve this problem? Which icon do I...
[ "In every page file, every piece of code including the page_config should be in a function, you can name that the main function and pass every code into it:\nfor e.g:\n# Homepage\n\nimport streamlit as st\n...\n\ndef main()\n st.set_page_config(\"Replace me with your page config\")\n # The rest of your code\n...
[ 1 ]
[]
[]
[ "python", "streamlit" ]
stackoverflow_0074521013_python_streamlit.txt
Q: How to retrieve query parameter from URL after RedirectResponse in FastAPI? I'm implementing an oauth autorization code flow. What I want is to retrieve the code that shows in the url after redirection. I've made researches but haven't found something really helpful. I think that if I can get the current url in th...
How to retrieve query parameter from URL after RedirectResponse in FastAPI?
I'm implementing an oauth autorization code flow. What I want is to retrieve the code that shows in the url after redirection. I've made researches but haven't found something really helpful. I think that if I can get the current url in the browser after the RedirectResponse, I can then extract the code parameter of it...
[ "You should instead retrieve the value of the code parameter inside the /callback, not /install, endpoint, since that is the endpoint to which you are being redirected—according to the link provided in your question:\nhttp://127.0.0.1:8000/callback/?code=random-string-xyz\n ^^^^^^^^^\n\nIn FastA...
[ 1 ]
[]
[]
[ "fastapi", "oauth", "python", "redirect" ]
stackoverflow_0074448083_fastapi_oauth_python_redirect.txt
Q: Comparing row-wise DATES and substituting the values with 1 or 0 I have one column to compare with other 100 columns. The columns I need to compare are all DATETIME The problem statement is as follows: If the date in the "UTIL_DATE" is greater than equal to the date in other columns, substitute that row's value t...
Comparing row-wise DATES and substituting the values with 1 or 0
I have one column to compare with other 100 columns. The columns I need to compare are all DATETIME The problem statement is as follows: If the date in the "UTIL_DATE" is greater than equal to the date in other columns, substitute that row's value to 1 Else, 0 I have attached an example image below for the reference....
[ "can you try this:\ndf=df.set_index('UTIL_DATE')\ndf=df.ge(df.index, axis=0)\ndf=df.replace({True:1,False:0})\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "datetime", "numpy", "pandas", "python" ]
stackoverflow_0074536364_dataframe_datetime_numpy_pandas_python.txt
Q: merge rows into new column value I am taking a df that is all dup value pairs and then from the 2nd row take the 2nd column value and add it to the first row in a new column called 'new_amt' then inserting NaN for the second row and new third column. After I'll drop all row that contain NaN. so the dataframe look ...
merge rows into new column value
I am taking a df that is all dup value pairs and then from the 2nd row take the 2nd column value and add it to the first row in a new column called 'new_amt' then inserting NaN for the second row and new third column. After I'll drop all row that contain NaN. so the dataframe look like this: ref_num Amt fy fund_ty...
[ "Why not do both operations at once (resolve duplicates as you describe and drop the redundant rows)?\nk = 'ref_num'\nnewdf = df.drop_duplicates(subset=k, keep='first').merge(\n df.drop_duplicates(subset=k, keep='last'), on='ref_num', suffixes=('', '_new'))\n>>> newdf\n ref_num Amt Amt_new\n0 1 10 ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074536138_pandas_python.txt
Q: Zip and merge the string ''' return a new string containing the 2 strings interwoven or zipped together. ex: Input: 'hi' 'ha' Ouput: hhia Input: 'lzr','iad' output: lizard def interleave(str1, str2): ls1 = zip(str1, str2) print(list(ls1)) # prints [('h', 'h'), ('i', 'a')] as expected ls2 = [''.join...
Zip and merge the string
''' return a new string containing the 2 strings interwoven or zipped together. ex: Input: 'hi' 'ha' Ouput: hhia Input: 'lzr','iad' output: lizard def interleave(str1, str2): ls1 = zip(str1, str2) print(list(ls1)) # prints [('h', 'h'), ('i', 'a')] as expected ls2 = [''.join(x) for x in ls1] print(ls...
[ "Because zip() is a python iterator. Once you retrieve the values of ls1 in third line(print(list(ls1))), the ls1 become empty.\nTry this case, it would be more clear:\ndef interleave(str1, str2):\n ls1 = zip(str1, str2)\n print(list(ls1)) # prints [('h', 'h'), ('i', 'a')] as expected\n print(list(ls1)) ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074526570_python.txt
Q: How to display a HTML file and text with flask python I am trying to make a website that displays text I can change (preferably instantly). I was able to do this with: @app.route('/') def index(): global val return str(val) along with a function running at the same time allowing me to change the variable ...
How to display a HTML file and text with flask python
I am trying to make a website that displays text I can change (preferably instantly). I was able to do this with: @app.route('/') def index(): global val return str(val) along with a function running at the same time allowing me to change the variable "val" However, now I would like to be able to display data ...
[ "In render_template(\"form.html\" , str=str)\nAnd in form.html\n<body>\n <p>{{str}}</p>\n</body>\n\nThis way using jinja syntax you can display the variable\nthank you\n" ]
[ 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074536401_flask_python.txt
Q: Regex Python pattern matching import re string = '39801 356, 2102 1111' # Three digit number followed by space followed by two digit number pattern = '(\d{3})' --- This i need to match 398 now its matching 801 # match variable contains a Match object. match = re.search(pattern, string) if match: print(match...
Regex Python pattern matching
import re string = '39801 356, 2102 1111' # Three digit number followed by space followed by two digit number pattern = '(\d{3})' --- This i need to match 398 now its matching 801 # match variable contains a Match object. match = re.search(pattern, string) if match: print(match.group()) else: print("pattern no...
[]
[]
[ "You need to indicate the match starts at the beginning of the string.\nA ^ is needed at the begging of the search.\nThe pattern is ^\\d{3}\nTake a look at the example regex https://regex101.com/r/jk44z6/2\n" ]
[ -1 ]
[ "python", "regex" ]
stackoverflow_0074536475_python_regex.txt
Q: How to write a python program to identify phoone numbers? Hi I have wirtten some code to identify phone numbers but it is not working as expected phone numbers should be format +44-4411109923 Area code such as +44 is optional and - and space before the phone number is also optional. I have written code below impor...
How to write a python program to identify phoone numbers?
Hi I have wirtten some code to identify phone numbers but it is not working as expected phone numbers should be format +44-4411109923 Area code such as +44 is optional and - and space before the phone number is also optional. I have written code below import re phoneregex = re.compile(r'[+0-9]?(\s|-)\d{10}') text = inp...
[ "I've fixed your phoneregex pattern and created a function that determines whether a string represents a phone number. Here's the code:\n\nimport re\n\n\ndef is_phone_number(phone_number: str) -> bool:\n \"\"\"Determine if string represents a phone number.\n\n A valid phone number is of one of the following f...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074533482_python_python_3.x.txt
Q: I am not clear on how to go past this point as it returns an error of "could not convert string to float X = Liver_data.drop('Class',axis=1) y = Liver_data['Class'] -1 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, stratify=y, random_state=99) scaler = StandardScaler() X_train = scale...
I am not clear on how to go past this point as it returns an error of "could not convert string to float
X = Liver_data.drop('Class',axis=1) y = Liver_data['Class'] -1 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, stratify=y, random_state=99) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) ValueError Tracebac...
[ "As you only want to use \"Total Bilirubin\" variable so you need to use that column in X. Something like X = Liver_data.loc[:,[\"Total Bilirubin\"]] in that way Standard Scaler works fine because only works with numeric columns. As you are passing string columns to the Standard Scaler will throw an error for the ...
[ 0 ]
[]
[]
[ "neural_network", "python", "train_test_split" ]
stackoverflow_0074496541_neural_network_python_train_test_split.txt
Q: i need help creating a function of add two matrices and return the sum matrix The below code looks to be error free to me at least. But I'm not getting the output I want, but if i dont use the function and add the two of them directly with the same syntax, I'm getting the correct answer. pls help a = [[1,1],[2,2]...
i need help creating a function of add two matrices and return the sum matrix
The below code looks to be error free to me at least. But I'm not getting the output I want, but if i dont use the function and add the two of them directly with the same syntax, I'm getting the correct answer. pls help a = [[1,1],[2,2]] #first matrix b = [[4,4],[3,3]] #second matrix #creating a function to add...
[ "Can you make sure the return statement is given outside both the for loops?.\nSeems like you have given the return statement inside for loop of j, So It's calculating just one sum and returning\ndef sum(m,n): \no = [[0,0],[0,0]] \nfor i in range(2): \n for j in range(2): \n o[i][j] = m[i][j] + n[i][j] \n...
[ 1, 0, 0 ]
[]
[]
[ "function", "list", "matrix", "python" ]
stackoverflow_0074536346_function_list_matrix_python.txt
Q: Select Pandas rows based on list index I have a dataframe df: 20060930 10.103 NaN 10.103 7.981 20061231 15.915 NaN 15.915 12.686 20070331 3.196 NaN 3.196 2.710 20070630 7.907 NaN 7.907 6.459 Then I want to select rows with certain sequence numbers which indic...
Select Pandas rows based on list index
I have a dataframe df: 20060930 10.103 NaN 10.103 7.981 20061231 15.915 NaN 15.915 12.686 20070331 3.196 NaN 3.196 2.710 20070630 7.907 NaN 7.907 6.459 Then I want to select rows with certain sequence numbers which indicated in a list, suppose here is [1,3], then ...
[ "Use .iloc for integer based indexing and .loc for label based indexing. See below example:\nind_list = [1, 3]\ndf.iloc[ind_list]\n\n", "you can also use iloc:\ndf.iloc[[1,3],:]\n\nThis will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that cas...
[ 222, 142, 103, 19, 5, 2, 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0019155718_pandas_python.txt
Q: PyInstaller windows binary missing third party python module system specs: PyInstaller: 5.6.2 Python: 3.9.2 Windows-10-10.0.15063-SP0 I set up a virtual environment and install my requirements, check. Following along with the pyinstaller documentation section 2.6, I run the command: pyinstaller myProgram.py As t...
PyInstaller windows binary missing third party python module
system specs: PyInstaller: 5.6.2 Python: 3.9.2 Windows-10-10.0.15063-SP0 I set up a virtual environment and install my requirements, check. Following along with the pyinstaller documentation section 2.6, I run the command: pyinstaller myProgram.py As the docs describe, this autogenerates a .spec file for my applicati...
[ "Ah ha! I was making this more complicated than it needed to be. no hook required. removed any mention of hookpath from spec file, and updated:\npathex=['./galil'],\n\nI will leave this here. someone can mark it as a duplicate because I found my answer here\n" ]
[ 0 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0074535250_pyinstaller_python.txt
Q: regex: negate a group with condition is it possible to match strings if a group is not present between a starting and end position, except if the group is followed by a certain character e.g. '§'? # match if '\.\s' is not present between 'start' and 'end' re.search(r'start((?!\.\s).)*end', string) for example tho...
regex: negate a group with condition
is it possible to match strings if a group is not present between a starting and end position, except if the group is followed by a certain character e.g. '§'? # match if '\.\s' is not present between 'start' and 'end' re.search(r'start((?!\.\s).)*end', string) for example those two strings should match: string = 'sta...
[ "You can add another negative lookahead after \\.\\s\nstart((?!\\.\\s(?!§)).)*end\n\nSee this demo at regex101\n" ]
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074536451_python_regex.txt
Q: Google cloud PubSub service not working (Python) I am trying to use the pub sub service on my python application. When I am running the code it get stuck on the last publisher line for some reason and the code never end. The subscriber seems fine.Does someone know what is wrong with my code? Publisher: import os f...
Google cloud PubSub service not working (Python)
I am trying to use the pub sub service on my python application. When I am running the code it get stuck on the last publisher line for some reason and the code never end. The subscriber seems fine.Does someone know what is wrong with my code? Publisher: import os from google.cloud import pubsub_v1 credentials_path = ...
[ "Google provides decent documentation for using its services including Pub/Sub including a basic Python example that would have helped you avoid your problem.\nAside: your publisher and subscriber snippets set GOOGLE_APPLICATION_CREDENTIALS statically within the code. Don't do this! Set the environment variable bef...
[ 3 ]
[]
[]
[ "google_cloud_platform", "google_cloud_pubsub", "python" ]
stackoverflow_0074535931_google_cloud_platform_google_cloud_pubsub_python.txt
Q: Convert txt file to csv, separation specific lines to column I am currently try to have the data like this (The ... just means there are more lines, no need to post the entire file here.) 376 932 noms sommets 0000 Abbesses 0001 Alexandre Dumas 0002 Alma Marceau ... 0375 Étienne Marcel coord sommets 0000 308 536 00...
Convert txt file to csv, separation specific lines to column
I am currently try to have the data like this (The ... just means there are more lines, no need to post the entire file here.) 376 932 noms sommets 0000 Abbesses 0001 Alexandre Dumas 0002 Alma Marceau ... 0375 Étienne Marcel coord sommets 0000 308 536 0001 472 386 0002 193 404 ... 0375 347 412 arcs values 0 238 41 0 15...
[ "from pathlib import Path\n\nimport pandas as pd\n\nf = Path(\"metro\")\n\nlines = [[], [], []]\nfile_num = -1\n\nfor line in f.read_text().split(\"\\n\"):\n if not line:\n continue\n cells = line.split(maxsplit=1)\n if cells[0] in [\"noms\", \"coord\", \"arcs\"]:\n file_num += 1\n if file...
[ 1, 1, 1 ]
[]
[]
[ "csv", "python", "txt" ]
stackoverflow_0074534469_csv_python_txt.txt
Q: Failed building wheel for python-rtmidi I'm trying to import magenta to use wavenet, however it always fails and I cannot find any useful information online. It keeps give me this error information Building wheels for collected packages: numba, python-rtmidi, llvmlite Building wheel for numba (setup.py) ... erro...
Failed building wheel for python-rtmidi
I'm trying to import magenta to use wavenet, however it always fails and I cannot find any useful information online. It keeps give me this error information Building wheels for collected packages: numba, python-rtmidi, llvmlite Building wheel for numba (setup.py) ... error error: subprocess-exited-with-error × ...
[ "Try setting this environment variable first:\nexport SETUPTOOLS_USE_DISTUTILS=stdlib\n\nor alternatively prefix your command, e.g. change poetry install to:\nSETUPTOOLS_USE_DISTUTILS=stdlib poetry install\n\n(source)\n" ]
[ 0 ]
[]
[]
[ "magenta", "python" ]
stackoverflow_0074500708_magenta_python.txt
Q: Injecting function call after __init__ with decorator I'm trying to find the best way to create a class decorator that does the following: Injects a few functions into the decorated class Forces a call to one of these functions AFTER the decorated class' __init__ is called Currently, I'm just saving off a refere...
Injecting function call after __init__ with decorator
I'm trying to find the best way to create a class decorator that does the following: Injects a few functions into the decorated class Forces a call to one of these functions AFTER the decorated class' __init__ is called Currently, I'm just saving off a reference to the 'original' __init__ method and replacing it with...
[ "Based on this post and this answer, an alternative way to do this is through a custom metaclass. This would work as follows (tested in Python 2.7):\n# define a new metaclass which overrides the \"__call__\" function\nclass NewInitCaller(type):\n def __call__(cls, *args, **kwargs):\n \"\"\"Called when you...
[ 16, 2, 1, 0 ]
[]
[]
[ "decorator", "pyqt4", "python" ]
stackoverflow_0016017397_decorator_pyqt4_python.txt
Q: Value error: The truth value of a series is ambiguous. Use a.empyt,a.bool(), a.utem(), a.any(), or a.all() I was trying to apply a function in python that checks for multiple conditions across different columns in a dataframe and returns a value. df= pd.DataFrame(data) def function(data): if data['product']= ...
Value error: The truth value of a series is ambiguous. Use a.empyt,a.bool(), a.utem(), a.any(), or a.all()
I was trying to apply a function in python that checks for multiple conditions across different columns in a dataframe and returns a value. df= pd.DataFrame(data) def function(data): if data['product']= product1: If data['tenure']> 4: return 19 X= df.apply(function) What am I doing wrong? I c...
[ "you need to compare with ==\nproduct1=\"some value\"\n\ndf= pd.DataFrame(data)\n\ndef function(data):\n if data['product']== product1:\n If data['tenure']> 4:\n return 19\n\nX= df.apply(function)\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074536345_pandas_python.txt
Q: How to access in base class method a certain class attributes all derived classes? I have a class hierarchy like this: class C: keys = {1} def get_keys(self): return C.keys + self... # ??? class D(C): keys = {2,3} class E(D): keys = {4,5} I'd like to access and gather together all keys ...
How to access in base class method a certain class attributes all derived classes?
I have a class hierarchy like this: class C: keys = {1} def get_keys(self): return C.keys + self... # ??? class D(C): keys = {2,3} class E(D): keys = {4,5} I'd like to access and gather together all keys contents from all derived classes (from self.__class__ to C) without the need of adding ...
[ "Have each class add its keys to the set inherited from the parent. Then use self.keys in the method.\nclass C:\n keys = {1}\n def get_keys(self):\n return self.keys\n\nclass D(C):\n keys = C.keys | {2,3}\n\nclass E(D):\n keys = D.keys | {4,5}\n\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074536667_python_python_3.x.txt
Q: Python Bigquery create temp table When I create temp table via python, an error throws 400 Use of CREATE TEMPORARY TABLE requires a script or session How can I create a session? from google.colab import auth from google.cloud import bigquery from google.colab import data_table client = bigquery.Client(project=proj...
Python Bigquery create temp table
When I create temp table via python, an error throws 400 Use of CREATE TEMPORARY TABLE requires a script or session How can I create a session? from google.colab import auth from google.cloud import bigquery from google.colab import data_table client = bigquery.Client(project=project, location = location) client.quer...
[ "You can create a session using the BigQuery API using the create_session parameter in a job config, for example:\njob_config=bigquery.QueryJobConfig(create_session=True)\nMore details on this excellent article:\nhttps://dev.to/stack-labs/bigquery-transactions-over-multiple-queries-with-sessions-2ll5\n", "That's ...
[ 1, 1 ]
[]
[]
[ "google_bigquery", "python", "temp_tables" ]
stackoverflow_0074529599_google_bigquery_python_temp_tables.txt
Q: How to calibrate camera and use it in real time? I am trying to calibrate two cameras. I want to calibrate each one individually. At this point, my script can calibrate both cameras successfully. But now I want to use those calibrated cameras in real time. the code that I am using is the one available in the OpenC...
How to calibrate camera and use it in real time?
I am trying to calibrate two cameras. I want to calibrate each one individually. At this point, my script can calibrate both cameras successfully. But now I want to use those calibrated cameras in real time. the code that I am using is the one available in the OpenCV documentation. Below is the code. I'll just share th...
[ "From calibration (OpenCV's calibrateCamera(), not your own function), you gain \"intrinsics\", i.e. camera matrix and distortion coefficients.\nStore those intrinsics.\nThen call initUndistortRectifyMap() with those intrinsics. You receive lookup maps suitable for remap(). You do this once, not for every video fra...
[ 1, 0 ]
[]
[]
[ "computer_vision", "opencv", "python" ]
stackoverflow_0074521195_computer_vision_opencv_python.txt
Q: Python annotation on __init__ for two ways to instantiate a class I have a class Circle class Circle: def __init__(self, R: float): self.R = R @property def A(self): return 3.14*self.R**2 # Annotation: Circle(R: float) -> None But I want two ways to create an instance of this class u...
Python annotation on __init__ for two ways to instantiate a class
I have a class Circle class Circle: def __init__(self, R: float): self.R = R @property def A(self): return 3.14*self.R**2 # Annotation: Circle(R: float) -> None But I want two ways to create an instance of this class using explicit arguments Given the radius R: Circle(R = 1) Given the di...
[ "I would write this as:\nclass Circle:\n def __init__(self, *, radius: float | None = None, diameter: float | None = None):\n if radius is diameter is None or None not in (radius, diameter):\n raise ValueError('radius xor diameter is required')\n elif radius is not None:\n sel...
[ 3, 2, 2 ]
[]
[]
[ "constructor", "parameter_passing", "python", "python_typing" ]
stackoverflow_0074509629_constructor_parameter_passing_python_python_typing.txt
Q: AttributeError: 'tuple' object has no attribute 'rank' when calling fit on a Keras model with custom generator I want to build a Neural Network with two inputs: for image data and for numeric data. So I wrote custom data generator for that. The train and validation dataframes contain 11 columns: image_name — path...
AttributeError: 'tuple' object has no attribute 'rank' when calling fit on a Keras model with custom generator
I want to build a Neural Network with two inputs: for image data and for numeric data. So I wrote custom data generator for that. The train and validation dataframes contain 11 columns: image_name — path to the image; 9 numeric features; target — class for the item (last column). The code for custom generator (based...
[ "You need to convert all the individual objects returned by both the training and validation generators to Numpy arrays:\n yield [np.array(imgs), np.array(cols)], np.array(targets)\n\nAlternatively, a simpler and much more efficient solution is to not iterate over the data batch at all; instead, we can take adva...
[ 9, 1 ]
[]
[]
[ "deep_learning", "keras", "neural_network", "python", "tensorflow" ]
stackoverflow_0062744659_deep_learning_keras_neural_network_python_tensorflow.txt
Q: jupyter server : not started, no kernel in vs code i am trying to use jupyter notebooks from vs code and installed jupyter notebook extension and i am using (base)conda environment for execution. while this happened Error: Jupyter cannot be started. Error attempting to locate jupyter: at A.startServer (c:\Users\DE...
jupyter server : not started, no kernel in vs code
i am trying to use jupyter notebooks from vs code and installed jupyter notebook extension and i am using (base)conda environment for execution. while this happened Error: Jupyter cannot be started. Error attempting to locate jupyter: at A.startServer (c:\Users\DELL\.vscode\extensions\ms-python.python-2020.2.63990\out\...
[ "I had exactly the same problem when I installed Visual Studio Code and tried to run some Python code from a jupyter notebook on my fresh Ubuntu 18.04.\nHow I solved it:\n1) Press Command+Shift+P to open a new command pallete\n2) Type >Python: Select Intepreter to start jupyter notebook server\n3) Open the notebook...
[ 58, 17, 11, 10, 4, 4, 2, 2, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "jupyter_notebook", "python", "visual_studio_code" ]
stackoverflow_0060330837_jupyter_notebook_python_visual_studio_code.txt
Q: TypeError: unsupported operand type(s) for ** or pow(): 'float' and 'CubicSpline' I am trying to solve a differential equation using scipy, but I cannot get past the TypeError that is being generated. I have looked, but I'm not sure how to solve this issue because the ** operator is what is used to denote an expon...
TypeError: unsupported operand type(s) for ** or pow(): 'float' and 'CubicSpline'
I am trying to solve a differential equation using scipy, but I cannot get past the TypeError that is being generated. I have looked, but I'm not sure how to solve this issue because the ** operator is what is used to denote an exponent. What can I do to solve this issue? Here is the data frame you will need to reprodu...
[ "The argument of CubicSpline.derivative(nu) is the derivative order, 1 for the first derivative, 2 for the second derivative, and so on. And you need to evaluate it on an argument to get a numerical value of the derivative at a given input.\n" ]
[ 0 ]
[]
[]
[ "python", "scipy", "typeerror" ]
stackoverflow_0074526991_python_scipy_typeerror.txt
Q: local variable 'x1' referenced before assignment python secant method I am trying to do the secant method to find the root of the polynonium (-2x**6)-(1.5x**4)+(10*x)+(2) with inithial value 2,3 and I get this error import numpy as np def f(x): return (-2*x**6)-(1.5*x**4)+(10*x)+(2) def secante(f,x,fp,N=100,...
local variable 'x1' referenced before assignment python secant method
I am trying to do the secant method to find the root of the polynonium (-2x**6)-(1.5x**4)+(10*x)+(2) with inithial value 2,3 and I get this error import numpy as np def f(x): return (-2*x**6)-(1.5*x**4)+(10*x)+(2) def secante(f,x,fp,N=100,emax=0.0001): for k in range(N): fp=(f(x1)-f(x0))/(x1-x0) ...
[ "You're referenceing x1 before you define it. You are also referencing x0 before it is defined. I'm not familiar with the math here anymore so I'm not confident with fixing the code but ultimately you need to declare these variables before the for loop so they exist before they are changed by the for loop, or els...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074536170_python.txt
Q: Incorrect path with function getcwd() I get the wrong path back. The Datafile is in D:... and get everytime the path C:\Python27\lib\site-packages\xy back from python. I use the function path = getcwd() How can I fix it? A: You may be executing the script in a different place than your intended directory. Solu...
Incorrect path with function getcwd()
I get the wrong path back. The Datafile is in D:... and get everytime the path C:\Python27\lib\site-packages\xy back from python. I use the function path = getcwd() How can I fix it?
[ "You may be executing the script in a different place than your intended directory.\nSolution 1: Move the .py file to the target directory, and execute it there.\n\nPros: \n\n\nEasy\nWorks cross-platform (and for other users - if you do this, use getcwdu for Unicode)\nNo hard-coded path strings\n\nCons:\n\n\nFile m...
[ 1, 0 ]
[]
[]
[ "getcwd", "path", "python" ]
stackoverflow_0034042056_getcwd_path_python.txt
Q: How to print the __str__ representation of the entire traceback When printing an exception using, for instance, print(ex), only the last exception in the chain is printed, how can I instead print all the exceptions in the chain without crowding it with excessive traceback information. For example: def test_with_c...
How to print the __str__ representation of the entire traceback
When printing an exception using, for instance, print(ex), only the last exception in the chain is printed, how can I instead print all the exceptions in the chain without crowding it with excessive traceback information. For example: def test_with_context(context: str, test: int) try: assert isinstance...
[ "I have produced a solution I'm not super keen on, but it does the job:\ndef cause_stack(exception: BaseException) -> List[BaseException]:\n if exception.__cause__ is None:\n return [exception]\n else:\n return [exception] + cause_stack(exception.__cause__)\n\n\ndef format_causes(exception: Base...
[ 0 ]
[]
[]
[ "error_handling", "exception", "python", "python_3.x", "raise" ]
stackoverflow_0074534502_error_handling_exception_python_python_3.x_raise.txt
Q: cryptography.exceptions.InvalidSignature: Signature did not match digest I wrote an example of KDC Server, using the package cryptography.fernet. I cannot understand why, randomly, sometimes it runs correctly and sometimes it ends with an exception: cryptography.exceptions.InvalidSignature: Signature did not match...
cryptography.exceptions.InvalidSignature: Signature did not match digest
I wrote an example of KDC Server, using the package cryptography.fernet. I cannot understand why, randomly, sometimes it runs correctly and sometimes it ends with an exception: cryptography.exceptions.InvalidSignature: Signature did not match digest. The keys are created once, at the startup of the main. So the issue s...
[ "The problem is caused by the Set returned in issue_session_key(). A Python Set is unordered, so response and invitation will be swapped in main() 50% of the time, causing the error. Use e.g. a Tuple instead of the Set. The Python Tuple is ordered:\n...\nreturn (\n keyA_KDC.encrypt(serialize(response)), # E(K...
[ 0 ]
[]
[]
[ "cryptography", "exception", "fernet", "python" ]
stackoverflow_0074535542_cryptography_exception_fernet_python.txt
Q: I'm trying to make a calculator but it doesn't work I'm new to python and trying to make a calculator. The actual calculator part works but I can't figure out how to make it so that when the user puts in something that is not "+, -, *, or /" it prints a sentence then closes. This is my code and the output (https:/...
I'm trying to make a calculator but it doesn't work
I'm new to python and trying to make a calculator. The actual calculator part works but I can't figure out how to make it so that when the user puts in something that is not "+, -, *, or /" it prints a sentence then closes. This is my code and the output (https://i.stack.imgur.com/EYzxg.png)
[ "if choice in [\"+\", \"/\", \"*\", \"-\"]:\n [do stuff]\nif choice not in [\"+\", \"/\", \"*\", \"-\"]:\n [do stuff]\n\nThough this is not the best way to do what you want\n", "The code you are trying to achieve:\nchoice = input(\"Enter '+' for addition, LA for subtraction, * for multiplication, and '/' for di...
[ 0, 0 ]
[]
[]
[ "calculator", "python" ]
stackoverflow_0074533945_calculator_python.txt
Q: django-plotly-dash multi session on CPU intensive pages Running django-plotly-dash, I have multiple python pages. The issue is that when I am loading one of the pages while it is running some calculations, I can not run the same page or other pages from a different session, and the webserver is not responding for ...
django-plotly-dash multi session on CPU intensive pages
Running django-plotly-dash, I have multiple python pages. The issue is that when I am loading one of the pages while it is running some calculations, I can not run the same page or other pages from a different session, and the webserver is not responding for other users. If I look at the runserver output, it is busy re...
[ "\nIf I look at the runserver output, it is busy rendering the first request only.\n\nIf I understand correctly, this means you use Django's development server, and thus that you are in development (if you use django-admin runserver in production, that's a serious issue).\n\nNow’s a good time to note: don’t use thi...
[ 1 ]
[]
[]
[ "django", "load_balancing", "plotly", "plotly_dash", "python" ]
stackoverflow_0074274383_django_load_balancing_plotly_plotly_dash_python.txt
Q: Uncertainty propagation and confidence intervals calculation using python scipy.curvefit I am trying to fit a function using scipy.optimize.curve_fit. I am implementing a fitting of data with the sum of 3 gaussians. Here is the data that must be fit. I need to estimate the parameters of each Gaussian and the erro...
Uncertainty propagation and confidence intervals calculation using python scipy.curvefit
I am trying to fit a function using scipy.optimize.curve_fit. I am implementing a fitting of data with the sum of 3 gaussians. Here is the data that must be fit. I need to estimate the parameters of each Gaussian and the errors of calculation of these parameters. So I need to calculate the uncertainty of the fitting p...
[ "One may calculate the uncertainty bands using strong analytical approach (if the function is known, like in my case). But it's pretty hard to obtain all the derivatives and even if it's possible a lot of calculations must be done for that.\nI havr tried to use simplified approach. I used Monte Carlo technique.\nI ...
[ 0 ]
[]
[]
[ "curve_fitting", "python", "scipy" ]
stackoverflow_0074523336_curve_fitting_python_scipy.txt
Q: How to get list of users who are having owner access for a azure subscription using python I am trying to get the list of users who are having owner access for a subscription. I tried checking for python azure sdk. But am not getting any api which does this functionality. Subscription list api is available but it ...
How to get list of users who are having owner access for a azure subscription using python
I am trying to get the list of users who are having owner access for a subscription. I tried checking for python azure sdk. But am not getting any api which does this functionality. Subscription list api is available but it is not providing details of users who are having access to the particular subscription. I tried ...
[ "Azure Python SDK\nIf you're looking to use the Azure Python SDK then you should use AuthorizationManagementClient class \nYou can try to get RoleAssignments for your subscription at the scope of subscription itself.\nI work closely with C#, so don't have Python code handy, but will try to update back with Python ...
[ 2, 1, 0 ]
[]
[]
[ "azure", "azure_active_directory", "azure_automation", "azure_sdk_python", "python" ]
stackoverflow_0052828180_azure_azure_active_directory_azure_automation_azure_sdk_python_python.txt
Q: Plotting points from a TKinter form I'm trying to learn GUIs in Python and trying to populate a plot as a test; I could get the random input to behave (see Add Red) but despite the x and y being fed in correctly (verified as print statements in debugging) the blue points snap to the origin and reset it to those va...
Plotting points from a TKinter form
I'm trying to learn GUIs in Python and trying to populate a plot as a test; I could get the random input to behave (see Add Red) but despite the x and y being fed in correctly (verified as print statements in debugging) the blue points snap to the origin and reset it to those values. What am I missing here? Thanks. imp...
[ "The issue is you are passing strings to the scatter function.\nYou can change the scatter plot line to ...\nplot.scatter(float(x), (y), marker = (3,0), color=\"Blue\")\n\nAlternatively, you can define the variable for the entries to be doubles.\nThe end of your openBlueWindow function would then look like this.\n ...
[ 1 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0074536636_matplotlib_python_tkinter.txt
Q: Applying lambda function to datetime I am using the following code to find clusters with difference <=1 in a list from itertools import groupby from operator import itemgetter data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] for k, g in groupby(enumerate(data), lambda (i, x): (i-x)): print map(itemgetter(...
Applying lambda function to datetime
I am using the following code to find clusters with difference <=1 in a list from itertools import groupby from operator import itemgetter data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] for k, g in groupby(enumerate(data), lambda (i, x): (i-x)): print map(itemgetter(1), g) If however I change the data to be...
[ "If you want to get all subsequences of items such that each item is an hour later than the previous one (not clusters of items that each are within an hour from eachother), you need to iterate over pairs (data[i-1], data[i]). Currently, you are just iterating over (i, data[i]) which raises TypeError when you try t...
[ 1, 0 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0039905432_lambda_python.txt
Q: Python-Selenium no such element: Unable to locate element I'm new to coding. I'am trying to make a twitter bot but when I find XPaths and paste it in my code it gives an error I tried to find the element with id, name, selector and paste it in my code but none of them worked from selenium import webdriver from web...
Python-Selenium no such element: Unable to locate element
I'm new to coding. I'am trying to make a twitter bot but when I find XPaths and paste it in my code it gives an error I tried to find the element with id, name, selector and paste it in my code but none of them worked from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium....
[ "You need to learn how to create correct, short and unique locators. Very long absolute XPaths and CSS Selectors are extremely breakable.\nAlso you need to use WebDriverWait expected_conditions explicit waits, not a hardcoded delays.\nThe following code works:\nfrom selenium import webdriver\nfrom selenium.webdriv...
[ 0 ]
[]
[]
[ "css_selectors", "python", "selenium", "webdriverwait", "xpath" ]
stackoverflow_0074537005_css_selectors_python_selenium_webdriverwait_xpath.txt
Q: OSError: SavedModel file does not exist I saved a model as trained_model.h5 and loaded the model in different file was easily able to run it, it was working until today, it has started showing error OSError: SavedModel file does not exist at: C:\Users\harsh\AppData\Local\Temp\tfhub_modules\602d30248ff7929470db09f7...
OSError: SavedModel file does not exist
I saved a model as trained_model.h5 and loaded the model in different file was easily able to run it, it was working until today, it has started showing error OSError: SavedModel file does not exist at: C:\Users\harsh\AppData\Local\Temp\tfhub_modules\602d30248ff7929470db09f7385fc895e9ceb4c0\{saved_model.pbtxt|saved_mod...
[ "I just deleted all the Temp files and it has started working fine again, I think it is some Windows flaw.\n", "Instead of using .h5 extension use .pd.\n" ]
[ 0, 0 ]
[]
[]
[ "deep_learning", "machine_learning", "python", "tensorflow" ]
stackoverflow_0073013513_deep_learning_machine_learning_python_tensorflow.txt
Q: How to annotate results of iteration? from __future__ import annotations from typing import TypeVar, Generic, Type T = TypeVar('T') class ListElem(Generic[T]): def __init__(self, value: T, nxt: ListElem[T] = None): self.value = value self.nxt = nxt class LinkedList(Generic[T]): def __in...
How to annotate results of iteration?
from __future__ import annotations from typing import TypeVar, Generic, Type T = TypeVar('T') class ListElem(Generic[T]): def __init__(self, value: T, nxt: ListElem[T] = None): self.value = value self.nxt = nxt class LinkedList(Generic[T]): def __init__(self, elem_factory: Type[ListElem],...
[ "I would say this is a bug in PyCharm's static type checker.\nThat elem type should be inferred as ListElem[int] and is correctly inferred as such by mypy for example.\nYour code still had a few issues. Mostly type-safety related (since you are already dealing with annotations), but a few other optimizations. One o...
[ 0 ]
[]
[]
[ "iteration", "methods", "oop", "python", "type_hinting" ]
stackoverflow_0074510046_iteration_methods_oop_python_type_hinting.txt
Q: How to download video by url using ffmpeg-python I'm trying to write script that will be downloading part of youtube video by url. I'm using ffmpeg + ffmpeg-python library. I have terminal command that I want put to python code. ffmpeg -i "url_to_download" -ss 00:00:15 -t 00:00:25 -c:v copy -c:a copy "demo.mp4" u...
How to download video by url using ffmpeg-python
I'm trying to write script that will be downloading part of youtube video by url. I'm using ffmpeg + ffmpeg-python library. I have terminal command that I want put to python code. ffmpeg -i "url_to_download" -ss 00:00:15 -t 00:00:25 -c:v copy -c:a copy "demo.mp4" url_to_download is an youtube stream url that I get lik...
[ "This answer worked for me\nffmpeg.input(url_to_download, ss=FROM, t=TO).output(\"demo.mp4\", vcodec=\"copy\", acodec=\"copy\").overwrite_output().run()\n\n" ]
[ 0 ]
[]
[]
[ "ffmpeg", "ffmpeg_python", "python" ]
stackoverflow_0074439126_ffmpeg_ffmpeg_python_python.txt
Q: 'Add' object is not callable I want to make a graphic with matplotlib and I have a problem with the class Intern Operation. This is the function: def makeGraphic(self, f, root): plt.rcParams['axes.unicode_minus'] = False fig = plt.figure(figsize=(6, 4)) # Nuevo lienzo # Use el método axis...
'Add' object is not callable
I want to make a graphic with matplotlib and I have a problem with the class Intern Operation. This is the function: def makeGraphic(self, f, root): plt.rcParams['axes.unicode_minus'] = False fig = plt.figure(figsize=(6, 4)) # Nuevo lienzo # Use el método axisartist.Subplot para crear un objet...
[ "That happens because your f is a symbolic expression, not a numerical function. So, inside your Halley.py file you would have to use sympy's lambdify to convert self.equation to a numerical function:\n# hopefully your expression has one symbol...\nf = lambdify(list(self.equation.free_symbols), self.equation)\nsupe...
[ 0 ]
[]
[]
[ "matplotlib", "numpy", "python", "sympy" ]
stackoverflow_0074537037_matplotlib_numpy_python_sympy.txt
Q: How to get names of scheduled queries in bigquery Using a python client to connect with bigquery, how can we get names of all the scheduled queries present in that project? I tried following up with this link - https://cloud.google.com/bigquery/docs/reference/datatransfer/libraries But got no information on the na...
How to get names of scheduled queries in bigquery
Using a python client to connect with bigquery, how can we get names of all the scheduled queries present in that project? I tried following up with this link - https://cloud.google.com/bigquery/docs/reference/datatransfer/libraries But got no information on the names of the scheduled queries.
[ "To list all the scheduled queries for a project with Python BigQuery Client :\ndef get_scheduled_queries_configs():\n from google.cloud import bigquery_datatransfer\n\n transfer_client = bigquery_datatransfer.DataTransferServiceClient()\n\n project_id = \"{project_id}\"\n parent = transfer_client.commo...
[ 1 ]
[]
[]
[ "api", "bigdata", "google_bigquery", "google_cloud_functions", "python" ]
stackoverflow_0074536688_api_bigdata_google_bigquery_google_cloud_functions_python.txt
Q: Mean value in Pandas higher is higher than it should be I'm trying to compare some NFL concussion stats with some individual player stats from the combine. dfcomb.to_excel(r'C:\Users\Documents\GWG\NFL Concussion\NFL_concussion\comb.xlsx', index=False) # Create a merged df with players that are concussed on...
Mean value in Pandas higher is higher than it should be
I'm trying to compare some NFL concussion stats with some individual player stats from the combine. dfcomb.to_excel(r'C:\Users\Documents\GWG\NFL Concussion\NFL_concussion\comb.xlsx', index=False) # Create a merged df with players that are concussed on dfconc and players that are on dfcomb dfcommon = dfcomb....
[ "The groupby method does not return sorted data, so your NFL and df data has different order when you add them to the plots. Try this:\nheightavgNFL = pd.DataFrame(dfcomb.groupby('position')['heightInches'].mean()).sort_values(by=['position'])\nheightavgdf = pd.DataFrame(dfcommon.groupby('position')['heightInches']...
[ 0 ]
[]
[]
[ "csv", "data_analysis", "mean", "pandas", "python" ]
stackoverflow_0074536482_csv_data_analysis_mean_pandas_python.txt
Q: Replacing one data frame value from another based on timestamp Criterion I am new to Python and may be it's a very basic question for many here so apologies in advance and please bear with me. I have a timeseries of water level records where the timestamps are not continuous. I want to create a new timeseries whic...
Replacing one data frame value from another based on timestamp Criterion
I am new to Python and may be it's a very basic question for many here so apologies in advance and please bear with me. I have a timeseries of water level records where the timestamps are not continuous. I want to create a new timeseries which is continuous and for the intervals where there is no data I want to assign ...
[ "This answer assumes that your input df, df3, has had the column renamed to Timestamp and the dtype converted to datetime. In this case, you can just use merge to make your life much easier\ndti = pd.date_range(\"2020-05-01\", periods=1224, freq=\"3H\")\ndti_df = pd.DataFrame(dti, columns=['Timestamp'])\nnew_df=pd....
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074525405_dataframe_pandas_python.txt
Q: Anotate return type with psycopg2 type stub I have a function which returns a psycopg2 connection, if a connection can be established. So the return type should be Optional[psycopg2.connection], or psycopg2.connection | None. However I am unable to import psycopg2.connection at runtime. I've tried the workaround m...
Anotate return type with psycopg2 type stub
I have a function which returns a psycopg2 connection, if a connection can be established. So the return type should be Optional[psycopg2.connection], or psycopg2.connection | None. However I am unable to import psycopg2.connection at runtime. I've tried the workaround mentioned in How can I import type-definitions fro...
[ "The question you linked proposes some extremely dirty hack which doesn't seem to work any more. There is absolutely no need for it under such simple circumstances. Moreover, to be honest, I cannot reproduce that solution on any mypy version starting from 0.800 (old enough, given that the linked answer is recent), ...
[ 1 ]
[]
[]
[ "mypy", "psycopg2", "python" ]
stackoverflow_0074534284_mypy_psycopg2_python.txt
Q: Extracting features from a pretrained model using hook function I want to extract features from some of the layers from a pretrained model. For this aim, I am using thi pretrained model from here. I removed some of the final layers and for loading the pretrained weights, I use strict=False. The architecture of the...
Extracting features from a pretrained model using hook function
I want to extract features from some of the layers from a pretrained model. For this aim, I am using thi pretrained model from here. I removed some of the final layers and for loading the pretrained weights, I use strict=False. The architecture of the model is as follows: Net( (blocks): ModuleList( (0): ResNetBas...
[ "Looking at the link you provided, the function create_r2plus1d() returns the following\n return Net(blocks=nn.ModuleList(blocks))\n\nYour object self.r2plus1d is already a Net instance, so your line\nself.r2plus1d.Net.blocks[1].register_forward_hook(get_activation('ResBlock1'))\n\nis basically like calling Net twi...
[ 3 ]
[]
[]
[ "deep_learning", "image_processing", "python", "pytorch" ]
stackoverflow_0074535731_deep_learning_image_processing_python_pytorch.txt
Q: Iterate multiple JSON Objects in POST request via Python #! /usr/bin/env python3 from contextlib import redirect_stdout import io from lib2to3.pgen2.token import LESS from locale import format_string from turtle import back import requests import json import sys from requests.structures import CaseInsensitiveDict...
Iterate multiple JSON Objects in POST request via Python
#! /usr/bin/env python3 from contextlib import redirect_stdout import io from lib2to3.pgen2.token import LESS from locale import format_string from turtle import back import requests import json import sys from requests.structures import CaseInsensitiveDict ### ONLY PROVEN FOR ONE OBJECT AT A TIME #data = open('com...
[ "So you're dealing with an NDJSON (Newline Delimited JSON) instead of a JSON.\nhttp://ndjson.org/\nOf course python has a library for it → https://pypi.org/project/ndjson/\nBelow is a simple load/loop to show how to deal with it.\nmain.py\nimport ndjson\nfrom pprint import pprint\n\n\nwith open('commandoutputid.ndj...
[ 0 ]
[]
[]
[ "for_loop", "json", "post", "python" ]
stackoverflow_0074535924_for_loop_json_post_python.txt
Q: Saving result from for loop to different columns I am trying to run a nested loop in which I want the output to be saved in four different columns. Let C1R1 be the value I want in the first column first row, C2R2 the one I want in the second column second row, etc. What I have come up with this far gives me a list...
Saving result from for loop to different columns
I am trying to run a nested loop in which I want the output to be saved in four different columns. Let C1R1 be the value I want in the first column first row, C2R2 the one I want in the second column second row, etc. What I have come up with this far gives me a list where the output is saved like this: ['C1R1', 'C2R1',...
[ "Try:\nimport pandas as pd\n\n\ndef get_dataframe(num_cols=4, num_values=24):\n return pd.DataFrame(\n ([v * 24 + c for v in range(num_cols)] for c in range(num_values)),\n columns=[f\"Column {c}\" for c in range(1, num_cols + 1)],\n )\n\n\ndf = get_dataframe()\nprint(df)\n\nPrints:\n Column ...
[ 0 ]
[]
[]
[ "for_loop", "nested_loops", "python" ]
stackoverflow_0074534987_for_loop_nested_loops_python.txt
Q: Python typing annotation for an object built with a class method Here's a code snippet. from typing import Generic, TypeVar, Union T = TypeVar('T') class Bar(object): def __init__(self, blah: Union[int, str]) -> None: self.blah = blah class Foo(Generic[T]): def __init__(self, bar: T) -> None: ...
Python typing annotation for an object built with a class method
Here's a code snippet. from typing import Generic, TypeVar, Union T = TypeVar('T') class Bar(object): def __init__(self, blah: Union[int, str]) -> None: self.blah = blah class Foo(Generic[T]): def __init__(self, bar: T) -> None: self.bar = bar @classmethod def extract(cls, klass: T)...
[ "So, you are specifying:\n@classmethod\ndef extract(cls, klass: T) -> 'Foo':\n\nbut Foo is implicitly Foo[Any], if you don't provide a type parameter. You want:\n@classmethod\ndef extract(cls, klass: T) -> 'Foo[T]':\n\n" ]
[ 3 ]
[]
[]
[ "pylance", "python", "python_typing", "visual_studio_code" ]
stackoverflow_0074537134_pylance_python_python_typing_visual_studio_code.txt
Q: Database in python - index issue for page in range(1, pages + 1): def append_organizator(organizator, organizatorzy=[]): organizatorzy.append(organizator) for i in organizatorzy: try: query = "INSERT INTO stypendia (organizator) values(%s)" values = [] values.ap...
Database in python - index issue
for page in range(1, pages + 1): def append_organizator(organizator, organizatorzy=[]): organizatorzy.append(organizator) for i in organizatorzy: try: query = "INSERT INTO stypendia (organizator) values(%s)" values = [] values.append(organizatorzy.pop()) ...
[ "You need to combine the insert operations - each insert will create a new row. You should also just use the parameters without the array, they really aren't needed.\nThis example only handles two parameters (same as your code above). Add additional parameters as needed and adjust the insert statement\n # The or...
[ 0 ]
[]
[]
[ "beautifulsoup", "database", "mysql", "python" ]
stackoverflow_0074537169_beautifulsoup_database_mysql_python.txt
Q: How to render math symbols as text in SVG/EPS/PDF images? When creating graphs using, for instance, Python. It is possible to save these figures as vector graphics (SVG, EPS, PDF) and the text is rendered separately. This makes it possible to select or search the text when shown in a pdf file. However, I've tried ...
How to render math symbols as text in SVG/EPS/PDF images?
When creating graphs using, for instance, Python. It is possible to save these figures as vector graphics (SVG, EPS, PDF) and the text is rendered separately. This makes it possible to select or search the text when shown in a pdf file. However, I've tried to render a simple graph using math symbols in addition to text...
[ "I have been able to get it to work in the way I think you want by first installing a LaTeX distribution (I used MikTex, from here) and then setting the matpotlib option to use LaTeX to render your symbols and text.\nNote that after installing MikTex, I had to open a new instance of my command prompt or code editor...
[ 2, 2 ]
[]
[]
[ "latex", "python", "symbols", "unicode", "vector_graphics" ]
stackoverflow_0074477713_latex_python_symbols_unicode_vector_graphics.txt
Q: PyTorch RuntimeError: "nll_loss_forward_reduce_cuda_kernel_2d_index" not implemented for 'Int' Trying to implement a TGCN model on my local machine (entire code link) and I get this above Runtime error related to PyTorch. This issue doesn't happen when I implement the same code on Google Colab. What's the issue he...
PyTorch RuntimeError: "nll_loss_forward_reduce_cuda_kernel_2d_index" not implemented for 'Int'
Trying to implement a TGCN model on my local machine (entire code link) and I get this above Runtime error related to PyTorch. This issue doesn't happen when I implement the same code on Google Colab. What's the issue here and how do I fix it? Thanks Here's the traceback error: Traceback (most recent call last): File...
[ "You have to make sure that both your objects have the same type when you call F.cross_entropy(). You probably have two different type on this line loss = compute_loss(out, y), where y is either float or long type tensor and out is int.\nYou have to cast your out to the same type as y with something like this\nout....
[ 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074534315_python_pytorch.txt
Q: Copy a specific cell for a column I'm working with a dataframe that has duplicate value, and I want to copy a cell and put in correct column. I'm beginner with python(and new in programming) and I don't know how to solve this. Example Process type value PVR Hono Civel 123456 PVR $5 $0 $0 $0 123456 Civel $17 $0 ...
Copy a specific cell for a column
I'm working with a dataframe that has duplicate value, and I want to copy a cell and put in correct column. I'm beginner with python(and new in programming) and I don't know how to solve this. Example Process type value PVR Hono Civel 123456 PVR $5 $0 $0 $0 123456 Civel $17 $0 $0 $0 123456 Hono $2 $0 $0 $0 ...
[ "I can't use pivot now because column \"Process\" has duplicate values. -- I think you misunderstand the pivot process, because this is exactly what a pivot is set up to handle. This seems to do what you want in one line:\nimport pandas as pd\n\ndata = [\n [123456,\"PVR\",\"$5\"],\n [123456,\"Civel\",\"$17\"...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074523581_python.txt
Q: Does imaplib works to download a pdf inside a mail from AppleMail? I am trying to download the pdf from a mail received on an Apple account xy@me.com. I have already managed to do it from a gmail account with no trouble but the result from imaplib.fetch seems to be empty using RFC822 when I apply it to a "@me.com"...
Does imaplib works to download a pdf inside a mail from AppleMail?
I am trying to download the pdf from a mail received on an Apple account xy@me.com. I have already managed to do it from a gmail account with no trouble but the result from imaplib.fetch seems to be empty using RFC822 when I apply it to a "@me.com" account, I get: b'34878 ()' When I use BODY instead, I get infos about...
[ "As I didn't get any answer to my question, I have been searching for a solution for the past few days.\nI managed to do it by using MailBox instead of imaplib.\n" ]
[ 1 ]
[]
[]
[ "apple_mail", "fetch", "imaplib", "python" ]
stackoverflow_0074421762_apple_mail_fetch_imaplib_python.txt
Q: How to put the input() in the middle of the sentence (python)? I would like to get the input() in the middle of the sentence. I have tried: print('I have ${} dollars'.format(float(input()))) and get this: 45 #asked before showing the print I have $45 dollars instead of this: I have $| dollars #(The "|" means the ...
How to put the input() in the middle of the sentence (python)?
I would like to get the input() in the middle of the sentence. I have tried: print('I have ${} dollars'.format(float(input()))) and get this: 45 #asked before showing the print I have $45 dollars instead of this: I have $| dollars #(The "|" means the place where the input() is requested) Is that possible?
[ "This is as close as you're going to get to what you want:\nprefix = \"I have $\"\ndollars = input(prefix)\nncols = len(dollars) + len(prefix) + 1\nprint(f\"\\033[F\\033[{ncols}G dollars\")\n\n\n\\033[F go to the (start of the) previous line\n\\03[{ncols}G move along ncols:\n\n" ]
[ 1 ]
[]
[]
[ "input", "python" ]
stackoverflow_0074536699_input_python.txt
Q: Which special methods bypasses __getattribute__ in Python? In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the __getattribute__() method even of the object’s metaclass. The docs mention special methods such as __hash__, __repr...
Which special methods bypasses __getattribute__ in Python?
In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the __getattribute__() method even of the object’s metaclass. The docs mention special methods such as __hash__, __repr__ and __len__, and I know from experience it also includes __i...
[ "You can find an answer in the python3 documentation for object.__getattribute__, which states:\n\nCalled unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(), the\n latter will not be called unless __getattribute__() either calls it\n explicitly or r...
[ 4, 2, 0 ]
[]
[]
[ "magic_methods", "python" ]
stackoverflow_0012872695_magic_methods_python.txt
Q: Insert or update if primary key exists into postgreSQL table with .to_sql() I have a pandas DataFrame that consists of multiple columns that I want to store into the postgreSQL database, using .to_sql(): my_table.to_sql('table', con=engine, schema='wrhouse', if_exists='append', index=False) I have set a primary k...
Insert or update if primary key exists into postgreSQL table with .to_sql()
I have a pandas DataFrame that consists of multiple columns that I want to store into the postgreSQL database, using .to_sql(): my_table.to_sql('table', con=engine, schema='wrhouse', if_exists='append', index=False) I have set a primary key (date), in order to avoid duplicate entries. So above-mentioned command works ...
[ "you could convert the my_table dataframe (which holds new values you'd like to send to the table in the database) to a numpy record array and add it to the query used in the execute function in your comment ^:\nvalues = str(list(my_table.to_records(index=False)))[1:-1]\nconn.execute(f\"INSERT INTO wrschema.table (...
[ 0 ]
[]
[]
[ "pandas", "pandas_to_sql", "postgresql", "python", "upsert" ]
stackoverflow_0074432724_pandas_pandas_to_sql_postgresql_python_upsert.txt
Q: Python 3.10.6 - Find the element-wise maxima of overlaid xarray datasets I'm working with gridded data, specifically netcdf data, trying to find the maximum grid point value for overlaying pixels of each netcdf file in a directory, ignoring null values. If you're familiar with ArcGIS, this is the same as running t...
Python 3.10.6 - Find the element-wise maxima of overlaid xarray datasets
I'm working with gridded data, specifically netcdf data, trying to find the maximum grid point value for overlaying pixels of each netcdf file in a directory, ignoring null values. If you're familiar with ArcGIS, this is the same as running the maximum function through Cell Statistics. However, when doing this through ...
[ "Here is the safe way to handle this data:\nimport numpy as np\nimport os\n\n\n# Directory that stores all the netcdf files\nfilepath = 'weekBatch/'\n\n\n# Putting each file into its own xarray dataset\nds_ge_0 = []\nds_ge_15 = []\nfor filename in os.listdir(filepath):\n ds = xr.open_dataset(filepath + filename)...
[ 1 ]
[]
[]
[ "netcdf", "python", "python_xarray" ]
stackoverflow_0074537405_netcdf_python_python_xarray.txt
Q: Conway's Game of Life Gliders break after a few generations So I tried creating Conway's game of life in python with pygame. I made this without watching any tutorials, which is probably why it is so broken. It seems to be working fine, but when I creates a glider it seems to just break after a few generations. I ...
Conway's Game of Life Gliders break after a few generations
So I tried creating Conway's game of life in python with pygame. I made this without watching any tutorials, which is probably why it is so broken. It seems to be working fine, but when I creates a glider it seems to just break after a few generations. I looked at some other posts about my problem and added their solut...
[ "Your function UpdateState both counts a cell's neighbors and updates the cell's state. Since you call that function in a loop, both are done together, which does not work, as explained here. You must split the \"count\" phase from the \"update state\" phase.\n" ]
[ 2 ]
[]
[]
[ "conways_game_of_life", "pygame", "python" ]
stackoverflow_0074536773_conways_game_of_life_pygame_python.txt
Q: Iterate millions of rows in pandas optimally What I am looking for is to put for each ID the most current description (as long as it is not an empty cell, and if it’s is empty, it should be the first non-empty description). I have sorted the DF by ID and by Date, so for each ID "group", the first description is th...
Iterate millions of rows in pandas optimally
What I am looking for is to put for each ID the most current description (as long as it is not an empty cell, and if it’s is empty, it should be the first non-empty description). I have sorted the DF by ID and by Date, so for each ID "group", the first description is the most current. The problem comes when I have to t...
[ "Sure thing – use groupby:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"columnaid\": [\"2321fdsf\", \"2321fdsf\", \"3gsdfer3\", \"4gdsfg44\", \"4gdsfg44\", \"4gdsfg44\", \"7fg45d\"],\n \"date\": [\"2022-11-16\", \"2022-10-07\", \"2022-09-02\", \"2021-12-04\", \"2021-09-23\", \"2021-03-06\", \...
[ 1, 1, 0 ]
[]
[]
[ "dataframe", "for_loop", "loops", "pandas", "python" ]
stackoverflow_0074529223_dataframe_for_loop_loops_pandas_python.txt
Q: Python NameError: name is not defined I have a python script and I am receiving the following error: Traceback (most recent call last): File "C:\Users\Tim\Desktop\pop-erp\test.py", line 1, in <module> s = Something() NameError: name 'Something' is not defined Here is the code that causes the problem: s = ...
Python NameError: name is not defined
I have a python script and I am receiving the following error: Traceback (most recent call last): File "C:\Users\Tim\Desktop\pop-erp\test.py", line 1, in <module> s = Something() NameError: name 'Something' is not defined Here is the code that causes the problem: s = Something() s.out() class Something: d...
[ "Define the class before you use it:\nclass Something:\n def out(self):\n print(\"it works\")\n\ns = Something()\ns.out()\n\nYou need to pass self as the first argument to all instance methods.\n", "Note that sometimes you will want to use the class type name inside its own definition, for example when ...
[ 106, 21, 5, 0 ]
[]
[]
[ "nameerror", "python", "python_3.x" ]
stackoverflow_0014804084_nameerror_python_python_3.x.txt
Q: How to Import files from another folder in python? How to import files from another folder, try so many things, but my attempt is not fruitful. How to resolve it? -> d: -> project Main -> First Folder -> my_main_file.py -> class (My_Main_Class) -> module1 ...
How to Import files from another folder in python?
How to import files from another folder, try so many things, but my attempt is not fruitful. How to resolve it? -> d: -> project Main -> First Folder -> my_main_file.py -> class (My_Main_Class) -> module1 -> module2 -> module3 -> Second Fo...
[ "in my_second_file.py\nfrom First_Folder.my_main_file import My_Main_Class\n\nAfter Your comment:\nfrom First_Folder.my_main_file import ex(your class object)\n\nIn your second file\nex.module1()\nex.module3()\n\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074537439_python_python_3.x.txt
Q: Reverse for 'admin_update' with arguments '('',)' not found. 1 pattern(s) tried: ['admin_update/(?P[^/]+)$'] I'm trying to pass arguments to edit table values. Would be grateful if anyone could breakdown the solution. views.py ` #@login_required(login_url='/admin_login/') def AdminManageRequests(request): less...
Reverse for 'admin_update' with arguments '('',)' not found. 1 pattern(s) tried: ['admin_update/(?P[^/]+)$']
I'm trying to pass arguments to edit table values. Would be grateful if anyone could breakdown the solution. views.py ` #@login_required(login_url='/admin_login/') def AdminManageRequests(request): lessons = Lesson.objects.all() return render(request,'admin/manage_requests.html',{'lessons':lessons}) def Admin...
[ "It should be <int:lesson_id> not only <lesson_id> as by default (when nothing is given) it is considered as string type so:\npath('admin_update/<int:lesson_id>/', views.AdminUpdateRequests, name='admin_update'),\n\nI'd also recommend you to use get_object_or_404() so:\nlesson = get_object_or_404(Lesson,pk=lesson_i...
[ 2 ]
[]
[]
[ "django", "django_forms", "django_templates", "django_urls", "python" ]
stackoverflow_0074537426_django_django_forms_django_templates_django_urls_python.txt
Q: discord has no attribute Intents once compiled So I'm making a GUI using Tkinter that one of the features is it launches a discord bot. Now when I run the code within VS Code it all works fine. However when I compile it using pyinstaller I get an error saying "Module discord has no attribute Intents". If I put the...
discord has no attribute Intents once compiled
So I'm making a GUI using Tkinter that one of the features is it launches a discord bot. Now when I run the code within VS Code it all works fine. However when I compile it using pyinstaller I get an error saying "Module discord has no attribute Intents". If I put the code for the bot in a separate python file and get ...
[ "Well the problem you are facing may be due to your bot structure\nSo first go to https://discord.com/developers/applications\nSelect your bot\nClick the options button\n\nthen go to bot scroll down and enable all intents\n\n", "It should be\nreturn discord.Intents.all()\n\nand not\nreturn discord.Intents().all()...
[ 1, 0 ]
[]
[]
[ "discord", "discord.py", "python", "tkinter" ]
stackoverflow_0072496293_discord_discord.py_python_tkinter.txt
Q: Annotate Min/Max/Median in Matplotlib Violin Plot Given this example code: import pandas as pd import matplotlib.pyplot as plt data = 'https://raw.githubusercontent.com/marsja/jupyter/master/flanks.csv' df = pd.read_csv(data, index_col=0) # Subsetting using Pandas query(): congruent = df.query('TrialType == "co...
Annotate Min/Max/Median in Matplotlib Violin Plot
Given this example code: import pandas as pd import matplotlib.pyplot as plt data = 'https://raw.githubusercontent.com/marsja/jupyter/master/flanks.csv' df = pd.read_csv(data, index_col=0) # Subsetting using Pandas query(): congruent = df.query('TrialType == "congruent"')['RT'] incongruent = df.query('TrialType == ...
[ "So this was as easy as getting the medians/mins/maxes and then enumerating, adding the annotation with plt.text, and adding some small values for positioning:\nmedians = results_df.groupby(['model_cat'])['test_f1'].median()\n\nfor i, v in enumerate(medians):\n plt.text((i+.85), (v+.001), str(round(v, 3)), fonts...
[ 0 ]
[]
[]
[ "data_science", "matplotlib", "python", "violin_plot", "visualization" ]
stackoverflow_0074329144_data_science_matplotlib_python_violin_plot_visualization.txt
Q: matplotlib, how to ignore key repeats I am trying to active a mode when a key is pressed and turn it off when the key is released. So, while holding a key, be in this mode. The problem is, matplotlib is interpreting a held key as many key presses and releases in rapid succession. Anyone know how to stop this? here...
matplotlib, how to ignore key repeats
I am trying to active a mode when a key is pressed and turn it off when the key is released. So, while holding a key, be in this mode. The problem is, matplotlib is interpreting a held key as many key presses and releases in rapid succession. Anyone know how to stop this? here is some sample code: import matplotlib.pyp...
[ "I was/am experiencing the same problem. I believe Matplotlib is working correctly (at least for me on Pop OS/Linux); there is an accessibility setting called repeat keys or auto repeat keys. When enabled, this setting will release your key if you press on it for X amount of time and repress it again and then the p...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0062271731_matplotlib_python.txt
Q: Trying to group by using multiple columns Using Pandas I am trying to do group by for multiple columns and then fill the pandas dataframe where a person name is not present For Example this is my Dataframe enter image description here V1 V2 V3 PN 1 10 20 A 2 10 21 A 3 10 20 C I have a unique pe...
Trying to group by using multiple columns
Using Pandas I am trying to do group by for multiple columns and then fill the pandas dataframe where a person name is not present For Example this is my Dataframe enter image description here V1 V2 V3 PN 1 10 20 A 2 10 21 A 3 10 20 C I have a unique person name list = ['A','B','C','D','E'] Expected...
[ "Try this, using pd.MultiIndex with reindex to create additional rows:\nimport pandas as pd\ndf = pd.DataFrame({'Version 1':[1,2,3],\n 'Version 2':[10,10,10],\n 'Version 3':[20,21,20],\n 'Person Name':'A A C'.split(' ')})\n\np_list = [*'ABCDE']\n\ndf.set_index([...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074536632_dataframe_pandas_python.txt
Q: Plotting sine wave with delayed starting time I want to plot a sine wave with a delayed starting time. For example, Sine wave frequency: 1Hz Total time: 2s 2 periods I want the sine wave to start at t=1s so there is only one period in my plot. My code so far is a = 1 d = 5 phi = 0 f = 1 # freque...
Plotting sine wave with delayed starting time
I want to plot a sine wave with a delayed starting time. For example, Sine wave frequency: 1Hz Total time: 2s 2 periods I want the sine wave to start at t=1s so there is only one period in my plot. My code so far is a = 1 d = 5 phi = 0 f = 1 # frequency dt = 0.01 # timestep fs = 1/dt ...
[ "First of all, for the delay of your sine, you have to modify this line\nt = np.linspace(0, Ttot, N)\n\nfor this\nt = np.linspace(1, Ttot, N)\n\nThis will provide your samples for the calculation of your signal, between the value of 1 and Ttot (which is 2 here).\nThen you can add a horizontal line of value d betwee...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074536008_matplotlib_python.txt
Q: Separating development and production parts of django project I'm building a site that relies on the output of a machine learning algorithm. All that is needed for the user-facing part of the site is the output of the algorithm (class labels for a set of items), which can be easily stored and retrieved from the dj...
Separating development and production parts of django project
I'm building a site that relies on the output of a machine learning algorithm. All that is needed for the user-facing part of the site is the output of the algorithm (class labels for a set of items), which can be easily stored and retrieved from the django models. The algorithm could be run once a day, and does not re...
[ "Just move what we discussed to the answer in case people have the same question, my suggestion is:\n\nSpend some time define what are the dependencies for your site and for the algorithm code.\nDump the dependency list into requirements.txt for each project.\nDeploy them on different environments so the conflicts ...
[ 4, 1, 0 ]
[]
[]
[ "django", "heroku", "python" ]
stackoverflow_0031753685_django_heroku_python.txt
Q: Feature scaling for polynomial regression Do we have to scale the polynomial features when creating a polynomial regression? This question is already answered here and the answer is no. But when creating a model with scikit learn, I do observe a huge difference. And I also found this article about the Importance o...
Feature scaling for polynomial regression
Do we have to scale the polynomial features when creating a polynomial regression? This question is already answered here and the answer is no. But when creating a model with scikit learn, I do observe a huge difference. And I also found this article about the Importance of Feature Scaling in Data Modeling. And the exa...
[ "Maybe because of numerical issues; polynomials are prone to ill-conditioning: I have experienced (outside of machine learning) such problems with not-so-complex polynomial models, and the first solution was scaling the values of the features.\nSymbolically the result is the same, but numerically can be much differ...
[ 0 ]
[]
[]
[ "linear_regression", "python", "regression", "scikit_learn" ]
stackoverflow_0062492473_linear_regression_python_regression_scikit_learn.txt
Q: Why can't I import my domain models into my flask app? I've been working through the Architecture Patterns with Python book and am reworking my app to follow a folder structure like the one on the authors git repo for chapter 4: https://github.com/cosmicpython/code/tree/master/src/allocation My problem is that I c...
Why can't I import my domain models into my flask app?
I've been working through the Architecture Patterns with Python book and am reworking my app to follow a folder structure like the one on the authors git repo for chapter 4: https://github.com/cosmicpython/code/tree/master/src/allocation My problem is that I cannot get the flask_app.py to import any of the domain modul...
[ "That's an awesome book, I hope you enjoy reading it as much as I did.\nIf I recall correctly, the package is installed before being used (check the docker files) and therefore are available globally. You could simulate this behavior adding your src/peaked folder to the PYTHONPATH environment variable (something li...
[ 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074536122_flask_python.txt
Q: open pdf link with python selenium os.environ['PATH'] += r"C:\Users\dew23\OneDrive\Computer Science" driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get("https://official.nba.com/nba-injury- report-2022-23-season/") WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPAT...
open pdf link with python selenium
os.environ['PATH'] += r"C:\Users\dew23\OneDrive\Computer Science" driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get("https://official.nba.com/nba-injury- report-2022-23-season/") WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="main"]/div/section[1]/d...
[ "There are several issues here:\n\nThe main issue causing your code to click the element but not to open the file is because you need to wait for element clickability. Element presence is a very first state when element is already presented but still not fully rendered. So, clicking a web element on that stage will...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "webdriverwait", "xpath" ]
stackoverflow_0074536352_python_selenium_selenium_webdriver_webdriverwait_xpath.txt
Q: Pandas Merge Many Rows of One Dataframe into Fewer Rows of Second Dataframe Is there an easy way to merge two dataframes such that df2 adds all its rows with matching 'on' values as new columns in df1? Open to other methods of joining the data as well. e.g. Matching on Course Offering Code and User Id df1: Course...
Pandas Merge Many Rows of One Dataframe into Fewer Rows of Second Dataframe
Is there an easy way to merge two dataframes such that df2 adds all its rows with matching 'on' values as new columns in df1? Open to other methods of joining the data as well. e.g. Matching on Course Offering Code and User Id df1: Course Offering Code User Id 001 1 001 2 df2: Course Offering Code U...
[ "You can do this one with pandas.DataFrame.pivot :\ndef flatten_cols(df):\n df.columns = ['_'.join(map(str, x)) for x in df.columns]\n df = df[sorted(df.columns, key=lambda x: int(x.split(\"_\")[-1]))]\n return df\n\nout = (\n df1\n .merge(df2, on=[\"Course Offering Code\", \"User Id\"], ho...
[ 0 ]
[]
[]
[ "merge", "pandas", "python" ]
stackoverflow_0074537102_merge_pandas_python.txt
Q: sklearn.cross_validate returns one unfitted estimator I used sklearn.model_selection.cross_validate for cross-validation of an sklearn.pipeline.Pipeline, which works great. Now I am interested in the coefficients of a feature selection step in the pipeline. The selector used is SelectFromModel(LinearSVC(penalty="l...
sklearn.cross_validate returns one unfitted estimator
I used sklearn.model_selection.cross_validate for cross-validation of an sklearn.pipeline.Pipeline, which works great. Now I am interested in the coefficients of a feature selection step in the pipeline. The selector used is SelectFromModel(LinearSVC(penalty="l1", dual=False)). By setting return_estimator=True the cros...
[ "After finalizing this question, and just before submitting it, I realized I should access the member estimator_ and not estimator.\nI hope this helps someone one day.\n" ]
[ 0 ]
[]
[]
[ "cross_validation", "python", "scikit_learn" ]
stackoverflow_0074537722_cross_validation_python_scikit_learn.txt
Q: Averaging five rows above the value in the target column The challenge that I have, and don't know how to approach is to have averaged five, ten, or whatever amount of rows above the target value plus the target row. Dataset target | A | B | ---------------------- nan | 6 | 4 | nan | 2 | 7 | ...
Averaging five rows above the value in the target column
The challenge that I have, and don't know how to approach is to have averaged five, ten, or whatever amount of rows above the target value plus the target row. Dataset target | A | B | ---------------------- nan | 6 | 4 | nan | 2 | 7 | nan | 4 | 9 | nan | 7 | 3 | nan | 3 | 7 | ...
[ "Try this, [::-1] reversing element to order the dataframe bottom to top, so we can group the values \"above\" valid targets:\ndf.groupby(df['target'].notna()[::-1].cumsum()[::-1]).apply(lambda x: x.tail(6).mean())\n\nOutput:\n target A B\ntarget \n1 51.0 3...
[ 1 ]
[]
[]
[ "data_preprocessing", "feature_engineering", "pandas", "python" ]
stackoverflow_0074537593_data_preprocessing_feature_engineering_pandas_python.txt
Q: Safen User Input Part I - htmlspecialchars You are a(n) novice/average/experienced/professional/world-famous Web Developer (choose one) who owns a(n) simple/clean/slick/beautiful/complicated/professional/business website (choose one or more) which contains form fields so visitors can send emails or leave a comment...
Safen User Input Part I - htmlspecialchars
You are a(n) novice/average/experienced/professional/world-famous Web Developer (choose one) who owns a(n) simple/clean/slick/beautiful/complicated/professional/business website (choose one or more) which contains form fields so visitors can send emails or leave a comment on your website with ease. However, with ease c...
[ "Here is the Solution:\ndef html_special_chars(data): \n symbols = {'<': '&lt;', '>': '&gt;', '\"': '&quot;', '&': '&amp;'}\n return \"\".join(symbols.get(x, x) for x in data)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0072893031_python.txt
Q: I get an error with TikTokAPI when i use api.getUserByName("swisscom") What is a problem? I use PyCharm on Ubuntu 22.04. from TikTokAPI import TikTokAPI api = TikTokAPI() user_obj = api.getUserByName("tomschoenwolf") When i start it i get error: Traceback (most recent call last): File "/home/user/PycharmProject...
I get an error with TikTokAPI when i use api.getUserByName("swisscom")
What is a problem? I use PyCharm on Ubuntu 22.04. from TikTokAPI import TikTokAPI api = TikTokAPI() user_obj = api.getUserByName("tomschoenwolf") When i start it i get error: Traceback (most recent call last): File "/home/user/PycharmProjects/video_download/with_api.py", line 3, in <module> user_obj = api.getUse...
[ "Are you sure you've installed the TikTokAPI package?\nLooks like it can be installed with pip: https://pypi.org/project/TikTokApi/\nTo verify installation type pip show TikTokApi in the terminal.\n" ]
[ 0 ]
[]
[]
[ "pycharm", "python", "python_3.x", "tiktok_api", "ubuntu_22.04" ]
stackoverflow_0074537576_pycharm_python_python_3.x_tiktok_api_ubuntu_22.04.txt
Q: How do I tell pylint about a descriptor providing access to iterables, subscriptables? I have a decorator that I can use to mark a read-only class property: class class_ro_property(property): def __init__(self, getter:Callable): self._getter = getter def __get__(self, _, cls): return self....
How do I tell pylint about a descriptor providing access to iterables, subscriptables?
I have a decorator that I can use to mark a read-only class property: class class_ro_property(property): def __init__(self, getter:Callable): self._getter = getter def __get__(self, _, cls): return self._getter(cls) class MyClass: @class_ro_property def my_property(cls): return...
[ "The straight answer is: that is a short-comming of the linter. A feature request should be open against \"pylint\" pointing to the fact it does not recognize descriptors.\nThat said, just strap a comment to skip linting where you are getting this problem as a workaround. Adding a comment like # pylint: disable=E11...
[ 0 ]
[ "My suggestion would be to write a metaclass that defines the property:\nclass MyMetaClass(type):\n @property\n def my_property(cls):\n return [1, 2, 3]\n\nclass MyClass(metaclass=MyMetaClass):\n my_property = MyClassMeta.my_property\n\nfor num in MyClass.my_property:\n print(num)\n\nPylint is fi...
[ -1 ]
[ "pylint", "python", "python_decorators", "python_descriptors" ]
stackoverflow_0074523859_pylint_python_python_decorators_python_descriptors.txt
Q: Extraction of versions in paths pandas column I have a dataframe column that looks like this: paths 0 ['/api/v2/clouds', '/api/v2/clouds/{cloud}'] 1 ['/v0.1/book-lists/{type}/{date}', '/v0.1/book-lists] ...
Extraction of versions in paths pandas column
I have a dataframe column that looks like this: paths 0 ['/api/v2/clouds', '/api/v2/clouds/{cloud}'] 1 ['/v0.1/book-lists/{type}/{date}', '/v0.1/book-lists] 2 ['/v1/Video/Rooms', '/v1/Video/Rooms/{RoomS...
[ "No need for keywords, just use pandas.Series.str.findall as you started to do:\ndf[\"Path_Version\"]= (\n df[\"paths\"].str.findall(r\"(v\\d\\.?\\d?)\")\n .apply(lambda x: \"/\".join(set(x)))\n )\n\n# Output :\nprint(df.to_string())\n ...
[ 5, 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074537690_pandas_python.txt
Q: Handling data trees in python with changing node attributes I have a tree where I want to dynamically add or remove nodes. For now I just want to focus on adding nodes. I want to create python class in such a way that adding one node will recalculate attributes (x and y axis coordinates) of affected nodes. I have ...
Handling data trees in python with changing node attributes
I have a tree where I want to dynamically add or remove nodes. For now I just want to focus on adding nodes. I want to create python class in such a way that adding one node will recalculate attributes (x and y axis coordinates) of affected nodes. I have attached below diagrams to better explain the behaviour that I wa...
[ "Probably there are libraries doing this. If you want to implement it yourself, following approach may help:\n\nFind the height of the tree. Use it to find the bottom line's y value.\nEvenly distribute all leaf nodes at y. Group them by their parents. If needed, put some more gap between nodes with different parent...
[ 0 ]
[]
[]
[ "nodes", "python", "tree" ]
stackoverflow_0074537776_nodes_python_tree.txt
Q: python multiprocessing spawn method's conflict when _fixup_main_from_path() is called experts, I am using python's multiprocessing's spawn method to spawn child processes. The child process is a function call. One issue that recently get notified is when child process is created, it will try to import all the impo...
python multiprocessing spawn method's conflict when _fixup_main_from_path() is called
experts, I am using python's multiprocessing's spawn method to spawn child processes. The child process is a function call. One issue that recently get notified is when child process is created, it will try to import all the import statement from main module via the call to _fixup_main_from_path() I actually don't need...
[ "You said: We don't want my_lib.py to depend on file1.py or x1.py.\nYour module already depends on x1.py because you need to import it so that you can call addFataSignalCallback. So that should not be an issue. Not wanting a dependence on file1.py is understandable. If you are concerned about whether whatever scrip...
[ 0 ]
[]
[]
[ "multiprocessing", "python", "subprocess" ]
stackoverflow_0074502924_multiprocessing_python_subprocess.txt
Q: How can I get the links of the apps from a certain developer, till now i have scrapped the web objects but unable to get the actual links? I am trying to extract the links of all application from a particular developer present on the playstore. import time from selenium import webdriver from webdriver_manager.chro...
How can I get the links of the apps from a certain developer, till now i have scrapped the web objects but unable to get the actual links?
I am trying to extract the links of all application from a particular developer present on the playstore. import time from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver. common.by import By driver = webdriver.Chrome (executable_path=ChromeDriverManager().ins...
[ "You are close to the solution.\nInside elements you located there are a elements containing the links.\nAll you need here is to wait for all those elements to become visible, get the list of those elements, iterate over the list and extract the links.\nThe following cod works:\nfrom selenium import webdriver\nfrom...
[ 0 ]
[]
[]
[ "css_selectors", "python", "selenium", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074537588_css_selectors_python_selenium_selenium_webdriver_webdriverwait.txt
Q: Using conda-index with S3 I am hosting my own private conda channel on S3, but I don't understand how to avoid mirroring all the packages on my local hard drive. The source of the problem is the repodata.json, channeldata.json, etc. files. If I build a single package and copy just the .tar.bz2 file to S3, conda-in...
Using conda-index with S3
I am hosting my own private conda channel on S3, but I don't understand how to avoid mirroring all the packages on my local hard drive. The source of the problem is the repodata.json, channeldata.json, etc. files. If I build a single package and copy just the .tar.bz2 file to S3, conda-install does not see it in the ch...
[ "One way to host a private conda channel in s3 and build packages there is to mount the s3 bucket as a FUSE filesystem (goofys works well for this task) and then run conda build and conda index locally.\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "conda", "python" ]
stackoverflow_0053269465_amazon_s3_conda_python.txt
Q: How can I remove the self-loop edges from a NetworkX undirected graph plot? I thought this would be obvious but I can't seem to figure this out. I tried just making all of the self-loops a weight of 0. It looks like the order of the edges isn't preserved or something. d = {'PRJNA551026-COASSEMBLY__METABAT2__P.1__...
How can I remove the self-loop edges from a NetworkX undirected graph plot?
I thought this would be obvious but I can't seem to figure this out. I tried just making all of the self-loops a weight of 0. It looks like the order of the edges isn't preserved or something. d = {'PRJNA551026-COASSEMBLY__METABAT2__P.1__bin.24': {'PRJNA551026-COASSEMBLY__METABAT2__P.1__bin.24': {'weight': 100.0}, 'SR...
[ "Instead of adjusting the edge weights, you can just pass an edgelist to draw_networkx_edges() and it will plot only those edges. There is a convenience function that only returns selfloops from a list of edges, so putting that together, you get:\nd = {'PRJNA551026-COASSEMBLY__METABAT2__P.1__bin.24': {'PRJNA551026...
[ 0 ]
[]
[]
[ "graph", "matplotlib", "networkx", "python" ]
stackoverflow_0074537283_graph_matplotlib_networkx_python.txt
Q: The output is mot coming as expected and the values are getting returned as none class Dog: def bark (self ): print("The dogo is barking") return def yolo (self): print ("Munni badnam") return d= Dog() print(d.bark()) print(d.yolo()) This is my code and this is my output - The...
The output is mot coming as expected and the values are getting returned as none
class Dog: def bark (self ): print("The dogo is barking") return def yolo (self): print ("Munni badnam") return d= Dog() print(d.bark()) print(d.yolo()) This is my code and this is my output - The dogo is barking None Munni badnam None
[ "This will do what you expect.\nclass Dog:\n def bark (self ):\n return \"The dogo is barking\"\n\n def yolo (self):\n return \"Munni badnam\"\n \nd= Dog()\nprint(d.bark())\nprint(d.yolo())\n\nAs a very general rule, a function like that should not have side effects (like printing stuff). Just let th...
[ 0 ]
[]
[]
[ "object", "python" ]
stackoverflow_0074537991_object_python.txt
Q: How to unpack only values from nested dict in for loop I have the following code mydict = { "key": { "k1": "v1", "k2": "v2", } } for k, (v1, v2) in mydict.items(): v1 and v2 actaully equals to k1 and k2, is there a way to extract v1 and v2 with any unpacking syntax? I tried to search for u...
How to unpack only values from nested dict in for loop
I have the following code mydict = { "key": { "k1": "v1", "k2": "v2", } } for k, (v1, v2) in mydict.items(): v1 and v2 actaully equals to k1 and k2, is there a way to extract v1 and v2 with any unpacking syntax? I tried to search for unpacking syntax but found nothing
[ "No need to complicate on trying to unpack values. Here is a workaround\nfor k, (v1, v2) in mydict.items():\n print(\"Access the values for the key:\", k, \"--->\", mydict[k][v1], mydict[k][v2])\n\noutput:\nAccessing the values for the key: key ---> v1 v2\n\n", "It is possible like this:\nmydict = {\n \"key...
[ 1, 0 ]
[]
[]
[ "argument_unpacking", "dictionary", "python", "python_3.x" ]
stackoverflow_0074533047_argument_unpacking_dictionary_python_python_3.x.txt