content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Why does Tkinter image not show up if created in a function? This code works: import tkinter root = tkinter.Tk() canvas = tkinter.Canvas(root) canvas.grid(row = 0, column = 0) photo = tkinter.PhotoImage(file = './test.gif') canvas.create_image(0, 0, image=photo) root.mainloop() It shows me the image. Now, this c...
Why does Tkinter image not show up if created in a function?
This code works: import tkinter root = tkinter.Tk() canvas = tkinter.Canvas(root) canvas.grid(row = 0, column = 0) photo = tkinter.PhotoImage(file = './test.gif') canvas.create_image(0, 0, image=photo) root.mainloop() It shows me the image. Now, this code compiles but it doesn't show me the image, and I don't know wh...
[ "The variable photo is a local variable which gets garbage collected after the class is instantiated. Save a reference to the photo, for example:\nself.photo = tkinter.PhotoImage(...)\n\nIf you do a Google search on \"tkinter image doesn't display\", the first result is this:\nWhy do my Tkinter images not appear? (...
[ 108, 6, 6, 1, 0 ]
[]
[]
[ "image", "python", "tkinter", "tkinter_canvas" ]
stackoverflow_0016424091_image_python_tkinter_tkinter_canvas.txt
Q: How to shorten a repetitive part of basic python code? I am new to coding, and just started learning Python last week. I made this Powerball number generator to practice: import random print(random.randrange(1, 70)) import random print(random.randrange(1,70)) import random print(random.randrange(1, 70)) impo...
How to shorten a repetitive part of basic python code?
I am new to coding, and just started learning Python last week. I made this Powerball number generator to practice: import random print(random.randrange(1, 70)) import random print(random.randrange(1,70)) import random print(random.randrange(1, 70)) import random print(random.randrange(1,70)) import random pri...
[ "To start, you only need to import random once before you use it for the first time. That should shorten it to this:\nimport random\n\nprint(random.randrange(1, 70))\n\nprint(random.randrange(1,70))\n\nprint(random.randrange(1, 70))\n\nprint(random.randrange(1,70))\n\nprint(random.randrange(1, 70))\n\nprint(random....
[ 1, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0074303974_python_random.txt
Q: Handle specific exception from python package I would like to handle the following Exception from py_vollib/py_lets_be_rational in specific way. py_lets_be_rational.exceptions.BelowIntrinsicException: The volatility is below the intrinsic value. Tried this without success: from py_vollib.black.implied_volatility ...
Handle specific exception from python package
I would like to handle the following Exception from py_vollib/py_lets_be_rational in specific way. py_lets_be_rational.exceptions.BelowIntrinsicException: The volatility is below the intrinsic value. Tried this without success: from py_vollib.black.implied_volatility import implied_volatility as impl_vol_b from py_let...
[ "Looking at the implementation, you're missing the period at the end of the sentence:\nif str(e) != 'The volatility is below the intrinsic value.':\n\nI don't see the point in this check because that will always be the message the exception is created with.\n" ]
[ 1 ]
[ "check the inputs provided by you in the formula.\nyou must have entered the wrong value of strike price\n" ]
[ -1 ]
[ "exception", "exception_handling", "python", "python_3.7" ]
stackoverflow_0052309471_exception_exception_handling_python_python_3.7.txt
Q: Scraping data through changing Xpaths I can't figure out how to scrape data, I am trying to scrape the product name, price and other information from the website, the product names are easy to access as they have similar xpath with only one tag that changes but for the prices the there are multiple changes to the ...
Scraping data through changing Xpaths
I can't figure out how to scrape data, I am trying to scrape the product name, price and other information from the website, the product names are easy to access as they have similar xpath with only one tag that changes but for the prices the there are multiple changes to the tags.Is there an alternative to how I can s...
[ "You no need to use hardcoded loop, rather identify unique xpath to identify parent element and then child element. Only ratings not avail for every product where you can use try..except block.\nproduct_name=[]\nproduct_price=[]\nproduct_rating=[]\nproduct_url=[]\ndriver.get('https://www.cdiscount.com/bricolage/cli...
[ 2 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "web_scraping", "xpath" ]
stackoverflow_0074303827_beautifulsoup_python_selenium_web_scraping_xpath.txt
Q: trying to use getter and setter in a list of dictionaries functions in python but I get the same error I have a simple program that has to delete some values that are between 2 given "days". For example, I have this list of dicts: lst=[{"day": 1, "sum": 25, "type": 'in'}, {"day": 2, "sum": 55, "type": 'in'}, {"day...
trying to use getter and setter in a list of dictionaries functions in python but I get the same error
I have a simple program that has to delete some values that are between 2 given "days". For example, I have this list of dicts: lst=[{"day": 1, "sum": 25, "type": 'in'}, {"day": 2, "sum": 55, "type": 'in'}, {"day": 3, "sum": 154, "type": 'out'}, {"day": 4, "sum": 99, "type": 'in'}] and I wanna delete the values with "...
[ "Iterate over the list using a forloop if you want to get rid of the index\nnew_transactions_list = []\nfor elem in lst:\n if not 1 <= elem[\"day\"] <= 3 :\n new_transactions_list.append(elem)\n \nprint(new_transactions_list)\n\nOutput\n[{'day': 4, 'sum': 99, 'type': 'in'}]\n \n\n", "If you are de...
[ 1, 0 ]
[]
[]
[ "dictionary", "error_handling", "list", "python" ]
stackoverflow_0074301836_dictionary_error_handling_list_python.txt
Q: How to use gcloud and python in one ci/cd pipeline I'm new in Google Cloud Artifact Registry and I managed to publish a module to there. However, now I want to automate this by putting it in a git pipeline but unfortunately I can't get this to work. I Think the problem is that I have to use 2 diffrent images (pyth...
How to use gcloud and python in one ci/cd pipeline
I'm new in Google Cloud Artifact Registry and I managed to publish a module to there. However, now I want to automate this by putting it in a git pipeline but unfortunately I can't get this to work. I Think the problem is that I have to use 2 diffrent images (python and google/cloud-sdk) but you can't use this in one s...
[ "As commented by @destiny, Error: gcloud: command not found means cloud-sdk is not installed on your machine.\nTry using google/cloud-sdk:latest tag which includes cloud cli latest image.\nBefore that make sure you have installed the Google Cloud CLI Docker image.\nTo install Cloud cli image from docker follow bel...
[ 0 ]
[]
[]
[ "gcloud", "gitlab_ci", "google_artifact_registry", "python" ]
stackoverflow_0074279221_gcloud_gitlab_ci_google_artifact_registry_python.txt
Q: Generate weighted edges from duplicate list of set in networkx python So, i want to create weighted graph with data in list of set like this : temp_comb_test = [{'AN', 'TA'}, {'TA', 'DP'},{'AS','TA'},{'HS','AS'},{'HS','TA'},{'TA','AA'},{'LS','TA'}] Those weighted, is generate from duplicate edges. Using set() typ...
Generate weighted edges from duplicate list of set in networkx python
So, i want to create weighted graph with data in list of set like this : temp_comb_test = [{'AN', 'TA'}, {'TA', 'DP'},{'AS','TA'},{'HS','AS'},{'HS','TA'},{'TA','AA'},{'LS','TA'}] Those weighted, is generate from duplicate edges. Using set() type of data is simply because in set, (A, B) and (B, A) is equal/duplicate da...
[ "You might want to use collections.Counter, which will count the occurrences of specific keys in an iterable:\nfrom collections import Counter\nfrom networkx import Graph\n\n# create edge counts\nt = [{'A', 'B'}, {'C', 'D'}, {'B', 'A'}]\n# note that Counter does not use sets, so change data to tuples\nc = Counter(m...
[ 1 ]
[]
[]
[ "edges", "graph", "networkx", "python", "weighted_graph" ]
stackoverflow_0074303387_edges_graph_networkx_python_weighted_graph.txt
Q: Is there a way to pick a random number of elements from a list with independent probabilities in Python? I wish to pick a random number of elements (can be 0 too) from a list in python. The probability of choosing any element is independent of others. For example: example_list = ['Apple', 'Orange', 'Kiwi', 'Mango'...
Is there a way to pick a random number of elements from a list with independent probabilities in Python?
I wish to pick a random number of elements (can be 0 too) from a list in python. The probability of choosing any element is independent of others. For example: example_list = ['Apple', 'Orange', 'Kiwi', 'Mango'] example_probabilties = [6, 9, 1, 4] I wish to pick out a random number of fruits, where the element 'Apple'...
[ "You can do it like this:\nimport random\n\n\nexample_list = ['Apple', 'Orange', 'Kiwi', 'Mango']\nexample_probabilties = [6, 9, 1, 4]\n\nchoices_with_None = (random.choices([example, None], [P, 100 - P])[0] for example, P in zip(example_list, example_probabilties))\nchoices = [c for c in choices_with_None if c is ...
[ 0, 0, 0 ]
[]
[]
[ "probability", "python" ]
stackoverflow_0074302420_probability_python.txt
Q: Memory consumption in python comparision I have a doubt like why memory consumption in python is high when compared to other languages like C/C++ . size of int in python is 28 bytes in python 3+ whereas in C its just 4 bytes . Python : import sys print(sys.getsizeof(1)) Output : 28 bytes C: // Driver code int...
Memory consumption in python comparision
I have a doubt like why memory consumption in python is high when compared to other languages like C/C++ . size of int in python is 28 bytes in python 3+ whereas in C its just 4 bytes . Python : import sys print(sys.getsizeof(1)) Output : 28 bytes C: // Driver code int main() { // Print the sizeof integer ...
[ "It's not the same data type. It's a related data type that happens to have the same name. For instance, C ints are only go up to 32767 (more in your case, but that's not guaranteed). Python ints are limited only by your memory, so I can do 2 ** 999999999, for instance. This ability, along with a reference count an...
[ 0 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0074304009_memory_python.txt
Q: beautiful soup find_all() exception i'm using beautiful soup Data = soup.find_all('td') which returns to me everything with the tag. is there a way for me to add an exception to not include the tag if colspan=7? cause that's the only indicator all the td tags are classless :) Thank you! A: I'm not very sure if i...
beautiful soup find_all() exception
i'm using beautiful soup Data = soup.find_all('td') which returns to me everything with the tag. is there a way for me to add an exception to not include the tag if colspan=7? cause that's the only indicator all the td tags are classless :) Thank you!
[ "I'm not very sure if it going works, but you can try it. You should filter first all \"td\" and after that, filter all collspan=7 . Please try using this:\nList_One=[]\nData = soup.find_all('td')\nfor x in Data:\n if not \"colspan=7\" in x.attrs:\n List_One.append(x)\nprint(List_One)\n\n", "Instead off...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074303804_beautifulsoup_python.txt
Q: List of tuples in String format to List of tuples Conversion I have a list of tuples where tuple is in string format data_list = ["('https://www.test.org/', 'testing', 'test1', 'test1')", "('https://testing2.com/', 'testing', 'test2', 'test2')"] To convert this to list of tuples I am using the following code for ...
List of tuples in String format to List of tuples Conversion
I have a list of tuples where tuple is in string format data_list = ["('https://www.test.org/', 'testing', 'test1', 'test1')", "('https://testing2.com/', 'testing', 'test2', 'test2')"] To convert this to list of tuples I am using the following code for val in data_list: valx = ast.literal_eval(val) But some time ...
[ "How about replace it with None? (In my example with eval instead of ast.literal_eval:\ndata_list = [\"('https://www.test.org/', 'testing', Undefined, 'test1')\", \"('https://testing2.com/', 'testing', 'test2', 'test2')\"]\n\nfor val in data_list:\n val = val.replace('Undefined', 'None')\n valx = eval(val)\n ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074304180_python.txt
Q: Flask based application : CloudFlare Gateway Timeout error Because the model prediction in my ML application takes 150 seconds to respond, I received gateway Timeout error. Is there a method to render something while the model prediction process running to avoid the aforementioned problem. A: You likely want you...
Flask based application : CloudFlare Gateway Timeout error
Because the model prediction in my ML application takes 150 seconds to respond, I received gateway Timeout error. Is there a method to render something while the model prediction process running to avoid the aforementioned problem.
[ "You likely want your API endpoint to kick off a background task that computes the model if it takes >150seconds to finish. You could also have another endpoint that gets the status of this job which your frontend can poll and then receive results from when the job is finished.\nThis is just one strategy that you c...
[ 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074304179_flask_python.txt
Q: CS50 Python Fuel Gauge I'm facing a problem with Fuel Gauge CS50's. My code's only passing through half of the requirements. Can someone help me with this one? https://cs50.harvard.edu/python/2022/psets/3/fuel/#demo My result while trying to check: :) fuel.py exists :) input of 3/4 yields output of 75% - OK :) i...
CS50 Python Fuel Gauge
I'm facing a problem with Fuel Gauge CS50's. My code's only passing through half of the requirements. Can someone help me with this one? https://cs50.harvard.edu/python/2022/psets/3/fuel/#demo My result while trying to check: :) fuel.py exists :) input of 3/4 yields output of 75% - OK :) input of 1/3 yields output of...
[ "The problem is that you don't validate the input - the user can enter whatever they want and you just take their word for it that they've entered the correct thing:\nfraction = input(\"Fuel Fraction: \")\n# No validation logic before you try to split. What if they forgot to include the /?\nx, y = fraction.split('/...
[ 0 ]
[]
[]
[ "cs50", "python" ]
stackoverflow_0074304216_cs50_python.txt
Q: pip installing Azure cli is taking forever. How can i speed this up? Got the following requirements.txt which i am pip installing. azure-cli is taking forever, longer then 7 min just to install. how can i speed this up? azureml-train-core==1.47.0 azureml-sdk==1.47.0 azure-storage-blob==12.13.1 matplotlib==3.6.1 nu...
pip installing Azure cli is taking forever. How can i speed this up?
Got the following requirements.txt which i am pip installing. azure-cli is taking forever, longer then 7 min just to install. how can i speed this up? azureml-train-core==1.47.0 azureml-sdk==1.47.0 azure-storage-blob==12.13.1 matplotlib==3.6.1 numpy==1.23.4 pandas== 1.5.1 pathlib==1.0.1 python-dotenv==0.14.0 pytz==2020...
[ "Since azure-cli has a lot of dependent packages , nearly 40 so the download will take a huge time to download.\nSteps to improve :\n\nUsing poetry packaged .whl file , wheel installation are faster.\nHaving a high speed internet connection.\nUpgrade your pip to latest version.\npip --disable-pip-version-check inst...
[ 1 ]
[]
[]
[ "azure_cli", "python", "requirements.txt" ]
stackoverflow_0074303984_azure_cli_python_requirements.txt.txt
Q: How to add the option of restarting a guessing game? IN PYTHON from random import randint num = randint (0,50) guess = int(input ("Enter your guess number: ")) attempts = 1 while num != guess and attempts <10: if guess > 50 or guess < 0: print ("Please enter an integer between 0 and 50") elif g...
How to add the option of restarting a guessing game? IN PYTHON
from random import randint num = randint (0,50) guess = int(input ("Enter your guess number: ")) attempts = 1 while num != guess and attempts <10: if guess > 50 or guess < 0: print ("Please enter an integer between 0 and 50") elif guess > num: print ("The number to guess is LOWER") elif ...
[ "This works. I avoided using functions in case you haven't covered than in class yet. But in the future using a function would be a good improvement.\nfrom random import randint\n\n# If is true the game will play\nkeep_playing = True\n\n# While keep_playing is true the game will continue\n# When the user finishes a...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074303853_python.txt
Q: How to change sub element in lxml My xml file: <?xml version='1.0' encoding='UTF-8'?> <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <CstmrCdtTrfInitn> <CtgyPurp>. // ---->i want to change this tag <Cd>SALA</Cd> //----->...
How to change sub element in lxml
My xml file: <?xml version='1.0' encoding='UTF-8'?> <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <CstmrCdtTrfInitn> <CtgyPurp>. // ---->i want to change this tag <Cd>SALA</Cd> //-----> no change </CtgyPurp> // ---...
[ "Something like this should work - note the treatment of namespaces:\nfrom lxml import etree\nctg = \"\"\"[your xml above\"]\"\"\"\n\ndoc = etree.XML(ctg.encode())\nns = {\"xx\": \"urn:iso:std:iso:20022:tech:xsd:pain.001.001.03\"}\ntarget = doc.xpath('//xx:CtgyPurp',namespaces=ns)[0]\ntarget.tag = \"newName\"\nprin...
[ 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0074303289_lxml_python.txt
Q: Matplotlib cannot find basic fonts I am using matplotlib version 2.0.0 on Python 3 in a miniconda virtual environment. I am working on a unix scientific computing cluster where I don't have root privileges. I am generally executing python code through an ipython notebook. If I do a basic command such as: import ma...
Matplotlib cannot find basic fonts
I am using matplotlib version 2.0.0 on Python 3 in a miniconda virtual environment. I am working on a unix scientific computing cluster where I don't have root privileges. I am generally executing python code through an ipython notebook. If I do a basic command such as: import matplotlib.pyplot as plt plt.scatter([1,5]...
[ "To get it to work, I had to combine the two current top answers. Here's what worked for me:\n$ sudo apt install msttcorefonts -qq\n$ rm ~/.cache/matplotlib -rf\n\n", "I had this exact same problem on a Vagrant VM running Ubuntu Xenial 64-bit. No matter how many fonts I had already installed, matplotlib was havin...
[ 68, 35, 25, 16, 9, 9, 9, 3, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "matplotlib", "miniconda", "python", "truetype" ]
stackoverflow_0042097053_matplotlib_miniconda_python_truetype.txt
Q: WMS get optimal size ratio upon defining bounding box I'm connecting with a WMS and saving a cropped map. Ideally I would like to just define the bounding box (bbox) and define either the height or width of the output image in pixels, to get the correct height/width ratio. However, I'm getting errors if I define t...
WMS get optimal size ratio upon defining bounding box
I'm connecting with a WMS and saving a cropped map. Ideally I would like to just define the bounding box (bbox) and define either the height or width of the output image in pixels, to get the correct height/width ratio. However, I'm getting errors if I define the height or width. It's working when I define the size of ...
[ "I don't know how generic this answer is, but it looks like the correct width/height ratio can be read from the bounding box of the WMS. Correcting the size of the output image with this ratio will lead to the desired result\n", "Aspect ratio is Width/Height, so from the bounding box you get:\nHeight = NorthMax -...
[ 0, 0 ]
[]
[]
[ "python", "wms" ]
stackoverflow_0058010615_python_wms.txt
Q: list of name and path of files in a directory and subdirectory where one or more subdir have a point in the middle python I'm trying to get path and filename, from a directory, including those ones inside the subdirectories. The problem is that some subfolders have one or more points in the name. So when I execut...
list of name and path of files in a directory and subdirectory where one or more subdir have a point in the middle python
I'm trying to get path and filename, from a directory, including those ones inside the subdirectories. The problem is that some subfolders have one or more points in the name. So when I execute this code listaFile=glob.glob('c:\test\ID_1'+/**/*.*',recursive= True) I get c:\test\ID_1\fil.e1.txt c:\test\ID_1\fil.e2.do...
[ "You need to filter it out checking if it's a file or folder. An easy way would be to use the pathlib instead of glob directly. Example below.\nlistaFile = [str(path) for path in pathlib.Path(r\"c:\\test\\ID_1\").rglob(\"*.*\") if path.is_file()]\n\n" ]
[ 1 ]
[]
[]
[ "glob", "python" ]
stackoverflow_0074304231_glob_python.txt
Q: How can i get value from "Span id" via BeautifulSoup in Python? https://www.isyatirim.com.tr/tr-tr/analiz/hisse/Sayfalar/sirket-karti.aspx?hisse=SASA Above this link, there is a value of a stock price highlighted with relatively big green text. I want to extract it but I can't get that value clearly. I only need t...
How can i get value from "Span id" via BeautifulSoup in Python?
https://www.isyatirim.com.tr/tr-tr/analiz/hisse/Sayfalar/sirket-karti.aspx?hisse=SASA Above this link, there is a value of a stock price highlighted with relatively big green text. I want to extract it but I can't get that value clearly. I only need to get the value that says "136,10". Does anyone know how can I get it...
[ "try:\n value = soup.find('span', {'id': 'xyz'}).get('value')\nexcept Exception as e:\n print(\"Got unhandled exception %s\" % str(e))\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "json", "python", "python_requests" ]
stackoverflow_0074304204_beautifulsoup_html_json_python_python_requests.txt
Q: If condition giving worng result opposite result to its condition If the condition gives worng result opposite result to its condition. here I want to print the links that do not start with youtube.com or include youtube.com but its prints the full list fetchurl = ["https://www.smithsonianmag.com/science-nature/ho...
If condition giving worng result opposite result to its condition
If the condition gives worng result opposite result to its condition. here I want to print the links that do not start with youtube.com or include youtube.com but its prints the full list fetchurl = ["https://www.smithsonianmag.com/science-nature/how-wolves-really-became-dogs-180970014/", "https://www.youtube.com/watch...
[ "If you want to print all \"links that not start with youtube.com or include youtube.com \"\nfor url in fetchurl:\n if \"https://www.youtube.com/\" not in url:\n print(url)\n\nThe above may not exclude everything. If so try this:\nfor url in fetchurl:\n if \"youtube.com\" not in url:\n print(url...
[ 2 ]
[]
[]
[ "for_loop", "if_statement", "python" ]
stackoverflow_0074304281_for_loop_if_statement_python.txt
Q: Is there a way to automate javascript functions on a web brower with powerbi tables? I have a table in powerbi that I need to save once daily. If I hover above the table, and click on the ... menu, I can see it creates a button element in HTML that allows me to save data to CSV file with Selenium However, in order...
Is there a way to automate javascript functions on a web brower with powerbi tables?
I have a table in powerbi that I need to save once daily. If I hover above the table, and click on the ... menu, I can see it creates a button element in HTML that allows me to save data to CSV file with Selenium However, in order to get this menu to appear in HTML, I need to call the javascript function that gets call...
[ "If you embed the report in a custom web page you can have a button that triggers the visual.ExportData Javascript API, EG https://playground.powerbi.com/en-us/dev-sandbox?showApi=reportExportVisualDataUnderlying\nBut that's an overly-complex and roundabout way to get data. Power BI has a direct API to get data fr...
[ 1 ]
[]
[]
[ "automation", "javascript", "powerbi", "python", "selenium" ]
stackoverflow_0074303967_automation_javascript_powerbi_python_selenium.txt
Q: Python conditionals without if statements I am trying to complete a homework exercise for the following and I am stumped: Create a variable called mark and assign it the value 65. Then write a series of if ... elif ... else statements to assign a new variable a grade such that marks below 50 produce "Fail", from ...
Python conditionals without if statements
I am trying to complete a homework exercise for the following and I am stumped: Create a variable called mark and assign it the value 65. Then write a series of if ... elif ... else statements to assign a new variable a grade such that marks below 50 produce "Fail", from 50 to 59 produce "Pass", from 60 to 69 produce ...
[ "Your current structure is likely the most readable and explicit if using pure Python. Note that you can simplify by only checking one bound as your intervals are successive and non-overlapping.\nmark = 50\nif mark > 69:\n print(mark, \"marks is a Distinction\")\nelif mark >= 60:\n print(mark, \"marks is a Me...
[ 5, 3, 1, 1 ]
[]
[]
[ "conditional_statements", "python" ]
stackoverflow_0074304076_conditional_statements_python.txt
Q: Convert an 1D list into a 2D list of pairs I have the list: [0, 15, 19, 26, 34, 62] How would I go about converting it into the following? [[0, 15], [19, 26], [34, 62]] A: You can use numpy: import numpy as np arr = [0, 15, 19, 26, 34, 62] np.reshape(arr, (-1, 2)) output: array([[ 0, 15], [19, 26], ...
Convert an 1D list into a 2D list of pairs
I have the list: [0, 15, 19, 26, 34, 62] How would I go about converting it into the following? [[0, 15], [19, 26], [34, 62]]
[ "You can use numpy:\nimport numpy as np\n\narr = [0, 15, 19, 26, 34, 62]\nnp.reshape(arr, (-1, 2))\n\noutput:\narray([[ 0, 15],\n [19, 26],\n [34, 62]])\n\n", "list = [0, 15, 19, 26, 34, 62]\n\nnew_list = []\nfor i in range(0, len(list), 2):\n new_list.append([list[i], list[i+1]])\n\n", "A simple...
[ 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074304405_list_python.txt
Q: How to write Django query to grab all objects in descending order according to two number fields? I'm using Django. i'm trying to write query according to the top rated products. i have product table. as you can see below. class Product(models.Model): user = models.ForeignKey(User, verbose_name=_("Owner"), on_...
How to write Django query to grab all objects in descending order according to two number fields?
I'm using Django. i'm trying to write query according to the top rated products. i have product table. as you can see below. class Product(models.Model): user = models.ForeignKey(User, verbose_name=_("Owner"), on_delete=models.CASCADE) name = models.CharField(_("Name"), max_length=150,null=True) average_r...
[ "You should order in descending order, you can do this by prefixing the fieldname with a minus (-):\ndef get_all_top_rated_products(self):\n return self.filter(is_remove=False).order_by(\n '-average_rating', '-total_reviews'\n )\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0074304475_django_django_models_django_rest_framework_python_python_3.x.txt
Q: boolean expression from truth table I want to convert truth table to boolean expression : for example , this is the table a b a+b>0 0 1 1 1 0 1 I want to get the following output: (¬a ^b ) ∨ (a ^¬b) I am thinking about using replace, : if (value == str(0)): ...
boolean expression from truth table
I want to convert truth table to boolean expression : for example , this is the table a b a+b>0 0 1 1 1 0 1 I want to get the following output: (¬a ^b ) ∨ (a ^¬b) I am thinking about using replace, : if (value == str(0)): table= table(str(value), 'not x') else: ...
[ "How did you use SOPform? I get\n\n" ]
[ 0 ]
[]
[]
[ "boolean_logic", "logic", "python", "sympy", "truthtable" ]
stackoverflow_0074274947_boolean_logic_logic_python_sympy_truthtable.txt
Q: Python Enum inheritance fail to initialize base class I was plaing with python Enums and I wanted to DRY my code a little bit by moving the from_string method to parent class from enum import Enum class Base(Enum): def __str__(self): return self.value @staticmethod def from_string(string: str...
Python Enum inheritance fail to initialize base class
I was plaing with python Enums and I wanted to DRY my code a little bit by moving the from_string method to parent class from enum import Enum class Base(Enum): def __str__(self): return self.value @staticmethod def from_string(string: str): try: return Base[string] exc...
[ "Base[string] will call the __new__ dunder method of an enum.\n__new__ will then call the initializer of the enum class with the string as an argument (enum_member.__init__(*args)).\nSo in order to make your code work you should add another argument to your initializer\ndef __init__(self, value):\n super().__ini...
[ 1 ]
[]
[]
[ "inheritance", "python", "python_3.x" ]
stackoverflow_0074304023_inheritance_python_python_3.x.txt
Q: AttributeError: 'NoneType' object has no attribute 'find_all' when scraping table data I am currently having problems understanding following error: AttributeError: 'NoneType' object has no attribute 'find_all' It is referring to line 21 of the following code: import pandas as pd import requests from bs4 import Be...
AttributeError: 'NoneType' object has no attribute 'find_all' when scraping table data
I am currently having problems understanding following error: AttributeError: 'NoneType' object has no attribute 'find_all' It is referring to line 21 of the following code: import pandas as pd import requests from bs4 import BeautifulSoup url = 'https://www.dwd.de/DE/wetter/wetterundklima_vorort/hessen/offenbach/_nod...
[ "Your error comes from the fact that table is None after the soup.find line. You can confirm that by testing table is None, which will give you True. The reason is that the table you are looking for actually does not have an id. Instead, it is under a div tag that has such an id.\nHere is a quick fix of your code.\...
[ 1 ]
[]
[]
[ "beautifulsoup", "lxml", "pandas", "python" ]
stackoverflow_0074304434_beautifulsoup_lxml_pandas_python.txt
Q: Does optuna.integration.TorchDistributedTrial support multinode optimization? Does integration.TorchDistributedTrial support multinode optimization? I'm using Optuna on a SLURM cluster. Suppose I would like to do a distributed hyperparameter optimization using two nodes with two gpus each. Would submitting a scrip...
Does optuna.integration.TorchDistributedTrial support multinode optimization?
Does integration.TorchDistributedTrial support multinode optimization? I'm using Optuna on a SLURM cluster. Suppose I would like to do a distributed hyperparameter optimization using two nodes with two gpus each. Would submitting a script like pytorch_distributed_simple.py to multiple nodes yield expected results? I a...
[ "Apparently, Optuna does allow multiple Optuna processes to do distributed runs. Why wouldn't it :)\nBasically, run pytorch_distributed_simple.py on multiple nodes (I use SLURM for this) and make sure every subprocess calls the trial.report() method. Every node is now responsible for its own trial. Trials can use D...
[ 0 ]
[]
[]
[ "distributed", "optuna", "python", "pytorch" ]
stackoverflow_0074291634_distributed_optuna_python_pytorch.txt
Q: Is there a way to remove unused imports for Python in VS Code? I would really like to know if there is some Extension in Visual Studio Code or other means that could help identify and remove any unused imports. I have quite a large number of imports like this and it's getting close to 40 lines. I know some of them...
Is there a way to remove unused imports for Python in VS Code?
I would really like to know if there is some Extension in Visual Studio Code or other means that could help identify and remove any unused imports. I have quite a large number of imports like this and it's getting close to 40 lines. I know some of them aren't in use, the problem is removing them safely. from django.cor...
[ "Go to the User Settings json file and add the following:\n\"python.linting.pylintEnabled\": true,\n\"python.linting.pylintArgs\": [\n \"--enable=W0614\"\n]\n\nThis should remove the unused python imports automatically.\nMore suggestions here:\nHow can I check for unused import in many Python files?\n", "Inter...
[ 19, 13, 9, 8, 6, 6, 2, 1, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0053352135_python_visual_studio_code.txt
Q: How to search through multiple (thousands) of JSON files to find files with a specific value and then append those specific values to a new list I recently generated 10,000 images with a corresponding .json file. I generated 10 before I did the bigger collection and so I am trying to filter out or search through t...
How to search through multiple (thousands) of JSON files to find files with a specific value and then append those specific values to a new list
I recently generated 10,000 images with a corresponding .json file. I generated 10 before I did the bigger collection and so I am trying to filter out or search through the 10,000 json files, for a specific key value. here is one of the JSON files for example: { "name": "GrapeGrannys #1", "description": "Grannys wi...
[ "json_file[\"attributes\"] is a list so you can't access it like a dictionary.\nTry this:\nfor single_file in files:\n with open(single_file, 'r') as f:\n\n try:\n json_file = json.load(f)\n attrs = json_file[\"attributes\"]\n has_grape_city = any(attr[\"value\"] == \"GrapeCity\" for attr in attr...
[ 0 ]
[]
[]
[ "json", "python", "search" ]
stackoverflow_0074304241_json_python_search.txt
Q: Errors while getting data in rpy query I need to get nasapower data with use rpy. In documentation r code works in this way: library("nasapower") daily_ag <- get_power(community = "ag", lonlat = c(151.81, -27.48), pars = c("RH2M", "T2M", "PRECTOTCORR"), ...
Errors while getting data in rpy query
I need to get nasapower data with use rpy. In documentation r code works in this way: library("nasapower") daily_ag <- get_power(community = "ag", lonlat = c(151.81, -27.48), pars = c("RH2M", "T2M", "PRECTOTCORR"), dates = "1985-01-01", ...
[ "It seems like you need change lonlat=[151.81, -27.48] to lonlat = robjects.vectors.FloatVector([151.81, -27.48]) based on the documentation.\nhttps://rpy2.github.io/doc/v2.9.x/html/vector.html#rpy2.robjects.vectors.FloatVector\n", "You need to convert the list to FloatSexpVector:\n!pip3 install rpy2==3.5.1\nimpo...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x", "r", "rpy2" ]
stackoverflow_0074295985_python_python_3.x_r_rpy2.txt
Q: About the database used by netbox Is the database used by netbox PostgreSQL? Our virtual machine base information is stored inside netbox. We need Java to go to netbox to create VM information and to get VM information. But this does not guarantee transactivity. So we want to use Java to connect to netbox's databa...
About the database used by netbox
Is the database used by netbox PostgreSQL? Our virtual machine base information is stored inside netbox. We need Java to go to netbox to create VM information and to get VM information. But this does not guarantee transactivity. So we want to use Java to connect to netbox's database for transactional operations. Our vi...
[ "Yes netbox uses PostgreSQL as a Database\n", "While it's entirely possible to directly interact with the database directly your better approach will likely be interacting through the API. It's quite robust and easy to interact with (as far as APIs go).\n" ]
[ 0, 0 ]
[]
[]
[ "java", "netbox", "postgresql", "python" ]
stackoverflow_0074300476_java_netbox_postgresql_python.txt
Q: It says illegal target for variable annotation.I am not quite getting where the problem is? P.S: try to use only if elif else statements Write a Python program to input three sides of a triangle. If a Triangle can be formed with given input, Check whether it forms a ‘right Triangle’ or ‘Equilateral Triangle’ or ‘N...
It says illegal target for variable annotation.I am not quite getting where the problem is? P.S: try to use only if elif else statements
Write a Python program to input three sides of a triangle. If a Triangle can be formed with given input, Check whether it forms a ‘right Triangle’ or ‘Equilateral Triangle’ or ‘Normal Triangle’. If Triangle cannot be formed, display ‘Triangle cannot be formed’. a=int(input("")) b=int(input("")) c=int(input("")) d=pow((...
[ "The only issue in your code is this line\nelif a==f or b==e or c==d:\n\nYou can't have \"elif\" without initial \"if\". The structure should look like:\na=int(input(\"\"))\nb=int(input(\"\"))\nc=int(input(\"\"))\nd=pow((a*a+b*b),0.5)\ne=pow((a*a+c*c),0.5)\nf=pow((b*b+c*c),0.5)\nif a>(b+c) or b>(a+c) or c>(a+b):\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074304626_python.txt
Q: Appending data (array) into excel elementwise by using python Appending array into excel columns elementwise I am trying to automate my excel console sheet using python/pandas and numpy. I have already read the excel, converted data into arrays, did the matrix ops. and now I am getting row vector of [1x6] which I ...
Appending data (array) into excel elementwise by using python
Appending array into excel columns elementwise I am trying to automate my excel console sheet using python/pandas and numpy. I have already read the excel, converted data into arrays, did the matrix ops. and now I am getting row vector of [1x6] which I want to append into 6 columns. How to do this in pandas as I am ver...
[ "For your first vector, i.e. names of your columns, you might want to write:\ndf.columns = arr\n\nFor all the others:\ndf.append(arr)\n\nhttps://pandas.pydata.org/docs/reference/api/pandas.DataFrame.append.html\n" ]
[ 0 ]
[]
[]
[ "excel", "numpy", "pandas", "python" ]
stackoverflow_0074304513_excel_numpy_pandas_python.txt
Q: Can't import between files in the same folder I'm trying to import Entity.py into Tower.py in the same directory, in order to instantiate the Entity class inside Tower.py. However, it keeps coming up with the same error. folder |_ scripts |_ Tower.py |_ Entity.py |_ Main.py Entity.py class Entit...
Can't import between files in the same folder
I'm trying to import Entity.py into Tower.py in the same directory, in order to instantiate the Entity class inside Tower.py. However, it keeps coming up with the same error. folder |_ scripts |_ Tower.py |_ Entity.py |_ Main.py Entity.py class Entity: ... Tower.py import Entity File "C:\...\sc...
[ "Modules are relative to the working directory. So, if you are running the app using Main.py, every import will be relative to the directory of Main.py.\nIf you want to import the Entity to Tower, you must import it like\nfrom scripts.Entity import Entity\n\nor with relative like\nfrom .Entity import Entity\n\nAnd ...
[ 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0074304570_import_python.txt
Q: Why does this always produce true? The code is supposed to take any string input and check if the word is an isogram (word that does not use repeating letters). But it doesn't actually do that sadly. # word input and defining variables word = list(str(input())) letter = 0 letters = len(word) x = 0 while letter <=...
Why does this always produce true?
The code is supposed to take any string input and check if the word is an isogram (word that does not use repeating letters). But it doesn't actually do that sadly. # word input and defining variables word = list(str(input())) letter = 0 letters = len(word) x = 0 while letter <= letters: # while loop to repeat once fo...
[ "letter as you've defined it is a number. word.count(<substring>) will count how many times <substring> appears in word. Why would you count how many time the number you are storing in letter appear in word?\nInstead, loop through every letter in word and test word.count(letter). If it's greater than one, then set ...
[ 0 ]
[ "Why not just count the number of unique letters in your word and compare it with total number of letters in the word with something like\nword = str(input())\nif len(set(word)) == len(word):\n print(\"true\")\nelse:\n print(\"false\")\n\n" ]
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0074304601_python_python_3.x.txt
Q: Raise an error if type hint is violated/ignored in Python? After looking at this question I learned that the type hints are, by default, not enforced whilst executing Python code. One can detect some discrepancies between the type hints and actual argument types using a slightly convoluted process of running pyann...
Raise an error if type hint is violated/ignored in Python?
After looking at this question I learned that the type hints are, by default, not enforced whilst executing Python code. One can detect some discrepancies between the type hints and actual argument types using a slightly convoluted process of running pyannotate to generate stubs whilst running Python code, and scanning...
[ "Hope this helps you - https://typeguard.readthedocs.io/en/latest/userguide.html#using-the-decorator\nThanks..\n", "The edit queue for the Answer by @Surya_1897 is full, hence I will include a more detailed description of the solution here.\nTypeguard does exactly what I was looking for. The following requirement...
[ 1, 0 ]
[]
[]
[ "python", "runtime", "type_hinting" ]
stackoverflow_0074304457_python_runtime_type_hinting.txt
Q: Type error: create_bool(): incompatible function arguments. Need some advice on this one i'm trying to create a pose detection module but for some reason i get this error every time. it has something to do with my variable declerations but i don't understand what. When i try to convert it to a module it gives me t...
Type error: create_bool(): incompatible function arguments. Need some advice on this one
i'm trying to create a pose detection module but for some reason i get this error every time. it has something to do with my variable declerations but i don't understand what. When i try to convert it to a module it gives me this type error, and this is my code: import cv2 import mediapipe as mp import time class pos...
[ "According to [GitHub]: google/mediapipe - (v0.8.11) mediapipe/mediapipe/python/solutions/pose.py (same on master branch), Poses initializer (around line #114) is:\n\n def __init__(self,\n static_image_mode=False,\n model_complexity=1,\n smooth_landmarks=True,\n ...
[ 0 ]
[]
[]
[ "mediapipe", "opencv", "python", "typeerror" ]
stackoverflow_0074304347_mediapipe_opencv_python_typeerror.txt
Q: Changing the template layout of the pandas dataframe Can you please help me with the following. I have the following pandas df: FB AMZN AAPL NFLX GOOG date 2004-01-01 10 4 1 7 0 2004-02-01 4 0 0 0 23 2004-03-01 6 0 ...
Changing the template layout of the pandas dataframe
Can you please help me with the following. I have the following pandas df: FB AMZN AAPL NFLX GOOG date 2004-01-01 10 4 1 7 0 2004-02-01 4 0 0 0 23 2004-03-01 6 0 0 0 34 2004-04-01 0 0 0 0 0 20...
[ "here is one way to do it\nAssuming the date is the index\n#melt the dataframe\ndf=df.melt( var_name='Company', value_name='Score', ignore_index=False)\n\n# reformat the date\ndf.index=pd.to_datetime(df.index).strftime('%d.%m.%Y')\ndf\n\n\n\n Company Score\n date \n01.01.2004 FB ...
[ 2, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074304657_dataframe_pandas_python.txt
Q: How can I get a value of a specific json key only on a certain level? I have a huge nested json file and I want to get the values of "text" but only on a certain level as there are many "text" keys deeper in the json file. The level I mean would be the "text:"Hi" after "event":"user". The file looks like this: ` ...
How can I get a value of a specific json key only on a certain level?
I have a huge nested json file and I want to get the values of "text" but only on a certain level as there are many "text" keys deeper in the json file. The level I mean would be the "text:"Hi" after "event":"user". The file looks like this: ` { "_id":{ "$oid":"123" }, "events":[ { ...
[ "Since events is a list, you can write a list comprehension (if there are multiple items you need), or you can use the next function to get an element that you need from the iterator:\nevent = next(e for e in data.get('events', list()) if e.get('event')=='user')\nprint(event.get('text', ''))\n\nUsing get method giv...
[ 1, 0 ]
[]
[]
[ "json", "key_value", "python" ]
stackoverflow_0074304384_json_key_value_python.txt
Q: merge/overwrite two JSON object in Python I want to merge two JSON files while the data overwrites itself in the main JSON file. My main object is the following: { "data": [ { "name": "name1", "gender": "male", "age": "20", "subject": "Python", ...
merge/overwrite two JSON object in Python
I want to merge two JSON files while the data overwrites itself in the main JSON file. My main object is the following: { "data": [ { "name": "name1", "gender": "male", "age": "20", "subject": "Python", "pass": "No" } ] } "...
[ "In general, you can use the built-in Python update method for dictionaries, which updates the current dictionary with values of a new one while keeping old data present.\nFor your case (assuming you always need to update the FIRST element in the array within the \"data\" key):\noriginal_data = {\n \"data\": [...
[ 1 ]
[]
[]
[ "arrays", "dictionary", "json", "merge", "python" ]
stackoverflow_0074304739_arrays_dictionary_json_merge_python.txt
Q: Combine multiple numpy arrays on coordinate system, each array defined by a location vector and 2 axis vectors I have image data loaded in python that was recorded from multiple detectorpanels. I would like to recreate the original image by putting each panel at the correct location. The data from each panel is in...
Combine multiple numpy arrays on coordinate system, each array defined by a location vector and 2 axis vectors
I have image data loaded in python that was recorded from multiple detectorpanels. I would like to recreate the original image by putting each panel at the correct location. The data from each panel is in the form of a numpy array and I know the location of the corner of each panel and and the unit vectors for each arr...
[ "Here is an idea I created dummy example but this should work:\nimport numpy as np\nimage_piece1 = np.random.randint(0, 10, size=(2, 2))\nimage_piece2 = np.random.randint(0, 10, size=(2, 2))\nimage_piece3 = np.random.randint(0, 10, size=(2, 2))\nimage_piece4 = np.random.randint(0, 10, size=(2, 2))\nlst_images = [im...
[ 0 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0074304294_matplotlib_numpy_python.txt
Q: converted py to exe using pyinstaller but when run it getting openpyxl module missing? I did pyinstaller --onefile main.py in command prompt This made the exe in a folder called dist where my project is which I then ran in command prompt and got the error below: DevTools listening on ws://127.0.0.1:49451/devtools/...
converted py to exe using pyinstaller but when run it getting openpyxl module missing?
I did pyinstaller --onefile main.py in command prompt This made the exe in a folder called dist where my project is which I then ran in command prompt and got the error below: DevTools listening on ws://127.0.0.1:49451/devtools/browser/b4cedddd-0d98-4929-8fdb-b92d174992cc [18704:11556:1103/114958.968:ERROR:device_event...
[ "\nWhen you open the dist folder, do you see the openpyxl module? If not, try to do it via the add-data or hidden-import. Or even easier, just copy paste it manually and see if that works. Like pyinstaller file.py --hidden-import=openpyxl\n\nYou could either try updating your pyhooks-contrib as it could have been f...
[ 0 ]
[]
[]
[ "openpyxl", "pyinstaller", "python", "python_3.x" ]
stackoverflow_0074303354_openpyxl_pyinstaller_python_python_3.x.txt
Q: Looking for a way to capture the updated text of an element after input with Selenium I've been creating a webscraper with selenium that will select several items, fill a cart, and then cycle through a list of zip codes, cities, and states to calculate the total cost + shipping + tax for a variety of locations. Th...
Looking for a way to capture the updated text of an element after input with Selenium
I've been creating a webscraper with selenium that will select several items, fill a cart, and then cycle through a list of zip codes, cities, and states to calculate the total cost + shipping + tax for a variety of locations. The scraper has been set up successfully and works, but the problem that I am running into is...
[ "There are two matches for your locator value, so it returns the SubTotal, change locator value to:\ndriver.find_element(By.CSS_SELECTOR,'.order-wizard-cart-summary-total .order-wizard-cart-summary-grid-right') \n\n" ]
[ 1 ]
[]
[]
[ "css_selectors", "ironwebscraper", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074298166_css_selectors_ironwebscraper_python_selenium_selenium_webdriver.txt
Q: ValueError on age? I am prompted the following: "In PyCharm, write a program that prompts the user for their name and age. Your program should then tell the user the year they were born. Here is a sample execution of the program with the user input in bold: What is your name? Amanda How old are you? 15 Hello Amand...
ValueError on age?
I am prompted the following: "In PyCharm, write a program that prompts the user for their name and age. Your program should then tell the user the year they were born. Here is a sample execution of the program with the user input in bold: What is your name? Amanda How old are you? 15 Hello Amanda! You were born in 2005...
[ "user_name = input('What is your name?')\nuser_age = input('What is your age?')\nuser_age = int(user_age)\nbirth_year = (2022 - user_age)\nprint('How old are you? <b>{}</b>'.format(user_age))\nprint('Hello <b>{}</b>! You were born in <b>{}</b>.'.format(user_name, birth_year))\n\n", "The function int(), takes a s...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074303615_python.txt
Q: How to display the coordinates of the points clicked on the image in Google Colab? I need to locate the mouse click location on an image in a google colab notebook. I tried the following script but nothing happened. The following code should work in Jupyter notebooks but it doesn't work on google colab: import mat...
How to display the coordinates of the points clicked on the image in Google Colab?
I need to locate the mouse click location on an image in a google colab notebook. I tried the following script but nothing happened. The following code should work in Jupyter notebooks but it doesn't work on google colab: import matplotlib matplotlib.use('TKAgg') import matplotlib.pyplot as plt import matplotlib.image ...
[ "You need to use an interactive IPython backend, e.g. ipympl:\n\nInstallation in Colab:\n\n!pip install ipympl\nfrom google.colab import output\noutput.enable_custom_widget_manager()\n\n\nsetup matplotlib to use it:\n\n%matplotlib ipympl\n\n\ntest it:\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfig, ax...
[ 3 ]
[]
[]
[ "google_colaboratory", "matplotlib", "opencv", "python" ]
stackoverflow_0074248955_google_colaboratory_matplotlib_opencv_python.txt
Q: How to insert python variables inside query in Memgrpah? I need to execute the following query: CREATE (m: Temp {val1: <variable>}) I know there exists save_node functionality but I don't want to use that. I tried the following syntax but it didn't work connection.execute("CREATE (m: Temp {{val1: variable}}}) Th...
How to insert python variables inside query in Memgrpah?
I need to execute the following query: CREATE (m: Temp {val1: <variable>}) I know there exists save_node functionality but I don't want to use that. I tried the following syntax but it didn't work connection.execute("CREATE (m: Temp {{val1: variable}}}) This seems to work only if the variable is a for loop iterator.
[ "You are missing a quatation mark at the end of the command as well as qurly brackets around\nvariable.\nHere is an example:\n from gqlalchemy import Memgraph\n\n print(\"Connect\")\n memgraph = Memgraph()\n\n print(\"Create a node\")\n variable = 100\n memgraph.execute(f\"CREATE (m: Temp {{val1: {variable}}});\")\...
[ 0 ]
[]
[]
[ "memgraphdb", "python" ]
stackoverflow_0074304920_memgraphdb_python.txt
Q: Path class alternative to __file__ in python Each python script has its own __file__ property, which is str with the path to this script. Since there is a pathlib.Path class, is there any corresponding alternative to __file__? Like __file_path__ such that type(__file_path__) == Path? Is it true that the closest we...
Path class alternative to __file__ in python
Each python script has its own __file__ property, which is str with the path to this script. Since there is a pathlib.Path class, is there any corresponding alternative to __file__? Like __file_path__ such that type(__file_path__) == Path? Is it true that the closest we can have to this is to just use Path(__file__) in...
[ "The __file__ and similar attributes are set by the import machinery. All these attribute use the str type to describe paths.\nIn order to treat these paths as Path instances, the simplest option is to convert them explicitly, for example as pathlib.Path(__file__), when needed.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074304235_python.txt
Q: change white space with regular expression in python I need to change white space to a character, but only if there are two or more white spaces and there is only one I want to keep it. An example of text is: 142526 0x8520003 2 2022-10-20 The interface status changes. (ifName=Gig. I need: 142526;0x8520003...
change white space with regular expression in python
I need to change white space to a character, but only if there are two or more white spaces and there is only one I want to keep it. An example of text is: 142526 0x8520003 2 2022-10-20 The interface status changes. (ifName=Gig. I need: 142526;0x8520003;2;2022-10-20 The interface status changes. (ifName=Gig. I...
[ "Use re.split() to match more than one space.\nimport re\n\nnew_headers = ';'.join(re.split(r'\\s{2,}', headers))\n\n\\s matches whitespace, and {2,} means to match 2 or more of them in a row.\n", "You can try to use maxsplit= parameter in str.split:\ns = \"\"\"142526 0x8520003 2 2022-10-20 The interface...
[ 2, 1, 1 ]
[]
[]
[ "python", "split", "text" ]
stackoverflow_0074304669_python_split_text.txt
Q: '_tkinter.tkapp' object has no attribute 'result' Error I'm creating a program that displays a graph of real estate in cities in the States. I was able to create a main function, which mainly concerns creating a graph of each city. Now, I am trying to add a new feature, which lets users choose one city among many ...
'_tkinter.tkapp' object has no attribute 'result' Error
I'm creating a program that displays a graph of real estate in cities in the States. I was able to create a main function, which mainly concerns creating a graph of each city. Now, I am trying to add a new feature, which lets users choose one city among many options by creating a combobox. What I want to make is basica...
[ "Try removing \"self.\" from messagebox function like this:\ndef main(self): # Main function\n #self. removed\n tkinter.messagebox.showinfo(title=\"Combobox\", message=\"Clicked\")\n \n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0074160864_python_python_3.x_tkinter.txt
Q: Unable to stop Streaming in tweepy after one minute I am trying to stream twitter data for a period of time of say 5 minutes, using the Stream.filter() method. I am storing the retrieved tweets in a JSON file. The problem is I am unable to stop the filter() method from within the program. I need to stop the execut...
Unable to stop Streaming in tweepy after one minute
I am trying to stream twitter data for a period of time of say 5 minutes, using the Stream.filter() method. I am storing the retrieved tweets in a JSON file. The problem is I am unable to stop the filter() method from within the program. I need to stop the execution manually. I tried stopping the data based on system t...
[ "\nIn order to close the stream you need to return False from on_data(), or on_status().\nBecause tweepy.Stream() runs a while loop itself, you don't need the while loop in on_data().\nWhen initializing MyListener, you didn't call the parent's class __init__ method, so it wasn't initialized properly.\n\nSo for what...
[ 29, 0, 0, 0 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0033498975_python_tweepy_twitter.txt
Q: How can I use a pip requirements file to uninstall as well as install packages? I have a pip requirements file that changes during development. Can pip be made to uninstall packages that do not appear in the requirements file as well as installing those that do appear? Is there a standard method? This would allow ...
How can I use a pip requirements file to uninstall as well as install packages?
I have a pip requirements file that changes during development. Can pip be made to uninstall packages that do not appear in the requirements file as well as installing those that do appear? Is there a standard method? This would allow the pip requirements file to be the canonical list of packages - an 'if and only if' ...
[ "This should uninstall anything not in requirements.txt:\npip freeze | grep -v -f requirements.txt - | grep -v '^#' | xargs pip uninstall -y\n\nAlthough this won't work quite right with packages installed with -e, i.e. from a git repository or similar. To skip those, just filter out packages starting with the -e fl...
[ 158, 29, 24, 22, 6, 4, 3, 2, 1, 0 ]
[ "It is possible now using:\npip uninstall -r requirements.txt\n\n" ]
[ -4 ]
[ "pip", "python" ]
stackoverflow_0013176968_pip_python.txt
Q: Configuring flake8 plugin when using flakeheaven I'm trying to configure flake8-quotes plugin to use double, not single, quotes. I'm using flakeheaven in my setup. This behaviour (type of quote) can't be influenced just by enabling / disabling an error code - the official documentation suggests using: [flake8] inl...
Configuring flake8 plugin when using flakeheaven
I'm trying to configure flake8-quotes plugin to use double, not single, quotes. I'm using flakeheaven in my setup. This behaviour (type of quote) can't be influenced just by enabling / disabling an error code - the official documentation suggests using: [flake8] inline-quotes = " However, when trying to add this to my...
[ "As Anthony mentioned, flakeheaven config is different from flake8's.\nSpecifically, as it uses toml, strings must be explicitly specified as such by using quotes for strings (see the strings section here):\n[tool.flakeheaven]\ninline-quotes = '\"'\n\nAfter changing the configuration file, clear the cache and then ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074067683_python.txt
Q: Passing an image as an argument to a function in python How can I create a function that takes an image file (not image filename) in python. Simply, like the following: FaceController.py import cv2 from Computer_Vision import Face_Detector as FD def detectface(): img = cv2.imread('DSC_1902.JPG') FD.detect...
Passing an image as an argument to a function in python
How can I create a function that takes an image file (not image filename) in python. Simply, like the following: FaceController.py import cv2 from Computer_Vision import Face_Detector as FD def detectface(): img = cv2.imread('DSC_1902.JPG') FD.detect(img) detectface() Face_Detector.py import cv2 def detec...
[ "You can pass a pointer pointing to the image instead of the image or the filename of the image\nEDIT\ndef image_function(imagePointer):\n #DO SOMETHING WITH THE IMAGE\n\n#HERE IS THE IMAGE POINTER\nimage = open('your_image.png')\n\n#CALLING THE FUNCTION\nimage_function(image)\n\nSorry, I don't know opencv so I ...
[ 1, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0048560201_opencv_python.txt
Q: Dropbox read only python api Hello i'm having a problem where i'm need api token to never expire but everytime it says "Token expired" And i can't find a tutorial how to do that. thanks. I tried to watch dropbox tutorials but they never mentioned how to do that. A: Dropbox is no longer offering the option for cr...
Dropbox read only python api
Hello i'm having a problem where i'm need api token to never expire but everytime it says "Token expired" And i can't find a tutorial how to do that. thanks. I tried to watch dropbox tutorials but they never mentioned how to do that.
[ "Dropbox is no longer offering the option for creating new long-lived access tokens. Dropbox is switching to only issuing short-lived access tokens (and optional refresh tokens) instead of long-lived access tokens. You can find more information on this migration here.\nApps can still get long-term access by request...
[ 0 ]
[]
[]
[ "dropbox", "dropbox_api", "python", "python_3.x" ]
stackoverflow_0074295697_dropbox_dropbox_api_python_python_3.x.txt
Q: Python - Scatter Plot - How to plot repeating X values with multiple Y values How do I go about plotting a scatter plot if I have a data frame where column A has repeating values. See image below Column A Column B Manager 200 Manager 150 Associate 200 Manager 150 So I want the scatter plot X axis to show col...
Python - Scatter Plot - How to plot repeating X values with multiple Y values
How do I go about plotting a scatter plot if I have a data frame where column A has repeating values. See image below Column A Column B Manager 200 Manager 150 Associate 200 Manager 150 So I want the scatter plot X axis to show column A but only shows once per value. I only want to show Manager once a...
[ "\nOf course I have no data of yours, so I have to construct my a, containing names and my b, containing multiples of 10, possibly $$$...\nI decided to place the names in the tick labels and in mouse-hover labels — if the tick labels, for a large no. of names, stick together you can just remove completely, see the ...
[ 0 ]
[]
[]
[ "matplotlib", "python", "scatter_plot" ]
stackoverflow_0074294954_matplotlib_python_scatter_plot.txt
Q: download an image file from S3 and send as email in python using BytesIO and MIMEApplication results to zero bytes I have this source to download a file from an S3 bucket where I uses BytesIO to store the read data in memory instead of file. with io.BytesIO() as img: img.name = 'screenshot.png' tr...
download an image file from S3 and send as email in python using BytesIO and MIMEApplication results to zero bytes
I have this source to download a file from an S3 bucket where I uses BytesIO to store the read data in memory instead of file. with io.BytesIO() as img: img.name = 'screenshot.png' try: get_bucket().download_fileobj(key, img) except Exception as e: logger.error('ERROR pr...
[ "Try adding a img.seek(0) after download_fileobj.\n" ]
[ 0 ]
[]
[]
[ "amazon_ses", "boto3", "python" ]
stackoverflow_0074301012_amazon_ses_boto3_python.txt
Q: Hi all, I want to transpose my data frame data={'id':[1, 2, 3],'A': ['edx',None , 'edx'],'B': [None,'com',None ],'C': ['tab','tab',None ] } df = pd.DataFrame(data) Given data frame : id A B C 1 edx None tab 2 None com tab 3 edx None None Desired Result: id Learn 1 edx 1 tab 2 com 2...
Hi all, I want to transpose my data frame
data={'id':[1, 2, 3],'A': ['edx',None , 'edx'],'B': [None,'com',None ],'C': ['tab','tab',None ] } df = pd.DataFrame(data) Given data frame : id A B C 1 edx None tab 2 None com tab 3 edx None None Desired Result: id Learn 1 edx 1 tab 2 com 2 tab 3 edx Same I Expect that I have menti...
[ "Try this. I would really suggest getting familiar with pd.melt as it's extremely useful in reshaping data that looks like this.\ndf = (df.melt(id_vars='id', value_name='Learn')\n .dropna()\n .sort_values(by='id', ascending='True'))\n \ndf.drop(columns=['variable'], inplace=True)\nprint(df)\n\nOut...
[ 1, 0 ]
[]
[]
[ "data_processing", "dataframe", "pandas", "python", "transpose" ]
stackoverflow_0074304945_data_processing_dataframe_pandas_python_transpose.txt
Q: How to return a tuple containing the smallest and largest numbers in the file In this exercise, I need to write a function that take input a string representing a filename. The file contains a list of integers, one integer per line. Function should return a tuple containing the smallest and largest numbers in the ...
How to return a tuple containing the smallest and largest numbers in the file
In this exercise, I need to write a function that take input a string representing a filename. The file contains a list of integers, one integer per line. Function should return a tuple containing the smallest and largest numbers in the file. My code attempt below did pass the auto-grader, but it is ugly. Would like to...
[ "You open the file twice, and both times read the entire content of the file into a list with file.readlines before finding the min or max respectively. If you read the file all at once, you can just as well map the lines to int directly, collect those in a list, and bind that to a variable and use it for both min ...
[ 1, 0, 0, 0 ]
[]
[]
[ "max", "min", "python", "tuples" ]
stackoverflow_0074304589_max_min_python_tuples.txt
Q: How to scrape a google search results page? I am trying to scrape google search results using the following code. I want to take the title and the url of the first page of the results and then continue by scraping the next pages of the search results too. This is a sample of code that I just started writing: from ...
How to scrape a google search results page?
I am trying to scrape google search results using the following code. I want to take the title and the url of the first page of the results and then continue by scraping the next pages of the search results too. This is a sample of code that I just started writing: from urllib.request import urlopen as uReq import urll...
[ "I would never scrape Google directly via raw http requests. Google can detect it so easily. In order to be not detected, I suggest using a automated browser like Chrome with selenium. \nIn your example, the problem is that Google delivers a differnt HTML version of it's SERP page because it detects the low level h...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x", "web_scraping" ]
stackoverflow_0051286702_python_python_3.x_web_scraping.txt
Q: How to merge two list into one dictionary? I have this function setValue(binaryString) that takes inputs binary string "binaryString" and returns the set of positions between 0 and len(binaryString)-1 whose corresponding entry in binaryString is '1'. so for example: binaryString = 10101 will return set {0, 2, 4}. ...
How to merge two list into one dictionary?
I have this function setValue(binaryString) that takes inputs binary string "binaryString" and returns the set of positions between 0 and len(binaryString)-1 whose corresponding entry in binaryString is '1'. so for example: binaryString = 10101 will return set {0, 2, 4}. the returned set indicates the position of numbe...
[ "How about a set comprehension?\ndef one_index(s):\n return {i for i, e in enumerate(s) if e == '1'}\n\nexamples = '0', '1', '110011', '10101'\n\nresult = {bs: one_index(bs) for bs in examples}\n\nprint(result)\n\nOutput:\n{'0': set(), '1': {0}, '110011': {0, 1, 4, 5}, '10101': {0, 2, 4}}\n\n", "If you have a ...
[ 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "function", "loops", "python" ]
stackoverflow_0074304797_dictionary_function_loops_python.txt
Q: Looking for a way to check if a word is in the list of not Implement three classes: VerbWord, NounWord and Dict. The VerbWord is for representing a verb and the NounWord is for representing a noun. Each of the VerbWord and NounWord should take a string as a parameter of the constructor. Assume that this string is ...
Looking for a way to check if a word is in the list of not
Implement three classes: VerbWord, NounWord and Dict. The VerbWord is for representing a verb and the NounWord is for representing a noun. Each of the VerbWord and NounWord should take a string as a parameter of the constructor. Assume that this string is the infinitive/singular of the word they represent, e.g. VerbWor...
[ "You are returning result of the check against the very first word in the list, regardless of if there was a match or not. Instead, you want to check if any word matched, and return False only if none of them did:\n def is_known(self,word):\n for w in self.words:\n a = w.get_forms()\n ...
[ 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0074305000_class_python.txt
Q: Getting the file name of downloaded video using yt-dlp I'm intending to use yt-dlp to download a video and then cut the video down afterward using ffmpeg. But to be able to use ffmpeg I am going to have to know the name of the file that yt-dlp produces. I have read through their documentation but I can't seem to f...
Getting the file name of downloaded video using yt-dlp
I'm intending to use yt-dlp to download a video and then cut the video down afterward using ffmpeg. But to be able to use ffmpeg I am going to have to know the name of the file that yt-dlp produces. I have read through their documentation but I can't seem to find a way of getting the file name back into my program.
[ "here are the doc examples\nthe numbers you mentioned (like .f399) I believe are temp only and are eventually removed when the final file is merged.\nif you want to get the filename:\nimport subprocess\nsomeFilename = subprocess.getoutput('yt-dlp --print filename https://www.youtube.com/something')\n# then pass som...
[ 1, 1 ]
[]
[]
[ "ffmpeg", "python", "yt_dlp" ]
stackoverflow_0074157935_ffmpeg_python_yt_dlp.txt
Q: AWS Glue - filter method causes "JDBC type for null" error I'm doing few transformation to my Glue DF in Python and noticed that filter() method, when implemented, causes below error: when loading to SQL Server RDS: `Can't get JDBC type for null Failed` Code: def get_credentials(self, glue_connection): glue_c...
AWS Glue - filter method causes "JDBC type for null" error
I'm doing few transformation to my Glue DF in Python and noticed that filter() method, when implemented, causes below error: when loading to SQL Server RDS: `Can't get JDBC type for null Failed` Code: def get_credentials(self, glue_connection): glue_context = self.gc credentials = glue_context.extract_jdbc_con...
[ "Glue's dynamicframe doesn't have cast method thus it it required to convert into spark's dataframe, do the cast and back to glue's df...\nDATA_TYPES = {\"null\": \"int\"}\n\njob = Context()\nrds = RDSClient(job)\n\nglue_df = rds.rds_df()\nspark_df = glue_df.toDF()\n\nfor column, dtype in spark_df.dtypes:\n if d...
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_glue", "python" ]
stackoverflow_0074295897_amazon_web_services_aws_glue_python.txt
Q: Group by two columns where values may be switched I have a dataframe that looks like this: Start End Total X Y 50 X Z 100 Y Z 50 Y X 100 I am trying to group by pairs "Start" --> "End", where values may be switched. I'm calculating the sum of "Total". The result would look like this: Start End Total X Y 15...
Group by two columns where values may be switched
I have a dataframe that looks like this: Start End Total X Y 50 X Z 100 Y Z 50 Y X 100 I am trying to group by pairs "Start" --> "End", where values may be switched. I'm calculating the sum of "Total". The result would look like this: Start End Total X Y 150 X Z 100 Y Z 50 X --> Y and ...
[ "Merge 'Start' and 'End' columns into array and then aggregate.\nInput:\nfrom pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('X', 'Y', 50),\n ('X', 'Z', 100),\n ('Y', 'Z', 50),\n ('Y', 'X', 100)],\n ['Start', 'End', 'Total'])\n\nScript:\narr = F.array_sort(F.array('Start', 'End...
[ 1 ]
[]
[]
[ "aggregate", "apache_spark", "group_by", "pyspark", "python" ]
stackoverflow_0074305014_aggregate_apache_spark_group_by_pyspark_python.txt
Q: How to convert int 1 into ascii 1 in python? I receive input that is in a float format. I've broken it up into individual int numbers and am trying to encode them as the same ascii characters. Ie: int 1 to ascii character 1. I have tried different variations of this: x = 1 y = chr(x) print (y) which results in as...
How to convert int 1 into ascii 1 in python?
I receive input that is in a float format. I've broken it up into individual int numbers and am trying to encode them as the same ascii characters. Ie: int 1 to ascii character 1. I have tried different variations of this: x = 1 y = chr(x) print (y) which results in ascii character SOH instead of ascii character 1.
[ "You can use the functions chr(),ord() and str() to encode it like that, I think what you want is the result of this.\nx=1\nprint(chr(ord(str(x))))\n\n", "For anyone reading, This is what I was looking for:\ny = f'0x{ord(str(1)):x}'\n\nwhich outputs:\n0x31\n" ]
[ 2, 0 ]
[]
[]
[ "ascii", "encode", "integer", "python" ]
stackoverflow_0074303456_ascii_encode_integer_python.txt
Q: not able to convert byte array to pdf file in nodejs & python We have an API that gives pdf files as a byte array,we are trying to convert that byte array response into pdf file const axios = require('axios') const fs = require('fs') const {Base64} = require('js-base64'); axios.post("some api....") .then((respo...
not able to convert byte array to pdf file in nodejs & python
We have an API that gives pdf files as a byte array,we are trying to convert that byte array response into pdf file const axios = require('axios') const fs = require('fs') const {Base64} = require('js-base64'); axios.post("some api....") .then((response) => { var u8 = new Uint8Array(response.data.success)...
[ "Just transfer data from response to file as stream:\nconst writeStream = createWriteStream('file.pdf');\nresponse.data.pipe(writeStream);\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "base64", "node.js", "python" ]
stackoverflow_0074305055_arrays_base64_node.js_python.txt
Q: Poetry: how to specify the same dependency twice with different CPU architectures (e.g x86 and x86_64) I am evaluating using Poetry for packaging and building a desktop application. The only roadblocker is that poetry doesn't seam to allow specifying the same package twice. For instance I couldn't do the following...
Poetry: how to specify the same dependency twice with different CPU architectures (e.g x86 and x86_64)
I am evaluating using Poetry for packaging and building a desktop application. The only roadblocker is that poetry doesn't seam to allow specifying the same package twice. For instance I couldn't do the following: [tool.poetry.dependencies] python = "^3.9" lru-dict = {path = "./packages/lru_dict-1.1.6-cp39-cp39-win_amd...
[ "From the poetry documentation:\n\nPoetry supports environment markers via the markers property.\n\nOne of those markers is platform_machine, which is the output of platform.machine().\nSo you should be able to do something like this:\n[tool.poetry.dependencies]\npython = \"^3.9\"\nlru-dict = [\n {path = \"./pac...
[ 0 ]
[]
[]
[ "packaging", "python", "python_poetry" ]
stackoverflow_0073806840_packaging_python_python_poetry.txt
Q: Bad Request : Did not attempt to load JSON data because the request Content-Type was not 'application/json' I'm using React as frontend and Flask as the backend here. I am sending a JSON file from react to flask using POST method with proper headers. But I keep on getting this error : Bad Request Did not attempt t...
Bad Request : Did not attempt to load JSON data because the request Content-Type was not 'application/json'
I'm using React as frontend and Flask as the backend here. I am sending a JSON file from react to flask using POST method with proper headers. But I keep on getting this error : Bad Request Did not attempt to load JSON data because the request Content-Type was not 'application/json'. Here is my React code which sends t...
[ "I cant add a question in the comment section yet because of lack of rep, so I'm going to ask you something here. If you have an object in localStorage, isn't it already stringified? And if it is then that means you're sending an object inside of a string inside of a string \"\"{...}\"\". I haven't tested this loca...
[ 0 ]
[]
[]
[ "fetch_api", "flask", "javascript", "python" ]
stackoverflow_0074302559_fetch_api_flask_javascript_python.txt
Q: Python - Run .jar file with later input / "Enter"-Simulation I'm writing a python script where at one point I need to run a .jar file. If I run the .jar file without python from the normal CMD I start it by: java -jar path\to\myFile.jar <some not important params> The .jar is doing some stuff and prints also what ...
Python - Run .jar file with later input / "Enter"-Simulation
I'm writing a python script where at one point I need to run a .jar file. If I run the .jar file without python from the normal CMD I start it by: java -jar path\to\myFile.jar <some not important params> The .jar is doing some stuff and prints also what it is doing right now. After a time it reaches a point where it sa...
[ "I got it to work by help of the comment of @Maged Saeed in this Post: https://stackoverflow.com/questions/28616018/multiple-inputs-and-outputs-in-python-subprocess-communicate#:~:text=This%20should%20be%20used%20with%20caution%20with%20line%20splitters%20and%20flushing%20the%20PIPE%20as%20it%20may%20create%20deadl...
[ 0 ]
[]
[]
[ "enter", "jar", "python" ]
stackoverflow_0074304368_enter_jar_python.txt
Q: Correct way for uploading image bytes to cloudinary I am using http://cloudinary.com/documentation/image_upload_api_reference as reference. There are two cases in which I want to upload the files to cloudinary. Upload image by directly giving url link. Upload image bytes by taking them from different source. I c...
Correct way for uploading image bytes to cloudinary
I am using http://cloudinary.com/documentation/image_upload_api_reference as reference. There are two cases in which I want to upload the files to cloudinary. Upload image by directly giving url link. Upload image bytes by taking them from different source. I could solve case 1, but had trouble in 2nd. I am pasting m...
[ "Your img_src parameter, which represents file, should be populated with either a byte array buffer (bytearray) or a Base64 URI. You can try something like:\n with open(img_src_str, \"rb\") as imageFile:\n f = imageFile.read()\n img_src = bytearray(f)\n\n cloudinary_response = cloudinary.uploader.up...
[ 0, 0 ]
[]
[]
[ "cloudinary", "python" ]
stackoverflow_0041098273_cloudinary_python.txt
Q: change odd elements in list to negative I am trying to change odd elements in a list of int to negative using slicing l[1::2] = -1 * l[1::2] However, I encounter the following error: ValueError: attempt to assign sequence of size 0 to extended slice of size 2 A: If you wish to uses slices: >>> a = [1,4,7,8,2] ...
change odd elements in list to negative
I am trying to change odd elements in a list of int to negative using slicing l[1::2] = -1 * l[1::2] However, I encounter the following error: ValueError: attempt to assign sequence of size 0 to extended slice of size 2
[ "If you wish to uses slices:\n>>> a = [1,4,7,8,2]\n>>> a[1::2] = [-x for x in a[1::2]]\n>>> a\n[1, -4, 7, -8, 2]\n\nWhen assigning to an extended slice like a[1::2], the list/slice on the right hand side must be the same length as the left hand side. In the above, we've mapped to a[1::2] with a list comprehension, ...
[ 2 ]
[ "Best way would be to do it vectorized with numpy. Without numpy, I don't see a way to do it without creating a new loop. Here you have two examples of how to do it. With and without numpy:\nimport numpy as np\n\n# vectorized\na = np.arange(10)\na[1::2] *= -1\nprint(a)\n# >>> [ 0 -1 2 -3 4 -5 6 -7 8 -9]\n\na =...
[ -1 ]
[ "python" ]
stackoverflow_0074305266_python.txt
Q: How to stop an Azure Event Hub Consumer Client in Python I am running into some trouble with Azure Event Bub with Python. Below is my strater code for connection (Taken from microsoft docs) import asyncio from azure.eventhub.aio import EventHubConsumerClient from azure.eventhub.extensions.checkpointstoreblobaio im...
How to stop an Azure Event Hub Consumer Client in Python
I am running into some trouble with Azure Event Bub with Python. Below is my strater code for connection (Taken from microsoft docs) import asyncio from azure.eventhub.aio import EventHubConsumerClient from azure.eventhub.extensions.checkpointstoreblobaio import BlobCheckpointStore async def on_event(partition_contex...
[ "@Abhishek\nThere are 2 options here :\n\nYou could stop listening when there is an inactivity for certain period time.\nYou could stop listening after fixed duration.\n\nHave detailed both in below steps.\nOPTION 1\nYou could use the max_wait_time parameter in order to stop listening in case there is no activity f...
[ 3, 0 ]
[]
[]
[ "async_await", "azure_eventhub", "python" ]
stackoverflow_0063301165_async_await_azure_eventhub_python.txt
Q: Pymunk Segment: Some static lines don't have collision I'm trying to place borders in a game made in pygame using pymunk 5.7.0 to prevent the player from leaving the map. When I do this however, only some of the lines acting as borders have collision. This is the code that I use: screen_size = (360, 360) static_b...
Pymunk Segment: Some static lines don't have collision
I'm trying to place borders in a game made in pygame using pymunk 5.7.0 to prevent the player from leaving the map. When I do this however, only some of the lines acting as borders have collision. This is the code that I use: screen_size = (360, 360) static_body = space.static_body static_lines = [ # North West c...
[ "I solved this myself. The problem is that the dimensions of the space are not the same as the dimensions of the screen. My screen size was (360, 360), but the dimensions of the space was (9, 9), as the map of my game was a 9x9 array. That is why the lines connected to the southeast didn't seem to have collision, w...
[ 1 ]
[]
[]
[ "pymunk", "python" ]
stackoverflow_0074303779_pymunk_python.txt
Q: VS Code. Run several tests that located in different folders I don't understand how to organize my test files in my project with VS Code. I have some .ipynb files in root from which I run some libs. Currently, I have only one package (lib1) with modules with test for each of them. But If I want to use another pack...
VS Code. Run several tests that located in different folders
I don't understand how to organize my test files in my project with VS Code. I have some .ipynb files in root from which I run some libs. Currently, I have only one package (lib1) with modules with test for each of them. But If I want to use another package (lib2) from my root where I want to locate my other tests. So,...
[ "The paramters in settings.json python.testing.unittestArgs are the same as in python -m unittest discover. So you can get help on their meaning and usage by running python -m unittest discover --help.\nI have a similar project setup with multiple modules in different folders and configured -s to point to their com...
[ 0 ]
[]
[]
[ "python", "python_unittest", "testing", "visual_studio_code" ]
stackoverflow_0070348445_python_python_unittest_testing_visual_studio_code.txt
Q: "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape" . (File management bug) So I'm making a program in Python that goes through all of your files in the download folder but when I run it, it says (SyntaxError: (unicode error) 'unicodeescape' codec ca...
"SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape" . (File management bug)
So I'm making a program in Python that goes through all of your files in the download folder but when I run it, it says (SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape). I use a variable to store the directory and put it in a for loop with the OS libra...
[ "#You can also use this to scan your directory and get all filename in it\n\nimport os\n\n\n\nsource_dir = \"C:/Users/(replace with you'r name to test)/example/Downloads\"\n\nfor file in os.listdir(source_dir):\n print(file)\n\n", "And if you want to remove desktop.ini from printing just write this code\nimpor...
[ 1, 1 ]
[]
[]
[ "directory", "file_management", "python" ]
stackoverflow_0074291971_directory_file_management_python.txt
Q: Django: Add property condition for another property For a property, I can't manage to filter a Queryset with another property. I want that if "father" has "Star" in "True", "star_descendant" returns "father". I have this error: Exception Value: 'QuerySet' object has no attribute 'star'. How to fix it? My code : ...
Django: Add property condition for another property
For a property, I can't manage to filter a Queryset with another property. I want that if "father" has "Star" in "True", "star_descendant" returns "father". I have this error: Exception Value: 'QuerySet' object has no attribute 'star'. How to fix it? My code : @property def star(self): if Evenements.obj...
[ "In your function, \"father\" and \"mother\" are querysets. \"star\" is a property of an object. You must to get an object. Queryset has no attribute \"star\".\nif Individus.objects.filter(codeid=self.xrefpere_id).count() > 0:\n father = Individus.objects.filter(codeid=self.xrefpere_id).first()\n if father.st...
[ 0 ]
[]
[]
[ "django", "function", "model", "properties", "python" ]
stackoverflow_0074304521_django_function_model_properties_python.txt
Q: matplotlib imshow fixed aspect and vertical colorbar matching master axis height I need to plot a mesh grid with "temperature map" values, currently I'm using imshow, with a colormap. This is described in the Matplotlib overview, so I modified the example to force custom aspect of the figure: import matplotlib.pyp...
matplotlib imshow fixed aspect and vertical colorbar matching master axis height
I need to plot a mesh grid with "temperature map" values, currently I'm using imshow, with a colormap. This is described in the Matplotlib overview, so I modified the example to force custom aspect of the figure: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np ...
[ "What happens here is that you applied an aspect of 0.5 to the imshow image. This divides the vertical extend of your image by 2, while the colorbar keeps the original extent. I see 2 solutions\nyou can manually set the size of the colorbar using:\ncax = fig.add_axes([0.85, 0.3, 0.04, 0.4])\n\n...or you can apply a...
[ 3, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0026563858_matplotlib_python.txt
Q: How to make inline bold text using PyFPDF? from fpdf import FPDF pdf1 = FPDF pdf1.multi_cell(0, 5, 'This is my disclaimer. THESE WORDS NEED TO BE BOLD. These words do not need to be bold.', 0, 0, 'L') pdf1.output("sample.pdf") A: I use fpdf for php and had the same need. But as Olivier mentioned in the comme...
How to make inline bold text using PyFPDF?
from fpdf import FPDF pdf1 = FPDF pdf1.multi_cell(0, 5, 'This is my disclaimer. THESE WORDS NEED TO BE BOLD. These words do not need to be bold.', 0, 0, 'L') pdf1.output("sample.pdf")
[ "I use fpdf for php and had the same need. \nBut as Olivier mentioned in the comments it is not possible. So I wrote a quick workaround, I have written a rough python implementation below.\nProbably not the most beautiful solution but it might serve you.\nfrom fpdf import FPDF\n\nclass FPDF_bold_multicell(FPDF):\n\...
[ 2, 0 ]
[]
[]
[ "fpdf", "pyfpdf", "python" ]
stackoverflow_0060736940_fpdf_pyfpdf_python.txt
Q: How to stop the delay in OpenCV Python So I'm trying to make an Ascii Video Player in Python, and it works but it's very slow. Is there any way that I can stop the delay, and also I can't see the top of the frame. import os import sys import cv2 from PIL import Image Chars = ["@", "#", "S", "%", "?", "*", "+", ";...
How to stop the delay in OpenCV Python
So I'm trying to make an Ascii Video Player in Python, and it works but it's very slow. Is there any way that I can stop the delay, and also I can't see the top of the frame. import os import sys import cv2 from PIL import Image Chars = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."] def resized_gray_image(im...
[ "The range() function does not include the upper limit due to which upper limit of you images is not being added. You can include the upper limit by.\nascii_image = \"\\n\".join([new_image_data[index:(index+new_width)] if new_width < totalPixels else new_image_data[index:totalPixels] for index in range(0, totalPixe...
[ 0 ]
[]
[]
[ "command_line", "opencv", "python", "python_3.x" ]
stackoverflow_0074303764_command_line_opencv_python_python_3.x.txt
Q: Numerically sort comma delimited string values of nested dictionary in Python I have a nested dictionary: some_dictionary = { "sub_dict1": { "miles": "5,024,279" }, "sub_dict2": { "miles": "733,391" }, "sub_dict3": { "miles": "7,151,502" } } I need to sort some_dict...
Numerically sort comma delimited string values of nested dictionary in Python
I have a nested dictionary: some_dictionary = { "sub_dict1": { "miles": "5,024,279" }, "sub_dict2": { "miles": "733,391" }, "sub_dict3": { "miles": "7,151,502" } } I need to sort some_dictionary by the numerical values of miles so when I display it should be something l...
[ "Try this instead:\ntop = dict(sorted(some_dictionary.items(), key= lambda x: int(x[1][\"miles\"].replace(\",\", \"\"))))\n\nYou were missing square brackets around \"miles\" and you probably want to convert the string to int to do the comparison as a number.\nAlso, since Python 3.7 default dictionary is ordered so...
[ 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074304690_dictionary_python.txt
Q: How to get column by number in Pandas? What's the difference between: Maand['P_Sanyo_Gesloten'] Out[119]: Time 2012-08-01 00:00:11 0 2012-08-01 00:05:10 0 2012-08-01 00:10:11 0 2012-08-01 00:20:10 0 2012-08-01 00:25:10 0 2012-08-01 00:30:09 0 2012-08-01 00:40:10 0 2012-08-01 00:50:09 0 201...
How to get column by number in Pandas?
What's the difference between: Maand['P_Sanyo_Gesloten'] Out[119]: Time 2012-08-01 00:00:11 0 2012-08-01 00:05:10 0 2012-08-01 00:10:11 0 2012-08-01 00:20:10 0 2012-08-01 00:25:10 0 2012-08-01 00:30:09 0 2012-08-01 00:40:10 0 2012-08-01 00:50:09 0 2012-08-01 01:05:10 0 2012-08-01 01:10:10 ...
[ "One is a column (aka Series), while the other is a DataFrame:\nIn [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])\n\nIn [2]: df\nOut[2]:\n a b\n0 1 2\n1 3 4\n\nThe column 'b' (aka Series):\nIn [3]: df['b']\nOut[3]:\n0 2\n1 4\nName: b, dtype: int64\n\nThe subdataframe with columns (position)...
[ 53, 19, 18, 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0017193850_pandas_python.txt
Q: Pygame window not opening until all processes are complete macOS 12.2 macOS Monterey 12.2 M1 Pro Version: pygame 2.1.2 (SDL 2.0.18, Python 3.10.7) Pygame will not display a window until all my code has run and the program is waiting for input to exit. Once program is complete, Pygame window shows. If I didn't use ...
Pygame window not opening until all processes are complete macOS 12.2
macOS Monterey 12.2 M1 Pro Version: pygame 2.1.2 (SDL 2.0.18, Python 3.10.7) Pygame will not display a window until all my code has run and the program is waiting for input to exit. Once program is complete, Pygame window shows. If I didn't use the following code: while True: for event in pygame.event.get(): ...
[ "I am not sure on your entire code, but try adding a pygame.display.update() in your while loop, this should make pygame keep the screen refreshed.\nAgain this could not solve your solution because you do not show your full program.\n" ]
[ 0 ]
[]
[]
[ "macos", "pygame", "python" ]
stackoverflow_0074305263_macos_pygame_python.txt
Q: finding unknown pattern in a string in python I am following a book and I came across a question : Can you spot a pattern in this two pieces of strings? 112a4a342cb214d0001acd24a3a12dadbcb4a0000000 1b2a34d4ac42d23b141acd24a3a12dadbcb4a2134141 The thing is I know that 'acd24a3a12dadbcb4a' is the matching piece. H...
finding unknown pattern in a string in python
I am following a book and I came across a question : Can you spot a pattern in this two pieces of strings? 112a4a342cb214d0001acd24a3a12dadbcb4a0000000 1b2a34d4ac42d23b141acd24a3a12dadbcb4a2134141 The thing is I know that 'acd24a3a12dadbcb4a' is the matching piece. However, What method can I use if I don't already kn...
[ "Your length of your both string is 44 characters.\nIn both string 1. and 2. common pattern starts from index 18 and ends at index 37.\nSo here's the example through which you match the similar pattern in all strings.\nstr1 = \"112a4a342cb214d0001acd24a3a12dadbcb4a0000000\"\nstr2 = \"1b2a34d4ac42d23b141acd24a3a12da...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074305157_python.txt
Q: Porting DateTime Ticks from C# to Python I have a a C# line of code string.Format("{0:D19}", DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks) That I am trying to port over to Python. I'm having trouble understanding how to port two aspects: I can't find an equivalent Python representation of DateTime.MaxValue.Tic...
Porting DateTime Ticks from C# to Python
I have a a C# line of code string.Format("{0:D19}", DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks) That I am trying to port over to Python. I'm having trouble understanding how to port two aspects: I can't find an equivalent Python representation of DateTime.MaxValue.Ticks and DateTime.UtcNow.Ticks. I can get to a u...
[ "I have data in Azure Table Storage that follows the Log-Tail pattern (which is identical to your code) and was looking for a way to filter on RowKey for better query performance than filtering on Timestamp and found that this worked for me:\nfrom datetime import datetime\n\ndef row_key(dt):\n t = (datetime(9999...
[ 0 ]
[]
[]
[ "c#", "datetime", "python" ]
stackoverflow_0071356853_c#_datetime_python.txt
Q: how can I plot a Likert scale? I have an excel spreadsheet as follows: data = pd.read_excel(r'survey.xlsx') Each row is a response to a survey, with columns being the different questions in Likert scale (Strong Agree, Mostly Agree, Neutral, Mostly Disagree, Strong Disagree). Let's say that for a given question, t...
how can I plot a Likert scale?
I have an excel spreadsheet as follows: data = pd.read_excel(r'survey.xlsx') Each row is a response to a survey, with columns being the different questions in Likert scale (Strong Agree, Mostly Agree, Neutral, Mostly Disagree, Strong Disagree). Let's say that for a given question, the survey information in the excel s...
[ "If you have your questions and would like to make a Likert-Chart out of the data you can convert your unique values for each question into a dictionary.\ncreate the response associated with the survey\nNOTE\nYou may have to change your scale to match the python package requirements\nquestions_response = {\n 1:\...
[ 0 ]
[]
[]
[ "excel", "likert", "pandas", "python" ]
stackoverflow_0070202972_excel_likert_pandas_python.txt
Q: how to count missing values that are not the regular missing in pandas I have a Dataframe that have some null values, but also other entries that I should count as missing. The forms of missing that I want to take into account are: The normal null value from pandas The string N/A 0.0 "-" I want to identify the p...
how to count missing values that are not the regular missing in pandas
I have a Dataframe that have some null values, but also other entries that I should count as missing. The forms of missing that I want to take into account are: The normal null value from pandas The string N/A 0.0 "-" I want to identify the percentage of missing values per column. I tried this # Total null values ...
[ "Using isin([])\nmis_val = df.Data.isin([pd.NA, np.nan, None, '-', 'N/A', 0]).sum()\n\nExample:\ndf = pd.DataFrame({'Data': [1, 2, 3, 'text', pd.NA, 5, 0, 4, '-', 12, 'N/A', 20, np.nan]})\nmis_val = df.Data.isin([pd.NA, np.nan, None, '-', 'N/A', 0]).sum()\nmis_val_percent = 100 * mis_val / df.size\nprint(f'Missed v...
[ 1, 0, 0 ]
[ "If you want count N/A in particular column:\ndf[\"Col_name\"].isna().sum()\n\nIf you want count N/A in full data frame:\ndf.isna().sum().sum()\n\n" ]
[ -1 ]
[ "missing_data", "pandas", "python" ]
stackoverflow_0074305111_missing_data_pandas_python.txt
Q: python equivalent of R's range Is there a python equivalent of R's range? A builtin function that returns max and min of a list (or series or similar)? > range(1:3) [1] 1 3 I could do something like min([1, 2, 3) and max([1, 2, 3]) but wondering if there's something that combines both. A: I don't believe that ...
python equivalent of R's range
Is there a python equivalent of R's range? A builtin function that returns max and min of a list (or series or similar)? > range(1:3) [1] 1 3 I could do something like min([1, 2, 3) and max([1, 2, 3]) but wondering if there's something that combines both.
[ "I don't believe that there is a builtin function in python that is the equivalent of range in R. However, it is easy enough to create using base python.\ndef range_r(lst):\n min_ = min(lst)\n max_ = max(lst)\n return min_, max_\n\nrange_r(range(1, 20)) # returns (1, 19)\nrange_r([1, 3, 5, 10]) # returns (...
[ 1 ]
[]
[]
[ "python", "r" ]
stackoverflow_0074305371_python_r.txt
Q: No module named traitlets.config.application I have installed ipython through apt-get install ipython on Ubuntu 14.04 and my python version is 2.7.6. When I ran ipython in the console, I faced this error and I could not find any similar problems on any site. Can someone help me? Traceback (most recent call last): ...
No module named traitlets.config.application
I have installed ipython through apt-get install ipython on Ubuntu 14.04 and my python version is 2.7.6. When I ran ipython in the console, I faced this error and I could not find any similar problems on any site. Can someone help me? Traceback (most recent call last): File "/usr/local/bin/ipython", line 4, in <modul...
[ "As @user3682792 says, just doing\nsudo pip install traitlets\n\nFixed this issue for me. Thanks!\n", "I get this error because of my python version\nit was 3.6 and I upgrade it to 3.8 and tadddaaaa :)\nthe problem solved\n", "I had the same issue. In my case it was because I had a version of ipython in ~/.loca...
[ 7, 0, 0 ]
[ "If you got here more recently, I have updated to Ubuntu 21.04 but for some reason got this error. Lo and behold my python was still python 2. Then do this:\nsudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10\nThis gives python3 a higher priority than python2 when \"python\" is called. Fi...
[ -1 ]
[ "ipython", "ipython_notebook", "python" ]
stackoverflow_0030469911_ipython_ipython_notebook_python.txt
Q: Why is find_one() timing out when find() works just fine using MongoDB? The code below connects to MongoDB, then attempts to find the specified record, which exists. The collections are very small. client = pymongo.MongoClient("PRIVATE_MONGO_ACCESS_HERE?retryWrites=true&w=majority") db = client.my_db score_holder ...
Why is find_one() timing out when find() works just fine using MongoDB?
The code below connects to MongoDB, then attempts to find the specified record, which exists. The collections are very small. client = pymongo.MongoClient("PRIVATE_MONGO_ACCESS_HERE?retryWrites=true&w=majority") db = client.my_db score_holder = db['app_data'].find_one({'score_holder': True}) Result: pymongo.errors.Ser...
[ "\nThis means we can be sure I am connecting to the database\n\nI suspect that this claim is incorrect which is resulting the conclusion about the overall problem similarly being incorrect.\nWhat I believe is happening here is that the find_one() call is executing immediately but the find() is not. A (PyMongo) curs...
[ 0 ]
[]
[]
[ "mongodb", "mongodb_query", "pymongo", "python" ]
stackoverflow_0074297645_mongodb_mongodb_query_pymongo_python.txt
Q: Tried to listen to windows notification but got element not found error I'm trying to create a script where it is able to listen to windows notifications and found this website "How can i listen to windows 10 notification" I tried to use the guide from that website but unfortunately received an "Element not found"...
Tried to listen to windows notification but got element not found error
I'm trying to create a script where it is able to listen to windows notifications and found this website "How can i listen to windows 10 notification" I tried to use the guide from that website but unfortunately received an "Element not found" error. I was hoping if someone could explain to me how this error occur and ...
[ "I also ran into the same issue with \"How can i listen to windows 10 notification\"\nI cobbled together something as a workaround based on this post: Stack Overflow The LED. It takes all the notifications and prints them out.\nfrom winrt.windows.ui.notifications.management import UserNotificationListener\nfrom win...
[ 0 ]
[]
[]
[ "python", "windows_runtime" ]
stackoverflow_0074124560_python_windows_runtime.txt
Q: how to compress multiples files present in subfolders with their respective file's names. zip files should contain in respective sub folders I am very new in python pls anyone tell me how to compress files present in subfolders respectively below is my code, but it won't work can anyone guide me import os import z...
how to compress multiples files present in subfolders with their respective file's names. zip files should contain in respective sub folders
I am very new in python pls anyone tell me how to compress files present in subfolders respectively below is my code, but it won't work can anyone guide me import os import zipfile for folder, subfolders, files in os.walk('DATA'): for file in files: if file.endswith('.txt'): with zipfile.ZipFi...
[ "If I understood your problem correctly, the .zip files weren't being saved into the same directories as the .txt files. The following code should solve that issue for you. It combines the folder and file objects to create the new paths.\nimport os\nimport zipfile\n\nfor folder, subfolders, files in os.walk('DATA')...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074300623_python.txt
Q: How does the Windows Python Launcher (py.exe) find the python executable(s)? I'm trying to use the Windows Python Launcher (py.exe) for the first time. I run python in a command shell but the launcher, running in the same shell, can't find any version of python.exe to run: where python ...
How does the Windows Python Launcher (py.exe) find the python executable(s)?
I'm trying to use the Windows Python Launcher (py.exe) for the first time. I run python in a command shell but the launcher, running in the same shell, can't find any version of python.exe to run: where python C:\Python38\python.exe py --list ...
[ "You was on the right path. In your case, you would need to add the the following entries in the registry:\n[HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\3.8]\n\n[HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\3.8\\InstallPath]\n@=\"C:\\\\python38\\\\\"\n\"ExecutablePath\"=\"C:\\\\Python38\\\\python.exe\"\n\"...
[ 0 ]
[]
[]
[ "launcher", "python", "windows" ]
stackoverflow_0066824903_launcher_python_windows.txt
Q: how to align text in PIL pictures I'm trying to output text to pictures with PIL. I was able to save the texts to png pictures but they are not aligned correctly. Here is the code: size = (2000, 500) W, H = size clear = PIL.Image.new(mode="RGB", size=size, color=(255, 255, 255)) draw = ImageDraw.Draw(clear) font =...
how to align text in PIL pictures
I'm trying to output text to pictures with PIL. I was able to save the texts to png pictures but they are not aligned correctly. Here is the code: size = (2000, 500) W, H = size clear = PIL.Image.new(mode="RGB", size=size, color=(255, 255, 255)) draw = ImageDraw.Draw(clear) font = ImageFont.truetype("ARIAL.TTF", size=2...
[ "You need to use a Monotype font, which is what terminals use to align each letter. With fonts like Arial, a lowercase L is less wide than an uppercase L, messing up the alignment.\n" ]
[ 2 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0074305591_python_python_imaging_library.txt
Q: New Gtk4 App. model : CLI positional arguments I'm trying to understand how to define CLI arguments using the new Gtk4 model but I only managed to define non-positional / flagged arguments: # (...) class MyApp(Adw.Application): def __init__(self, *args, **kwargs): super().__init__( *args, ...
New Gtk4 App. model : CLI positional arguments
I'm trying to understand how to define CLI arguments using the new Gtk4 model but I only managed to define non-positional / flagged arguments: # (...) class MyApp(Adw.Application): def __init__(self, *args, **kwargs): super().__init__( *args, application_id="org.example.myapp", ...
[ "I got the solution / answer on the official Gtk community channel:\nclass MyApp(Adw.Application):\n def __init__(self, *args, **kwargs):\n super().__init__(\n *args,\n application_id=\"org.example.myapp\",\n flags=Gio.ApplicationFlags.HANDLES_OPEN,\n **kwargs\n...
[ 0 ]
[]
[]
[ "gtk4", "python" ]
stackoverflow_0074304947_gtk4_python.txt
Q: How to take the end and the begin of a numpy array I wanted to have the end and the begin of a numpy array. Example: a = np.array([1,2,3,4,5]) print(a[-2:2]) What I expected: [4,5,1] But actually it gives an empty array []. Is it somehow doable? A: here is one approach roll the array by specified count, so the ...
How to take the end and the begin of a numpy array
I wanted to have the end and the begin of a numpy array. Example: a = np.array([1,2,3,4,5]) print(a[-2:2]) What I expected: [4,5,1] But actually it gives an empty array []. Is it somehow doable?
[ "here is one approach\nroll the array by specified count, so the header rolls after the end\nthen slice the array\n\na = np.array([1,2,3,4,5])\n\n\nnp.roll(a, -1)[2:]\n\nOR\na = np.array([1,2,3,4,5])\nvalues_from_start=1\nno_of_values = 3\n\nstart = len(a) - no_of_values\n\nnp.roll(a, values_from_start*(-1) )[start...
[ 2 ]
[]
[]
[ "numpy", "python", "python_3.x" ]
stackoverflow_0074305578_numpy_python_python_3.x.txt
Q: is there a method to process dataframe? i have a dataframe llike : words ; in ; region1 ; region2 mars ; france ; marseille 3 ; marseille 1 lil ; france; lille marig ; italy; marseille 3 ; nantes 3 i want to have in output : regions ; words_list ; in_list marseille 3 ; ["mars","marig"] ; ["france","italy"] marse...
is there a method to process dataframe?
i have a dataframe llike : words ; in ; region1 ; region2 mars ; france ; marseille 3 ; marseille 1 lil ; france; lille marig ; italy; marseille 3 ; nantes 3 i want to have in output : regions ; words_list ; in_list marseille 3 ; ["mars","marig"] ; ["france","italy"] marseille 1 ; ["mars"] ; ["france"] lille ; ['lil'...
[ "Assume df is your dataframe. I think you can get the desired output if you use this :\nGroup by region1 (then region2) and get the list of values for both columns 'words' and 'in'\noutput_1 = df.groupby('region1').agg({'words': lambda x: list(x), 'in' : lambda x: list(x)}).reset_index()\noutput_2 = df.groupby('reg...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074305580_dataframe_pandas_python_python_3.x.txt
Q: Question about IF ELSE and mathematic in python Data Time,PM2.5, 1/1/2014,9 2/1/2014,10 import pandas as pd df = pd.read_csv('xx.csv') data = pd.DataFrame(df) def calculation(y): if 0 < y and y < 12: bello=data.assign(API=(50/12)*y) elif 12.1 <= y and y <= 50.4: bello=data.assign(API=(((1...
Question about IF ELSE and mathematic in python
Data Time,PM2.5, 1/1/2014,9 2/1/2014,10 import pandas as pd df = pd.read_csv('xx.csv') data = pd.DataFrame(df) def calculation(y): if 0 < y and y < 12: bello=data.assign(API=(50/12)*y) elif 12.1 <= y and y <= 50.4: bello=data.assign(API=(((100-51)/(50.4-12.1))*(y-12.1))+51) elif 50.5 <= y ...
[ "For example, you can rewrite the function for single value and use df.apply(...)\nimport pandas as pd\ndata = pd.DataFrame({'PM2.5': [15, 50, 1000]})\n\ndef calculation(y):\n if 0<y<12:\n return (50/12)*y\n elif 12.1 <= y <= 50.4:\n return (((100-51)/(50.4-12.1))*(y-12.1))+51\n ## .... \n ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074305378_pandas_python.txt
Q: Python Override non class functions with the code below when I run file a.py the output expectedly is "hello" and with file b.py I want to override bar() from a so I get a "Goodbye" as a result My goal with this is to change a more complicated function alongside of a program while implementing simpler functions i...
Python Override non class functions
with the code below when I run file a.py the output expectedly is "hello" and with file b.py I want to override bar() from a so I get a "Goodbye" as a result My goal with this is to change a more complicated function alongside of a program while implementing simpler functions in the main program I understand that clas...
[ "As everyone has mentioned my only options would be to change my code to Object Oriented or to duplicate all the dependent functions into the new module\n" ]
[ 0 ]
[]
[]
[ "overriding", "python" ]
stackoverflow_0074292777_overriding_python.txt