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: Matching values in datasets with different structures I need to add values from Dataset A to Dataset B through a shared key. However, the datasets are not organized in the same way. Dataset A has multiple entrances with the same key (name), and Dataset B is the identification (don't ask why they used the ID as a s...
Matching values in datasets with different structures
I need to add values from Dataset A to Dataset B through a shared key. However, the datasets are not organized in the same way. Dataset A has multiple entrances with the same key (name), and Dataset B is the identification (don't ask why they used the ID as a separate dataset): dataset_A = {'Name' : ["John Snow", "John...
[ "Step 1 Dataframe Creation: The dataframes for the two datasets can be created using the following code:\nimport pandas as pd\n\n# elements of first dataset\nfirst_Set = {'Prod_1': ['Laptop', 'Mobile Phone',\n 'Desktop', 'LED'],\n 'Price_1': [25000, 8000, 20000, 35000]\n }\n\n# crea...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074631414_dataframe_pandas_python.txt
Q: Finding the words immediate before and after a string dynamically specified I have a strings below: CREATE VIEW [dbo].[TestView] AS SELECT T1.Col1,T1.Col2,T2.Col1,T2.Col2,T3.Col1,T3.Col2 FROM table_1 T1 LEFT JOIN table_2 T2 ON T1.Col1 = T2.Col2 INNER JOIN Table_3 T3 ON T1.Col2 = T3.Col2 Objective I want to group...
Finding the words immediate before and after a string dynamically specified
I have a strings below: CREATE VIEW [dbo].[TestView] AS SELECT T1.Col1,T1.Col2,T2.Col1,T2.Col2,T3.Col1,T3.Col2 FROM table_1 T1 LEFT JOIN table_2 T2 ON T1.Col1 = T2.Col2 INNER JOIN Table_3 T3 ON T1.Col2 = T3.Col2 Objective I want to group the list of Tables and their column Names. So I want a dataframe like below: Tab...
[ "Looking at the broader aim, I would approach it as follows:\n\nWith a regex, first identify the tables and their aliases, which occur after FROM or JOIN keywords. No need to assume aliases start with \"T\".\n\nCollect this information in a dictionary keyed by the table alias, and with a pair as corresponding data:...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074629375_python_regex.txt
Q: Ctypes send an array of structures I have to realize a project between Python and C. One of the instructions is to use ctypes, so I need to call my C function from Python. The latter needs me to send it two integer variables and a structure array. But I can't get the declaration to work. I don't know how to make t...
Ctypes send an array of structures
I have to realize a project between Python and C. One of the instructions is to use ctypes, so I need to call my C function from Python. The latter needs me to send it two integer variables and a structure array. But I can't get the declaration to work. I don't know how to make the declaration. C: typedef struct //D...
[ "I suspect the problem is that you were creating a list[reference] instead of Array[reference] which translates to tab = (reference * 2)(). Let's see if this works:\nimport ctypes as c\n\ndef sac_dos_brute(nb_produit: int, reference: c.Array[reference], masse: float) -> None:\n dll = c.cdll.LoadLibrary('C:/..../...
[ 1, 0, 0 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0074628879_c_ctypes_python.txt
Q: Why is the "1" after sum necessary to avoid a syntax error Why does this work: def hamming_distance(dna_1,dna_2): hamming_distance = sum(1 for a, b in zip(dna_1, dna_2) if a != b) return hamming_distance As opposed to this: def hamming_distance(dna_1,dna_2): hamming_distance = sum(for a, b in zip(dna_...
Why is the "1" after sum necessary to avoid a syntax error
Why does this work: def hamming_distance(dna_1,dna_2): hamming_distance = sum(1 for a, b in zip(dna_1, dna_2) if a != b) return hamming_distance As opposed to this: def hamming_distance(dna_1,dna_2): hamming_distance = sum(for a, b in zip(dna_1, dna_2) if a != b) return hamming_distance I get this err...
[ "You wrote a generator expression. Generator expressions must produce a value (some expression to the left of the first for). Without it, you're saying \"please sum all the lack-of-values not-produced by this generator expression\".\nAsk yourself:\n\nWhat does a genexpr that produces nothing even mean?\nWhat is sum...
[ 0, 0 ]
[]
[]
[ "function", "python", "sum" ]
stackoverflow_0074631508_function_python_sum.txt
Q: How to design an interface with an irregular grid layout I'm trying to design an interface in Python with Kivy. I need to add widgets to my App in a precise scheme, let's say a grid with two rows and three columns. I would not add widgets in all six positions. I am not sure that the GridLayout is the most suitable...
How to design an interface with an irregular grid layout
I'm trying to design an interface in Python with Kivy. I need to add widgets to my App in a precise scheme, let's say a grid with two rows and three columns. I would not add widgets in all six positions. I am not sure that the GridLayout is the most suitable, so I started modifying a more complex layout. from kivy.app ...
[ "You can just add a Widget to take up the space that you want blank:\n BoxLayout:\n orientation: 'horizontal'\n Button:\n text: \"4\"\n Widget:\n Button:\n text: \"6\" \"\"\")\n\n" ]
[ 0 ]
[]
[]
[ "kivy", "layout", "python", "user_interface" ]
stackoverflow_0074629295_kivy_layout_python_user_interface.txt
Q: AWS textract: UnsupportedDocumentException for PNG and JPG images. Error occurs only in production and not locally I'm getting the following error when I deploy A FastAPI app to AWS Lambda that uses the AWS Textract service. The strange thing is that, it works perfectly fine in my local development environment, bu...
AWS textract: UnsupportedDocumentException for PNG and JPG images. Error occurs only in production and not locally
I'm getting the following error when I deploy A FastAPI app to AWS Lambda that uses the AWS Textract service. The strange thing is that, it works perfectly fine in my local development environment, but throws this error when I deploy it. Error: botocore.errorfactory.UnsupportedDocumentException: An error occurred (Unsu...
[ "Are you using the file pointer for any other purpose than this function call ?\nI just had the same error when trying to call client.analyze_document on the open file using the sample code provided by aws. They give the following code :\nenter image description here\nBut it turned out (in my case), that calling im...
[ 2 ]
[]
[]
[ "amazon_textract", "amazon_web_services", "api", "aws_lambda", "python" ]
stackoverflow_0074530762_amazon_textract_amazon_web_services_api_aws_lambda_python.txt
Q: Hangman written in python doesnt recognise correct letters guessed :/ So I'm working my first project which hangman written in python every works like the visuals and the incorrect letters. However, It is unable to recognise the correct letter guessed. import random from hangman_visual import lives_visual_dict imp...
Hangman written in python doesnt recognise correct letters guessed :/
So I'm working my first project which hangman written in python every works like the visuals and the incorrect letters. However, It is unable to recognise the correct letter guessed. import random from hangman_visual import lives_visual_dict import string # random word with open('random.txt', 'r') as f: All_Text...
[ "Your error is this: When checking if the user_letter is in the WORD2GUESS, you falsely remove it from used_letters, but it has to stay in the set.\nAlso you are missing some way of escaping the while loop when fully guessing the word. That could be done at the same spot by checking if used_letters contain all the ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074628556_python.txt
Q: Struggling with python's import mechanism I am an experienced java enterprise developer but very new to python enterprise development shop. I am currently, struggling to understand why some imports work while others don't. Some background: Our dev team recently upgraded python from 3.6 to 3.10.5 and following is o...
Struggling with python's import mechanism
I am an experienced java enterprise developer but very new to python enterprise development shop. I am currently, struggling to understand why some imports work while others don't. Some background: Our dev team recently upgraded python from 3.6 to 3.10.5 and following is our package structure src/ bunch of files (docke...
[ "The -m parameter is used with the import name, not the path. So you'd use python3 -m package.moduleA (with . instead of /, and no .py), not python3 -m package/moduleA.py.\nThat said, it only works if package.moduleA is locatable from one of the roots in sys.path. Shy of installing the package, the simplest way to ...
[ 2, 0 ]
[]
[]
[ "importerror", "python", "python_import" ]
stackoverflow_0074631218_importerror_python_python_import.txt
Q: Is this correct for rock-paper-scissor game | Python? The question is : Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game) player1 = input("Player 1: ") player2 =...
Is this correct for rock-paper-scissor game | Python?
The question is : Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game) player1 = input("Player 1: ") player2 = input("Player 2: ") if player1 == "rock" and player2 == "...
[ "You could use a while loop, i.e. something like\nplay = 'Y'\n\nwhile play=='Y':\n # your original code\n\n play = input(\"Do you want to play again (Y/N): \")\n\nAlso I'd suggest you check that the responses from the user are valid (i.e. what if they type potatoe, in your code nothing will print if one or bo...
[ 0, 0 ]
[]
[]
[ "input", "python", "reset" ]
stackoverflow_0071837673_input_python_reset.txt
Q: How to replace a value in a list while input? I have a string in an input that needs to be split into separate values and left in a list. I am using the following construct to enter values. How can the value -1 be noticed on a variable var? import sys readline = sys.stdin.readline var = 10**5 current_line = list(...
How to replace a value in a list while input?
I have a string in an input that needs to be split into separate values and left in a list. I am using the following construct to enter values. How can the value -1 be noticed on a variable var? import sys readline = sys.stdin.readline var = 10**5 current_line = list(map(int, readline().split())) Example input: -1 3 ...
[ "Just check for -1s as you go and replace them with var:\ncurrent_line = [var if i == -1 else i for i in map(int, readline().split())]\n\nvar if i == -1 else i is Python's ternary conditional operator (more precisely \"conditional expression\"), so -1 values get replaced, and all others are kept unchanged.\n", "Y...
[ 1, 1, 1 ]
[]
[]
[ "input", "python" ]
stackoverflow_0074631596_input_python.txt
Q: How to store a massive number of byte strings while having easy access to any small partion of them Here's my problem. I have a huge dataset of videos. To save space as much as possible, I encode each image frame to a byte string with PyTurboJPEG. In this way, each video is a list of byte strings. Then I use pickl...
How to store a massive number of byte strings while having easy access to any small partion of them
Here's my problem. I have a huge dataset of videos. To save space as much as possible, I encode each image frame to a byte string with PyTurboJPEG. In this way, each video is a list of byte strings. Then I use pickle to dump this list of byte strings to the disk. When I want to access a certain video, I load the .pkl f...
[ "I found an elegant solution. Just read the original binary stream. For examples, we have three images in a video, the length of the bytes of the first image is 8192, the second is 8633, and the third is 8321. We save the bytes of all three images in one file named video.bin, and the following codes shows how we ca...
[ 0 ]
[]
[]
[ "large_files", "numpy", "python" ]
stackoverflow_0074628765_large_files_numpy_python.txt
Q: How to convert Class to Class I need to upload some items in DynamoDB. I am using boto3 resource for the same. The item I need to insert are a couple of JSON strings dumped together. I need to convert them to dict so I can insert them in DynamoDB. def update_record_Dynamo( company_name, first_name, las...
How to convert Class to Class
I need to upload some items in DynamoDB. I am using boto3 resource for the same. The item I need to insert are a couple of JSON strings dumped together. I need to convert them to dict so I can insert them in DynamoDB. def update_record_Dynamo( company_name, first_name, last_name, email, status, ...
[ "It looks like you're uploading it as a list of dictionaries, instead of dictionaries themselves.\nflag_dict = json.dumps([existing_user, flag])\nCreates the list, and you can see in the error that comes back that it still has the brackets around it. You'll want to recreate it as a dictionary of dictionaries if you...
[ 0 ]
[]
[]
[ "amazon_dynamodb", "dictionary", "python" ]
stackoverflow_0074631481_amazon_dynamodb_dictionary_python.txt
Q: Decoding several text files from Byte to UTF-8 I'm currently trying to loop over roughly 9000 .txt files in python to extract data and add them to a joined pandas data frame. The .txt data is stored in bytes, so in order to access it I was told to use a decoder. Because I'm interested in preserving special charact...
Decoding several text files from Byte to UTF-8
I'm currently trying to loop over roughly 9000 .txt files in python to extract data and add them to a joined pandas data frame. The .txt data is stored in bytes, so in order to access it I was told to use a decoder. Because I'm interested in preserving special characters, I would like to use the UTF-8 decoder, but I'm ...
[ "Maybe you could try every codec available in your environment and check which result fits best.\nHere is a way of doing that:\nimport os, codecs, encodings\nfrom collections import OrderedDict\nfrom typing import Union\nfrom cprinter import TC\nfrom input_timeout import InputTimeout\n\n\nclass CodecChecker:\n d...
[ 0 ]
[]
[]
[ "pandas", "python", "python_unicode", "utf_8" ]
stackoverflow_0074630082_pandas_python_python_unicode_utf_8.txt
Q: How to make a recursive function to generate the combination of numbers eg. for n=3, (1,1,1),(1,1,2) and so on? def generate(n): t=[] lol=[[] for i in range(n**n)] helper(n,t,lol) return(lol) def helper(n,t,lol): global j if len(t)==n: lol[j]=lol[j]+t j += 1 retur...
How to make a recursive function to generate the combination of numbers eg. for n=3, (1,1,1),(1,1,2) and so on?
def generate(n): t=[] lol=[[] for i in range(n**n)] helper(n,t,lol) return(lol) def helper(n,t,lol): global j if len(t)==n: lol[j]=lol[j]+t j += 1 return for i in range(1,n+1): print(i) t.append(i) helper(n,t,lol) t.pop() j=0 ...
[ "Try this code:\ndef generate(n):\n def helper(m, n, s):\n if m==0:\n print(s)\n else:\n for x in range(1,n+1):\n helper(m-1, n, s+[x])\n assert n>=1\n helper(n, n, [])\n\nExamples:\n>>> generate(1)\n[1]\n>>> generate(2)\n[1, 1]\n[1, 2]\n[2, 1]\n[2, 2]\n>>...
[ 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074583392_python_recursion.txt
Q: character "@" in the name of a variable in the django template I have a dictionary in my views.py mydata = {'@model': 'wolfen', '@genre': 'fantastic', 'price: '350'} which I pass to the django view in a context like this context['mydata'] = mydata and in my view i display like this {{mydata.@model}} the problem...
character "@" in the name of a variable in the django template
I have a dictionary in my views.py mydata = {'@model': 'wolfen', '@genre': 'fantastic', 'price: '350'} which I pass to the django view in a context like this context['mydata'] = mydata and in my view i display like this {{mydata.@model}} the problem is that the django template uses the "@" character for other tags. ...
[ "Rename the data, for example with:\nmydata = {'@model': 'wolfen', '@genre': 'fantastic', 'price': '350'}\nmydata = {k[1:] if k.startswith('@') else k: v for k, v in mydata.items()}\ncontext['mydata'] = mydata\nThen you can use {{ mydata.model }} in the template.\nOr for subdictionaries:\nmydata_2 = {\n '1': {'@...
[ 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074631600_django_django_templates_python.txt
Q: Open an Alert dialog box while clicking on the camera icon button if the the camera is not open yet in kivymd I'm beginner in Kivy, I make a screen which has an image in which a camera live feed is fitted and 2 buttons the 1st start camera which open the webcam and the 2nd is the icon button to take a picture and...
Open an Alert dialog box while clicking on the camera icon button if the the camera is not open yet in kivymd
I'm beginner in Kivy, I make a screen which has an image in which a camera live feed is fitted and 2 buttons the 1st start camera which open the webcam and the 2nd is the icon button to take a picture and store it locally but the problem is that if i clicked the icon button before clicking the start camera it give me ...
[ "You can put that line that causes the exception in a try block. And in the except block display a Popup.\nOr you can disable the capture_image Button, and enable it from within the load_video() method.\n" ]
[ 0 ]
[]
[]
[ "kivy", "kivymd", "python" ]
stackoverflow_0074622929_kivy_kivymd_python.txt
Q: How do I add lines to a key and different lines as values? So I start put with a file that lists title, actor, title, actor, etc. 12 Years a Slave Topsy Chapman 12 Years a Slave Devin Maurice Evans 12 Years a Slave Brad Pitt 12 Years a Slave Jay Huguley 12 Years a Slave Devy...
How do I add lines to a key and different lines as values?
So I start put with a file that lists title, actor, title, actor, etc. 12 Years a Slave Topsy Chapman 12 Years a Slave Devin Maurice Evans 12 Years a Slave Brad Pitt 12 Years a Slave Jay Huguley 12 Years a Slave Devyn A. Tyler 12 Years a Slave Willo Jean-Baptiste Amer...
[ "Using a defaultdict is usually a better choice:\nfrom collections import defaultdict\ndata = defaultdict(list)\n\nwith open(\"filename.txt\", 'r') as f:\n stripped = map(str.strip, f)\n for movie, actor in zip(stripped, stripped):\n data[movie].append(actor)\n\nprint(data)\n\n", "So you need to swit...
[ 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074630771_dictionary_python.txt
Q: How to prevent end users from editing a hidden input value in a Django social website In a website having a "Comment" and "reply to a comment" system. After each comment in the template, There's a "Add a reply" form which have a hidden input to carry the comment pk on its value attribute. How to prevent the end u...
How to prevent end users from editing a hidden input value in a Django social website
In a website having a "Comment" and "reply to a comment" system. After each comment in the template, There's a "Add a reply" form which have a hidden input to carry the comment pk on its value attribute. How to prevent the end user from editing that hidden input value ? And If this is not possible, What would be the c...
[ "You can't prevent somebody from editing the value attribute, since it's client-sided.\nThe better approach would be to check on the server-side whether the user is permitted to comment or reply to the given post. For example, you can check if the user is a friend of the creator of the post. If it's not, you can bl...
[ 0, 0, 0 ]
[]
[]
[ "django", "django_templates", "html", "javascript", "python" ]
stackoverflow_0074582094_django_django_templates_html_javascript_python.txt
Q: Having access to all modules in python package directly When creating a Python Package with different modules, I have to import it like this: from Package_A import Module_1 Object_1 = Module_1.Class_1() What I would like to have is the possibility to have all the classes available in the main package as follows:...
Having access to all modules in python package directly
When creating a Python Package with different modules, I have to import it like this: from Package_A import Module_1 Object_1 = Module_1.Class_1() What I would like to have is the possibility to have all the classes available in the main package as follows: import Package_A as pa Object_1 = pa.Class_1() Can anyone ...
[ "Packages\nSuppose you want to design a collection of modules (a “package”) for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: .wav, .aiff, .au), so you may need to create and maintain a growing collection of modul...
[ 0 ]
[]
[]
[ "python", "python_packaging" ]
stackoverflow_0074631491_python_python_packaging.txt
Q: Adding iterations to a list depending on input Good morning, I am wondering if someone can point me in the right direction. I am trying to have a loop go through a list and add them to a printable list. let's say the user inputs the number two: Then it should print go pull out two random class-names of the list. i...
Adding iterations to a list depending on input
Good morning, I am wondering if someone can point me in the right direction. I am trying to have a loop go through a list and add them to a printable list. let's say the user inputs the number two: Then it should print go pull out two random class-names of the list. if the user inputs 4 it should pull out 4 random clas...
[ "Use the random std package, just put your instantiated objects in a list and you can choose a random one like such:\nfrom random\nvalues = [1,2,3,4,5,6]\nrand_val = random.choice(values)\n\n", "You can do a ranged for, which means that the for will execute x times (range(x)). By this way now you have a for execu...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074624856_python_python_3.x.txt
Q: Convert tab delimited data into dictionary I'm trying to convert an array with a dictionary to a flattened dictionary and export it to a JSON file. I have an initial tab-delimited file, and have tried multiple ways but not coming to the final result. If there is more than one row present then save these as arrays ...
Convert tab delimited data into dictionary
I'm trying to convert an array with a dictionary to a flattened dictionary and export it to a JSON file. I have an initial tab-delimited file, and have tried multiple ways but not coming to the final result. If there is more than one row present then save these as arrays in the dictionary Name file code fi...
[ "create list for each column and iterate to append row by row\nimport csv\nimport json \n\n# read file\nd = {}\nwith open('write_object.tmp') as f:\n reader = csv.reader(f, delimiter='\\t')\n headers = next(reader)\n for head in headers:\n d[head] = []\n for row in reader:\n for i, head...
[ 1, 0 ]
[]
[]
[ "csv", "dictionary", "python" ]
stackoverflow_0074631513_csv_dictionary_python.txt
Q: In behave, how do you run a scenario only? I have a 'behave' feature that has a lot of tests on it. I only need to run a specific scenario for development needs. How do I do it? (preferably on the command line) A: If you want to run a single test for that feature, use the -n or --name flag which seems to want t...
In behave, how do you run a scenario only?
I have a 'behave' feature that has a lot of tests on it. I only need to run a specific scenario for development needs. How do I do it? (preferably on the command line)
[ "If you want to run a single test for that feature, use the -n or --name flag which seems to want the text after Scenario:\nbehave -n 'This is a scenario name'\n\n\nYou can run a feature file by using -i or --include flags and then the name of the feature file. \nbehave -i file_name.feature\n\nor:\nbehave --include...
[ 38, 35, 4, 0, 0 ]
[]
[]
[ "bdd", "python", "python_behave" ]
stackoverflow_0027030233_bdd_python_python_behave.txt
Q: How to call a variadic function with ctypes from multiple threads? I have a shared library, libfoo.so, with a variadic function: int foo(int handle, ...); that uses handle to access to static variables within the library. Now, I want to use it with ctypes in a multithread program. import ctypes as ct # main lib ...
How to call a variadic function with ctypes from multiple threads?
I have a shared library, libfoo.so, with a variadic function: int foo(int handle, ...); that uses handle to access to static variables within the library. Now, I want to use it with ctypes in a multithread program. import ctypes as ct # main lib = ct.cdll.LoadLibrary('libfoo.so') foo = lib.foo foo.restype = ct.c_int ...
[ "Instead of setting .argtypes for each function resulting in a race condition, create the correct ctypes type as you call each function:\nimport ctypes as ct\n\n# main\nlib = ct.cdll.LoadLibrary('libfoo.so')\nfoo = lib.foo\nfoo.argtypes = ct.c_int, # define the known types. ctypes will allow more\nfoo.restype = ct...
[ 1 ]
[]
[]
[ "ctypes", "multithreading", "python", "variadic_functions" ]
stackoverflow_0074630617_ctypes_multithreading_python_variadic_functions.txt
Q: socket.gaierror: [Errno -2] Name or service not known docker-compose + rabbitmq + pika (Python) I have docker container with rabbitmq, it has an address: 192.168.220.10, domain in my local etc/hosts: rabbitmq So, Im trying to use pika (python) from another container with fastapi app, it has an address: 192.168.220...
socket.gaierror: [Errno -2] Name or service not known docker-compose + rabbitmq + pika (Python)
I have docker container with rabbitmq, it has an address: 192.168.220.10, domain in my local etc/hosts: rabbitmq So, Im trying to use pika (python) from another container with fastapi app, it has an address: 192.168.220.5. Of course, all containers have a network: net: driver: bridge ipam: config: - subnet: 192.168.220...
[ "parameters = pika.URLParameters('amqp://rabbitmq:27474129@rabbitmq:5672/%2F')\nconnection = pika.BlockingConnection(parameters)\n\n" ]
[ 0 ]
[]
[]
[ "docker_compose", "docker_networking", "pika", "python", "rabbitmq" ]
stackoverflow_0074631641_docker_compose_docker_networking_pika_python_rabbitmq.txt
Q: How do I solve a two-sum problem with multiple solutions? So essentially it is a simple two sum problem but there are multiple solutions. At the end I would like to return all pairs that sum up to the target within a given list and then tally the total number of pairs at the end and return that as well. Currently ...
How do I solve a two-sum problem with multiple solutions?
So essentially it is a simple two sum problem but there are multiple solutions. At the end I would like to return all pairs that sum up to the target within a given list and then tally the total number of pairs at the end and return that as well. Currently can only seem to return 1 pair of numbers. So far my solution h...
[ "I took your code and did a couple of tweaks to where summations were being tested and how the data was being stored. Following is your tweaked code.\ndef suminlist(mylist,target):\n sumlist = []\n count = 0\n for i in range(len(mylist)):\n for x in range(i+1,len(mylist)):\n sum = mylist...
[ 1, 0, 0 ]
[]
[]
[ "list", "python", "sum" ]
stackoverflow_0074621971_list_python_sum.txt
Q: Catch sklearn joblib output to python logging When using sklearn, I want to see the output. Therefore, I use verbose when available. Generally, I want timestamps, process ids etc, so I use the python logging module when I can. Getting sklearn output to the logging module has been done before, e.g. https://stackove...
Catch sklearn joblib output to python logging
When using sklearn, I want to see the output. Therefore, I use verbose when available. Generally, I want timestamps, process ids etc, so I use the python logging module when I can. Getting sklearn output to the logging module has been done before, e.g. https://stackoverflow.com/a/50803365 However, I want to run in para...
[ "I did come up with a workaround using the dask backend instead. I define a worker plugin that essentially is my contextmanager\nimport dask.distributed\nclass LogPlugin(dask.distributed.WorkerPlugin):\n name = \"LoggerRedirector\"\n\n def setup(self, worker: dask.distributed.Worker):\n self.originals ...
[ 0 ]
[]
[]
[ "joblib", "python", "python_logging", "scikit_learn" ]
stackoverflow_0074631614_joblib_python_python_logging_scikit_learn.txt
Q: Why does GPU memory increase when recreating and reassigning a JAX numpy array to the same variable name? When I recreate and reassign a JAX np array to the same variable name, for some reason the GPU memory nearly doubles the first recreation and then stays stable for subsequent recreations/reassignments. Why doe...
Why does GPU memory increase when recreating and reassigning a JAX numpy array to the same variable name?
When I recreate and reassign a JAX np array to the same variable name, for some reason the GPU memory nearly doubles the first recreation and then stays stable for subsequent recreations/reassignments. Why does this happen and is this generally expected behavior for JAX arrays? Fully runnable minimal example: https://c...
[ "The reason for this behavior comes from the interaction of several things:\n\nWithout pre-allocation, the GPU memory usage will grow as needed, but will not shrink when buffers are deleted.\n\nWhen you reassign a python variable, the old value still exists in memory until the Python garbage collector notices it is...
[ 1 ]
[]
[]
[ "gpu", "jax", "memory", "nvidia", "python" ]
stackoverflow_0074628777_gpu_jax_memory_nvidia_python.txt
Q: How to generate a ripple shape pattern using python I am looking to create a repetitive pattern from a single shape (in the example below, the starting shape would be the smallest centre star) using Python. The pattern would look something like this: To give context, I am working on a project that uses a camera t...
How to generate a ripple shape pattern using python
I am looking to create a repetitive pattern from a single shape (in the example below, the starting shape would be the smallest centre star) using Python. The pattern would look something like this: To give context, I am working on a project that uses a camera to detect a shape on a rectangle of sand. The idea is that...
[ "Assing you are using turtle (very beginner friendly) you can use this:\nimport turtle, math\n\nturtle.title(\"Stars!\")\n\nt = turtle.Turtle()\nt.speed(900) # make it go fast\nt.hideturtle() # hide turtle\nt.width(1.5) # make lines nice & thick\n\ndef drawstar(size):\n t.up() # make turtle not draw while reposi...
[ 0, 0 ]
[]
[]
[ "image", "python", "shapes" ]
stackoverflow_0074578308_image_python_shapes.txt
Q: Training and validation loss history for MLPRegressor I am using an MLPRegressor to solve a regression problem and would like to plot the loss function, i.e., by how much the loss decreases in each training epoch, for both training and validation. Following the solution here, I have been able to plot the validatio...
Training and validation loss history for MLPRegressor
I am using an MLPRegressor to solve a regression problem and would like to plot the loss function, i.e., by how much the loss decreases in each training epoch, for both training and validation. Following the solution here, I have been able to plot the validation loss with loss_curve: pd.DataFrame(mlp.loss_curve_).plot(...
[]
[]
[ "Yes, there is a way.\nYou can just create two numpy arrays with the information of both train and validation loss and plot two lines in the same graph as in:\nPlotting multiple line graphs in matplotlib\n" ]
[ -1 ]
[ "python", "scikit_learn" ]
stackoverflow_0074631843_python_scikit_learn.txt
Q: How do I combine elements from two loops without issues? When I execute this code... from bs4 import BeautifulSoup with open("games.html", "r") as page: doc = BeautifulSoup(page, "html.parser") titles = doc.select("a.title") prices = doc.select("span.price-inner") for game_soup in doc.find_all("div", {"clas...
How do I combine elements from two loops without issues?
When I execute this code... from bs4 import BeautifulSoup with open("games.html", "r") as page: doc = BeautifulSoup(page, "html.parser") titles = doc.select("a.title") prices = doc.select("span.price-inner") for game_soup in doc.find_all("div", {"class": "game-options-wrapper"}): game_ids = (game_soup.button...
[ "I feel like all 3 details (title, price_official, price_lowest) are probably all in a shared container. It would be better to loop through these containers and select the details as sets from each container to make sure the wight prices and titles are being paired up, but I can't tell you how to do that without se...
[ 1 ]
[]
[]
[ "beautifulsoup", "loops", "python", "web_scraping" ]
stackoverflow_0074631667_beautifulsoup_loops_python_web_scraping.txt
Q: How to Tokenize block of text as one token in python? Recently I am working on a genome data set which consists of many blocks of genomes. On previous works on natural language processing, I have used sent_tokenize and word_tokenize from nltk to tokenize the sentences and words. But when I use these functions on g...
How to Tokenize block of text as one token in python?
Recently I am working on a genome data set which consists of many blocks of genomes. On previous works on natural language processing, I have used sent_tokenize and word_tokenize from nltk to tokenize the sentences and words. But when I use these functions on genome data set, it is not able to tokenize the genomes corr...
[ "You just need to concatenate the lines between two ids apparently. There should be no need for nltk or any tokenizer, just a bit of programming ;)\n\npatterns = {}\nwith open('data', \"r\") as f:\n id = None\n current = \"\"\n for line0 in f:\n line= line0.rstrip()\n if line[0] == '>' : # n...
[ 3 ]
[]
[]
[ "nlp", "nltk", "python", "tokenize" ]
stackoverflow_0074623917_nlp_nltk_python_tokenize.txt
Q: Write a function that accepts two strings and returns the indices of all occurrences of second string in the first string as a list Write a function that accepts two strings and returns the indices of all the occurrences of the second string in the first string as a list. If the second string is not present in the...
Write a function that accepts two strings and returns the indices of all occurrences of second string in the first string as a list
Write a function that accepts two strings and returns the indices of all the occurrences of the second string in the first string as a list. If the second string is not present in the first string then it should return -1 def indices(a,b): c=[] if b!="": for i in b: x=b.find(i) a...
[ "Method #1 : Using list comprehension + startswith() This task can be performed using the two functionalities. The startswith function primarily performs the task of getting the starting indices of substring and list comprehension is used to iterate through the whole target string.\n# Python3 code to demonstrate wo...
[ 0 ]
[]
[]
[ "indices", "python", "string" ]
stackoverflow_0074631907_indices_python_string.txt
Q: Inserting data using PyMongo based on a defined data model I have a dataset consisting of 250 rows that looks like to following: In MongoDB Compass, I inserted the first row as follows: db.employees.insertOne([{"employee_id": 412153, "first_name": "Carrol", "last_...
Inserting data using PyMongo based on a defined data model
I have a dataset consisting of 250 rows that looks like to following: In MongoDB Compass, I inserted the first row as follows: db.employees.insertOne([{"employee_id": 412153, "first_name": "Carrol", "last_name": "Dhin", "email": "carrol.dhin@co...
[ "from pymongo import MongoClient\nimport pandas as pd\n\nclient = MongoClient(‘localhost’, 27017)\ndb = client.MD\ncollection = db.gammaCorp\n\ndf = pd.read_csv(‘ ’) #insert CSV name here\n\ndata = {}\n\nfor i in df.index:\n data['employee_id'] = df['employee_id'][i]\n data['first_name'] = df['first_name'][i]...
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0074606136_mongodb_pymongo_python.txt
Q: Difficulties to make the .wait() function work with .stop() on a discord button And thank you in advance to whoever wants to help me. So I created a slash command to create a reminder with 2 buttons to decide what to do next : The call to the command works, the embed too, the buttons too. But after clicking on the...
Difficulties to make the .wait() function work with .stop() on a discord button
And thank you in advance to whoever wants to help me. So I created a slash command to create a reminder with 2 buttons to decide what to do next : The call to the command works, the embed too, the buttons too. But after clicking on the buttons I would like them to stop the "await view.wait()" with the "interaction:disc...
[ "\nHowever I don't think the \"interaction:discord.Interaction.stop()\" line works and I don't know why\n\nThis line doesn't make a lot of sense syntactically but I'll gloss over that for now. Interaction.stop() literally doesn't exist, so that line isn't gonna do a whole lot. Not sure what you expect to happen.\nD...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python", "wait" ]
stackoverflow_0074629185_discord_discord.py_python_wait.txt
Q: How to plot scikit learn classification report? Is it possible to plot with matplotlib scikit-learn classification report?. Let's assume I print the classification report like this: print '\n*Classification Report:\n', classification_report(y_test, predictions) confusion_matrix_graph = confusion_matrix(y_test,...
How to plot scikit learn classification report?
Is it possible to plot with matplotlib scikit-learn classification report?. Let's assume I print the classification report like this: print '\n*Classification Report:\n', classification_report(y_test, predictions) confusion_matrix_graph = confusion_matrix(y_test, predictions) and I get: Clasification Report: ...
[ "Expanding on Bin's answer:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef show_values(pc, fmt=\"%.2f\", **kw):\n '''\n Heatmap with text in each cell with matplotlib's pyplot\n Source: https://stackoverflow.com/a/25074150/395857 \n By HYRY\n '''\n from itertools import izip\n pc.u...
[ 42, 28, 15, 14, 7, 6, 3, 2, 2, 1, 1, 0 ]
[ "You can do:\nimport matplotlib.pyplot as plt\n\ncm = [[0.50, 1.00, 0.67],\n [0.00, 0.00, 0.00],\n [1.00, 0.67, 0.80]]\nlabels = ['class 0', 'class 1', 'class 2']\nfig, ax = plt.subplots()\nh = ax.matshow(cm)\nfig.colorbar(h)\nax.set_xticklabels([''] + labels)\nax.set_yticklabels([''] + labels)\nax.set...
[ -1 ]
[ "matplotlib", "numpy", "python", "scikit_learn" ]
stackoverflow_0028200786_matplotlib_numpy_python_scikit_learn.txt
Q: How to sent push message from multiple apps in python I have 2 different apps with 2 different credentials for firebase. So firebase_admin is 2 times initialised. import of firebase from firebase_admin import credentials, messaging Initialise 2 firebase_admins and assigne the json credentials. #initialize firebas...
How to sent push message from multiple apps in python
I have 2 different apps with 2 different credentials for firebase. So firebase_admin is 2 times initialised. import of firebase from firebase_admin import credentials, messaging Initialise 2 firebase_admins and assigne the json credentials. #initialize firebase 1 json_file_first = location of the json one credentials_...
[ "I did found the solution, its in the response below the message itself. You can add the firebase_admin instance.\ndef sendPushNotificationTest(title, msg, registration_token):\n message = messaging.MulticastMessage( ///i think i have to define the sender before messaging\n notification=messaging.Notifi...
[ 0 ]
[]
[]
[ "firebase", "python" ]
stackoverflow_0074631191_firebase_python.txt
Q: How to click on button in telethon? How i can click on buttons in "keyboardButton" I can click on inline buttons in messages, but i don't know how click in buttons above the keyboard .click() don't work, because it's not a message A: Please, correct me if i wrong. Use event.click(0,0) If the button is at the top...
How to click on button in telethon?
How i can click on buttons in "keyboardButton" I can click on inline buttons in messages, but i don't know how click in buttons above the keyboard .click() don't work, because it's not a message
[ "Please, correct me if i wrong.\nUse event.click(0,0)\nIf the button is at the top left\nUse event.click(0,1)\nIf the button is at number 2 from the top left\nSo, (row,column)\nHope it's easy to understand.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074630777_python.txt
Q: How can I get elements from nested lists? The problem that I have to solve is; write a recursive python function recSumList() that sums all the integer and float elements in the list. you can use the type() function to find the type of the element. List : [1, "abcd", 2.2, [3.6, 4], [5, "8", 6]] I just could write;...
How can I get elements from nested lists?
The problem that I have to solve is; write a recursive python function recSumList() that sums all the integer and float elements in the list. you can use the type() function to find the type of the element. List : [1, "abcd", 2.2, [3.6, 4], [5, "8", 6]] I just could write; def recSumlist(): list1 = [1, "abcd", 2.2,...
[ "\nIf current item is a list, get sum of all the elements.\nElse if it is an int or float return the corresponding value.\nIf its str or something else return 0 to ignore the values\n\ndef recSumlist(l):\n if isinstance(l, list):\n return sum(recSumlist(i) for i in l)\n return l if isinstance(l, (float...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074631977_python.txt
Q: How can I do a histogram with 1D gaussian mixture with sklearn? I would like to do an histogram with mixture 1D gaussian as the picture. Thanks Meng for the picture. My histogram is this: I have a file with a lot of data (4,000,000 of numbers) in a column: 1.727182 1.645300 1.619943 1.709263 1.614427 1.5223...
How can I do a histogram with 1D gaussian mixture with sklearn?
I would like to do an histogram with mixture 1D gaussian as the picture. Thanks Meng for the picture. My histogram is this: I have a file with a lot of data (4,000,000 of numbers) in a column: 1.727182 1.645300 1.619943 1.709263 1.614427 1.522313 And I'm using the follow script with modifications than Meng and ...
[ "Although this is a reasonably old thread, I would like to provide my take on it. I believe my answer can be more comprehensible to some. Moreover, I include a test to check whether or not the desired number of components makes statistical sense via the BIC criterion.\n# import libraries (some are for cosmetics)\ni...
[ 4, 3, 0 ]
[]
[]
[ "gmm", "histogram", "matplotlib", "python", "scikit_learn" ]
stackoverflow_0055187037_gmm_histogram_matplotlib_python_scikit_learn.txt
Q: Django check user.is_authenticated before UserCreationForm to prevent a user to signup twice In Django, I am trying to prevent an already existing user to register (sign up) again. In my case, the user can sign up with a form. My approach is to check in views.py if the user already exists by checking is_authentica...
Django check user.is_authenticated before UserCreationForm to prevent a user to signup twice
In Django, I am trying to prevent an already existing user to register (sign up) again. In my case, the user can sign up with a form. My approach is to check in views.py if the user already exists by checking is_authenticated upfront. If the user does not exist, then the form entries will be processed and the user will...
[ "Have you tried request.user.is_anonymous?\n", "If the user is already logged in it will raise is_authenticated as True and False it there's no user logged in.\nI guess you're trying to register/sign up with no active session, then the first inner if request.user.is_authenticated is evaluated False and not used, ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074632086_django_python.txt
Q: Confluent Kafka poll, when does a message get committed I have a Python application that has autocommit=True and it is using poll() to get messages with a interval of 1 second. I was reading on the documentation and it mentions that polling reads message in a background thread and queues them so that the main thre...
Confluent Kafka poll, when does a message get committed
I have a Python application that has autocommit=True and it is using poll() to get messages with a interval of 1 second. I was reading on the documentation and it mentions that polling reads message in a background thread and queues them so that the main thread can take them afterwards. I was a bit confused there on wh...
[ "As mentioned in the docs, every auto.commit.interval.ms, any polled offsets will get committed.\nIf you are concerned about missing data, you should always disable auto-commits, in any Kafka client, and handle commits on your own after you know you've actually processed those records.\n" ]
[ 1 ]
[]
[]
[ "apache_kafka", "confluent_kafka_python", "librdkafka", "python" ]
stackoverflow_0074629190_apache_kafka_confluent_kafka_python_librdkafka_python.txt
Q: How can I round a string made of numbers efficiently using Python? Using Python 3... I've written code that rounds the values for ArcGIS symbology labels. The label is given as a string like "0.3324 - 0.6631". My reproducible code is... label = "0.3324 - 0.6631" label_list = [] label_split = label.split(" - ") fo...
How can I round a string made of numbers efficiently using Python?
Using Python 3... I've written code that rounds the values for ArcGIS symbology labels. The label is given as a string like "0.3324 - 0.6631". My reproducible code is... label = "0.3324 - 0.6631" label_list = [] label_split = label.split(" - ") for num in label_split: num = round(float(num), 2) # rounded to 2 deci...
[ "This solution doesn't try to operate on a sequence but on the 2 values.\nA bit more readable to me.\nx, _, y = label.partition(\" - \")\nlabel = f\"{float(x):.2f} - {float(y):.2f}\"\n\n", "You could use a regular expression to search for a number with more than two decimal places, and round it.\nThe regex \\b\\d...
[ 2, 1, 1 ]
[]
[]
[ "floating_point", "python", "python_3.x", "rounding", "string" ]
stackoverflow_0074630596_floating_point_python_python_3.x_rounding_string.txt
Q: Creating a nested dictionaries via for-loop I'm having trouble creating a dictionary with multiple keys and values inside an other dictionary by using a for-loop. I have a program that reads another text file, and then inputs it's information to the dictionaries. The file looks something like this: GPU;GeForce GTX...
Creating a nested dictionaries via for-loop
I'm having trouble creating a dictionary with multiple keys and values inside an other dictionary by using a for-loop. I have a program that reads another text file, and then inputs it's information to the dictionaries. The file looks something like this: GPU;GeForce GTX 1070 Ti;430 CPU;AMD Ryzen 7 2700X;233 GPU;GeForc...
[ "You can simply achieve the expected behavior using collections.defaultdict and a simple loop.\nNB. I am emulating a file with a split text here\nf = '''GPU;GeForce GTX 1070 Ti;430\nCPU;AMD Ryzen 7 2700X;233\nGPU;GeForce GTX 2060;400\nCPU;Intel Core i7-11700;360\nRAM;HyperX 16GB;180\nPSU;Corsair RM850X;210'''\n\nfr...
[ 4, 0, 0, 0, 0 ]
[]
[]
[ "data_structures", "dictionary", "filereader", "nested", "python" ]
stackoverflow_0070112370_data_structures_dictionary_filereader_nested_python.txt
Q: ERROR: No results. Previous SQL was not a query cnxn = pyodbc.connect(driver="{ODBC Driver 17 for SQL Server}", server="xxx", database="yy", user="abc", password="abc") cursor = cnxn.cursor() b = alter table temp1 add column3 varchar(10) cursor.execute(b) cursor.fetchall() from the above code I'm trying to alter...
ERROR: No results. Previous SQL was not a query
cnxn = pyodbc.connect(driver="{ODBC Driver 17 for SQL Server}", server="xxx", database="yy", user="abc", password="abc") cursor = cnxn.cursor() b = alter table temp1 add column3 varchar(10) cursor.execute(b) cursor.fetchall() from the above code I'm trying to alter the table and add the column as i contain 2 tables 1...
[ "change the line of code to as below\nb = 'alter table temp1 add column3 varchar(10);'\nthis assigns the entire SQL command as string to the variable b, which then you can use in the call to execute() function of the cursor.\nAlso, the ALTER TABLE SQL statement will not return any results set, so you need not call ...
[ 0, 0 ]
[]
[]
[ "python", "sql", "sql_server" ]
stackoverflow_0070363825_python_sql_sql_server.txt
Q: python runs older version after installing updated version on Mac I am currently running python 3.6 on my Mac, and installed the latest version of Python (3.11) by downloading and installing through the official python releases. Running python3.11 opens the interpreter in 3.11, and python3.11 --version returns Py...
python runs older version after installing updated version on Mac
I am currently running python 3.6 on my Mac, and installed the latest version of Python (3.11) by downloading and installing through the official python releases. Running python3.11 opens the interpreter in 3.11, and python3.11 --version returns Python 3.11.0, but python -V in terminal returns Python 3.6.1 :: Continuu...
[ "By default MacOS ships with Python-2.-. But, I guess most of us have long back started to work with Python-3 and it is very irritating to run python3 every time instead of python in terminal. Here is how to do this.\nOpen the terminal (bash or zsh) whatever shell you are using.\nInstall python-3 using Homebrew (ht...
[ 1, 1 ]
[]
[]
[ "homebrew", "pip", "python", "python_venv", "terminal" ]
stackoverflow_0074631751_homebrew_pip_python_python_venv_terminal.txt
Q: Plots not rendering properly on an implicit plot (python) I am trying to plot two curves and then mark their intersection with a vertical line from the x-axis to the point of intersection. Sometimes the line will generate other times it will not unless I show the plot and then append it as well. To see this try op...
Plots not rendering properly on an implicit plot (python)
I am trying to plot two curves and then mark their intersection with a vertical line from the x-axis to the point of intersection. Sometimes the line will generate other times it will not unless I show the plot and then append it as well. To see this try option 1 with b = 24, c = 159 then try option 4 where a = 15, c =...
[ "Replace the plot3 = plot_implic.... command with the following:\nplot3 = plot_implicit(Eq(x, newxroot),(x,0,2*newxroot), (y,0,2*newyroot), line_color='black', show=False, adaptive=False)\n\nNote that I used adaptive=False which should create a constant width line, and I also plotted the vertical line over the same...
[ 0 ]
[]
[]
[ "math", "mathematical_expressions", "plot", "python", "sympy" ]
stackoverflow_0074630508_math_mathematical_expressions_plot_python_sympy.txt
Q: pytesseract not keeping leading zeroes when using image_to_data() I'm using pytesseract to process the following image: When I use the image_to_string() function config = "--oem 3 -l eng --psm 7" pytesseract.image_to_string(potential_image, config = config) I get the correct "03" output. However, when I use the ...
pytesseract not keeping leading zeroes when using image_to_data()
I'm using pytesseract to process the following image: When I use the image_to_string() function config = "--oem 3 -l eng --psm 7" pytesseract.image_to_string(potential_image, config = config) I get the correct "03" output. However, when I use the image_to_data() function predict = pytesseract.image_to_data(potential_...
[ "Rather than using data.frame as the output type, use a regular Python dictionary:\npytesseract.image_to_data(image, config = config, output_type = pytesseract.Output.DICT)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "python", "python_tesseract" ]
stackoverflow_0074291461_dataframe_python_python_tesseract.txt
Q: Python for each element in a list add the value of previous index and next index For each element in a list I want to add the value before and after the element and append the result to an empty list. The problem is that at index 0 there is no index before and at the end there is no index next. At index 0 I want t...
Python for each element in a list add the value of previous index and next index
For each element in a list I want to add the value before and after the element and append the result to an empty list. The problem is that at index 0 there is no index before and at the end there is no index next. At index 0 I want to add the value of index 0 with value of index 1, and in the last index I want to add ...
[ "You can make the conditions inside the for loop\nfor i in range(len(vec)):\n if i == 0 :\n newValue = vec[i] + vec[i+1]\n elif i == len(vec)-1:\n newValue = vec[i] + vec[i-1]\n else:\n newValue = vec[i] + vec[i+1] + vec[i-1]\n newVec.append(newValue)\n\nprint(newVec)\n\noutput:\n[3...
[ 2, 2, 1 ]
[]
[]
[ "append", "for_loop", "list", "python", "range" ]
stackoverflow_0074632371_append_for_loop_list_python_range.txt
Q: Python dataprep lat_long_clean low performance on my dataset I have latitude and longitude data in a dataframe with the following format: Longitude Latitude 055.25.30E 21.19.15S 075.26.27W 40.39.08N 085.02.00W 29.44.00N I run the below code based on clean_lat_long: from dataprep.clean import clean_lat_long d...
Python dataprep lat_long_clean low performance on my dataset
I have latitude and longitude data in a dataframe with the following format: Longitude Latitude 055.25.30E 21.19.15S 075.26.27W 40.39.08N 085.02.00W 29.44.00N I run the below code based on clean_lat_long: from dataprep.clean import clean_lat_long dfa['lat_long'] = dfa['Latitude'] + ' ' + dfa['Longitude'] clean_...
[ "I obtained much better results by removing the first point (.) between degrees and minutes with the following instruction:\ndfa['lat_long'] = dfa['Latitude'].str.replace('.', ' ',1, regex=True) + ' ' + dfa['Longitude'].str.replace('.', ' ',1, regex=True) \n\nWhich transformed the dataset into:\nLongitude Latitud...
[ 0 ]
[]
[]
[ "geocoding", "python" ]
stackoverflow_0074630909_geocoding_python.txt
Q: Unable to save email attachment from outlook to local drive i have written the below code to save email attachment from outlook with specific subject but its throwing an error. Below is the code : import win32com.client import os outlook = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI") inbox...
Unable to save email attachment from outlook to local drive
i have written the below code to save email attachment from outlook with specific subject but its throwing an error. Below is the code : import win32com.client import os outlook = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI") inbox = outlook.Folders('xyz.com').Folders("Inbox") messages = inbox.I...
[ "Change the line\natch.SaveAsFile(os.getcwd() + 'H:\\Atul\\Save' + atch.Filename)\n\nto\natch.SaveAsFile('H:\\Atul\\Save\\' + atch.Filename)\n\n" ]
[ 0 ]
[]
[]
[ "outlook", "pandas", "python", "pywin32" ]
stackoverflow_0074632167_outlook_pandas_python_pywin32.txt
Q: Syntax error: positional argument follows key word argument I'm fairly new to coding and I'm having trouble figuring out this error. The error: > File "main.py", line 7 bot = commands. Bot(commandS_prefix= "!", intents = discord. Intents,all()) SyntaxError: positional argument follow s keyword argument My code:...
Syntax error: positional argument follows key word argument
I'm fairly new to coding and I'm having trouble figuring out this error. The error: > File "main.py", line 7 bot = commands. Bot(commandS_prefix= "!", intents = discord. Intents,all()) SyntaxError: positional argument follow s keyword argument My code: import discord import os from discord import app_commands fro...
[ "bot = commands. Bot(commandS_prefix= \"!\", intents = discord. Intents,all())\n\nBecause you have a comma between Intents and all(), all() is being interpreted as a separate argument. Change the comma to a period.\n" ]
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074632276_discord.py_python.txt
Q: How to scrape Next button on Linkedin with Selenium using Python? I am trying to scrape LinkedIn website using Selenium. I can't parse Next button. It resists as much as it can. I've spent a half of a day to adress this, but all in vain. I tried absolutely various options, with text and so on. Only work with start...
How to scrape Next button on Linkedin with Selenium using Python?
I am trying to scrape LinkedIn website using Selenium. I can't parse Next button. It resists as much as it can. I've spent a half of a day to adress this, but all in vain. I tried absolutely various options, with text and so on. Only work with start ID but scrape other button. selenium.common.exceptions.NoSuchElementEx...
[ "OK, there are several issues here:\n\nThe main problem why your code not worked is because the \"next\" pagination is initially even not created on the page until you scrolling the page, so I added the mechanism, to scroll the page until that button can be clicked.\nit's not good to create locators based on local ...
[ 0 ]
[]
[]
[ "python", "scroll", "selenium", "webdriverwait", "xpath" ]
stackoverflow_0074631101_python_scroll_selenium_webdriverwait_xpath.txt
Q: Can't install tensorflow-text~=2.11.0 I got a warning something like warnings.warn( No local packages or working download links found for tensorflow-text~=2.11.0 error: Could not find suitable distribution for Requirement.parse('tensorflow-text~=2.11.0') and if I run pip install 'tensorflow-text~=2.11.0' I got :...
Can't install tensorflow-text~=2.11.0
I got a warning something like warnings.warn( No local packages or working download links found for tensorflow-text~=2.11.0 error: Could not find suitable distribution for Requirement.parse('tensorflow-text~=2.11.0') and if I run pip install 'tensorflow-text~=2.11.0' I got : ERROR: Could not find a version that satis...
[ "As per their note, they have dropped building for Windows with v2.11.0. So, you'll need to build from source or seek a third-party build.\n", "I think you should run\npip install tensorflow-text==2.11.0\n\nwithout any quotes or swung dash\n", "Install directtly. The latest version of tensorflow-text is 2.11.0 ...
[ 1, 0, 0 ]
[]
[]
[ "conda", "pip", "python", "tensorflow", "windows" ]
stackoverflow_0074628389_conda_pip_python_tensorflow_windows.txt
Q: How can I add a new column to a dataframe with a lookup to the same column? (1 rows above) I've created this dataframe - Range = np.arange(1,101,1) A={ 0:-1, 1:0, 2:4 } Table = pd.DataFrame({"Row": Range}) Table["Intervals"]=np.where(Table["Row"]==1,0,(Table["Row"]%3).map(A)) Table Row Intervals 0 1 0 ...
How can I add a new column to a dataframe with a lookup to the same column? (1 rows above)
I've created this dataframe - Range = np.arange(1,101,1) A={ 0:-1, 1:0, 2:4 } Table = pd.DataFrame({"Row": Range}) Table["Intervals"]=np.where(Table["Row"]==1,0,(Table["Row"]%3).map(A)) Table Row Intervals 0 1 0 1 2 4 2 3 -1 3 4 0 4 5 4 ... ... ... 95 96 -1 96 97 0 97 98 4 98 99 -1 9...
[ "We'll start by adding the value -25 to the 0th row in a new column, NewColumn\nTable.loc[0, \"NewColumn\"] = -25\n\nThen we fill the nulls with the Intervals column and convert back to int (they were floats)\nTable[\"NewColumn\"] = Table[\"NewColumn\"].fillna(Table[\"Intervals\"]).astype(int)\n\nAnd last cumulativ...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074632426_dataframe_pandas_python.txt
Q: Sort values and re order after Context I have a table in this format: File IDR IDC Type I/P Value 1 1 ID1 Primary P 5 1 1 ID2 Secondary P 6 1 1 ID3 Primary I 7 2 2 ID4 Primary I 8 2 2 ID5 Secondary P 10 Each ['File'] have has its own IDR. Each ['IDR'] has an IDC with a type (Primary/Secondary) and a value....
Sort values and re order after
Context I have a table in this format: File IDR IDC Type I/P Value 1 1 ID1 Primary P 5 1 1 ID2 Secondary P 6 1 1 ID3 Primary I 7 2 2 ID4 Primary I 8 2 2 ID5 Secondary P 10 Each ['File'] have has its own IDR. Each ['IDR'] has an IDC with a type (Primary/Secondary) and a value. The problem I need to ...
[ "Could you sort all the columns at once?\nprint(df.sort_values([\n \"File\",\n \"IDR\",\n \"Type\",\n \"IDC\",\n \"Value\"\n], ascending=[True, True, True, False, True,]))\n\n File IDR IDC Type I/P Value\n2 1 1 ID3 Primary I 7\n0 1 1 ID1 Primary P 5\n1 ...
[ 0 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python", "sorting" ]
stackoverflow_0074632281_dataframe_group_by_pandas_python_sorting.txt
Q: Removing a key from a dictionary using the value Can I somehow delete a value from a dictionary using its key? The function del_contact is supposed to delete a contact using only the name of the contact, but unfortunately I have the dictionary and the value, but not the key. How can this be solved? my_contacts = {...
Removing a key from a dictionary using the value
Can I somehow delete a value from a dictionary using its key? The function del_contact is supposed to delete a contact using only the name of the contact, but unfortunately I have the dictionary and the value, but not the key. How can this be solved? my_contacts = { 1: { "Name": "Tom Jones", "Number...
[ "Basically what you can do is iterate of the dict and save only the keys without that user's name.\nThis code will do the trick:\nmy_contacts = {1: {\"Name\": \"Tom Jones\",\n \"Number\": \"911\",\n \"Birthday\": \"22.10.1995\",\n \"Address\": \"212 street\"},\n...
[ 1, 0, 0, 0 ]
[]
[]
[ "contacts", "dictionary", "python" ]
stackoverflow_0074632313_contacts_dictionary_python.txt
Q: How to separately send email to the form I made web contact form, my email sending to subscribe email box , I want to send email to the form only. Please help me driver.get('https://shop.rtrpilates.com/') driver.find_element_by_partial_link_text('Contact'),click try: username_box = driver.find_element_by_xpat...
How to separately send email to the form
I made web contact form, my email sending to subscribe email box , I want to send email to the form only. Please help me driver.get('https://shop.rtrpilates.com/') driver.find_element_by_partial_link_text('Contact'),click try: username_box = driver.find_element_by_xpath('//input[@type="email"]') username_box.s...
[ "Seems you main problem here is that you trying to use deprecated methods find_element_by_*. None of these is supported by Selenium 4.\nAlso code you shared is missing delays to wait for elements to become clickable etc.\nThe following short code works:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrom...
[ 0 ]
[]
[]
[ "css_selectors", "python", "selenium", "selenium4", "webdriverwait" ]
stackoverflow_0074629118_css_selectors_python_selenium_selenium4_webdriverwait.txt
Q: I get invalid_grant error for mastodon/mastodon.py. How do I do Oauth2 instead? This code is taken almost verbatim from mastodon.py's README.md it always returns Traceback (most recent call last): File "C:\Users\matth\GitHub\feed_thing\again.py", line 32, in mastodon.log_in( File "C:\Users\matth.virtualenvs\...
I get invalid_grant error for mastodon/mastodon.py. How do I do Oauth2 instead?
This code is taken almost verbatim from mastodon.py's README.md it always returns Traceback (most recent call last): File "C:\Users\matth\GitHub\feed_thing\again.py", line 32, in mastodon.log_in( File "C:\Users\matth.virtualenvs\feed_thing-LXMa84iN\lib\site-packages\mastodon\Mastodon.py", line 568, in log_in rais...
[ "I found part of the solution. If 2 factor auth is enabled on your account, mastodon.py (as of today) can't handle login. If you disable 2 factor auth, then you can login as expected.\nAnother hint for people who find this, sometimes you need to delete the *.secret files for mastodon.py to work (i.e. if you've chan...
[ 1 ]
[]
[]
[ "mastodon", "mastodon_py", "python" ]
stackoverflow_0074631471_mastodon_mastodon_py_python.txt
Q: Traceback (most recent call last): _tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack in python I have a problem with my code in Python I want to transfer the data after entering it into the excel file But I get an error with the title: Traceback (most recent call...
Traceback (most recent call last): _tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack in python
I have a problem with my code in Python I want to transfer the data after entering it into the excel file But I get an error with the title: Traceback (most recent call last): File "C:\Users\yasen\Desktop\برمجة\graphics\main11.py", line 60, in firstname_text = Label(text = "الاسم الاول * ",).grid(row=0) File "C:\Users...
[ "As I just said on FB - you cant miy .place, .pack. and .grid\nfrom tkinter import *\nimport pandas as pd\n \n \n def send_info():\n path = 'Registers.form.xlsx'\n df1 = pd.read_excel(path)\n SeriesA = df1['firstname']\n SeriesB = df1['secondname']\n SeriesC = df1['thirdn...
[ 0, 0, -2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0071792488_python_tkinter.txt
Q: Python: daily average function I am trying to make a function that returns a list/array with the daily averages for a variable from either one of 3 csv files Each csv file is similar to this: date, time, variable1, variable2, variable3 2021-01-01,01:00:00,1.43738,25.838,22.453 2021-01-01,02:00:00,2.08652,21.028,19...
Python: daily average function
I am trying to make a function that returns a list/array with the daily averages for a variable from either one of 3 csv files Each csv file is similar to this: date, time, variable1, variable2, variable3 2021-01-01,01:00:00,1.43738,25.838,22.453 2021-01-01,02:00:00,2.08652,21.028,19.099 2021-01-01,03:00:00,1.39101,23....
[ "Well.\nFirst of all - try to do it yourself before asking a question.\nIt will help you to learn things.\nBut now to your question.\ncsv_lines_test = [\n\"date, time, variable1, variable2, variable3\\n\",\n\"2021-01-01,01:00:00,1.43738,25.838,22.453\\n\",\n\"2021-01-01,02:00:00,2.08652,21.028,19.099\\n\",\n\"2021-...
[ 0 ]
[]
[]
[ "average", "function", "numpy", "pandas", "python" ]
stackoverflow_0074632400_average_function_numpy_pandas_python.txt
Q: Read CSV file from Azure Blob Storage with out knowing the csv file name in python In azure Blob storage i have CSV files. I need to read those CSV files into dataframe. Csv file name vary every time. So i need to read csv from from azure blobstorage container folder. Folder name is constant but csv file name vary...
Read CSV file from Azure Blob Storage with out knowing the csv file name in python
In azure Blob storage i have CSV files. I need to read those CSV files into dataframe. Csv file name vary every time. So i need to read csv from from azure blobstorage container folder. Folder name is constant but csv file name vary.
[ "Here is how you can read csv files to dataframes\nfrom azure.storage.blob import BlockBlobService\nimport pandas as pd\nfrom io import StringIO\n\nSTORAGEACCOUNTNAME= \"<YOUR_STORAGE_ACCOUNTNAME>\"\nSTORAGEACCOUNTKEY= \"<YOUR_STORAGE_ACCOUNT_KEY>\"\nCONTAINERNAME= \"<YOUR_CONTAINER_NAME>\"\nBLOBNAME= \"<BLOB_NAME>...
[ 0, 0 ]
[]
[]
[ "azure_blob_storage", "pandas", "python" ]
stackoverflow_0071935502_azure_blob_storage_pandas_python.txt
Q: How to separate string between semicolon and count length In a pandas data frame is there anyway to split a column by '; ' and count the string length, like in this example: Col1 Col2 123; 345 3; 3 54; 8903 2; 4 the result should be in an XLSX file. for index, row in df1.iterrows(): valid0 = row['Part_Numb...
How to separate string between semicolon and count length
In a pandas data frame is there anyway to split a column by '; ' and count the string length, like in this example: Col1 Col2 123; 345 3; 3 54; 8903 2; 4 the result should be in an XLSX file. for index, row in df1.iterrows(): valid0 = row['Part_Number'] valid1 = valid0.split('; ') valid1 = [le...
[ "Can you try this:\ndf['col3']=df['Col1'].apply(lambda x: '; '.join([str(len(i)) for i in x.split('; ')]))\n\n'''\n Col1 col3\n0 123; 345 3; 3\n1 54; 8903 2; 4\n\n\n'''\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074632209_pandas_python.txt
Q: Regular expression to capture n words after pattern that do not contain that pattern I'm trying to write a regular expression that captures n words after a pattern, which was answered in this question, except I want the search to keep going for another n words if it encounters that pattern again. For example, if ...
Regular expression to capture n words after pattern that do not contain that pattern
I'm trying to write a regular expression that captures n words after a pattern, which was answered in this question, except I want the search to keep going for another n words if it encounters that pattern again. For example, if my main search pattern is 'x', and I want to capture a word that contains 'x' and n=3 word...
[ "It's not clear that regex is the most natural way to solve your use case.\nConsider this hybrid approach.\nimport re\n\npattern = re.compile(r\"x\") # or whatever\n\ndef get_at_least_n(text: str, n=3) -> Optional[range]:\n words = text.split()\n matches = list(map(pattern.search, words))\n if not any(mat...
[ 1 ]
[]
[]
[ "python", "regex", "regex_lookarounds" ]
stackoverflow_0074631188_python_regex_regex_lookarounds.txt
Q: Pandas add column of count of another column across all the datafram I have a dataframe: df = C1 C2 E 1 2 3 4 9 1 3 1 1 8 2 8 8 1 2 I want to add another columns that will have the count of the value that is in the columns 'E' in all the dataframe (in the column E...
Pandas add column of count of another column across all the datafram
I have a dataframe: df = C1 C2 E 1 2 3 4 9 1 3 1 1 8 2 8 8 1 2 I want to add another columns that will have the count of the value that is in the columns 'E' in all the dataframe (in the column E) So here the output will be: df = C1. C2. E. cou 1. 2. 3. 1 ...
[ "Here's one way. Find the matches and add them up.\nimport pandas as pd\n\ndata = [\n [1,2,3],[4,9,1],[3,1,1],[8,2,8]\n]\n\ndf = pd.DataFrame( data, columns=['C1','C2','E'])\nprint(df)\n\ndef count(val):\n return (df['C1']==val).sum() + (df['C2']==val).sum()\n\ndf['cou'] = df.E.apply(count)\nprint(df)\n\nOut...
[ 0 ]
[]
[]
[ "data_munging", "data_science", "dataframe", "pandas", "python" ]
stackoverflow_0074632631_data_munging_data_science_dataframe_pandas_python.txt
Q: Remove/ filter rows in JSON based on condition with python I have a table in a JSON whereby I need an entire row to be deleted/ filtered based on the condition if "Disposition (Non Open Market)" in "transactionType" then delete/ filter entry in all columns. Below is what my JSON file looks like: { "lastDate":{...
Remove/ filter rows in JSON based on condition with python
I have a table in a JSON whereby I need an entire row to be deleted/ filtered based on the condition if "Disposition (Non Open Market)" in "transactionType" then delete/ filter entry in all columns. Below is what my JSON file looks like: { "lastDate":{ "0":"11\/22\/2022", "1":"10\/28\/2022", ...
[ "I was able to remove according to value by appending the keys that have the string value to a list and then simply removing it\nimport json\n\ndata = json.load(open(\"AAPL22_institutional_table_MRKTVAL.json\"))\n\ndelete_keys = []\n\nfor value in data['transactionType']:\n if data['transactionType'][value] == '...
[ 2, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074632543_json_python.txt
Q: Ultra Basic Question on PySpark with Kubernetes After fighting with the lack of documentation and wildly misleading information out there on PySpark with Kubernetes I think I have boiled this down to one question. How do I get the driver pod that gets spun up to read my python file (not a dependency, the actual fi...
Ultra Basic Question on PySpark with Kubernetes
After fighting with the lack of documentation and wildly misleading information out there on PySpark with Kubernetes I think I have boiled this down to one question. How do I get the driver pod that gets spun up to read my python file (not a dependency, the actual file itself)? Here's the command I'm using: kubectl run...
[ "You are not mounting any volume to the pod, so even if the file is present in the NFS mount, it won't be visible from within the pod. You must mount it. In the following command, you are creating a pod but not attaching any volume to it.\nkubectl run --namespace apache-spark apache-spark-client --rm --tty -i --re...
[ 1 ]
[]
[]
[ "apache_spark", "kubernetes", "pyspark", "python" ]
stackoverflow_0074631612_apache_spark_kubernetes_pyspark_python.txt
Q: How to dynamically find the nearest specific parent of a selected element? I want to parse many html pages and remove a div that contains the text "Message", using beautifulsoup html.parser and python. The div has no name or id, so pointing to it is not possible. I am able to do this for 1 html page. In the code b...
How to dynamically find the nearest specific parent of a selected element?
I want to parse many html pages and remove a div that contains the text "Message", using beautifulsoup html.parser and python. The div has no name or id, so pointing to it is not possible. I am able to do this for 1 html page. In the code below, you will see 6 .parent . This is because there are 5 tags (p,i,b,span,a) b...
[ "As described in your question, that there is no other <div> between, you could use .find_parent():\nsoup.find(text=re.compile('Message')).find_parent('div').decompose()\n\nBe aware, that if you use find_all() you have to iterate your ResultSet while unsing .find_parent():\nfor r in soup.find_all(text=re.compile('M...
[ 3 ]
[]
[]
[ "beautifulsoup", "html", "html_parsing", "python" ]
stackoverflow_0074632532_beautifulsoup_html_html_parsing_python.txt
Q: How to test a single GET request in parallel for specified count? I want to parallely send a GET request for the specified count say 100 times. How to achieve this using JMeter or Python ? I tried bzm parallel executor but that doesn't workout. A: import requests import threading totalRequests = 0 numberOfThrea...
How to test a single GET request in parallel for specified count?
I want to parallely send a GET request for the specified count say 100 times. How to achieve this using JMeter or Python ? I tried bzm parallel executor but that doesn't workout.
[ "import requests\nimport threading\n\ntotalRequests = 0\nnumberOfThreads = 10\nthreads = [0] * numberOfThreads\n\n\ndef worker(thread):\n r = requests.get(\"url\")\n threads[thread] = 0 # free thread\n\n\nwhile totalRequests < 100:\n for thread in range(numberOfThreads):\n if threads[thread] == 0:\...
[ 1, 0 ]
[]
[]
[ "jmeter", "jmeter_plugins", "playwright", "python" ]
stackoverflow_0074631728_jmeter_jmeter_plugins_playwright_python.txt
Q: Sphinx - ran`make html` and I am missing content for a few modules Repo link: https://github.com/Eric-Cortez/aepsych-fork Problem: I am running into an issue when generating sphinx documentation when I run make html most of the modules are generated except for 3 which are aepsych.database, aepsych.plotting, and ae...
Sphinx - ran`make html` and I am missing content for a few modules
Repo link: https://github.com/Eric-Cortez/aepsych-fork Problem: I am running into an issue when generating sphinx documentation when I run make html most of the modules are generated except for 3 which are aepsych.database, aepsych.plotting, and aepsych.server. file structure: (root) aepsych-fork/ |__ aepsyc...
[ "I recreated a conda environment with all of the dependencies and was still getting an error. WARNING: autodoc: failed to import module 'acquisition.bvn' from module 'aepsych'; the following exception was raised: No module named 'botorch.sampling.normal' So I added autodoc_mock_imports = [\"botorch\"] to sphinx/con...
[ 0 ]
[]
[]
[ "documentation", "init", "python", "python_sphinx" ]
stackoverflow_0074608512_documentation_init_python_python_sphinx.txt
Q: Convert bytes in a pandas dataframe column into hexadecimals There is a problem when pandas reads read_sql bytes column. If you look at the sql request through DBeaver, then the bytes column shows differently, but if you look at it through read_sql, it seems that pandas translates the value into a hex. For example...
Convert bytes in a pandas dataframe column into hexadecimals
There is a problem when pandas reads read_sql bytes column. If you look at the sql request through DBeaver, then the bytes column shows differently, but if you look at it through read_sql, it seems that pandas translates the value into a hex. For example, pandas shows column value - b'\x80\xbc\x10`K\xa8\x95\xd8\x11\xe5...
[ "It looks like the column (which I call 'col' below) contains bytes. There's the .hex() method that you can map to each item in the column to convert them into hexadecimal strings.\ndf['col'] = df['col'].map(lambda e: e.hex())\n\nThis produces\n80bc10604ba895d811e54bf9e7d78c71\n\nIt seems the specific output you wa...
[ 1 ]
[]
[]
[ "pandas", "python", "sql_server" ]
stackoverflow_0074628652_pandas_python_sql_server.txt
Q: trimming and removing adapter from sequences in biopython I got this question that I am unable to solve: A user has an input DNA.txt file which consists of 5 sequences. Each sequences starts with the same 14 base pair fragment - a sequencing adapter that should have been removed. Write a program that will (a) trim...
trimming and removing adapter from sequences in biopython
I got this question that I am unable to solve: A user has an input DNA.txt file which consists of 5 sequences. Each sequences starts with the same 14 base pair fragment - a sequencing adapter that should have been removed. Write a program that will (a) trim this adapter and write the cleaned sequences to a new file and...
[ "think I got it, not using biopython though:\nimport io\n\nfile =io.StringIO('AAAAAAAAAAAAAATTTTT\\nAAAAAAAAAAAAAATTTTT\\nAAAAAAAAAAAAAATTTT\\nAAAAAAAAAAAAAATTTTT\\nAAAAAAAAAAAAAATTTTT\\n')\n\nprint('read file :') \nfor i in file.readlines():\n print(i.strip(),'\\n')\nfile.seek(0)\n\nnewfile =io.StringIO()\nf...
[ 0 ]
[]
[]
[ "biopython", "python" ]
stackoverflow_0074628843_biopython_python.txt
Q: pandas datetime Series difference not working as expected The following is a minimal working example import pandas as pd df = pd.DataFrame({"datetime": [ "2021-09-01 00:00:01", "2021-09-01 00:00:02", "2021-09-01 00:00:03", "2021-09-01 00:00:04", "2021-09-01 00:00:05", ...
pandas datetime Series difference not working as expected
The following is a minimal working example import pandas as pd df = pd.DataFrame({"datetime": [ "2021-09-01 00:00:01", "2021-09-01 00:00:02", "2021-09-01 00:00:03", "2021-09-01 00:00:04", "2021-09-01 00:00:05", "2021-09-01 00:00:06", "2021-09-01 00:00:07", ...
[ "In your example the index is taken into account. So it will take the same times an subtract them, which then ends up 0 days.\nNaT because index 0 and 9 are not present in both Series.\ndf[\"datetime\"][1::] - df[\"datetime\"][0:-1].values\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074632594_datetime_pandas_python.txt
Q: check if element is in anywhere the list I have two lists: expected = ["apple", "banana", "pear"] actual = ["banana_yellow", "apple", "pear_green"] I'm trying to assert that expected = actual. Even though the color is added at the end to some elements, it should still return true. Things I tried: for i in expecte...
check if element is in anywhere the list
I have two lists: expected = ["apple", "banana", "pear"] actual = ["banana_yellow", "apple", "pear_green"] I'm trying to assert that expected = actual. Even though the color is added at the end to some elements, it should still return true. Things I tried: for i in expected: assert i in actual I was hoping somethi...
[ "Try this:\ndef isequal(actual: list, expected: list) -> bool:\n actual.sort()\n expected.sort()\n if len(actual) != len(expected):\n return False\n for i, val in enumerate(expected):\n if not actual[i].startswith(val):\n return False\n return True\n\nprint(isequal(actual, ex...
[ 0, 0, 0, 0 ]
[]
[]
[ "compare", "list", "python" ]
stackoverflow_0074632667_compare_list_python.txt
Q: How to handle input value error when using under sampling methods from imblearn? Thank you for your help in advance. I am trying to use the RandomUnderSampler() and fit_sample() methods from imblearn to balance a botnet dataset with two missing values. The dataset contains a label column for binary classification ...
How to handle input value error when using under sampling methods from imblearn?
Thank you for your help in advance. I am trying to use the RandomUnderSampler() and fit_sample() methods from imblearn to balance a botnet dataset with two missing values. The dataset contains a label column for binary classification that uses 0 and 1 as values. I am using Azure ML designer where I created a Python Scr...
[ "Thank you Ghada. Posting your solution into answer section to help other community members.\nUsed the to_numeric() function to convert the string to numeric after removing the spaces in the string.\n\ncolumns = ['flgs', 'proto', 'saddr', 'daddr', 'state', 'category', 'subcategory']\nfor x in columns: dataframe1[x]...
[ 0 ]
[]
[]
[ "azure", "imbalanced_data", "machine_learning", "python" ]
stackoverflow_0073664778_azure_imbalanced_data_machine_learning_python.txt
Q: Reorganize pandas 'timed' dataframe into single row to allow for concat I have dataframes (stored in excel files) of data for a single participant each of which look like df1 = pd.DataFrame([['15:05', '15:06', '15:07', '15:08'], [7.333879016553067, 8.066897471204006, 7.070168678977272, 6.501888904228463], [64.1671...
Reorganize pandas 'timed' dataframe into single row to allow for concat
I have dataframes (stored in excel files) of data for a single participant each of which look like df1 = pd.DataFrame([['15:05', '15:06', '15:07', '15:08'], [7.333879016553067, 8.066897471204006, 7.070168678977272, 6.501888904228463], [64.16712081101915, 65.08486717007806, 67.22483766233766, 64.40328265521458], [114.21...
[ "Assuming that each row is Time 0, Time 1, etc. We can use the index for our top level in the MultiIndex\n# convert index to string and add \"Time \"\ndf1.index = \"Time \" + df1.index.astype(str)\n\nThen groupby the index, take the max (or some other aggregate that keeps the original values) of all columns besides...
[ 1 ]
[]
[]
[ "data_munging", "dataframe", "pandas", "python" ]
stackoverflow_0074632618_data_munging_dataframe_pandas_python.txt
Q: How can I get all objects of a model and it's fields? I have a Product Model and I want to be able to count all it's objects in a method so I can render the total number in a template, same for each category but I can only do that with the number_of_likes method. class Category(models.Model): name = models.Cha...
How can I get all objects of a model and it's fields?
I have a Product Model and I want to be able to count all it's objects in a method so I can render the total number in a template, same for each category but I can only do that with the number_of_likes method. class Category(models.Model): name = models.CharField(max_length=45) ... class Product(models.Model):...
[ "You can work with:\ndef number_of_products_for_category(self):\n return Product.objects.filter(category_id=self.category_id).count()\nBut if you use this for all categories, you can .annotate(..) [Django-doc] the queryset:\nfrom django.db.models import Count\n\ncategories = Category.objects.annotate(num_product...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074632939_django_django_models_python.txt
Q: convert matrix to image How would I go about going converting a list of lists of ints into a matrix plot in Python? The example data set is: [[3, 5, 3, 5, 2, 3, 2, 4, 3, 0, 5, 0, 3, 2], [5, 2, 2, 0, 0, 3, 2, 1, 0, 5, 3, 5, 0, 0], [2, 5, 3, 1, 1, 3, 3, 0, 0, 5, 4, 4, 3, 3], [4, 1, 4, 2, 1, 4, 5, 1, 2, 2, 0, 1, 2...
convert matrix to image
How would I go about going converting a list of lists of ints into a matrix plot in Python? The example data set is: [[3, 5, 3, 5, 2, 3, 2, 4, 3, 0, 5, 0, 3, 2], [5, 2, 2, 0, 0, 3, 2, 1, 0, 5, 3, 5, 0, 0], [2, 5, 3, 1, 1, 3, 3, 0, 0, 5, 4, 4, 3, 3], [4, 1, 4, 2, 1, 4, 5, 1, 2, 2, 0, 1, 2, 3], [5, 1, 1, 1, 5, 2, 5, ...
[ "You may try \nfrom pylab import *\nA = rand(5,5)\nfigure(1)\nimshow(A, interpolation='nearest')\ngrid(True)\n\n\nsource\n", "Perhaps matshow() from matplotlib is what you need.\n", "You can also use pyplot from matplotlib, follows the code:\nfrom matplotlib import pyplot as plt\n\n\nplt.imshow(\n[[3, 5, 3, 5,...
[ 16, 9, 0 ]
[]
[]
[ "image", "matrix", "python" ]
stackoverflow_0004841611_image_matrix_python.txt
Q: In dagster, how do I load_asset_value from a job executed in process with mem_io_manager? For this question, consider I have a repository with one asset: @asset def my_int(): return 1 @repository def my_repo(): return [my_int] I want to execute it in process (with mem_io_manager), but I would like to ret...
In dagster, how do I load_asset_value from a job executed in process with mem_io_manager?
For this question, consider I have a repository with one asset: @asset def my_int(): return 1 @repository def my_repo(): return [my_int] I want to execute it in process (with mem_io_manager), but I would like to retrieve the value returned by my_int from memory later. I can do that with fs_io_manager, for exa...
[ "mem_io_manager doesn't store objects to file storage like fs_io_manager. You could in your my_int asset,\n\nsave the value to a file or some other cloud storage and retrieve it later or\nAdd the value as metadata if it is a simple integer or string and retrieve that later.\n\nFor the second case, using metadata, y...
[ 2, 0, 0 ]
[]
[]
[ "dagster", "python" ]
stackoverflow_0074615651_dagster_python.txt
Q: How to subtract/black-out regions within an image in Python OpenCV I am working on a project that involves automating a video game using computer vision. My next task involves separating the game's UI elements from the actual game's field of view. For instance: We would take a screenshot of the entire client windo...
How to subtract/black-out regions within an image in Python OpenCV
I am working on a project that involves automating a video game using computer vision. My next task involves separating the game's UI elements from the actual game's field of view. For instance: We would take a screenshot of the entire client window like so: Then we would locate the various UI elements on screen (this...
[ "I ended up solving this by using slicing to set all pixels in a range to black. I thought of this because I knew that cropping an image was a similar process, and both involved selecting a range of pixels:\nimport cv2\nimport numpy as np\n\n# Let's assume we have already taken a screenshot of the client window\ncl...
[ 1 ]
[]
[]
[ "image_processing", "numpy", "python" ]
stackoverflow_0074632739_image_processing_numpy_python.txt
Q: Python Add an id column which resets based on another column value I have a data frame like the one below, and I want to add an id column that restarts based on the node value. node1,0.858 node1,0.897 node1,0.954 node2,3.784 node2,7.640 node2,11.592 For example, I want the output below 0, node1, 0.858 1, node1, 0...
Python Add an id column which resets based on another column value
I have a data frame like the one below, and I want to add an id column that restarts based on the node value. node1,0.858 node1,0.897 node1,0.954 node2,3.784 node2,7.640 node2,11.592 For example, I want the output below 0, node1, 0.858 1, node1, 0.897 2, node1, 0.954 0, node2, 3.784 1, node2, 7.640 2, node2, 11.592 I...
[ "You can group by the column you wish to base the partition on and then use cumcount() or cumsum(). Then use set_index() to reassign the index to the new field. You can skip that line however if you just need the partition index as a column.\nimport pandas as pd\n\ndata = {'Name':['node1','node1','node1','node2','n...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074632959_dataframe_pandas_python.txt
Q: Postgres cursor execute for search bar not working properly (psycopg2) Trying to make a simple search bar for my website and found out about the "Like" feature of psycopg2 But im getting the error Incomplete placeholder and not sure how to fix it.[enter image description here](https://i.stack.imgur.com/lI2JC.png) ...
Postgres cursor execute for search bar not working properly (psycopg2)
Trying to make a simple search bar for my website and found out about the "Like" feature of psycopg2 But im getting the error Incomplete placeholder and not sure how to fix it.[enter image description here](https://i.stack.imgur.com/lI2JC.png) Tried a bunch of stuff , Too much to list out. I'm expecting it to return al...
[ "string = f\"select * from tweet_fields WHERE text like '%{data.Keyword}%'\"\\ self.twittercursor.execute(string) \nFigured it out finally\n" ]
[ 0 ]
[]
[]
[ "orm", "postgresql", "psycopg2", "python", "sql" ]
stackoverflow_0074632237_orm_postgresql_psycopg2_python_sql.txt
Q: python dict to html unordered list Currently im trying to transform this python dict to a html unordered list: {'dataStreamId': 'raw:com.google.nutrition:NutritionSource', 'dataStreamName': 'NutritionSource', 'type': 'raw', 'dataType': {'name': 'com.google.nutrition', 'field': [{'name': 'nutrients', 'format': 'ma...
python dict to html unordered list
Currently im trying to transform this python dict to a html unordered list: {'dataStreamId': 'raw:com.google.nutrition:NutritionSource', 'dataStreamName': 'NutritionSource', 'type': 'raw', 'dataType': {'name': 'com.google.nutrition', 'field': [{'name': 'nutrients', 'format': 'map'}, {'name': 'meal_type', 'format': 'in...
[ "Try:\ndct = {\n \"dataStreamId\": \"raw:com.google.nutrition:NutritionSource\",\n \"dataStreamName\": \"NutritionSource\",\n \"type\": \"raw\",\n \"dataType\": {\n \"name\": \"com.google.nutrition\",\n \"field\": [\n {\"name\": \"nutrients\", \"format\": \"map\"},\n ...
[ 1, 1 ]
[]
[]
[ "dictionary", "html_lists", "python", "python_3.x" ]
stackoverflow_0074628578_dictionary_html_lists_python_python_3.x.txt
Q: How to read multiline json-like file with multiple JSON fragments separated by just a new line? I have a json file with multiple json objects (each object can be a multiple line json) Example: {"date": "2022-11-29", "runs": [{"23597": 821260}, {"23617": 821699}]} {"date": "2022-11-30", "runs": [{"23597": 821269}, ...
How to read multiline json-like file with multiple JSON fragments separated by just a new line?
I have a json file with multiple json objects (each object can be a multiple line json) Example: {"date": "2022-11-29", "runs": [{"23597": 821260}, {"23617": 821699}]} {"date": "2022-11-30", "runs": [{"23597": 821269}, {"23617": 8213534}]} Note that indeed this is not valid JSON as whole file (and hence regular "read ...
[ "NDJSON, not JSON.\nIt's a valid file format and often confused for JSON.\nPython of course has a library for this.\nimport ndjson\n\nwith open('run_log.json','r') as file:\n d = ndjson.load(file)\n for elem in d:\n print(type(elem), elem)\n\noutput\n<class 'dict'> {'date': '2022-11-29', 'runs': [{'235...
[ 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074632449_json_python.txt
Q: What does sum(x%2==0) mean?? (python) import numpy as np x = np.array([1, -1, 2, 5, 7]) print(sum(x%2==0)) This is the code, and I can't understand what does ' sum(x%2==0) ' mean. Does it mean to sum even number? I'm studying for school test and My professor said output of the above code is 1. But I can't unders...
What does sum(x%2==0) mean?? (python)
import numpy as np x = np.array([1, -1, 2, 5, 7]) print(sum(x%2==0)) This is the code, and I can't understand what does ' sum(x%2==0) ' mean. Does it mean to sum even number? I'm studying for school test and My professor said output of the above code is 1. But I can't understand what does ' sum(x%2==0)' mean..
[ "Set1:\nimport numpy as np\nx = np.array([1, -1, 2, 5, 7,4])\nprint(x)\ny = sum(x)\nprint(y)\nprint(x%2==0)\nprint(sum(x%2==0))\n\nOutput:\n[ 1 -1 2 5 7]\n14\n[False False True False False]\n1\n\nSet2:\nimport numpy as np\nx = np.array([1, -1, 2, 5, 7, 4])\nprint(x)\ny = sum(x)\nprint(y)\nprint(x%2==0)\nprint(s...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074631450_python.txt
Q: How to convert a Scikit-learn dataset to a Pandas dataset How do I convert data from a Scikit-learn Bunch object to a Pandas DataFrame? from sklearn.datasets import load_iris import pandas as pd data = load_iris() print(type(data)) data1 = pd. # Is there a Pandas method to accomplish this? A: Manually, you can u...
How to convert a Scikit-learn dataset to a Pandas dataset
How do I convert data from a Scikit-learn Bunch object to a Pandas DataFrame? from sklearn.datasets import load_iris import pandas as pd data = load_iris() print(type(data)) data1 = pd. # Is there a Pandas method to accomplish this?
[ "Manually, you can use pd.DataFrame constructor, giving a numpy array (data) and a list of the names of the columns (columns).\nTo have everything in one DataFrame, you can concatenate the features and the target into one numpy array with np.c_[...] (note the []):\nimport numpy as np\nimport pandas as pd\nfrom skle...
[ 197, 115, 85, 18, 15, 14, 9, 8, 8, 6, 6, 4, 3, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "dataset", "pandas", "python", "scikit_learn" ]
stackoverflow_0038105539_dataset_pandas_python_scikit_learn.txt
Q: Passing keyword arguments from URL to Flask api I stripped my snippets as far as I could. I want to use arbitrary number of passed keywords and values in my flask application from URL. For example: http://localhost:5000/duck?order=90 I would like to use order=90 as an item in a dictionary {"order" = 90} or setting...
Passing keyword arguments from URL to Flask api
I stripped my snippets as far as I could. I want to use arbitrary number of passed keywords and values in my flask application from URL. For example: http://localhost:5000/duck?order=90 I would like to use order=90 as an item in a dictionary {"order" = 90} or setting its value to a variable. The app.py: from flask impo...
[ "finally, after a day:\nit is working to some extent.\nmyresource.py:\n\nfrom flask import request\n\nfrom flask_restful import Resource from http import HTTPStatus\n\nclass Quack(Resource):\n\n def get(self): \n order = request.args.get(\"order\")\n return order, HTTPStatus.OK\n\n\n" ]
[ 0 ]
[]
[]
[ "flask_restful", "keyword_argument", "python", "url" ]
stackoverflow_0074632464_flask_restful_keyword_argument_python_url.txt
Q: How to make Faster API calls in Python I am trying to read Indian stock market data using API calls. For this example, I have used 10 stocks. My current program is: First I define the Function: def get_prices(stock): start_unix = 1669794745 end_unix = start_unix + 1800 interval = 1 url = 'https://...
How to make Faster API calls in Python
I am trying to read Indian stock market data using API calls. For this example, I have used 10 stocks. My current program is: First I define the Function: def get_prices(stock): start_unix = 1669794745 end_unix = start_unix + 1800 interval = 1 url = 'https://priceapi.moneycontrol.com/techCharts/indianM...
[ "When scraping data from the web, most of the type is typically spent on waiting for server responses. In order to issue a large amount of queries and to get responses as fast as possible, issuing multiple queries in parallel is the right approach. To be as efficient as possible, you have to find the right balance ...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074632975_python_python_3.x.txt
Q: Subclassing module to deprecate a module level variable/constant? Assuming I have a module and I want to deprecate something in that module. That's very easy for functions, essentially this can be done using a decorator: import warnings def deprecated(func): def old(*args, **kwargs): warnings.warn("Th...
Subclassing module to deprecate a module level variable/constant?
Assuming I have a module and I want to deprecate something in that module. That's very easy for functions, essentially this can be done using a decorator: import warnings def deprecated(func): def old(*args, **kwargs): warnings.warn("That has been deprecated, use the new features!", DeprecationWarning) ...
[ "PEP 562 has been accepted and will be added in Python 3.7 (not released at the time of writing) and that will allow (or at least greatly simplify) deprecating module level constants.\nIt works by adding a __getattr__ function in the module. For example in this case:\nimport builtins\nimport warnings\n\ndef __getat...
[ 3, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0045744919_module_python.txt
Q: How to access a dataframe column with no name Here is the dataframe I am trying to access its columns (team and player) PSxG GA league season game team player ITA-Serie A 2223 2022-08-14 Fiorentina-Cremonese Cremonese Ionuț Radu 2.5 3 3ed8bdff Fiorentina Pierluigi Go...
How to access a dataframe column with no name
Here is the dataframe I am trying to access its columns (team and player) PSxG GA league season game team player ITA-Serie A 2223 2022-08-14 Fiorentina-Cremonese Cremonese Ionuț Radu 2.5 3 3ed8bdff Fiorentina Pierluigi Gollini 1.2 2 3ed8bdff Here is the output of the...
[ "Instead of .iloc, you can use .iat.\nIn the example you provided, the column number for team is 3 and for player is 4, so you can access the column elements like this as shown below.\nfor example\n\nyou have 10 rows in your dataFrame\nname of your dataFrame is data_table\n\n\nfor i in range(10):\n print(data_ta...
[ 0 ]
[]
[]
[ "data_preprocessing", "dataframe", "pandas", "python" ]
stackoverflow_0074633035_data_preprocessing_dataframe_pandas_python.txt
Q: How to correctly use iterrows in a DataFrame I want to find out the highest price of a specified house type, "mansion". instead of using df[df["h_type"] == "mansion"]["h_price"].max() , i want to try something new. I use iterrows() method, but it does not work out as expected. First, I defind a price function atte...
How to correctly use iterrows in a DataFrame
I want to find out the highest price of a specified house type, "mansion". instead of using df[df["h_type"] == "mansion"]["h_price"].max() , i want to try something new. I use iterrows() method, but it does not work out as expected. First, I defind a price function attempting to find out the highest price (this works) ...
[ "What you want is to groupby each h_type and then get the max h_price like below.\ndf_grouped = df[['h_type','h_price'] ].groupby(['h_type']).max()\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074632749_python.txt
Q: Set value as key and a list of values as value in Python I have a big dictionary (250k+ keys) like this: dict = { 0: [apple, green], 1: [banana, yellow], 2: [apple, red], 3: [apple, brown], 4: [kiwi, green], 5: [kiwi, brown], ... } Goal to achie...
Set value as key and a list of values as value in Python
I have a big dictionary (250k+ keys) like this: dict = { 0: [apple, green], 1: [banana, yellow], 2: [apple, red], 3: [apple, brown], 4: [kiwi, green], 5: [kiwi, brown], ... } Goal to achieve: 1. I want a new dictionary with the first value of the lis...
[ "You can use a defaultdict to group the items by the first entry\nfrom collections import defaultdict\n\nfruits = defaultdict(list)\n\ndata = {\n 0: ['apple', 'green'],\n 1: ['banana', 'yellow'],\n 2: ['apple', 'red'],\n 3: ['apple', 'brown'],\n 4: ['kiwi', 'green'],\n 5: ['kiwi', 'brown']\n}\n\nfor _, v in d...
[ 1 ]
[]
[]
[ "dictionary", "dictionary_comprehension", "python" ]
stackoverflow_0074632369_dictionary_dictionary_comprehension_python.txt
Q: Simplest way to publish over Zeroconf/Bonjour? I've got some apps I would like to make visible with zeroconf. Is there an easy scriptable way to do this? Is there anything that needs to be done by my network admin to enable this? Python or sh would be preferrable. OS-specific suggestions welcome for Linux and O...
Simplest way to publish over Zeroconf/Bonjour?
I've got some apps I would like to make visible with zeroconf. Is there an easy scriptable way to do this? Is there anything that needs to be done by my network admin to enable this? Python or sh would be preferrable. OS-specific suggestions welcome for Linux and OS X.
[ "pybonjour doesn't seem to be actively maintained. I'm using python-zeroconf.\npip install zeroconf\n\nHere is an excerpt from a script I use to announce a Twisted-Autobahn WebSocket to an iOS device:\nfrom zeroconf import ServiceInfo, Zeroconf\n\nclass WebSocketManager(service.Service, object):\n ws_service_nam...
[ 11, 10, 7, 2, 1 ]
[]
[]
[ "bonjour", "python", "zeroconf" ]
stackoverflow_0001916017_bonjour_python_zeroconf.txt
Q: Trouble with injecting Callable I'm using python-dependency-injector. I tried this code and it worked perfectly: https://python-dependency-injector.ets-labs.org/providers/callable.html that page also mentioned next: Callable provider handles an injection of the dependencies the same way like a Factory provider. ...
Trouble with injecting Callable
I'm using python-dependency-injector. I tried this code and it worked perfectly: https://python-dependency-injector.ets-labs.org/providers/callable.html that page also mentioned next: Callable provider handles an injection of the dependencies the same way like a Factory provider. So I went and wrote this code: import...
[ "The method passlib.hash.sha256_crypt.verify requires two positional arguments, secret and hash as shown here: https://passlib.readthedocs.io/en/stable/lib/passlib.hash.sha256_crypt.html\nBecause you're injecting an attribute of the Container, the DI framework must create an instance of this to inject it into the b...
[ 0, 0 ]
[]
[]
[ "dependency_injection", "python" ]
stackoverflow_0073522651_dependency_injection_python.txt
Q: Mean of selected rows of a matrix with Numpy and performance I need to compute the mean of a 2D across one dimension. Here I keep all rows: import numpy as np, time x = np.random.random((100000, 500)) t0 = time.time() y = x.mean(axis=0) # y.shape is (500,) as expected print(time.time() - t0) # 36 milliseco...
Mean of selected rows of a matrix with Numpy and performance
I need to compute the mean of a 2D across one dimension. Here I keep all rows: import numpy as np, time x = np.random.random((100000, 500)) t0 = time.time() y = x.mean(axis=0) # y.shape is (500,) as expected print(time.time() - t0) # 36 milliseconds When I filter and select some rows, I notice it is 8 times sl...
[ "(Sorry for first version of this answer)\nProblem is with creation of new array which takes a lot of time compared to calculating mean.\nI tried to optimize whole process using numba:\nimport numba\n@numba.jit('float64[:](float64[:, :], int32[:])')\ndef selective_mean(array, indices):\n sum = np.zeros(array.sha...
[ 1, 1, 1 ]
[]
[]
[ "mean", "numpy", "performance", "python" ]
stackoverflow_0074628642_mean_numpy_performance_python.txt
Q: python: have a default value when formatting strings (str.format() method) Is there a way to have a default value when doing string formatting? For example: s = "Text {0} here, and text {1} there" s.format('foo', 'bar') What I'm looking for is setting a default value for a numbered index, so that it can be skippe...
python: have a default value when formatting strings (str.format() method)
Is there a way to have a default value when doing string formatting? For example: s = "Text {0} here, and text {1} there" s.format('foo', 'bar') What I'm looking for is setting a default value for a numbered index, so that it can be skipped in the placeholder, e.g. something like this: s = "Text {0:'default text'} her...
[ "You can't do it within the format string itself, but using named placeholders, you can pass a dict-like thing to .format_map that contains a generic default value, or combine a dict of defaults for each value with the provided dict to override individually.\nExamples:\n\nWith a defaulting dict-like thing:\nfrom co...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "string" ]
stackoverflow_0074631840_python_python_3.x_string.txt
Q: Visual Studio Code does not show variable color or problems anymore About 4 days ago, while I was doing my schoolwork I noticed that the variable colors don't turn blue like they used to, and it does not show me problems in the code anymore. I am a beginner in coding, so the "not showing problem" thing is a big is...
Visual Studio Code does not show variable color or problems anymore
About 4 days ago, while I was doing my schoolwork I noticed that the variable colors don't turn blue like they used to, and it does not show me problems in the code anymore. I am a beginner in coding, so the "not showing problem" thing is a big issue for me. Would anyone know how can I get them back? Also, this problem...
[ "Maybe you need to install a vs code plug-in called pylance and make sure that it is not disabled in your workspace.\n", "uninstall Visual Studio Code\nand delete user\\AppData\\Roaming\\Code (windows)\nand the install it again,\nmay be it's due to a buggy extension or some setting\n", "You can follow the pictu...
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0071935260_python_visual_studio_code.txt
Q: How to deactivate a QVideoProbe? According to the docs "If source is zero, this probe will be deactivated" But calling setSource(0) gives the following exception: Exception has occurred: TypeError 'PySide2.QtMultimedia.QVideoProbe.setSource' called with wrong argument types: PySide2.QtMultimedia.QVideoProbe.setS...
How to deactivate a QVideoProbe?
According to the docs "If source is zero, this probe will be deactivated" But calling setSource(0) gives the following exception: Exception has occurred: TypeError 'PySide2.QtMultimedia.QVideoProbe.setSource' called with wrong argument types: PySide2.QtMultimedia.QVideoProbe.setSource(int) Supported signatures: PyS...
[ "The source object can be cleared like this:\nself.probe.setSource(None)\n\nIn C++, passing zero to a pointer argument means the function will recieve a null pointer. Since this can't be done explicitly in Python, PySide/PyQt allow None to be passed instead.\nGenerally speaking, it's always advisable to consult the...
[ 2 ]
[]
[]
[ "pyqt5", "pyside2", "python", "qtmultimedia", "video" ]
stackoverflow_0074631000_pyqt5_pyside2_python_qtmultimedia_video.txt
Q: How do I run a while loop in tkinter window while it is open? I have a while loop that I want to run while the Tkinter window is open but the Tkinter window doesn't even open when the while loop is running. This is a problem since my while loop is an infinite loop. I basically want to create a programme that provi...
How do I run a while loop in tkinter window while it is open?
I have a while loop that I want to run while the Tkinter window is open but the Tkinter window doesn't even open when the while loop is running. This is a problem since my while loop is an infinite loop. I basically want to create a programme that provides the users with new choices after a previous choice is selected ...
[ "The mainloop() is the main reason for the window to be displayed continuously. When the while loop is running, the mainloop() does not get executed until the while loop ends. And because in your case the while loop never ends, the code including the mainloop() keeps waiting for its turn to be executed.\nTo overcom...
[ 1, 0, 0 ]
[]
[]
[ "python", "python_3.x", "tkinter", "user_interface", "while_loop" ]
stackoverflow_0061016789_python_python_3.x_tkinter_user_interface_while_loop.txt
Q: How to create a function that change is_active=False to True? How to create a function that change is_active=False to True? The case is that I want to create a function that change the value in an user case from is_active=False to is_active=True. At my final point I want to create "an email verification" when some...
How to create a function that change is_active=False to True?
How to create a function that change is_active=False to True? The case is that I want to create a function that change the value in an user case from is_active=False to is_active=True. At my final point I want to create "an email verification" when someone registered. If someone registered on my website, he receive an ...
[ "I think what you want is a function something like this\ndef register_confirm(request, activation_key):\n\nif request.user.is_authenticated():\n \n HttpResponseRedirect('/home')\n\nuser_profile = get_object_or_404(UserProfile, \n activation_key=activation_key)\n\nif user_profile.key_expires < ...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "django_views", "python", "reactjs" ]
stackoverflow_0074632893_django_django_rest_framework_django_views_python_reactjs.txt
Q: openpyxl error raise ValueError('Min value is {0}'.format(self.min)) in opening heavy file with formatting I'm trying to use openpyxl for the first time on a very heavy file, that happens to be over 20 500 Ko, has a lot of formatting and a VBA macro. My code keeps returning the following error: File " \Anaconda3\l...
openpyxl error raise ValueError('Min value is {0}'.format(self.min)) in opening heavy file with formatting
I'm trying to use openpyxl for the first time on a very heavy file, that happens to be over 20 500 Ko, has a lot of formatting and a VBA macro. My code keeps returning the following error: File " \Anaconda3\lib\site-packages\openpyxl\styles\alignment.py", line 52, in __init__ self.relativeIndent = relativeIndent ...
[ "The traceback says that there is a problem with the Alignment definition in the workbook's stylesheet. openpyxl follows the OOXML specification very closely to minimise unpleasant surprises later, this is why it tends to raise exceptions or give warnings rather than let things pass.\nFor more details we'll need to...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "openpyxl", "python", "valueerror", "vba", "xlsm" ]
stackoverflow_0066499849_openpyxl_python_valueerror_vba_xlsm.txt