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: Concatenate Columns in CSV file using Python and Count the Total per UniqueID This question have been asked multiple times in this community but I couldn't find the correct answers since I am beginner in Python. I got 2 questions actually: I want to concatenate 3 columns (A,B,C) with its value into 1 Column. Head...
Concatenate Columns in CSV file using Python and Count the Total per UniqueID
This question have been asked multiple times in this community but I couldn't find the correct answers since I am beginner in Python. I got 2 questions actually: I want to concatenate 3 columns (A,B,C) with its value into 1 Column. Header would be ABC. import os import pandas as pd directory = 'C:/Path' ext = ('.csv'...
[ "Next time, try to specify your issues and give a minimal reproducible example.\nThis is just an example how to use pd.melt and pd.groupby.\nI hope it helps with your question.\nimport pandas as pd\n\n### example dataframe\ndf = pd.DataFrame([['first', 1, 2, 3], ['second', 4, 5, 6], ['third', 7, 8, 9]], columns=['I...
[ 0, 0 ]
[]
[]
[ "concatenation", "csv", "hyperlink", "python" ]
stackoverflow_0074598513_concatenation_csv_hyperlink_python.txt
Q: How to sort the columns by length of values in an excel file in python ? (preferably using def) I have a list of data as following. I need to add the current data to a new worksheet sorted by the length of the values in the third column (p_seq) enter image description here I was able to add the current data using ...
How to sort the columns by length of values in an excel file in python ? (preferably using def)
I have a list of data as following. I need to add the current data to a new worksheet sorted by the length of the values in the third column (p_seq) enter image description here I was able to add the current data using openpyxl but I'm struggling with sorting them. Ideally I would like to create a function. Thank you i...
[ " strings_col1 = [\"abcdefgh\", \"ijklmn\", \"opqr\", \"stuvwxyz123\"]\n sorted_list_col1 = list(sorted(strings_col1, key = len))\n print(sorted_list_col1)\n\noutput:\n\n['opqr', 'ijklmn', 'abcdefgh', 'stuvwxyz123']\n\n" ]
[ 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0074609845_excel_openpyxl_python.txt
Q: How to remove to duplicates of a list in python? Exercise: “Let’s go Grocery Shopping” A mother wants to list down the things she needs to buy, however, she needs a simple list that be run every time and can be modified whenever she changes her mind. Starting with just an empty list, write a function that creates ...
How to remove to duplicates of a list in python?
Exercise: “Let’s go Grocery Shopping” A mother wants to list down the things she needs to buy, however, she needs a simple list that be run every time and can be modified whenever she changes her mind. Starting with just an empty list, write a function that creates a grocery list that does the following: • Add an Item ...
[]
[]
[ "I think you want this.\nremove_item = \"eggs\"\nmyList = [\"Eggs\", \"eggS\", \"eGgS\", \"miLk\", \"milk\"]\nresult=[]\n\nmarker = set()\n\nfor l in myList:\n ll = l.lower()\n if ll != remove_item.lower():\n result.append(ll)\n\n\nprint(result)\n\n", "You would want the remove_items function to look...
[ -1, -1 ]
[ "list", "python", "python_3.x" ]
stackoverflow_0074609829_list_python_python_3.x.txt
Q: Pandas .sort_values() function returning data frame with scattered values I'm using pandas to load a short_desc.csv with the following columns: ["report_id", "when","what"] with #read csv shortDesc = pd.read_csv('short_desc.csv') #get all numerical and nonnull values shortDesc = shortDesc[shortDesc['report_id']....
Pandas .sort_values() function returning data frame with scattered values
I'm using pandas to load a short_desc.csv with the following columns: ["report_id", "when","what"] with #read csv shortDesc = pd.read_csv('short_desc.csv') #get all numerical and nonnull values shortDesc = shortDesc[shortDesc['report_id'].str.isdigit().notnull()] #convert 'when' from UNIX timestamp to datetime short...
[ "I found out that:\n#get all numerical and nonnull values\nshortDesc = shortDesc[shortDesc['report_id'].str.isdigit().notnull()]\n\nwas only checking if a value was not null and probably overwriting the str.isdigit() check, which caused the field \"report_id\" to not drop nonnumeric values. I changed this to two se...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074596270_dataframe_pandas_python.txt
Q: How can I put a table inside a layout box using Rich in Python? This is code I am using to put a table inside the layout. However, in the output I am getting lot of ansii code-like characters, and even though I have defined the colour attribute for the column, in the output it is not appearing. from re import X im...
How can I put a table inside a layout box using Rich in Python?
This is code I am using to put a table inside the layout. However, in the output I am getting lot of ansii code-like characters, and even though I have defined the colour attribute for the column, in the output it is not appearing. from re import X import psycopg2 from rich.console import Console from rich.table import...
[ "No need to capture the output of the Table. Return the Table instance and add it to your layout.\n" ]
[ 1 ]
[]
[]
[ "python", "rich" ]
stackoverflow_0074523297_python_rich.txt
Q: nested list comprehension with os.walk Trying to enumerate all files in a certain directory (like 'find .' in Linux, or 'dir /s /b' in Windows). I came up with the following nested list comprehension: from os import walk from os.path import join root = r'c:\windows' #choose any folder here allfiles = [join(ro...
nested list comprehension with os.walk
Trying to enumerate all files in a certain directory (like 'find .' in Linux, or 'dir /s /b' in Windows). I came up with the following nested list comprehension: from os import walk from os.path import join root = r'c:\windows' #choose any folder here allfiles = [join(root,f) for f in files for root,dirs,files in ...
[ "You need to reverse the nesting;\nallfiles = [join(root,f) for root,dirs,files in walk(root) for f in files]\n\nSee the list comprehension documentation:\n\nWhen a list comprehension is supplied, it consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case...
[ 29, 5, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0013051785_list_comprehension_python.txt
Q: Side inputs to WriteToBigQuery - PCollection of size 2 with more than one element accessed as a singleton view I have a streaming apache beam pipeline which does operations on data and writes to big query, the table name and schema of said data is within the data itself, so i am using side inputs to provide table ...
Side inputs to WriteToBigQuery - PCollection of size 2 with more than one element accessed as a singleton view
I have a streaming apache beam pipeline which does operations on data and writes to big query, the table name and schema of said data is within the data itself, so i am using side inputs to provide table name and schema using side_inputs for both of them. So my pipeline code looks something like this - pipeline | "Wri...
[ "This issue occurs probably due to some issue with the code which is returning elements in GlobalWindow while the PCollection has a different window set. For your requirement, I would suggest you to insert beam.WindowInto(beam.window.GlobalWindows()) between beam.WindowInto(NONGLOBALWINDOW) | beam.GroupByKey() an...
[ 0 ]
[]
[]
[ "apache_beam", "google_bigquery", "google_cloud_dataflow", "google_cloud_platform", "python" ]
stackoverflow_0074589874_apache_beam_google_bigquery_google_cloud_dataflow_google_cloud_platform_python.txt
Q: How to continue the loop after thrown an error with python? I want to create a small program keep print error using while-loop after raised an exception. If we input incorrect number. n = int(input("Enter: ")) error = False while not error: class error(BaseException): pass try: def n...
How to continue the loop after thrown an error with python?
I want to create a small program keep print error using while-loop after raised an exception. If we input incorrect number. n = int(input("Enter: ")) error = False while not error: class error(BaseException): pass try: def number(n): if n == 2: print("correct")...
[ "As was pointed out in the comments, the issue is caused by using the same name error for your custom exception class and for a boolean variable which you seem to have intended to use to track the current status. Once you run:\nclass error(BaseException):\n pass\n\nerror is now a class, which is not False so the...
[ 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074609854_python_while_loop.txt
Q: How to write/use K8 Python client to create a new role, sa & role binding I am currently figuring out what is the best way to programmatically manage the Kubernetes cluster (eks). I have come across a python Kubernetes client where I was able to load the local config and then create a namespace. I am running a jen...
How to write/use K8 Python client to create a new role, sa & role binding
I am currently figuring out what is the best way to programmatically manage the Kubernetes cluster (eks). I have come across a python Kubernetes client where I was able to load the local config and then create a namespace. I am running a jenkins job where I would like it to create a namespace, role, rolebinding, as. I ...
[ "You'll most likely want to use the RbacAuthorizationV1Api. Afterward you can call create_namespaced_role and create_namespaced_role_binding to make what you need.\nA snippet might look like\nfrom kubernetes import client, config\n\nconfig.load_incluster_config()\npolicy_api = client.RbacAuthorizationV1Api()\nrole ...
[ 0 ]
[]
[]
[ "client", "k8s_serviceaccount", "kubernetes", "programmatically", "python" ]
stackoverflow_0071563628_client_k8s_serviceaccount_kubernetes_programmatically_python.txt
Q: Redirect localhost:5000/some_path to localhost:5000 I have a dockenizer flask api app that runs in localhost:5000. The api runs with no problem. But when I tried to use it by another app, which I cannot change, it uses localhost:5000/some_path. I'd like to redirect from localhost:5000/some_path to localhost:5000. ...
Redirect localhost:5000/some_path to localhost:5000
I have a dockenizer flask api app that runs in localhost:5000. The api runs with no problem. But when I tried to use it by another app, which I cannot change, it uses localhost:5000/some_path. I'd like to redirect from localhost:5000/some_path to localhost:5000. I have read that I can use a prefix in my flask api app, ...
[ "If you use a web server to serve your application you could manage it with it, for example with nginx you could do:\nlocation = /some_path {\n return 301 /;\n}\n\nOr you can use a middleware:\nclass PrefixMiddleware(object):\n def __init__(self, app, prefix=\"\"):\n self.app = app\n self.prefix =...
[ 0 ]
[]
[]
[ "api", "flask", "python" ]
stackoverflow_0074604160_api_flask_python.txt
Q: Get only unique words from a sentence in Python Let's say I have a string that says "mango mango peach". How can I print only the unique words in that string. The desired output for the above string would be [peach] as a list Thanks!! A: Python has a built in method called count that would work very well here ...
Get only unique words from a sentence in Python
Let's say I have a string that says "mango mango peach". How can I print only the unique words in that string. The desired output for the above string would be [peach] as a list Thanks!!
[ "Python has a built in method called count that would work very well here \ntext = \"mango mango peach apple apple banana\"\nwords = text.split()\n\nfor word in words:\n if text.count(word) == 1:\n print(word)\n else:\n pass\n\n\n(xenial)vash@localhost:~/python/stack_overflow$ python3.7 mango...
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0052373683_python.txt
Q: how can I use Python WatchDog to find out who changed the file? There is the simplest script that shows when it was changed, but how do I get detailed information? For example, who changed it with reference to the directory. ` import sys import logging from watchdog.observers import Observer from watchdog.events i...
how can I use Python WatchDog to find out who changed the file?
There is the simplest script that shows when it was changed, but how do I get detailed information? For example, who changed it with reference to the directory. ` import sys import logging from watchdog.observers import Observer from watchdog.events import LoggingEventHandler if __name__ == "__main__": logging.bas...
[ "The watchdog works via inotify mechanism and will only notify you that a file had been changed, created or deleted. There is no information in the filesystem about who did the change. The information you have is basically the same information that you would get by looking at a directory listing such as with ls -al...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074609932_python_python_3.x.txt
Q: Problem importing TensorFlow 2 in Python (running on WSL in Windows) Problem: I followed Microsoft's instruction in order to properly install and run TensorFlow 2 in WSL with GPU acceleration, using DirectML (here's the document). Following the installation, when I try and import tensorflow in Python I get the fol...
Problem importing TensorFlow 2 in Python (running on WSL in Windows)
Problem: I followed Microsoft's instruction in order to properly install and run TensorFlow 2 in WSL with GPU acceleration, using DirectML (here's the document). Following the installation, when I try and import tensorflow in Python I get the following output: >>> import tensorflow ...
[ "Had the same problem, and downgrading TensorFlow from 2.11 fixed it. First remove the existing version:\npip uninstall tensorflow-cpu\n\nThen re-install, this time with 2.10.0:\npip install tensorflow-cpu==2.10.0\n\nAfter that, try importing it in Python. You should see something like the following (apologies for ...
[ 0 ]
[]
[]
[ "anaconda", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074534936_anaconda_python_tensorflow_tensorflow2.0.txt
Q: How to read json data in Python that received the json data from sns This is the json data I am receiving from aws sns notifications. I want to access deploymentGroupName which is inside the Records->Sns->Message In my lambda python code I am trying to do like this. eventName = json.loads(event.Records[0].Sns.Mes...
How to read json data in Python that received the json data from sns
This is the json data I am receiving from aws sns notifications. I want to access deploymentGroupName which is inside the Records->Sns->Message In my lambda python code I am trying to do like this. eventName = json.loads(event.Records[0].Sns.Message).deploymentGroupName; This is the json I received. { 'Records': ...
[ "If event has no \"\" surrounding, it has converted to dict already. However, you need to deal with json for Message.\nimport json\n\nmsg = event['Records'][0]['Sns']['Message']\ndeploymentGroupName = json.loads(msg)['deploymentGroupName']\ndeploymentGroupName\n\noutput:\n'Sandbox-ec2-deployment'\n\n" ]
[ 2 ]
[]
[]
[ "aws_lambda", "json", "lambda", "python" ]
stackoverflow_0074610109_aws_lambda_json_lambda_python.txt
Q: Tkinter on mac shows up as a black screen So here is my code: from tkinter import * root = Tk() root.title("Greeting") Label(root, text = "Hello World").pack() root.mainloop() but the only thing that shows up on the window after running it is a black screen you can see the code and the window in this image if it ...
Tkinter on mac shows up as a black screen
So here is my code: from tkinter import * root = Tk() root.title("Greeting") Label(root, text = "Hello World").pack() root.mainloop() but the only thing that shows up on the window after running it is a black screen you can see the code and the window in this image if it helps
[ "After much digging, I've found a solution (with some caveats) -\nyou'll need both homebrew and pyenv installed for this to work. The idea is to replace your old deprecated tkinter installation with an up-to-date one that actually works*\n\nNote that this will wipe out any packages you’ve installed with pip - back ...
[ 3, 0, 0, 0 ]
[]
[]
[ "macos", "python", "tkinter" ]
stackoverflow_0073056296_macos_python_tkinter.txt
Q: Deploy Django CMS on IIS Server After learning from this tutorial now I can run Django CMS on my laptop using virual envronment. But I want to deploy this CMS to IIS server. I also installed pip install wfastcgi But when I try to set DJANGO_SETTINGS_MODULE in IIS CGI Setting, I find that I still don't have .set...
Deploy Django CMS on IIS Server
After learning from this tutorial now I can run Django CMS on my laptop using virual envronment. But I want to deploy this CMS to IIS server. I also installed pip install wfastcgi But when I try to set DJANGO_SETTINGS_MODULE in IIS CGI Setting, I find that I still don't have .settings file yet. Regarding to settin...
[ "I tried the tutorial. I found the problem you mentioned. Actually, the settings.py file in your screenshot is the \".settings\" file you are missing.\nAnd you want to know how to deploy Django CMS on IIS Server. You can refer to this tutorial for the steps. Hope it is useful for you.\n" ]
[ 0 ]
[]
[]
[ "cgi", "django_cms", "iis", "python", "window" ]
stackoverflow_0074601681_cgi_django_cms_iis_python_window.txt
Q: How to include the start date and end date while filtering in django In views.py: if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strpt...
How to include the start date and end date while filtering in django
In views.py: if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) check_box_status = request....
[ "Breaks.objects.filter(date__range=[\"2011-01-01\", \"2011-01-31\"])\n\nOr if you are just trying to filter month wise:\nBreaks.objects.filter(date__year='2011', \n date__month='01')\n\nPlease reply to this message ,If it doesn't work.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074609060_django_python.txt
Q: NameError: name 'get_transforms' is not defined This code was running without any problems before I updated my python and fastai: from fastai import * from fastai.vision import * import torch ... tfms = get_transforms(do_flip=True,flip_vert=True,max_rotate=360,max_warp=0,max_zoom=1.1,max_lighting=0.1,p_lighting=0....
NameError: name 'get_transforms' is not defined
This code was running without any problems before I updated my python and fastai: from fastai import * from fastai.vision import * import torch ... tfms = get_transforms(do_flip=True,flip_vert=True,max_rotate=360,max_warp=0,max_zoom=1.1,max_lighting=0.1,p_lighting=0.5) After updating the fastai to 2.1.2 and python to ...
[ "For Data Augmentation methods in FastAI 2 you have to use other methods names, for example:\naug_transforms\n", "I got the same question, fastai 1.0.61 could probably solve the problem.\n", "Enter this code at the very beginning and download it :\n!pip install \"torch==1.4\" \"torchvision==0.5.0\"\n\n" ]
[ 4, 0, 0 ]
[]
[]
[ "fast_ai", "python", "python_3.x" ]
stackoverflow_0064643190_fast_ai_python_python_3.x.txt
Q: How to iterate over dictionaries in a list and extract key values to a separate list I'm trying to match key value from different dictionaries in a list and make them as individual list.Below is the example format originallist=[ {"A":"Autonomous","C":"Combined","D":"Done"}, {"B":"Bars","A":"Aircraft"}, {"C":"Calcu...
How to iterate over dictionaries in a list and extract key values to a separate list
I'm trying to match key value from different dictionaries in a list and make them as individual list.Below is the example format originallist=[ {"A":"Autonomous","C":"Combined","D":"Done"}, {"B":"Bars","A":"Aircraft"}, {"C":"Calculative"} ] #Note: The dictionaries present in the original list may vary in number #I was...
[ "The best option would be to use a defaultdict.\nfrom collections import defaultdict\n\nout = defaultdict(list)\n\n#data is the list in question\n\nfor rec in data:\n for key,value in rec.items():\n out[key].append(value)\n\n\nA defaultdict returns a default value in case the key does not exist. dict.item...
[ 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074610186_dictionary_list_python.txt
Q: Python - Data Attributes vs Class Attributes and Instance Attributes - When to use Data Attributes? I am learning Python and have started a chapter on "classes" and also class/instance attributes. The chapter starts off with a very basic example of creating an empty class class Contact: pass x=Contact() So an...
Python - Data Attributes vs Class Attributes and Instance Attributes - When to use Data Attributes?
I am learning Python and have started a chapter on "classes" and also class/instance attributes. The chapter starts off with a very basic example of creating an empty class class Contact: pass x=Contact() So an empty class is created and an instance of the class is created. Then it also throws in the following lin...
[ "Python is a very dynamic language. Classes acts like molds, they can create instance according to a specific shape, but unlike other languages where shapes are fixed, in Python you can (nearly) always modify their shape.\nI never heard of \"data attribute\" in this context, so I'm not surprised that you did find n...
[ 1 ]
[]
[]
[ "attributes", "class", "python" ]
stackoverflow_0074603434_attributes_class_python.txt
Q: Set variable storing text as a .get_group category Is it possible to use a variable storing text or a list as a category for .get_group. Something like this: import pandas as pd df = pd.read_excel("HondaSales.xlsx") brand = ["honda", "acura"] year = "2020" brands1 = df.groupby(["Brand","Year"]) honda = brands1...
Set variable storing text as a .get_group category
Is it possible to use a variable storing text or a list as a category for .get_group. Something like this: import pandas as pd df = pd.read_excel("HondaSales.xlsx") brand = ["honda", "acura"] year = "2020" brands1 = df.groupby(["Brand","Year"]) honda = brands1.get_group([brand, year]) sales = honda["UNI_VEH"] sales...
[]
[]
[ "Here is the error:\nhonda = brands1.get_group([brand, year]), please share more info, because it suits you.\n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0074609849_pandas_python.txt
Q: Why am I getting {"detail":[{"loc":["path","id"],"msg":"field required","type":"value_error.missing"}]} if I made query with params? This is the endpoint that is not working: @router.get( "/{question_id}", tags=["questions"], status_code=status.HTTP_200_OK, response_model=Question, dependencies...
Why am I getting {"detail":[{"loc":["path","id"],"msg":"field required","type":"value_error.missing"}]} if I made query with params?
This is the endpoint that is not working: @router.get( "/{question_id}", tags=["questions"], status_code=status.HTTP_200_OK, response_model=Question, dependencies=[Depends(get_db)], ) def get_question(id: int = Path(..., gt=0)): return get_question_service(id) This is what the server shows when...
[ "There is a mismatch between the path parameter in the path string and the function argument. Rename the function argument to question_id\n@router.get(\n \"/{question_id}\",\n tags=[\"questions\"],\n status_code=status.HTTP_200_OK,\n response_model=Question,\n dependencies=[Depends(get_db)],\n)\ndef ...
[ 0 ]
[]
[]
[ "fastapi", "fastapi_crudrouter", "python" ]
stackoverflow_0074608894_fastapi_fastapi_crudrouter_python.txt
Q: "cannot connect to X server" while trying to connect to PyBullet in WSL I am currently using a windows machine, and am busy with some Genetic Algorithm stuff that relies on using a PyBullet virtual environment to test out the locomotive capacity of my "robots". The project I'm working on required me to use multi-t...
"cannot connect to X server" while trying to connect to PyBullet in WSL
I am currently using a windows machine, and am busy with some Genetic Algorithm stuff that relies on using a PyBullet virtual environment to test out the locomotive capacity of my "robots". The project I'm working on required me to use multi-threading, so my lecturer recommended that I install WSL to do so because appa...
[ "It looks like your script wants to open some sort of graphical user interface.\nYou can try to install an X11 server on windows and configure this in WSL. That way you can open a graphical window in WSL. You should be able to find some tutorials online, but it can be a bit tedious. This could help you to get start...
[ 0, 0 ]
[]
[]
[ "pybullet", "python", "windows_subsystem_for_linux" ]
stackoverflow_0074600817_pybullet_python_windows_subsystem_for_linux.txt
Q: Python: Traceback codecs.charmap_decode(input,self.errors,decoding_table)[0] Following is sample code, aim is just to merges text files from give folder and it's sub folder. i am getting Traceback occasionally so not sure where to look. also need some help to enhance the code to prevent blank line being merge & to...
Python: Traceback codecs.charmap_decode(input,self.errors,decoding_table)[0]
Following is sample code, aim is just to merges text files from give folder and it's sub folder. i am getting Traceback occasionally so not sure where to look. also need some help to enhance the code to prevent blank line being merge & to display no lines in merged/master file. Probably it's good idea to before merging...
[ "The error is thrown because Python 3 opens your files with a default encoding that doesn't match the contents.\nIf all you are doing is copying file contents, you'd be better off using the shutil.copyfileobj() function together with opening the files in binary mode. That way you avoid encoding issues altogether (a...
[ 18, 4 ]
[ "Handling import and decode error with file handling\n\nOpen file with full absolute path\n\n(source - absolute path for directory of file folder, getting all files inside file_folder)\nimport os\nfile_list = os.listdir(source)\nfor file in file_list:\n absolute_file_path = os.path.join(source,file) \n fil...
[ -1 ]
[ "file_io", "python", "python_3.x", "python_unicode", "traceback" ]
stackoverflow_0012213178_file_io_python_python_3.x_python_unicode_traceback.txt
Q: Web scraping with Python - how to click on date of same value I'm trying to click on the button that contains the text "30 de novembro" but when I use my code it clicks on the "30 de outubro" button How to fix? Screenshot of HTML code Here's the code I'm using selecdia = navegador.find_element(by=By.LINK_TEXT, val...
Web scraping with Python - how to click on date of same value
I'm trying to click on the button that contains the text "30 de novembro" but when I use my code it clicks on the "30 de outubro" button How to fix? Screenshot of HTML code Here's the code I'm using selecdia = navegador.find_element(by=By.LINK_TEXT, value='30') selecdia.click() sleep(1)
[ "Looks like the title attribute is the only way to uniquely identify the link you wish to click, therefore in Selenium 4 syntax:\nselecdia = navegador.find_element(By.CSS_SELECTOR, \"a[title='30 de novembro']\")\n\nor:\nselecdia = navegador.find_element(By.XPATH, \"//a[@title='30 de novembro']\")\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "pandas", "python", "selenium", "web_scraping" ]
stackoverflow_0074607736_beautifulsoup_pandas_python_selenium_web_scraping.txt
Q: Odoo - Different XPath depending on a field I want Odoo to show an Xpath or not, depending on a condition I have this 3 fields lots_id = fields.Many2one('stock.production.lot', 'Lot/Serial Number') q_auth = fields.Boolean(related='lot_id.q_auth', string="Quality Auth.") needs_auth= fields.Boolean("Needs Auth") If...
Odoo - Different XPath depending on a field
I want Odoo to show an Xpath or not, depending on a condition I have this 3 fields lots_id = fields.Many2one('stock.production.lot', 'Lot/Serial Number') q_auth = fields.Boolean(related='lot_id.q_auth', string="Quality Auth.") needs_auth= fields.Boolean("Needs Auth") If needs_auth == False, i need to show this xpath ...
[ "You can use onchange function and return lots_id field domain when the needs_auth field value change.\nExample:\n@api.onchange(\"needs_auth\")\ndef _update_lots_id_domain(self):\n domain = [('product_id', '=?', self.product_id.id)]\n if self.needs_auth:\n domain.append(\n ('q_auth', '!=', F...
[ 0, 0 ]
[]
[]
[ "odoo", "odoo_8", "python", "xml" ]
stackoverflow_0074595716_odoo_odoo_8_python_xml.txt
Q: Python Dataframe Linear Regression every column being emptied? I'm working with Pandas & Numpy to create a Linear Regression model to predict the gross of movies. I'm able to successfully import the dataset and drop the columns I'm not using, and convert the ones I am into float64. This leads to some columns havin...
Python Dataframe Linear Regression every column being emptied?
I'm working with Pandas & Numpy to create a Linear Regression model to predict the gross of movies. I'm able to successfully import the dataset and drop the columns I'm not using, and convert the ones I am into float64. This leads to some columns having NaN as values: import pandas as pd import numpy as np import sklea...
[ "You can use: errors ='ignore', Where both text and numbers are given.\nThere are other ways of preprocessing, you just need to know what you need it for.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "linear_regression", "numpy", "pandas", "python" ]
stackoverflow_0074602692_dataframe_linear_regression_numpy_pandas_python.txt
Q: Filtering a column with an empty array in Pyspark I have a DataFrame which contains a lot of repeated values. An aggregated, distinct count of it looks like below > df.groupby('fruits').count().sort(F.desc('count')).show() | fruits | count | | ----------- | ----------- | | [Apples] | 123 ...
Filtering a column with an empty array in Pyspark
I have a DataFrame which contains a lot of repeated values. An aggregated, distinct count of it looks like below > df.groupby('fruits').count().sort(F.desc('count')).show() | fruits | count | | ----------- | ----------- | | [Apples] | 123 | | [] | 344 | | [Apples, plum]|...
[ "It might be an array containing an empty string:\nis_empty = F.udf(lambda arr: arr == [''], T.BooleanType())\n\nOr it might be an array of null:\nis_empty = F.udf(lambda arr: arr == [None], T.BooleanType())\n\nTo check them all at once you can use:\nis_empty = F.udf(lambda arr: arr in [[], [''], [None]], T.Boolean...
[ 3, 2, 0 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "pyspark", "python" ]
stackoverflow_0065662265_apache_spark_apache_spark_sql_pyspark_python.txt
Q: A weighted version of random.choice I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with: def weightedChoice(choices): """Like random.choice, but each element can have a different chance of being select...
A weighted version of random.choice
I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with: def weightedChoice(choices): """Like random.choice, but each element can have a different chance of being selected. choices can be any iterable cont...
[ "Since version 1.7.0, NumPy has a choice function that supports probability distributions.\nfrom numpy.random import choice\ndraw = choice(list_of_candidates, number_of_items_to_pick,\n p=probability_distribution)\n\nNote that probability_distribution is a sequence in the same order of list_of_candidat...
[ 405, 357, 143, 82, 24, 20, 17, 15, 14, 10, 5, 4, 3, 3, 2, 2, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "Step-1: Generate CDF F in which you're interesting\nStep-2: Generate u.r.v. u\nStep-3: Evaluate z=F^{-1}(u)\nThis modeling is described in course of probability theory or stochastic processes. This is applicable just because you have easy CDF.\n" ]
[ -1 ]
[ "optimization", "python" ]
stackoverflow_0003679694_optimization_python.txt
Q: Error on Python serial import When I try to import the serial I get the following error: Traceback (most recent call last): File "C:\Documents and Settings\eduardo.pereira\workspace\thgspeak\tst.py", line 7, in <module> import serial File "C:\Python27\lib\site-packages\serial\__init__.py", line 27, in <mod...
Error on Python serial import
When I try to import the serial I get the following error: Traceback (most recent call last): File "C:\Documents and Settings\eduardo.pereira\workspace\thgspeak\tst.py", line 7, in <module> import serial File "C:\Python27\lib\site-packages\serial\__init__.py", line 27, in <module> from serial.serialwin32 im...
[ "The version of pySerial that you're using is trying to call a function that's only available in Windows Vista, whereas you're running Windows XP.\nIt might be worth experimenting with using an older version of pySerial.\nThe code in question was added to pySerial on 3 May 2016, so a version just prior to that migh...
[ 3, 3, 1, 0 ]
[]
[]
[ "pyserial", "python" ]
stackoverflow_0038262930_pyserial_python.txt
Q: Torch: Input type and weight type (torch.cuda.FloatTensor) should be the same Note: I have already seen similar questions: the same error, tell torch not to use GPU, but the answers do not work for me. I have installed PyTorch version 1.13.0+cu117 (the latest), and the code structure is as follows (an image classi...
Torch: Input type and weight type (torch.cuda.FloatTensor) should be the same
Note: I have already seen similar questions: the same error, tell torch not to use GPU, but the answers do not work for me. I have installed PyTorch version 1.13.0+cu117 (the latest), and the code structure is as follows (an image classification task): # os.environ["CUDA_VISIBLE_DEVICES"]="" # required? device = tor...
[ "The issue was due to incorrect usage of summary from torchinfo. It does a forward pass (if input size is provided), and the device is (by default) selected on basis of torch.cuda.is_available().\nIf device (as specified in the question) argument is given to summary, the training happens just fine.\n" ]
[ 0 ]
[]
[]
[ "deep_learning", "machine_learning", "python", "pytorch" ]
stackoverflow_0074609050_deep_learning_machine_learning_python_pytorch.txt
Q: Dynamically create pyspark dataframes according to a condition I have a pyspark dataframe store_df :- store ID Div 637 4000000970 Pac 637 4000000435 Pac 637 4000055542 Pac 637 4000042206 Pac 638 2200015935 Pac 638 2200000483 Pac 638 4000014114 Pac 640 4000000162 Pac 640 2200000067 Pac 642 2200000067 Mac...
Dynamically create pyspark dataframes according to a condition
I have a pyspark dataframe store_df :- store ID Div 637 4000000970 Pac 637 4000000435 Pac 637 4000055542 Pac 637 4000042206 Pac 638 2200015935 Pac 638 2200000483 Pac 638 4000014114 Pac 640 4000000162 Pac 640 2200000067 Pac 642 2200000067 Mac 642 4000044148 Mac 642 4000014114 Mac I want...
[ "I can't test it but it should be something like this if I understood it right now\nstore_ids = [637, 123, 865]\nfor store_id in store_ids: \n div_type = stores.select(\"Div\").where(f.col(\"ID\") == store_id ).collect()[0][0]\n final_list.join(stores, stores.ID == final_list.ID)\n .select(\"*\")\n ...
[ 0, 0 ]
[]
[]
[ "azure_databricks", "pyspark", "python" ]
stackoverflow_0074601979_azure_databricks_pyspark_python.txt
Q: unexpected link to one same object in different objects , while condition isn't works I face with unexpected link to one same object in different objects , while condition isn't works. So there are 3 objects: c1, c2, c3 = C(1, 'name1'), C(2, 'name2'), C(3, 'name3') they have next fields and interface: class C: ...
unexpected link to one same object in different objects , while condition isn't works
I face with unexpected link to one same object in different objects , while condition isn't works. So there are 3 objects: c1, c2, c3 = C(1, 'name1'), C(2, 'name2'), C(3, 'name3') they have next fields and interface: class C: def __init__(self, c_id:int, c_name:str, b:List=[]): self.c_id:int= c_id:int ...
[ "So, you could be confused hardy when you use mutable objects as a default value of argument in your methods. There is the best explanation .\n" ]
[ 1 ]
[]
[]
[ "asynchronous", "object", "python" ]
stackoverflow_0074603908_asynchronous_object_python.txt
Q: Try except works when file is run from IDE but when compiled into exe with pyinstaller it doesnt work I created a python tool with Tkinter GUI. These are the pieces of the script. The problem is with the try-except in these lines of code. try: pldf_csv[data['sls_data']['add_columns']].write_csv(endpath,sep='\t'...
Try except works when file is run from IDE but when compiled into exe with pyinstaller it doesnt work
I created a python tool with Tkinter GUI. These are the pieces of the script. The problem is with the try-except in these lines of code. try: pldf_csv[data['sls_data']['add_columns']].write_csv(endpath,sep='\t') except: write_eror_status = True print("CANNOT WRITE FILE") If I run the python file via VSCode th...
[ "Since the error was raised when writing CSV with polars and polars has its own dependencies, when it's in exe form it needs to include --recursive-copy-metadata as per documentation pyinstaller --recursive-copy-metadata polars --onefile -w \"myfile.py\"\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074609168_python.txt
Q: tqdm: extract time passed + time remaining? I have been going over the tqdm docs, but no matter where I look, I cannot find a method by which to extract the time passed and estimated time remaining fields (basically the center of the progress bar on each line: 00:00<00:02). 0%| | 0/200 [00:00<?, ?it/s] ...
tqdm: extract time passed + time remaining?
I have been going over the tqdm docs, but no matter where I look, I cannot find a method by which to extract the time passed and estimated time remaining fields (basically the center of the progress bar on each line: 00:00<00:02). 0%| | 0/200 [00:00<?, ?it/s] 4%|▎ | 7/200 [00:00<00:02, 68.64it/s] ...
[ "tqdm objects expose some information via the public property format_dict.\nfrom tqdm import tqdm\n\nwith tqdm(total=100) as t:\n ...\n t.update()\n print(t.format_interval(t.format_dict['elapsed']))\n\nOtherwise you could parse str(t).split()\n", "You can get elapsed and remaining time from format_dict ...
[ 17, 1, 0, -2 ]
[]
[]
[ "iterable", "printing", "progress_bar", "python", "tqdm" ]
stackoverflow_0056677267_iterable_printing_progress_bar_python_tqdm.txt
Q: Remove all combination of set at the end of string REGEX I want to write a REGEX that removes all combination of a group of characters from the end of strings. For instance removes "k", "t", "a", "u" and all of their combinations from the end of the string: Input: ["Rajakatu","Lapinlahdenktau","Nurmenkaut","Linnak...
Remove all combination of set at the end of string REGEX
I want to write a REGEX that removes all combination of a group of characters from the end of strings. For instance removes "k", "t", "a", "u" and all of their combinations from the end of the string: Input: ["Rajakatu","Lapinlahdenktau","Nurmenkaut","Linnakoskenkuat"] Output: ["Raja","Lapinlahden","Nurmen","Linnakosk...
[ "How about something like this [ktau]{4}\\b?\nhttps://regex101.com/r/BVwTcs/1\nThis will match at the end of a word for those character combinations.\nFor example, k, followed by u, followed by a, followed by t.\nThis can also match aaaa so take that into account.\nIt will match any 4 combinations of the characters...
[ 1, 0 ]
[]
[]
[ "combinations", "filter", "python", "string" ]
stackoverflow_0074610334_combinations_filter_python_string.txt
Q: Need to store my function's results as a dictionary value in Python Pandas I have 2 functions that read a csv file and count the following as checks: number of rows in that csv number of rows that have a null value in the 'ID' column I am trying to create a dataframe that looks like this Checks Summary Findings...
Need to store my function's results as a dictionary value in Python Pandas
I have 2 functions that read a csv file and count the following as checks: number of rows in that csv number of rows that have a null value in the 'ID' column I am trying to create a dataframe that looks like this Checks Summary Findings Check #1 Number of records on file function #1 results (Number of record...
[ "The reason is that you're printing the function objects, and not their results:\nfunction1 != function1()\nSo for your case you need:\ntable = {\n 'Checks' : ['Check #1', 'Check #2'],\n 'Summary' : ['Number of records on file', 'Number of records missing an ID'],\n 'Findings' : [function1(), function2()]\n...
[ 2, 2, 0 ]
[]
[]
[ "dataframe", "dictionary", "function", "pandas", "python" ]
stackoverflow_0074610722_dataframe_dictionary_function_pandas_python.txt
Q: How to move specific cells in an excel file to a new column with openpyxl in python I am trying to moving some specific cells to a designated location. As shown in the image, would like to move data in cells D3 to E2, D5 to E4,..... so on so for. Is it doable with openpyxl? Any suggestions would be greatly appreci...
How to move specific cells in an excel file to a new column with openpyxl in python
I am trying to moving some specific cells to a designated location. As shown in the image, would like to move data in cells D3 to E2, D5 to E4,..... so on so for. Is it doable with openpyxl? Any suggestions would be greatly appreciate it!! Click to see the image Here is what I got so far. It worked per say. wb=xl.load_...
[ "Thats a good effort.\nHere are some comments to help and also on how to skip one row.\n\nShould generally only ever need to save the workbook once at the end of all your edits, unless you are making multiple copies. So the wb.save after the insert command is not necessary.\nThere shouldn't be need to use 'mr + 1' ...
[ 0 ]
[]
[]
[ "excel", "move", "openpyxl", "python" ]
stackoverflow_0074539605_excel_move_openpyxl_python.txt
Q: How to validate random choice within Python? I've been trying to make this dumb little program that spits out a random quote to the user from either Kingdom Hearts or Alan Wake (both included in .txt files) and I've hit a snag. I've made the program select a random quote from either of the text files (residing in ...
How to validate random choice within Python?
I've been trying to make this dumb little program that spits out a random quote to the user from either Kingdom Hearts or Alan Wake (both included in .txt files) and I've hit a snag. I've made the program select a random quote from either of the text files (residing in lists) and to finish I just need to validate wheth...
[ "You are working with more than 1 if-statement this means that the programm is gonna check both of them individually also, check the first one if is correct is going to print 'correct' then is gonna check the next if-statement and if this one is false is gonna print \"Incorrect\", try doing this\nif quote == choice...
[ 1 ]
[]
[]
[ "if_statement", "list", "python", "random", "string" ]
stackoverflow_0074610751_if_statement_list_python_random_string.txt
Q: TypeError: pointplot() got an unexpected keyword argument This bit of code used to run without the error notification that follows the code. Any clues as to why this is happening here? fig, ax = plt.subplots(1,1,figsize=(16,5)) w = sns.pointplot(y='DelayTime',x='Weather2',data=df[['Weather2','DelayTime','Severity...
TypeError: pointplot() got an unexpected keyword argument
This bit of code used to run without the error notification that follows the code. Any clues as to why this is happening here? fig, ax = plt.subplots(1,1,figsize=(16,5)) w = sns.pointplot(y='DelayTime',x='Weather2',data=df[['Weather2','DelayTime','Severity']], hue = 'Severity' ,ci=N...
[ "I don't know why it worked before, but after reading the seaborn documentation ( documentation ) the parameter height doesn't exist when you use pointplot.\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python", "seaborn" ]
stackoverflow_0074610269_matplotlib_python_seaborn.txt
Q: unable to find the path for uploading a file using streamlit python code Im writting a simple python application where the user selects a file from their local file manager and tries to upload using strealit Im able to succesfully take the file the user had given using streamlit.uploader and stored the file in a ...
unable to find the path for uploading a file using streamlit python code
Im writting a simple python application where the user selects a file from their local file manager and tries to upload using strealit Im able to succesfully take the file the user had given using streamlit.uploader and stored the file in a temp directory from the stramlit app folder but the issue is i cant give the p...
[ "Thanks all for response after days of struggle at last I've figured out the mistake im making.\nI dont know if I'm right or wrong correct me if I'm wrong but this worked for me:\n object_name_in_gcs_bucket = bucket.blob(\"path-to-upload\"+file.name)\n\nChanging the , to + between the filepath and filename mad...
[ 1, 0, 0 ]
[]
[]
[ "api", "google_cloud_storage", "python", "python_3.x", "streamlit" ]
stackoverflow_0074574390_api_google_cloud_storage_python_python_3.x_streamlit.txt
Q: 403 Forbidden in airflow DAG Triggering API When I am trying to call the API from POSTMAN in Airflow DAG, I am facing a 403 Forbidden error. I have enabled the headers for basic authentication with the username and password in Postman. In the airflow.cfg file, I have enabled auth_backend = airflow.contrib.auth.bac...
403 Forbidden in airflow DAG Triggering API
When I am trying to call the API from POSTMAN in Airflow DAG, I am facing a 403 Forbidden error. I have enabled the headers for basic authentication with the username and password in Postman. In the airflow.cfg file, I have enabled auth_backend = airflow.contrib.auth.backends.password_auth. This error occurs when I att...
[ "The basic auth seems fine, it is base64 encoded already. 403 means you are authorized in the application but this specific action is forbidden. In airflow there are different roles admin/dag manager/operator and not all roles are allowed to do DAG operations. Can you specify the user role and operations you try to...
[ 2 ]
[]
[]
[ "airflow", "postman", "python" ]
stackoverflow_0074609067_airflow_postman_python.txt
Q: Python Azure function triggered by Blob storage printing file name incorrectly I'm triggering an Azure function with a blob trigger event. A container sample-workitems has a file base.csv and receives a new file new.csv. I'm reading base.csv from the sample-workitems and new.csv from InputStream for the same conta...
Python Azure function triggered by Blob storage printing file name incorrectly
I'm triggering an Azure function with a blob trigger event. A container sample-workitems has a file base.csv and receives a new file new.csv. I'm reading base.csv from the sample-workitems and new.csv from InputStream for the same container. def main(myblob: func.InputStream, base: func.InputStream): logging.info(f...
[ "I have reproduced in my environment and the below code worked for me and I followed code of @SwethaKandikonda 's SO-thread\ninit.py:\nimport logging\nfrom azure.storage.blob import BlockBlobService\nimport azure.functions as func\n\n\ndef main(myblob: func.InputStream):\n logging.info(f\"Python blob trigger fun...
[ 0 ]
[]
[]
[ "azure", "azure_blob_storage", "azure_functions", "python" ]
stackoverflow_0074596449_azure_azure_blob_storage_azure_functions_python.txt
Q: How to replace numbers in selected columns that falls in certain value python? How do you replace numbers with np.nan in selected columns if the number falls in between 2 ranges? A B C D 2 3 5 7 2 8 9 7 5 3 6 7 select columns B & C replace numbers if number is <=5 and >=7 A B C D 2 NaN 5 7 2 NaN NaN 7 5 N...
How to replace numbers in selected columns that falls in certain value python?
How do you replace numbers with np.nan in selected columns if the number falls in between 2 ranges? A B C D 2 3 5 7 2 8 9 7 5 3 6 7 select columns B & C replace numbers if number is <=5 and >=7 A B C D 2 NaN 5 7 2 NaN NaN 7 5 NaN 6 7
[ "Use a boolean mask for in place modification (boolean indexing):\ncols = ['B', 'C']\nm = (df[cols].gt(7)|df[cols].lt(5)).reindex(columns=df.columns, fill_value=False)\n\ndf[m] = np.nan\n\nIf you need a copy:\ncols = ['B', 'C']\nout = df.mask((df[cols].gt(7)|df[cols].lt(5))\n .reindex(columns=df.column...
[ 3, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074610668_dataframe_pandas_python.txt
Q: Having problems passing info from one function to another (Python) I'm fairly new to python (been taking classes for a few months) and I've come across a reoccurring problem with my code involving passing information, such as an integer, from one function to another. In this case, I'm having problems with passing ...
Having problems passing info from one function to another (Python)
I'm fairly new to python (been taking classes for a few months) and I've come across a reoccurring problem with my code involving passing information, such as an integer, from one function to another. In this case, I'm having problems with passing "totalPints" from "def getTotal" to "def averagePints" (totalPints in de...
[ "You have a variable scoping issue. In getTotal, totalPints is being updated with its value local to the function, not the global one like you are expecting. Returning the new value from the function and assigning it seems to have the intended effect. Below is the updated snippet:\n def getTotal(pints, t...
[ 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074609783_function_python.txt
Q: Is there a way to parse my xml file displaying only tags and value? In my XML file [studentinfo.xml] is there a way to loop through the xml file and only output each tag and the value? I would like child tags to be displayed as well. Below breaks everything down. I am open to other solutions as well. <?xml version...
Is there a way to parse my xml file displaying only tags and value?
In my XML file [studentinfo.xml] is there a way to loop through the xml file and only output each tag and the value? I would like child tags to be displayed as well. Below breaks everything down. I am open to other solutions as well. <?xml version="1.0" encoding="UTF-8"?> <stu:StudentBreakdown> <stu:Studentdata> <s...
[ "If I add <stu:StudentBreakdown xmlns:stu= \"stu\" xmlns:st=\"st\"> to your XML root element, I get with:\nimport pandas as pd\nimport xml.etree.ElementTree as ET\n\ntree = ET.parse('ns.xml')\nroot= tree.getroot()\n\ncolumns= [\"TAG\", \"VALUE\"]\ndata = []\nfor stud in root.iter():\n if \"\\n\" not in stud.text...
[ 1 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0074608564_elementtree_python_xml.txt
Q: how do i make tkinter update I have an entry field that stores my list to a text file when i press the button to store the info, it gets stored but i have to restart the app to see it on the options menu How do i make the app update without having to restart it? ` from tkinter import * from tkinter import messageb...
how do i make tkinter update
I have an entry field that stores my list to a text file when i press the button to store the info, it gets stored but i have to restart the app to see it on the options menu How do i make the app update without having to restart it? ` from tkinter import * from tkinter import messagebox root = Tk() root.title("test t...
[ "You should re-read and update your list after you put input and added line. You should avoid using my_list = open(\"Characters.txt\") as you may forget to close it. Or sometimes it gives an error and stay unclosed which you cannot perform anything over it.\nfrom tkinter import *\nfrom tkinter import messagebox\n\n...
[ 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074610777_python_tkinter.txt
Q: Taking mean of all rows in a numpy matrix grouped by values based on another numpy matrix I have a matrix A of size NXN with float values and another boolean matrix B of size NXN For every row, I need to find the mean of all values in A belonging to indices where True is the corresponding value for that index in m...
Taking mean of all rows in a numpy matrix grouped by values based on another numpy matrix
I have a matrix A of size NXN with float values and another boolean matrix B of size NXN For every row, I need to find the mean of all values in A belonging to indices where True is the corresponding value for that index in matrix B Similarly, I need to find the mean of all values in A belonging to indices where False ...
[ "The mean issue can be resolved by computing a mask:\nmask_norm = tf.reduce_sum(tf.clip_by_value(true_mat, 0., 1.),axis=0)\ntrue_mean = tf.math.divide(tf.reduce_sum(true_mat, axis=1), mask_norm)\n#true_mean : [1.5, 6. , 8. ]\n\nYou can find the count using tf.reduce_sum(tf.where(true_mean < false_mean, 1, 0))\n", ...
[ 1, 1, 1 ]
[]
[]
[ "arrays", "numpy", "python", "pytorch", "tensorflow" ]
stackoverflow_0074610101_arrays_numpy_python_pytorch_tensorflow.txt
Q: Python dataframe to list/dict I have a sample dataframe as below I want this dataframe converted to this below format in python so I can pass it into dtype { 'FirstName':'string', 'LastName':'string', 'Department':'integer', 'EmployeeID':'string', } Could anyone please let me know how this can be done. To note ...
Python dataframe to list/dict
I have a sample dataframe as below I want this dataframe converted to this below format in python so I can pass it into dtype { 'FirstName':'string', 'LastName':'string', 'Department':'integer', 'EmployeeID':'string', } Could anyone please let me know how this can be done. To note above: I need the exact string {'Fi...
[ "dict/zip the two series:\nimport pandas as pd\n\ndata = pd.DataFrame({\n 'Column_Name': ['FirstName', 'LastName', 'Department', 'EmployeeID'],\n 'Datatype': ['string', 'string', 'integer', 'string'],\n})\n\nmapping = dict(zip(data['Column_Name'], data['Datatype']))\n\nprint(mapping)\n\nprints out\n{'FirstNam...
[ 2, 1, 0 ]
[]
[]
[ "dataframe", "dtype", "json", "list", "python" ]
stackoverflow_0074610486_dataframe_dtype_json_list_python.txt
Q: How to combine two jointplots with different colors I want two jointplots to be plotted together, not on different figures. How can I do that? I tried sns.jointplot(column_headers[4],column_headers[6],data=df,color="blue") sns.jointplot(column_headers[4],column_headers[6],data=typesatt[0],color="red") It gave me ...
How to combine two jointplots with different colors
I want two jointplots to be plotted together, not on different figures. How can I do that? I tried sns.jointplot(column_headers[4],column_headers[6],data=df,color="blue") sns.jointplot(column_headers[4],column_headers[6],data=typesatt[0],color="red") It gave me two different figures
[ "You'll need to merge your dataframes, adding a hue column. Here is an example starting from some test data. Note that when using multiple distributions, in order to make the plot more readable, seaborn automatically changes the marginal plots from histograms to kdeplots.\nimport matplotlib.pyplot as plt\nimport se...
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "python", "seaborn" ]
stackoverflow_0074609337_matplotlib_pandas_python_seaborn.txt
Q: Append new column to a Snowpark DataFrame with simple string I've started using python Snowpark and no doubt missing obvious answers based on being unfamiliar to the syntax and documentation. I would like to do a very simple operation: append a new column to an existing Snowpark DataFrame and assign with a simple ...
Append new column to a Snowpark DataFrame with simple string
I've started using python Snowpark and no doubt missing obvious answers based on being unfamiliar to the syntax and documentation. I would like to do a very simple operation: append a new column to an existing Snowpark DataFrame and assign with a simple string. Any pointers to the documentation to what I presume is rea...
[ "You can do this by using the function with_column in combination with the lit function. The with_column function needs a Column expression and for a literal value this can be made with the lit function. see documentation here: https://docs.snowflake.com/en/developer-guide/snowpark/reference/python/api/snowflake.sn...
[ 0 ]
[]
[]
[ "dataframe", "python", "snowpark" ]
stackoverflow_0074562541_dataframe_python_snowpark.txt
Q: Algorithm to calculate number of child per each parent from excel file I have an excel file containing 2 columns & 763 row, screenshot : parent-child file Those strange strings is just a code for a mobile sites. As a description, this file has in both columns a mobile sites names, and as you know, mobile sites for...
Algorithm to calculate number of child per each parent from excel file
I have an excel file containing 2 columns & 763 row, screenshot : parent-child file Those strange strings is just a code for a mobile sites. As a description, this file has in both columns a mobile sites names, and as you know, mobile sites forward mobile traffic to each other, so the parent site forward traffic to the...
[ "You want to build a graph.\nYou can combine pandas and networkx for this:\nimport pandas as pd\nimport networkx as nx\n\nG = nx.from_pandas_edgelist(pd.read_excel('CHILD--PARENT.xlsx'),\n source='Parent', target='Child',\n create_using=nx.DiGraph)\n\nThen fetch...
[ 1 ]
[]
[]
[ "algorithm", "data_structures", "dataframe", "excel_formula", "python" ]
stackoverflow_0074610928_algorithm_data_structures_dataframe_excel_formula_python.txt
Q: Ipywidgets FileUpload widget is not working with JupyterLab web app inside Docker This is my first question on Stackoverflow. I am using JupyterLab with Ipywidgets for a while now and wanted to put my work into a Docker container to share it. Unfortunately, I ran into an issue with the FileUpload widget from Ipywi...
Ipywidgets FileUpload widget is not working with JupyterLab web app inside Docker
This is my first question on Stackoverflow. I am using JupyterLab with Ipywidgets for a while now and wanted to put my work into a Docker container to share it. Unfortunately, I ran into an issue with the FileUpload widget from Ipywidgets which worked perfectly fine when JupyterLab was ran locally. With JupyterLab insi...
[ "The FileUpload widget from Ipywidgets is a widget that allows users to upload files from their local file system to the JupyterLab web application. It works by sending an HTTP request to the JupyterLab server, which then reads the file and sends it back to the widget.\nIn order to make the FileUpload widget work w...
[ 1 ]
[]
[]
[ "docker", "ipywidgets", "jupyter_lab", "python" ]
stackoverflow_0074463062_docker_ipywidgets_jupyter_lab_python.txt
Q: Adding to Random Index I'm trying to add some value at random indexes in a PIL image. I could do that by #find random row and column indices idx_r=random.choices(np.arange(cat[:,0,0].shape[0]), k=int((cat.shape[0]*0.25))) idx_c=random.choices(np.arange(cat[0,:,0].shape[0]), k=int((cat.shape[1]*0.25))) ...
Adding to Random Index
I'm trying to add some value at random indexes in a PIL image. I could do that by #find random row and column indices idx_r=random.choices(np.arange(cat[:,0,0].shape[0]), k=int((cat.shape[0]*0.25))) idx_c=random.choices(np.arange(cat[0,:,0].shape[0]), k=int((cat.shape[1]*0.25))) #add at those indices ...
[ "Firstly, you don't really \"find random row and column indices\". What you are doing is generating an array of size k with random elements of cat[:,0,0], not with their indices.\nGenerating a random arry of indices would be done as follow:\nidx_r=random.choices(np.arange(cat[:,0,0].shape[0]), k=int((cat.shape[0]*0...
[ 0 ]
[]
[]
[ "arrays", "python", "pytorch" ]
stackoverflow_0074610802_arrays_python_pytorch.txt
Q: Trying a Password Validation Program in Python (pls help me) My code was supposed to check two passwords check the length of the passwords check the first and last letters of the passwords and check the uppercase and lowercase of the passwords pass1 = "secret" pass2 = "choccie" InputPassword = input("Write the ...
Trying a Password Validation Program in Python (pls help me)
My code was supposed to check two passwords check the length of the passwords check the first and last letters of the passwords and check the uppercase and lowercase of the passwords pass1 = "secret" pass2 = "choccie" InputPassword = input("Write the password: ") error = "Wrong password input" def PasswordChecker(p...
[ "I corrected your code:\nYou had several errors in your code, like using the bitwise and, not correctly calling the function and some conditionals that I did not understnd what they did.\nWhat I undeartand you want to do is have a list of allowed password, and grant access if the input password matches one of those...
[ 0, 0 ]
[]
[]
[ "password_checker", "passwords", "python" ]
stackoverflow_0074610875_password_checker_passwords_python.txt
Q: Vue3 frontend, Django back end. Key error for validated data in serializer I have a Vue front end that collects data (and files) from a user and POST it to a Django Rest Framework end point using Axios. Here is the code for that function: import { ref } from "vue"; import axios from "axios"; const fields = ref({ ...
Vue3 frontend, Django back end. Key error for validated data in serializer
I have a Vue front end that collects data (and files) from a user and POST it to a Django Rest Framework end point using Axios. Here is the code for that function: import { ref } from "vue"; import axios from "axios"; const fields = ref({ audience: "", cancomment: "", category: "", body: "", errors...
[ "So, after a few hours of research I was able to find my own solution. The method used to read multiple files, was taken from this answer. By breaking the [object FileList] into separate files and appending them to the FormData. The models are based on this answer\nOn the backend, overriding the create method of th...
[ 0, 0 ]
[]
[]
[ "axios", "django", "django_rest_framework", "python", "vue.js" ]
stackoverflow_0074580505_axios_django_django_rest_framework_python_vue.js.txt
Q: Odoo - Show list of users that belongs to a group I want to get in a field all the users that belongs to a group. I tried this but is not working managers = fields.Many2many('res.users', string="Managers in group", default=lambda self: self.env['res.users'].search([('id','in','module.group_pos_manager')])) Im get...
Odoo - Show list of users that belongs to a group
I want to get in a field all the users that belongs to a group. I tried this but is not working managers = fields.Many2many('res.users', string="Managers in group", default=lambda self: self.env['res.users'].search([('id','in','module.group_pos_manager')])) Im getting this error The above exception was the direct caus...
[ "There are two cases when using in or not in operators, the value (right) can be a list or a boolean (The boolean case is an abuse and handled for backward compatibility)\nYou can use self.env.ref to get the list of users that belongs to a group using the group's external identifier\nExample:\ndefault=lambda self: ...
[ 1 ]
[]
[]
[ "odoo", "odoo_15", "python" ]
stackoverflow_0074603962_odoo_odoo_15_python.txt
Q: Best way to flatten a list of dicts that contains a nested list of dicts? I have a list of dicts in which one of the dict values is also a list of dicts. I want to flatten it into a list of dicts. I have some working code and would like opinions on whether ot not there is a more idiomatic way of achieving this. He...
Best way to flatten a list of dicts that contains a nested list of dicts?
I have a list of dicts in which one of the dict values is also a list of dicts. I want to flatten it into a list of dicts. I have some working code and would like opinions on whether ot not there is a more idiomatic way of achieving this. Here is my code: from pprint import pprint transactions = [ { "Custo...
[ "I would use a list comprehension.\n[{'Customer': d['Customer'], \n 'Store': d['Store'], \n 'Basket': d['Basket'], \n **d2} \n for d in transactions \n for d2 in d['items']]\n# [{'Customer': 'Leia', 'Store': 'Hammersmith', 'Basket': 'basket1', \n# 'Product': 'Cheddar', 'Quantity': 2, 'GrossSpend': 2.5}, \...
[ 2, 1 ]
[ "If you just want to flatten the list it can be done with this simple code:\nouput = []\n\nfor transaction in transactions:\n output = [*output, *transaction]\n\n\nThe * operator in python returns the values of an iterator as in iterator with in braces/brackets. It is equivalent to the ...(spread) operator in jav...
[ -2 ]
[ "python" ]
stackoverflow_0074610778_python.txt
Q: How to append dictionary from one column to anther column in pandas I have a dataframe like below: df = pd.DataFrame({'id' : [1,2,3], 'attributes' : [{'dd' : True, 'budget' : '35k'}, {'dd' : True, 'budget' : '25k'}, {'dd' : True, 'budget' : '40k'}], 'prod.attributes' : [{'img' :...
How to append dictionary from one column to anther column in pandas
I have a dataframe like below: df = pd.DataFrame({'id' : [1,2,3], 'attributes' : [{'dd' : True, 'budget' : '35k'}, {'dd' : True, 'budget' : '25k'}, {'dd' : True, 'budget' : '40k'}], 'prod.attributes' : [{'img' : 'img1.url', 'name' : 'millennials'}, {'img' : 'img2.url', 'name' : 'sing...
[ "More efficient than apply, use a loop and update the dictionaries in place:\nfor d1, d2 in zip(df['attributes'], df['prod.attributes']):\n d1['prod'] = d2\n\nIf you want to remove the original column use pop:\nfor d1, d2 in zip(df['attributes'], df.pop('prod.attributes')):\n d1['prod'] = d2\n\nUpdated datafr...
[ 2, 1 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074611165_dictionary_pandas_python.txt
Q: How to connect to SFTP through Paramiko with SSH key - Pageant I am trying to connect to an SFTP through Paramiko with a passphrase protected SSH key. I have loaded the key into Pageant (which I understand is supported by Paramiko) but I can't get it to decrypt my private key. I have found this example here that r...
How to connect to SFTP through Paramiko with SSH key - Pageant
I am trying to connect to an SFTP through Paramiko with a passphrase protected SSH key. I have loaded the key into Pageant (which I understand is supported by Paramiko) but I can't get it to decrypt my private key. I have found this example here that references allow_agent=True but this does not appear to be a paramete...
[ "You have to provide a passphrase, when loading an encrypted key using the RSAKey.from_private_key_file.\nThough note that you do not have to load the key at all, when using the Pageant. That's the point of using an authentication agent. But only the SSHClient class supports the Pageant. The Transport class does no...
[ 9, 0 ]
[]
[]
[ "pageant", "paramiko", "private_key", "python", "ssh" ]
stackoverflow_0025399635_pageant_paramiko_private_key_python_ssh.txt
Q: How to connect broken lines in binary image using OpenCV/Python I have images like the following one and the lines are broken. I have tried to connect them using morphological operations but it's not effective. I've also thought of calculating orientation but since lines are parallel I can not do this. Is there a...
How to connect broken lines in binary image using OpenCV/Python
I have images like the following one and the lines are broken. I have tried to connect them using morphological operations but it's not effective. I've also thought of calculating orientation but since lines are parallel I can not do this. Is there a way that I can dilate in certain orientation in Python? Or any other...
[ "You did not make it entirely clear what result exactly you are after (or what your problem with the morpholocial op's was, exactly), but i had a shot at it.\n\nConnecting all the \"lines\" into a single object with a morpholical operation. I used a circular kernel here, which i think gives decent results. No rotat...
[ 0 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074606038_image_processing_opencv_python.txt
Q: why I am getting this error:"Received bad response from Model Management Service:\nResponse Code: 403\" while trying to de This is my code which I am trying to deploy my model on Azure AML: aciconfig = AciWebservice.deploy_configuration( cpu_cores=1, memory_gb=1, tags={"data":"n...
why I am getting this error:"Received bad response from Model Management Service:\nResponse Code: 403\" while trying to de
This is my code which I am trying to deploy my model on Azure AML: aciconfig = AciWebservice.deploy_configuration( cpu_cores=1, memory_gb=1, tags={"data":"nlp classifier"}, description='nlp cLASSIFICATION MODEL' ) inference_config = InferenceConfig(entry_scr...
[ "\nI tried to reproduce the issue and it worked for me.\n\naciconfig = AciWebservice.deploy_configuration(\ncpu_cores=1,\nmemory_gb=1,\ntags={\"data\":\"nlp classifier\"},\ndescription='nlp cLASSIFICATION MODEL'\n)\ninference_config = InferenceConfig(entry_script=\"scoringscript.py\", environment=myenv)\nservice =...
[ 0 ]
[]
[]
[ "azure_machine_learning_studio", "azure_machine_learning_workbench", "python" ]
stackoverflow_0074577329_azure_machine_learning_studio_azure_machine_learning_workbench_python.txt
Q: move files to subdirectories that are named on part of the filenames I have a few data files in a directory, and I want to move them to the subdirectories based on their filenames. Let's say we created the first directory named "20220322_170444," and it should contain the first four files only because in the next ...
move files to subdirectories that are named on part of the filenames
I have a few data files in a directory, and I want to move them to the subdirectories based on their filenames. Let's say we created the first directory named "20220322_170444," and it should contain the first four files only because in the next file the "el" is less than the previous one, so the second folder, let's s...
[ "Some string splitting can do this for you.\nimport shutil\nimport os\n\n\nfiles = [\n \"cfrad.20220322_170444.122_COW1_v2_s02_el3.40_SUR.nc\",\n \"cfrad.20220322_170456.550_COW1_v2_s03_el4.22_SUR.nc\",\n \"cfrad.20220322_170508.975_COW1_v2_s04_el5.09_SUR.nc\",\n \"cfrad.20220322_170521.397_COW1_v2_s05_...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074610266_python.txt
Q: Why is the custom layer decomposed into several operations in Keras? I want to get the weights of my custom layer, but I couldn't get them by model.layer().get_weights()[X]. So I checked the layers of the model, it seems that the custom layer is decomposed into several operations and no weights can be found in the...
Why is the custom layer decomposed into several operations in Keras?
I want to get the weights of my custom layer, but I couldn't get them by model.layer().get_weights()[X]. So I checked the layers of the model, it seems that the custom layer is decomposed into several operations and no weights can be found in these layers. Here is the custom layer code class PixelBaseConv(Layer): ...
[ "I found why this problem occurred.\nI wrote the custom layer by\nimport tensorflow.python.keras \n\nwhile using other keras layers and creating the model by\nimport tensorflow.keras\n\nI think these two libraries may not be compatible, so my custom layer was splitted into several operation layers. Thus, weights ca...
[ 0 ]
[]
[]
[ "deep_learning", "keras", "keras_layer", "python", "tensorflow" ]
stackoverflow_0074488122_deep_learning_keras_keras_layer_python_tensorflow.txt
Q: N queens placed in k*k chessboard? My problem should be a variant of N queens problem: Is there an algorithm to print all ways to place N queens in a k*k chessboard? I have tried to modify the DFS method used in the N-queens problem like the following but soon realized that I could only search the first "queen_num...
N queens placed in k*k chessboard?
My problem should be a variant of N queens problem: Is there an algorithm to print all ways to place N queens in a k*k chessboard? I have tried to modify the DFS method used in the N-queens problem like the following but soon realized that I could only search the first "queen_number" of rows in the chessboard. def ...
[ "Here's a solution based on the Python port of Niklaus Wirth's n-queen solver from https://en.wikipedia.org/wiki/Eight_queens_puzzle\ndef queens(n, k, i=0, a=[], b=[], c=[]):\n if k == 0:\n yield a + [None] * (n - len(a))\n return\n for j in range(n):\n if j not in a and i+j not in b and ...
[ 2, 0 ]
[]
[]
[ "algorithm", "n_queens", "python" ]
stackoverflow_0074608957_algorithm_n_queens_python.txt
Q: Cannot import module that imports a custom class I have a directory design that looks like this: MyProject --- - script.py | - helpers --- - __init__.py | - class_container.py | ...
Cannot import module that imports a custom class
I have a directory design that looks like this: MyProject --- - script.py | - helpers --- - __init__.py | - class_container.py | - helper.py class_container.py has a class called MyC...
[ "You have to create a __init__.py file in the MyProject/helpers directory. Maybe you already have created it. If not, create an empty file.\nThen in the MyProject/helpers/helper.py, access the module helpers.class_container like this.\nfrom helpers.class_container import MyClass\ndef func():\n # some code using M...
[ 0 ]
[]
[]
[ "import", "module", "path", "python", "scope" ]
stackoverflow_0074607575_import_module_path_python_scope.txt
Q: I keep getting 'None' when getting enviroment variables I'm trying to keep my token in an enviroment variable, so I created the file .env, and I stored the TOKEN there: TOKEN=XXX When I run my .py file, I can't get the enviroment variable TOKEN, it keeps printing 'None'. import os token = os.environ.get("TOK...
I keep getting 'None' when getting enviroment variables
I'm trying to keep my token in an enviroment variable, so I created the file .env, and I stored the TOKEN there: TOKEN=XXX When I run my .py file, I can't get the enviroment variable TOKEN, it keeps printing 'None'. import os token = os.environ.get("TOKEN") print(token)
[ "What you are trying to do is use a dotenv variable directly using os.environ.\nIn order to use variables from .env, you need the dotenv library.\nInstall dotenv library:\npip install dotenv\n\nThen import dotenv like this.\nfrom dotenv import load_dotenv\nload_dotenv() # this will load variables from .env.\n\n", ...
[ 2, 0 ]
[]
[]
[ "discord.py", "environment_variables", "python" ]
stackoverflow_0068164516_discord.py_environment_variables_python.txt
Q: Where does Kubeflow pipeline look for packages in `packages_to_install`? I am using Kubeflow Pipelines in Vertex AI to create my ML pipeline and has beeen able to use standard packaged in Kubeflow component using the below syntax @component( # this component builds an xgboost classifier with xgboost packages...
Where does Kubeflow pipeline look for packages in `packages_to_install`?
I am using Kubeflow Pipelines in Vertex AI to create my ML pipeline and has beeen able to use standard packaged in Kubeflow component using the below syntax @component( # this component builds an xgboost classifier with xgboost packages_to_install=["google-cloud-bigquery", "xgboost", "pandas", "sklearn", "joblib"...
[ "Under the hood, the step will install the package at the runtime when executing the component. This requires a package to be hosted in a location that can be accessed by the runtime environment later.\nGiven that, you need to upload the package to a location that can be accessed later, e.g. git repository as Jose ...
[ 1, 1, 0 ]
[]
[]
[ "google_cloud_vertex_ai", "kubeflow", "kubeflow_pipelines", "python" ]
stackoverflow_0072716087_google_cloud_vertex_ai_kubeflow_kubeflow_pipelines_python.txt
Q: ModuleNotFoundError: No module named 'paho' I am trying to make connection with my raspberry Pi and my PC windows through MQTT protocol. And I have a problem I cant solve on my PC - I can t import library that I have installed to my program: import paho.mqtt.client as mqtt Results in the error ModuleNotFoundError:...
ModuleNotFoundError: No module named 'paho'
I am trying to make connection with my raspberry Pi and my PC windows through MQTT protocol. And I have a problem I cant solve on my PC - I can t import library that I have installed to my program: import paho.mqtt.client as mqtt Results in the error ModuleNotFoundError: No module named 'paho' The topic was already iss...
[ "pip install paho-mqtt\n\nhttps://pypi.org/project/paho-mqtt/\nI solved my error by using this command\n" ]
[ 0 ]
[]
[]
[ "import", "libraries", "mqtt", "pip", "python" ]
stackoverflow_0071565510_import_libraries_mqtt_pip_python.txt
Q: IPython Notebook: how to display() multiple objects without newline Currently when I use display() function in the IPython notebook I get newlines inserted between objects: >>> display('first line', 'second line') first line second line But I would like the print() function's behaviour where everything is kept ...
IPython Notebook: how to display() multiple objects without newline
Currently when I use display() function in the IPython notebook I get newlines inserted between objects: >>> display('first line', 'second line') first line second line But I would like the print() function's behaviour where everything is kept on the same line, e.g.: >>> print("all on", "one line") all on one line ...
[ "No, display cannot prevent newlines, in part because there are no newlines to prevent. Each displayed object gets its own div to sit in, and these are arranged vertically. You might be able to adjust this by futzing with CSS, but I wouldn't recommend that.\nThe only way you could really get two objects to display...
[ 9, 0 ]
[]
[]
[ "ipython", "jupyter_notebook", "python" ]
stackoverflow_0017439176_ipython_jupyter_notebook_python.txt
Q: Django UUID Field does not autocreate with new entry I just added a new model where I want to use a UUID for the first time. I run Django 3.1.3 on python 3.8.10. Found some questions about this and I am quite certain I did it according to those suggestions. However, when I add an entry to that model (in phpmyadmin...
Django UUID Field does not autocreate with new entry
I just added a new model where I want to use a UUID for the first time. I run Django 3.1.3 on python 3.8.10. Found some questions about this and I am quite certain I did it according to those suggestions. However, when I add an entry to that model (in phpmyadmin web-surface) the UUID is not being added, it just stays e...
[ "The default = uuid.uuid4 is a Django ORM default, it's not something the database will do for you like the auto incrementing for ID. So if you add an entry via the phpmyadmin, it will not set the uuid field.\n", "You will be needing to make migration like this in order to populate the fields for existing entries...
[ 1, 0, 0 ]
[ "change default = uuid.uuid4 to default = uuid.uuid4()\n" ]
[ -2 ]
[ "django", "python" ]
stackoverflow_0072270982_django_python.txt
Q: tkinter button color won't change (non-click event) I created a program to move a knight around a chess board touching every square without touching the same one twice, starting from a random location. I am attempting to show this action using tkinter by changing the color of the square (which is a button) to red ...
tkinter button color won't change (non-click event)
I created a program to move a knight around a chess board touching every square without touching the same one twice, starting from a random location. I am attempting to show this action using tkinter by changing the color of the square (which is a button) to red as the knight moves. The Chess Board is made of tkinter b...
[ "You are just complicated everything. Create a cell class and keep information of x,y and iftouched in it. This way you can add new capabilities into cells easily.\nCreate a board and make an array inside it. Create cell instances and place into that array.\nYou should do inside this board whatever you do. Define ...
[ 0 ]
[]
[]
[ "python", "tkinter", "tkinter_button" ]
stackoverflow_0074602264_python_tkinter_tkinter_button.txt
Q: How can I specify which try block to continue from? I have the following code while True: try: height_input=input(f"Please enter your height in meters : ") height=float(height_input) # weight_input=input(f"P...
How can I specify which try block to continue from?
I have the following code while True: try: height_input=input(f"Please enter your height in meters : ") height=float(height_input) # weight_input=input(f"Please enter your weight in kilograms") ...
[ "Firstly, your exception handling syntax is wrong. You want the following.\ntry:\n height_input = input(f\"Please enter your height in meters : \")\n height = float(height_input)\nexcept ValueError:\n print(\"Invalid Input. Please Try Again\")\n continue\n\nSecondly, continue is just going to the next loop iter...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074611138_python.txt
Q: Get data from an API with Flask I have a simple flask app, which is intended to make a request to an api and return data. Unfortunately, I can't share the details, so you can reproduce the error. The app looks like that: from flask import Flask import requests import json from requests.auth import HTTPBasicAuth a...
Get data from an API with Flask
I have a simple flask app, which is intended to make a request to an api and return data. Unfortunately, I can't share the details, so you can reproduce the error. The app looks like that: from flask import Flask import requests import json from requests.auth import HTTPBasicAuth app = Flask(__name__) @app.route("/")...
[ "flask app return format json. If you return req.content, it will break function. You must parse response request to json before return it.\nfrom flask import jsonify \nreturn jsonify(req.json())\n\nIt's better with safe load response when the request fail\nreq = requests.get()\nif req.status_code !=200:\n return...
[ 0 ]
[]
[]
[ "flask", "python", "python_requests" ]
stackoverflow_0074610450_flask_python_python_requests.txt
Q: Python list subtraction operation I want something like this: >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] >>> y = [1, 3, 5, 7, 9] >>> y - x # should return [2,4,6,8,0] A: Use a list comprehension: [item for item in x if item not in y] If you want to use the - infix syntax, you can just do: class MyList(list): ...
Python list subtraction operation
I want something like this: >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] >>> y = [1, 3, 5, 7, 9] >>> y - x # should return [2,4,6,8,0]
[ "Use a list comprehension:\n[item for item in x if item not in y]\n\nIf you want to use the - infix syntax, you can just do:\nclass MyList(list):\n def __init__(self, *args):\n super(MyList, self).__init__(args)\n\n def __sub__(self, other):\n return self.__class__(*[item for item in self if ite...
[ 456, 362, 45, 42, 25, 14, 10, 10, 9, 6, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003428536_list_python.txt
Q: How to paginate the filtered results in django views.py def do_paginator(get_records_by_date,request): page = request.GET.get('page', 1) paginator = Paginator(get_records_by_date, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except Emp...
How to paginate the filtered results in django
views.py def do_paginator(get_records_by_date,request): page = request.GET.get('page', 1) paginator = Paginator(get_records_by_date, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num...
[ "You don't need the if else block, you can simply do as it is documented here.\n page = request.GET.get('page')\n paginator = Paginator(get_records_by_date, 5)\n users = paginator.get_page(page)\n return users\n\nThe django method already deals with input verification in the page GET, so you don't need ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074611243_django_python.txt
Q: Convert into 1D list from multidimensional and multi type array I am doing my first project in NLP and and have encoded features of audio files (400 in length) using towhee. In the output, each row is encoding of each audio file. The output is as shown below: 0 [([[[-0.5464456 -0.27430105 -0.7668772 ... .....
Convert into 1D list from multidimensional and multi type array
I am doing my first project in NLP and and have encoded features of audio files (400 in length) using towhee. In the output, each row is encoding of each audio file. The output is as shown below: 0 [([[[-0.5464456 -0.27430105 -0.7668772 ... ... 1 [([[[ 2.4055429 1.6134734 0.87733674 ... ... 2 [([...
[ "Actually this was a simple problem to solve using numpy library. I had to convert all using numpy.array() funtion. Numpy takes care of all the different types and converts them into numpy array.\nm = numpy.array(row[3])\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "list", "nlp", "numpy", "python" ]
stackoverflow_0074588807_arrays_list_nlp_numpy_python.txt
Q: Pandas: How to custom-sort on multiple columns? I have a pandas dataframe with data like: +-----------+-----------------+---------+ | JOB-NAME | Status | SLA | +-----------+-----------------+---------+ | job_1 | YET_TO_START | --- | | job_3 | COMPLETED | MET | | job_4 | R...
Pandas: How to custom-sort on multiple columns?
I have a pandas dataframe with data like: +-----------+-----------------+---------+ | JOB-NAME | Status | SLA | +-----------+-----------------+---------+ | job_1 | YET_TO_START | --- | | job_3 | COMPLETED | MET | | job_4 | RUNNING | MET | | job_2 | YET_TO_START...
[ "You can extend dictionary by values from another columns, only necessary different keys in both columns for correct working like mentioned mozway in comments:\nsort_order_dict = {\"FAILED\":0, \"YET_TO_START\":1, \"RUNNING\":2, \"COMPLETED\":3,\n \"LATE\":4, \"---\":5, \"NOT_MET\":6, \"MET\":7}\n...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074611496_pandas_python.txt
Q: Enable pyenv-virtualenv prompt at terminal I just installed pyenv and virtualenv following: https://realpython.com/intro-to-pyenv/ After completing installation I was prompted with: pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simula...
Enable pyenv-virtualenv prompt at terminal
I just installed pyenv and virtualenv following: https://realpython.com/intro-to-pyenv/ After completing installation I was prompted with: pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior I added export PYENV_VIRTUALENV...
[ "Borrowing a solution from here, the following works (added to .bashrc or .bash_aliases):\nexport PYENV_VIRTUALENV_DISABLE_PROMPT=1\nexport BASE_PROMPT=$PS1\nfunction updatePrompt {\n if [[ \"$(pyenv virtualenvs)\" == *\"* $(pyenv version-name) \"* ]]; then\n export PS1='($(pyenv version-name)) '$BASE_PRO...
[ 1 ]
[]
[]
[ "pyenv", "pyenv_virtualenv", "python", "virtualenv" ]
stackoverflow_0074611317_pyenv_pyenv_virtualenv_python_virtualenv.txt
Q: How to override a method in python of an object and call super? I have an Object of the following class which inherates from the algorithm class. class AP(Algorithm): def evaluate(self, u): return self.stuff *2 +u The Algorithm class has a method called StoppingCritiria. At some point in the p...
How to override a method in python of an object and call super?
I have an Object of the following class which inherates from the algorithm class. class AP(Algorithm): def evaluate(self, u): return self.stuff *2 +u The Algorithm class has a method called StoppingCritiria. At some point in the project the object objAP = AP() gets created. Later on I can then actu...
[ "See Override a method at instance level for many possible solutions. None of them will really work with super though, since you're simply not defining the replacement function in a class. You can define it slightly differently though for it to work:\nclass Foo:\n def bar(self):\n print('bar')\n\nf = Foo(...
[ 2 ]
[]
[]
[ "inheritance", "python", "python_3.x", "python_class" ]
stackoverflow_0074611413_inheritance_python_python_3.x_python_class.txt
Q: numpy keeps turning zeroes into very small numbers and "-2147483648" I have this code import numpy a=numpy.pad(numpy.empty([8,8]), 1, constant_values=1) print(a) 50% of the times I execute it it prints a normal array, 50% of times it prints this [[ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+00...
numpy keeps turning zeroes into very small numbers and "-2147483648"
I have this code import numpy a=numpy.pad(numpy.empty([8,8]), 1, constant_values=1) print(a) 50% of the times I execute it it prints a normal array, 50% of times it prints this [[ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 ...
[ "You are using numpy.empty which is an\n\nArray of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.\n\nSee documentation.\nUse either numpy.zeros or numpy.ones to start with a proper initialized array.\n", "The problem lies in the fact that an empty a...
[ 1, 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074611463_arrays_numpy_python.txt
Q: Permutation List with Variable Dependencies- UnboundLocalError I was trying to break down the code to the simplest form before adding more variables and such. I'm stuck. I wanted it so when I use intertools the first response is the permutations of tricks and the second response is dependent on the trick's landin...
Permutation List with Variable Dependencies- UnboundLocalError
I was trying to break down the code to the simplest form before adding more variables and such. I'm stuck. I wanted it so when I use intertools the first response is the permutations of tricks and the second response is dependent on the trick's landings() and is a permutation of the trick's corresponding landing. I wa...
[ "Add a landing = \"\" after def landings(tricks): to get rid of the error.\nBut the if checks in your function are wrong. You check if tricks, which is a list, is equal to backflip, etc. which are all strings. So thats why none of the ifs are true and landing got no value assigned.\nThat question was also about per...
[ 0 ]
[]
[]
[ "error_handling", "function", "permutation", "python" ]
stackoverflow_0074611395_error_handling_function_permutation_python.txt
Q: Filtering one column based on values in two other columns I've got an upper boundary and a lower boundary based on a predicted value and I want to filter out the data that do not fall between the upper and lower boundaries. My data frame looks like this weight KG Upper Boundary Lower Boundary 23.2 30 20 55.2 40...
Filtering one column based on values in two other columns
I've got an upper boundary and a lower boundary based on a predicted value and I want to filter out the data that do not fall between the upper and lower boundaries. My data frame looks like this weight KG Upper Boundary Lower Boundary 23.2 30 20 55.2 40 30 44.2 50 40 47.8 50 40 38.7 30 20 and I'd l...
[ "Your code works just fine. If it doesn't do the job. It might have the version and platform related thing.\nMy environment is following:\n\nMacbook M1 chip, Ventura\nPython 3.9.14\nPandas 1.5.2\n\nCode is following:\nimport pandas as pd\n\n# Build DataFrame\nnames = [\"weight_KG\", \"UpperBoundary\", \"LowerBounda...
[ 1 ]
[]
[]
[ "filtering", "python" ]
stackoverflow_0074605358_filtering_python.txt
Q: Tensorflow Multi Head Attention on Inputs: 4 x 5 x 20 x 64 with attention_axes=2 throwing mask dimension error (tf 2.11.0) The expectation here is that the attention is applied on the 2nd dimension (4, 5, 20, 64). I am trying to apply self attention using the following code (issue reproducible with this code): imp...
Tensorflow Multi Head Attention on Inputs: 4 x 5 x 20 x 64 with attention_axes=2 throwing mask dimension error (tf 2.11.0)
The expectation here is that the attention is applied on the 2nd dimension (4, 5, 20, 64). I am trying to apply self attention using the following code (issue reproducible with this code): import numpy as np import tensorflow as tf from keras import layers as tfl class Encoder(tfl.Layer): def __init__(self,): ...
[ "Just concat the input along axis=0\nimport numpy as np\nimport tensorflow as tf\nfrom keras import layers as tfl\n\nclass Encoder(tfl.Layer):\n def __init__(self,):\n super().__init__()\n self.embed_layer = tfl.Embedding(4500, 64, mask_zero=True)\n self.attn_layer = tfl.MultiHeadAttention(n...
[ 1 ]
[]
[]
[ "attention_model", "python", "python_3.x", "self_attention", "tensorflow" ]
stackoverflow_0074610068_attention_model_python_python_3.x_self_attention_tensorflow.txt
Q: Create a pdf from an image list I am developing a program in python to produce raffle tickets. The program creates as many tickets as required from a reference image by modifying only the ticket number. I have a list of images with potentially several hundred items. I would like to resize my images and save them i...
Create a pdf from an image list
I am developing a program in python to produce raffle tickets. The program creates as many tickets as required from a reference image by modifying only the ticket number. I have a list of images with potentially several hundred items. I would like to resize my images and save them in a pdf to allow printing. The user h...
[ "disclaimer: I am the author of borb, the library used in this answer\nYou can simply add the Image to a Document (use absolute positioning), and then add a Paragraph of text (containing the raffle number) at the position you want to have it.\nfrom borb.pdf import Document\nfrom borb.pdf import Page\nfrom borb.pdf...
[ 0 ]
[]
[]
[ "image", "pdf", "python" ]
stackoverflow_0074607775_image_pdf_python.txt
Q: BayesianOptimization search errors out "TypeError: 'float' object is not subscriptable" I am getting the error TypeError: 'float' object is not subscriptable from the following line: tuner_nn.search(x_train, y_train, epochs=50, validation_data=(x_val,y_val ), verbose=0, callbacks=[Earlystopping]) I know there a...
BayesianOptimization search errors out "TypeError: 'float' object is not subscriptable"
I am getting the error TypeError: 'float' object is not subscriptable from the following line: tuner_nn.search(x_train, y_train, epochs=50, validation_data=(x_val,y_val ), verbose=0, callbacks=[Earlystopping]) I know there are a lot of questions with the the same error but still could not find a solution for this is...
[ "I think the proble comes from the following lines\nbesthp_nn = tuner_nn.get_best_hyperparameters()\\[0\\]\n\nand\nbesthp_gru = tuner_gru.get_best_hyperparameters()\\[0\\]\n\nYou might want to try something like\nbesthp_nn = tuner_nn.get_best_hyperparameters(1)[0]\nbesthp_gru = tuner_gru.get_best_hyperparameters(1)...
[ 0, 0 ]
[]
[]
[ "neural_network", "python", "python_3.x" ]
stackoverflow_0074611572_neural_network_python_python_3.x.txt
Q: How to subtract second level columns in multiIndex level dataframe Here is the example data I am working with. What I am trying to accomplish is 1) subtract b column from column a and 2) create the C column in front of a and b columns. I would like to loop through and create the C column for x, y and z. import pan...
How to subtract second level columns in multiIndex level dataframe
Here is the example data I am working with. What I am trying to accomplish is 1) subtract b column from column a and 2) create the C column in front of a and b columns. I would like to loop through and create the C column for x, y and z. import pandas as pd df = pd.DataFrame(data=[[100,200,400,500,111,222], [77,28,110,...
[ "Use DataFrame.xs for select second levels with avoid remove first level with drop_level=False, then use rename for same MultiIndex, subtract and add to original with concat, last use DataFrame.sort_index:\ndfa = df.xs('a', axis=1, level=1, drop_level=False).rename(columns={'a':'c'})\ndfb = df.xs('b', axis=1, level...
[ 2, 2, 1 ]
[]
[]
[ "dataframe", "multi_index", "pandas", "pivot_table", "python" ]
stackoverflow_0074609560_dataframe_multi_index_pandas_pivot_table_python.txt
Q: Replace the symbol in list my_list=['A0_123','BD_SEI','SW_TH'] I need to replace the '_' to '+' . Expected output: my_list=['A0+123','BD+SEI','SW+TH'] Can some one help me? A: As pointed out by @python_user, you can iterate through every element in your list using a list comprehension and using replace(): new_li...
Replace the symbol in list
my_list=['A0_123','BD_SEI','SW_TH'] I need to replace the '_' to '+' . Expected output: my_list=['A0+123','BD+SEI','SW+TH'] Can some one help me?
[ "As pointed out by @python_user, you can iterate through every element in your list using a list comprehension and using replace():\nnew_list = [i.replace('_', '+') for i in my_list]\nReturns your expected output\n['A0+123', 'BD+SEI', 'SW+TH']\n\n" ]
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074611263_list_python.txt
Q: Why do I get a flask weakref error when importing my SQLAlchemy db from a submodule? I currently have a flask project set up as follows (I did make a few modifications here to try and get the smallest working example, so some of this may be changed slightly) from extensions import db def create_api(): # Create ...
Why do I get a flask weakref error when importing my SQLAlchemy db from a submodule?
I currently have a flask project set up as follows (I did make a few modifications here to try and get the smallest working example, so some of this may be changed slightly) from extensions import db def create_api(): # Create API app api = Flask(__name__) # Configure... the configs api.config['SQLALCHEMY_...
[ "I've recently encountered the exact same problem while trying to put my routes into a submodule.\nI can't explain why this happens, but from what I can tell, it has something to do with the Flask-SQLAlchemy version - I've initially tried running version 3.0.2.\nWhat solved the problem for me was a downgrade to ver...
[ 0 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0074366188_flask_flask_sqlalchemy_python_sqlalchemy.txt
Q: Python mmap permission denied on Windows I have the following code that works perfectly: server.py from mmap import mmap from pickle import load, dump mm = mmap(-1, 32, tagname='test') last_request_id = None while True: mm.seek(0) try: request_id = int(load(mm)) if request_id != last_requ...
Python mmap permission denied on Windows
I have the following code that works perfectly: server.py from mmap import mmap from pickle import load, dump mm = mmap(-1, 32, tagname='test') last_request_id = None while True: mm.seek(0) try: request_id = int(load(mm)) if request_id != last_request_id: last_request_id = request...
[ "You need to call the OpenFileMapping() at the client. But currently the Python mmap module calls the CreateFileMapping() to open an existing file mapping object.(You can see that at this.)\nSo you can't do what you want in pure Python. I recommend using other IPC mechanisms provided by multiprocessing module.(The ...
[ 1 ]
[]
[]
[ "local_security_policy", "memory_mapped_files", "python", "windows", "windows_server_2019" ]
stackoverflow_0074607900_local_security_policy_memory_mapped_files_python_windows_windows_server_2019.txt
Q: KEYERROR issues with Flask-Mail I am having trouble with creating a flask server that can send confirmation emails. I get a KEY ERROR even though I have made sure to install both Flask and Flask_Mail through my Terminal Window. This is the code that generates the error: import os import re from flask import Flask...
KEYERROR issues with Flask-Mail
I am having trouble with creating a flask server that can send confirmation emails. I get a KEY ERROR even though I have made sure to install both Flask and Flask_Mail through my Terminal Window. This is the code that generates the error: import os import re from flask import Flask, render_template,request,redirect fr...
[ "Never mind, I somehow got it to work. I think the problem had to do with the environmental variables. What I did was change my code from the one above to this:\napp.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER')\napp.config[\"MAIL_PASSWORD\"] = os.environ.get(\"MAIL_PASSWORD\")\napp.config[\...
[ 0 ]
[]
[]
[ "cs50", "flask", "flask_mail", "html", "python" ]
stackoverflow_0074604904_cs50_flask_flask_mail_html_python.txt
Q: tkinter callback event to retrieve value from Entry and write to text file *First of all, i am trying to create a register system saved into textfile(not real system, i know its not safe to write into textfiles) Created the GUI and then i defined multiple functions which is Menu, register and submit. Submit functi...
tkinter callback event to retrieve value from Entry and write to text file
*First of all, i am trying to create a register system saved into textfile(not real system, i know its not safe to write into textfiles) Created the GUI and then i defined multiple functions which is Menu, register and submit. Submit function is nested and inside register function. The problem is when i nested the func...
[ "I do not understand how you write code. You are using too many duplicates. I will not going to explain to you. In line 51 and 54 , I changed command to None. You can replace it.\nHere is code:\nfrom tkinter import *\n\nstart = Tk()\nstart.geometry(\"800x500\")\nstart.configure(bg=\"lightblue\")\nstart.title(\"Bibl...
[ 0 ]
[]
[]
[ "event_handling", "function", "python", "tkinter", "user_interface" ]
stackoverflow_0074610943_event_handling_function_python_tkinter_user_interface.txt
Q: Cannot import django-smart-selects I wanted to use the django smart select library to create related dropdowns. I did everything as indicated in the library documentation, but an error occurs: import "smart_selects.db_fields" could not be resolved Pylance(reportMissingImports) [Ln2, Col6] Even when I enter "impo...
Cannot import django-smart-selects
I wanted to use the django smart select library to create related dropdowns. I did everything as indicated in the library documentation, but an error occurs: import "smart_selects.db_fields" could not be resolved Pylance(reportMissingImports) [Ln2, Col6] Even when I enter "import ..." the library itself already glows...
[ "You can use:\nUSE_DJANGO_JQUERY = True instead of JQUERY_URL = True in your \nsettings.py\n\nPlease reply to this message if the issue still persist.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "django_smart_selects", "dropdown", "python" ]
stackoverflow_0074593363_django_django_forms_django_smart_selects_dropdown_python.txt
Q: how to send email from gmai.com to hotmail.com/yahoo.com with colab, the words and pictures have become unormal I want to send messages from "southrotaryclub@gmail.com" to several emails like gmail or hotmail, yahoo etc. However, when I send this message. the hotmail words have become several html files instead of...
how to send email from gmai.com to hotmail.com/yahoo.com with colab, the words and pictures have become unormal
I want to send messages from "southrotaryclub@gmail.com" to several emails like gmail or hotmail, yahoo etc. However, when I send this message. the hotmail words have become several html files instead of real words. When I read this hotmail from my iphone, the picture of "address.png" became the random numbers. Does an...
[ "Try using SMTP. It is a standard Python packages. And the syntax is pretty easy.\nTutorial link - https://www.youtube.com/watch?v=JRCJ6RtE3xU\n" ]
[ 0 ]
[]
[]
[ "gmail", "hotmail", "html_email", "mimemultipart", "python" ]
stackoverflow_0074611777_gmail_hotmail_html_email_mimemultipart_python.txt
Q: Django Authentication issue after reseting password I am using django 1.8 for my project and I have tried using django.contrib.auth.middleware.SessionAuthenticationMiddleware in middleware to log off the other session after resetting the password. This is fine but the problem I am facing is after resetting it is l...
Django Authentication issue after reseting password
I am using django 1.8 for my project and I have tried using django.contrib.auth.middleware.SessionAuthenticationMiddleware in middleware to log off the other session after resetting the password. This is fine but the problem I am facing is after resetting it is logging off even that session who changed the password. I ...
[ "If you use your own view to change password, django gives you ability to update the session after changing password so that the user isn't logged off.\nFor that you can use update_session_auth_hash function.\nDjango's user_change_password update the session after password change. But for you own custom views, you ...
[ 5, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0036350317_django_python.txt
Q: visualize overlapping communities in graph by any of the python or R modules How can I visualize communities if there are overlapping communities in the graph? I can use any module in python (networkx, igraph, matplotlib, etc.) or R. For example, information on nodes, edges, and the nodes in each community is give...
visualize overlapping communities in graph by any of the python or R modules
How can I visualize communities if there are overlapping communities in the graph? I can use any module in python (networkx, igraph, matplotlib, etc.) or R. For example, information on nodes, edges, and the nodes in each community is given as follows. Note that node G spans two communities. list_nodes = ['A', 'B', 'C',...
[ "Below is an option for igraph within R.\n\nI think you may have to annotate the community info manually (see grp below) and then use it when plotting, e.g.,\ng <- graph_from_data_frame(df, directed = FALSE)\ngrp <- lapply(\n groups(cluster_edge_betweenness(g)),\n function(x) {\n c(\n x,\n names(whic...
[ 3 ]
[]
[]
[ "igraph", "networkx", "python", "r", "visualization" ]
stackoverflow_0074609794_igraph_networkx_python_r_visualization.txt
Q: Regex : replace url inside string i have string = 'Server:xxx-zzzzzzzzz.eeeeeeeeeee.frPIPELININGSIZE' i need a python regex expression to identify xxx-zzzzzzzzz.eeeeeeeeeee.fr to do a sub-string function to it Expected output : string : 'Server:PIPELININGSIZE' the URL is inside a string, i tried a lot of regex e...
Regex : replace url inside string
i have string = 'Server:xxx-zzzzzzzzz.eeeeeeeeeee.frPIPELININGSIZE' i need a python regex expression to identify xxx-zzzzzzzzz.eeeeeeeeeee.fr to do a sub-string function to it Expected output : string : 'Server:PIPELININGSIZE' the URL is inside a string, i tried a lot of regex expressions
[ "No regex. single line use just to split on your target word.\nstring = 'Server:xxx-zzzzzzzzz.eeeeeeeeeee.frPIPELININGSIZE'\n\nlast = string.split(\"fr\",1)[1]\n\nfirst =string[:string.index(\":\")]\nprint(f'{first} : {last}')\n\nGives #\nServer:PIPELININGSIZE\n\n", "Not sure if this helps, because your question ...
[ 0, 0, 0 ]
[]
[]
[ "python", "replace", "string", "url" ]
stackoverflow_0074611048_python_replace_string_url.txt
Q: how to remove item not match in list of object list Here is my list, it's list of object and inside object there is list: please rev [ { "id": 1, "test": [ { "id__": 1 }, { "id__": 1 }, { ...
how to remove item not match in list of object list
Here is my list, it's list of object and inside object there is list: please rev [ { "id": 1, "test": [ { "id__": 1 }, { "id__": 1 }, { "id__": 1 }, { ...
[ "This is probably what you want:\nfiltered_result = []\nfor i in a:\n lst_id = i[\"id\"]\n lst_to_compare = i[\"test\"]\n filtered_inner_list = [item for item in lst_to_compare if item[\"id__\"] == lst_id]\n filtered_result.append({\"id\": lst_id, \"test\": filtered_inner_list})\n\nprint(filtered_result...
[ 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074611555_dictionary_list_python.txt
Q: Column disappearing after .apply - Pandas (Python) I'm new to pandas and I'm trying to merge the following 2 dataframes into 1 : nopat 0 2021-12-31 3.580000e+09 1 2020-12-31 6.250000e+08 2 2019-12-31 -1.367000e+09 3 2018-12-31 2.028000e+09 capital_employed 0 2021-12-31 5...
Column disappearing after .apply - Pandas (Python)
I'm new to pandas and I'm trying to merge the following 2 dataframes into 1 : nopat 0 2021-12-31 3.580000e+09 1 2020-12-31 6.250000e+08 2 2019-12-31 -1.367000e+09 3 2018-12-31 2.028000e+09 capital_employed 0 2021-12-31 5.924000e+10 1 2020-12-31 6.062400e+10 2 2019-12-31 ...
[ "If you want a method-chained solution, you could use something like this:\nimport pandas as pd\n\n\nroce_by_year = (\n pd.merge(nopat, capital_employed)\n .rename(columns={\"\": \"date\"})\n .assign(\n date=lambda xdf: pd.to_datetime(\n xdf[\"date\"], errors=\"coerce\"\n ).dt.year...
[ 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074611681_pandas_python.txt
Q: Python AttributeError: type object has no attribute I have a simple node class with Id and Value, but python seems to not be able to access those attributes when i use the objects in a list. This is the class Node for context. class Node(): def __init__(self, id : int, value : int): self.id = id ...
Python AttributeError: type object has no attribute
I have a simple node class with Id and Value, but python seems to not be able to access those attributes when i use the objects in a list. This is the class Node for context. class Node(): def __init__(self, id : int, value : int): self.id = id self.value = value This is a priority queue implementa...
[ "This is the problem:\nclass ListAlt():\n def __init__(self):\n self.queue = [Node] # <--\n\nYou are setting queue to a list containing the Node class. Why not just an empty list?\nAlso, dequeue returns a Node instance. So to get 10, you need to write this instead:\nprint(lista.dequeue().value)\n\n\nHere...
[ 3, 2 ]
[]
[]
[ "attributeerror", "python" ]
stackoverflow_0074611974_attributeerror_python.txt