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: Best method to measure execution time of a python snippet I want to compare execution time of two snippets and see which one is faster. So, I want an accurate method to measure execution time of my python snippets. I already tried using time.time(), time.process_time(), time.perf_counter_ns() as well as timeit.timeit(), but I am facing the same issues with all of the them. That is: when I use any of the above methods to measure execution time of THE SAME snippet, it returns a different value each time I run it. And this variation is somewhat significant, to the extent that I cannot reliably use them to compare difference in execution time of two snippets. As an example, I am running following code in my google colab: import time t1 = time.perf_counter() sample_list = [] for i in range(1000000): sample_list.append(i) t2 = time.perf_counter() print(t2 - t1) I ran above code 10 times and the variation in my results is about 50% (min value = 0.14, max value = 0.28). Any alternatives? A: The execution time of a given code snippet will almost always be different every time you run it. Most tools that are available for profiling a single function/snippet of code take this into account, and run the code multiple times to be able to provide an average execution time. The reason for this is that there are other processes running on your computer, and resources are not always allocated the same way, so it is impossible to control every variable so that you get the same execution time for every run. One of the easiest ways to profile a given function or short snippet of code is using the %timeit "magic" command in ipython. Example: >>> %timeit 1 + 1 8.41 ns ± 0.0181 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each) It also allows you to enter a multi-line block of code to time if you use %%timeit instead of %timeit. The timeit library can be used independently, but it is often easier to use in an interactive ipython session. Additional resources: How to profile my code? What is %timeit in Python? How can I time a code segment for testing performance with Pythons timeit?
Best method to measure execution time of a python snippet
I want to compare execution time of two snippets and see which one is faster. So, I want an accurate method to measure execution time of my python snippets. I already tried using time.time(), time.process_time(), time.perf_counter_ns() as well as timeit.timeit(), but I am facing the same issues with all of the them. That is: when I use any of the above methods to measure execution time of THE SAME snippet, it returns a different value each time I run it. And this variation is somewhat significant, to the extent that I cannot reliably use them to compare difference in execution time of two snippets. As an example, I am running following code in my google colab: import time t1 = time.perf_counter() sample_list = [] for i in range(1000000): sample_list.append(i) t2 = time.perf_counter() print(t2 - t1) I ran above code 10 times and the variation in my results is about 50% (min value = 0.14, max value = 0.28). Any alternatives?
[ "The execution time of a given code snippet will almost always be different every time you run it. Most tools that are available for profiling a single function/snippet of code take this into account, and run the code multiple times to be able to provide an average execution time. The reason for this is that there are other processes running on your computer, and resources are not always allocated the same way, so it is impossible to control every variable so that you get the same execution time for every run.\nOne of the easiest ways to profile a given function or short snippet of code is using the %timeit \"magic\" command in ipython. Example:\n>>> %timeit 1 + 1\n8.41 ns ± 0.0181 ns per loop (mean ± std. dev. of 7 runs, 100,000,000 loops each)\n\nIt also allows you to enter a multi-line block of code to time if you use %%timeit instead of %timeit.\nThe timeit library can be used independently, but it is often easier to use in an interactive ipython session.\nAdditional resources:\n\nHow to profile my code?\nWhat is %timeit in Python?\nHow can I time a code segment for testing performance with Pythons timeit?\n\n" ]
[ 3 ]
[]
[]
[ "python", "time", "timeit" ]
stackoverflow_0074495814_python_time_timeit.txt
Q: How to create a pandas dataframe using a list of 'epoch dates' into '%Y-%m-%d %s:%m:%f%z' format? My objective is to create the following pandas dataframe (with the 'date_time' column in '%Y-%m-%d %s:%m:%f%z' format): batt_no date_time 3 4 2019-09-19 20:59:06+00:00 4 5 2019-09-19 23:44:07+00:00 5 6 2019-09-20 00:44:06+00:00 6 7 2019-09-20 01:14:06+00:00 But the constraint is that I don't want to first create a dataframe as follows and then convert the 'date_time' column into the above format. batt_no date_time 3 4 1568926746 4 5 1568936647 5 6 1568940246 6 7 1568942046 I need to directly create it by converting two lists of values into the desired dataframe. The following is what I've tried but I get an error (please note: the 'date_time' values are in epoch format which I need to specify but have them converted into the '%Y-%m-%d %s:%m:%f%z' format): pd.DataFrame({'batt_volt':[4,5,6,7], 'date_time':[1568926746,1568936647,1568940246,1568942046].dt.strftime('%Y-%m-%d %s:%m:%f%z')}, index=[3,4,5,6]) Can anyone please help? Edit Note: My question is different from the one asked here. The question there deals with conversion of a single value of pandas datetime to unix timestamp. Mine's different because: My timestamp values are slightly different from any of the types mentioned there I don't need to convert any timestamp value, rather create a full-fledged dataframe having values of the desired timestamp - in a particular manner using lists that I've clearly mentioned in my question. I've clearly stated the way I've attempted the process but requires some modifications in order to run without error, which in no way is similar to the question asked in the aforementioned link. Hence, my question is definitely different. I'd request to kindly reopen it. A: As suggested, I put the solution in comment as an answer here. pd.DataFrame({'batt_volt':[4,5,6,7], 'date_time': pd.to_datetime([1568926746,1568936647,1568940246,1568942046], unit='s', utc=True).strftime('%Y-%m-%d %s:%m:%f%z')}, index=[3,4,5,6]) pd.to_datetime works with dates, or list of dates, and input dates can be in many formats including epoch int. Keyword unit ensure that those ints are interpreted as a number of seconds since 1970-01-01, not of ms, μs, ns, ... So it is quite easy to use when creating a DataFrame to create directly the list of dates. Since a list of string, with a specific format was wanted (btw, outside any specific context, I maintain that it is probably preferable to store datetimes, and convert to string only for I/O operations. But I don't know the specific context), we can use .strftime on the result, which is of type DatetimeIndex when to_datetime is called with a list. And .strftime also works on those, and then is applied on all datetimes of the list. So we get a list of string of the wanted format. Last remaining problem was the timezone. And here, there is no perfect solution. Because a simple int as those we had at the beginning does not carry a timezone. By default, to_datetime creates datetime without a timezone (like those ints are). So they are relative to any timezone the user decide they are. to_datetime can create "timezone aware datetime". But only UTC. Which is done by keyword arg utc=True With that we get timezone aware datetime, assuming that the ints we provided were in number of seconds since 1970-01-01 00:00:00+00:00
How to create a pandas dataframe using a list of 'epoch dates' into '%Y-%m-%d %s:%m:%f%z' format?
My objective is to create the following pandas dataframe (with the 'date_time' column in '%Y-%m-%d %s:%m:%f%z' format): batt_no date_time 3 4 2019-09-19 20:59:06+00:00 4 5 2019-09-19 23:44:07+00:00 5 6 2019-09-20 00:44:06+00:00 6 7 2019-09-20 01:14:06+00:00 But the constraint is that I don't want to first create a dataframe as follows and then convert the 'date_time' column into the above format. batt_no date_time 3 4 1568926746 4 5 1568936647 5 6 1568940246 6 7 1568942046 I need to directly create it by converting two lists of values into the desired dataframe. The following is what I've tried but I get an error (please note: the 'date_time' values are in epoch format which I need to specify but have them converted into the '%Y-%m-%d %s:%m:%f%z' format): pd.DataFrame({'batt_volt':[4,5,6,7], 'date_time':[1568926746,1568936647,1568940246,1568942046].dt.strftime('%Y-%m-%d %s:%m:%f%z')}, index=[3,4,5,6]) Can anyone please help? Edit Note: My question is different from the one asked here. The question there deals with conversion of a single value of pandas datetime to unix timestamp. Mine's different because: My timestamp values are slightly different from any of the types mentioned there I don't need to convert any timestamp value, rather create a full-fledged dataframe having values of the desired timestamp - in a particular manner using lists that I've clearly mentioned in my question. I've clearly stated the way I've attempted the process but requires some modifications in order to run without error, which in no way is similar to the question asked in the aforementioned link. Hence, my question is definitely different. I'd request to kindly reopen it.
[ "As suggested, I put the solution in comment as an answer here.\npd.DataFrame({'batt_volt':[4,5,6,7], 'date_time': pd.to_datetime([1568926746,1568936647,1568940246,1568942046], unit='s', utc=True).strftime('%Y-%m-%d %s:%m:%f%z')}, index=[3,4,5,6])\n\npd.to_datetime works with dates, or list of dates, and input dates can be in many formats including epoch int. Keyword unit ensure that those ints are interpreted as a number of seconds since 1970-01-01, not of ms, μs, ns, ...\nSo it is quite easy to use when creating a DataFrame to create directly the list of dates.\nSince a list of string, with a specific format was wanted (btw, outside any specific context, I maintain that it is probably preferable to store datetimes, and convert to string only for I/O operations. But I don't know the specific context), we can use .strftime on the result, which is of type DatetimeIndex when to_datetime is called with a list. And .strftime also works on those, and then is applied on all datetimes of the list. So we get a list of string of the wanted format.\nLast remaining problem was the timezone. And here, there is no perfect solution. Because a simple int as those we had at the beginning does not carry a timezone. By default, to_datetime creates datetime without a timezone (like those ints are). So they are relative to any timezone the user decide they are.\nto_datetime can create \"timezone aware datetime\". But only UTC. Which is done by keyword arg utc=True\nWith that we get timezone aware datetime, assuming that the ints we provided were in number of seconds since 1970-01-01 00:00:00+00:00\n" ]
[ 1 ]
[]
[]
[ "dataframe", "datetime", "numpy", "pandas", "python" ]
stackoverflow_0074346335_dataframe_datetime_numpy_pandas_python.txt
Q: discord bot is replying to every message that contains a word from a phrase in a list @client.event async def on_message(message): if message.author == client.user: return List = open("D:/code/code/DIscord bot/myFile.txt").readlines() List = str(List).replace("\\n", " ") if message.content in List: msg = 'REAL!' await message.reply(msg) im trying to get the bot to read all the sentences in a .txt file (one sentence per row) and then when that phrase is said in discord, itll respond with "REAL!" this all works but it seems to also respond to every message sent. A: You assign List to be a string, not an array. What you likely want is this: List = open("D:/code/code/DIscord bot/myFile.txt").readlines() List = str(List).split("\\n") This allows your in statement to check for entire sentences instead of individual words. Note, you may want to convert all the text to lowercase or do something of that sort. A: You're asking this in the context of the discord API, but it could easily be reduced to a simple str unit test. You're checking whether message.content in List. An equivalent check, which would yield greater diagnostic value, is if List.find(message.content) > -1: Why? Because upon unwanted match, you could log the numeric .find() result and examine the portion of List which matched. This includes examining the match length -- sometimes we see the empty string or another very short match which appears in the larger haystack. Log both strings, understand where the match is, and revise your logic. Do this within a discord handler, or more conveniently within a TestCase. Pep-8 asks that the identifier be spelled lst. Using the same identifier to denote first a vector and then a string is not improving the readability of the code. The Hare and the Hatter ask that we say what we mean, and mean what we say. The name was accurate upon initial assignment, but less so when re-assigned. A: Change this line into List = str(List).replace("\\n", " ") This List = list(map(lambda item: item.strip(), List)) This will remove \n from all the strings in the collection, and maintain the list datatype
discord bot is replying to every message that contains a word from a phrase in a list
@client.event async def on_message(message): if message.author == client.user: return List = open("D:/code/code/DIscord bot/myFile.txt").readlines() List = str(List).replace("\\n", " ") if message.content in List: msg = 'REAL!' await message.reply(msg) im trying to get the bot to read all the sentences in a .txt file (one sentence per row) and then when that phrase is said in discord, itll respond with "REAL!" this all works but it seems to also respond to every message sent.
[ "You assign List to be a string, not an array. What you likely want is this:\nList = open(\"D:/code/code/DIscord bot/myFile.txt\").readlines()\nList = str(List).split(\"\\\\n\")\n\nThis allows your in statement to check for entire sentences instead of individual words. Note, you may want to convert all the text to lowercase or do something of that sort.\n", "You're asking this in the context of the discord\nAPI, but it could easily be reduced to a\nsimple str unit test.\nYou're checking whether message.content in List.\nAn equivalent check, which would yield\ngreater diagnostic value, is\n if List.find(message.content) > -1:\n\nWhy? Because upon unwanted match,\nyou could log the numeric .find() result\nand examine the portion of List which\nmatched. This includes examining the\nmatch length -- sometimes we see the\nempty string or another very short match\nwhich appears in the larger haystack.\nLog both strings, understand where\nthe match is, and revise your logic.\nDo this within a discord handler,\nor more conveniently within a TestCase.\n\nPep-8 asks that the identifier be spelled lst.\n\nUsing the same identifier to denote\nfirst a vector and then a string\nis not improving the readability\nof the code.\nThe Hare and the Hatter ask that\nwe say what we mean,\nand mean what we say.\nThe name was accurate upon initial\nassignment, but less so when\nre-assigned.\n", "Change this line into\nList = str(List).replace(\"\\\\n\", \" \")\n\nThis\nList = list(map(lambda item: item.strip(), List))\n\nThis will remove \\n from all the strings in the collection, and maintain the list datatype\n" ]
[ 0, 0, 0 ]
[]
[]
[ "discord", "nextcord", "python" ]
stackoverflow_0074495513_discord_nextcord_python.txt
Q: How to identify the unfinished rectangle by image processing? I have a color image. After several preprocessing I am able to get the following image. However, as you have seen the door portion is not complete, only 3 lines are visible on the post processed one. Not the 4th boundary lin, because on the original photo, the color portion was missing at that part. Now I can identify the two windows, but how to identify the door? Is there any way to complete the unfinished part of the door as rectangle ? The yellow ticked door is also needed to be identified. A: You want an image processing algorithm that given 3 sides of a rectangle will know to "close" the fourth one. Suppose we give you such an algorithm, how do you expect it to differentiate between the green rectangle (the door you want to detect) and the red rectangle (you do not want)? A: I beleive you should somehow take a step back from your processed image and identify a car blocking a view of the door. So it boils down to the car hood identification. Maybe use high gradient color change in this area (color quickly gradients from dark grey [door] to light grey [hood] indicating last curve to be added to three straight lines of the door).
How to identify the unfinished rectangle by image processing?
I have a color image. After several preprocessing I am able to get the following image. However, as you have seen the door portion is not complete, only 3 lines are visible on the post processed one. Not the 4th boundary lin, because on the original photo, the color portion was missing at that part. Now I can identify the two windows, but how to identify the door? Is there any way to complete the unfinished part of the door as rectangle ? The yellow ticked door is also needed to be identified.
[ "You want an image processing algorithm that given 3 sides of a rectangle will know to \"close\" the fourth one.\nSuppose we give you such an algorithm, how do you expect it to differentiate between the green rectangle (the door you want to detect) and the red rectangle (you do not want)?\n\n", "I beleive you should somehow take a step back from your processed image and identify a car blocking a view of the door.\nSo it boils down to the car hood identification. Maybe use high gradient color change in this area (color quickly gradients from dark grey [door] to light grey [hood] indicating last curve to be added to three straight lines of the door).\n" ]
[ 0, 0 ]
[]
[]
[ "image_processing", "image_segmentation", "opencv", "python" ]
stackoverflow_0071503894_image_processing_image_segmentation_opencv_python.txt
Q: Why can't I establish a tcp connection, via sockets in python, with a root name server? Background: I want to establish a TCP connection with a root name server so I can send a dns query and inspect the response I tried establishing a TCP connection with a root name server using the socket module in python, particularly with a.root-servers.net I wrote the code below in an interactive python shell, in Windows 11. I ran: import socket a = socket.socket() a.connect(("a.root-servers.net", 53)) But I get the error: TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Why is this the case? A: I get good virtual circuit (TCP) results from this: $ time dig +vc +norec ns . @a.root-servers.net ; <<>> DiG 9.10.6 <<>> +vc +norec ns . @a.root-servers.net ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 60546 ;; flags: qr aa; QUERY: 1, ANSWER: 13, AUTHORITY: 0, ADDITIONAL: 27 ... ;; Query time: 13 msec ;; SERVER: 198.41.0.4#53(198.41.0.4) ;; WHEN: Fri Nov 18 14:38:22 PST 2022 ;; MSG SIZE rcvd: 828 real 0m0.056s The end-to-end path from your client to the root server is different from mine. Unlike mine, it has one or more filtering routers (firewalls) that discard port 53 TCP packets. Doing so violates section 6.1.3.2 of rfc 1123 host requirements. It is essential to allow TCP domain requests through, as some DNS answers will not fit within limited size UDP datagrams. Recommend you ask your local firewall admin to fix its config, or seek an alternate internet connectivity solution.
Why can't I establish a tcp connection, via sockets in python, with a root name server?
Background: I want to establish a TCP connection with a root name server so I can send a dns query and inspect the response I tried establishing a TCP connection with a root name server using the socket module in python, particularly with a.root-servers.net I wrote the code below in an interactive python shell, in Windows 11. I ran: import socket a = socket.socket() a.connect(("a.root-servers.net", 53)) But I get the error: TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Why is this the case?
[ "I get good virtual circuit (TCP) results from this:\n$ time dig +vc +norec ns . @a.root-servers.net\n\n; <<>> DiG 9.10.6 <<>> +vc +norec ns . @a.root-servers.net\n;; global options: +cmd\n;; Got answer:\n;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 60546\n;; flags: qr aa; QUERY: 1, ANSWER: 13, AUTHORITY: 0, ADDITIONAL: 27\n...\n;; Query time: 13 msec\n;; SERVER: 198.41.0.4#53(198.41.0.4)\n;; WHEN: Fri Nov 18 14:38:22 PST 2022\n;; MSG SIZE rcvd: 828\n\n\nreal 0m0.056s\n\nThe end-to-end path from your client\nto the root server is different from mine.\nUnlike mine, it has one or more filtering\nrouters (firewalls) that discard port 53\nTCP packets.\nDoing so violates section 6.1.3.2\nof rfc 1123 host requirements.\nIt is essential to allow TCP domain\nrequests through, as some DNS answers\nwill not fit within limited size\nUDP datagrams.\n\nRecommend you ask your local firewall\nadmin to fix its config, or seek an\nalternate internet connectivity solution.\n" ]
[ 1 ]
[]
[]
[ "dns", "python", "sockets", "tcp", "windows" ]
stackoverflow_0074495961_dns_python_sockets_tcp_windows.txt
Q: Attempt to scrape search results from a site - Python I needed to scrape the telefone numbers and the email addreses from the following using python: url = 'https://rma.cultura.gob.ar/#/app/museos/resultados?provincias=Buenos%20Aires' source = requests.get(url).text soup = BeautifulSoup(source, 'lxml') print(soup) The problem is that what I get from the requests.get is not the html that I need. I suppose the site uses javascript to show those results but I'm not familiar with that since I'm just starting with python programming. I solved this by copying the code of each result page to an unique text file and then extracting the emails with regex but I'm curious if there is something simple to be done to access the data directly. A: The data you see on the page is loaded from external URL via JavaScript. To get the data you can use requests/json modules, for example: import json import requests api_url = "https://rmabackend.cultura.gob.ar/api/museos" params = { "estado": "Publicado", "grupo": "Museo", "o": "p", "ordenar": "nombre_oficial_institucion", "page": 1, "page_size": "12", "provincias": "Buenos Aires", } while True: data = requests.get(api_url, params=params).json() # uncomment this to print all data: # print(json.dumps(data, indent=4)) for d in data["data"]: print(d["attributes"]["nombre-oficial-institucion"]) if params["page"] == data["meta"]["pagination"]["pages"]: break params["page"] += 1 Prints: 2 Museos, Bellas Artes y MAC Archivo Histórico y Museo "Astillero Río Santiago" (ARS) Archivo Histórico y Museo del Servicio Penitenciario Bonaerense Archivo y Museo Historico Municipal Roberto T. Barili "Villa Mitre" Asociación Casa Bruzzone Biblioteca Popular y Museo "José Manuel Estrada" Casa Museo "Haroldo Conti" Casa Museo "Xul Solar" - Tigre Complejo Histórico y Museográfico "Dr. Alfredo Antonio Sabaté" ...and so on. A: The page is using AJAX to load content. Using something like Selenium to simulate the browser will allow all the javascript to run and then you can extract the source: from selenium import webdriver from bs4 import BeautifulSoup from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() url = 'https://rma.cultura.gob.ar/#/app/museos/resultados?provincias=Buenos%20Aires' # navigate to the page driver.get(url) # wait until a link with text 'ficha' has loaded WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, 'ficha'))) source = driver.page_source soup = BeautifulSoup(source, features='lxml') driver.quit()
Attempt to scrape search results from a site - Python
I needed to scrape the telefone numbers and the email addreses from the following using python: url = 'https://rma.cultura.gob.ar/#/app/museos/resultados?provincias=Buenos%20Aires' source = requests.get(url).text soup = BeautifulSoup(source, 'lxml') print(soup) The problem is that what I get from the requests.get is not the html that I need. I suppose the site uses javascript to show those results but I'm not familiar with that since I'm just starting with python programming. I solved this by copying the code of each result page to an unique text file and then extracting the emails with regex but I'm curious if there is something simple to be done to access the data directly.
[ "The data you see on the page is loaded from external URL via JavaScript. To get the data you can use requests/json modules, for example:\nimport json\nimport requests\n\napi_url = \"https://rmabackend.cultura.gob.ar/api/museos\"\n\nparams = {\n \"estado\": \"Publicado\",\n \"grupo\": \"Museo\",\n \"o\": \"p\",\n \"ordenar\": \"nombre_oficial_institucion\",\n \"page\": 1,\n \"page_size\": \"12\",\n \"provincias\": \"Buenos Aires\",\n}\n\nwhile True:\n data = requests.get(api_url, params=params).json()\n\n # uncomment this to print all data:\n # print(json.dumps(data, indent=4))\n\n for d in data[\"data\"]:\n print(d[\"attributes\"][\"nombre-oficial-institucion\"])\n\n if params[\"page\"] == data[\"meta\"][\"pagination\"][\"pages\"]:\n break\n\n params[\"page\"] += 1\n\nPrints:\n2 Museos, Bellas Artes y MAC\nArchivo Histórico y Museo \"Astillero Río Santiago\" (ARS)\nArchivo Histórico y Museo del Servicio Penitenciario Bonaerense\nArchivo y Museo Historico Municipal Roberto T. Barili \"Villa Mitre\"\nAsociación Casa Bruzzone\nBiblioteca Popular y Museo \"José Manuel Estrada\"\nCasa Museo \"Haroldo Conti\"\nCasa Museo \"Xul Solar\" - Tigre\nComplejo Histórico y Museográfico \"Dr. Alfredo Antonio Sabaté\"\n\n\n...and so on.\n\n", "The page is using AJAX to load content. Using something like Selenium to simulate the browser will allow all the javascript to run and then you can extract the source:\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\ndriver = webdriver.Chrome()\nurl = 'https://rma.cultura.gob.ar/#/app/museos/resultados?provincias=Buenos%20Aires'\n\n# navigate to the page\ndriver.get(url)\n# wait until a link with text 'ficha' has loaded\nWebDriverWait(driver, 10).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, 'ficha')))\nsource = driver.page_source\nsoup = BeautifulSoup(source, features='lxml')\ndriver.quit()\n\n" ]
[ 1, 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074495820_python_web_scraping.txt
Q: How to connect to GCP Memorystore redis from local? I am able to access GCP Memorystore Redis from gcp cloud run through vpc connector. But how can I do that from my localhost ? A: You can connect from a localhost machine with port forwarding and it can be helpful to connect to your Redis instance during development. Create a compute engine instance by running the following command: gcloud compute instances create NAME --machine-type=f1-micro --zone=ZONE Open a new terminal on your local machine. To create an SSH tunnel that port forwards traffic through the Compute Engine VM, run the following command: gcloud compute ssh COMPUTE_VM_NAME --zone=ZONE -- -N -L 6379:REDIS_INSTANCE_IP_ADDRESS:6379 To test the connection, open a new terminal window and run the following command: redis-cli ping The SSH tunnel remains open as long as you keep the terminal window with the SSH tunnel connection up and running. I suggest you use the link for setting up a development environment. A: If you are using Redis as caching-only, or simple pub/sub, I would just spin up a local redis container for development.
How to connect to GCP Memorystore redis from local?
I am able to access GCP Memorystore Redis from gcp cloud run through vpc connector. But how can I do that from my localhost ?
[ "You can connect from a localhost machine with port forwarding and it can be helpful to connect to your Redis instance during development.\nCreate a compute engine instance by running the following command:\n gcloud compute instances create NAME --machine-type=f1-micro --zone=ZONE\n\nOpen a new terminal on your local machine.\nTo create an SSH tunnel that port forwards traffic through the Compute Engine VM, run the following command:\n gcloud compute ssh COMPUTE_VM_NAME --zone=ZONE -- -N -L 6379:REDIS_INSTANCE_IP_ADDRESS:6379\n\n\nTo test the connection, open a new terminal window and run the following command:\n redis-cli ping\n\n\nThe SSH tunnel remains open as long as you keep the terminal window with the SSH tunnel connection up and running.\n\n\nI suggest you use the link for setting up a development environment.\n", "If you are using Redis as caching-only, or simple pub/sub, I would just spin up a local redis container for development.\n" ]
[ 2, 0 ]
[]
[]
[ "google_cloud_platform", "python" ]
stackoverflow_0068407501_google_cloud_platform_python.txt
Q: With list of tuples corresponding to int values, want to create a unique list of those tuples corresponding to the sum of all the int values (python) I have a huge list of sublists, each sublist consisting of a tuple and an int. Example: [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]] I want to create a unique list of those tuples corresponding to the sum of all those integer values using python. For the example above, my desired output looks like this: [[(1, 1), 71], [(1, 2), 44.5], [(1, 3), 24], [(1, 4), 22], [(1, 5), 27], [(1, 6), 9.5]] Could I get some help on how to do this? I have tried to use dictionaries to solve this problem, but I keep running into errors, as I am not too familiar with how to use them. A: You can try this (though there's probably a shorter way): a= [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]] b = {} for l in a: if b.get(l[0]): b[l[0]] += l[1] else: b[l[0]] = l[1] c = [[x,y] for x,y in b.items()] # [[(1, 1), 71.0], # [(1, 2), 44.5], # [(1, 3), 24.0], # [(1, 4), 22.0], # [(1, 5), 27.0], # [(1, 6), 9.5]] A: Using a dictionary to solve. Since it's a list of lists, you will need to specify what you want the key in the dictionary to be. In this case you wan't it to be the tuple. So when looping through that'll be at index 0 e.g. item[0]. You set the number as the value item[1] to the tuple. So you add to dictionary, if it's already in dictionary you add the two number "+=" if it's not in dictionary you just set the value "=" example = [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]] dict_tuples = {} # tuple will be key in dict for item in example: #see if tuple item[0] is in dict. # if it's in dict already, add to it's value if item[0] in dict_tuples: dict_tuples[item[0]] += item[1] # if it's not in dict else: dict_tuples[item[0]] = item[1] # if you want it back in a list alist = list(dict_tuples.items()) print(alist) A: Solution A method using defaultdict goes like this: from collections import defaultdict L = [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]] out = defaultdict(lambda: 0) for [key, val] in L: out[key] += val out = [[each] for each in out.items()] Returns: [[((1, 1), 71.0)], [((1, 2), 44.5)], [((1, 3), 24.0)], [((1, 4), 22.0)], [((1, 5), 27.0)], [((1, 6), 9.5)]] Explanation: out is created as a defaultdict, such that out[somekey] returns 0 if somekey is not already a key in out. We then go through every [tuple-int] in your original list, and add the value of int to out[tuple]. If tuple isn't already a key in out, then tuple takes its place among out's keys and the value assigned to it becomes int. Finally we loop through out to reshape it into the form you wanted - [[tuple, int]]. If this particular format's not too important to you, you could skip that last step and just convert out.items() to a list like this: print (list(out.items())) # returns: [((1, 1), 71.0), ((1, 2), 44.5), ((1, 3), 24.0), ((1, 4), 22.0), ((1, 5), 27.0), ((1, 6), 9.5)]
With list of tuples corresponding to int values, want to create a unique list of those tuples corresponding to the sum of all the int values (python)
I have a huge list of sublists, each sublist consisting of a tuple and an int. Example: [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]] I want to create a unique list of those tuples corresponding to the sum of all those integer values using python. For the example above, my desired output looks like this: [[(1, 1), 71], [(1, 2), 44.5], [(1, 3), 24], [(1, 4), 22], [(1, 5), 27], [(1, 6), 9.5]] Could I get some help on how to do this? I have tried to use dictionaries to solve this problem, but I keep running into errors, as I am not too familiar with how to use them.
[ "You can try this (though there's probably a shorter way):\na= [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]]\n\nb = {}\n\nfor l in a:\n if b.get(l[0]):\n b[l[0]] += l[1]\n else:\n b[l[0]] = l[1]\n\nc = [[x,y] for x,y in b.items()]\n\n# [[(1, 1), 71.0],\n# [(1, 2), 44.5],\n# [(1, 3), 24.0],\n# [(1, 4), 22.0],\n# [(1, 5), 27.0],\n# [(1, 6), 9.5]]\n\n", "Using a dictionary to solve.\nSince it's a list of lists, you will need to specify what you want the key in the dictionary to be. In this case you wan't it to be the tuple. So when looping through that'll be at index 0 e.g. item[0]. You set the number as the value item[1] to the tuple. So you add to dictionary, if it's already in dictionary you add the two number \"+=\" if it's not in dictionary you just set the value \"=\"\nexample = [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]]\n\ndict_tuples = {}\n# tuple will be key in dict\nfor item in example:\n #see if tuple item[0] is in dict. \n # if it's in dict already, add to it's value\n if item[0] in dict_tuples:\n dict_tuples[item[0]] += item[1]\n # if it's not in dict \n else:\n dict_tuples[item[0]] = item[1]\n\n# if you want it back in a list\nalist = list(dict_tuples.items())\nprint(alist)\n\n", "Solution\nA method using defaultdict goes like this:\nfrom collections import defaultdict\n\nL = [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]]\n\nout = defaultdict(lambda: 0)\n\nfor [key, val] in L:\n out[key] += val\n\nout = [[each] for each in out.items()]\n\nReturns:\n[[((1, 1), 71.0)], [((1, 2), 44.5)], [((1, 3), 24.0)], [((1, 4), 22.0)], [((1, 5), 27.0)], [((1, 6), 9.5)]]\n\nExplanation:\nout is created as a defaultdict, such that out[somekey] returns 0 if somekey is not already a key in out.\nWe then go through every [tuple-int] in your original list, and add the value of int to out[tuple]. If tuple isn't already a key in out, then tuple takes its place among out's keys and the value assigned to it becomes int.\nFinally we loop through out to reshape it into the form you wanted - [[tuple, int]]. If this particular format's not too important to you, you could skip that last step and just convert out.items() to a list like this:\nprint (list(out.items())) \n# returns:\n[((1, 1), 71.0), ((1, 2), 44.5), ((1, 3), 24.0), ((1, 4), 22.0), ((1, 5), 27.0), ((1, 6), 9.5)]\n\n" ]
[ 1, 1, 1 ]
[]
[]
[ "list", "python", "tuples", "unique" ]
stackoverflow_0074495864_list_python_tuples_unique.txt
Q: How to use a parameter and its reciprocal in a CVXPY DPP? In the following test program import cvxpy as cp def cp_log_ratio_norm(a, b): # Both `a * cp.inv_pos(b)` and `a / b` make this problem non-DPP return cp.maximum(a * b, b * cp.inv_pos(a)) var = cp.Variable(pos=True) param = cp.Parameter(pos=True) param.value = 5 objective = cp.Minimize(cp_log_ratio_norm(var, param)) problem = cp.Problem(objective, []) objective_value = problem.solve() print(f"Objective value = {objective_value}") print(f"Status = {problem.status}") we see that using the reciprocal of a parameter causes DPP (disciplined parameterized programming) to break with the message: miniconda3/envs/faster-unmixer/lib/python3.10/site-packages/cvxpy/reductions/solvers/solving_chain.py:178: UserWarning: You are solving a parameterized problem that is not DPP. Because the problem is not DPP, subsequent solves will not be faster than the first one. For more information, see the documentation on Discplined Parametrized Programming, at https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming How can I make this work? A: Looking at the docs we find that this is expected: As another example, the quotient expr / p is not DPP-compliant when p is a parameter, but this can be rewritten as expr * p_tilde, where p_tilde is a parameter that represents 1/p. But in your case we need both p and 1 / p? Keeping those two synchronized is challenging. We can use a class we'll call ReciprocalParameter to make it easier. import cvxpy as cp from typing import Optional class ReciprocalParameter: """Used for times when you want a cvxpy Parameter and its ratio""" def __init__(self, *args, **kwargs) -> None: self._p = cp.Parameter(*args, **kwargs) # Reciprocal of the above self._rp = cp.Parameter(*args, **kwargs) @property def value(self) -> Optional[float]: """Return the value of the Parameter""" return self._p.value @value.setter def value(self, val: Optional[float]) -> None: """ Simultaneously set the value of the Parameter (given by `p`) and its reciprocal (given by `rp`) """ self._p.value = val self._rp.value = 1 / val if val is not None else None @property def p(self) -> cp.Parameter: """Returns the parameter""" return self._p @property def rp(self) -> cp.Parameter: """Returns the reciprocal of the parameter""" return self._rp def cp_log_ratio_norm(a, b: ReciprocalParameter): # Both `a * cp.inv_pos(b)` and `a / b` make this problem non-DPP return cp.maximum(a * b.rp, b.p * cp.inv_pos(a)) var = cp.Variable(pos=True) param = ReciprocalParameter(pos=True) param.value = 5 objective = cp.Minimize(cp_log_ratio_norm(var, param)) problem = cp.Problem(objective, []) objective_value = problem.solve() print(f"Objective value = {objective_value}") print(f"Status = {problem.status}") Note that we treat ReciprocalParameter just like a normal cvxpy.Parameter until the point of use when we are forced to decide whether we want the parameter's value (ReciprocalParameter.p) or its reciprocal (ReciprocalParameter.rp).
How to use a parameter and its reciprocal in a CVXPY DPP?
In the following test program import cvxpy as cp def cp_log_ratio_norm(a, b): # Both `a * cp.inv_pos(b)` and `a / b` make this problem non-DPP return cp.maximum(a * b, b * cp.inv_pos(a)) var = cp.Variable(pos=True) param = cp.Parameter(pos=True) param.value = 5 objective = cp.Minimize(cp_log_ratio_norm(var, param)) problem = cp.Problem(objective, []) objective_value = problem.solve() print(f"Objective value = {objective_value}") print(f"Status = {problem.status}") we see that using the reciprocal of a parameter causes DPP (disciplined parameterized programming) to break with the message: miniconda3/envs/faster-unmixer/lib/python3.10/site-packages/cvxpy/reductions/solvers/solving_chain.py:178: UserWarning: You are solving a parameterized problem that is not DPP. Because the problem is not DPP, subsequent solves will not be faster than the first one. For more information, see the documentation on Discplined Parametrized Programming, at https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming How can I make this work?
[ "Looking at the docs we find that this is expected:\n\nAs another example, the quotient expr / p is not DPP-compliant when p is a parameter, but this can be rewritten as expr * p_tilde, where p_tilde is a parameter that represents 1/p.\n\nBut in your case we need both p and 1 / p? Keeping those two synchronized is challenging. We can use a class we'll call ReciprocalParameter to make it easier.\nimport cvxpy as cp\nfrom typing import Optional\n\nclass ReciprocalParameter:\n \"\"\"Used for times when you want a cvxpy Parameter and its ratio\"\"\"\n\n def __init__(self, *args, **kwargs) -> None:\n self._p = cp.Parameter(*args, **kwargs)\n # Reciprocal of the above\n self._rp = cp.Parameter(*args, **kwargs)\n\n @property\n def value(self) -> Optional[float]:\n \"\"\"Return the value of the Parameter\"\"\"\n return self._p.value\n\n @value.setter\n def value(self, val: Optional[float]) -> None:\n \"\"\"\n Simultaneously set the value of the Parameter (given by `p`)\n and its reciprocal (given by `rp`)\n \"\"\"\n self._p.value = val\n self._rp.value = 1 / val if val is not None else None\n\n @property\n def p(self) -> cp.Parameter:\n \"\"\"Returns the parameter\"\"\"\n return self._p\n\n @property\n def rp(self) -> cp.Parameter:\n \"\"\"Returns the reciprocal of the parameter\"\"\"\n return self._rp\n\ndef cp_log_ratio_norm(a, b: ReciprocalParameter):\n # Both `a * cp.inv_pos(b)` and `a / b` make this problem non-DPP\n return cp.maximum(a * b.rp, b.p * cp.inv_pos(a))\n\nvar = cp.Variable(pos=True)\nparam = ReciprocalParameter(pos=True)\nparam.value = 5\nobjective = cp.Minimize(cp_log_ratio_norm(var, param))\nproblem = cp.Problem(objective, [])\nobjective_value = problem.solve()\n\nprint(f\"Objective value = {objective_value}\")\nprint(f\"Status = {problem.status}\")\n\nNote that we treat ReciprocalParameter just like a normal cvxpy.Parameter until the point of use when we are forced to decide whether we want the parameter's value (ReciprocalParameter.p) or its reciprocal (ReciprocalParameter.rp).\n" ]
[ 1 ]
[]
[]
[ "convex_optimization", "cvxpy", "mathematical_optimization", "python" ]
stackoverflow_0074496052_convex_optimization_cvxpy_mathematical_optimization_python.txt
Q: Add multiple unknowns to a string in Pyton I need to add to the line: url="items.point&point1={item}%2C{item}&point2C{item}%2C{item}" four values ​​of possible coordinates instead of "item" value. We have to generate these coordinate values ​​in a loop. I tried many different options for how to do this, but the program displays a lot of extra values. My code: import numpy as np coordinates=[] for item in np.arange(45.024287,45.024295,0.000001): coordinates.append("%.6f" %item) for item in np.arange(45.024287,45.024295,0.000001): coordinates.append("%.6f" %item) urls=[] for item in (coordinates): urls.append(f"items.point&point1{item}%2C{item}&point2={item}%2C{item}") print(urls) I need to get this result: "items.point&point1=45.024295%2C45.024295&point2=39.073557%2C45.005125","items.point&point1=45.024294%2C45.024294&point2=39.073557%2C45.005125"...Etc With different coordinates But I am getting repeated values ​​due to the fact that the loop is in a loop. Can you tell me how you can substitute several variables in a string without doubling the values?Please A: I remember reading recently something related to your problem. Can't remember the post, else I'd link it, but I took notes about the beautiful method! So try this: urls=[] for item1, item2 in zip(*[iter(coordinates)]*2): urls.append(f"items.point&point1{item1}%2C{item2}&point2=39.073557%2C45.005125") print(urls) A: There's no need for the coordinates array. Just append to urls in the nested for loop to get all the combinations of item values. for item1 in np.arange(45.024287,45.024295,0.000001): for item2 in np.arange(45.024287,45.024295,0.000001): urls.append(f"items.point&point1={item1}%2C{item2}&point2=39.073557%2C45.005125")
Add multiple unknowns to a string in Pyton
I need to add to the line: url="items.point&point1={item}%2C{item}&point2C{item}%2C{item}" four values ​​of possible coordinates instead of "item" value. We have to generate these coordinate values ​​in a loop. I tried many different options for how to do this, but the program displays a lot of extra values. My code: import numpy as np coordinates=[] for item in np.arange(45.024287,45.024295,0.000001): coordinates.append("%.6f" %item) for item in np.arange(45.024287,45.024295,0.000001): coordinates.append("%.6f" %item) urls=[] for item in (coordinates): urls.append(f"items.point&point1{item}%2C{item}&point2={item}%2C{item}") print(urls) I need to get this result: "items.point&point1=45.024295%2C45.024295&point2=39.073557%2C45.005125","items.point&point1=45.024294%2C45.024294&point2=39.073557%2C45.005125"...Etc With different coordinates But I am getting repeated values ​​due to the fact that the loop is in a loop. Can you tell me how you can substitute several variables in a string without doubling the values?Please
[ "I remember reading recently something related to your problem. Can't remember the post, else I'd link it, but I took notes about the beautiful method! So try this:\nurls=[]\nfor item1, item2 in zip(*[iter(coordinates)]*2):\n urls.append(f\"items.point&point1{item1}%2C{item2}&point2=39.073557%2C45.005125\")\nprint(urls)\n\n", "There's no need for the coordinates array. Just append to urls in the nested for loop to get all the combinations of item values.\nfor item1 in np.arange(45.024287,45.024295,0.000001):\n for item2 in np.arange(45.024287,45.024295,0.000001):\n urls.append(f\"items.point&point1={item1}%2C{item2}&point2=39.073557%2C45.005125\")\n\n" ]
[ 1, 0 ]
[]
[]
[ "loops", "python", "string" ]
stackoverflow_0074495932_loops_python_string.txt
Q: How do I open the main window and all the other Windows remain hidden untill called? I have a bunch of Tk() throughout my program. So when I first run main all these other windows come on to the screen and I have to minimize them to get the main window on front. How do I prevent these windows from opening and just open the main window? There are 3 or 4 .py files imported by the main. I've tried withdraw(),iconify(),tkraise() most of the windows are widgets with frames on them as many as 5 on some.import bids import bids import jobs import costs import accounting import customers import labor import sales import vendors import tkinter as tk from job_notes import JobNotes def Main(): root1 = tk.Tk() a_menu = tk.Menu(root1) root1.config(menu = a_menu) root1.geometry('1600x1275') root1.title("The Upper menu box |") the_label = tk.Label(root1,text= " ***** Use The Menu Above for Menu Implementation ****** ",font=('verdana',42,'bold'),relief='raised') the_label.grid(row=0,column=0) label1 = tk.Label(root1,text="1.To Create a Bid select (File: 'Create an Estimate' from the menu above",font=('verdana',18,'bold'),relief ="raised") label1.grid(row=1,column=0,pady=10) label2 = tk.Label(root1,text="2.To Change a Bid into a Job select View/Edit: 'View/Edit an Estimate' than Confirm the Bid",font=('verdana',18,'bold')) label2.grid(row=2,column=0,pady=10) label3 = tk.Label(root1,text="3.To view/edit a Job go to View/Edit: 'View/Edit a Job'",font=('verdana',18,'bold')) label3.grid(row=3,column=0,pady=10) file_menu = tk.Menu(a_menu) a_menu.add_cascade(label="File",menu=file_menu) file_menu.add_command(label="Create an Estimate", command=bids.bid.create_bid) file_menu.add_command(label="Create Sales Order",command=sales.create_salesorder) file_menu.add_command(label="Create a work order",command=jobs.Jobs.create_workorder) file_menu.add_command(label="Create an Invoice",command=sales.create_an_invoice) file_menu.add_separator() file_menu.add_command(label="Enter A Customer",command=customers.Customer.enter_customer) file_menu.add_command(label="Enter A Vendor",command=vendors.enter_vendor) edit_menu = tk.Menu(a_menu) a_menu.add_cascade(label="View/Edit",menu=edit_menu) edit_menu.add_command(label="View/Edit an estimate",command=bids.bid.edit_bid) edit_menu.add_command(label="View/Edit Jobs",command=jobs.Jobs.tree_to_view_jobs) edit_menu.add_command(label="View/Edit a Work Order",command=jobs.Jobs.edit_work_order) edit_menu.add_separator() edit_menu.add_command(label="View/Edit Customer info",command=customers.edit_customer) edit_menu.add_command(label="View/Edit a Vendor",command=vendors.edit_vendor) add_menu = tk.Menu(a_menu) a_menu.add_cascade(label="Add",menu=add_menu) add_menu.add_command(label="Add costs",command=costs.Costs.add_cost) add_menu.add_command(label="Add Labor",command=labor.Labor.add_labor) add_menu.add_command(label="add_change_order",command=jobs.change_order) add_menu.add_separator() add_menu.add_command(label="Add Notes to job",command=jobs.add_notes) add_menu.add_separator() add_menu.add_command(label="Add a vendor invoice",command=vendors.add_vendor_invoice) add_menu.add_command(label="Add Notes to Bid",command=bids.bid.add_notes) view_menu = tk.Menu(a_menu) a_menu.add_cascade(label="View",menu=view_menu) view_menu.add_command(label="View Jobs",command=jobs.view_jobs) view_menu.add_command(label="View Work Orders",command=jobs.view_work_orders) view_menu.add_separator() view_menu.add_command(label="View Customers",command=customers.view_customers) view_menu.add_command(label="View Vendors",command=vendors.view_vendors) admin_menu = tk.Menu(a_menu) a_menu.add_cascade(label="Administrations",menu=admin_menu) # # approve vendor invoice(costs), confirm sales invoices(sales), finished jobs, accounts receivables # # accounts payable, general ledger, general journal,balance sheet,income statement # #employee payroll,Sales reports with a drop down menu, by customer, by date, by amounts # #pay sales comission, vendor rates drop down menu desc,rate # # add - to schedule root1.mainloop() if __name__ == '__main__': Main() ``` this is main.py as you can see there are a number of import an in those imports ther are multiple Tk() functions the answer is root1.focus_force() right above root1.mainloop() A: i figured out how to get the main window to come up in front of the other tkinter windows that are created by my imports root1.focus_force() called it right before root1.mainloop()
How do I open the main window and all the other Windows remain hidden untill called?
I have a bunch of Tk() throughout my program. So when I first run main all these other windows come on to the screen and I have to minimize them to get the main window on front. How do I prevent these windows from opening and just open the main window? There are 3 or 4 .py files imported by the main. I've tried withdraw(),iconify(),tkraise() most of the windows are widgets with frames on them as many as 5 on some.import bids import bids import jobs import costs import accounting import customers import labor import sales import vendors import tkinter as tk from job_notes import JobNotes def Main(): root1 = tk.Tk() a_menu = tk.Menu(root1) root1.config(menu = a_menu) root1.geometry('1600x1275') root1.title("The Upper menu box |") the_label = tk.Label(root1,text= " ***** Use The Menu Above for Menu Implementation ****** ",font=('verdana',42,'bold'),relief='raised') the_label.grid(row=0,column=0) label1 = tk.Label(root1,text="1.To Create a Bid select (File: 'Create an Estimate' from the menu above",font=('verdana',18,'bold'),relief ="raised") label1.grid(row=1,column=0,pady=10) label2 = tk.Label(root1,text="2.To Change a Bid into a Job select View/Edit: 'View/Edit an Estimate' than Confirm the Bid",font=('verdana',18,'bold')) label2.grid(row=2,column=0,pady=10) label3 = tk.Label(root1,text="3.To view/edit a Job go to View/Edit: 'View/Edit a Job'",font=('verdana',18,'bold')) label3.grid(row=3,column=0,pady=10) file_menu = tk.Menu(a_menu) a_menu.add_cascade(label="File",menu=file_menu) file_menu.add_command(label="Create an Estimate", command=bids.bid.create_bid) file_menu.add_command(label="Create Sales Order",command=sales.create_salesorder) file_menu.add_command(label="Create a work order",command=jobs.Jobs.create_workorder) file_menu.add_command(label="Create an Invoice",command=sales.create_an_invoice) file_menu.add_separator() file_menu.add_command(label="Enter A Customer",command=customers.Customer.enter_customer) file_menu.add_command(label="Enter A Vendor",command=vendors.enter_vendor) edit_menu = tk.Menu(a_menu) a_menu.add_cascade(label="View/Edit",menu=edit_menu) edit_menu.add_command(label="View/Edit an estimate",command=bids.bid.edit_bid) edit_menu.add_command(label="View/Edit Jobs",command=jobs.Jobs.tree_to_view_jobs) edit_menu.add_command(label="View/Edit a Work Order",command=jobs.Jobs.edit_work_order) edit_menu.add_separator() edit_menu.add_command(label="View/Edit Customer info",command=customers.edit_customer) edit_menu.add_command(label="View/Edit a Vendor",command=vendors.edit_vendor) add_menu = tk.Menu(a_menu) a_menu.add_cascade(label="Add",menu=add_menu) add_menu.add_command(label="Add costs",command=costs.Costs.add_cost) add_menu.add_command(label="Add Labor",command=labor.Labor.add_labor) add_menu.add_command(label="add_change_order",command=jobs.change_order) add_menu.add_separator() add_menu.add_command(label="Add Notes to job",command=jobs.add_notes) add_menu.add_separator() add_menu.add_command(label="Add a vendor invoice",command=vendors.add_vendor_invoice) add_menu.add_command(label="Add Notes to Bid",command=bids.bid.add_notes) view_menu = tk.Menu(a_menu) a_menu.add_cascade(label="View",menu=view_menu) view_menu.add_command(label="View Jobs",command=jobs.view_jobs) view_menu.add_command(label="View Work Orders",command=jobs.view_work_orders) view_menu.add_separator() view_menu.add_command(label="View Customers",command=customers.view_customers) view_menu.add_command(label="View Vendors",command=vendors.view_vendors) admin_menu = tk.Menu(a_menu) a_menu.add_cascade(label="Administrations",menu=admin_menu) # # approve vendor invoice(costs), confirm sales invoices(sales), finished jobs, accounts receivables # # accounts payable, general ledger, general journal,balance sheet,income statement # #employee payroll,Sales reports with a drop down menu, by customer, by date, by amounts # #pay sales comission, vendor rates drop down menu desc,rate # # add - to schedule root1.mainloop() if __name__ == '__main__': Main() ``` this is main.py as you can see there are a number of import an in those imports ther are multiple Tk() functions the answer is root1.focus_force() right above root1.mainloop()
[ "i figured out how to get the main window to come up in front of the other tkinter windows that are created by my imports\nroot1.focus_force()\ncalled it right before\nroot1.mainloop()\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074494090_python_tkinter.txt
Q: Pyinstaller raise a warning when I run it Hi when I try to convert my kivy python application to an executable file , it gives me the following error , any ideas on how to fix it ? PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_kivy required by hook for module /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PyInstaller/hooks/hook-kivy.py. Please check whether module __PyInstaller_hooks_0_kivy actually exists and whether the hook is compatible with your version of /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PyInstaller/hooks/hook-kivy.py: You might want to read more about hooks in the manual and provide a pull-request to improve PyInstaller. 761086 WARNING: stderr: PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_kivy required by hook for module /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PyInstaller/hooks/hook-kivy.py. Please check whether module __PyInstaller_hooks_0_kivy actually exists and whether the hook is compatible with your version of /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PyInstaller/hooks/hook-kivy.py: You might want to read more about hooks in the manual and provide a pull-request to improve PyInstaller. A: pip install -U pyinstaller-hooks-contrib
Pyinstaller raise a warning when I run it
Hi when I try to convert my kivy python application to an executable file , it gives me the following error , any ideas on how to fix it ? PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_kivy required by hook for module /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PyInstaller/hooks/hook-kivy.py. Please check whether module __PyInstaller_hooks_0_kivy actually exists and whether the hook is compatible with your version of /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PyInstaller/hooks/hook-kivy.py: You might want to read more about hooks in the manual and provide a pull-request to improve PyInstaller. 761086 WARNING: stderr: PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_kivy required by hook for module /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PyInstaller/hooks/hook-kivy.py. Please check whether module __PyInstaller_hooks_0_kivy actually exists and whether the hook is compatible with your version of /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/PyInstaller/hooks/hook-kivy.py: You might want to read more about hooks in the manual and provide a pull-request to improve PyInstaller.
[ "pip install -U pyinstaller-hooks-contrib\n" ]
[ 0 ]
[]
[]
[ "kivy", "pyinstaller", "python" ]
stackoverflow_0072601797_kivy_pyinstaller_python.txt
Q: Change python version to 3.x According to poetry's docs, the proper way to setup a new project is with poetry new poetry-demo, however this creates a project based on the now deprecated python2.7 by creating the following toml file: [tool.poetry] name = "poetry-demo" version = "0.1.0" description = "" authors = ["Harsha Goli <harshagoli@gmail.com>"] [tool.poetry.dependencies] python = "^2.7" [tool.poetry.dev-dependencies] pytest = "^4.6" [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api" How can I update this to 3.7? Simply changing python = "^2.7" to python = "^3.7" results in the following error when poetry install is run: [SolverProblemError] The current project's Python requirement (2.7.17) is not compatible with some of the required packages Python requirement: - zipp requires Python >=3.6 Because no versions of pytest match >=4.6,<4.6.9 || >4.6.9,<5.0 and pytest (4.6.9) depends on importlib-metadata (>=0.12), pytest (>=4.6,<5.0) requires importlib-metadata (>=0.12). And because no versions of importlib-metadata match >=0.12,<1.5.0 || >1.5.0 and importlib-metadata (1.5.0) depends on zipp (>=0.5), pytest (>=4.6,<5.0) requires zipp (>=0.5). Because zipp (3.1.0) requires Python >=3.6 and no versions of zipp match >=0.5,<3.1.0 || >3.1.0, zipp is forbidden. Thus, pytest is forbidden. So, because poetry-demo depends on pytest (^4.6), version solving failed. A: Poetry makes it super easy to work with different Python versions or virtual environments. The recommended way to specify your Python version according to Poetry docs is poetry env use /path/to/preferred/python/version You can get the path to your Python version by running which python3.7 on Linux or py -0p on Windows. A: Whenever you change dependencies by hand in your pyproject.toml you have to take care of these points: Run poetry lock --no-update afterwards. The reasons for this is, that poetry install takes the poetry.lock as input if can find one and not the pyproject.toml. If you change the python version and uses in-project virtualenv, remove the .venv before running poetry install. poetry doesn't change the python version of a venv once it is created, because it uses the python version itself to create the virtualenv. A: Use: poetry env use 3.9 or poetry env use $(which python3.9) doesn't work for some reason for python 3.9. Though having explicitly stated version requirement in pyproject.toml file, it's sad that one needs to manually enforce this. A: Interestingly, poetry is silently failing due to a missing package the tool itself relies on and continues to install a broken venv. Here's how you fix it. sudo apt install python3-venv poetry env remove python3 poetry install I had to remove pytest, and then reinstall with poetry add pytest. EDIT: I ran into this issue again when upgrading a project from python3.7 to python3.8 - for this instead of installing python3-venv, you'd want to install python3.8-venv instead A: I had the same problem. I solve it by fixing the first line in the file /home/nordman/.poetry/bin/poetry (nordman is my local name). Just change #!/usr/bin/env python to #!/usr/bin/env python3 A: You can change in pyproject.toml and execute de this command "poetry env use 3.x" that works for me. A: I tried every solution I could find, but could not get poetry to pick up the upgraded version of Python. Finally found something that worked. tldr; Run poetry config virtualenvs.in-project true to use local venvs Run deactivate to exit any existing venv Run poetry shell to activate a new, local venv So here's what I was seeing: (my-project) ~/I/my-project ❯❯❯ poetry env info Virtualenv Python: 3.9.6 Implementation: CPython Path: /Users/my-user/.local/share/virtualenvs/my-project-some-hash Valid: True System Platform: darwin OS: posix Python: /usr/local/opt/python@3.9/Frameworks/Python.framework/Versions/3.9 I tried running poetry env remove python and got an error: (my-project) ~/I/my-project ❯❯❯ poetry env remove python ValueError Environment "my-project-some-hash-py3.9" does not exist. Meanwhile, I saw somewhere that it's recommend to use local virtual environments by setting this property, so I did it: poetry config virtualenvs.in-project true This did not solve my problem, but then I realized that changing this setting would not take affect automatically because I was already in another non-local virtual environment (see poetry env info output above). So based on the docs, I ran deactivate to deactivate the current virtual environment. Now, I saw this: ~/I/my-project ❯❯❯ poetry env info Virtualenv Python: 3.10.1 Implementation: CPython Path: NA System Platform: darwin OS: posix Python: /Users/my-user/.pyenv/versions/3.10.1 Now I ran poetry shell to create a new virtual environment and it picked up the new local venvs setting: ~/I/my-project ❯❯❯ poetry shell Creating virtualenv my-project in /Users/my-user/projects/my-project/.venv Spawning shell within /Users/my-user/projects/my-project/.venv And finally, I saw the upgraded Python version I was expecting! (.venv) ~/I/my-project ❯❯❯ poetry run python -V Python 3.10.1 Update: After I did all of the above, I noticed that poetry env use works fine! (.venv) ~/I/my-project ❯❯❯ python -V Python 3.10.1 (.venv) ~/I/my-project ❯❯❯ poetry env use 3.9.6 Recreating virtualenv my-project in /Users/my-user/projects/my-project/.venv Using virtualenv: /Users/my-user/projects/my-project/.venv (.venv) ~/I/my-project ❯❯❯ python -V Python 3.9.6 A: I've experienced the exact same behavior on my MacBook! So to make this practical, first, let's see, what is the default Python for the MacBook. I'm running macOS Big Sur 11.2.1 (20D74). In terminal: python --version Python 2.7.16 With that, let's install poetry. I've used poetry installation script from the GitHub. Using this script is a recommended method to install poetry (though I'd argue this is NOT the best idea to pipe scripts from the Internet into the python interpreter) The installation script is pretty smart: it attempts to detect which python is available on the system: def _which_python(self): """Decides which python executable we'll embed in the launcher script.""" allowed_executables = ["python", "python3"] if WINDOWS: allowed_executables += ["py.exe -3", "py.exe -2"] ... So as the default Python is 2.7.16, and that is what returned by calling python, the entry in ~/.poetry/bin will look like: #!/usr/bin/env python And here you go! The default python will end up in the pyproject.toml file and you'll need to do an extra dance to a) make sure python3 is a dependency for your project; and b) that the virtual environment will use python3 as python interpreter. As @mfalade mentioned, you can set environment with poetry env: poetry env use /path/to/python3 And also modifying the pyproject.toml with: ... [tool.poetry.dependencies] python = "^3.9" ... From this point you are good to go, poetry will use python3 to create virtual environment for you project, dependency is specified in the file and ... the grass is green again. But can we use python3 by default? There is an insightful thread on GitHub and another one. And if you look back at the code snippet from the installation script above, you might wonder why not to check for python3 first and then for python, especially taking into account that this is the exact order for Windows installation. Well, you are not alone, I also wonder ;) I would not suggest editing the ~/.poetry/bin/poetry file directly as this file is generated by the installation script (so what will happen if you run installation script again? And again?). Really, this is a minor annoyance, and knowing the tool it is easy to work around it. I'd expect that to be mentioned in installation guide though... Anyway, hope it helps! A: You can simply use pyenv for that. Create .python-version file inside your project and poetry will match the exact python version. # check current python version (set up globally) ❯ pyenv version 3.9.0 (set by /Users/tomasz.zieba@showpad.com/.python-version) # create .python-version file for project ❯ pyenv local 3.9.0 # check python version again (now it's set up locally) ❯ pyenv version 3.9.0 (set by /Users/tomasz.zieba@showpad.com/Documents/myproject/.python-version) ❯ poetry lock (...) ❯ poetry run python --version Python 3.9.0 A: The way I do it, and it's super effective: Use pyenv to manage the pyenv versions, and it's plugin pyenv-virtualenv to manage the versions as virtual environments, then poetry to pick the version from them automatically as it manages the dependencies: Use pyenv to install whatever version of python you want to use: pyenv install -v 3.7 Create a virtual environment based on the installed version 3.7. You will need the plugin pyenv-virtualenv. pyenv virtualenv 3.7 arshbot_3.7_virtualenv Assume a project called arshbot_proj. Working in $HOME directory: mkdir ~/arshbot_proj cd ~/arshbot_proj Use the virtual env we just created. Attach this project to it. Below creates .python-version file indicating arshbot_3.7_virtualenv. pyenv local arshbot_3.7_virtualenv Use poetry init to create the pyproject.toml inside the dir using arshbot_3.7_virtualenv. You could also use poetry new instead of poetry init to create project structure alongside pyproject.toml instead of making your project first in above step. With pyproject.toml and .python-version both inside this dir, poetry will automatically pick the 3.7 courtesy of arshbot_3.7_virtualenv. Poetry will also use this virtual env to install packages at ~/.pyenv/versions/3.7/envs/arshbot_3.7_virtualenv/lib/python3.7/site-packages poetry init That is it. Poetry will pick the 3.7 automatically every time you run it from inside that directory attached to that virtual environment, with it activated. For different python version, just repeat the above steps, replace 3.7 with the new version. The virtual environment will appear twice: In the envs directory as a virtual environment, and also in the versions directory as a version, with contents replicating when poetry installs packages. BONUS: We try to make it even more clear using a different approach, same concept, same results. Since by default, if you didn't change PYENV_ROOT, pyenv installs every python version in ~/.pyenv/versions: If you want the system version(shipped with your distro) to be part of the versions you can select, use venv to mimick a pyenv installation of a python version, now call it system_ver in place of the 3.7. Since it's already in the system, we don't need pyenv to download it, we copy it over to our versions directory, so that it's available to create a virtual environment cd ~/.pyenv/versions python3 -m venv --copies system system_ver pyenv virtualenv system_ver system_ver_virtualenv To use it in your project in place of previous version 3.7: cd ~/arshbot_proj pyenv local system_ver_virtualenv Poetry will now use whatever version came originally with your distro. The --copies will ensure venv copies the files instead of use links, so you may omit it. Usually useful if you need to later make a multi stage dockerfile for the project using the files from the virtual environment. A: I am running ubuntu 22.04 and only have python 3.10 installed. I've destroyed my system python enough times that I refuse to dance with older versions, or running any installs from pip. What I wanted is an older version of python, that was installed by not installed over my current python install. What I did was follow this guide. sudo apt install libgdbm-dev build-essential libnss3-dev libreadline-dev libffi-dev libsqlite3-dev libbz2-dev libncurses5-dev libssl-dev zlib1g-dev cd /tmp wget https://www.python.org/ftp/python/3.9.14/Python-3.9.14.tgz tar -xf Python-3.9.14.tgz cd Python-3.9.14 ./configure --enable-optimizations ## if you want to run in parallel set -j to how many cpus you have ## I subtracted 2 so my machine wouldn't have a stroke # lscpu | egrep 'CPU\(s\)' # make -j <cpus you are comfortable with> make ## Super important to run altinstall to not overwrite sudo make altinstall ## I updated the pyproject.toml to ^3.9 poetry env use /usr/local/bin/python3.9 Testing this out now, if I don't post anything after this, it either worked or I am not longer living. A: Just edit pyproject.toml file and change the version of python to 3.7 as in : python = "^3.7"
Change python version to 3.x
According to poetry's docs, the proper way to setup a new project is with poetry new poetry-demo, however this creates a project based on the now deprecated python2.7 by creating the following toml file: [tool.poetry] name = "poetry-demo" version = "0.1.0" description = "" authors = ["Harsha Goli <harshagoli@gmail.com>"] [tool.poetry.dependencies] python = "^2.7" [tool.poetry.dev-dependencies] pytest = "^4.6" [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api" How can I update this to 3.7? Simply changing python = "^2.7" to python = "^3.7" results in the following error when poetry install is run: [SolverProblemError] The current project's Python requirement (2.7.17) is not compatible with some of the required packages Python requirement: - zipp requires Python >=3.6 Because no versions of pytest match >=4.6,<4.6.9 || >4.6.9,<5.0 and pytest (4.6.9) depends on importlib-metadata (>=0.12), pytest (>=4.6,<5.0) requires importlib-metadata (>=0.12). And because no versions of importlib-metadata match >=0.12,<1.5.0 || >1.5.0 and importlib-metadata (1.5.0) depends on zipp (>=0.5), pytest (>=4.6,<5.0) requires zipp (>=0.5). Because zipp (3.1.0) requires Python >=3.6 and no versions of zipp match >=0.5,<3.1.0 || >3.1.0, zipp is forbidden. Thus, pytest is forbidden. So, because poetry-demo depends on pytest (^4.6), version solving failed.
[ "Poetry makes it super easy to work with different Python versions or virtual environments. The recommended way to specify your Python version according to Poetry docs is\npoetry env use /path/to/preferred/python/version\n\nYou can get the path to your Python version by running\nwhich python3.7\non Linux or\npy -0p\non Windows.\n", "Whenever you change dependencies by hand in your pyproject.toml you have to take care of these points:\n\nRun poetry lock --no-update afterwards. The reasons for this is, that poetry install takes the poetry.lock as input if can find one and not the pyproject.toml.\n\nIf you change the python version and uses in-project virtualenv, remove the .venv before running poetry install. poetry doesn't change the python version of a venv once it is created, because it uses the python version itself to create the virtualenv.\n\n\n", "Use:\npoetry env use 3.9\n\nor\npoetry env use $(which python3.9)\n\ndoesn't work for some reason for python 3.9. Though having explicitly stated version requirement in pyproject.toml file, it's sad that one needs to manually enforce this.\n", "Interestingly, poetry is silently failing due to a missing package the tool itself relies on and continues to install a broken venv. Here's how you fix it.\nsudo apt install python3-venv\npoetry env remove python3\npoetry install\n\nI had to remove pytest, and then reinstall with poetry add pytest.\nEDIT: I ran into this issue again when upgrading a project from python3.7 to python3.8 - for this instead of installing python3-venv, you'd want to install python3.8-venv instead\n", "I had the same problem. I solve it by fixing the first line in the file /home/nordman/.poetry/bin/poetry (nordman is my local name).\nJust change #!/usr/bin/env python to #!/usr/bin/env python3\n", "You can change in pyproject.toml and execute de this command \"poetry env use 3.x\" that works for me.\n", "I tried every solution I could find, but could not get poetry to pick up the upgraded version of Python. Finally found something that worked.\ntldr;\n\nRun poetry config virtualenvs.in-project true to use local venvs\nRun deactivate to exit any existing venv\nRun poetry shell to activate a new, local venv\n\nSo here's what I was seeing:\n(my-project) ~/I/my-project ❯❯❯ poetry env info\n\nVirtualenv\nPython: 3.9.6\nImplementation: CPython\nPath: /Users/my-user/.local/share/virtualenvs/my-project-some-hash\nValid: True\n\nSystem\nPlatform: darwin\nOS: posix\nPython: /usr/local/opt/python@3.9/Frameworks/Python.framework/Versions/3.9\n\n\nI tried running poetry env remove python and got an error:\n\n(my-project) ~/I/my-project ❯❯❯ poetry env remove python\n\n ValueError\n\n Environment \"my-project-some-hash-py3.9\" does not exist.\n\n\nMeanwhile, I saw somewhere that it's recommend to use local virtual environments by setting this property, so I did it:\npoetry config virtualenvs.in-project true\nThis did not solve my problem, but then I realized that changing this setting would not take affect automatically because I was already in another non-local virtual environment (see poetry env info output above).\nSo based on the docs, I ran deactivate to deactivate the current virtual environment.\nNow, I saw this:\n~/I/my-project ❯❯❯ poetry env info\n\nVirtualenv\nPython: 3.10.1\nImplementation: CPython\nPath: NA\n\nSystem\nPlatform: darwin\nOS: posix\nPython: /Users/my-user/.pyenv/versions/3.10.1\n\n\nNow I ran poetry shell to create a new virtual environment and it picked up the new local venvs setting:\n~/I/my-project ❯❯❯ poetry shell\nCreating virtualenv my-project in /Users/my-user/projects/my-project/.venv\nSpawning shell within /Users/my-user/projects/my-project/.venv\n\nAnd finally, I saw the upgraded Python version I was expecting!\n(.venv) ~/I/my-project ❯❯❯ poetry run python -V\nPython 3.10.1\n\nUpdate: After I did all of the above, I noticed that poetry env use works fine!\n(.venv) ~/I/my-project ❯❯❯ python -V\nPython 3.10.1\n(.venv) ~/I/my-project ❯❯❯ poetry env use 3.9.6\nRecreating virtualenv my-project in /Users/my-user/projects/my-project/.venv\nUsing virtualenv: /Users/my-user/projects/my-project/.venv\n(.venv) ~/I/my-project ❯❯❯ python -V\nPython 3.9.6\n\n\n", "I've experienced the exact same behavior on my MacBook! So to make this practical, first, let's see, what is the default Python for the MacBook. I'm running macOS Big Sur 11.2.1 (20D74). In terminal:\npython --version \nPython 2.7.16\n\nWith that, let's install poetry. I've used poetry installation script from the GitHub. Using this script is a recommended method to install poetry (though I'd argue this is NOT the best idea to pipe scripts from the Internet into the python interpreter)\nThe installation script is pretty smart: it attempts to detect which python is available on the system:\ndef _which_python(self):\n \"\"\"Decides which python executable we'll embed in the launcher script.\"\"\"\n allowed_executables = [\"python\", \"python3\"]\n if WINDOWS:\n allowed_executables += [\"py.exe -3\", \"py.exe -2\"]\n...\n\nSo as the default Python is 2.7.16, and that is what returned by calling python, the entry in ~/.poetry/bin will look like:\n#!/usr/bin/env python\n\nAnd here you go! The default python will end up in the pyproject.toml file and you'll need to do an extra dance to a) make sure python3 is a dependency for your project; and b) that the virtual environment will use python3 as python interpreter.\nAs @mfalade mentioned, you can set environment with poetry env:\npoetry env use /path/to/python3\n\nAnd also modifying the pyproject.toml with:\n...\n[tool.poetry.dependencies]\npython = \"^3.9\"\n...\n\nFrom this point you are good to go, poetry will use python3 to create virtual environment for you project, dependency is specified in the file and ... the grass is green again.\nBut can we use python3 by default? There is an insightful thread on GitHub and another one. And if you look back at the code snippet from the installation script above, you might wonder why not to check for python3 first and then for python, especially taking into account that this is the exact order for Windows installation. Well, you are not alone, I also wonder ;)\nI would not suggest editing the ~/.poetry/bin/poetry file directly as this file is generated by the installation script (so what will happen if you run installation script again? And again?).\nReally, this is a minor annoyance, and knowing the tool it is easy to work around it. I'd expect that to be mentioned in installation guide though...\nAnyway, hope it helps!\n", "You can simply use pyenv for that. Create .python-version file inside your project and poetry will match the exact python version.\n# check current python version (set up globally)\n❯ pyenv version\n3.9.0 (set by /Users/tomasz.zieba@showpad.com/.python-version)\n\n# create .python-version file for project\n❯ pyenv local 3.9.0\n\n# check python version again (now it's set up locally)\n❯ pyenv version\n3.9.0 (set by /Users/tomasz.zieba@showpad.com/Documents/myproject/.python-version)\n\n❯ poetry lock\n(...)\n\n❯ poetry run python --version\nPython 3.9.0\n\n", "The way I do it, and it's super effective:\nUse pyenv to manage the pyenv versions, and it's plugin pyenv-virtualenv to manage the versions as virtual environments, then poetry to pick the version from them automatically as it manages the dependencies:\nUse pyenv to install whatever version of python you want to use:\npyenv install -v 3.7\n\nCreate a virtual environment based on the installed version 3.7.\nYou will need the plugin pyenv-virtualenv.\npyenv virtualenv 3.7 arshbot_3.7_virtualenv\n\nAssume a project called arshbot_proj. Working in $HOME directory:\nmkdir ~/arshbot_proj\ncd ~/arshbot_proj\n\nUse the virtual env we just created. Attach this project to it.\nBelow creates .python-version file indicating arshbot_3.7_virtualenv.\npyenv local arshbot_3.7_virtualenv\n\nUse poetry init to create the pyproject.toml inside the dir using\narshbot_3.7_virtualenv.\nYou could also use poetry new instead of poetry init to create project\nstructure alongside pyproject.toml instead of making your project first in\nabove step.\nWith pyproject.toml and .python-version both inside this dir, poetry\nwill automatically pick the 3.7 courtesy of arshbot_3.7_virtualenv.\nPoetry will also use this virtual env to install packages at\n~/.pyenv/versions/3.7/envs/arshbot_3.7_virtualenv/lib/python3.7/site-packages\npoetry init\n\nThat is it. Poetry will pick the 3.7 automatically every time you run it from inside that directory attached to that virtual environment, with it activated. For different python version, just repeat the above steps, replace 3.7 with the new version.\nThe virtual environment will appear twice: In the envs directory as a virtual environment, and also in the versions directory as a version, with contents replicating when poetry installs packages.\nBONUS:\nWe try to make it even more clear using a different approach, same concept, same results.\nSince by default, if you didn't change PYENV_ROOT, pyenv installs every python version in ~/.pyenv/versions:\nIf you want the system version(shipped with your distro) to be part of the versions you can select, use venv to mimick a pyenv installation of a python version, now call it system_ver in place of the 3.7. Since it's already in the system, we don't need pyenv to download it, we copy it over to our versions directory, so that it's available to create a virtual environment\ncd ~/.pyenv/versions\npython3 -m venv --copies system system_ver\npyenv virtualenv system_ver system_ver_virtualenv\n\nTo use it in your project in place of previous version 3.7:\ncd ~/arshbot_proj\npyenv local system_ver_virtualenv\n\nPoetry will now use whatever version came originally with your distro. The --copies will ensure venv copies the files instead of use links, so you may omit it. Usually useful if you need to later make a multi stage dockerfile for the project using the files from the virtual environment.\n", "I am running ubuntu 22.04 and only have python 3.10 installed. I've destroyed my system python enough times that I refuse to dance with older versions, or running any installs from pip. What I wanted is an older version of python, that was installed by not installed over my current python install. What I did was follow this guide.\nsudo apt install libgdbm-dev build-essential libnss3-dev libreadline-dev libffi-dev libsqlite3-dev libbz2-dev libncurses5-dev libssl-dev zlib1g-dev\ncd /tmp\nwget https://www.python.org/ftp/python/3.9.14/Python-3.9.14.tgz\ntar -xf Python-3.9.14.tgz\ncd Python-3.9.14 \n./configure --enable-optimizations\n\n## if you want to run in parallel set -j to how many cpus you have\n## I subtracted 2 so my machine wouldn't have a stroke\n# lscpu | egrep 'CPU\\(s\\)'\n# make -j <cpus you are comfortable with>\nmake\n\n## Super important to run altinstall to not overwrite\nsudo make altinstall\n\n## I updated the pyproject.toml to ^3.9\npoetry env use /usr/local/bin/python3.9\n\nTesting this out now, if I don't post anything after this, it either worked or I am not longer living.\n", "Just edit pyproject.toml file and change the version of python to 3.7 as in :\npython = \"^3.7\"\n\n" ]
[ 54, 42, 32, 9, 9, 6, 4, 3, 3, 0, 0, 0 ]
[]
[]
[ "python", "python_poetry" ]
stackoverflow_0060580113_python_python_poetry.txt
Q: how to convert the result of product to hex? how to use a method to change it into hexadecimal. It looks i made an mistake. please help me to find a solution. print("Full Names:" " "+ string, [ord(i) for i in string]) product = reduce(lambda x,y: x*y, [ord(i) for i in string]) print(product) random.seed(2) random.uniform(len(string) ,2000000) product = reduce(lambda x,y: x^y, [ord(i) for i in string]) print(product) print("the exa number of:" + hex(54)) A: Printing in different bases can be done in a few ways: First of all there is the hex() function: >>> print("The result is: ", hex(28)) The result is: 0x1c This returns the hex as most other applications would want it. However, if you only want the hex itself, without the 0x to start it, you can use format(). This function has two variations, one with caps, and one with small letters, by passing it a small or a capital letter x respectively: >>> print("The result is: ", format(28, "x") The result is 1c >>> print("The result is: ", format(28, "X")) The result is 1C Lastly, you can use numpy with np.base_repr(), which can print to any base, not just hexadecimal, but using that in this case would be overkill. Once you have your string (e.g. from format()) you can do normal string operations on it if you want only a part of it. So, getting the first 16 characters would be: print("The result is: "format(28, "x")[:16]) I hope that helps! :-)
how to convert the result of product to hex?
how to use a method to change it into hexadecimal. It looks i made an mistake. please help me to find a solution. print("Full Names:" " "+ string, [ord(i) for i in string]) product = reduce(lambda x,y: x*y, [ord(i) for i in string]) print(product) random.seed(2) random.uniform(len(string) ,2000000) product = reduce(lambda x,y: x^y, [ord(i) for i in string]) print(product) print("the exa number of:" + hex(54))
[ "Printing in different bases can be done in a few ways:\nFirst of all there is the hex() function:\n>>> print(\"The result is: \", hex(28))\nThe result is: 0x1c\n\nThis returns the hex as most other applications would want it.\nHowever, if you only want the hex itself, without the 0x to start it, you can use format(). This function has two variations, one with caps, and one with small letters, by passing it a small or a capital letter x respectively:\n>>> print(\"The result is: \", format(28, \"x\")\nThe result is 1c\n>>> print(\"The result is: \", format(28, \"X\"))\nThe result is 1C\n\nLastly, you can use numpy with np.base_repr(), which can print to any base, not just hexadecimal, but using that in this case would be overkill.\n\nOnce you have your string (e.g. from format()) you can do normal string operations on it if you want only a part of it. So, getting the first 16 characters would be:\nprint(\"The result is: \"format(28, \"x\")[:16])\n\nI hope that helps! :-)\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074495749_python.txt
Q: Asynchronous Web Scraping, Python Im trying to run this function every 2seconds forever : import requests from bs4 import BeautifulSoup import asyncio async def scrape(): test = [] r = requests.get(coin_desk) soup = BeautifulSoup(r.text, features='xml') title = soup.find_all('title')[2] await asyncio.sleep(2) for x in title: test.append(x) print(test) if name == 'main': try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(scrape()) except (KeyboardInterrupt, SystemExit): pass If i use run_forever() instead of run_until_complete(scrape()) nothing gets printed out, it just runs forever and skips the function it seems. A: The async routine (scrape) was never placed into the event loop. You can add it with loop.create_task(routine) See: What does asyncio.create_task() do?
Asynchronous Web Scraping, Python
Im trying to run this function every 2seconds forever : import requests from bs4 import BeautifulSoup import asyncio async def scrape(): test = [] r = requests.get(coin_desk) soup = BeautifulSoup(r.text, features='xml') title = soup.find_all('title')[2] await asyncio.sleep(2) for x in title: test.append(x) print(test) if name == 'main': try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(scrape()) except (KeyboardInterrupt, SystemExit): pass If i use run_forever() instead of run_until_complete(scrape()) nothing gets printed out, it just runs forever and skips the function it seems.
[ "The async routine (scrape) was never placed into the event loop.\nYou can add it with\nloop.create_task(routine)\n\nSee:\nWhat does asyncio.create_task() do?\n" ]
[ 0 ]
[]
[]
[ "asynchronous", "beautifulsoup", "python", "request", "web_scraping" ]
stackoverflow_0074495579_asynchronous_beautifulsoup_python_request_web_scraping.txt
Q: Simple Python chatbot in Replit I'm a lawyer and (very) beginning programmer. I'm at step 1 of learning to build a chatbot that can hopefully help me advise my clients someday. I'm trying to follow this Medium post on how to build a simple python chatbot: https://towardsdatascience.com/how-to-create-a-chatbot-with-python-deep-learning-in-less-than-an-hour-56a063bdfc44 Luckily I was able to import the author's GitHub repo to my Replit. Author's GH: https://github.com/jerrytigerxu/Simple-Python-Chatbot My Repl: https://replit.com/@AugieRakow/Simple-Python-Chatbot#chatbot_model.h5 But I can't quite get it to work. I have 3 embarrassingly basic questions: main.py. I didn't see a "main.py" file in the GH repo, so I imagine I need to add that. Is that correct? code excerpts The author's Medium post includes code excerpts that appear to be importing various libraries etc. Should I copy all those code excerpts into main.py? chatbot_model.h5 The contents of the author's chatbot_model.h5 file on GH are appearing in my Replit with garbled red "NULNULNUL" text repeating line after line. Is that a corrupt file? Is there an easy remedy? https://replit.com/@AugieRakow/Simple-Python-Chatbot#chatbot_model.h5 Any guidance is much appreciated! A: No, a main.py doesn't have any specific meaning, it's just conventional to name the "entry point" that name. Any other name can be used for an "entry point" too. You probably need to use libraries shown in the tutorial, but you need to import them in those files where they are used. It's probably just some value it can't decode to something that it could show you properly so it just substitutes it with that symbol, it's probably nothing, just an encoding thing or similar. Most certainly it shouldn't mean that the file is corrupt.
Simple Python chatbot in Replit
I'm a lawyer and (very) beginning programmer. I'm at step 1 of learning to build a chatbot that can hopefully help me advise my clients someday. I'm trying to follow this Medium post on how to build a simple python chatbot: https://towardsdatascience.com/how-to-create-a-chatbot-with-python-deep-learning-in-less-than-an-hour-56a063bdfc44 Luckily I was able to import the author's GitHub repo to my Replit. Author's GH: https://github.com/jerrytigerxu/Simple-Python-Chatbot My Repl: https://replit.com/@AugieRakow/Simple-Python-Chatbot#chatbot_model.h5 But I can't quite get it to work. I have 3 embarrassingly basic questions: main.py. I didn't see a "main.py" file in the GH repo, so I imagine I need to add that. Is that correct? code excerpts The author's Medium post includes code excerpts that appear to be importing various libraries etc. Should I copy all those code excerpts into main.py? chatbot_model.h5 The contents of the author's chatbot_model.h5 file on GH are appearing in my Replit with garbled red "NULNULNUL" text repeating line after line. Is that a corrupt file? Is there an easy remedy? https://replit.com/@AugieRakow/Simple-Python-Chatbot#chatbot_model.h5 Any guidance is much appreciated!
[ "\nNo, a main.py doesn't have any specific meaning, it's just conventional to name the \"entry point\" that name. Any other name can be used for an \"entry point\" too.\n\nYou probably need to use libraries shown in the tutorial, but you need to import them in those files where they are used.\n\nIt's probably just some value it can't decode to something that it could show you properly so it just substitutes it with that symbol, it's probably nothing, just an encoding thing or similar. Most certainly it shouldn't mean that the file is corrupt.\n\n\n" ]
[ 0 ]
[]
[]
[ "chatbot", "python", "replit" ]
stackoverflow_0074496023_chatbot_python_replit.txt
Q: Recursive function to go through list of references to indices in same list I have this list: [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []] It could be described as a list of references to other items in the same list, like this: 0 --> 1 2 3 4 1 --> 5 2 --> 6 7 3 --> 8 4 --> 9 5 --> 10 11 6 --> 12 13 14 7 --> 15 16 8 --> 15 16 9 --> 15 16 10 --> 17 11 --> 18 12 --> 19 13 --> 20 14 --> 21 15 --> 20 16 --> 21 17 --> None 18 --> None 19 --> None 20 --> None 21 --> None So, from index 0 one can move to either 1, 2, 3 or 4. From 1 you can go to 5, and from 5 you can go to 10 etc. until you can't go any further (like when you reach index 17). I'm trying to make a function that would return this when fed the above list: [0,1,5,10,17] [0,1,5,11,18] [0,2,6,12,19] [0,2,6,13,20] [0,2,6,14,21] [0,2,7,15,20] [0,2,7,16,21] [0,3,8,15,20] [0,3,8,16,21] [0,4,9,15,20] [0,4,9,16,21] Unfortunately, I just can't come up a solution. I understand that this probably calls for a recursive function, but I'm getting so confused by it. Without actually knowing what I did, I managed to come up with this function: def recurse_into(A,i): B = [i] for j in tree[i]: B += recurse_into(A,j) return B It returns this: [0, 1, 5, 10, 17, 11, 18, 2, 6, 12, 19, 13, 20, 14, 21, 7, 15, 20, 16, 21, 3, 8, 15, 20, 16, 21, 4, 9, 15, 20, 16, 21] From that I probably could come up with something that generates the wanted results, but I wonder how I could get the result I want directly from the recursive function. I would very much appreciate some pointers or tips on how to achieve this. Thanks! A: Here is my implementation of what I understood from my requirements def dfs(graph, u, curr,res): c = curr+ [u] if(len(graph[u]) == 0): res.append(c) for v in graph[u]: dfs(graph, v, c, res) graph = [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []] u = 0 res = [] dfs(graph, u, [],res) print(res) So I'm doing a DFS here. A: tree = [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []] def recourse_into(i): R=[] if len(tree[i]) ==0 : return [[i]] for h in tree[i]: t=recourse_into(h) for j in t : R.append([i]+j) return R print(recourse_into(0))
Recursive function to go through list of references to indices in same list
I have this list: [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []] It could be described as a list of references to other items in the same list, like this: 0 --> 1 2 3 4 1 --> 5 2 --> 6 7 3 --> 8 4 --> 9 5 --> 10 11 6 --> 12 13 14 7 --> 15 16 8 --> 15 16 9 --> 15 16 10 --> 17 11 --> 18 12 --> 19 13 --> 20 14 --> 21 15 --> 20 16 --> 21 17 --> None 18 --> None 19 --> None 20 --> None 21 --> None So, from index 0 one can move to either 1, 2, 3 or 4. From 1 you can go to 5, and from 5 you can go to 10 etc. until you can't go any further (like when you reach index 17). I'm trying to make a function that would return this when fed the above list: [0,1,5,10,17] [0,1,5,11,18] [0,2,6,12,19] [0,2,6,13,20] [0,2,6,14,21] [0,2,7,15,20] [0,2,7,16,21] [0,3,8,15,20] [0,3,8,16,21] [0,4,9,15,20] [0,4,9,16,21] Unfortunately, I just can't come up a solution. I understand that this probably calls for a recursive function, but I'm getting so confused by it. Without actually knowing what I did, I managed to come up with this function: def recurse_into(A,i): B = [i] for j in tree[i]: B += recurse_into(A,j) return B It returns this: [0, 1, 5, 10, 17, 11, 18, 2, 6, 12, 19, 13, 20, 14, 21, 7, 15, 20, 16, 21, 3, 8, 15, 20, 16, 21, 4, 9, 15, 20, 16, 21] From that I probably could come up with something that generates the wanted results, but I wonder how I could get the result I want directly from the recursive function. I would very much appreciate some pointers or tips on how to achieve this. Thanks!
[ "Here is my implementation of what I understood from my requirements\n\ndef dfs(graph, u, curr,res):\n c = curr+ [u]\n if(len(graph[u]) == 0):\n res.append(c)\n for v in graph[u]:\n dfs(graph, v, c, res)\n \n \n \ngraph = [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []]\n\nu = 0\nres = []\ndfs(graph, u, [],res)\n\nprint(res)\n\nSo I'm doing a DFS here.\n", "tree = [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []]\n\ndef recourse_into(i):\n R=[]\n if len(tree[i]) ==0 :\n return [[i]]\n for h in tree[i]:\n t=recourse_into(h)\n for j in t :\n R.append([i]+j)\n return R\n\n\nprint(recourse_into(0))\n\n" ]
[ 1, 1 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074495938_python_recursion.txt
Q: How to show first 5 characters within a column in Python? Need the Zip column to only show the first 5 characters Result: enter image description here Expected Result: enter image description here Source Code: import pandas as pd import numpy as np #numpy is the module which can replace errors from huge datasets from openpyxl import load_workbook from openpyxl.styles import Font df_1 = pd.read_csv('correctional_facilities.csv') df_2 = pd.read_csv('ems.csv') df_3 = pd.read_csv('prt_hospital_space.csv') df_4 = pd.read_csv('ec_hospital_space.csv') df_5 = pd.read_csv('government.csv') df_6 = pd.read_csv('fire.csv') df_7 = pd.read_csv('prt_community_space.csv') df_8 = pd.read_csv('ec_community_space_part1.csv') df_9 = pd.read_csv('ec_community_space_part2.csv') df_10 = pd.read_csv('police_facilities.csv') df_11 = pd.read_csv('schools.csv') df_12 = pd.read_csv('surgery_center.csv') df_all = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12], sort=False) #this combines the sheets from 1,2,3 and the sort function as false so our columns stay in the same order df_all.rename(columns={'Territory Assigned': 'Territory_Name', 'Treatment Region': 'Region_Name', '⭐ Customer Type': 'Customer_Type'}, inplace=True) #this renames the column headers to readable columns for axtria df_all = df_all.replace(np.nan, 'N/A', regex=True) #replaces blanks/errors with N/A remove = ['Country', 'Action'] #this will remove all unwanted columns df_all.drop(columns=remove, inplace=True) df_all['Zip'].str[:5] #this will only have 5 numbers for the zip code A: You're not assigning the sliced string back to the dataframe. You just have to replace df_all['Zip'].str[:5] with df_all['Zip'] = df_all['Zip'].str[:5] Example: >>> import pandas as pd >>> data = [["Alice"],["Bob"],["Eve"]] >>> df = pd.DataFrame(data,columns=['Name']) >>> df Name 0 Alice 1 Bob 2 Eve >>> df['Name'].str[::-1] 0 ecilA 1 boB 2 evE >>> df # It didn't stick.... Name 0 Alice 1 Bob 2 Eve >>> df['Name'] = df['Name'].str[::-1] >>> df # That's better Name 0 ecilA 1 boB 2 evE
How to show first 5 characters within a column in Python?
Need the Zip column to only show the first 5 characters Result: enter image description here Expected Result: enter image description here Source Code: import pandas as pd import numpy as np #numpy is the module which can replace errors from huge datasets from openpyxl import load_workbook from openpyxl.styles import Font df_1 = pd.read_csv('correctional_facilities.csv') df_2 = pd.read_csv('ems.csv') df_3 = pd.read_csv('prt_hospital_space.csv') df_4 = pd.read_csv('ec_hospital_space.csv') df_5 = pd.read_csv('government.csv') df_6 = pd.read_csv('fire.csv') df_7 = pd.read_csv('prt_community_space.csv') df_8 = pd.read_csv('ec_community_space_part1.csv') df_9 = pd.read_csv('ec_community_space_part2.csv') df_10 = pd.read_csv('police_facilities.csv') df_11 = pd.read_csv('schools.csv') df_12 = pd.read_csv('surgery_center.csv') df_all = pd.concat([df_1, df_2, df_3, df_4, df_5, df_6, df_7, df_8, df_9, df_10, df_11, df_12], sort=False) #this combines the sheets from 1,2,3 and the sort function as false so our columns stay in the same order df_all.rename(columns={'Territory Assigned': 'Territory_Name', 'Treatment Region': 'Region_Name', '⭐ Customer Type': 'Customer_Type'}, inplace=True) #this renames the column headers to readable columns for axtria df_all = df_all.replace(np.nan, 'N/A', regex=True) #replaces blanks/errors with N/A remove = ['Country', 'Action'] #this will remove all unwanted columns df_all.drop(columns=remove, inplace=True) df_all['Zip'].str[:5] #this will only have 5 numbers for the zip code
[ "You're not assigning the sliced string back to the dataframe. You just have to replace df_all['Zip'].str[:5] with df_all['Zip'] = df_all['Zip'].str[:5]\nExample:\n>>> import pandas as pd\n>>> data = [[\"Alice\"],[\"Bob\"],[\"Eve\"]]\n>>> df = pd.DataFrame(data,columns=['Name'])\n>>> df\nName\n0 Alice\n1 Bob\n2 Eve\n>>> df['Name'].str[::-1]\n0 ecilA\n1 boB\n2 evE\n>>> df\n# It didn't stick....\nName\n0 Alice\n1 Bob\n2 Eve\n>>> df['Name'] = df['Name'].str[::-1]\n>>> df\n# That's better\nName\n0 ecilA\n1 boB\n2 evE\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074495737_pandas_python.txt
Q: How to interact with shell in Python and get return code There are questions like this, that show how to interact with a shell in Python, sending stuff to its stdin and reading back stuff from its stdout. I'd just like to do one more thing on top of that: Start a process running a shell -- say: subprocess.Popen(["powershell --someArgs"]) interact with that shell/process by: sending it the occasional command through stdin (commands that can take a while and spew a lot of output) consume each command's output through stdout, Identify when each command completes and and get the return code for each command, to know which ones succeed or fail. I suspect there's no way to do the last part, other than to have the shell itself print its last return code, and have the parent parse that from stdout (also, scanning stdout for the prompt to know when the command finishes?). But I'm asking anyways... Code samples are welcome but not necessary -- precise descriptions should be good enough :-) (Ideally, using built-in modules like subprocess, without needing to install any new packages.)
How to interact with shell in Python and get return code
There are questions like this, that show how to interact with a shell in Python, sending stuff to its stdin and reading back stuff from its stdout. I'd just like to do one more thing on top of that: Start a process running a shell -- say: subprocess.Popen(["powershell --someArgs"]) interact with that shell/process by: sending it the occasional command through stdin (commands that can take a while and spew a lot of output) consume each command's output through stdout, Identify when each command completes and and get the return code for each command, to know which ones succeed or fail. I suspect there's no way to do the last part, other than to have the shell itself print its last return code, and have the parent parse that from stdout (also, scanning stdout for the prompt to know when the command finishes?). But I'm asking anyways... Code samples are welcome but not necessary -- precise descriptions should be good enough :-) (Ideally, using built-in modules like subprocess, without needing to install any new packages.)
[]
[]
[ "That's on the contrary the easiest part.\nWhen the subprocess terminates, it sends its exit code.\nIt is the return value of wait method\nimport subprocess\np=subprocess.Popen(['sh', '-c', 'sleep 5 ; exit 12'])\nx=p.wait()\nprint(f'exit code was {x}')\n\nNote that you are not forced to literally wait the process for this to work. You can \"wait\" it after it is done, and do some other task in your python process in between (parallelism being one of the reasons why you may call subprocesses)\nimport subprocess\nimport time\np=subprocess.Popen(['sh', '-c', 'sleep 5 ; exit 12'])\ntime.sleep(10) # or anything else. The point is `.wait` is called after the process has returned\nx=p.wait()\nprint(f'exit code was {x}')\n\n" ]
[ -1 ]
[ "interactive", "powershell", "python", "shell", "subprocess" ]
stackoverflow_0074495770_interactive_powershell_python_shell_subprocess.txt
Q: Pandas with MatplotLib: plotting regression line with log-x scale The issue is this one: I'm trying to plot a lineal regression line over a scatter plot, from two Pandas Series obtained from a Panda DataFrame. Each one of these Series represents a column of the DataFrame. Here, the 'X' axis of my scatter plot is represented in a logarithmic scale. I've looked for a similar issue here: Plotting regression line with log y scale However, despite having consulted that post, I couldn't achieve to get the result I want to, since in this case, the axis represented with a log scale is 'X' instead of 'Y', the arguments passed to the plot function are Pandas Series instead of NumPy arrays, and finally, I'm using figure and axes unpacked from the subplot function instead of using directly the plot function (this is: "ax.scatter..." instead of "plt.scatter...") So then, here's my code and my result until now ("municipios" is my DataFrame): Although I've tried a lot of things based on the mentioned post, I'm always getting an unexpected and wrong result, which consists of a line plotted with lots of irregular segments. Does anyone have an idea of what I'm doing wrong or what should I do? Thank's a lot! A: I could achieve this using Seaborn, like this ('municipios' is my whole Pandas DataFrame): x=np.log(municipios['DENSIDAD_HABITACIONAL']) y=municipios['PORCENTAJE_NBI'] s=sns.regplot(x=x, y=y,fit_reg=True) s.figure.set_size_inches(18.5, 10.5) sns.despine() And also: x=np.log(municipios['POBLACION']) y=np.log(municipios['SUPERFICIE']) s=sns.regplot(x=x, y=y,fit_reg=True) s.figure.set_size_inches(18.5, 10.5) sns.despine()
Pandas with MatplotLib: plotting regression line with log-x scale
The issue is this one: I'm trying to plot a lineal regression line over a scatter plot, from two Pandas Series obtained from a Panda DataFrame. Each one of these Series represents a column of the DataFrame. Here, the 'X' axis of my scatter plot is represented in a logarithmic scale. I've looked for a similar issue here: Plotting regression line with log y scale However, despite having consulted that post, I couldn't achieve to get the result I want to, since in this case, the axis represented with a log scale is 'X' instead of 'Y', the arguments passed to the plot function are Pandas Series instead of NumPy arrays, and finally, I'm using figure and axes unpacked from the subplot function instead of using directly the plot function (this is: "ax.scatter..." instead of "plt.scatter...") So then, here's my code and my result until now ("municipios" is my DataFrame): Although I've tried a lot of things based on the mentioned post, I'm always getting an unexpected and wrong result, which consists of a line plotted with lots of irregular segments. Does anyone have an idea of what I'm doing wrong or what should I do? Thank's a lot!
[ "I could achieve this using Seaborn, like this ('municipios' is my whole Pandas DataFrame):\nx=np.log(municipios['DENSIDAD_HABITACIONAL'])\ny=municipios['PORCENTAJE_NBI']\n\ns=sns.regplot(x=x, y=y,fit_reg=True)\ns.figure.set_size_inches(18.5, 10.5)\n\nsns.despine()\n\nAnd also:\nx=np.log(municipios['POBLACION'])\ny=np.log(municipios['SUPERFICIE'])\n\ns=sns.regplot(x=x, y=y,fit_reg=True)\ns.figure.set_size_inches(18.5, 10.5)\n\nsns.despine()\n\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "matplotlib", "numpy", "pandas", "python" ]
stackoverflow_0074437281_jupyter_notebook_matplotlib_numpy_pandas_python.txt
Q: Accessing a DataFrame inside of a class I have created a DataFrame inside of a class but I am having trouble using it outside of the class or even calling it. How would I do that? I just want to print the DataFrame outside of the class. class Youpi(Baseball, Soccer): def __init__(self): Baseball.__init__(self, self) self.Random_df = pd.DataFrame(columns = ["Hot-Dogs"]) def Attendance(self, hot_dogs): dictionary = {"Hot-Dogs":5} self.Random_df = self.Random_df.append(dictionary, ignore_index=True) return self.Random_df Desired output: // instruction to print the dataframe here Output: Hot-Dogs 5 A: I would try print(dictionary.Attendance)
Accessing a DataFrame inside of a class
I have created a DataFrame inside of a class but I am having trouble using it outside of the class or even calling it. How would I do that? I just want to print the DataFrame outside of the class. class Youpi(Baseball, Soccer): def __init__(self): Baseball.__init__(self, self) self.Random_df = pd.DataFrame(columns = ["Hot-Dogs"]) def Attendance(self, hot_dogs): dictionary = {"Hot-Dogs":5} self.Random_df = self.Random_df.append(dictionary, ignore_index=True) return self.Random_df Desired output: // instruction to print the dataframe here Output: Hot-Dogs 5
[ "I would try print(dictionary.Attendance)\n" ]
[ 0 ]
[]
[]
[ "class", "dataframe", "python" ]
stackoverflow_0074496000_class_dataframe_python.txt
Q: Python: How to access list object deep within a nested dictionary structure? I have a rather deep python nested array(converted from XML for ease in processing) that has a list within a bunch of dictionaries. I need to access the list object (which should be 'Apparatus') so I can do a number of manipulations. A) Count the current number of list objects so I can add another; B) Change some of the items within the dictionaries within the list objects. But I can't seem to tease out the syntax to let me access the list item(s). (After I figure it out, I'll need to do similar tasks on the more deeply nested "ApparatusPersonnel"). Here's the Dictionary Structure (whose format I don't dictate, nor can I alter, since I have to unparse it back to xml to be consumed by a program outside of my control). ` { 'CadData': { 'EmsIncidentCollection': { 'EmsIncident': { 'AgencyNumber': '222222', 'ZoneNumber': '30'}}, 'FireIncidentCollection': { 'FireIncident': { 'AgencyNumber': '222222', 'Alarm': '2014-02-02T02:23:22-06:00', 'AlarmType': 'TypeofAlarm_SingleStation', 'ApartmentNumber': '4', 'ApparatusCollection': { 'Apparatus': [ { 'ApparatusPersonnelCollection': { 'ApparatusPersonnel': [ { 'FirstName': 'Jon', 'LastName': 'Snow', 'Level': 'PersonnelLevel_FirefighterI', 'LicenseNumber': '1234', 'Rank': 'Captain', 'Role': 'PersonnelRole_Driver', 'TimeIn': '2014-02-02T02:16:23-06:00', 'TimeOut': '2014-02-02T02:22:23-06:00'}, { 'LicenseNumber': '1138'}]}, 'Arrival': '2014-02-02T02:18:22-06:00', 'Clear': '2014-02-02T02:19:22-06:00', 'Dispatch': '2014-02-02T02:16:22-06:00', 'Enroute': '2014-02-02T02:17:22-06:00', 'InService': '2014-02-02T02:20:22-06:00', 'Number': 'AM22'}, { 'Number': 'EM11'}]}, 'Arrival': '2014-02-02T02:24:22-06:00', 'CadID': '0200222', 'CityName': 'Lakeville', 'Controlled': '2014-02-02T02:25:22-06:00', 'CountyName': 'Dakota', 'CrossStreet': None, 'District': None, 'Fdid': '123', 'InService': '2014-02-02T02:27:22-06:00', 'IncidentDate': '2014-02-02T02:21:22-06:00', 'IncidentNumber': '0200222', 'LastUnitCleared': '2014-02-02T02:26:22-06:00', 'Latitude': '44.6550598', 'Longitude': '-93.2710266', 'MixUseProperty': 'MixedUseProperty_IndustrialUse', 'Narrative': 'This ' 'is ' 'a ' 'test ' 'narrative.', 'Psap': '2014-02-02T02:22:22-06:00', 'Shift': 'A', 'StateName': 'MN', 'Station': 'Test ' 'Station', 'StreetName': 'Fake', 'StreetNumber': '123', 'StreetPrefix': 'N', 'StreetSuffix': 'N', 'StreetType': 'ST', 'ZipCode': '55044', 'ZoneNumber': '2B'}}}} ` I have tried to access the list this way: ` for key in my_dict['CadData']['FireIncidentCollection']['FireIncident']['ApparatusCollection']: print(key) print(type(key)) print(len(key)) ` It's putting me in the right spot, but telling me it's a Str: Apparatus <class 'str'> 9 Iterating over the next layer down gives me only the Dictionary object below: ` for key in my_dict['CadData']['FireIncidentCollection']['FireIncident']['ApparatusCollection']['Apparatus']: print(key) print(type(key)) print(len(key)) ` {'Number': 'AM22', 'Dispatch': '2014-02-02T02:16:22-06:00', 'Enroute': '2014-02-02T02:17:22-06:00', 'Arrival': '2014-02-02T02:18:22-06:00', 'Clear': '2014-02-02T02:19:22-06:00', 'InService': '2014-02-02T02:20:22-06:00', 'ApparatusPersonnelCollection': {'ApparatusPersonnel': [{'LicenseNumber': '1234', 'Level': 'PersonnelLevel_FirefighterI', 'Role': 'PersonnelRole_Driver', 'FirstName': 'Jon', 'LastName': 'Snow', 'TimeIn': '2014-02-02T02:16:23-06:00', 'TimeOut': '2014-02-02T02:22:23-06:00', 'Rank': 'Captain'}, {'LicenseNumber': '1138'}]}} <class 'dict'> 7 {'Number': 'EM11'} <class 'dict'> 1 I want to be able to get the length of the list (2 in the sample data) so I can access the list items directly and have an index value to add another (so I would add ....[Apparatus][2]. How can I do that? And, am I going about this poorly, accessing the elements directly by the known element names? Thanks. A: Your desired list can be obtained like this: desired_list = my_dict['CadData']['FireIncidentCollection']['FireIncident']['ApparatusCollection']['Apparatus'] Trying print (desired_list) returns: [{'ApparatusPersonnelCollection': {'ApparatusPersonnel': [{'FirstName': 'Jon', 'LastName': 'Snow', 'Level': 'PersonnelLevel_FirefighterI', 'LicenseNumber': '1234', 'Rank': 'Captain', 'Role': 'PersonnelRole_Driver', 'TimeIn': '2014-02-02T02:16:23-06:00', 'TimeOut': '2014-02-02T02:22:23-06:00'}, {'LicenseNumber': '1138'}]}, 'Arrival': '2014-02-02T02:18:22-06:00', 'Clear': '2014-02-02T02:19:22-06:00', 'Dispatch': '2014-02-02T02:16:22-06:00', 'Enroute': '2014-02-02T02:17:22-06:00', 'InService': '2014-02-02T02:20:22-06:00', 'Number': 'AM22'}, {'Number': 'EM11'}] Which is the list you're trying to get a hold of, yes? If you wanted the length, you'd simply try len(desired_list), which as you wanted, returns 2. As for whether you're going about this poorly by accessing content directly using known key names - that depends on whether your data is always organised this way, so that your target information is always identifiable by the same keys. If this isn't the case, then there has to be some other reliable means by which to identify your data. I guess the answer to your latter question depends on what your overall data set does (and might, if it's changeable) look like.
Python: How to access list object deep within a nested dictionary structure?
I have a rather deep python nested array(converted from XML for ease in processing) that has a list within a bunch of dictionaries. I need to access the list object (which should be 'Apparatus') so I can do a number of manipulations. A) Count the current number of list objects so I can add another; B) Change some of the items within the dictionaries within the list objects. But I can't seem to tease out the syntax to let me access the list item(s). (After I figure it out, I'll need to do similar tasks on the more deeply nested "ApparatusPersonnel"). Here's the Dictionary Structure (whose format I don't dictate, nor can I alter, since I have to unparse it back to xml to be consumed by a program outside of my control). ` { 'CadData': { 'EmsIncidentCollection': { 'EmsIncident': { 'AgencyNumber': '222222', 'ZoneNumber': '30'}}, 'FireIncidentCollection': { 'FireIncident': { 'AgencyNumber': '222222', 'Alarm': '2014-02-02T02:23:22-06:00', 'AlarmType': 'TypeofAlarm_SingleStation', 'ApartmentNumber': '4', 'ApparatusCollection': { 'Apparatus': [ { 'ApparatusPersonnelCollection': { 'ApparatusPersonnel': [ { 'FirstName': 'Jon', 'LastName': 'Snow', 'Level': 'PersonnelLevel_FirefighterI', 'LicenseNumber': '1234', 'Rank': 'Captain', 'Role': 'PersonnelRole_Driver', 'TimeIn': '2014-02-02T02:16:23-06:00', 'TimeOut': '2014-02-02T02:22:23-06:00'}, { 'LicenseNumber': '1138'}]}, 'Arrival': '2014-02-02T02:18:22-06:00', 'Clear': '2014-02-02T02:19:22-06:00', 'Dispatch': '2014-02-02T02:16:22-06:00', 'Enroute': '2014-02-02T02:17:22-06:00', 'InService': '2014-02-02T02:20:22-06:00', 'Number': 'AM22'}, { 'Number': 'EM11'}]}, 'Arrival': '2014-02-02T02:24:22-06:00', 'CadID': '0200222', 'CityName': 'Lakeville', 'Controlled': '2014-02-02T02:25:22-06:00', 'CountyName': 'Dakota', 'CrossStreet': None, 'District': None, 'Fdid': '123', 'InService': '2014-02-02T02:27:22-06:00', 'IncidentDate': '2014-02-02T02:21:22-06:00', 'IncidentNumber': '0200222', 'LastUnitCleared': '2014-02-02T02:26:22-06:00', 'Latitude': '44.6550598', 'Longitude': '-93.2710266', 'MixUseProperty': 'MixedUseProperty_IndustrialUse', 'Narrative': 'This ' 'is ' 'a ' 'test ' 'narrative.', 'Psap': '2014-02-02T02:22:22-06:00', 'Shift': 'A', 'StateName': 'MN', 'Station': 'Test ' 'Station', 'StreetName': 'Fake', 'StreetNumber': '123', 'StreetPrefix': 'N', 'StreetSuffix': 'N', 'StreetType': 'ST', 'ZipCode': '55044', 'ZoneNumber': '2B'}}}} ` I have tried to access the list this way: ` for key in my_dict['CadData']['FireIncidentCollection']['FireIncident']['ApparatusCollection']: print(key) print(type(key)) print(len(key)) ` It's putting me in the right spot, but telling me it's a Str: Apparatus <class 'str'> 9 Iterating over the next layer down gives me only the Dictionary object below: ` for key in my_dict['CadData']['FireIncidentCollection']['FireIncident']['ApparatusCollection']['Apparatus']: print(key) print(type(key)) print(len(key)) ` {'Number': 'AM22', 'Dispatch': '2014-02-02T02:16:22-06:00', 'Enroute': '2014-02-02T02:17:22-06:00', 'Arrival': '2014-02-02T02:18:22-06:00', 'Clear': '2014-02-02T02:19:22-06:00', 'InService': '2014-02-02T02:20:22-06:00', 'ApparatusPersonnelCollection': {'ApparatusPersonnel': [{'LicenseNumber': '1234', 'Level': 'PersonnelLevel_FirefighterI', 'Role': 'PersonnelRole_Driver', 'FirstName': 'Jon', 'LastName': 'Snow', 'TimeIn': '2014-02-02T02:16:23-06:00', 'TimeOut': '2014-02-02T02:22:23-06:00', 'Rank': 'Captain'}, {'LicenseNumber': '1138'}]}} <class 'dict'> 7 {'Number': 'EM11'} <class 'dict'> 1 I want to be able to get the length of the list (2 in the sample data) so I can access the list items directly and have an index value to add another (so I would add ....[Apparatus][2]. How can I do that? And, am I going about this poorly, accessing the elements directly by the known element names? Thanks.
[ "Your desired list can be obtained like this:\ndesired_list = my_dict['CadData']['FireIncidentCollection']['FireIncident']['ApparatusCollection']['Apparatus']\n\nTrying print (desired_list) returns:\n[{'ApparatusPersonnelCollection': {'ApparatusPersonnel': [{'FirstName': 'Jon',\n 'LastName': 'Snow',\n 'Level': 'PersonnelLevel_FirefighterI',\n 'LicenseNumber': '1234',\n 'Rank': 'Captain',\n 'Role': 'PersonnelRole_Driver',\n 'TimeIn': '2014-02-02T02:16:23-06:00',\n 'TimeOut': '2014-02-02T02:22:23-06:00'},\n {'LicenseNumber': '1138'}]},\n 'Arrival': '2014-02-02T02:18:22-06:00',\n 'Clear': '2014-02-02T02:19:22-06:00',\n 'Dispatch': '2014-02-02T02:16:22-06:00',\n 'Enroute': '2014-02-02T02:17:22-06:00',\n 'InService': '2014-02-02T02:20:22-06:00',\n 'Number': 'AM22'},\n {'Number': 'EM11'}]\n\nWhich is the list you're trying to get a hold of, yes? If you wanted the length, you'd simply try len(desired_list), which as you wanted, returns 2.\nAs for whether you're going about this poorly by accessing content directly using known key names - that depends on whether your data is always organised this way, so that your target information is always identifiable by the same keys. If this isn't the case, then there has to be some other reliable means by which to identify your data. I guess the answer to your latter question depends on what your overall data set does (and might, if it's changeable) look like.\n" ]
[ 0 ]
[]
[]
[ "arrays", "dictionary", "indexing", "list", "python" ]
stackoverflow_0074496130_arrays_dictionary_indexing_list_python.txt
Q: Converting from np.float64 to np.float32 completely changes the value of some numbers I have a numpy array of dtype=float64, when attempting to convert it the types to float 32, some values change completely. for example, i have the following array: `test_64 = np.array([20110927.00000,20110928.00000,20110929.00000,20110930.00000,20111003.00000,20111004.00000,20111005.00000,20111006.00000,20111007.00000,20111010.00000,20111011.00000,20111012.00000,20111013.00000,20111014.00000,20111017.00000,20111018.00000,20111019.00000,20111020.00000,20111021.00000,20111024.00000,20111025.00000,20111026.00000,20111027.00000,20111028.00000,20111031.00000,20111101.00000,20111102.00000,20111103.00000,20111104.00000,20111107.00000,20111108.00000,20111109.00000,20111110.00000,20111111.00000,20111114.00000,20111115.00000,20111116.00000,20111117.00000,20111118.00000,20111121.00000,20111122.00000,20111123.00000,20111125.00000,20111128.00000,20111129.00000,20111130.00000,20111201.00000,20111202.00000,20111205.00000,20111206.00000,20111207.00000,20111208.00000,20111209.00000,20111212.00000,20111213.00000,20111214.00000,20111215.00000,20111216.00000,20111219.00000,20111220.00000,20111221.00000,20111222.00000,20111223.00000,20111227.00000,20111228.00000,20111229.00000,20111230.00000,20120103.00000,20120104.00000,20120105.00000,20120106.00000,20120109.00000,20120110.00000,20120111.00000,20120112.00000,20120113.00000,20120117.00000,20120118.00000,20120119.00000,20120120.00000,20120123.00000,20120124.00000,20120125.00000,20120126.00000,20120127.00000,20120130.00000,20120131.00000,20120201.00000,20120202.00000,20120203.00000,20120206.00000,20120207.00000,20120208.00000,20120209.00000,20120210.00000,20120213.00000,20120214.00000,20120215.00000,20120216.00000,20120217.00000]) test_32 = np.array(test_64, dtype=np.float32)` this would change the values of 20110927.00000 to 20110928.00000 even attempting: np.float32(test_64[0]) would result to changing the value to of 20110927.00000 to 20110928.00000 same thing happening when using cupy arrays A: Well, yes, that is what float32 are. Shortest way to see it, float32 have 24 bits significand (1 bit of sign, and 8 bits of exponents). That is 33 bits in all. But the 1st significand bit is not stored, because it is assumed to be 1. np.log2(20110927.) # 24.2614762474699 So, see the problem. You would need 25 bits to be able to have a unit precision on this number. Since you haven't, well, 20110927 and 20110928 are roughly the same from float32 point of view. Longest answer, encode 20110927 in FP32, and then encode 20110928. 20110927 is 1.1987046599388123 × 2²⁴ So exponent is 24. That is, 24+127=151 in the FP32 format Then forgetting the 1st one, that is implicit (since exponent was chosen such as it starts with this 1.), the 23 significand bits s=1.1987046599388123 # Implicit 1 s=s%1*2 # 0.3974... →0 s=s%1*2 # 0.7948... →0 s=s%1*2 # 1.5896... →1 s=s%1*2 # 1.1793... →1 s=s%1*2 # 0.3585... →0 s=s%1*2 # 0.7171... →0 s=s%1*2 # 1.4342... →1 s=s%1*2 # 0.8684... →0 s=s%1*2 # 1.7368... →1 s=s%1*2 # 1.4736... →1 s=s%1*2 # 0.9471... →0 s=s%1*2 # 1.8943... →1 s=s%1*2 # 1.7886... →1 s=s%1*2 # 1.5771... →1 s=s%1*2 # 1.1543... →1 s=s%1*2 # 0.3086... →0 s=s%1*2 # 0.6172... →0 s=s%1*2 # 1.2344... →1 s=s%1*2 # 0.4688... →0 s=s%1*2 # 0.9375... →0 s=s%1*2 # 1.8750... →1 s=s%1*2 # 1.7500... →1 s=s%1*2 # 1.5000... →1 (s%1 is the fractional part of a float. 1.51%1 is 0.51) I compute it that way, starting from 20110927/2²⁴, since that is what is encoded in base 2. But in reality, what that is, is just the binary encoding of 20110927 24 most significant bits. bin(20119827) # 1001100101101111001001111 Note that those are the same bits, but for the last 1, since there are 25 bits, and we need only 24. Including the implicit 1. And because the next bit is 1, or because the last s of my algorithm on floats is 1.5, it is rounded to the next. So in the end, what is encoded is 100110010110111100101000 (I precise this rounding thing for accuracy, to get an exact result. But that is not the reason of your problem. It it was not rounded up, all that would have changed is that, instead of having 20110927=20110928, you would have had 20110927=20110926. But anyway, 24 bits are not enough to distinguish two consecutive base 10 numbers greater than 16777216. Anyway, it is not a sure thing. Sometimes, .5 get rounded down) Ignoring the first one, and adding the sign (0) and exponent (24+127=151 aka 1001011) The float32 representation of 20110927.0 is 01001011100110010110111100101000 Do the same for 20110928.0... and you get the exact same result. So, in float32, 20110927.0 and 20110928.0 (and 20110927.5, ...) are the same thing. Another way to check that without the theory on how to encode float32 is import struct bin(struct.unpack('i', struct.pack('f', 20110927))[0]) # 0b1001011100110010110111100101000 bin(struct.unpack('i', struct.pack('f', 20110928))[0]) # 0b1001011100110010110111100101000 Or to see a bigger picture import struct for i in range(20110901, 20110931): print(i, bin(struct.unpack('i', struct.pack('f', i))[0])) 20110901 0b1001011100110010110111100011010 20110902 0b1001011100110010110111100011011 20110903 0b1001011100110010110111100011100 20110904 0b1001011100110010110111100011100 20110905 0b1001011100110010110111100011100 20110906 0b1001011100110010110111100011101 20110907 0b1001011100110010110111100011110 20110908 0b1001011100110010110111100011110 20110909 0b1001011100110010110111100011110 20110910 0b1001011100110010110111100011111 20110911 0b1001011100110010110111100100000 20110912 0b1001011100110010110111100100000 20110913 0b1001011100110010110111100100000 20110914 0b1001011100110010110111100100001 20110915 0b1001011100110010110111100100010 20110916 0b1001011100110010110111100100010 20110917 0b1001011100110010110111100100010 20110918 0b1001011100110010110111100100011 20110919 0b1001011100110010110111100100100 20110920 0b1001011100110010110111100100100 20110921 0b1001011100110010110111100100100 20110922 0b1001011100110010110111100100101 20110923 0b1001011100110010110111100100110 20110924 0b1001011100110010110111100100110 20110925 0b1001011100110010110111100100110 20110926 0b1001011100110010110111100100111 20110927 0b1001011100110010110111100101000 20110928 0b1001011100110010110111100101000 20110929 0b1001011100110010110111100101000 20110930 0b1001011100110010110111100101001 Note that half of the times .5 is rounded up, half of the times rounded down. Leading to this 3/1 pattern. 20110919=20110920=20110921, 20110922 is unique, 20110923=20110924=20110925, 20110926 is unique, 20119727=20110928=20110929. ... But, the important point is that there are less possible float32 that there are of possible 8 digits base 10 numbers in this range.
Converting from np.float64 to np.float32 completely changes the value of some numbers
I have a numpy array of dtype=float64, when attempting to convert it the types to float 32, some values change completely. for example, i have the following array: `test_64 = np.array([20110927.00000,20110928.00000,20110929.00000,20110930.00000,20111003.00000,20111004.00000,20111005.00000,20111006.00000,20111007.00000,20111010.00000,20111011.00000,20111012.00000,20111013.00000,20111014.00000,20111017.00000,20111018.00000,20111019.00000,20111020.00000,20111021.00000,20111024.00000,20111025.00000,20111026.00000,20111027.00000,20111028.00000,20111031.00000,20111101.00000,20111102.00000,20111103.00000,20111104.00000,20111107.00000,20111108.00000,20111109.00000,20111110.00000,20111111.00000,20111114.00000,20111115.00000,20111116.00000,20111117.00000,20111118.00000,20111121.00000,20111122.00000,20111123.00000,20111125.00000,20111128.00000,20111129.00000,20111130.00000,20111201.00000,20111202.00000,20111205.00000,20111206.00000,20111207.00000,20111208.00000,20111209.00000,20111212.00000,20111213.00000,20111214.00000,20111215.00000,20111216.00000,20111219.00000,20111220.00000,20111221.00000,20111222.00000,20111223.00000,20111227.00000,20111228.00000,20111229.00000,20111230.00000,20120103.00000,20120104.00000,20120105.00000,20120106.00000,20120109.00000,20120110.00000,20120111.00000,20120112.00000,20120113.00000,20120117.00000,20120118.00000,20120119.00000,20120120.00000,20120123.00000,20120124.00000,20120125.00000,20120126.00000,20120127.00000,20120130.00000,20120131.00000,20120201.00000,20120202.00000,20120203.00000,20120206.00000,20120207.00000,20120208.00000,20120209.00000,20120210.00000,20120213.00000,20120214.00000,20120215.00000,20120216.00000,20120217.00000]) test_32 = np.array(test_64, dtype=np.float32)` this would change the values of 20110927.00000 to 20110928.00000 even attempting: np.float32(test_64[0]) would result to changing the value to of 20110927.00000 to 20110928.00000 same thing happening when using cupy arrays
[ "Well, yes, that is what float32 are.\nShortest way to see it, float32 have 24 bits significand (1 bit of sign, and 8 bits of exponents). That is 33 bits in all. But the 1st significand bit is not stored, because it is assumed to be 1.\nnp.log2(20110927.)\n# 24.2614762474699\n\nSo, see the problem. You would need 25 bits to be able to have a unit precision on this number. Since you haven't, well, 20110927 and 20110928 are roughly the same from float32 point of view.\nLongest answer, encode 20110927 in FP32, and then encode 20110928.\n20110927 is 1.1987046599388123 × 2²⁴\nSo exponent is 24.\nThat is, 24+127=151 in the FP32 format\nThen forgetting the 1st one, that is implicit (since exponent was chosen such as it starts with this 1.), the 23 significand bits\ns=1.1987046599388123 # Implicit 1\ns=s%1*2 # 0.3974... →0\ns=s%1*2 # 0.7948... →0\ns=s%1*2 # 1.5896... →1\ns=s%1*2 # 1.1793... →1\ns=s%1*2 # 0.3585... →0\ns=s%1*2 # 0.7171... →0\ns=s%1*2 # 1.4342... →1\ns=s%1*2 # 0.8684... →0\ns=s%1*2 # 1.7368... →1\ns=s%1*2 # 1.4736... →1\ns=s%1*2 # 0.9471... →0\ns=s%1*2 # 1.8943... →1\ns=s%1*2 # 1.7886... →1\ns=s%1*2 # 1.5771... →1\ns=s%1*2 # 1.1543... →1\ns=s%1*2 # 0.3086... →0\ns=s%1*2 # 0.6172... →0\ns=s%1*2 # 1.2344... →1\ns=s%1*2 # 0.4688... →0\ns=s%1*2 # 0.9375... →0\ns=s%1*2 # 1.8750... →1\ns=s%1*2 # 1.7500... →1\ns=s%1*2 # 1.5000... →1\n\n(s%1 is the fractional part of a float. 1.51%1 is 0.51)\nI compute it that way, starting from 20110927/2²⁴, since that is what is encoded in base 2. But in reality, what that is, is just the binary encoding of 20110927 24 most significant bits.\nbin(20119827)\n# 1001100101101111001001111\n\nNote that those are the same bits, but for the last 1, since there are 25 bits, and we need only 24. Including the implicit 1.\nAnd because the next bit is 1, or because the last s of my algorithm on floats is 1.5, it is rounded to the next.\nSo in the end, what is encoded is\n100110010110111100101000\n(I precise this rounding thing for accuracy, to get an exact result. But that is not the reason of your problem. It it was not rounded up, all that would have changed is that, instead of having 20110927=20110928, you would have had 20110927=20110926. But anyway, 24 bits are not enough to distinguish two consecutive base 10 numbers greater than 16777216. Anyway, it is not a sure thing. Sometimes, .5 get rounded down)\nIgnoring the first one, and adding the sign (0) and exponent (24+127=151 aka 1001011)\nThe float32 representation of 20110927.0 is\n01001011100110010110111100101000\nDo the same for 20110928.0... and you get the exact same result.\nSo, in float32, 20110927.0 and 20110928.0 (and 20110927.5, ...) are the same thing.\nAnother way to check that without the theory on how to encode float32 is\nimport struct\nbin(struct.unpack('i', struct.pack('f', 20110927))[0])\n# 0b1001011100110010110111100101000\nbin(struct.unpack('i', struct.pack('f', 20110928))[0])\n# 0b1001011100110010110111100101000\n\n\nOr to see a bigger picture\nimport struct\nfor i in range(20110901, 20110931):\n print(i, bin(struct.unpack('i', struct.pack('f', i))[0]))\n\n20110901 0b1001011100110010110111100011010\n20110902 0b1001011100110010110111100011011\n20110903 0b1001011100110010110111100011100\n20110904 0b1001011100110010110111100011100\n20110905 0b1001011100110010110111100011100\n20110906 0b1001011100110010110111100011101\n20110907 0b1001011100110010110111100011110\n20110908 0b1001011100110010110111100011110\n20110909 0b1001011100110010110111100011110\n20110910 0b1001011100110010110111100011111\n20110911 0b1001011100110010110111100100000\n20110912 0b1001011100110010110111100100000\n20110913 0b1001011100110010110111100100000\n20110914 0b1001011100110010110111100100001\n20110915 0b1001011100110010110111100100010\n20110916 0b1001011100110010110111100100010\n20110917 0b1001011100110010110111100100010\n20110918 0b1001011100110010110111100100011\n20110919 0b1001011100110010110111100100100\n20110920 0b1001011100110010110111100100100\n20110921 0b1001011100110010110111100100100\n20110922 0b1001011100110010110111100100101\n20110923 0b1001011100110010110111100100110\n20110924 0b1001011100110010110111100100110\n20110925 0b1001011100110010110111100100110\n20110926 0b1001011100110010110111100100111\n20110927 0b1001011100110010110111100101000\n20110928 0b1001011100110010110111100101000\n20110929 0b1001011100110010110111100101000\n20110930 0b1001011100110010110111100101001\n\nNote that half of the times .5 is rounded up, half of the times rounded down. Leading to this 3/1 pattern. 20110919=20110920=20110921, 20110922 is unique, 20110923=20110924=20110925, 20110926 is unique, 20119727=20110928=20110929. ...\nBut, the important point is that there are less possible float32 that there are of possible 8 digits base 10 numbers in this range.\n" ]
[ 3 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074495636_arrays_numpy_python.txt
Q: Import "flask_sqlalchemy" could not be resolved from source: Pylance I have tried all of the other solutions before posting here so I hope this does not get removed. Error comes form this line: from flask_sqlalchemy import SQLAlchemy I am running the latest version of VSCode. Things I've tried from within my virtual envionment (venv) 1. pip install flask_sqlalchemy 2. pip3 install flask_sqlalchemy 3. pip install flask_sqlalchemy --user I also have my python VSCode python interpreter set to the the interpreter within the virtual environment. I can see the flask_sqalchemy is installed within my requirements.txt: Flask==1.1.1 Flask-SQLAlchemy==2.5.1 I really don't know what else to try at this point. A: I was having the same problem, I messed around a lot reinstalling things so I'm not 100% sure what the perfect solution is but this is what finally worked for me. View -> Command Pallete -> Python: Select Interpreter -> Select the version that says 'Global' Then follow the same steps but instead select the version that says 'Recommended'. I am assuming it somehow reinitialized the version of python I was trying to use. A: I was having the same problem, but I was using pipenv which sets up a special environment for the execution with the python modules installed in that environment. When I execute the "pipenv shell" command, the response shows me the environment that is created and has the version of the interpreter that should be used for this environment. The line I get is: myuser@Pspec7:~/pydev/flask$ . /home/myuser/.local/share/virtualenvs/flask-E0DF0fBp/bin/activate When you get to the point where you can select your interpreter: In the interpreter list look for the path that corresponds to your environment. From the line above, my interpreter was: Python 3.8.10 ('flask-E0DF0fBp') This was for me. You need to look for your correspoding string. Without setting the interpreter correctly, it cannot look through the packages you have installed.
Import "flask_sqlalchemy" could not be resolved from source: Pylance
I have tried all of the other solutions before posting here so I hope this does not get removed. Error comes form this line: from flask_sqlalchemy import SQLAlchemy I am running the latest version of VSCode. Things I've tried from within my virtual envionment (venv) 1. pip install flask_sqlalchemy 2. pip3 install flask_sqlalchemy 3. pip install flask_sqlalchemy --user I also have my python VSCode python interpreter set to the the interpreter within the virtual environment. I can see the flask_sqalchemy is installed within my requirements.txt: Flask==1.1.1 Flask-SQLAlchemy==2.5.1 I really don't know what else to try at this point.
[ "I was having the same problem, I messed around a lot reinstalling things so I'm not 100% sure what the perfect solution is but this is what finally worked for me.\nView -> Command Pallete -> Python: Select Interpreter -> Select the version that says 'Global'\nThen follow the same steps but instead select the version that says 'Recommended'.\nI am assuming it somehow reinitialized the version of python I was trying to use.\n", "I was having the same problem, but I was using pipenv which sets up a special environment for the execution with the python modules installed in that environment. When I execute the \"pipenv shell\" command, the response shows me the environment that is created and has the version of the interpreter that should be used for this environment.\nThe line I get is:\nmyuser@Pspec7:~/pydev/flask$ . /home/myuser/.local/share/virtualenvs/flask-E0DF0fBp/bin/activate\nWhen you get to the point where you can select your interpreter: In the interpreter list look for the path that corresponds to your environment.\nFrom the line above, my interpreter was: Python 3.8.10 ('flask-E0DF0fBp')\nThis was for me. You need to look for your correspoding string.\nWithout setting the interpreter correctly, it cannot look through the packages you have installed.\n" ]
[ 1, 0 ]
[]
[]
[ "pylance", "python", "visual_studio_code" ]
stackoverflow_0071489531_pylance_python_visual_studio_code.txt
Q: How to migrate password hashes from Passlib.bcrypt to Django's default pbkdf2_sha256? I had a FastAPI app that had been using Passlib's bcrypt module to hash passwords. Here's an example string that is stored in the database as a password: $2b$12$62GCnIkiQp7dE/N2.Al4t.ODW.JYXCz8rHHmaLt63NnML4xDgKhFK Now, the problem is I'm not sure whether it's possible to migrate this hash over to my new django application, since django stores hashes in a string that looks like this: <algorithm>$<iterations>$<salt>$<hash> I thought the solution could be that the PassLib hash is B64 encoded, but I'm not really sure how to decode it into something that works for Django. A: Okay, so after trying around I came up with the solution First: add "django.contrib.auth.hashers.BCryptPasswordHasher" to settings.PASSWORD_HASHERS Now, you can to every string that looks $2b$12$62GCnIkiQp7dE/N2.Al4t.ODW.JYXCz8rHHmaLt63NnML4xDgKhFK you add bcrypt$ for the result to look like bcrypt$$2b$12$62GCnIkiQp7dE/N2.Al4t.ODW.JYXCz8rHHmaLt63NnML4xDgKhFK. Not sure why there have to be two dollar signs after the method name, but if they are not there - django raises an exception: it expect 5 objects from hash.split("$"), and the second object is called "empty". After doing this to my passwords that I used in my FastAPI app and adding users to django, authorization started to work.
How to migrate password hashes from Passlib.bcrypt to Django's default pbkdf2_sha256?
I had a FastAPI app that had been using Passlib's bcrypt module to hash passwords. Here's an example string that is stored in the database as a password: $2b$12$62GCnIkiQp7dE/N2.Al4t.ODW.JYXCz8rHHmaLt63NnML4xDgKhFK Now, the problem is I'm not sure whether it's possible to migrate this hash over to my new django application, since django stores hashes in a string that looks like this: <algorithm>$<iterations>$<salt>$<hash> I thought the solution could be that the PassLib hash is B64 encoded, but I'm not really sure how to decode it into something that works for Django.
[ "Okay, so after trying around I came up with the solution\nFirst: add \"django.contrib.auth.hashers.BCryptPasswordHasher\" to settings.PASSWORD_HASHERS\nNow, you can to every string that looks $2b$12$62GCnIkiQp7dE/N2.Al4t.ODW.JYXCz8rHHmaLt63NnML4xDgKhFK you add bcrypt$ for the result to look like bcrypt$$2b$12$62GCnIkiQp7dE/N2.Al4t.ODW.JYXCz8rHHmaLt63NnML4xDgKhFK.\nNot sure why there have to be two dollar signs after the method name, but if they are not there - django raises an exception: it expect 5 objects from hash.split(\"$\"), and the second object is called \"empty\".\nAfter doing this to my passwords that I used in my FastAPI app and adding users to django, authorization started to work.\n" ]
[ 0 ]
[]
[]
[ "bcrypt", "hash", "pbkdf2", "python" ]
stackoverflow_0074478134_bcrypt_hash_pbkdf2_python.txt
Q: Plotly express: text is "flying in" in animations Added some text (to be displayed on the bars) in a bar chart with animation frames. And well, the text instead of rising along with the bar (like in the beginning of the GIF when I manually move the slider), flies in from the top left corner at each frame until the bar is big enough to fit in the number. Now, tweaking textposition in fig.update_traces() does kinda help. But it limits the text to either inside or outside. The former is not visible in smaller bars at all and the latter imo doesn't look as good as what auto would've looked like without the flying in. Here is the code to replicate the problem in a smaller dataset- import pandas as pd from pandas import Timestamp import plotly.express as px df = pd.DataFrame({'continent': {127: 'South America', 128: 'South America', 129: 'South America', 130: 'South America', 131: 'South America', 105: 'Oceania', 106: 'Oceania', 107: 'Oceania', 108: 'Oceania', 109: 'Oceania'}, 'date': {127: Timestamp('2021-03-01 00:00:00'), 128: Timestamp('2021-03-26 00:00:00'), 129: Timestamp('2021-04-20 00:00:00'), 130: Timestamp('2021-05-15 00:00:00'), 131: Timestamp('2021-06-09 00:00:00'), 105: Timestamp('2021-03-01 00:00:00'), 106: Timestamp('2021-03-26 00:00:00'), 107: Timestamp('2021-04-20 00:00:00'), 108: Timestamp('2021-05-15 00:00:00'), 109: Timestamp('2021-06-09 00:00:00')}, 'total_cases': {127: 20465329.0, 128: 23470911.0, 129: 26544779.0, 130: 29891133.0, 131: 30634559.0, 105: 35923.0, 106: 42208.0, 107: 46514.0, 108: 50183.0, 109: 50805.0}}) px.bar(df, x='continent', y='total_cases', animation_frame=df.date.astype(str), text='total_cases') A: I realize this question was asked a long time ago, but I'm still going to answer it. Essentially, since the text doesn't 'fit', it flies. I think that that will make more sense by the time you get to the end of this answer. If you render this code in too small of a space, you can still reproduce the 'flying' effect. I start out by explaining the code, but at the end of the answer, I've put all the code together in one chunk to make it easier for you to collect. Some background...not all that important to the solution! Alright, in Python, you've got Plotly Express and Plotly Graph Objects. Express functions are intuitive, simple, and somewhat inflexible. Graph Objects are less intuitive, complex, and extremely flexible. Essentially all express graphs are turned into graph objects in the background. This answer will use the simplicity of Express, then dump that content into graph objects so that you can stop 'flying' your text. Create some data First things first---we need to separate the text from the bar chart. Instead of using the height of the bar, we're going to add quite a bit of space between the bar and the text because of the extremely large differences in bar values. In the data you provided in your question, the range was between 0 and 30M, so I used a 1,000,000 buffer. You may need to adjust that since your original data appears to have twice the range. I'm going to create the variable y to store these values. Then I sorted the data by date since it isn't in the example data. (I'm assuming, of course, this is an expectation. You can remove this, of course.) df['y'] = [1000000] * 10 df.sort_values('date', inplace = True) The text trace I'm using a bar chart, but I've set the opacity to 0. The color is specified because light colors tell Plotly to use black text. fig = px.bar(df, x = 'continent', y = 'y', text = 'total_cases', opacity = 0, # light color despite opacity, so text is black color_discrete_sequence = ['aliceblue'], animation_frame=df.date.astype('str')) The bar trace I've made two changes from your original call: assigned an object name and removed the text argument. fig2 = px.bar(df, x = 'continent', y = 'total_cases', animation_frame=df.date.astype('str')) Extracting the animation Now, we're going to create the frames we need for graph_objects. Since we have two traces, I'm going to enumerate them. frames = [ # create two traces for each frame using the two plots go.Frame(data = f.data + fig.frames[i].data, name = f.name) for i, f in enumerate(fig2.frames) ] Consolidating the graphics Next, we're going to create a new figure using the frames just created and the layout from the bar trace. (It doesn't matter which layout you choose.) # consolidate data into one graph fig4 = go.Figure(data = frames[0].data, frames = frames, layout = fig2.layout) If you render the plot at this point, you'll see that the text runs off the top of the graph. Animation frames inherently are set to autorange, adjusting the y-axis continuously. It will be much better to see a single range for the animation. To do this, set the fixedrange to true, then I added the tick arrays (values and labels). fig4.update_yaxes(range = [0, 34000000], fixedrange = True, ticktext = ["0", "5M", "10M", "10M", "20M", "25M", "30M"], tickvals = [0, 5000000, 10000000, 15000000, 20000000, 25000000, 30000000]) FYI regarding tick customization I'm aware that your range will be different. Instead of writing it all out, you could enumerate the tick values and labels. So if you needed to go to 60M, then you would just need to change the 7 in each of these statements to 13. For the values (tickvals) [x + 50000000 * i for i, x in enumerate([0] * 7)] For the labels (ticktext) [str(x + 5 * i) + "M" for i, x in enumerate([0] * 7)] Check out the Animation on Code Pen I used plotly.io's to_html and pasted it into a Code Pen. Check out the animation here. Consolidated Code Here's all of the code altogether (including the packages you need): import plotly.graph_objects as go import pandas as pd # for the data from pandas import Timestamp # for the data import plotly.express as px df['y'] = [1000000] * 10 # location for text placement df.sort_values('date', inplace = True) fig = px.bar(df, x = 'continent', y = 'y', text = 'total_cases', opacity = 0, # light color despite opacity, so text is black color_discrete_sequence = ['aliceblue'], animation_frame=df.date.astype('str')) fig1 = px.bar(df, x = 'continent', y = 'total_cases', animation_frame=df.date.astype('str')) frames = [ # create two traces for each frame using the two plots go.Frame(data = f.data + fig.frames[i].data, name = f.name) for i, f in enumerate(fig1.frames) ] # consolidate data into one graph fig4 = go.Figure(data = frames[0].data, frames = frames, layout = fig.layout) fig4.update_yaxes(range = [0, 34000000], fixedrange = True, ticktext = ["0", "5M", "10M", "10M", "20M", "25M", "30M"], tickvals = [0, 5000000, 10000000, 15000000, 20000000, 25000000, 30000000]) fig4.show()
Plotly express: text is "flying in" in animations
Added some text (to be displayed on the bars) in a bar chart with animation frames. And well, the text instead of rising along with the bar (like in the beginning of the GIF when I manually move the slider), flies in from the top left corner at each frame until the bar is big enough to fit in the number. Now, tweaking textposition in fig.update_traces() does kinda help. But it limits the text to either inside or outside. The former is not visible in smaller bars at all and the latter imo doesn't look as good as what auto would've looked like without the flying in. Here is the code to replicate the problem in a smaller dataset- import pandas as pd from pandas import Timestamp import plotly.express as px df = pd.DataFrame({'continent': {127: 'South America', 128: 'South America', 129: 'South America', 130: 'South America', 131: 'South America', 105: 'Oceania', 106: 'Oceania', 107: 'Oceania', 108: 'Oceania', 109: 'Oceania'}, 'date': {127: Timestamp('2021-03-01 00:00:00'), 128: Timestamp('2021-03-26 00:00:00'), 129: Timestamp('2021-04-20 00:00:00'), 130: Timestamp('2021-05-15 00:00:00'), 131: Timestamp('2021-06-09 00:00:00'), 105: Timestamp('2021-03-01 00:00:00'), 106: Timestamp('2021-03-26 00:00:00'), 107: Timestamp('2021-04-20 00:00:00'), 108: Timestamp('2021-05-15 00:00:00'), 109: Timestamp('2021-06-09 00:00:00')}, 'total_cases': {127: 20465329.0, 128: 23470911.0, 129: 26544779.0, 130: 29891133.0, 131: 30634559.0, 105: 35923.0, 106: 42208.0, 107: 46514.0, 108: 50183.0, 109: 50805.0}}) px.bar(df, x='continent', y='total_cases', animation_frame=df.date.astype(str), text='total_cases')
[ "I realize this question was asked a long time ago, but I'm still going to answer it. Essentially, since the text doesn't 'fit', it flies. I think that that will make more sense by the time you get to the end of this answer. If you render this code in too small of a space, you can still reproduce the 'flying' effect.\nI start out by explaining the code, but at the end of the answer, I've put all the code together in one chunk to make it easier for you to collect.\nSome background...not all that important to the solution!\nAlright, in Python, you've got Plotly Express and Plotly Graph Objects. Express functions are intuitive, simple, and somewhat inflexible. Graph Objects are less intuitive, complex, and extremely flexible. Essentially all express graphs are turned into graph objects in the background.\nThis answer will use the simplicity of Express, then dump that content into graph objects so that you can stop 'flying' your text.\nCreate some data\nFirst things first---we need to separate the text from the bar chart. Instead of using the height of the bar, we're going to add quite a bit of space between the bar and the text because of the extremely large differences in bar values.\nIn the data you provided in your question, the range was between 0 and 30M, so I used a 1,000,000 buffer. You may need to adjust that since your original data appears to have twice the range.\nI'm going to create the variable y to store these values. Then I sorted the data by date since it isn't in the example data. (I'm assuming, of course, this is an expectation. You can remove this, of course.)\ndf['y'] = [1000000] * 10\ndf.sort_values('date', inplace = True) \n\nThe text trace\nI'm using a bar chart, but I've set the opacity to 0. The color is specified because light colors tell Plotly to use black text.\nfig = px.bar(df, x = 'continent', y = 'y', text = 'total_cases', opacity = 0,\n # light color despite opacity, so text is black\n color_discrete_sequence = ['aliceblue'],\n animation_frame=df.date.astype('str'))\n\nThe bar trace\nI've made two changes from your original call: assigned an object name and removed the text argument.\nfig2 = px.bar(df, x = 'continent', y = 'total_cases', \n animation_frame=df.date.astype('str'))\n\nExtracting the animation\nNow, we're going to create the frames we need for graph_objects. Since we have two traces, I'm going to enumerate them.\nframes = [ # create two traces for each frame using the two plots\n go.Frame(data = f.data + fig.frames[i].data, name = f.name)\n for i, f in enumerate(fig2.frames)\n]\n\nConsolidating the graphics\nNext, we're going to create a new figure using the frames just created and the layout from the bar trace. (It doesn't matter which layout you choose.)\n# consolidate data into one graph\nfig4 = go.Figure(data = frames[0].data, frames = frames, layout = fig2.layout)\n\nIf you render the plot at this point, you'll see that the text runs off the top of the graph. Animation frames inherently are set to autorange, adjusting the y-axis continuously. It will be much better to see a single range for the animation. To do this, set the fixedrange to true, then I added the tick arrays (values and labels).\nfig4.update_yaxes(range = [0, 34000000], fixedrange = True, \n ticktext = [\"0\", \"5M\", \"10M\", \"10M\", \"20M\", \"25M\", \"30M\"],\n tickvals = [0, 5000000, 10000000, 15000000, 20000000, 25000000, 30000000])\n\nFYI regarding tick customization\nI'm aware that your range will be different. Instead of writing it all out, you could enumerate the tick values and labels. So if you needed to go to 60M, then you would just need to change the 7 in each of these statements to 13.\nFor the values (tickvals)\n[x + 50000000 * i for i, x in enumerate([0] * 7)]\n\nFor the labels (ticktext)\n[str(x + 5 * i) + \"M\" for i, x in enumerate([0] * 7)]\n\nCheck out the Animation on Code Pen\nI used plotly.io's to_html and pasted it into a Code Pen. Check out the animation here.\nConsolidated Code\nHere's all of the code altogether (including the packages you need):\nimport plotly.graph_objects as go \nimport pandas as pd # for the data\nfrom pandas import Timestamp # for the data\nimport plotly.express as px\n\ndf['y'] = [1000000] * 10 # location for text placement\ndf.sort_values('date', inplace = True)\n\nfig = px.bar(df, x = 'continent', y = 'y', text = 'total_cases', opacity = 0,\n # light color despite opacity, so text is black\n color_discrete_sequence = ['aliceblue'],\n animation_frame=df.date.astype('str'))\n\nfig1 = px.bar(df, x = 'continent', y = 'total_cases', \n animation_frame=df.date.astype('str'))\n\nframes = [ # create two traces for each frame using the two plots\n go.Frame(data = f.data + fig.frames[i].data, name = f.name)\n for i, f in enumerate(fig1.frames)\n]\n# consolidate data into one graph\nfig4 = go.Figure(data = frames[0].data, frames = frames, layout = fig.layout)\n\nfig4.update_yaxes(range = [0, 34000000], fixedrange = True, \n ticktext = [\"0\", \"5M\", \"10M\", \"10M\", \"20M\", \"25M\", \"30M\"],\n tickvals = [0, 5000000, 10000000, 15000000, 20000000, 25000000, 30000000])\n\nfig4.show()\n\n" ]
[ 0 ]
[]
[]
[ "animation", "data_visualization", "plotly", "plotly_python", "python" ]
stackoverflow_0067972110_animation_data_visualization_plotly_plotly_python_python.txt
Q: Stripe implementation in django not redirecting to success page I was trying to implement stripe in Django and everything worked fine until I tried to redirect the user to a success page after the payment. Can anybody have a look at my code and tell me what I am doing wrong? views.py @csrf_exempt def create_checkout_session(request, id): request_data = json.loads(request.body) gig = get_object_or_404(Gig, pk=id) stripe.api_key = settings.STRIPE_SECRET_KEY checkout_session = stripe.checkout.Session.create( customer_email=request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'eur', 'product_data': { 'name': gig.seller, }, 'unit_amount': int(gig.price * 100), }, 'quantity': 1, } ], mode='payment', success_url='http://127.0.0.1:8000/checkout/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://127.0.0.1:8000/checkout/failed/', ) order = OrderDetail() order.customer_email = request_data['email'] order.gig = gig order.stripe_payment_intent = checkout_session.payment_intent order.amount = int(gig.price * 100) order.save() # return JsonResponse({'data': checkout_session}) return JsonResponse({'sessionId': checkout_session.id}) class PaymentSuccessView(TemplateView): template_name = "checkout/payment_success.html" def get(self, request, *args, **kwargs): session_id = request.GET.get('session_id') if session_id is None: return HttpResponse("failed") stripe.api_key = settings.STRIPE_SECRET_KEY session = stripe.checkout.Session.retrieve(session_id) order = get_object_or_404(OrderDetail, stripe_payment_intent=session.payment_intent) order.has_paid = True order.save() return render(request, self.template_name) models.py from django.db import models from django.core import validators class OrderDetail(models.Model): id = models.BigAutoField( primary_key=True ) # You can change as a Foreign Key to the user model customer_email = models.EmailField( verbose_name='Customer Email' ) gig = models.ForeignKey( to=Gig, verbose_name='Product', on_delete=models.PROTECT ) amount = models.IntegerField( verbose_name='Amount' ) stripe_payment_intent = models.CharField( max_length=200, null=True, blank=True ) # This field can be changed as status has_paid = models.BooleanField( default=False, verbose_name='Payment Status' ) created_on = models.DateTimeField( auto_now_add=True ) updated_on = models.DateTimeField( auto_now_add=True ) class Gig(models.Model): id = models.BigAutoField( primary_key=True ) gigger = models.ForeignKey( Mentors, on_delete=models.CASCADE, related_name="seller") description = models.TextField( blank=True, max_length=800, verbose_name='Description' ) price = models.DecimalField( verbose_name='Price', decimal_places=2, max_digits=6, ) def __str__(self): return f"{self.gigger}, ${self.price}, id:{self.id}" class Comments: user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Commentor") comment = models.TextField(blank=True) stars = models.PositiveSmallIntegerField() product.html {% extends 'web/layout.html' %} {% block body %} <h1 class="text-center">Product Detail</h1> <div class="container"> <div class="card"> <div class="card-header"> <h2>Product Detail</h2> </div> <div class="card-body"> <div class="container row"> <div class="col-md-2"> <img src="https://dummyimage.com/150x150.gif?text={{ object.name }}" alt=""> </div> <div class="col-md-10"> <h1>Name: {{ object.seller.mentor.username }}</h1> <p>Description: {{ object.description }}</p> <p>Price: {{ object.price }}</p> <div class="form-group"> <label for="email">Email: </label> <input type="email" name="email" id="email" class="form-control" placeholder="{{object.gigger.mentor.email}}"> <small>Please enter your email address</small> </div> </div> </div> </div> <div class="card-footer d-flex"> <button class="btn btn-success ml-auto" id="checkout-button">Checkout</button> </div> </div> </div> <script src="https://js.stripe.com/v3/"></script> <script type="text/javascript"> // Create an instance of the Stripe object with your publishable API key var stripe = Stripe('{{ stripe_publishable_key }}'); var checkoutButton = document.getElementById('checkout-button'); checkoutButton.addEventListener('click', function () { var email = document.getElementById('email').value; if (email.length == 0) { alert("Please enter your email address."); return; } // Create a new Checkout Session using the server-side endpoint you // created in step 3. fetch("http://127.0.0.1:8000/checkout/api/checkout-session/{{ object.id }}/", { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify( { email: email } ) }) .then(response => response.json()) .then(function (session) { return stripe.redirectToCheckout({ sessionId: session.sessionId }); }) .then(function (result) { // If `redirectToCheckout` fails due to a browser or network // error, you should display the localized error message to your // customer using `error.message`. if (result.error) { alert(result.error.message); } }) .catch(function (error) { console.error('Error:', error); }); }); </script> {% endblock %} After placing an order, when I go in the 'order details' object and see the 'stripe_payment_intend' key is always empty, it doesn't get saved. What else could I try to get each different order? A: The issue is that the point when you create the Checkout Session and set the order data is disconnected from the point at which you render your success page with the PaymentSuccessView class. Just because those two pieces of code are in the same file does not mean the state will be maintained between different requests. What you can do instead is add the order information to the Checkout Session using metadata. Then when you retrieve the Checkout Session on your success page you can read the metadata from the Checkout Session to get the associated information.
Stripe implementation in django not redirecting to success page
I was trying to implement stripe in Django and everything worked fine until I tried to redirect the user to a success page after the payment. Can anybody have a look at my code and tell me what I am doing wrong? views.py @csrf_exempt def create_checkout_session(request, id): request_data = json.loads(request.body) gig = get_object_or_404(Gig, pk=id) stripe.api_key = settings.STRIPE_SECRET_KEY checkout_session = stripe.checkout.Session.create( customer_email=request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'eur', 'product_data': { 'name': gig.seller, }, 'unit_amount': int(gig.price * 100), }, 'quantity': 1, } ], mode='payment', success_url='http://127.0.0.1:8000/checkout/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://127.0.0.1:8000/checkout/failed/', ) order = OrderDetail() order.customer_email = request_data['email'] order.gig = gig order.stripe_payment_intent = checkout_session.payment_intent order.amount = int(gig.price * 100) order.save() # return JsonResponse({'data': checkout_session}) return JsonResponse({'sessionId': checkout_session.id}) class PaymentSuccessView(TemplateView): template_name = "checkout/payment_success.html" def get(self, request, *args, **kwargs): session_id = request.GET.get('session_id') if session_id is None: return HttpResponse("failed") stripe.api_key = settings.STRIPE_SECRET_KEY session = stripe.checkout.Session.retrieve(session_id) order = get_object_or_404(OrderDetail, stripe_payment_intent=session.payment_intent) order.has_paid = True order.save() return render(request, self.template_name) models.py from django.db import models from django.core import validators class OrderDetail(models.Model): id = models.BigAutoField( primary_key=True ) # You can change as a Foreign Key to the user model customer_email = models.EmailField( verbose_name='Customer Email' ) gig = models.ForeignKey( to=Gig, verbose_name='Product', on_delete=models.PROTECT ) amount = models.IntegerField( verbose_name='Amount' ) stripe_payment_intent = models.CharField( max_length=200, null=True, blank=True ) # This field can be changed as status has_paid = models.BooleanField( default=False, verbose_name='Payment Status' ) created_on = models.DateTimeField( auto_now_add=True ) updated_on = models.DateTimeField( auto_now_add=True ) class Gig(models.Model): id = models.BigAutoField( primary_key=True ) gigger = models.ForeignKey( Mentors, on_delete=models.CASCADE, related_name="seller") description = models.TextField( blank=True, max_length=800, verbose_name='Description' ) price = models.DecimalField( verbose_name='Price', decimal_places=2, max_digits=6, ) def __str__(self): return f"{self.gigger}, ${self.price}, id:{self.id}" class Comments: user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Commentor") comment = models.TextField(blank=True) stars = models.PositiveSmallIntegerField() product.html {% extends 'web/layout.html' %} {% block body %} <h1 class="text-center">Product Detail</h1> <div class="container"> <div class="card"> <div class="card-header"> <h2>Product Detail</h2> </div> <div class="card-body"> <div class="container row"> <div class="col-md-2"> <img src="https://dummyimage.com/150x150.gif?text={{ object.name }}" alt=""> </div> <div class="col-md-10"> <h1>Name: {{ object.seller.mentor.username }}</h1> <p>Description: {{ object.description }}</p> <p>Price: {{ object.price }}</p> <div class="form-group"> <label for="email">Email: </label> <input type="email" name="email" id="email" class="form-control" placeholder="{{object.gigger.mentor.email}}"> <small>Please enter your email address</small> </div> </div> </div> </div> <div class="card-footer d-flex"> <button class="btn btn-success ml-auto" id="checkout-button">Checkout</button> </div> </div> </div> <script src="https://js.stripe.com/v3/"></script> <script type="text/javascript"> // Create an instance of the Stripe object with your publishable API key var stripe = Stripe('{{ stripe_publishable_key }}'); var checkoutButton = document.getElementById('checkout-button'); checkoutButton.addEventListener('click', function () { var email = document.getElementById('email').value; if (email.length == 0) { alert("Please enter your email address."); return; } // Create a new Checkout Session using the server-side endpoint you // created in step 3. fetch("http://127.0.0.1:8000/checkout/api/checkout-session/{{ object.id }}/", { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify( { email: email } ) }) .then(response => response.json()) .then(function (session) { return stripe.redirectToCheckout({ sessionId: session.sessionId }); }) .then(function (result) { // If `redirectToCheckout` fails due to a browser or network // error, you should display the localized error message to your // customer using `error.message`. if (result.error) { alert(result.error.message); } }) .catch(function (error) { console.error('Error:', error); }); }); </script> {% endblock %} After placing an order, when I go in the 'order details' object and see the 'stripe_payment_intend' key is always empty, it doesn't get saved. What else could I try to get each different order?
[ "The issue is that the point when you create the Checkout Session and set the order data is disconnected from the point at which you render your success page with the PaymentSuccessView class. Just because those two pieces of code are in the same file does not mean the state will be maintained between different requests.\nWhat you can do instead is add the order information to the Checkout Session using metadata. Then when you retrieve the Checkout Session on your success page you can read the metadata from the Checkout Session to get the associated information.\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0074489504_django_django_models_django_templates_django_views_python.txt
Q: Why does Python allow a module to import itself? In a simple Program in BugTest.py: from BugTest import * print("Hello World") note my error in importing BugTest.py from BugTest.py Here is the output: Hello World Hello World My question is: Why doesn't this cause a compile error? Is this a bug in Python? Why does it only import twice, rather than enter an infinite loop? A: Why doesn't this cause a compile error? Because it's completely valid syntax. The only error (absent a problem in the Python runtime itself, such as running out of memory or failing to find the source code) that can occur at compile time in Python is SyntaxError. Names are only resolved at runtime. That said, it's also completely valid at runtime. Why does it only import twice, rather than enter an infinite loop? from BugTest import * means - roughly - "look for an existing module named BugTest; if not found, find and load BugTest.py, create a module object from it named BugTest, and put it in the module cache. Then, copy all the names from the BugTest module into the current module (overwriting any existing names)." When you run the program, Python creates a module object from the BugTest.py code, and (very usefully) gives it the special name __main__. Then it runs the top-level code, triggering the import statement. Now it creates another module object from the BugTest.py code, giving it the usual name of BugTest. That module's top-level code runs as well; but when it tries to import, a BugTest module is already in the module cache. A: You executed $ python BugTest.py which asked for two statements to run, an import and a print. The pair of statements ran exactly once. The first statement performed an import, which has the side effect of printing a line. Then the second statement, a print, printed a line as requested. Everything happened according to plan. It is usually considered undesirable for an import to have side effects such as print(). In this case, of course, it makes perfectly good sense during debugging. Once imported, a module appears in a hash table and will not be re-imported again. So attempting a double import here would not provoke three lines of output. That is, having done (a possibly time consuming) import x, we won't see x imported again. If top-level, or any transitive dependencies imported by top-level, asks for import x, it is simply skipped, as a cache hit.
Why does Python allow a module to import itself?
In a simple Program in BugTest.py: from BugTest import * print("Hello World") note my error in importing BugTest.py from BugTest.py Here is the output: Hello World Hello World My question is: Why doesn't this cause a compile error? Is this a bug in Python? Why does it only import twice, rather than enter an infinite loop?
[ "\nWhy doesn't this cause a compile error?\n\nBecause it's completely valid syntax. The only error (absent a problem in the Python runtime itself, such as running out of memory or failing to find the source code) that can occur at compile time in Python is SyntaxError. Names are only resolved at runtime.\nThat said, it's also completely valid at runtime.\n\nWhy does it only import twice, rather than enter an infinite loop?\n\nfrom BugTest import * means - roughly - \"look for an existing module named BugTest; if not found, find and load BugTest.py, create a module object from it named BugTest, and put it in the module cache. Then, copy all the names from the BugTest module into the current module (overwriting any existing names).\"\nWhen you run the program, Python creates a module object from the BugTest.py code, and (very usefully) gives it the special name __main__. Then it runs the top-level code, triggering the import statement. Now it creates another module object from the BugTest.py code, giving it the usual name of BugTest. That module's top-level code runs as well; but when it tries to import, a BugTest module is already in the module cache.\n", "You executed\n$ python BugTest.py\n\nwhich asked for two statements to run,\nan import and a print.\nThe pair of statements ran exactly once.\nThe first statement performed an import,\nwhich has the side effect of printing a line.\nThen the second statement, a print,\nprinted a line as requested.\nEverything happened according to plan.\n\nIt is usually considered undesirable for\nan import to have side effects\nsuch as print().\nIn this case, of course,\nit makes perfectly good sense\nduring debugging.\n\nOnce imported,\na module appears in a hash table\nand will not be re-imported again.\nSo attempting a double import\nhere would not provoke three lines of output.\nThat is, having done (a possibly time\nconsuming) import x,\nwe won't see x imported again.\nIf top-level, or any transitive\ndependencies imported by top-level,\nasks for import x, it is simply\nskipped, as a cache hit.\n" ]
[ 4, 2 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0074496200_python_python_import.txt
Q: Tesseract doesn't recognize certain pictures. Python Tesseract works fine when I use other pictures but whenever I use this picture it doesn't recognize the picture. Can someone explain me why please? import cv2 import pytesseract import time import random from pynput.keyboard import Controller keyboard = Controller() # Create the controller pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' img = cv2.imread("capture5.png") #img = cv2.resize(img, (300, 300)) cv2.imshow("capture5", img) text = pytesseract.image_to_string(img) print(text) cv2.waitKey(0) cv2.destroyAllWindows() A: I fixed my problem, all I needed to do was add this code to my script. text = pytesseract.image_to_string( img, config=("-c tessedit" "_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ" " --psm 10" " "))
Tesseract doesn't recognize certain pictures. Python
Tesseract works fine when I use other pictures but whenever I use this picture it doesn't recognize the picture. Can someone explain me why please? import cv2 import pytesseract import time import random from pynput.keyboard import Controller keyboard = Controller() # Create the controller pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' img = cv2.imread("capture5.png") #img = cv2.resize(img, (300, 300)) cv2.imshow("capture5", img) text = pytesseract.image_to_string(img) print(text) cv2.waitKey(0) cv2.destroyAllWindows()
[ "I fixed my problem, all I needed to do was add this code to my script.\ntext = pytesseract.image_to_string(\n img, config=(\"-c tessedit\"\n \"_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \" --psm 10\"\n \" \"))\n\n" ]
[ 0 ]
[]
[]
[ "ocr", "python", "tesseract" ]
stackoverflow_0074495663_ocr_python_tesseract.txt
Q: Recursive function that filter names (python) I need to define a recursive function that takes two parameters (a list with names and an initial), and returns a new list with all the names that start with the initial. Right now I have got this code, and i don't know why it doesn't work: def filter_names(names, initial): result = [] if names[0][0] == initial: result.append(names[0]) else: filter_names(names[1:], initial) return result A: Your recursive call isn't appending to the same result that's defined in the outer scope. Usually in a recursive function you combine the result of your recursive call with whatever work you've done in the current frame. In this case that might look like this: def filter_names(names, initial): if not names: return [] return ( [names[0]] if names[0][0] == initial else [] ) + filter_names([1:], initial) A: I'm going to say that this is not a good use of recursion, but you have some misconception about how to go about it: def filter_name(names, initial) -> list[str]: if 0 == len(names): # base case return [] else: # iterative case head = names[0] # The first element tail = names[1:] # Everything else tail_names = filter_name(tail, initial) # Get the result of the recursive call on 'everything else' if head[0] == initial: # Decide if the first element should change your result tail_names.append(head) # If so, modify your result return tail_names # Return it For recursion you need to define a base case and an iterative step. The iterative step should call the function again, with a smaller input. Then it should add (any necessary) change into the returned result before returning it. This code is unnecessarily explicit - there are more concise ways to do it, but it illustrates what is going on. The base case is that you have an empty list of names. You know what should be returned in this case - an empty list. The iterative case should first figure out what the next-smallest version of the problem is. Here, it is a list that is one shorter, tail. First get the result of recursing with that new, shorter input. With that result, you then take the difference - in this case head and decide if you need to modify the result. After that, you return that result. That said, there is a far easier, efficient and idiomatic way to do this in python: result = [name for name in names if name[0] == initial]
Recursive function that filter names (python)
I need to define a recursive function that takes two parameters (a list with names and an initial), and returns a new list with all the names that start with the initial. Right now I have got this code, and i don't know why it doesn't work: def filter_names(names, initial): result = [] if names[0][0] == initial: result.append(names[0]) else: filter_names(names[1:], initial) return result
[ "Your recursive call isn't appending to the same result that's defined in the outer scope.\nUsually in a recursive function you combine the result of your recursive call with whatever work you've done in the current frame. In this case that might look like this:\ndef filter_names(names, initial):\n if not names:\n return []\n return (\n [names[0]] if names[0][0] == initial else []\n ) + filter_names([1:], initial)\n\n", "I'm going to say that this is not a good use of recursion, but you have some misconception about how to go about it:\ndef filter_name(names, initial) -> list[str]:\n if 0 == len(names): # base case\n return [] \n else: # iterative case\n head = names[0] # The first element\n tail = names[1:] # Everything else\n tail_names = filter_name(tail, initial) # Get the result of the recursive call on 'everything else'\n if head[0] == initial: # Decide if the first element should change your result\n tail_names.append(head) # If so, modify your result\n return tail_names # Return it\n\nFor recursion you need to define a base case and an iterative step. The iterative step should call the function again, with a smaller input. Then it should add (any necessary) change into the returned result before returning it.\nThis code is unnecessarily explicit - there are more concise ways to do it, but it illustrates what is going on.\nThe base case is that you have an empty list of names. You know what should be returned in this case - an empty list.\nThe iterative case should first figure out what the next-smallest version of the problem is. Here, it is a list that is one shorter, tail. First get the result of recursing with that new, shorter input. With that result, you then take the difference - in this case head and decide if you need to modify the result. After that, you return that result.\nThat said, there is a far easier, efficient and idiomatic way to do this in python:\nresult = [name for name in names if name[0] == initial]\n\n" ]
[ 1, 0 ]
[]
[]
[ "function", "python", "recursion" ]
stackoverflow_0074496273_function_python_recursion.txt
Q: Recursive python function that checks if a string represents the" relief of a landscape" I'm trying to build a recursive function to represent the relief of a landscape using a string. The string can have a random length but only contains '\' '/' '_' '¯'. For example: If I give (/¯\/\__/¯¯\/\_/\__) it should return True. If the string is empty, it's also valid. It's not valid if there's a discontinuity between consecutive characters, for example, ¯\¯\ or ¯ is not valid. Examples: print(isLandscape(' ')) -------- True print(isLandscape('_')) -------- True print(isLandscape('_/\_')) -------- True print(isLandscape('/¯\/\__/\_/¯\_')) -------- True print(isLandscape('_/_/¯_/¯¯')) -------- False print(isLandscape('_/¯\_\_')) -------- False I tried to build it with a buch of if statments. It worked, but it was chunky and not recursive. Any help will be highly appreciated A: You want a datastructure like this: level = { "_": (0, 0), # initial level, final level "¯": (1, 1), "/": (0, 1), r"\": (1, 0), } Now it's just a matter of iterating through characters and looking up the levels. Verify that final level of character i is identical to initial level of character i + 1.
Recursive python function that checks if a string represents the" relief of a landscape"
I'm trying to build a recursive function to represent the relief of a landscape using a string. The string can have a random length but only contains '\' '/' '_' '¯'. For example: If I give (/¯\/\__/¯¯\/\_/\__) it should return True. If the string is empty, it's also valid. It's not valid if there's a discontinuity between consecutive characters, for example, ¯\¯\ or ¯ is not valid. Examples: print(isLandscape(' ')) -------- True print(isLandscape('_')) -------- True print(isLandscape('_/\_')) -------- True print(isLandscape('/¯\/\__/\_/¯\_')) -------- True print(isLandscape('_/_/¯_/¯¯')) -------- False print(isLandscape('_/¯\_\_')) -------- False I tried to build it with a buch of if statments. It worked, but it was chunky and not recursive. Any help will be highly appreciated
[ "You want a datastructure like this:\nlevel = {\n \"_\": (0, 0), # initial level, final level\n \"¯\": (1, 1),\n \"/\": (0, 1),\n r\"\\\": (1, 0),\n}\n\nNow it's just a matter of iterating through\ncharacters and looking up the levels.\nVerify that final level of character i\nis identical to initial level of character i + 1.\n" ]
[ 0 ]
[]
[]
[ "function", "list", "python", "recursion", "string" ]
stackoverflow_0074495856_function_list_python_recursion_string.txt
Q: No type hint with return values for TypedDict in PyCharm Atm I am starting with the typing library. When I create a wrong dict in-line I will get a typehint that the created dictionary is indeed not correct, and 'type hint': 42 is highlighted. Is it normal that the wrong return value in the function is not highlighted? Which is 'no type hint': 88 in this case. from typing import TypedDict class Test(TypedDict): asdf: str a1: int asdf: Test = {'type hint': 42} def raw_to_prop() -> Test: return {'no type hint': 88} A: I think this question should end up getting closed, but here's what I see in PyCharm 2022.2.3 with a Python 3.10 environment on Windows 10: And: Note that the squigly lines are the result of there not being sufficient empty lines between the function definitions and the rest of the main body code.
No type hint with return values for TypedDict in PyCharm
Atm I am starting with the typing library. When I create a wrong dict in-line I will get a typehint that the created dictionary is indeed not correct, and 'type hint': 42 is highlighted. Is it normal that the wrong return value in the function is not highlighted? Which is 'no type hint': 88 in this case. from typing import TypedDict class Test(TypedDict): asdf: str a1: int asdf: Test = {'type hint': 42} def raw_to_prop() -> Test: return {'no type hint': 88}
[ "I think this question should end up getting closed, but here's what I see in PyCharm 2022.2.3 with a Python 3.10 environment on Windows 10:\n\nAnd:\n\nNote that the squigly lines are the result of there not being sufficient empty lines between the function definitions and the rest of the main body code.\n" ]
[ 1 ]
[]
[]
[ "pycharm", "python", "python_typing" ]
stackoverflow_0074495944_pycharm_python_python_typing.txt
Q: Numpy masking in 3 channel array The following Snippet will create a test image # Create 3x3x3 image test_image = [] for i in range(9): if i < 6: image.append([255, 22, 96]) else: image.append([255, 0, 0]) Out: array([[[255, 22, 96], [255, 22, 96], [255, 22, 96]], [[255, 22, 96], [255, 22, 96], [255, 22, 96]], [[255, 0, 0], [255, 0, 0], [255, 0, 0]]], dtype=int32) My goal is to create a single-channel image of zeros BUT for every [255, 22, 96] in test_image, I want to set the number 100 in the new single_channel image: I tried the following: test_image = np.array(test_image) height, width, channels = test_image.shape single_channel_img = np.zeros(test_image.shape, dtype=int) msk = test_image == [255, 22, 96] # DOES NOT WORK AS EXPECTED single_channel_img[msk] = 100 Which does not work because the result of the masking: msk = test_image == [255, 22, 96] returns: array([[[ True, True, True], [ True, True, True], [ True, True, True]], [[ True, True, True], [ True, True, True], [ True, True, True]], [[ True, False, False], [ True, False, False], [ True, False, False]]]) Why does the masking return True for the last 3 Pixel and how can I make sure that that comparison returns True only if all 3 Values are the same? My assumption was that the way I mask should just return True when all 3 RGB values are equal to [255, 22, 96]. A: You can convert msk to a 3-D array using array broadcasting: https://numpy.org/doc/stable/user/basics.broadcasting.html The command .reshape can be used to change the dimensions of an array. Numpy will automatically fill out the "thin" dimension. So for example,comparing arrays with shapes (n,n,3) and(1,1,3) is the same as comparing each sub-array test_image[i,j,:] with the target (1,1,3). import numpy as np # Create 3x3x3 image test_image = [] for i in range(9): if i < 6: test_image.append([255, 22, 96]) else: test_image.append([255, 0, 0]) test_image = np.array(test_image).reshape((3,3,3)) # test image shape needed to be fixed single_channel_img = np.zeros(test_image.shape, dtype=int) msk = test_image == np.array([255,22,96]).reshape((1,1,3)) # now it works single_channel_img[msk] = 100 print(single_channel_img) # [[[100 100 100] # [100 100 100] # [100 100 100]] # # [[100 100 100] # [100 100 100] # [100 100 100]] # # [[100 0 0] # [100 0 0] # [100 0 0]]] PS. PyTorch also has array broadcasting, it is really useful in deep learning.
Numpy masking in 3 channel array
The following Snippet will create a test image # Create 3x3x3 image test_image = [] for i in range(9): if i < 6: image.append([255, 22, 96]) else: image.append([255, 0, 0]) Out: array([[[255, 22, 96], [255, 22, 96], [255, 22, 96]], [[255, 22, 96], [255, 22, 96], [255, 22, 96]], [[255, 0, 0], [255, 0, 0], [255, 0, 0]]], dtype=int32) My goal is to create a single-channel image of zeros BUT for every [255, 22, 96] in test_image, I want to set the number 100 in the new single_channel image: I tried the following: test_image = np.array(test_image) height, width, channels = test_image.shape single_channel_img = np.zeros(test_image.shape, dtype=int) msk = test_image == [255, 22, 96] # DOES NOT WORK AS EXPECTED single_channel_img[msk] = 100 Which does not work because the result of the masking: msk = test_image == [255, 22, 96] returns: array([[[ True, True, True], [ True, True, True], [ True, True, True]], [[ True, True, True], [ True, True, True], [ True, True, True]], [[ True, False, False], [ True, False, False], [ True, False, False]]]) Why does the masking return True for the last 3 Pixel and how can I make sure that that comparison returns True only if all 3 Values are the same? My assumption was that the way I mask should just return True when all 3 RGB values are equal to [255, 22, 96].
[ "You can convert msk to a 3-D array using array broadcasting:\nhttps://numpy.org/doc/stable/user/basics.broadcasting.html\nThe command .reshape can be used to change the dimensions of an array. Numpy will automatically fill out the \"thin\" dimension. So for example,comparing arrays with shapes (n,n,3) and(1,1,3) is the same as comparing each sub-array test_image[i,j,:] with the target (1,1,3).\nimport numpy as np\n\n# Create 3x3x3 image\ntest_image = []\nfor i in range(9):\n if i < 6:\n test_image.append([255, 22, 96])\n else:\n test_image.append([255, 0, 0])\n\ntest_image = np.array(test_image).reshape((3,3,3)) # test image shape needed to be fixed\nsingle_channel_img = np.zeros(test_image.shape, dtype=int)\n\nmsk = test_image == np.array([255,22,96]).reshape((1,1,3)) # now it works\nsingle_channel_img[msk] = 100\n\nprint(single_channel_img)\n# [[[100 100 100]\n# [100 100 100]\n# [100 100 100]]\n# \n# [[100 100 100]\n# [100 100 100]\n# [100 100 100]]\n# \n# [[100 0 0]\n# [100 0 0]\n# [100 0 0]]]\n\n\nPS. PyTorch also has array broadcasting, it is really useful in deep learning.\n" ]
[ 1 ]
[]
[]
[ "image", "numpy", "opencv", "python", "rgb" ]
stackoverflow_0074496375_image_numpy_opencv_python_rgb.txt
Q: how to convert text file data to python dictionary I have seen quite a few questions like this however none like mine specific separation of items with newlines. text file: John City: New york Job: surgeon Happy: no Terry City: Miami House: Yes Job: nurse Married: No Joe City: LA Married: No Job: None Dictionary should have separate items which are determined by the blank line in the text document, and the format stays the same like= 'key': 'value' but there isnt a predetermined set amount per item of the dict. could be 4 items like joe or three like john. So far i have: with open(file.txt) as file: id = {} for line in file: if line is not '\n' k,v = line.strip().split(': ', 1) id[k] = v.strip() print(id) I know this is incorrect and the previous quides have been no help when dealing with newlines. I expect it to look like: { "John": { "City": "new york", "Job": "surgeon", "Happy": "no" }, "Terry": { "City": "Miami", "House": "Yes", "Job": "nurse", "Married": "No" }, "Joe": { "City": "LA", "Married": "No", "Job": "None" } } A: Try: text = """\ John City: New york Job: surgeon Happy: no Terry City: Miami House: Yes Job: nurse Married: No Joe City: LA Married: No Job: None""" out = {} for group in text.split("\n\n"): lines = group.split("\n") out[lines[0]] = dict(l.split(": ") for l in lines[1:]) print(out) Prints: { "John": {"City": "New york", "Job": "surgeon", "Happy": "no"}, "Terry": {"City": "Miami", "House": "Yes", "Job": "nurse", "Married": "No"}, "Joe": {"City": "LA", "Married": "No", "Job": "None"}, } EDIT: To read the text from a file: with open("your_file.txt", "r") as f_in: text = f_in.read().strip() out = {} for group in text.split("\n\n"): lines = group.split("\n") out[lines[0]] = dict(l.split(": ") for l in lines[1:]) print(out) EDIT 2: If your file contains: City: New york Job: surgeon Happy: no City: Miami House: Yes Job: nurse Married: No City: LA Married: No Job: None then: with open("your_file.txt", "r") as f_in: text = f_in.read().strip() out = [] for group in text.split("\n\n"): lines = group.split("\n") out.append(dict(l.split(": ") for l in lines)) print(out) prints: [ {"City": "New york", "Job": "surgeon", "Happy": "no"}, {"City": "Miami", "House": "Yes", "Job": "nurse", "Married": "No"}, {"City": "LA", "Married": "No", "Job": "None"}, ]
how to convert text file data to python dictionary
I have seen quite a few questions like this however none like mine specific separation of items with newlines. text file: John City: New york Job: surgeon Happy: no Terry City: Miami House: Yes Job: nurse Married: No Joe City: LA Married: No Job: None Dictionary should have separate items which are determined by the blank line in the text document, and the format stays the same like= 'key': 'value' but there isnt a predetermined set amount per item of the dict. could be 4 items like joe or three like john. So far i have: with open(file.txt) as file: id = {} for line in file: if line is not '\n' k,v = line.strip().split(': ', 1) id[k] = v.strip() print(id) I know this is incorrect and the previous quides have been no help when dealing with newlines. I expect it to look like: { "John": { "City": "new york", "Job": "surgeon", "Happy": "no" }, "Terry": { "City": "Miami", "House": "Yes", "Job": "nurse", "Married": "No" }, "Joe": { "City": "LA", "Married": "No", "Job": "None" } }
[ "Try:\ntext = \"\"\"\\\nJohn\nCity: New york\nJob: surgeon\nHappy: no\n\nTerry\nCity: Miami\nHouse: Yes\nJob: nurse\nMarried: No\n\nJoe\nCity: LA\nMarried: No\nJob: None\"\"\"\n\nout = {}\nfor group in text.split(\"\\n\\n\"):\n lines = group.split(\"\\n\")\n out[lines[0]] = dict(l.split(\": \") for l in lines[1:])\n\nprint(out)\n\nPrints:\n{\n \"John\": {\"City\": \"New york\", \"Job\": \"surgeon\", \"Happy\": \"no\"},\n \"Terry\": {\"City\": \"Miami\", \"House\": \"Yes\", \"Job\": \"nurse\", \"Married\": \"No\"},\n \"Joe\": {\"City\": \"LA\", \"Married\": \"No\", \"Job\": \"None\"},\n}\n\n\nEDIT: To read the text from a file:\nwith open(\"your_file.txt\", \"r\") as f_in:\n text = f_in.read().strip()\n\nout = {}\nfor group in text.split(\"\\n\\n\"):\n lines = group.split(\"\\n\")\n out[lines[0]] = dict(l.split(\": \") for l in lines[1:])\n\nprint(out)\n\n\nEDIT 2:\nIf your file contains:\nCity: New york\nJob: surgeon\nHappy: no\n\nCity: Miami\nHouse: Yes\nJob: nurse\nMarried: No\n\nCity: LA\nMarried: No\nJob: None\n\nthen:\nwith open(\"your_file.txt\", \"r\") as f_in:\n text = f_in.read().strip()\n\nout = []\nfor group in text.split(\"\\n\\n\"):\n lines = group.split(\"\\n\")\n out.append(dict(l.split(\": \") for l in lines))\n\nprint(out)\n\nprints:\n[\n {\"City\": \"New york\", \"Job\": \"surgeon\", \"Happy\": \"no\"},\n {\"City\": \"Miami\", \"House\": \"Yes\", \"Job\": \"nurse\", \"Married\": \"No\"},\n {\"City\": \"LA\", \"Married\": \"No\", \"Job\": \"None\"},\n]\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "list", "python", "python_3.x" ]
stackoverflow_0074496420_dictionary_list_python_python_3.x.txt
Q: PYTHONPATH works in interactive mode but fails in script Problem I've been trying to run a python script which imports from the Foundation package: from Foundation import ... Whenever I try to run this I get the following error: Things I've done: I've installed the Foundation package and verified that it was installed in /usr/local/lib/python3.7/site-packages I've added export PYTHONPATH='/usr/local/lib/python3.7/site-packages' to my .zshrc file. When I go into interactive mode, sys.path includes /usr/local/lib/python3.7/site-packages and I can successfully import Foundation: When I run the script using /usr/local/bin/python3.7, sys.path does not include /usr/local/lib/python3.7/site-packages and importing Foundation fails: Does anyone know why this might be happening and/or how to fix this? Why does running this script have a different sys.path than running the same python executable in interactive mode? (I know I could use sys.path.extend(desired path) or something like that but that's not an ideal solution) A: First, you run Python as your user (say ~joe or whatever your UID is) but then you bring sudo to the table. And that's where things starts to differ, because it will not inherit your environment. Simple test for you to replay (substitute python3 by whatever path/version you want): $ python3 >>> import sys >>> sys.path ['', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.10/dist-packages', '/home/<USER>/.local/lib/python3.10/site-packages'] then the same but with sudo: $ sudo python3 >>> import sys >>> sys.path ['', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.10/dist-packages'] To work this around you either need to ensure your superuser's environment fits your needs or you feed python interpreter with needed value of PYTHONPATH on the fly: $ sudo PYTHONPATH=/FOO/BAR python3 >>> import sys >>> sys.path ['', '/FOO/BAR', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.10/dist-packages']
PYTHONPATH works in interactive mode but fails in script
Problem I've been trying to run a python script which imports from the Foundation package: from Foundation import ... Whenever I try to run this I get the following error: Things I've done: I've installed the Foundation package and verified that it was installed in /usr/local/lib/python3.7/site-packages I've added export PYTHONPATH='/usr/local/lib/python3.7/site-packages' to my .zshrc file. When I go into interactive mode, sys.path includes /usr/local/lib/python3.7/site-packages and I can successfully import Foundation: When I run the script using /usr/local/bin/python3.7, sys.path does not include /usr/local/lib/python3.7/site-packages and importing Foundation fails: Does anyone know why this might be happening and/or how to fix this? Why does running this script have a different sys.path than running the same python executable in interactive mode? (I know I could use sys.path.extend(desired path) or something like that but that's not an ideal solution)
[ "First, you run Python as your user (say ~joe or whatever your UID is) but then you bring sudo to the table. And that's where things starts to differ, because it will not inherit your environment. Simple test for you to replay (substitute python3 by whatever path/version you want):\n$ python3\n>>> import sys\n>>> sys.path\n['', '/usr/lib/python310.zip', '/usr/lib/python3.10', \n'/usr/lib/python3.10/lib-dynload', '/usr/lib/python3/dist-packages', \n'/usr/local/lib/python3.10/dist-packages', \n'/home/<USER>/.local/lib/python3.10/site-packages']\n\nthen the same but with sudo:\n$ sudo python3\n>>> import sys\n>>> sys.path\n['', '/usr/lib/python310.zip', '/usr/lib/python3.10', \n'/usr/lib/python3.10/lib-dynload', '/usr/lib/python3/dist-packages', \n'/usr/local/lib/python3.10/dist-packages']\n\nTo work this around you either need to ensure your superuser's environment fits your needs or you feed python interpreter with needed value of PYTHONPATH on the fly:\n$ sudo PYTHONPATH=/FOO/BAR python3\n>>> import sys\n>>> sys.path\n['', '/FOO/BAR', '/usr/lib/python310.zip', '/usr/lib/python3.10', \n'/usr/lib/python3.10/lib-dynload', '/usr/lib/python3/dist-packages', \n'/usr/local/lib/python3.10/dist-packages']\n\n" ]
[ 1 ]
[]
[]
[ "python", "pythonpath", "sys.path" ]
stackoverflow_0074496416_python_pythonpath_sys.path.txt
Q: Remove a value of a data frame based on a condition between columns I have this df with 9 columns x y1_x y2_x y3_x y4_x 0 -17.7 -0.785430 NaN NaN NaN 1 -15.0 NaN NaN NaN -3820.085000 2 -12.5 NaN NaN 2.138833 NaN 3 -12.4 NaN NaN 1.721205 NaN 4 -12.1 NaN 2.227343 2.227343 NaN d1 d2 d3 d4 0 0.053884 NaN NaN NaN 1 NaN NaN NaN 0.085000 2 NaN NaN 0.143237 NaN 3 NaN NaN 0.251180 NaN 4 NaN 0.127343 0.440931 NaN Between y1_x and y4_x I can only have 1 non NaN value per row. The condition to choose which value is removed is explained in this example: In row 4 there are 2 values between y1_x and y4_x The value that becomes NaN is the one from y3_x because in that same row, d3 > d2 A: you can use: #get count of nans between ('y1_x', 'y2_x', 'y3_x', 'y4_x', 'd1', 'd2', 'd3', 'd4') final['mask']=final.iloc[:,1:5].isna().sum(axis=1) #if the mask is 2, it means it will be filled with nan. count=len(final[final['mask']==2]) #We enter the loop as many as the number of rows with a mask value of 2. for i in range(0,count): mask=final[final['mask']==2].iloc[[i]] #get nth row #get columns (('y1_x', 'y2_x', 'y3_x', 'y4_x', 'd1', 'd2', 'd3', 'd4')) and drop nans abc=mask[mask['mask']==2].iloc[:,1:8].dropna(axis=1,how='all') to_replace_col_name=abc.iloc[:,2:4].max(axis=0).reset_index()['index'][1] #which column is bigger ? #Once we know the name of the big column, the 2 columns before this column is the one we will change. replace_col=abc.columns.get_loc(to_replace_col_name) replace_col=abc.columns[replace_col - 2] #now we know which column to change mask[replace_col]=np.nan final.loc[mask.index,:]=mask #replace row according to index name print(final) ''' x y1_x y2_x y3_x ... d2 d3 d4 mask 0 -17.7 -0.78543 NaN NaN ... NaN NaN NaN 3 1 -15.0 NaN NaN NaN ... NaN NaN 0.085 3 2 -12.5 NaN NaN 2.138833 ... NaN 0.143237 NaN 3 3 -12.4 NaN NaN 1.721205 ... NaN 0.251180 NaN 3 4 -12.1 NaN 2.227343 NaN ... 0.127343 0.440931 NaN 2 ''' A: Another possible solution: auxd = df.filter(like='d') auxy = df.filter(like='y') auxd.columns = auxy.columns colmin = auxd.idxmin(axis=1) df[auxy.columns] = auxy.apply(lambda x: x.where(colmin.eq(x.name))) Output: x y1_x y2_x y3_x y4_x d1 d2 d3 d4 0 -17.7 -0.78543 NaN NaN NaN 0.053884 NaN NaN NaN 1 -15.0 NaN NaN NaN -3820.085 NaN NaN NaN 0.085 2 -12.5 NaN NaN 2.138833 NaN NaN NaN 0.143237 NaN 3 -12.4 NaN NaN 1.721205 NaN NaN NaN 0.251180 NaN 4 -12.1 NaN 2.227343 NaN NaN NaN 0.127343 0.440931 NaN
Remove a value of a data frame based on a condition between columns
I have this df with 9 columns x y1_x y2_x y3_x y4_x 0 -17.7 -0.785430 NaN NaN NaN 1 -15.0 NaN NaN NaN -3820.085000 2 -12.5 NaN NaN 2.138833 NaN 3 -12.4 NaN NaN 1.721205 NaN 4 -12.1 NaN 2.227343 2.227343 NaN d1 d2 d3 d4 0 0.053884 NaN NaN NaN 1 NaN NaN NaN 0.085000 2 NaN NaN 0.143237 NaN 3 NaN NaN 0.251180 NaN 4 NaN 0.127343 0.440931 NaN Between y1_x and y4_x I can only have 1 non NaN value per row. The condition to choose which value is removed is explained in this example: In row 4 there are 2 values between y1_x and y4_x The value that becomes NaN is the one from y3_x because in that same row, d3 > d2
[ "you can use:\n#get count of nans between ('y1_x', 'y2_x', 'y3_x', 'y4_x', 'd1', 'd2', 'd3', 'd4')\nfinal['mask']=final.iloc[:,1:5].isna().sum(axis=1)\n\n#if the mask is 2, it means it will be filled with nan.\ncount=len(final[final['mask']==2])\n\n#We enter the loop as many as the number of rows with a mask value of 2.\nfor i in range(0,count):\n mask=final[final['mask']==2].iloc[[i]] #get nth row\n\n #get columns (('y1_x', 'y2_x', 'y3_x', 'y4_x', 'd1', 'd2', 'd3', 'd4')) and drop nans\n abc=mask[mask['mask']==2].iloc[:,1:8].dropna(axis=1,how='all')\n to_replace_col_name=abc.iloc[:,2:4].max(axis=0).reset_index()['index'][1] #which column is bigger ?\n\n #Once we know the name of the big column, the 2 columns before this column is the one we will change.\n\n replace_col=abc.columns.get_loc(to_replace_col_name) \n replace_col=abc.columns[replace_col - 2]\n\n #now we know which column to change\n mask[replace_col]=np.nan\n final.loc[mask.index,:]=mask #replace row according to index name\n\nprint(final)\n'''\n x y1_x y2_x y3_x ... d2 d3 d4 mask\n0 -17.7 -0.78543 NaN NaN ... NaN NaN NaN 3\n1 -15.0 NaN NaN NaN ... NaN NaN 0.085 3\n2 -12.5 NaN NaN 2.138833 ... NaN 0.143237 NaN 3\n3 -12.4 NaN NaN 1.721205 ... NaN 0.251180 NaN 3\n4 -12.1 NaN 2.227343 NaN ... 0.127343 0.440931 NaN 2\n\n'''\n\n", "Another possible solution:\nauxd = df.filter(like='d')\nauxy = df.filter(like='y')\nauxd.columns = auxy.columns\ncolmin = auxd.idxmin(axis=1)\n\ndf[auxy.columns] = auxy.apply(lambda x: x.where(colmin.eq(x.name)))\n\nOutput:\n x y1_x y2_x y3_x y4_x d1 d2 d3 d4\n0 -17.7 -0.78543 NaN NaN NaN 0.053884 NaN NaN NaN\n1 -15.0 NaN NaN NaN -3820.085 NaN NaN NaN 0.085\n2 -12.5 NaN NaN 2.138833 NaN NaN NaN 0.143237 NaN\n3 -12.4 NaN NaN 1.721205 NaN NaN NaN 0.251180 NaN\n4 -12.1 NaN 2.227343 NaN NaN NaN 0.127343 0.440931 NaN\n\n" ]
[ 2, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074495116_dataframe_pandas_python.txt
Q: Problems filtering columns that have many rows with a None value(Django database) I am filtering a certain column in PostgreSQL database. n = Database.objects.values(column).count() for i in range(0, n): name = list(Database.objects.all().values_list(column, flat=True))[i] There are 105 lines. From line 86 onwards the values are None. However, when querying line 43, the returned value is None, although in the database this line is filled with a value. Strangely, when I populate lines 86 onwards, the query on line 43 is correct and does not return a None value. I want to know if there is any problem when filtering columns that have many None values and why this might be happening A: I want to know if there is any problem when filtering columns that have many None values No, there is no problem with that. A relational database contains sets of rows, named "tables". Sets are unordered. Yet you speak of values starting at this or that offset, as though we had a list of values where order matters. I recommend that you order your result rows so they appear in a reproducible sequence. Use ORDER BY with the database, and sorted( ... ) for python expressions.
Problems filtering columns that have many rows with a None value(Django database)
I am filtering a certain column in PostgreSQL database. n = Database.objects.values(column).count() for i in range(0, n): name = list(Database.objects.all().values_list(column, flat=True))[i] There are 105 lines. From line 86 onwards the values are None. However, when querying line 43, the returned value is None, although in the database this line is filled with a value. Strangely, when I populate lines 86 onwards, the query on line 43 is correct and does not return a None value. I want to know if there is any problem when filtering columns that have many None values and why this might be happening
[ "\nI want to know if there is any problem when filtering columns that have many None values\n\nNo, there is no problem with that.\n\nA relational database contains sets of rows,\nnamed \"tables\".\nSets are unordered. Yet you speak of values\nstarting at this or that offset, as though\nwe had a list of values where order matters.\nI recommend that you order your result rows\nso they appear in a reproducible sequence.\nUse ORDER BY with the database,\nand sorted( ... ) for python expressions.\n" ]
[ 1 ]
[]
[]
[ "django", "django_database", "python" ]
stackoverflow_0074496489_django_django_database_python.txt
Q: Finding a Sum of Series in Python Write a python program that calculate the sum of the series: (1,2,9,28, ... , 1000001). The sum of that series is represented using the equation below. Find the value of y and print it. I can't figure it out A: Since you haven't provided the equation, I'm just going to give general advice. If we imagine that our education is: x*2 {from 0 to 20}, we can use a list and the sum() function to solve it. result = sum([x*2 for x in range(0,21)])
Finding a Sum of Series in Python
Write a python program that calculate the sum of the series: (1,2,9,28, ... , 1000001). The sum of that series is represented using the equation below. Find the value of y and print it. I can't figure it out
[ "Since you haven't provided the equation, I'm just going to give general advice.\nIf we imagine that our education is: x*2 {from 0 to 20}, we can use a list and the sum() function to solve it.\nresult = sum([x*2 for x in range(0,21)])\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074496247_python.txt
Q: Adding another argument to my discord.py command I'm trying to add an additional argument to this mute command I have made for my discord.py bot but I'm getting a SyntaxError and have been having trouble understanding the syntax for what I'm trying to do. Here is the part of my program that is relevant to my issue: #Tempmute Command @bot.command(name='tempmute') @commands.has_role('Moderator' or 'Admin') async def mute(ctx, member: discord.Member,time): #Retrieves the amount of time the user should be muted for muted_role=discord.utils.get(ctx.guild.roles, name="Muted") time_convert = {"s":1, "m":60, "h":3600,"d":86400} tempmute= int(time[0]) * time_convert[time[-1]] #Deletes invocation and adds muted role to target, sends embed confirming user has been delete THEN deletes embed await ctx.message.delete() await member.add_roles(muted_role) #Notifies target was muted through sending a direct message notify = discord.Embed(title="Muted", description=f" You have been muted in {member.guild.name}.",colour=discord.Colour.light_gray()) #Catches an exception if the direct message fails to send try: await member.send(notify) except Exception as e: embedFail = discord.Embed(description= f" **{ctx.author.mention}, I was unable to notify this user they were muted**", color=discord.Color.red()) await ctx.send(embed=embedFail, delete_after=5) embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} has been muted successfully", color=discord.Color.green()) await ctx.send(embed=embed, delete_after=5) #Removes role after given time await asyncio.sleep(tempmute) await member.remove_roles(muted_role) This line defines my arguments for my asynchronous function 'mute' async def mute(ctx, member: discord.Member,time): When I try to add an additional argument 'reason' I run into a SyntaxError async def mute(ctx, member: discord.Member,time,reason): I should also note when adding the additional argument, I'm also changing my embedded message the bot displays to add the reason given from the author as well. See this changed line here: embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} has been muted successfully for", reason, color=discord.Color.green()) The error I get is: SyntaxError: positional argument follows keyword argument If someone could please explain why I'm not able to simply add this additional piece to my mute command I would greatly appreciate it. Thank you! Also if you have any additional suggestions for improving the use of this command please feel free leave a comment noting your suggestion as well. (Please take into consideration though I'm new to Python and discord.py so I may need a detailed explanation or example as to what you're suggesting I improve in my code.) A: The error I get is: SyntaxError: positional argument follows keyword argument Rather than: ...muted successfully for", reason, color=... try a simple reason=reason kwarg call: ...muted successfully for", reason=reason, color=... The motivation for this diagnostic is to improve code clarity at the call site. The caller may use "short" positional args f(a, b, c) but then once you start using keywords, you should keep using them so it's clear which value gets substituted for which formal parameter. f(a, b, c, d=4, e=5, f=6, g=g, h=h) A: You have to put color=discord.Color.green() AFTER reason. This is because reason is a positional argument, so if you put it before the color, a named argument, python will get confused. Also, a small side note is that @commands.has_role('Moderator' or 'Admin') is not going to work. or is a boolean operator, so it is used for just True and False. Use @commands.has_any_role('Moderator', 'Admin') to check if they have either the Moderator or Admin role.
Adding another argument to my discord.py command
I'm trying to add an additional argument to this mute command I have made for my discord.py bot but I'm getting a SyntaxError and have been having trouble understanding the syntax for what I'm trying to do. Here is the part of my program that is relevant to my issue: #Tempmute Command @bot.command(name='tempmute') @commands.has_role('Moderator' or 'Admin') async def mute(ctx, member: discord.Member,time): #Retrieves the amount of time the user should be muted for muted_role=discord.utils.get(ctx.guild.roles, name="Muted") time_convert = {"s":1, "m":60, "h":3600,"d":86400} tempmute= int(time[0]) * time_convert[time[-1]] #Deletes invocation and adds muted role to target, sends embed confirming user has been delete THEN deletes embed await ctx.message.delete() await member.add_roles(muted_role) #Notifies target was muted through sending a direct message notify = discord.Embed(title="Muted", description=f" You have been muted in {member.guild.name}.",colour=discord.Colour.light_gray()) #Catches an exception if the direct message fails to send try: await member.send(notify) except Exception as e: embedFail = discord.Embed(description= f" **{ctx.author.mention}, I was unable to notify this user they were muted**", color=discord.Color.red()) await ctx.send(embed=embedFail, delete_after=5) embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} has been muted successfully", color=discord.Color.green()) await ctx.send(embed=embed, delete_after=5) #Removes role after given time await asyncio.sleep(tempmute) await member.remove_roles(muted_role) This line defines my arguments for my asynchronous function 'mute' async def mute(ctx, member: discord.Member,time): When I try to add an additional argument 'reason' I run into a SyntaxError async def mute(ctx, member: discord.Member,time,reason): I should also note when adding the additional argument, I'm also changing my embedded message the bot displays to add the reason given from the author as well. See this changed line here: embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} has been muted successfully for", reason, color=discord.Color.green()) The error I get is: SyntaxError: positional argument follows keyword argument If someone could please explain why I'm not able to simply add this additional piece to my mute command I would greatly appreciate it. Thank you! Also if you have any additional suggestions for improving the use of this command please feel free leave a comment noting your suggestion as well. (Please take into consideration though I'm new to Python and discord.py so I may need a detailed explanation or example as to what you're suggesting I improve in my code.)
[ "\nThe error I get is: SyntaxError: positional argument follows keyword argument\n\nRather than:\n...muted successfully for\", reason, color=...\n\ntry a simple reason=reason kwarg call:\n...muted successfully for\", reason=reason, color=...\n\n\nThe motivation for this diagnostic\nis to improve code clarity at the\ncall site.\nThe caller may use \"short\" positional\nargs\nf(a, b, c)\n\nbut then once you start using keywords,\nyou should keep using them so it's\nclear which value gets substituted\nfor which formal parameter.\nf(a, b, c, d=4, e=5, f=6, g=g, h=h)\n\n", "You have to put color=discord.Color.green() AFTER reason. This is because reason is a positional argument, so if you put it before the color, a named argument, python will get confused.\nAlso, a small side note is that @commands.has_role('Moderator' or 'Admin') is not going to work. or is a boolean operator, so it is used for just True and False. Use @commands.has_any_role('Moderator', 'Admin') to check if they have either the Moderator or Admin role.\n" ]
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074496484_discord_discord.py_python.txt
Q: how to translate javascript child inheritance into python I'm having trouble translating the following JavaScript code into python. My problem is inheriting the parent properties and methods in the ChildNode class by using super.__init__(). In js, you just call super() and get all the props. It doesn't seem to be the same in python. The super function is demanding to have val and key inside the parenthesis but I'm not sure how that would work because Im getting val from the ChildNode.__init__ function JS CODE that does what I want class BinarySearchTree { constructor(val, key) { this.val = val; this.left = null; this.right = null; this.key = key; } insert(val) { const currNode = this; if (val === currNode.val) return null; if (val < currNode.val) { if (!currNode.left) { currNode.left = new ChildNode(val); return this; } else { currNode.left.insert(val); } } if (val > currNode.val) { if (!currNode.right) { currNode.right = new ChildNode(val); return this; } else { currNode.right.insert(val); } } } } class ChildNode extends BinarySearchTree { constructor(val) { super(); this.val = val; delete this.key; } } var root = new BinarySearchTree(20, 14); root.insert(8); root.insert(22); root.insert(4); console.log(root); Python attempt class BinarySearchTree: def __init__(self, val: int, key: int): self.val = val self.left = None self.right = None self.key = key def insert(self, val): currNode = self if val == currNode.val: return None if val < currNode.val: if not currNode.left: currNode.left = ChildNode(val) return self else: currNode.left.insert(val) if val > currNode.val: if not currNode.right: currNode.right = ChildNode(val) return self else: currNode.right.insert(val) # having trouble inheriting here class ChildNode(BinarySearchTree): def __init__(self, val): super().__init__() self.val = val del self.key root = BinarySearchTree(20, 14) root.insert(8) root.insert(22) root.insert(4) print(root) A: The child class's __init__ method needs to pass the appropriate arguments in the super().__init__() call. # having trouble inheriting here class ChildNode(BinarySearchTree): def __init__(self, val: int): super().__init__(val, '') del self.key You don't need to do self.val = val in the child class, since that's done by the parent class. That said, this doesn't seem like an appropriate class hierarchy in either language. You shouldn't delete attributes in the child class, because any inherited methods that depend on it will fail. A: In Javascript if you do not pass parameters to a function it defaults them to being undefined, however, this is not tolerated by Python. If you run your code you will notice you get the following error. Traceback (most recent call last): File "main.py", line 41, in <module> root.insert(8) File "main.py", line 17, in insert currNode.left = ChildNode(val) File "main.py", line 34, in __init__ super().__init__() TypeError: __init__() missing 2 required positional arguments: 'val' and 'key' Which is very helpful because it tells us that the super.__init__() call is missing two arguments, which are defined in the super class. If you intend to replicate the JS behaviour then you would do well to add a default None to the arguments in the constructor of the superclass. class BinarySearchTree: def __init__(self, val: int = None, key: int = None): self.val = val self.left = None self.right = None self.key = key
how to translate javascript child inheritance into python
I'm having trouble translating the following JavaScript code into python. My problem is inheriting the parent properties and methods in the ChildNode class by using super.__init__(). In js, you just call super() and get all the props. It doesn't seem to be the same in python. The super function is demanding to have val and key inside the parenthesis but I'm not sure how that would work because Im getting val from the ChildNode.__init__ function JS CODE that does what I want class BinarySearchTree { constructor(val, key) { this.val = val; this.left = null; this.right = null; this.key = key; } insert(val) { const currNode = this; if (val === currNode.val) return null; if (val < currNode.val) { if (!currNode.left) { currNode.left = new ChildNode(val); return this; } else { currNode.left.insert(val); } } if (val > currNode.val) { if (!currNode.right) { currNode.right = new ChildNode(val); return this; } else { currNode.right.insert(val); } } } } class ChildNode extends BinarySearchTree { constructor(val) { super(); this.val = val; delete this.key; } } var root = new BinarySearchTree(20, 14); root.insert(8); root.insert(22); root.insert(4); console.log(root); Python attempt class BinarySearchTree: def __init__(self, val: int, key: int): self.val = val self.left = None self.right = None self.key = key def insert(self, val): currNode = self if val == currNode.val: return None if val < currNode.val: if not currNode.left: currNode.left = ChildNode(val) return self else: currNode.left.insert(val) if val > currNode.val: if not currNode.right: currNode.right = ChildNode(val) return self else: currNode.right.insert(val) # having trouble inheriting here class ChildNode(BinarySearchTree): def __init__(self, val): super().__init__() self.val = val del self.key root = BinarySearchTree(20, 14) root.insert(8) root.insert(22) root.insert(4) print(root)
[ "The child class's __init__ method needs to pass the appropriate arguments in the super().__init__() call.\n# having trouble inheriting here\nclass ChildNode(BinarySearchTree):\n def __init__(self, val: int):\n super().__init__(val, '')\n\n del self.key\n\nYou don't need to do self.val = val in the child class, since that's done by the parent class.\nThat said, this doesn't seem like an appropriate class hierarchy in either language. You shouldn't delete attributes in the child class, because any inherited methods that depend on it will fail.\n", "In Javascript if you do not pass parameters to a function it defaults them to being undefined, however, this is not tolerated by Python. If you run your code you will notice you get the following error.\nTraceback (most recent call last):\n File \"main.py\", line 41, in <module>\n root.insert(8)\n File \"main.py\", line 17, in insert\n currNode.left = ChildNode(val)\n File \"main.py\", line 34, in __init__\n super().__init__()\nTypeError: __init__() missing 2 required positional arguments: 'val' and 'key'\n\nWhich is very helpful because it tells us that the super.__init__() call is missing two arguments, which are defined in the super class.\nIf you intend to replicate the JS behaviour then you would do well to add a default None to the arguments in the constructor of the superclass.\nclass BinarySearchTree:\n def __init__(self, val: int = None, key: int = None):\n self.val = val\n self.left = None\n self.right = None\n self.key = key\n\n" ]
[ 1, 1 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0074496525_javascript_python.txt
Q: root.iconbitmap() forces tkinter to enter a temporary eventloop? Does wm_iconbitmap method forces tkinter to enter an event loop while it processes the icon file? Is there a way to avoid this? Check this example that illustrates this: from tkinter import * import time root = Tk() root.iconbitmap('images/logo.ico') # Without `mainloop()` shows the window, means the events have started being processed? time.sleep(3) I couldn't find any related info in the documentation either. Thanks in advance :) Edit: A little more research shows that root.iconbitmap() does not enter event loop, maybe because there is no icon to process/check? But that would not answer why root.iconphoto does not enter an event-loop when called A: The eventloop and the created window are different things. In your case it is the window that is forced into existence and is mentioned in the source code as a side effect: Side effects: One or all windows may have their icon changed. The Tcl result may be modified. The window-manager will be initialised if it wasn't already. The given window will be forced into existence. See the source code for details.
root.iconbitmap() forces tkinter to enter a temporary eventloop?
Does wm_iconbitmap method forces tkinter to enter an event loop while it processes the icon file? Is there a way to avoid this? Check this example that illustrates this: from tkinter import * import time root = Tk() root.iconbitmap('images/logo.ico') # Without `mainloop()` shows the window, means the events have started being processed? time.sleep(3) I couldn't find any related info in the documentation either. Thanks in advance :) Edit: A little more research shows that root.iconbitmap() does not enter event loop, maybe because there is no icon to process/check? But that would not answer why root.iconphoto does not enter an event-loop when called
[ "The eventloop and the created window are different things. In your case it is the window that is forced into existence and is mentioned in the source code as a side effect:\n\nSide effects:\nOne or all windows may have their icon changed.\nThe Tcl result may be modified. The window-manager will be\ninitialised if it wasn't already. The given window will be forced\ninto existence.\n\nSee the source code for details.\n" ]
[ 1 ]
[]
[]
[ "event_loop", "python", "tkinter" ]
stackoverflow_0070777760_event_loop_python_tkinter.txt
Q: How can I include the absolute value of a decision variable in PuLP objective function The problem setup is fairly simple. There are 5 available instruments in a portfolio that can be traded. The optimizer needs to figure out which instruments need to be bought and / or sold to make max profit, There are the estimates for price change and some risk constraints. Now as in the real world, there are always transaction costs. These are always positive whether the securities are bought or sold. How do I setup this optimization problem? Below is what I have setup without transaction costs, and I have included the commented line to indicate how the transaction cost would work. from pulp import * import pandas as pd df = pd.DataFrame({ 'instrument':["A", "B", "C", "D", "E"], 'price_change':[-6.09, -3.15, 6.1 , 6.43, 6.48], 'transaction_cost':[0.6, 0.6, 3.0, 6.0, 3.0], 'factor_A':[ 0.28032, -0.20112, 0.55631, -0.73323, -0.54905], 'factor_B':[18.87091, 15.73831, 29.61791, 24.64536, 29.68997] }) prob = LpProblem("The portfolio Problem", LpMaximize) instr_avl = LpVariable.dicts("Instr", df['instrument'].values,lowBound=None, upBound=None, cat= 'Integer') # The objective function prob += (lpSum([instr_avl[i] * df[df['instrument']==i]['price_change'].values[0] # -abs(instr_avl[i]) * df[df['instrument']==i]['spread_cost'].values[0] for i in df['instrument'].values]), "Total Profit") # Factor constraints prob += lpSum([instr_avl[i] * df[df['instrument']==i]['factor_A'].values[0] for i in df['instrument'].values]) == 0, "factor_A Constraint" prob += lpSum([instr_avl[i] * df[df['instrument']==i]['factor_B'].values[0] for i in df['instrument'].values]) <= 1000, "factor_B max Constraint" prob += lpSum([instr_avl[i] * df[df['instrument']==i]['factor_B'].values[0] for i in df['instrument'].values]) >= -1000, "factor_B min Constraint" # The problem is solved using PuLP's choice of Solver prob.solve() for v in prob.variables(): print(v.name, "=", v.varValue, v.lowBound, v.upBound, v.cat) print("Total profit= ", value(prob.objective)) Of course the code does not run if the commented line is uncommented. Would highly appreciate any ideas on how to implement this or any workarounds! A: Introduce a non-negative variable say absv[i]. Add the two constraints: absv[i] >= instr_avl[i] and absv[i] >= -instr_avl[i]. Add the term: -absv[i]*df[df['instrument']==i]['spread_cost'].values[0] to the objective. This type of formulation is described in detail in basically any book on linear programming. You may want to consult one to get a better understanding of this common formulation trick.
How can I include the absolute value of a decision variable in PuLP objective function
The problem setup is fairly simple. There are 5 available instruments in a portfolio that can be traded. The optimizer needs to figure out which instruments need to be bought and / or sold to make max profit, There are the estimates for price change and some risk constraints. Now as in the real world, there are always transaction costs. These are always positive whether the securities are bought or sold. How do I setup this optimization problem? Below is what I have setup without transaction costs, and I have included the commented line to indicate how the transaction cost would work. from pulp import * import pandas as pd df = pd.DataFrame({ 'instrument':["A", "B", "C", "D", "E"], 'price_change':[-6.09, -3.15, 6.1 , 6.43, 6.48], 'transaction_cost':[0.6, 0.6, 3.0, 6.0, 3.0], 'factor_A':[ 0.28032, -0.20112, 0.55631, -0.73323, -0.54905], 'factor_B':[18.87091, 15.73831, 29.61791, 24.64536, 29.68997] }) prob = LpProblem("The portfolio Problem", LpMaximize) instr_avl = LpVariable.dicts("Instr", df['instrument'].values,lowBound=None, upBound=None, cat= 'Integer') # The objective function prob += (lpSum([instr_avl[i] * df[df['instrument']==i]['price_change'].values[0] # -abs(instr_avl[i]) * df[df['instrument']==i]['spread_cost'].values[0] for i in df['instrument'].values]), "Total Profit") # Factor constraints prob += lpSum([instr_avl[i] * df[df['instrument']==i]['factor_A'].values[0] for i in df['instrument'].values]) == 0, "factor_A Constraint" prob += lpSum([instr_avl[i] * df[df['instrument']==i]['factor_B'].values[0] for i in df['instrument'].values]) <= 1000, "factor_B max Constraint" prob += lpSum([instr_avl[i] * df[df['instrument']==i]['factor_B'].values[0] for i in df['instrument'].values]) >= -1000, "factor_B min Constraint" # The problem is solved using PuLP's choice of Solver prob.solve() for v in prob.variables(): print(v.name, "=", v.varValue, v.lowBound, v.upBound, v.cat) print("Total profit= ", value(prob.objective)) Of course the code does not run if the commented line is uncommented. Would highly appreciate any ideas on how to implement this or any workarounds!
[ "\nIntroduce a non-negative variable say absv[i].\nAdd the two constraints: absv[i] >= instr_avl[i] and absv[i] >= -instr_avl[i].\nAdd the term: -absv[i]*df[df['instrument']==i]['spread_cost'].values[0] to the objective.\n\nThis type of formulation is described in detail in basically any book on linear programming. You may want to consult one to get a better understanding of this common formulation trick.\n" ]
[ 1 ]
[]
[]
[ "linear_programming", "optimization", "pulp", "python" ]
stackoverflow_0074496539_linear_programming_optimization_pulp_python.txt
Q: date countdown not working as intended. time keeps printing I have made a script to show the difference between today's date and a date you put in and ended it with the print function and an f string. from datetime import datetime today = datetime.today() print("Please enter the date you want to find out how many days until below: ") year = int(input("What year? ")) month = int(input("What month? ")) day = int(input("What day? ")) date2 = datetime(year, month, day) difference = date2 - today print(f"There are only {difference.days+1} days left until {date2} from {today}") it prints the correct data however it shows the time aswell. so it shows this as an example: "There are only 96 days left until 2023-02-23 00:00:00 from 2022-11-19 00:14:18.003365" how do I remove the time? also if there are any other suggestions on improving this I'm all ears. A: You could use date for this calculation. from datetime import date today = date.today() print("Please enter the date you want to find out how many days until below: ") year = int(input("What year? ")) month = int(input("What month? ")) day = int(input("What day? ")) date2 = date(year, month, day) difference = date2 - today print(f"There are only {difference.days+1} days left until {date2} from {today}")
date countdown not working as intended. time keeps printing
I have made a script to show the difference between today's date and a date you put in and ended it with the print function and an f string. from datetime import datetime today = datetime.today() print("Please enter the date you want to find out how many days until below: ") year = int(input("What year? ")) month = int(input("What month? ")) day = int(input("What day? ")) date2 = datetime(year, month, day) difference = date2 - today print(f"There are only {difference.days+1} days left until {date2} from {today}") it prints the correct data however it shows the time aswell. so it shows this as an example: "There are only 96 days left until 2023-02-23 00:00:00 from 2022-11-19 00:14:18.003365" how do I remove the time? also if there are any other suggestions on improving this I'm all ears.
[ "You could use date for this calculation.\nfrom datetime import date\n\ntoday = date.today()\nprint(\"Please enter the date you want to find out how many days until below: \")\nyear = int(input(\"What year? \"))\nmonth = int(input(\"What month? \"))\nday = int(input(\"What day? \"))\n\n\ndate2 = date(year, month, day)\n\ndifference = date2 - today\n\nprint(f\"There are only {difference.days+1} days left until {date2} from {today}\")\n\n" ]
[ 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074496577_datetime_python.txt
Q: PYTHON - extract list element using keyword My goal is to extract an element from many list that similar like this. Taking elements that is food. test_list = ['Tools: Pen', 'Food: Sandwich', 'Fruit: Apple' ] I the final result would be "Sandwich" by look list element with the word "Food:" and split from there. My usual method is lookup by index test_list[1].split(': ')[1] However, I go through many lists that number of elements is varied, and I want to look up the food item in the "food:" section. I don't know if there is a function that would help me choose element from a list using "keyword search" Another example, test_list_2 = ['Tools: Pen', 'Tree: Willow' 'Food: Drumstick', 'Fruit: Apple' ] With the same lines of code, test_list_2 result would be "Drumstick" Please kindly help my find a way to do that in Python. Thank you A: I would consider using a dictionary for this application. to translate a list of the form you gave into a dictionary: test_dict = {i.split(": ")[0]: i.split(": ")[1] for i in test_list} And then you can access elements by key test_dict['Food'] A: What you want is a dictionary. test_list_2 = {'Tools': 'Pen', 'Tree': 'Willow', 'Food': 'Drumstick', 'Fruit': 'Apple' } print(test_list_2["Tools"])
PYTHON - extract list element using keyword
My goal is to extract an element from many list that similar like this. Taking elements that is food. test_list = ['Tools: Pen', 'Food: Sandwich', 'Fruit: Apple' ] I the final result would be "Sandwich" by look list element with the word "Food:" and split from there. My usual method is lookup by index test_list[1].split(': ')[1] However, I go through many lists that number of elements is varied, and I want to look up the food item in the "food:" section. I don't know if there is a function that would help me choose element from a list using "keyword search" Another example, test_list_2 = ['Tools: Pen', 'Tree: Willow' 'Food: Drumstick', 'Fruit: Apple' ] With the same lines of code, test_list_2 result would be "Drumstick" Please kindly help my find a way to do that in Python. Thank you
[ "I would consider using a dictionary for this application.\nto translate a list of the form you gave into a dictionary:\ntest_dict = {i.split(\": \")[0]: i.split(\": \")[1] for i in test_list}\n\nAnd then you can access elements by key\ntest_dict['Food']\n\n", "What you want is a dictionary.\ntest_list_2 =\n{'Tools': 'Pen',\n'Tree': 'Willow',\n'Food': 'Drumstick',\n'Fruit': 'Apple'\n}\n\nprint(test_list_2[\"Tools\"])\n\n" ]
[ 2, 0 ]
[]
[]
[ "list", "pdfplumber", "python" ]
stackoverflow_0074496611_list_pdfplumber_python.txt
Q: Issues with continuously nesting while loops in python I'm writing a text-based RPG in python 3. I'm writing it with individual scenes that will execute related functions based on user input in that specific scene. Some of those inputs will move the user to a new scene. The player is stuck in a scene with a while True loop until they move to a new scene, where they are once again stuck in a while True loop. This hasn't been a problem, but I'm a novice I would just like to know if this could cause issues down the line since the game will essentially be running on infinitely nested while loops. Below is how I'm getting inputs from players and using them to execute commands based on where the player is. Note my code structure isn't quite like this, I'm using classes and storing available commands differently, but I wanted a simple way to show how the scene changing works. My question only pertains to the while loops. Thanks so much! def scene_room(): while True: user_input = input() if user_input == "go outside": scene_outside() elif user_input == "exit": exit() else: print("Invalid input.") def scene_outside(): while True: user_input = input() if user_input == "go room": scene_room() elif user_input == "info": print("You're outside.") elif user_input == "exit": exit() else: print("Invalid command") scene_room() A: Based on the comments the answer is yes, nesting while loops can cause issues by both exceeding the limited stack size and because while loops are generally "blocking" in nature (which I don't fully understand, but I'm including this for people that will). In this specific case, there is also the issue of possibly infinite recursion because the functions are also nesting. A solution to the code I provided is to return the new scene without calling it from within the while loop or function. We need a wrapper function to handle calling new scenes so that we can exit each scene function before calling a new one. def scene_room(): while True: user_input = input() if user_input == "go outside": return scene_outside # break loop before calling elif user_input == "exit": exit() else: print("Invalid input.") def scene_outside(): while True: user_input = input() if user_input == "go room": return scene_room # # break loop before calling elif user_input == "info": print("You're outside.") # not new scene so stay in loop elif user_input == "exit": exit() else: print("Invalid command") def play(): new_scene = scene_room while True: new_scene = new_scene()
Issues with continuously nesting while loops in python
I'm writing a text-based RPG in python 3. I'm writing it with individual scenes that will execute related functions based on user input in that specific scene. Some of those inputs will move the user to a new scene. The player is stuck in a scene with a while True loop until they move to a new scene, where they are once again stuck in a while True loop. This hasn't been a problem, but I'm a novice I would just like to know if this could cause issues down the line since the game will essentially be running on infinitely nested while loops. Below is how I'm getting inputs from players and using them to execute commands based on where the player is. Note my code structure isn't quite like this, I'm using classes and storing available commands differently, but I wanted a simple way to show how the scene changing works. My question only pertains to the while loops. Thanks so much! def scene_room(): while True: user_input = input() if user_input == "go outside": scene_outside() elif user_input == "exit": exit() else: print("Invalid input.") def scene_outside(): while True: user_input = input() if user_input == "go room": scene_room() elif user_input == "info": print("You're outside.") elif user_input == "exit": exit() else: print("Invalid command") scene_room()
[ "Based on the comments the answer is yes, nesting while loops can cause issues by both exceeding the limited stack size and because while loops are generally \"blocking\" in nature (which I don't fully understand, but I'm including this for people that will). In this specific case, there is also the issue of possibly infinite recursion because the functions are also nesting.\nA solution to the code I provided is to return the new scene without calling it from within the while loop or function. We need a wrapper function to handle calling new scenes so that we can exit each scene function before calling a new one.\ndef scene_room():\n while True:\n user_input = input()\n if user_input == \"go outside\":\n return scene_outside # break loop before calling\n elif user_input == \"exit\":\n exit()\n else:\n print(\"Invalid input.\")\n\ndef scene_outside():\n while True:\n user_input = input()\n if user_input == \"go room\":\n return scene_room # # break loop before calling\n elif user_input == \"info\":\n print(\"You're outside.\") # not new scene so stay in loop\n elif user_input == \"exit\":\n exit()\n else:\n print(\"Invalid command\")\n\ndef play():\n new_scene = scene_room\n while True:\n new_scene = new_scene()\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "while_loop" ]
stackoverflow_0074491570_python_python_3.x_while_loop.txt
Q: using ray + light gbm + limited memory So, I would like to train a lightGBM on a remote, large ray cluster and a large dataset. Before that, I would like to write the code such that I can run the training also in a memory-constrained setting, e.g. my local laptop, where the dataset does not fit in-mem. That will require some way of lazy loading the data. The way I imagine it, I should be possible with ray to load batches of random samples of the large dataset from disk (multiple .pq files) and feed them to the lightgbm training function. The memory should thereby act as a fast buffer, which contains random, loaded batches that are fed to the training function and then removed from memory. Multiple workers take care of training + IO ops for loading new samples from disk into memory. The maximum amount of memory can be constrained to not exceed my local resources, such that my pc doesn't crash. Is this possible? I did not understand yet whether the LGBM needs the full dataset at once, or can be fed batches iteratively, such as with neural networks, for instance. So far, I have tried using the lightgbm_ray lib for this: from lightgbm_ray import RayDMatrix, RayParams, train, RayFileType # some stuff before ... # make dataset data_train = RayDMatrix( data=filenames, label=TARGET, feature_names=features, filetype=RayFileType.PARQUET, num_actors=2, lazy=True, ) # feed to training function evals_result = {} bst = train( params_model, data_train, evals_result=evals_result, valid_sets=[data_train], valid_names=["train"], verbose_eval=False, ray_params=RayParams(num_actors=2, cpus_per_actor=2) ) I thought the lazy=True keyword might take care of it, however, when executing this, I see the memory being maxed out and then my app crashes. Thanks for any advice! A: LightGBM requires loading the entire dataset for training, so in this case, you can test on your laptop with a subset of the data (i.e. only pass a subset of the parquet filenames in). The lazy=True flag delays the data loading to be split across the actors, rather than loading into memory first, then splitting+sending to actors. However, this would still load the entire dataset into memory, since all actors are on the same (local) node. Additionally, when you do move to running on the remote cluster, these tips might be helpful to optimize memory usage: https://docs.ray.io/en/latest/train/gbdt.html?highlight=xgboost%20memro#how-to-optimize-xgboost-memory-usage.
using ray + light gbm + limited memory
So, I would like to train a lightGBM on a remote, large ray cluster and a large dataset. Before that, I would like to write the code such that I can run the training also in a memory-constrained setting, e.g. my local laptop, where the dataset does not fit in-mem. That will require some way of lazy loading the data. The way I imagine it, I should be possible with ray to load batches of random samples of the large dataset from disk (multiple .pq files) and feed them to the lightgbm training function. The memory should thereby act as a fast buffer, which contains random, loaded batches that are fed to the training function and then removed from memory. Multiple workers take care of training + IO ops for loading new samples from disk into memory. The maximum amount of memory can be constrained to not exceed my local resources, such that my pc doesn't crash. Is this possible? I did not understand yet whether the LGBM needs the full dataset at once, or can be fed batches iteratively, such as with neural networks, for instance. So far, I have tried using the lightgbm_ray lib for this: from lightgbm_ray import RayDMatrix, RayParams, train, RayFileType # some stuff before ... # make dataset data_train = RayDMatrix( data=filenames, label=TARGET, feature_names=features, filetype=RayFileType.PARQUET, num_actors=2, lazy=True, ) # feed to training function evals_result = {} bst = train( params_model, data_train, evals_result=evals_result, valid_sets=[data_train], valid_names=["train"], verbose_eval=False, ray_params=RayParams(num_actors=2, cpus_per_actor=2) ) I thought the lazy=True keyword might take care of it, however, when executing this, I see the memory being maxed out and then my app crashes. Thanks for any advice!
[ "LightGBM requires loading the entire dataset for training, so in this case, you can test on your laptop with a subset of the data (i.e. only pass a subset of the parquet filenames in).\nThe lazy=True flag delays the data loading to be split across the actors, rather than loading into memory first, then splitting+sending to actors. However, this would still load the entire dataset into memory, since all actors are on the same (local) node.\nAdditionally, when you do move to running on the remote cluster, these tips might be helpful to optimize memory usage: https://docs.ray.io/en/latest/train/gbdt.html?highlight=xgboost%20memro#how-to-optimize-xgboost-memory-usage.\n" ]
[ 0 ]
[]
[]
[ "lightgbm", "python", "ray" ]
stackoverflow_0074446130_lightgbm_python_ray.txt
Q: How can I compare this template list to a list of words? I'm trying to find out which words fit into this template but don't know how to compare them. Is there any way to do this without counting specific alphabetic characters in the template, getting their indices, and then checking each letter in each word? The desired output is a list of words from words that fit the template. alist = [] template = ['_', '_', 'l', '_', '_'] words = ['hello', 'jacky', 'helps'] if (word fits template): alist.append(word) A: You can use zip to compare the word to template: def word_fits(word, template): if len(word) != len(template): return False for w, t in zip(word, template): if t != "_" and w != t: return False return True template = ["_", "_", "l", "_", "_"] words = ["hello", "jacky", "helps"] alist = [w for w in words if word_fits(w, template)] print(alist) Prints: ["hello", "helps"] A: You could use a regex (converting your template to a regex, then getting all matching words): import re template = ['_', '_', 'l', '_', '_'] words = ['hello', 'jacky', 'helps'] regexp = ''.join(template).replace('_','.') # '..l..' in this case match_words = [word for word in words if re.match(regexp,word)] match_words # Out[108]: ['hello', 'helps']
How can I compare this template list to a list of words?
I'm trying to find out which words fit into this template but don't know how to compare them. Is there any way to do this without counting specific alphabetic characters in the template, getting their indices, and then checking each letter in each word? The desired output is a list of words from words that fit the template. alist = [] template = ['_', '_', 'l', '_', '_'] words = ['hello', 'jacky', 'helps'] if (word fits template): alist.append(word)
[ "You can use zip to compare the word to template:\ndef word_fits(word, template):\n if len(word) != len(template):\n return False\n\n for w, t in zip(word, template):\n if t != \"_\" and w != t:\n return False\n\n return True\n\n\ntemplate = [\"_\", \"_\", \"l\", \"_\", \"_\"]\nwords = [\"hello\", \"jacky\", \"helps\"]\n\nalist = [w for w in words if word_fits(w, template)]\n\nprint(alist)\n\nPrints:\n[\"hello\", \"helps\"]\n\n", "You could use a regex (converting your template to a regex, then getting all matching words):\nimport re\ntemplate = ['_', '_', 'l', '_', '_']\nwords = ['hello', 'jacky', 'helps']\nregexp = ''.join(template).replace('_','.')\n# '..l..' in this case\nmatch_words = [word for word in words if re.match(regexp,word)]\n\nmatch_words\n# Out[108]: ['hello', 'helps']\n\n" ]
[ 4, 1 ]
[]
[]
[ "comparison", "for_loop", "list", "loops", "python" ]
stackoverflow_0074496668_comparison_for_loop_list_loops_python.txt
Q: Flatten broken horizontal bar chart to line graph or heatmap I have data for all the time I've spent coding. This data is represented as a dictionary where the key is the date and the value is a list of tuples containing the time I started a coding session and how long the coding session lasted. I have successfully plotted this on a broken_barh using the below code, where the y-axis is the date, the x-axis is the time in that day and each broken bar is an individual session. for i,subSessions in enumerate(sessions.values()): plt.broken_barh(subSessions, (i,1)) months = {} start = getStartMonth() for month in period_range(start=start,end=datetime.today(),freq="M"): month = str(month) months[month] = (datetime.strptime(month,'%Y-%m')-start).days plt.yticks(list(months.values()),months.keys()) plt.xticks(range(0,24*3600,3600),[str(i)+":00" for i in range(24)],rotation=45) plt.gca().invert_yaxis() plt.show() I want to use this data to discover what times of the day I spend the most time coding, but it isn't very clear from the above chart so I'd like to display it as a line graph or heatmap where the y-axis is the number of days I spent coding at the time on the x-axis (or, in other words, how many sessions are present in that column of the above chart). How do I accomplish this? A: You can find some great examples of how to create a heatmap from matplotlib website. Here is a basic code with some random data: import matplotlib.pyplot as plt import numpy as np import pandas as pd index_labels = np.arange(0,24) column_labels = pd.date_range(start='1/1/2022', end='1/31/2022').strftime('%m/%d') #random data np.random.seed(12345) data = np.random.randint(0,60, size=(len(index_labels), len(column_labels))) df = pd.DataFrame(data=data, columns=column_labels, index=index_labels) #heatmap function def heatmap(df, ax, cbarlabel="", cmap="Greens", label_num_dec_place=0): df = df.copy() # Ploting a blank heatmap im = ax.imshow(df.values, cmap) # create a customized colorbar cbar = ax.figure.colorbar(im, ax=ax, fraction=0.05, extend='both', extendfrac=0.05) cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom", fontsize=14) # Setting ticks ax.set_xticks(np.arange(df.shape[1]), labels=df.columns, fontsize=12) ax.set_yticks(np.arange(df.shape[0]), labels=list(df.index), fontsize=12) # proper placement of ticks ax.tick_params(axis='x', top=True, bottom=False, labeltop=True, labelbottom=False) ax.spines[:].set_visible(False) ax.grid(which="both", visible="False", color="white", linestyle='solid', linewidth=2) ax.grid(False) # Rotation of tick labels plt.setp(ax.get_xticklabels(), rotation=-60, ha="right", rotation_mode=None) plt.setp(ax.get_yticklabels(), rotation=30) #plotting and saving fig, ax = plt.subplots(facecolor=(1,1,1), figsize=(20,8), dpi=200) heatmap(df=df, ax=ax, cbarlabel="time (min)", cmap="Greens", label_num_dec_place=0) plt.savefig('time_heatmap.png', bbox_inches='tight', facecolor=fig.get_facecolor(), transparent=True, ) Output: A: One way to do it is to use sampling. Choose how many samples you want to take in a given interval (the precision, for example 288 samples per day) and split each interval by that number of samples and count how many sessions are within this sample. The downside to this is that it can't be 100% precise and increasing the precision increases the time it takes to generate (for me, it takes several minutes to generate a second-precise image, though this level of precision makes little to no difference to the result). Here is some code which can produce both a heatmap and a line graph # Configuration options precisionPerDay = 288 timeTicksPerDay = 24 timeTickRotation = 60 timeTickFontSize = 6 heatmap = True # Constants hoursInDay = 24 secondsInHour = 3600 secondsInDay = hoursInDay*secondsInHour xInterval = secondsInDay/precisionPerDay timeTickSecondInterval = precisionPerDay/timeTicksPerDay timeTickHourInterval = hoursInDay/timeTicksPerDay # Calculating x-axis (time) ticks xAxis = range(precisionPerDay) timeTickLabels = [] timeTickLocations = [] for timeTick in range(timeTicksPerDay): timeTickLocations.append(int(timeTick*timeTickSecondInterval)) hours = timeTick/timeTicksPerDay*hoursInDay hour = int(hours) minute = int((hours-hour)*60) timeTickLabels.append(f"{hour:02d}:{minute:02d}") # Calculating y-axis (height) heights = [] for dayX in xAxis: rangeStart = dayX*xInterval rangeEnd = rangeStart+xInterval y = 0 for date,sessions in sessions.items(): for session in sessions: if session[0] < rangeEnd and session[0]+session[1] > rangeStart: y += 1 heights.append(y) # Plotting data if heatmap: plt.yticks([]) plt.imshow([heights], aspect="auto") else: plt.plot(xAxis,heights) plt.ylim(ymin=0) plt.xlim(xmin=0,xmax=len(heights)) plt.xlabel("Time of day") plt.ylabel("How often I've coded at that time") plt.xticks(timeTickLocations,timeTickLabels, fontsize=timeTickFontSize,rotation=timeTickRotation) plt.show() And here are some sample results Graph produced by same configuration options shown in above code Same data but as a line graph with a lower precision (24 per day) and more time ticks (48)
Flatten broken horizontal bar chart to line graph or heatmap
I have data for all the time I've spent coding. This data is represented as a dictionary where the key is the date and the value is a list of tuples containing the time I started a coding session and how long the coding session lasted. I have successfully plotted this on a broken_barh using the below code, where the y-axis is the date, the x-axis is the time in that day and each broken bar is an individual session. for i,subSessions in enumerate(sessions.values()): plt.broken_barh(subSessions, (i,1)) months = {} start = getStartMonth() for month in period_range(start=start,end=datetime.today(),freq="M"): month = str(month) months[month] = (datetime.strptime(month,'%Y-%m')-start).days plt.yticks(list(months.values()),months.keys()) plt.xticks(range(0,24*3600,3600),[str(i)+":00" for i in range(24)],rotation=45) plt.gca().invert_yaxis() plt.show() I want to use this data to discover what times of the day I spend the most time coding, but it isn't very clear from the above chart so I'd like to display it as a line graph or heatmap where the y-axis is the number of days I spent coding at the time on the x-axis (or, in other words, how many sessions are present in that column of the above chart). How do I accomplish this?
[ "You can find some great examples of how to create a heatmap from matplotlib website.\nHere is a basic code with some random data:\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nindex_labels = np.arange(0,24)\ncolumn_labels = pd.date_range(start='1/1/2022', end='1/31/2022').strftime('%m/%d')\n\n#random data\nnp.random.seed(12345)\ndata = np.random.randint(0,60, size=(len(index_labels), len(column_labels)))\ndf = pd.DataFrame(data=data, columns=column_labels, index=index_labels)\n\n#heatmap function\ndef heatmap(df, ax, cbarlabel=\"\", cmap=\"Greens\", label_num_dec_place=0):\n df = df.copy()\n \n # Ploting a blank heatmap\n im = ax.imshow(df.values, cmap)\n\n # create a customized colorbar\n cbar = ax.figure.colorbar(im, ax=ax, fraction=0.05, extend='both', extendfrac=0.05)\n cbar.ax.set_ylabel(cbarlabel, rotation=-90, va=\"bottom\", fontsize=14)\n\n # Setting ticks\n ax.set_xticks(np.arange(df.shape[1]), labels=df.columns, fontsize=12)\n ax.set_yticks(np.arange(df.shape[0]), labels=list(df.index), fontsize=12)\n\n # proper placement of ticks\n ax.tick_params(axis='x', top=True, bottom=False,\n labeltop=True, labelbottom=False)\n\n ax.spines[:].set_visible(False)\n ax.grid(which=\"both\", visible=\"False\", color=\"white\", linestyle='solid', linewidth=2)\n ax.grid(False)\n \n # Rotation of tick labels\n plt.setp(ax.get_xticklabels(), rotation=-60, \n ha=\"right\", rotation_mode=None)\n plt.setp(ax.get_yticklabels(), rotation=30)\n\n#plotting and saving\nfig, ax = plt.subplots(facecolor=(1,1,1), figsize=(20,8), dpi=200)\nheatmap(df=df, ax=ax, cbarlabel=\"time (min)\", cmap=\"Greens\", label_num_dec_place=0)\nplt.savefig('time_heatmap.png', \n bbox_inches='tight', \n facecolor=fig.get_facecolor(), \n transparent=True,\n )\n\nOutput:\n\n", "One way to do it is to use sampling. Choose how many samples you want to take in a given interval (the precision, for example 288 samples per day) and split each interval by that number of samples and count how many sessions are within this sample. The downside to this is that it can't be 100% precise and increasing the precision increases the time it takes to generate (for me, it takes several minutes to generate a second-precise image, though this level of precision makes little to no difference to the result).\nHere is some code which can produce both a heatmap and a line graph\n# Configuration options\nprecisionPerDay = 288\ntimeTicksPerDay = 24\ntimeTickRotation = 60\ntimeTickFontSize = 6\nheatmap = True\n\n# Constants\nhoursInDay = 24\nsecondsInHour = 3600\nsecondsInDay = hoursInDay*secondsInHour\nxInterval = secondsInDay/precisionPerDay\ntimeTickSecondInterval = precisionPerDay/timeTicksPerDay\ntimeTickHourInterval = hoursInDay/timeTicksPerDay\n\n# Calculating x-axis (time) ticks\nxAxis = range(precisionPerDay)\ntimeTickLabels = []\ntimeTickLocations = []\nfor timeTick in range(timeTicksPerDay):\n timeTickLocations.append(int(timeTick*timeTickSecondInterval))\n hours = timeTick/timeTicksPerDay*hoursInDay\n hour = int(hours)\n minute = int((hours-hour)*60)\n timeTickLabels.append(f\"{hour:02d}:{minute:02d}\")\n\n# Calculating y-axis (height)\nheights = []\nfor dayX in xAxis:\n rangeStart = dayX*xInterval\n rangeEnd = rangeStart+xInterval\n y = 0\n for date,sessions in sessions.items():\n for session in sessions:\n if session[0] < rangeEnd and session[0]+session[1] > rangeStart:\n y += 1\n heights.append(y)\n\n# Plotting data\nif heatmap:\n plt.yticks([])\n plt.imshow([heights], aspect=\"auto\")\nelse:\n plt.plot(xAxis,heights)\n plt.ylim(ymin=0)\nplt.xlim(xmin=0,xmax=len(heights))\nplt.xlabel(\"Time of day\")\nplt.ylabel(\"How often I've coded at that time\")\nplt.xticks(timeTickLocations,timeTickLabels,\n fontsize=timeTickFontSize,rotation=timeTickRotation)\nplt.show()\n\nAnd here are some sample results\nGraph produced by same configuration options shown in above code\n\nSame data but as a line graph with a lower precision (24 per day) and more time ticks (48)\n\n" ]
[ 0, 0 ]
[]
[]
[ "charts", "matplotlib", "python" ]
stackoverflow_0074482626_charts_matplotlib_python.txt
Q: how to groupby rows and create new columns on pyspark original dataframe id email name 1 id1@first.com john 2 id2@first.com Maike 2 id2@second Maike 1 id1@second.com john I want to convert to this id email email1 name 1 id1@first.com id1@second.com john 2 id2@first.com id2@second Maike it's only an example, I have very large file and more than 60 columns im using df = spark.read.option("header",True) \ .csv("contatcs.csv", sep =',') but works to with pyspark.pandas api import pyspark.pandas as ps df = ps.read_csv('contacts.csv', sep=',') df.head() but I prefer spark.read because it's a Lazy Evaluation and the pandas API is not A: In order to do it deterministically in Spark, you must have some rule to determine which email is first and which is second. The row order in the CSV file (not having a specified column for row number) is a bad rule when you work with Spark, because every row may go to a different node, and then you will cannot see which of rows was first or second. In the following example, I assume that the rule is the alphabetical order, so I collect all the emails into one array using collect_set and then sort them using array_sort. Input: from pyspark.sql import functions as F df = spark.createDataFrame( [('1', 'id1@first.com', 'john'), ('2', 'id2@first.com', 'Maike'), ('2', 'id2@second', 'Maike'), ('1', 'id1@second.com', 'john')], ['id', 'email', 'name']) Script: emails = F.array_sort(F.collect_set('email')) df = df.groupBy('id', 'name').agg( emails[0].alias('email0'), emails[1].alias('email1'), ) df.show() # +---+-----+-------------+--------------+ # | id| name| email0| email1| # +---+-----+-------------+--------------+ # | 2|Maike|id2@first.com| id2@second| # | 1| john|id1@first.com|id1@second.com| # +---+-----+-------------+--------------+ If you had a row number, something like... from pyspark.sql import functions as F df = spark.createDataFrame( [('1', '1', 'id1@first.com', 'john'), ('2', '2', 'id2@first.com', 'Maike'), ('3', '2', 'id2@second', 'Maike'), ('4', '1', 'id1@second.com', 'john')], ['row_number', 'id', 'email', 'name']) You could use something like below options: emails = F.array_sort(F.collect_set(F.struct(F.col('row_number').cast('long'), 'email'))) df = df.groupBy('id', 'name').agg( emails[0]['email'].alias('email0'), emails[1]['email'].alias('email1'), ) df.show() # +---+-----+-------------+--------------+ # | id| name| email0| email1| # +---+-----+-------------+--------------+ # | 2|Maike|id2@first.com| id2@second| # | 1| john|id1@first.com|id1@second.com| # +---+-----+-------------+--------------+ from pyspark.sql import Window as W w = W.partitionBy('id', 'name').orderBy('row_number') df = (df .withColumn('_rn', F.row_number().over(w)) .filter('_rn <= 2') .withColumn('_rn', F.concat(F.lit('email'), '_rn')) .groupBy('id', 'name') .pivot('_rn') .agg(F.first('email')) ) df.show() # +---+-----+-------------+--------------+ # | id| name| email1| email2| # +---+-----+-------------+--------------+ # | 1| john|id1@first.com|id1@second.com| # | 2|Maike|id2@first.com| id2@second| # +---+-----+-------------+--------------+ A: If you wanted to make it dynamic so that it creates new email counts based on maximum email count, you can try logic and code below from pyspark.sql import functions as F df = spark.createDataFrame( [('1', 'id1@first.com', 'john'), ('2', 'id2@first.com', 'Maike'), ('2', 'id2_3@first.com', 'Maike'), ('2', 'id2@second', 'Maike'), ('1', 'id1@second.com', 'john')], ['id', 'email', 'name']) df.show() +---+---------------+-----+ | id| email| name| +---+---------------+-----+ | 1| id1@first.com| john| | 2| id2@first.com|Maike| | 2|id2_3@first.com|Maike| | 2| id2@second|Maike| | 1| id1@second.com| john| Solution new = ( df.groupBy('id','name').agg(collect_set('email').alias('email') )#Collect unique emails .withColumn('x',max(size('email')).over(Window.partitionBy()))#Find the group with maximum emails, for use in email column count ) new = (new.withColumn('email',F.struct(*[ F.col("email")[i].alias(f"email{i+1}") for i in range(new.select('x').collect()[0][0])]))#Convert email column to struct type .selectExpr('x','id','name','email.*') #Select all columns ) new.show(truncate=False) Outcome +---+---+-----+-------------+--------------+---------------+ |x |id |name |email1 |email2 |email3 | +---+---+-----+-------------+--------------+---------------+ |3 |1 |john |id1@first.com|id1@second.com|null | |3 |2 |Maike|id2@second |id2@first.com |id2_3@first.com| +---+---+-----+-------------+--------------+---------------+ A: pyspark I have included a corner case when there is uneven number of email ids. For that, find the max length and iterate to fetch email at each index: from pyspark.sql import functions as F df = spark.createDataFrame([(1, 'id1@first.com', 'john'),(2, 'id2@first.com', 'Maike'),(2, 'id2@second', 'Maike'),(1, 'id1@second.com', 'john'),(3, 'id3@third.com', 'amy'),], ['id', 'email', 'name']) df = df.groupby("id", "name").agg(F.collect_list("email").alias("email")) max_len = df.select(F.size("email").alias("size")).collect()[0]["size"] for i in range(1, max_len + 1): df = df.withColumn(f"email{i}", F.when(F.size("email") >= i, F.element_at("email", i)).otherwise(F.lit(""))) df = df.drop("email") Output: +---+-----+-------------+--------------+ |id |name |email1 |email2 | +---+-----+-------------+--------------+ |2 |Maike|id2@first.com|id2@second | |3 |amy |id3@third.com| | |1 |john |id1@first.com|id1@second.com| +---+-----+-------------+--------------+ pandas Since you have mentioned pandas in the tags, following is the solution in pandas: df = pd.DataFrame(data=[(1, 'id1@first.com', 'john'),(2, 'id2@first.com', 'Maike'),(2, 'id2@second', 'Maike'),(1, 'id1@second.com', 'john'),(3, 'id3@third.com', 'amy'),], columns=["id","email","name"]) df = df.groupby("id").agg(email=("email",list), name=("name",pd.unique)) df2 = df.apply(lambda row: pd.Series(data={f"email{i+1}":v for i,v in enumerate(row["email"])}, dtype="object"), axis=1) df = df.drop("email", axis=1).merge(df2, on="id") Output: name email1 email2 id 1 john id1@first.com id1@second.com 2 Maike id2@first.com id2@second 3 amy id3@third.com NaN
how to groupby rows and create new columns on pyspark
original dataframe id email name 1 id1@first.com john 2 id2@first.com Maike 2 id2@second Maike 1 id1@second.com john I want to convert to this id email email1 name 1 id1@first.com id1@second.com john 2 id2@first.com id2@second Maike it's only an example, I have very large file and more than 60 columns im using df = spark.read.option("header",True) \ .csv("contatcs.csv", sep =',') but works to with pyspark.pandas api import pyspark.pandas as ps df = ps.read_csv('contacts.csv', sep=',') df.head() but I prefer spark.read because it's a Lazy Evaluation and the pandas API is not
[ "In order to do it deterministically in Spark, you must have some rule to determine which email is first and which is second. The row order in the CSV file (not having a specified column for row number) is a bad rule when you work with Spark, because every row may go to a different node, and then you will cannot see which of rows was first or second.\nIn the following example, I assume that the rule is the alphabetical order, so I collect all the emails into one array using collect_set and then sort them using array_sort.\nInput:\nfrom pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('1', 'id1@first.com', 'john'),\n ('2', 'id2@first.com', 'Maike'),\n ('2', 'id2@second', 'Maike'),\n ('1', 'id1@second.com', 'john')],\n ['id', 'email', 'name'])\n\nScript:\nemails = F.array_sort(F.collect_set('email'))\ndf = df.groupBy('id', 'name').agg(\n emails[0].alias('email0'),\n emails[1].alias('email1'),\n)\ndf.show()\n# +---+-----+-------------+--------------+\n# | id| name| email0| email1|\n# +---+-----+-------------+--------------+\n# | 2|Maike|id2@first.com| id2@second|\n# | 1| john|id1@first.com|id1@second.com|\n# +---+-----+-------------+--------------+\n\n\nIf you had a row number, something like...\nfrom pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('1', '1', 'id1@first.com', 'john'),\n ('2', '2', 'id2@first.com', 'Maike'),\n ('3', '2', 'id2@second', 'Maike'),\n ('4', '1', 'id1@second.com', 'john')],\n ['row_number', 'id', 'email', 'name'])\n\nYou could use something like below options:\nemails = F.array_sort(F.collect_set(F.struct(F.col('row_number').cast('long'), 'email')))\ndf = df.groupBy('id', 'name').agg(\n emails[0]['email'].alias('email0'),\n emails[1]['email'].alias('email1'),\n)\ndf.show()\n# +---+-----+-------------+--------------+\n# | id| name| email0| email1|\n# +---+-----+-------------+--------------+\n# | 2|Maike|id2@first.com| id2@second|\n# | 1| john|id1@first.com|id1@second.com|\n# +---+-----+-------------+--------------+\n\nfrom pyspark.sql import Window as W\n\nw = W.partitionBy('id', 'name').orderBy('row_number')\ndf = (df\n .withColumn('_rn', F.row_number().over(w))\n .filter('_rn <= 2')\n .withColumn('_rn', F.concat(F.lit('email'), '_rn'))\n .groupBy('id', 'name')\n .pivot('_rn')\n .agg(F.first('email'))\n)\ndf.show()\n# +---+-----+-------------+--------------+\n# | id| name| email1| email2|\n# +---+-----+-------------+--------------+\n# | 1| john|id1@first.com|id1@second.com|\n# | 2|Maike|id2@first.com| id2@second|\n# +---+-----+-------------+--------------+\n\n", "If you wanted to make it dynamic so that it creates new email counts based on maximum email count, you can try logic and code below\nfrom pyspark.sql import functions as F\ndf = spark.createDataFrame(\n [('1', 'id1@first.com', 'john'),\n ('2', 'id2@first.com', 'Maike'),\n ('2', 'id2_3@first.com', 'Maike'),\n ('2', 'id2@second', 'Maike'),\n ('1', 'id1@second.com', 'john')],\n ['id', 'email', 'name'])\n\ndf.show()\n\n\n\n+---+---------------+-----+\n| id| email| name|\n+---+---------------+-----+\n| 1| id1@first.com| john|\n| 2| id2@first.com|Maike|\n| 2|id2_3@first.com|Maike|\n| 2| id2@second|Maike|\n| 1| id1@second.com| john|\n\nSolution\nnew = ( df.groupBy('id','name').agg(collect_set('email').alias('email') )#Collect unique emails\n .withColumn('x',max(size('email')).over(Window.partitionBy()))#Find the group with maximum emails, for use in email column count\n )\n \nnew = (new.withColumn('email',F.struct(*[ F.col(\"email\")[i].alias(f\"email{i+1}\") for i in range(new.select('x').collect()[0][0])]))#Convert email column to struct type\n .selectExpr('x','id','name','email.*') #Select all columns\n )\nnew.show(truncate=False)\n\nOutcome\n+---+---+-----+-------------+--------------+---------------+\n|x |id |name |email1 |email2 |email3 |\n+---+---+-----+-------------+--------------+---------------+\n|3 |1 |john |id1@first.com|id1@second.com|null |\n|3 |2 |Maike|id2@second |id2@first.com |id2_3@first.com|\n+---+---+-----+-------------+--------------+---------------+\n\n", "pyspark\nI have included a corner case when there is uneven number of email ids. For that, find the max length and iterate to fetch email at each index:\nfrom pyspark.sql import functions as F\ndf = spark.createDataFrame([(1, 'id1@first.com', 'john'),(2, 'id2@first.com', 'Maike'),(2, 'id2@second', 'Maike'),(1, 'id1@second.com', 'john'),(3, 'id3@third.com', 'amy'),], ['id', 'email', 'name'])\n\ndf = df.groupby(\"id\", \"name\").agg(F.collect_list(\"email\").alias(\"email\"))\nmax_len = df.select(F.size(\"email\").alias(\"size\")).collect()[0][\"size\"]\nfor i in range(1, max_len + 1):\n df = df.withColumn(f\"email{i}\", F.when(F.size(\"email\") >= i, F.element_at(\"email\", i)).otherwise(F.lit(\"\")))\ndf = df.drop(\"email\")\n\nOutput:\n+---+-----+-------------+--------------+\n|id |name |email1 |email2 |\n+---+-----+-------------+--------------+\n|2 |Maike|id2@first.com|id2@second |\n|3 |amy |id3@third.com| |\n|1 |john |id1@first.com|id1@second.com|\n+---+-----+-------------+--------------+\n\npandas\nSince you have mentioned pandas in the tags, following is the solution in pandas:\ndf = pd.DataFrame(data=[(1, 'id1@first.com', 'john'),(2, 'id2@first.com', 'Maike'),(2, 'id2@second', 'Maike'),(1, 'id1@second.com', 'john'),(3, 'id3@third.com', 'amy'),], columns=[\"id\",\"email\",\"name\"])\n\ndf = df.groupby(\"id\").agg(email=(\"email\",list), name=(\"name\",pd.unique))\ndf2 = df.apply(lambda row: pd.Series(data={f\"email{i+1}\":v for i,v in enumerate(row[\"email\"])}, dtype=\"object\"), axis=1)\ndf = df.drop(\"email\", axis=1).merge(df2, on=\"id\")\n\nOutput:\n name email1 email2\nid \n1 john id1@first.com id1@second.com\n2 Maike id2@first.com id2@second\n3 amy id3@third.com NaN\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "apache_spark", "csv", "group_by", "pyspark", "python" ]
stackoverflow_0074484873_apache_spark_csv_group_by_pyspark_python.txt
Q: why it doesn't work when I write comments in python Image of the code and error I'm getting A: You didn't save the file :)...
why it doesn't work when I write comments in python
Image of the code and error I'm getting
[ "You didn't save the file :)...\n" ]
[ 3 ]
[]
[]
[ "comments", "python" ]
stackoverflow_0074496776_comments_python.txt
Q: How do I put an attribute as a variable in a python function? I have this function: def webdriver_wait(browser, delay, tag_name, tag, succesful_message, fail_message): try: wait_by_var = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.tag_name, tag))) print(succesful_message) return wait_by_var except TimeoutException: print(fail_message) My problem comes when I execute the function. Due to the function variable tag_name, I get the following error: AttributeError: type object 'By' has no attribute 'tag_name' I want the attribute from By. to be as a variable in my function, so that when I call the function webdriver_wait() I can choose either a TAG_NAME,ÌD,XPATH,CSS_SELECTOR etc. The rest of the variables in the function i.e. browser, delay, tag etc all work. How do I create a function where I can put an attribute of By. as a function variable? A: Use the getattr() function to get an arbitrary attribute of a function by its name. getattr(By, tag_name)
How do I put an attribute as a variable in a python function?
I have this function: def webdriver_wait(browser, delay, tag_name, tag, succesful_message, fail_message): try: wait_by_var = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.tag_name, tag))) print(succesful_message) return wait_by_var except TimeoutException: print(fail_message) My problem comes when I execute the function. Due to the function variable tag_name, I get the following error: AttributeError: type object 'By' has no attribute 'tag_name' I want the attribute from By. to be as a variable in my function, so that when I call the function webdriver_wait() I can choose either a TAG_NAME,ÌD,XPATH,CSS_SELECTOR etc. The rest of the variables in the function i.e. browser, delay, tag etc all work. How do I create a function where I can put an attribute of By. as a function variable?
[ "Use the getattr() function to get an arbitrary attribute of a function by its name.\ngetattr(By, tag_name)\n\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "python", "selenium", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074496772_attributeerror_python_selenium_selenium_webdriver_webdriverwait.txt
Q: How can I add a string inside a string? The problem is simple, I'm given a random string and a random pattern and I'm told to get all the posible combinations of that pattern that occur in the string and mark then with [target] and [endtarget] at the beggining and end. For example: given the following text: "XuyZB8we4" and the following pattern: "XYZAB" The expected output would be: "[target]X[endtarget]uy[target]ZB[endtarget]8we4". I already got the part that identifies all the words, but I can't find a way of placing the [target] and [endtarget] strings after and before the pattern (called in the code match). import re def tagger(text, search): place_s = "[target]" place_f = "[endtarget]" pattern = re.compile(rf"[{search}]+") matches = pattern.finditer(text) for match in matches: print(match) return test_string test_string = "alsikjuyZB8we4 aBBe8XAZ piarBq8 Bq84Z " pattern = "XYZAB" print(tagger(test_string, pattern)) I also tried the for with the sub method, but I couldn't get it to work. for match in matches: re.sub(match.group(0), place_s + match.group(0) + place_f, text) return text A: re.sub allows you to pass backreferences to matched groups within your pattern. so you do need to enclose your pattern in parentheses, or create a named group, and then it will replace all matches in the entire string at once with your desired replacements: In [10]: re.sub(r'([XYZAB]+)', r'[target]\1[endtarget]', test_string) Out[10]: 'alsikjuy[target]ZB[endtarget]8we4 a[target]BB[endtarget]e8[target]XAZ[endtarget] piar[target]B[endtarget]q8 [target]B[endtarget]q84[target]Z[endtarget] ' With this approach, re.finditer is not not needed at all.
How can I add a string inside a string?
The problem is simple, I'm given a random string and a random pattern and I'm told to get all the posible combinations of that pattern that occur in the string and mark then with [target] and [endtarget] at the beggining and end. For example: given the following text: "XuyZB8we4" and the following pattern: "XYZAB" The expected output would be: "[target]X[endtarget]uy[target]ZB[endtarget]8we4". I already got the part that identifies all the words, but I can't find a way of placing the [target] and [endtarget] strings after and before the pattern (called in the code match). import re def tagger(text, search): place_s = "[target]" place_f = "[endtarget]" pattern = re.compile(rf"[{search}]+") matches = pattern.finditer(text) for match in matches: print(match) return test_string test_string = "alsikjuyZB8we4 aBBe8XAZ piarBq8 Bq84Z " pattern = "XYZAB" print(tagger(test_string, pattern)) I also tried the for with the sub method, but I couldn't get it to work. for match in matches: re.sub(match.group(0), place_s + match.group(0) + place_f, text) return text
[ "re.sub allows you to pass backreferences to matched groups within your pattern. so you do need to enclose your pattern in parentheses, or create a named group, and then it will replace all matches in the entire string at once with your desired replacements:\nIn [10]: re.sub(r'([XYZAB]+)', r'[target]\\1[endtarget]', test_string)\nOut[10]: 'alsikjuy[target]ZB[endtarget]8we4 a[target]BB[endtarget]e8[target]XAZ[endtarget] piar[target]B[endtarget]q8 [target]B[endtarget]q84[target]Z[endtarget] '\n\nWith this approach, re.finditer is not not needed at all.\n" ]
[ 3 ]
[]
[]
[ "python", "python_re", "string" ]
stackoverflow_0074496812_python_python_re_string.txt
Q: Failed to install Calliope I am trying to install the package calliope on python 3.7 using pycharm and I am getting this error that I don't understand. I also tryed o install it via anaconda but still I am getting the same problem. Any help please would be highly appreciated. It is really imporant where I need this package to run a program about energy management. Collecting calliope Using cached calliope-0.6.8.tar.gz (725 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing metadata (pyproject.toml): started Preparing metadata (pyproject.toml): finished with status 'done' Collecting xarray<0.21,>=0.20 Using cached xarray-0.20.2-py3-none-any.whl (845 kB) Collecting plotly<3.11,>=3.10 Using cached plotly-3.10.0-py2.py3-none-any.whl (41.5 MB) Collecting netcdf4>=1.2.2 Using cached netCDF4-1.6.2.tar.gz (777 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'error' error: subprocess-exited-with-error Getting requirements to build wheel did not run successfully. exit code: 1 [33 lines of output] reading from setup.cfg... HDF5_DIR environment variable not set, checking some standard locations .. checking C:\Users\m.haddad\include ... hdf5 headers not found in C:\Users\m.haddad\include checking /usr/local\include ... hdf5 headers not found in /usr/local\include checking /sw\include ... hdf5 headers not found in /sw\include checking /opt\include ... hdf5 headers not found in /opt\include checking /opt/local\include ... hdf5 headers not found in /opt/local\include checking /opt/homebrew\include ... hdf5 headers not found in /opt/homebrew\include checking /usr\include ... hdf5 headers not found in /usr\include Traceback (most recent call last): File "C:\Users\m.haddad\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 351, in <module> main() File "C:\Users\m.haddad\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 333, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "C:\Users\m.haddad\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "C:\Users\ME920~1.HAD\AppData\Local\Temp\pip-build-env-6qd6b_6t\overlay\Lib\site-packages\setuptools\build_meta.py", line 338, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "C:\Users\ME920~1.HAD\AppData\Local\Temp\pip-build-env-6qd6b_6t\overlay\Lib\site-packages\setuptools\build_meta.py", line 320, in _get_build_requires self.run_setup() File "C:\Users\ME920~1.HAD\AppData\Local\Temp\pip-build-env-6qd6b_6t\overlay\Lib\site-packages\setuptools\build_meta.py", line 335, in run_setup exec(code, locals()) File "<string>", line 449, in <module> File "<string>", line 390, in _populate_hdf5_info ValueError: did not find HDF5 headers [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error Getting requirements to build wheel did not run successfully. exit code: 1 See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. Thank you everyone A: Download HDF5 https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.12/hdf5-1.12.1/bin/windows/ Set the environment variable HDF5_DIR to C:/Program Files/HDF_Group/HDF5/<your unzipped location>
Failed to install Calliope
I am trying to install the package calliope on python 3.7 using pycharm and I am getting this error that I don't understand. I also tryed o install it via anaconda but still I am getting the same problem. Any help please would be highly appreciated. It is really imporant where I need this package to run a program about energy management. Collecting calliope Using cached calliope-0.6.8.tar.gz (725 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing metadata (pyproject.toml): started Preparing metadata (pyproject.toml): finished with status 'done' Collecting xarray<0.21,>=0.20 Using cached xarray-0.20.2-py3-none-any.whl (845 kB) Collecting plotly<3.11,>=3.10 Using cached plotly-3.10.0-py2.py3-none-any.whl (41.5 MB) Collecting netcdf4>=1.2.2 Using cached netCDF4-1.6.2.tar.gz (777 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'error' error: subprocess-exited-with-error Getting requirements to build wheel did not run successfully. exit code: 1 [33 lines of output] reading from setup.cfg... HDF5_DIR environment variable not set, checking some standard locations .. checking C:\Users\m.haddad\include ... hdf5 headers not found in C:\Users\m.haddad\include checking /usr/local\include ... hdf5 headers not found in /usr/local\include checking /sw\include ... hdf5 headers not found in /sw\include checking /opt\include ... hdf5 headers not found in /opt\include checking /opt/local\include ... hdf5 headers not found in /opt/local\include checking /opt/homebrew\include ... hdf5 headers not found in /opt/homebrew\include checking /usr\include ... hdf5 headers not found in /usr\include Traceback (most recent call last): File "C:\Users\m.haddad\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 351, in <module> main() File "C:\Users\m.haddad\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 333, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "C:\Users\m.haddad\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "C:\Users\ME920~1.HAD\AppData\Local\Temp\pip-build-env-6qd6b_6t\overlay\Lib\site-packages\setuptools\build_meta.py", line 338, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "C:\Users\ME920~1.HAD\AppData\Local\Temp\pip-build-env-6qd6b_6t\overlay\Lib\site-packages\setuptools\build_meta.py", line 320, in _get_build_requires self.run_setup() File "C:\Users\ME920~1.HAD\AppData\Local\Temp\pip-build-env-6qd6b_6t\overlay\Lib\site-packages\setuptools\build_meta.py", line 335, in run_setup exec(code, locals()) File "<string>", line 449, in <module> File "<string>", line 390, in _populate_hdf5_info ValueError: did not find HDF5 headers [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error Getting requirements to build wheel did not run successfully. exit code: 1 See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. Thank you everyone
[ "\nDownload HDF5 https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.12/hdf5-1.12.1/bin/windows/\n\nSet the environment variable HDF5_DIR to C:/Program Files/HDF_Group/HDF5/<your unzipped location>\n\n\n" ]
[ 0 ]
[]
[]
[ "anaconda", "calliope", "pip", "python", "python_3.x" ]
stackoverflow_0074490226_anaconda_calliope_pip_python_python_3.x.txt
Q: Output values in a list below a user defined amount - functions Python programming problem for first year college kids. Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, get the last value from the input, and output all integers less than or equal to that value. Ex: If the input is: 5 50 60 140 200 75 100 the output is: 50 60 75 The 5 indicates that there are five integers in the list, namely 50, 60, 140, 200, and 75. The 100 indicates that the program should output all integers less than or equal to 100, so the program outputs 50, 60, and 75. Such functionality is common on sites like Amazon, where a user can filter results. Your code must define and call the following two functions: def get_user_values() def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold) Utilizing functions will help to make your main very clean and intuitive. Here's what I have: n = int(input()) user_values =[] def get_user_values(): for i in range(n): num = int(input()) user_values.append(num) upper_threshold=user_values[-1] return user_values, upper_threshold def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold): user_values = [i for i in user_values if i <= user_values[-1]] print(*user_values, sep = "\n") if __name__ == '__main__': user_values, upper_threshold = get_user_values() output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold) the output is correct for the example problem, but not for anything else. A: You went to all the trouble to separate the threshold value, and then you don't use it. Change one line: def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold): user_values = [i for i in user_values if i <= upper_threshold] print(*user_values, sep = "\n") A: def get_user_values(): for i in range(user_input): nums = int(input()) user_values.append(nums) upper_threshold = int(input()) return user_values, upper_threshold def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold): for i in user_values: if i <= upper_threshold: user_values = i print(user_values) if __name__ == '__main__': user_input = int(input()) user_values = [] user_values, upper_threshold = get_user_values() output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold)
Output values in a list below a user defined amount - functions
Python programming problem for first year college kids. Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, get the last value from the input, and output all integers less than or equal to that value. Ex: If the input is: 5 50 60 140 200 75 100 the output is: 50 60 75 The 5 indicates that there are five integers in the list, namely 50, 60, 140, 200, and 75. The 100 indicates that the program should output all integers less than or equal to 100, so the program outputs 50, 60, and 75. Such functionality is common on sites like Amazon, where a user can filter results. Your code must define and call the following two functions: def get_user_values() def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold) Utilizing functions will help to make your main very clean and intuitive. Here's what I have: n = int(input()) user_values =[] def get_user_values(): for i in range(n): num = int(input()) user_values.append(num) upper_threshold=user_values[-1] return user_values, upper_threshold def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold): user_values = [i for i in user_values if i <= user_values[-1]] print(*user_values, sep = "\n") if __name__ == '__main__': user_values, upper_threshold = get_user_values() output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold) the output is correct for the example problem, but not for anything else.
[ "You went to all the trouble to separate the threshold value, and then you don't use it. Change one line:\ndef output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):\n user_values = [i for i in user_values if i <= upper_threshold]\n print(*user_values, sep = \"\\n\")\n\n", "def get_user_values():\n\n for i in range(user_input):\n nums = int(input())\n user_values.append(nums)\n upper_threshold = int(input())\n return user_values, upper_threshold\n \ndef output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):\n for i in user_values:\n if i <= upper_threshold:\n user_values = i\n \n print(user_values)\n \nif __name__ == '__main__':\n user_input = int(input())\n user_values = []\n \n user_values, upper_threshold = get_user_values()\n output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold)\n\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0069656068_python.txt
Q: How do I create test and train samples from one dataframe with pandas? I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing. Thanks! A: Scikit Learn's train_test_split is a good one. It will split both numpy arrays and dataframes. from sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.2) A: I would just use numpy's randn: In [11]: df = pd.DataFrame(np.random.randn(100, 2)) In [12]: msk = np.random.rand(len(df)) < 0.8 In [13]: train = df[msk] In [14]: test = df[~msk] And just to see this has worked: In [15]: len(test) Out[15]: 21 In [16]: len(train) Out[16]: 79 A: Pandas random sample will also work train=df.sample(frac=0.8,random_state=200) test=df.drop(train.index) For the same random_state value you will always get the same exact data in the training and test set. This brings in some level of repeatability while also randomly separating training and test data. A: I would use scikit-learn's own training_test_split, and generate it from the index from sklearn.model_selection import train_test_split y = df.pop('output') X = df X_train,X_test,y_train,y_test = train_test_split(X.index,y,test_size=0.2) X.iloc[X_train] # return dataframe train A: There are many ways to create a train/test and even validation samples. Case 1: classic way train_test_split without any options: from sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.3) Case 2: case of a very small datasets (<500 rows): in order to get results for all your lines with this cross-validation. At the end, you will have one prediction for each line of your available training set. from sklearn.model_selection import KFold kf = KFold(n_splits=10, random_state=0) y_hat_all = [] for train_index, test_index in kf.split(X, y): reg = RandomForestRegressor(n_estimators=50, random_state=0) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] clf = reg.fit(X_train, y_train) y_hat = clf.predict(X_test) y_hat_all.append(y_hat) Case 3a: Unbalanced datasets for classification purpose. Following the case 1, here is the equivalent solution: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.3) Case 3b: Unbalanced datasets for classification purpose. Following the case 2, here is the equivalent solution: from sklearn.model_selection import StratifiedKFold kf = StratifiedKFold(n_splits=10, random_state=0) y_hat_all = [] for train_index, test_index in kf.split(X, y): reg = RandomForestRegressor(n_estimators=50, random_state=0) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] clf = reg.fit(X_train, y_train) y_hat = clf.predict(X_test) y_hat_all.append(y_hat) Case 4: you need to create a train/test/validation sets on big data to tune hyperparameters (60% train, 20% test and 20% val). from sklearn.model_selection import train_test_split X_train, X_test_val, y_train, y_test_val = train_test_split(X, y, test_size=0.6) X_test, X_val, y_test, y_val = train_test_split(X_test_val, y_test_val, stratify=y, test_size=0.5) A: No need to convert to numpy. Just use a pandas df to do the split and it will return a pandas df. from sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.2) And if you want to split x from y X_train, X_test, y_train, y_test = train_test_split(df[list_of_x_cols], df[y_col],test_size=0.2) And if you want to split the whole df X, y = df[list_of_x_cols], df[y_col] A: You can use below code to create test and train samples : from sklearn.model_selection import train_test_split trainingSet, testSet = train_test_split(df, test_size=0.2) Test size can vary depending on the percentage of data you want to put in your test and train dataset. A: There are many valid answers. Adding one more to the bunch. from sklearn.cross_validation import train_test_split #gets a random 80% of the entire set X_train = X.sample(frac=0.8, random_state=1) #gets the left out portion of the dataset X_test = X.loc[~df_model.index.isin(X_train.index)] A: You may also consider stratified division into training and testing set. Startified division also generates training and testing set randomly but in such a way that original class proportions are preserved. This makes training and testing sets better reflect the properties of the original dataset. import numpy as np def get_train_test_inds(y,train_proportion=0.7): '''Generates indices, making random stratified split into training set and testing sets with proportions train_proportion and (1-train_proportion) of initial sample. y is any iterable indicating classes of each observation in the sample. Initial proportions of classes inside training and testing sets are preserved (stratified sampling). ''' y=np.array(y) train_inds = np.zeros(len(y),dtype=bool) test_inds = np.zeros(len(y),dtype=bool) values = np.unique(y) for value in values: value_inds = np.nonzero(y==value)[0] np.random.shuffle(value_inds) n = int(train_proportion*len(value_inds)) train_inds[value_inds[:n]]=True test_inds[value_inds[n:]]=True return train_inds,test_inds df[train_inds] and df[test_inds] give you the training and testing sets of your original DataFrame df. A: You can use ~ (tilde operator) to exclude the rows sampled using df.sample(), letting pandas alone handle sampling and filtering of indexes, to obtain two sets. train_df = df.sample(frac=0.8, random_state=100) test_df = df[~df.index.isin(train_df.index)] A: If you need to split your data with respect to the lables column in your data set you can use this: def split_to_train_test(df, label_column, train_frac=0.8): train_df, test_df = pd.DataFrame(), pd.DataFrame() labels = df[label_column].unique() for lbl in labels: lbl_df = df[df[label_column] == lbl] lbl_train_df = lbl_df.sample(frac=train_frac) lbl_test_df = lbl_df.drop(lbl_train_df.index) print '\n%s:\n---------\ntotal:%d\ntrain_df:%d\ntest_df:%d' % (lbl, len(lbl_df), len(lbl_train_df), len(lbl_test_df)) train_df = train_df.append(lbl_train_df) test_df = test_df.append(lbl_test_df) return train_df, test_df and use it: train, test = split_to_train_test(data, 'class', 0.7) you can also pass random_state if you want to control the split randomness or use some global random seed. A: To split into more than two classes such as train, test, and validation, one can do: probs = np.random.rand(len(df)) training_mask = probs < 0.7 test_mask = (probs>=0.7) & (probs < 0.85) validatoin_mask = probs >= 0.85 df_training = df[training_mask] df_test = df[test_mask] df_validation = df[validatoin_mask] This will put approximately 70% of data in training, 15% in test, and 15% in validation. A: shuffle = np.random.permutation(len(df)) test_size = int(len(df) * 0.2) test_aux = shuffle[:test_size] train_aux = shuffle[test_size:] TRAIN_DF =df.iloc[train_aux] TEST_DF = df.iloc[test_aux] A: Just select range row from df like this row_count = df.shape[0] split_point = int(row_count*1/5) test_data, train_data = df[:split_point], df[split_point:] A: import pandas as pd from sklearn.model_selection import train_test_split datafile_name = 'path_to_data_file' data = pd.read_csv(datafile_name) target_attribute = data['column_name'] X_train, X_test, y_train, y_test = train_test_split(data, target_attribute, test_size=0.8) A: This is what I wrote when I needed to split a DataFrame. I considered using Andy's approach above, but didn't like that I could not control the size of the data sets exactly (i.e., it would be sometimes 79, sometimes 81, etc.). def make_sets(data_df, test_portion): import random as rnd tot_ix = range(len(data_df)) test_ix = sort(rnd.sample(tot_ix, int(test_portion * len(data_df)))) train_ix = list(set(tot_ix) ^ set(test_ix)) test_df = data_df.ix[test_ix] train_df = data_df.ix[train_ix] return train_df, test_df train_df, test_df = make_sets(data_df, 0.2) test_df.head() A: There are many great answers above so I just wanna add one more example in the case that you want to specify the exact number of samples for the train and test sets by using just the numpy library. # set the random seed for the reproducibility np.random.seed(17) # e.g. number of samples for the training set is 1000 n_train = 1000 # shuffle the indexes shuffled_indexes = np.arange(len(data_df)) np.random.shuffle(shuffled_indexes) # use 'n_train' samples for training and the rest for testing train_ids = shuffled_indexes[:n_train] test_ids = shuffled_indexes[n_train:] train_data = data_df.iloc[train_ids] train_labels = labels_df.iloc[train_ids] test_data = data_df.iloc[test_ids] test_labels = data_df.iloc[test_ids] A: if you want to split it to train, test and validation set you can use this function: from sklearn.model_selection import train_test_split import pandas as pd def train_test_val_split(df, test_size=0.15, val_size=0.45): temp, test = train_test_split(df, test_size=test_size) total_items_count = len(df.index) val_length = total_items_count * val_size new_val_propotion = val_length / len(temp.index) train, val = train_test_split(temp, test_size=new_val_propotion) return train, test, val A: If your wish is to have one dataframe in and two dataframes out (not numpy arrays), this should do the trick: def split_data(df, train_perc = 0.8): df['train'] = np.random.rand(len(df)) < train_perc train = df[df.train == 1] test = df[df.train == 0] split_data ={'train': train, 'test': test} return split_data A: I think you also need to a get a copy not a slice of dataframe if you wanna add columns later. msk = np.random.rand(len(df)) < 0.8 train, test = df[msk].copy(deep = True), df[~msk].copy(deep = True) A: You can make use of df.as_matrix() function and create Numpy-array and pass it. Y = df.pop() X = df.as_matrix() x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2) model.fit(x_train, y_train) model.test(x_test) A: A bit more elegant to my taste is to create a random column and then split by it, this way we can get a split that will suit our needs and will be random. def split_df(df, p=[0.8, 0.2]): import numpy as np df["rand"]=np.random.choice(len(p), len(df), p=p) r = [df[df["rand"]==val] for val in df["rand"].unique()] return r A: you need to convert pandas dataframe into numpy array and then convert numpy array back to dataframe import pandas as pd df=pd.read_csv('/content/drive/My Drive/snippet.csv', sep='\t') from sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.2) train1=pd.DataFrame(train) test1=pd.DataFrame(test) train1.to_csv('/content/drive/My Drive/train.csv',sep="\t",header=None, encoding='utf-8', index = False) test1.to_csv('/content/drive/My Drive/test.csv',sep="\t",header=None, encoding='utf-8', index = False) A: In my case, I wanted to split a data frame in Train, test and dev with a specific number. Here I am sharing my solution First, assign a unique id to a dataframe (if already not exist) import uuid df['id'] = [uuid.uuid4() for i in range(len(df))] Here are my split numbers: train = 120765 test = 4134 dev = 2816 The split function def df_split(df, n): first = df.sample(n) second = df[~df.id.isin(list(first['id']))] first.reset_index(drop=True, inplace = True) second.reset_index(drop=True, inplace = True) return first, second Now splitting into train, test, dev train, test = df_split(df, 120765) test, dev = df_split(test, 4134) A: How about this? df is my dataframe total_size=len(df) train_size=math.floor(0.66*total_size) (2/3 part of my dataset) #training dataset train=df.head(train_size) #test dataset test=df.tail(len(df) -train_size) A: I would use K-fold cross validation. It's been proven to give much better results than the train_test_split Here's an article on how to apply it with sklearn from the documentation itself: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html A: The sample method selects a part of data, you can shuffle the data first by passing a seed value. train = df.sample(frac=0.8, random_state=42) For test set you can drop the rows through indexes of train DF and then reset the index of new DF. test = df.drop(train_data.index).reset_index(drop=True) A: Split df into train, validate, test. Given a df of augmented data, select only the dependent and independent columns. Assign 10% of most recent rows (using 'dates' column) to test_df. Randomly assign 10% of remaining rows to validate_df with rest being assigned to train_df. Do not reindex. Check that all rows are uniquely assigned. Use only native python and pandas libs. Method 1: Split rows into train, validate, test dataframes. train_df = augmented_df[dependent_and_independent_columns] test_df = train_df.sort_values('dates').tail(int(len(augmented_df)*0.1)) # select latest 10% of dates for test data train_df = train_df.drop(test_df.index) # drop rows assigned to test_df validate_df = train_df.sample(frac=0.1) # randomly assign 10% train_df = train_df.drop(validate_df.index) # drop rows assigned to validate_df assert len(augmented_df) == len(set(train_df.index).union(validate_df.index).union(test_df.index)) # every row must be uniquely assigned to a df Method 2: Split rows when validate must be subset of train (fastai) train_validate_test_df = augmented_df[dependent_and_independent_columns] test_df = train_validate_test_df.loc[augmented_df.sort_values('dates').tail(int(len(augmented_df)*0.1)).index] # select latest 10% of dates for test data train_validate_df = train_validate_test_df.drop(test_df.index) # drop rows assigned to test_df validate_df = train_validate_df.sample(frac=validate_ratio) # assign 10% to validate_df train_df = train_validate_df.drop(validate_df.index) # drop rows assigned to validate_df assert len(augmented_df) == len(set(train_df.index).union(validate_df.index).union(test_df.index)) # every row must be uniquely assigned to a df # fastai example usage dls = fastai.tabular.all.TabularDataLoaders.from_df( train_validate_df, valid_idx=train_validate_df.index.get_indexer_for(validate_df.index))
How do I create test and train samples from one dataframe with pandas?
I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing. Thanks!
[ "Scikit Learn's train_test_split is a good one. It will split both numpy arrays and dataframes.\nfrom sklearn.model_selection import train_test_split\n\ntrain, test = train_test_split(df, test_size=0.2)\n\n", "I would just use numpy's randn:\nIn [11]: df = pd.DataFrame(np.random.randn(100, 2))\n\nIn [12]: msk = np.random.rand(len(df)) < 0.8\n\nIn [13]: train = df[msk]\n\nIn [14]: test = df[~msk]\n\nAnd just to see this has worked:\nIn [15]: len(test)\nOut[15]: 21\n\nIn [16]: len(train)\nOut[16]: 79\n\n", "Pandas random sample will also work\ntrain=df.sample(frac=0.8,random_state=200)\ntest=df.drop(train.index)\n\nFor the same random_state value you will always get the same exact data in the training and test set. This brings in some level of repeatability while also randomly separating training and test data.\n", "I would use scikit-learn's own training_test_split, and generate it from the index\nfrom sklearn.model_selection import train_test_split\n\n\ny = df.pop('output')\nX = df\n\nX_train,X_test,y_train,y_test = train_test_split(X.index,y,test_size=0.2)\nX.iloc[X_train] # return dataframe train\n\n", "There are many ways to create a train/test and even validation samples.\nCase 1: classic way train_test_split without any options:\nfrom sklearn.model_selection import train_test_split\ntrain, test = train_test_split(df, test_size=0.3)\n\nCase 2: case of a very small datasets (<500 rows): in order to get results for all your lines with this cross-validation. At the end, you will have one prediction for each line of your available training set.\nfrom sklearn.model_selection import KFold\nkf = KFold(n_splits=10, random_state=0)\ny_hat_all = []\nfor train_index, test_index in kf.split(X, y):\n reg = RandomForestRegressor(n_estimators=50, random_state=0)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n clf = reg.fit(X_train, y_train)\n y_hat = clf.predict(X_test)\n y_hat_all.append(y_hat)\n\nCase 3a: Unbalanced datasets for classification purpose. Following the case 1, here is the equivalent solution:\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.3)\n\nCase 3b: Unbalanced datasets for classification purpose. Following the case 2, here is the equivalent solution:\nfrom sklearn.model_selection import StratifiedKFold\nkf = StratifiedKFold(n_splits=10, random_state=0)\ny_hat_all = []\nfor train_index, test_index in kf.split(X, y):\n reg = RandomForestRegressor(n_estimators=50, random_state=0)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n clf = reg.fit(X_train, y_train)\n y_hat = clf.predict(X_test)\n y_hat_all.append(y_hat)\n\nCase 4: you need to create a train/test/validation sets on big data to tune hyperparameters (60% train, 20% test and 20% val).\nfrom sklearn.model_selection import train_test_split\nX_train, X_test_val, y_train, y_test_val = train_test_split(X, y, test_size=0.6)\nX_test, X_val, y_test, y_val = train_test_split(X_test_val, y_test_val, stratify=y, test_size=0.5)\n\n", "No need to convert to numpy. Just use a pandas df to do the split and it will return a pandas df.\nfrom sklearn.model_selection import train_test_split\n\ntrain, test = train_test_split(df, test_size=0.2)\n\nAnd if you want to split x from y\nX_train, X_test, y_train, y_test = train_test_split(df[list_of_x_cols], df[y_col],test_size=0.2)\n\n\nAnd if you want to split the whole df\nX, y = df[list_of_x_cols], df[y_col]\n\n", "You can use below code to create test and train samples :\nfrom sklearn.model_selection import train_test_split\ntrainingSet, testSet = train_test_split(df, test_size=0.2)\n\nTest size can vary depending on the percentage of data you want to put in your test and train dataset.\n", "There are many valid answers. Adding one more to the bunch.\nfrom sklearn.cross_validation import train_test_split\n#gets a random 80% of the entire set\nX_train = X.sample(frac=0.8, random_state=1)\n#gets the left out portion of the dataset\nX_test = X.loc[~df_model.index.isin(X_train.index)]\n\n", "You may also consider stratified division into training and testing set. Startified division also generates training and testing set randomly but in such a way that original class proportions are preserved. This makes training and testing sets better reflect the properties of the original dataset.\nimport numpy as np \n\ndef get_train_test_inds(y,train_proportion=0.7):\n '''Generates indices, making random stratified split into training set and testing sets\n with proportions train_proportion and (1-train_proportion) of initial sample.\n y is any iterable indicating classes of each observation in the sample.\n Initial proportions of classes inside training and \n testing sets are preserved (stratified sampling).\n '''\n\n y=np.array(y)\n train_inds = np.zeros(len(y),dtype=bool)\n test_inds = np.zeros(len(y),dtype=bool)\n values = np.unique(y)\n for value in values:\n value_inds = np.nonzero(y==value)[0]\n np.random.shuffle(value_inds)\n n = int(train_proportion*len(value_inds))\n\n train_inds[value_inds[:n]]=True\n test_inds[value_inds[n:]]=True\n\n return train_inds,test_inds\n\ndf[train_inds] and df[test_inds] give you the training and testing sets of your original DataFrame df.\n", "You can use ~ (tilde operator) to exclude the rows sampled using df.sample(), letting pandas alone handle sampling and filtering of indexes, to obtain two sets.\ntrain_df = df.sample(frac=0.8, random_state=100)\ntest_df = df[~df.index.isin(train_df.index)]\n\n", "If you need to split your data with respect to the lables column in your data set you can use this:\ndef split_to_train_test(df, label_column, train_frac=0.8):\n train_df, test_df = pd.DataFrame(), pd.DataFrame()\n labels = df[label_column].unique()\n for lbl in labels:\n lbl_df = df[df[label_column] == lbl]\n lbl_train_df = lbl_df.sample(frac=train_frac)\n lbl_test_df = lbl_df.drop(lbl_train_df.index)\n print '\\n%s:\\n---------\\ntotal:%d\\ntrain_df:%d\\ntest_df:%d' % (lbl, len(lbl_df), len(lbl_train_df), len(lbl_test_df))\n train_df = train_df.append(lbl_train_df)\n test_df = test_df.append(lbl_test_df)\n\n return train_df, test_df\n\nand use it:\ntrain, test = split_to_train_test(data, 'class', 0.7)\n\nyou can also pass random_state if you want to control the split randomness or use some global random seed.\n", "To split into more than two classes such as train, test, and validation, one can do:\nprobs = np.random.rand(len(df))\ntraining_mask = probs < 0.7\ntest_mask = (probs>=0.7) & (probs < 0.85)\nvalidatoin_mask = probs >= 0.85\n\n\ndf_training = df[training_mask]\ndf_test = df[test_mask]\ndf_validation = df[validatoin_mask]\n\nThis will put approximately 70% of data in training, 15% in test, and 15% in validation.\n", "shuffle = np.random.permutation(len(df))\ntest_size = int(len(df) * 0.2)\ntest_aux = shuffle[:test_size]\ntrain_aux = shuffle[test_size:]\nTRAIN_DF =df.iloc[train_aux]\nTEST_DF = df.iloc[test_aux]\n\n", "Just select range row from df like this\nrow_count = df.shape[0]\nsplit_point = int(row_count*1/5)\ntest_data, train_data = df[:split_point], df[split_point:]\n\n", "import pandas as pd\n\nfrom sklearn.model_selection import train_test_split\n\ndatafile_name = 'path_to_data_file'\n\ndata = pd.read_csv(datafile_name)\n\ntarget_attribute = data['column_name']\n\nX_train, X_test, y_train, y_test = train_test_split(data, target_attribute, test_size=0.8)\n\n", "This is what I wrote when I needed to split a DataFrame. I considered using Andy's approach above, but didn't like that I could not control the size of the data sets exactly (i.e., it would be sometimes 79, sometimes 81, etc.).\ndef make_sets(data_df, test_portion):\n import random as rnd\n\n tot_ix = range(len(data_df))\n test_ix = sort(rnd.sample(tot_ix, int(test_portion * len(data_df))))\n train_ix = list(set(tot_ix) ^ set(test_ix))\n\n test_df = data_df.ix[test_ix]\n train_df = data_df.ix[train_ix]\n\n return train_df, test_df\n\n\ntrain_df, test_df = make_sets(data_df, 0.2)\ntest_df.head()\n\n", "There are many great answers above so I just wanna add one more example in the case that you want to specify the exact number of samples for the train and test sets by using just the numpy library.\n# set the random seed for the reproducibility\nnp.random.seed(17)\n\n# e.g. number of samples for the training set is 1000\nn_train = 1000\n\n# shuffle the indexes\nshuffled_indexes = np.arange(len(data_df))\nnp.random.shuffle(shuffled_indexes)\n\n# use 'n_train' samples for training and the rest for testing\ntrain_ids = shuffled_indexes[:n_train]\ntest_ids = shuffled_indexes[n_train:]\n\ntrain_data = data_df.iloc[train_ids]\ntrain_labels = labels_df.iloc[train_ids]\n\ntest_data = data_df.iloc[test_ids]\ntest_labels = data_df.iloc[test_ids]\n\n", "if you want to split it to train, test and validation set you can use this function:\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\n\ndef train_test_val_split(df, test_size=0.15, val_size=0.45):\n temp, test = train_test_split(df, test_size=test_size)\n total_items_count = len(df.index)\n val_length = total_items_count * val_size\n new_val_propotion = val_length / len(temp.index) \n train, val = train_test_split(temp, test_size=new_val_propotion)\n return train, test, val\n\n", "If your wish is to have one dataframe in and two dataframes out (not numpy arrays), this should do the trick:\ndef split_data(df, train_perc = 0.8):\n\n df['train'] = np.random.rand(len(df)) < train_perc\n\n train = df[df.train == 1]\n\n test = df[df.train == 0]\n\n split_data ={'train': train, 'test': test}\n\n return split_data\n\n", "I think you also need to a get a copy not a slice of dataframe if you wanna add columns later.\nmsk = np.random.rand(len(df)) < 0.8\ntrain, test = df[msk].copy(deep = True), df[~msk].copy(deep = True)\n\n", "You can make use of df.as_matrix() function and create Numpy-array and pass it.\nY = df.pop()\nX = df.as_matrix()\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2)\nmodel.fit(x_train, y_train)\nmodel.test(x_test)\n\n", "A bit more elegant to my taste is to create a random column and then split by it, this way we can get a split that will suit our needs and will be random. \ndef split_df(df, p=[0.8, 0.2]):\nimport numpy as np\ndf[\"rand\"]=np.random.choice(len(p), len(df), p=p)\nr = [df[df[\"rand\"]==val] for val in df[\"rand\"].unique()]\nreturn r\n\n", "you need to convert pandas dataframe into numpy array and then convert numpy array back to dataframe \n import pandas as pd\ndf=pd.read_csv('/content/drive/My Drive/snippet.csv', sep='\\t')\nfrom sklearn.model_selection import train_test_split\n\ntrain, test = train_test_split(df, test_size=0.2)\ntrain1=pd.DataFrame(train)\ntest1=pd.DataFrame(test)\ntrain1.to_csv('/content/drive/My Drive/train.csv',sep=\"\\t\",header=None, encoding='utf-8', index = False)\ntest1.to_csv('/content/drive/My Drive/test.csv',sep=\"\\t\",header=None, encoding='utf-8', index = False)\n\n", "In my case, I wanted to split a data frame in Train, test and dev with a specific number. Here I am sharing my solution\nFirst, assign a unique id to a dataframe (if already not exist)\nimport uuid\ndf['id'] = [uuid.uuid4() for i in range(len(df))]\n\nHere are my split numbers:\ntrain = 120765\ntest = 4134\ndev = 2816\n\nThe split function\ndef df_split(df, n):\n \n first = df.sample(n)\n second = df[~df.id.isin(list(first['id']))]\n first.reset_index(drop=True, inplace = True)\n second.reset_index(drop=True, inplace = True)\n return first, second\n\nNow splitting into train, test, dev\ntrain, test = df_split(df, 120765)\ntest, dev = df_split(test, 4134)\n\n", "How about this?\ndf is my dataframe\ntotal_size=len(df)\n\ntrain_size=math.floor(0.66*total_size) (2/3 part of my dataset)\n\n#training dataset\ntrain=df.head(train_size)\n#test dataset\ntest=df.tail(len(df) -train_size)\n\n", "I would use K-fold cross validation.\nIt's been proven to give much better results than the train_test_split Here's an article on how to apply it with sklearn from the documentation itself: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html\n", "The sample method selects a part of data, you can shuffle the data first by passing a seed value.\ntrain = df.sample(frac=0.8, random_state=42)\n\nFor test set you can drop the rows through indexes of train DF and then reset the index of new DF.\ntest = df.drop(train_data.index).reset_index(drop=True)\n\n", "Split df into train, validate, test. Given a df of augmented data, select only the dependent and independent columns. Assign 10% of most recent rows (using 'dates' column) to test_df. Randomly assign 10% of remaining rows to validate_df with rest being assigned to train_df. Do not reindex. Check that all rows are uniquely assigned. Use only native python and pandas libs.\nMethod 1: Split rows into train, validate, test dataframes.\ntrain_df = augmented_df[dependent_and_independent_columns]\ntest_df = train_df.sort_values('dates').tail(int(len(augmented_df)*0.1)) # select latest 10% of dates for test data\ntrain_df = train_df.drop(test_df.index) # drop rows assigned to test_df\nvalidate_df = train_df.sample(frac=0.1) # randomly assign 10%\ntrain_df = train_df.drop(validate_df.index) # drop rows assigned to validate_df\nassert len(augmented_df) == len(set(train_df.index).union(validate_df.index).union(test_df.index)) # every row must be uniquely assigned to a df\n\nMethod 2: Split rows when validate must be subset of train (fastai)\ntrain_validate_test_df = augmented_df[dependent_and_independent_columns]\ntest_df = train_validate_test_df.loc[augmented_df.sort_values('dates').tail(int(len(augmented_df)*0.1)).index] # select latest 10% of dates for test data\ntrain_validate_df = train_validate_test_df.drop(test_df.index) # drop rows assigned to test_df\nvalidate_df = train_validate_df.sample(frac=validate_ratio) # assign 10% to validate_df\ntrain_df = train_validate_df.drop(validate_df.index) # drop rows assigned to validate_df\nassert len(augmented_df) == len(set(train_df.index).union(validate_df.index).union(test_df.index)) # every row must be uniquely assigned to a df\n# fastai example usage\ndls = fastai.tabular.all.TabularDataLoaders.from_df(\ntrain_validate_df, valid_idx=train_validate_df.index.get_indexer_for(validate_df.index))\n\n" ]
[ 916, 469, 391, 42, 27, 26, 15, 8, 6, 6, 5, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_2.7" ]
stackoverflow_0024147278_dataframe_pandas_python_python_2.7.txt
Q: Is there a way to find the directory of a file that imports another? I am looking for a way to find the directory of a file that imports another. This most likely seems very unspecific so, I am going to try to fix that. Lets say we have a file in a directory named "library.py", and we have another file named "main.py." If in main.py, you import library.py, is the a way to call a function that is in main.py from library.py, or is there a way to get the directory to main.py. Either way works. main.py: import library def saysom(): print("something") library.dosumthing() saysom() library.py: def dosumthing(): #calls a function from main.py without importing main A: in your main.py file do this import os import library print(os.path.abspath(library.__file__)) this will give you the directory to the library.py file
Is there a way to find the directory of a file that imports another?
I am looking for a way to find the directory of a file that imports another. This most likely seems very unspecific so, I am going to try to fix that. Lets say we have a file in a directory named "library.py", and we have another file named "main.py." If in main.py, you import library.py, is the a way to call a function that is in main.py from library.py, or is there a way to get the directory to main.py. Either way works. main.py: import library def saysom(): print("something") library.dosumthing() saysom() library.py: def dosumthing(): #calls a function from main.py without importing main
[ "in your main.py file do this\nimport os\nimport library\n\nprint(os.path.abspath(library.__file__))\n\nthis will give you the directory to the library.py file\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074496928_python.txt
Q: How to add error bars to a grouped bar plot? I would like to add error bar in my plot that I can show the min max of each plot. Please, anyone can help me. Thanks in advance. The min max is as follow: Delay = (53.46 (min 0, max60) , 36.22 (min 12,max 70), 83 (min 21,max 54), 17 (min 12,max 70)) Latency = (38 (min 2,max 70), 44 (min 12,max 87), 53 (min 9,max 60), 10 (min 11,max 77)) import matplotlib.pyplot as plt import pandas as pd from pandas import DataFrame from matplotlib.dates import date2num import datetime Delay = (53.46, 36.22, 83, 17) Latency = (38, 44, 53, 10) index = ['T=0', 'T=26', 'T=50','T=900'] df = pd.DataFrame({'Delay': Delay, 'Latency': Latency}, index=index) ax = df.plot.bar(rot=0) plt.xlabel('Time') plt.ylabel('(%)') plt.ylim(0, 101) plt.savefig('TestX.png', dpi=300, bbox_inches='tight') plt.show() A: In order to plot in the correct location on a bar plot, the patch data for each bar must be extracted. An ndarray is returned with one matplotlib.axes.Axes per column. In the case of this figure, ax.patches contains 8 matplotlib.patches.Rectangle objects, one for each segment of each bar. By using the associated methods for this object, the height, width, and x locations can be extracted, and used to draw a line with plt.vlines. The height of the bar is used to extract the correct min and max value from dict, z. Unfortunately, the patch data does not contain the bar label (e.g. Delay & Latency). import pandas as pd import matplotlib.pyplot as plt # create dataframe Delay = (53.46, 36.22, 83, 17) Latency = (38, 44, 53, 10) index = ['T=0', 'T=26', 'T=50','T=900'] df = pd.DataFrame({'Delay': Delay, 'Latency': Latency}, index=index) # dicts with errors Delay_error = {53.46: {'min': 0,'max': 60}, 36.22: {'min': 12,'max': 70}, 83: {'min': 21,'max': 54}, 17: {'min': 12,'max': 70}} Latency_error = {38: {'min': 2, 'max': 70}, 44: {'min': 12,'max': 87}, 53: {'min': 9,'max': 60}, 10: {'min': 11,'max': 77}} # combine them; providing all the keys are unique z = {**Delay_error, **Latency_error} # plot ax = df.plot.bar(rot=0) plt.xlabel('Time') plt.ylabel('(%)') plt.ylim(0, 101) for p in ax.patches: x = p.get_x() # get the bottom left x corner of the bar w = p.get_width() # get width of bar h = p.get_height() # get height of bar min_y = z[h]['min'] # use h to get min from dict z max_y = z[h]['max'] # use h to get max from dict z plt.vlines(x+w/2, min_y, max_y, color='k') # draw a vertical line If there are non-unique values in the two dicts, so they can't be combined, we can select the correct dict based on the bar plot order. All the bars for a single label are plotted first. In this case, index 0-3 are the Dalay bars, and 4-7 are the Latency bars for i, p in enumerate(ax.patches): print(i, p) x = p.get_x() w = p.get_width() h = p.get_height() if i < len(ax.patches)/2: # select which dictionary to use d = Delay_error else: d = Latency_error min_y = d[h]['min'] max_y = d[h]['max'] plt.vlines(x+w/2, min_y, max_y, color='k') A: Some zipping and stacking will suffice—see bar_min_maxs below. Simplifying and slightly generalizing Trenton's code: import matplotlib.pyplot as plt import numpy as np import pandas as pd # create dataframe Delay = (53.46, 36.22, 83, 17) Latency = (38, 44, 53, 10) index = ['T=0', 'T=26', 'T=50','T=900'] df = pd.DataFrame({'Delay': Delay, 'Latency': Latency, 'Delay_min': (0, 12, 21, 12), # supply min and max 'Delay_max': (60, 70, 54, 70), 'Latency_min': (2, 12, 9, 11), 'Latency_max': (70, 87, 60, 77)}, index=index) # plot ax = df[['Delay', 'Latency']].plot.bar(rot=0) plt.xlabel('Time') plt.ylabel('(%)') plt.ylim(0, 101) # bar_min_maxs[i] is bar/patch i's min, max bar_min_maxs = np.vstack((list(zip(df['Delay_min'], df['Delay_max'])), list(zip(df['Latency_min'], df['Latency_max'])))) assert len(bar_min_maxs) == len(ax.patches) for p, (min_y, max_y) in zip(ax.patches, bar_min_maxs): plt.vlines(p.get_x() + p.get_width()/2, min_y, max_y, color='k') And if errorbars are expressed through margins of errors instead of mins and maxs, i.e., the errorbar is centered at the bar's height w/ length 2 x margin of error, then here's code to plot those: import matplotlib.pyplot as plt import numpy as np import pandas as pd # create dataframe Delay = (53.46, 36.22, 83, 17) Latency = (38, 44, 53, 10) index = ['T=0', 'T=26', 'T=50','T=900'] df = pd.DataFrame({'Delay': Delay, 'Latency': Latency, 'Delay_moe': (5, 15, 25, 35), # supply margin of error 'Latency_moe': (10, 20, 30, 40)}, index=index) # plot ax = df[['Delay', 'Latency']].plot.bar(rot=0) plt.xlabel('Time') plt.ylabel('(%)') plt.ylim(0, 101) # bar_moes[i] is bar/patch i's margin of error, i.e., half the length of an # errorbar centered at the bar's height bar_moes = np.ravel(df[['Delay_moe', 'Latency_moe']].values.T) assert len(bar_moes) == len(ax.patches) for p, moe in zip(ax.patches, bar_moes): height = p.get_height() # of bar min_y, max_y = height - moe, height + moe plt.vlines(p.get_x() + p.get_width()/2, min_y, max_y, color='k')
How to add error bars to a grouped bar plot?
I would like to add error bar in my plot that I can show the min max of each plot. Please, anyone can help me. Thanks in advance. The min max is as follow: Delay = (53.46 (min 0, max60) , 36.22 (min 12,max 70), 83 (min 21,max 54), 17 (min 12,max 70)) Latency = (38 (min 2,max 70), 44 (min 12,max 87), 53 (min 9,max 60), 10 (min 11,max 77)) import matplotlib.pyplot as plt import pandas as pd from pandas import DataFrame from matplotlib.dates import date2num import datetime Delay = (53.46, 36.22, 83, 17) Latency = (38, 44, 53, 10) index = ['T=0', 'T=26', 'T=50','T=900'] df = pd.DataFrame({'Delay': Delay, 'Latency': Latency}, index=index) ax = df.plot.bar(rot=0) plt.xlabel('Time') plt.ylabel('(%)') plt.ylim(0, 101) plt.savefig('TestX.png', dpi=300, bbox_inches='tight') plt.show()
[ "\nIn order to plot in the correct location on a bar plot, the patch data for each bar must be extracted.\nAn ndarray is returned with one matplotlib.axes.Axes per column.\n\nIn the case of this figure, ax.patches contains 8 matplotlib.patches.Rectangle objects, one for each segment of each bar.\n\nBy using the associated methods for this object, the height, width, and x locations can be extracted, and used to draw a line with plt.vlines.\n\n\n\n\nThe height of the bar is used to extract the correct min and max value from dict, z.\n\nUnfortunately, the patch data does not contain the bar label (e.g. Delay & Latency).\n\n\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# create dataframe\nDelay = (53.46, 36.22, 83, 17)\nLatency = (38, 44, 53, 10)\nindex = ['T=0', 'T=26', 'T=50','T=900']\ndf = pd.DataFrame({'Delay': Delay, 'Latency': Latency}, index=index)\n\n# dicts with errors\nDelay_error = {53.46: {'min': 0,'max': 60}, 36.22: {'min': 12,'max': 70}, 83: {'min': 21,'max': 54}, 17: {'min': 12,'max': 70}}\nLatency_error = {38: {'min': 2, 'max': 70}, 44: {'min': 12,'max': 87}, 53: {'min': 9,'max': 60}, 10: {'min': 11,'max': 77}}\n\n# combine them; providing all the keys are unique\nz = {**Delay_error, **Latency_error}\n\n# plot\nax = df.plot.bar(rot=0)\nplt.xlabel('Time')\nplt.ylabel('(%)')\nplt.ylim(0, 101)\n\nfor p in ax.patches:\n x = p.get_x() # get the bottom left x corner of the bar\n w = p.get_width() # get width of bar\n h = p.get_height() # get height of bar\n min_y = z[h]['min'] # use h to get min from dict z\n max_y = z[h]['max'] # use h to get max from dict z\n plt.vlines(x+w/2, min_y, max_y, color='k') # draw a vertical line\n\n\n\nIf there are non-unique values in the two dicts, so they can't be combined, we can select the correct dict based on the bar plot order.\nAll the bars for a single label are plotted first.\n\nIn this case, index 0-3 are the Dalay bars, and 4-7 are the Latency bars\n\n\n\nfor i, p in enumerate(ax.patches):\n print(i, p)\n x = p.get_x()\n w = p.get_width()\n h = p.get_height()\n \n if i < len(ax.patches)/2: # select which dictionary to use\n d = Delay_error\n else:\n d = Latency_error\n \n min_y = d[h]['min']\n max_y = d[h]['max']\n plt.vlines(x+w/2, min_y, max_y, color='k')\n\n", "Some zipping and stacking will suffice—see bar_min_maxs below. Simplifying and slightly generalizing Trenton's code:\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n# create dataframe\nDelay = (53.46, 36.22, 83, 17)\nLatency = (38, 44, 53, 10)\nindex = ['T=0', 'T=26', 'T=50','T=900']\ndf = pd.DataFrame({'Delay': Delay, 'Latency': Latency,\n 'Delay_min': (0, 12, 21, 12), # supply min and max\n 'Delay_max': (60, 70, 54, 70),\n 'Latency_min': (2, 12, 9, 11),\n 'Latency_max': (70, 87, 60, 77)},\n index=index)\n\n# plot\nax = df[['Delay', 'Latency']].plot.bar(rot=0)\nplt.xlabel('Time')\nplt.ylabel('(%)')\nplt.ylim(0, 101)\n\n# bar_min_maxs[i] is bar/patch i's min, max\nbar_min_maxs = np.vstack((list(zip(df['Delay_min'], df['Delay_max'])),\n list(zip(df['Latency_min'], df['Latency_max']))))\nassert len(bar_min_maxs) == len(ax.patches)\n\nfor p, (min_y, max_y) in zip(ax.patches, bar_min_maxs):\n plt.vlines(p.get_x() + p.get_width()/2,\n min_y, max_y, color='k')\n\n\nAnd if errorbars are expressed through margins of errors instead of mins and maxs, i.e., the errorbar is centered at the bar's height w/ length 2 x margin of error, then here's code to plot those:\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n# create dataframe\nDelay = (53.46, 36.22, 83, 17)\nLatency = (38, 44, 53, 10)\nindex = ['T=0', 'T=26', 'T=50','T=900']\ndf = pd.DataFrame({'Delay': Delay, 'Latency': Latency,\n 'Delay_moe': (5, 15, 25, 35), # supply margin of error\n 'Latency_moe': (10, 20, 30, 40)},\n index=index)\n\n# plot\nax = df[['Delay', 'Latency']].plot.bar(rot=0)\nplt.xlabel('Time')\nplt.ylabel('(%)')\nplt.ylim(0, 101)\n\n# bar_moes[i] is bar/patch i's margin of error, i.e., half the length of an\n# errorbar centered at the bar's height\nbar_moes = np.ravel(df[['Delay_moe', 'Latency_moe']].values.T)\nassert len(bar_moes) == len(ax.patches)\n\nfor p, moe in zip(ax.patches, bar_moes):\n height = p.get_height() # of bar\n min_y, max_y = height - moe, height + moe\n plt.vlines(p.get_x() + p.get_width()/2,\n min_y, max_y, color='k')\n\n\n" ]
[ 3, 0 ]
[]
[]
[ "data_science", "matplotlib", "pandas", "python" ]
stackoverflow_0063866002_data_science_matplotlib_pandas_python.txt
Q: django update database everyday I made a wordlegolf site, www.wordlegolfing.com, where my friends and I play wordle and it tracks our scores daily. I keep track of all the users scores and have a scoreboard shown on the site. If someone forgets to do the wordle that day I currently manually adjust there scores to reflect that but I would like to make it so this is done automatically. I have the site running on heroku currently. Not really looking for exact code but is there something easy to use that could run a program or something that allow me to check if a different field is null each day at midnight and if so save an input I have tried celery and I cant get it to install (wordleenv) kyleflannelly@MacBook-Pro-5 wordlegolfing % pip install django-celery Collecting django-celery Using cached django_celery-3.3.1-py3-none-any.whl (63 kB) Collecting celery<4.0,>=3.1.15 Using cached celery-3.1.26.post2-py2.py3-none-any.whl (526 kB) Requirement already satisfied: django>=1.8 in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from django-celery) (4.1) Requirement already satisfied: pytz>dev in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from celery<4.0,>=3.1.15->django-celery) (2022.2.1) Collecting kombu<3.1,>=3.0.37 Using cached kombu-3.0.37-py2.py3-none-any.whl (240 kB) Collecting billiard<3.4,>=3.3.0.23 Using cached billiard-3.3.0.23.tar.gz (151 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: asgiref<4,>=3.5.2 in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from django>=1.8->django-celery) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from django>=1.8->django-celery) (0.4.2) Collecting amqp<2.0,>=1.4.9 Using cached amqp-1.4.9-py2.py3-none-any.whl (51 kB) Collecting anyjson>=0.3.3 Using cached anyjson-0.3.3.tar.gz (8.3 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [1 lines of output] error in anyjson setup command: use_2to3 is invalid. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. │ exit code: 1 ╰─> [1 lines of output] error in anyjson setup command: use_2to3 is invalid. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. A: You don't need Celery to run a daily job. You do need a script that does what you want. Since you want to interact with the Django database, a custom management command might be your best bet. Once you have a script that does what you want, you can schedule it to run on your preferred schedule, e.g. daily at 2am.
django update database everyday
I made a wordlegolf site, www.wordlegolfing.com, where my friends and I play wordle and it tracks our scores daily. I keep track of all the users scores and have a scoreboard shown on the site. If someone forgets to do the wordle that day I currently manually adjust there scores to reflect that but I would like to make it so this is done automatically. I have the site running on heroku currently. Not really looking for exact code but is there something easy to use that could run a program or something that allow me to check if a different field is null each day at midnight and if so save an input I have tried celery and I cant get it to install (wordleenv) kyleflannelly@MacBook-Pro-5 wordlegolfing % pip install django-celery Collecting django-celery Using cached django_celery-3.3.1-py3-none-any.whl (63 kB) Collecting celery<4.0,>=3.1.15 Using cached celery-3.1.26.post2-py2.py3-none-any.whl (526 kB) Requirement already satisfied: django>=1.8 in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from django-celery) (4.1) Requirement already satisfied: pytz>dev in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from celery<4.0,>=3.1.15->django-celery) (2022.2.1) Collecting kombu<3.1,>=3.0.37 Using cached kombu-3.0.37-py2.py3-none-any.whl (240 kB) Collecting billiard<3.4,>=3.3.0.23 Using cached billiard-3.3.0.23.tar.gz (151 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: asgiref<4,>=3.5.2 in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from django>=1.8->django-celery) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /Users/kyleflannelly/Dev/environments/wordleenv/lib/python3.10/site-packages (from django>=1.8->django-celery) (0.4.2) Collecting amqp<2.0,>=1.4.9 Using cached amqp-1.4.9-py2.py3-none-any.whl (51 kB) Collecting anyjson>=0.3.3 Using cached anyjson-0.3.3.tar.gz (8.3 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [1 lines of output] error in anyjson setup command: use_2to3 is invalid. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. │ exit code: 1 ╰─> [1 lines of output] error in anyjson setup command: use_2to3 is invalid. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output.
[ "You don't need Celery to run a daily job.\nYou do need a script that does what you want. Since you want to interact with the Django database, a custom management command might be your best bet.\nOnce you have a script that does what you want, you can schedule it to run on your preferred schedule, e.g. daily at 2am.\n" ]
[ 0 ]
[]
[]
[ "celery", "django", "heroku", "python" ]
stackoverflow_0074493765_celery_django_heroku_python.txt
Q: 5*2=55 not 10! Why? I want to output 5 * 2 = 10 but python output is 55! How do I resolve this problem? a = 0 b = 2 a = input("a? :") #(get 5 as input) c = a * b print (c) This is my code. when I input a number it repeat same number I entered two times insterd of showing multipiy it. What do I have to do to solve this? A: a is a string, so it will be '5'*2='55' if you want 10, you need to cast a to int. a=int(input()) here is the link to document https://docs.python.org/3/library/functions.html#input
5*2=55 not 10! Why?
I want to output 5 * 2 = 10 but python output is 55! How do I resolve this problem? a = 0 b = 2 a = input("a? :") #(get 5 as input) c = a * b print (c) This is my code. when I input a number it repeat same number I entered two times insterd of showing multipiy it. What do I have to do to solve this?
[ "a is a string,\nso it will be\n'5'*2='55'\n\nif you want 10, you need to cast a to int.\na=int(input())\n\nhere is the link to document\nhttps://docs.python.org/3/library/functions.html#input\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074496965_python.txt
Q: tkinter ttk Radiobutton layout - apply padding between indicator and label Is it possible to add a padding between Radiobutton's label and the checkbox? For example I want to move "Option 1" and "Option 2" texts to lower from their checkboxes: screen = Tk() canvas = Canvas(screen, width=600, height=600) canvas.pack() s = ttk.Style() s.layout('TRadiobutton', [('Radiobutton.padding', {'children': [('Radiobutton.indicator', {'side': 'top', 'sticky': 'n'}), ('Radiobutton.focus', {'side': 'left', 'children': [('Radiobutton.label', {'sticky': 'nswe'})], 'sticky': ''})], 'sticky': 'nswe'})]) r = StringVar() r.set(" ") def clicked(value): extension = value.get() rb_1 = ttk.Radiobutton(screen, text="Audio", variable=r, value=".mp3", command= lambda: clicked(r.get())) rb_2 = ttk.Radiobutton(screen, text="Video", variable=r, value=".mp4", command= lambda: clicked(r.get())) canvas.create_window(255, 177, window=rb_1) canvas.create_window(340, 177, window=rb_2) screen.mainloop() A: So basically the trick to simulate what you want is to use ipady which is available for grid and pack. Example: rad_button = ttk.Radiobutton(root, text='abc') rad_button.pack(expand=False, fill=None,ipady=15) Then all you need to do is to stick the parts to the right side with a layout that could look like this: style.layout(style_name, [('Radiobutton.padding', {'sticky': 'nswe', 'children': [ ('Radiobutton.indicator',{'side': 'top', 'sticky': ''}), ('Radiobutton.focus',{'side': 'bottom', 'sticky': '', 'children': [('Radiobutton.label', { 'side': 'left','sticky': ''})]})]})]) Result on Windows 11 with theme default looks like: Be aware that this does not add padding between the two elements, it just sets extra space inside the widget with ipady and sticks them to top and bottom of that space. Update: For canvas you can specify the option height to achieve a similar result with create_window
tkinter ttk Radiobutton layout - apply padding between indicator and label
Is it possible to add a padding between Radiobutton's label and the checkbox? For example I want to move "Option 1" and "Option 2" texts to lower from their checkboxes: screen = Tk() canvas = Canvas(screen, width=600, height=600) canvas.pack() s = ttk.Style() s.layout('TRadiobutton', [('Radiobutton.padding', {'children': [('Radiobutton.indicator', {'side': 'top', 'sticky': 'n'}), ('Radiobutton.focus', {'side': 'left', 'children': [('Radiobutton.label', {'sticky': 'nswe'})], 'sticky': ''})], 'sticky': 'nswe'})]) r = StringVar() r.set(" ") def clicked(value): extension = value.get() rb_1 = ttk.Radiobutton(screen, text="Audio", variable=r, value=".mp3", command= lambda: clicked(r.get())) rb_2 = ttk.Radiobutton(screen, text="Video", variable=r, value=".mp4", command= lambda: clicked(r.get())) canvas.create_window(255, 177, window=rb_1) canvas.create_window(340, 177, window=rb_2) screen.mainloop()
[ "So basically the trick to simulate what you want is to use ipady which is available for grid and pack. Example:\nrad_button = ttk.Radiobutton(root, text='abc')\nrad_button.pack(expand=False, fill=None,ipady=15)\n\nThen all you need to do is to stick the parts to the right side with a layout that could look like this:\nstyle.layout(style_name,\n [('Radiobutton.padding',\n {'sticky': 'nswe', 'children': [\n ('Radiobutton.indicator',{'side': 'top', 'sticky': ''}),\n ('Radiobutton.focus',{'side': 'bottom', 'sticky': '',\n 'children':\n [('Radiobutton.label', {\n 'side': 'left','sticky': ''})]})]})])\n\nResult on Windows 11 with theme default looks like:\n\nBe aware that this does not add padding between the two elements, it just sets extra space inside the widget with ipady and sticks them to top and bottom of that space.\n\nUpdate:\nFor canvas you can specify the option height to achieve a similar result with create_window\n" ]
[ 2 ]
[]
[]
[ "python", "tkinter", "ttk" ]
stackoverflow_0074496540_python_tkinter_ttk.txt
Q: Genetic Algorithm using fixed length vector I am trying to implement a genetic algorithm using fixed-length vectors of real numbers. I found a simple implementation online using a binary encoded values. My confusion arises when I am trying to figure out a way to initialise the array and set the bounds for this algorithm. Below is a snippet of the code with binary decoded code: def decode(bounds, n_bits, bitstring): decoded = list() largest = 2**n_bits for i in range(len(bounds)): # extract the substring start, end = i * n_bits, (i * n_bits)+n_bits substring = bitstring[start:end] # convert bitstring to a string of chars chars = ''.join([str(s) for s in substring]) # convert string to integer integer = int(chars, 2) # scale integer to desired range value = bounds[i][0] + (integer/largest) * (bounds[i][1] - bounds[i][0]) # store decoded.append(value) return decoded Can this be rewritten as an array of real numbers to encode a solution and not a bit string? The full code is from the following article: Simple Genetic Algorithm From Scratch in Python # genetic algorithm search for continuous function optimization from numpy.random import randint from numpy.random import rand # objective function def objective(x): return x[0] ** 2.0 + x[1] ** 2.0 # decode bitstring to numbers def decode(bounds, n_bits, bitstring): decoded = list() largest = 2 ** n_bits for i in range(len(bounds)): # extract the substring start, end = i * n_bits, (i * n_bits) + n_bits substring = bitstring[start:end] # convert bitstring to a string of chars chars = ''.join([str(s) for s in substring]) # convert string to integer integer = int(chars, 2) # scale integer to desired range value = bounds[i][0] + (integer / largest) * (bounds[i][1] - bounds[i][0]) # store decoded.append(value) return decoded # tournament selection def selection(pop, scores, k=3): # first random selection selection_ix = randint(len(pop)) for ix in randint(0, len(pop), k - 1): # check if better (e.g. perform a tournament) if scores[ix] < scores[selection_ix]: selection_ix = ix return pop[selection_ix] # crossover two parents to create two children def crossover(p1, p2, r_cross): # children are copies of parents by default c1, c2 = p1.copy(), p2.copy() # check for recombination if rand() < r_cross: # select crossover point that is not on the end of the string pt = randint(1, len(p1) - 2) # perform crossover c1 = p1[:pt] + p2[pt:] c2 = p2[:pt] + p1[pt:] return [c1, c2] # mutation operator def mutation(bitstring, r_mut): for i in range(len(bitstring)): # check for a mutation if rand() < r_mut: # flip the bit bitstring[i] = 1 - bitstring[i] # genetic algorithm def genetic_algorithm(objective, bounds, n_bits, n_iter, n_pop, r_cross, r_mut): # initial population of random bitstring pop = [randint(0, 2, n_bits * len(bounds)).tolist() for _ in range(n_pop)] # keep track of best solution best, best_eval = 0, objective(decode(bounds, n_bits, pop[0])) # enumerate generations for gen in range(n_iter): # decode population decoded = [decode(bounds, n_bits, p) for p in pop] # evaluate all candidates in the population scores = [objective(d) for d in decoded] # check for new best solution for i in range(n_pop): if scores[i] < best_eval: best, best_eval = pop[i], scores[i] print(">%d, new best f(%s) = %f" % (gen, decoded[i], scores[i])) # select parents selected = [selection(pop, scores) for _ in range(n_pop)] # create the next generation children = list() for i in range(0, n_pop, 2): # get selected parents in pairs p1, p2 = selected[i], selected[i + 1] # crossover and mutation for c in crossover(p1, p2, r_cross): # mutation mutation(c, r_mut) # store for next generation children.append(c) # replace population pop = children return [best, best_eval] # define range for input bounds = [[-5.0, 5.0], [-5.0, 5.0]] # define the total iterations n_iter = 100 # bits per variable n_bits = 16 # define the population size n_pop = 100 # crossover rate r_cross = 0.9 # mutation rate r_mut = 1.0 / (float(n_bits) * len(bounds)) # perform the genetic algorithm search best, score = genetic_algorithm(objective, bounds, n_bits, n_iter, n_pop, r_cross, r_mut) print('Done!') decoded = decode(bounds, n_bits, best) print('f(%s) = %f' % (decoded, score)) A: It appears that you are referencing the code in this article: Simple Genetic Algorithm From Scratch in Python. The bit-vector representation of individuals that is used in the starting code is an encoding of a real-valued vector. If you want your representation of an individual to be a real-valued vector, it means that you don't have do any decoding or encoding at all. Initialize your population to be a vector of random real values within the bounds def genetic_algorithm(objective, bounds, n_iter, n_pop, r_cross, r_mut): # initial population of random real-valued vectors pop = [[random.uniform(bound[0], bound[1]) for bound in bounds] for _ in range(n_pop)] ... Then, in the genetic algorithm itself, there is no need to decode the population, since they are already real-valued vectors. # genetic algorithm def genetic_algorithm(objective, bounds, n_iter, n_pop, r_cross, r_mut): # initial population of random real-valued vectors pop = [[random.uniform(bound[0], bound[1]) for bound in bounds] for _ in range(n_pop)] # keep track of best solution best, best_eval = 0, objective(pop[0]) # enumerate generations for gen in range(n_iter): # evaluate all candidates in the population scores = [objective(d) for d in pop] # check for new best solution for i in range(n_pop): if scores[i] < best_eval: best, best_eval = pop[i], scores[i] print(">%d, new best f(%s) = %f" % (gen, pop[i], scores[i])) # select parents selected = [selection(pop, scores) for _ in range(n_pop)] # create the next generation children = list() for i in range(0, n_pop, 2): # get selected parents in pairs p1, p2 = selected[i], selected[i + 1] # crossover and mutation for c in crossover(p1, p2, r_cross): # mutation mutation(c, r_mut) # store for next generation children.append(c) # replace population pop = children return [best, best_eval] The one thing that remains to be addressed is to modify the mutation and crossover functions so that they operate on real-valued vectors, instead of bit-strings. There are many approaches to how you could implement mutation and cross-over for real-valued vectors; some examples are listed in this StackOverflow post. You have a genome with certain genes: genome = { GeneA: value, GeneB: value, GeneC: value } So take for example: genome = { GeneA: 1, GeneB: 2.5, GeneC: 3.4 } A few examples of mutation could be: Switch around two genes: { GeneA: 1, GeneB: 3.4, GeneC: 2.5 } Add/substract a random value from a gene: { GeneA: 0.9, GeneB: 2.5, GeneC: 3.4 } Suppose you have two genomes: genome1 = { GeneA: 1, GeneB: 2.5, GeneC: 3.4 } genome2 = { GeneA: 0.4, GeneB: 3.5, GeneC: 3.2 } A few examples of crossover could be: Taking the average: { GeneA: 0.7, GeneB: 3.0, GeneC: 3.3 } Uniform (50% chance): { GeneA: 0.4, GeneB: 2.5, GeneC: 3.2 } N-point crossover: { GeneA: 1, | CROSSOVER POINT | GeneB: 3.5, GeneC: 3.2 }
Genetic Algorithm using fixed length vector
I am trying to implement a genetic algorithm using fixed-length vectors of real numbers. I found a simple implementation online using a binary encoded values. My confusion arises when I am trying to figure out a way to initialise the array and set the bounds for this algorithm. Below is a snippet of the code with binary decoded code: def decode(bounds, n_bits, bitstring): decoded = list() largest = 2**n_bits for i in range(len(bounds)): # extract the substring start, end = i * n_bits, (i * n_bits)+n_bits substring = bitstring[start:end] # convert bitstring to a string of chars chars = ''.join([str(s) for s in substring]) # convert string to integer integer = int(chars, 2) # scale integer to desired range value = bounds[i][0] + (integer/largest) * (bounds[i][1] - bounds[i][0]) # store decoded.append(value) return decoded Can this be rewritten as an array of real numbers to encode a solution and not a bit string? The full code is from the following article: Simple Genetic Algorithm From Scratch in Python # genetic algorithm search for continuous function optimization from numpy.random import randint from numpy.random import rand # objective function def objective(x): return x[0] ** 2.0 + x[1] ** 2.0 # decode bitstring to numbers def decode(bounds, n_bits, bitstring): decoded = list() largest = 2 ** n_bits for i in range(len(bounds)): # extract the substring start, end = i * n_bits, (i * n_bits) + n_bits substring = bitstring[start:end] # convert bitstring to a string of chars chars = ''.join([str(s) for s in substring]) # convert string to integer integer = int(chars, 2) # scale integer to desired range value = bounds[i][0] + (integer / largest) * (bounds[i][1] - bounds[i][0]) # store decoded.append(value) return decoded # tournament selection def selection(pop, scores, k=3): # first random selection selection_ix = randint(len(pop)) for ix in randint(0, len(pop), k - 1): # check if better (e.g. perform a tournament) if scores[ix] < scores[selection_ix]: selection_ix = ix return pop[selection_ix] # crossover two parents to create two children def crossover(p1, p2, r_cross): # children are copies of parents by default c1, c2 = p1.copy(), p2.copy() # check for recombination if rand() < r_cross: # select crossover point that is not on the end of the string pt = randint(1, len(p1) - 2) # perform crossover c1 = p1[:pt] + p2[pt:] c2 = p2[:pt] + p1[pt:] return [c1, c2] # mutation operator def mutation(bitstring, r_mut): for i in range(len(bitstring)): # check for a mutation if rand() < r_mut: # flip the bit bitstring[i] = 1 - bitstring[i] # genetic algorithm def genetic_algorithm(objective, bounds, n_bits, n_iter, n_pop, r_cross, r_mut): # initial population of random bitstring pop = [randint(0, 2, n_bits * len(bounds)).tolist() for _ in range(n_pop)] # keep track of best solution best, best_eval = 0, objective(decode(bounds, n_bits, pop[0])) # enumerate generations for gen in range(n_iter): # decode population decoded = [decode(bounds, n_bits, p) for p in pop] # evaluate all candidates in the population scores = [objective(d) for d in decoded] # check for new best solution for i in range(n_pop): if scores[i] < best_eval: best, best_eval = pop[i], scores[i] print(">%d, new best f(%s) = %f" % (gen, decoded[i], scores[i])) # select parents selected = [selection(pop, scores) for _ in range(n_pop)] # create the next generation children = list() for i in range(0, n_pop, 2): # get selected parents in pairs p1, p2 = selected[i], selected[i + 1] # crossover and mutation for c in crossover(p1, p2, r_cross): # mutation mutation(c, r_mut) # store for next generation children.append(c) # replace population pop = children return [best, best_eval] # define range for input bounds = [[-5.0, 5.0], [-5.0, 5.0]] # define the total iterations n_iter = 100 # bits per variable n_bits = 16 # define the population size n_pop = 100 # crossover rate r_cross = 0.9 # mutation rate r_mut = 1.0 / (float(n_bits) * len(bounds)) # perform the genetic algorithm search best, score = genetic_algorithm(objective, bounds, n_bits, n_iter, n_pop, r_cross, r_mut) print('Done!') decoded = decode(bounds, n_bits, best) print('f(%s) = %f' % (decoded, score))
[ "It appears that you are referencing the code in this article: Simple Genetic Algorithm From Scratch in Python.\nThe bit-vector representation of individuals that is used in the starting code is an encoding of a real-valued vector. If you want your representation of an individual to be a real-valued vector, it means that you don't have do any decoding or encoding at all.\nInitialize your population to be a vector of random real values within the bounds\ndef genetic_algorithm(objective, bounds, n_iter, n_pop, r_cross, r_mut):\n # initial population of random real-valued vectors\n pop = [[random.uniform(bound[0], bound[1]) for bound in bounds] for _ in range(n_pop)]\n...\n\nThen, in the genetic algorithm itself, there is no need to decode the population, since they are already real-valued vectors.\n# genetic algorithm\ndef genetic_algorithm(objective, bounds, n_iter, n_pop, r_cross, r_mut):\n # initial population of random real-valued vectors\n pop = [[random.uniform(bound[0], bound[1]) for bound in bounds] for _ in range(n_pop)]\n # keep track of best solution\n best, best_eval = 0, objective(pop[0])\n # enumerate generations\n for gen in range(n_iter):\n # evaluate all candidates in the population\n scores = [objective(d) for d in pop]\n # check for new best solution\n for i in range(n_pop):\n if scores[i] < best_eval:\n best, best_eval = pop[i], scores[i]\n print(\">%d, new best f(%s) = %f\" % (gen, pop[i], scores[i]))\n # select parents\n selected = [selection(pop, scores) for _ in range(n_pop)]\n # create the next generation\n children = list()\n for i in range(0, n_pop, 2):\n # get selected parents in pairs\n p1, p2 = selected[i], selected[i + 1]\n # crossover and mutation\n for c in crossover(p1, p2, r_cross):\n # mutation\n mutation(c, r_mut)\n # store for next generation\n children.append(c)\n # replace population\n pop = children\n return [best, best_eval]\n\nThe one thing that remains to be addressed is to modify the mutation and crossover functions so that they operate on real-valued vectors, instead of bit-strings. There are many approaches to how you could implement mutation and cross-over for real-valued vectors; some examples are listed in this StackOverflow post.\n\nYou have a genome with certain genes:\ngenome = { GeneA: value, GeneB: value, GeneC: value }\n\nSo take for example:\ngenome = { GeneA: 1, GeneB: 2.5, GeneC: 3.4 }\n\nA few examples of mutation could be:\n\nSwitch around two genes: { GeneA: 1, GeneB: 3.4, GeneC: 2.5 }\nAdd/substract a random value from a gene: { GeneA: 0.9, GeneB: 2.5, GeneC: 3.4 } \n\nSuppose you have two genomes:\ngenome1 = { GeneA: 1, GeneB: 2.5, GeneC: 3.4 }\ngenome2 = { GeneA: 0.4, GeneB: 3.5, GeneC: 3.2 }\n\nA few examples of crossover could be:\n\nTaking the average: { GeneA: 0.7, GeneB: 3.0, GeneC: 3.3 }\nUniform (50% chance): { GeneA: 0.4, GeneB: 2.5, GeneC: 3.2 }\nN-point crossover: { GeneA: 1, | CROSSOVER POINT | GeneB: 3.5, GeneC: 3.2 }\n\n\n" ]
[ 1 ]
[]
[]
[ "evolutionary_algorithm", "genetic_algorithm", "python" ]
stackoverflow_0074496593_evolutionary_algorithm_genetic_algorithm_python.txt
Q: Code for the game and there is error in operating Here I want to operate the code in line 14. But is is type error. Can we make remove it making both int or anything. A: Try: sticks_remaining = len(sticks_remaining) - pickup Since, sticks_remaining is a string. Or if you just want the number of | remaining you can do: sticks_remaining = (len(sticks_remaining) - pickup) * '|' A: Line 14 is causing the Type Error. This is because you are trying to subtract an int from a string sticks_remaining = sticks_remaining - pick where pick is an integer. Please refer to this article for a solution How to subtract strings in python
Code for the game and there is error in operating
Here I want to operate the code in line 14. But is is type error. Can we make remove it making both int or anything.
[ "Try:\nsticks_remaining = len(sticks_remaining) - pickup\n\nSince, sticks_remaining is a string.\nOr\nif you just want the number of | remaining you can do:\nsticks_remaining = (len(sticks_remaining) - pickup) * '|'\n\n", "Line 14 is causing the Type Error. This is because you are trying to subtract an int from a string sticks_remaining = sticks_remaining - pick where pick is an integer. Please refer to this article for a solution How to subtract strings in python\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074497027_python.txt
Q: How to find third and fourth max in list? I am trying find the third and fourth max number in a list and then sum them. The solution must be linear O(n). eg: >>> Max_34([1000, 1, 100, 2, 99, 200,100]) 199 Here's what I did: The problem is that it will work for max_34([1,2,3,4]), but it won't work for max_34([1000, 1, 100, 2, 99, 200,100]). Why ? Could someone please correct my code without writing a new one. I really wanna learn from my mistakes. Thanks in advance :) update : Would this be O(n) ? Why ?
How to find third and fourth max in list?
I am trying find the third and fourth max number in a list and then sum them. The solution must be linear O(n). eg: >>> Max_34([1000, 1, 100, 2, 99, 200,100]) 199 Here's what I did: The problem is that it will work for max_34([1,2,3,4]), but it won't work for max_34([1000, 1, 100, 2, 99, 200,100]). Why ? Could someone please correct my code without writing a new one. I really wanna learn from my mistakes. Thanks in advance :) update : Would this be O(n) ? Why ?
[]
[]
[ "The reason your code does not work is because you can not iterate over a list and have it skip values you deleted after you started. The loop iterates over the original list. Here's what I would do instead\ndef removeall(l, item):\n while item in l:\n l.remove(item)\n return l\ndef max_34(a):\n max1 = max(a)\n a = removeall(a, max1)\n max2 = max(a)\n a = removeall(a, max2)\n max3 = max(a)\n a = removeall(a, max3)\n max4 = max(a)\n return (max3 + max4)\n\n", "The following code is linear O(n) and I think is quite nice:\n\n\nfrom __future__ import annotations\n\nfrom typing import List, Union\n\nNumber = Union[int, float]\n\n\ndef upper_maxs(lst, indexers: slice | None = None) -> List | Number:\n \"\"\"Return some max values from list.\n\n Parameters\n ----------\n lst : list\n The list to get the upper maxes from.\n indexers : slice | None\n The indexers to use to get the upper maxes.\n\n Returns\n -------\n list | number\n The greatest elements of the list.\n\n Examples\n --------\n The following examples works like a normal ``max`` call:\n >>> upper_maxs([1, 2, 3, 4, 5])\n 5\n\n To return the three elements with the highest values, you set the\n ``indexers`` parameter to the appropriate slice:\n >>> upper_maxs([1, 2, 3, 4, 5], slice(0, 3))\n [5, 4, 3]\n\n To retrieve the third and fourth highest values, you can set the\n ``indexers`` parameter to ``slice(2, 4)``:\n >>> upper_maxs([1, 2, 3, 4, 5], slice(2, 4))\n [3, 4]\n \"\"\"\n if indexers is None:\n indexers = slice(0, 1)\n return lst[0] if len(lst) == 1 else sorted(lst, reverse=True)[indexers]\n\n\nTo test whether upper_maxs function is actually O(n), I've recorded the\ntime it takes to compute the results for lists ranging from sizes of 1,000,000 elements to 50,000,000 (with increments of 1,000,000 elements). Here's the code I've used to test it:\n\nimport numpy as np\nimport time\n\n\nidxers = slice(2, 4)\nsizes = []\nexecution_times = []\n\nfor size in np.arange(1_000_000, 50_000_001, 1_000_000):\n\n sample_lst = np.random.randint(1, 100, size)\n start_time = time.time()\n upper_maxs(sample_lst, idxers)\n took = time.time() - start_time\n print(\n f\"For a list of size {size:,}, the function took {took:,.2f}s to process.\"\n )\n execution_times.append(took)\n sizes. Append(size)\n\n\nThese were the results I got:\nFor a list of size 1,000,000, the function took 0.37s to process.\nFor a list of size 2,000,000, the function took 0.75s to process.\nFor a list of size 3,000,000, the function took 1.12s to process.\nFor a list of size 4,000,000, the function took 1.50s to process.\nFor a list of size 5,000,000, the function took 1.87s to process.\nFor a list of size 6,000,000, the function took 2.25s to process.\nFor a list of size 7,000,000, the function took 2.67s to process.\nFor a list of size 8,000,000, the function took 3.02s to process.\nFor a list of size 9,000,000, the function took 3.42s to process.\nFor a list of size 10,000,000, the function took 3.79s to process.\nFor a list of size 11,000,000, the function took 4.17s to process.\nFor a list of size 12,000,000, the function took 4.66s to process.\nFor a list of size 13,000,000, the function took 5.03s to process.\nFor a list of size 14,000,000, the function took 5.55s to process.\nFor a list of size 15,000,000, the function took 5.76s to process.\nFor a list of size 16,000,000, the function took 6.20s to process.\nFor a list of size 17,000,000, the function took 6.58s to process.\nFor a list of size 18,000,000, the function took 6.96s to process.\nFor a list of size 19,000,000, the function took 7.43s to process.\nFor a list of size 20,000,000, the function took 8.15s to process.\nFor a list of size 21,000,000, the function took 8.18s to process.\nFor a list of size 22,000,000, the function took 8.50s to process.\nFor a list of size 23,000,000, the function took 8.87s to process.\nFor a list of size 24,000,000, the function took 9.25s to process.\nFor a list of size 25,000,000, the function took 9.78s to process.\nFor a list of size 26,000,000, the function took 10.09s to process.\nFor a list of size 27,000,000, the function took 10.47s to process.\nFor a list of size 28,000,000, the function took 10.94s to process.\nFor a list of size 29,000,000, the function took 11.44s to process.\nFor a list of size 30,000,000, the function took 11.73s to process.\nFor a list of size 31,000,000, the function took 12.07s to process.\nFor a list of size 32,000,000, the function took 12.48s to process.\nFor a list of size 33,000,000, the function took 12.73s to process.\nFor a list of size 34,000,000, the function took 13.22s to process.\nFor a list of size 35,000,000, the function took 13.50s to process.\nFor a list of size 36,000,000, the function took 13.94s to process.\nFor a list of size 37,000,000, the function took 14.32s to process.\nFor a list of size 38,000,000, the function took 14.74s to process.\nFor a list of size 39,000,000, the function took 15.07s to process.\nFor a list of size 40,000,000, the function took 15.45s to process.\nFor a list of size 41,000,000, the function took 15.86s to process.\nFor a list of size 42,000,000, the function took 16.28s to process.\nFor a list of size 43,000,000, the function took 16.64s to process.\nFor a list of size 44,000,000, the function took 17.03s to process.\nFor a list of size 45,000,000, the function took 17.42s to process.\nFor a list of size 46,000,000, the function took 17.96s to process.\nFor a list of size 47,000,000, the function took 18.26s to process.\nFor a list of size 48,000,000, the function took 18.65s to process.\nFor a list of size 49,000,000, the function took 19.16s to process.\nFor a list of size 50,000,000, the function took 19.58s to process.\n\nIf you plot the execution times, and list sizes you'll see that it has indeed O(n) complexity:\n\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(15, 12))\nplt.plot(sizes, execution_times)\nplt.xlabel('List Size (number of elements)', fontsize=16)\nplt.ylabel('Execution Time (seconds)', fontsize=16)\nplt.title('Execution Time x List Size', fontsize=18)\nplt.grid('both')\nplt.show()\n\n\nOutputs:\n\nEdit\nAs per Kelly Bundy suggestion, I've converted the sample_lst\nfrom numpy to list, before calling the function and also increased the upper bound range of the list elements to 10**9 and ran the tests again:\nidxers = slice(2, 4)\nsizes = []\nexecution_times = []\n\nfor size in np.arange(1_000_000, 50_000_001, 1_000_000):\n\n sample_lst = np.random.randint(1, 10**9, size).tolist()\n start_time = time.time()\n upper_maxs(sample_lst, idxers)\n took = time.time() - start_time\n print(\n f\"For a list of size {size:,}, the function took {took:,.2f}s to process.\"\n )\n execution_times.append(took)\n sizes. Append(size)\n\nHere's the results I've got:\nFor a list of size 1,000,000, the function took 0.35s to process.\nFor a list of size 2,000,000, the function took 0.81s to process.\nFor a list of size 3,000,000, the function took 1.30s to process.\nFor a list of size 4,000,000, the function took 1.86s to process.\nFor a list of size 5,000,000, the function took 2.32s to process.\nFor a list of size 6,000,000, the function took 2.94s to process.\nFor a list of size 7,000,000, the function took 3.46s to process.\nFor a list of size 8,000,000, the function took 4.12s to process.\nFor a list of size 9,000,000, the function took 4.63s to process.\nFor a list of size 10,000,000, the function took 5.31s to process.\nFor a list of size 11,000,000, the function took 5.88s to process.\nFor a list of size 12,000,000, the function took 6.56s to process.\nFor a list of size 13,000,000, the function took 7.27s to process.\nFor a list of size 14,000,000, the function took 7.87s to process.\nFor a list of size 15,000,000, the function took 8.40s to process.\nFor a list of size 16,000,000, the function took 9.03s to process.\nFor a list of size 17,000,000, the function took 9.65s to process.\nFor a list of size 18,000,000, the function took 10.27s to process.\nFor a list of size 19,000,000, the function took 11.11s to process.\nFor a list of size 20,000,000, the function took 11.60s to process.\nFor a list of size 21,000,000, the function took 12.21s to process.\nFor a list of size 22,000,000, the function took 12.92s to process.\nFor a list of size 23,000,000, the function took 13.71s to process.\nFor a list of size 24,000,000, the function took 14.42s to process.\nFor a list of size 25,000,000, the function took 15.05s to process.\nFor a list of size 26,000,000, the function took 15.64s to process.\nFor a list of size 27,000,000, the function took 16.38s to process.\nFor a list of size 28,000,000, the function took 16.52s to process.\nFor a list of size 29,000,000, the function took 17.08s to process.\nFor a list of size 30,000,000, the function took 17.50s to process.\nFor a list of size 31,000,000, the function took 18.43s to process.\nFor a list of size 32,000,000, the function took 19.28s to process.\nFor a list of size 33,000,000, the function took 20.09s to process.\nFor a list of size 34,000,000, the function took 20.61s to process.\nFor a list of size 35,000,000, the function took 21.42s to process.\nFor a list of size 36,000,000, the function took 22.03s to process.\nFor a list of size 37,000,000, the function took 23.07s to process.\nFor a list of size 38,000,000, the function took 23.39s to process.\nFor a list of size 39,000,000, the function took 24.12s to process.\nFor a list of size 40,000,000, the function took 24.71s to process.\nFor a list of size 41,000,000, the function took 25.48s to process.\nFor a list of size 42,000,000, the function took 26.13s to process.\nFor a list of size 43,000,000, the function took 26.59s to process.\nFor a list of size 44,000,000, the function took 27.31s to process.\nFor a list of size 45,000,000, the function took 28.17s to process.\nFor a list of size 46,000,000, the function took 28.86s to process.\nFor a list of size 47,000,000, the function took 29.71s to process.\nFor a list of size 48,000,000, the function took 30.11s to process.\nFor a list of size 49,000,000, the function took 31.03s to process.\nFor a list of size 50,000,000, the function took 32.01s to process.\n\nAnd here's the plot of the new execution times vs. list sizes:\n\nto me the plot still seems \"linear O(n)ish\".\n" ]
[ -1, -1 ]
[ "python" ]
stackoverflow_0074496871_python.txt
Q: Adding multiple lines to a strip plot in plotly I would like to add multiple short lines to a strip plot in plotly, preferably in a way that scales to adding more columns/categories. In my actual problem I have quite a few more columns. It would also be awesome if these lines could have their own hover label. I got the first one manually, but for the rest it is/would be hard to manual set each line, especially when there are 10 categories. import plotly.express as px df = px.data.tips() fig = px.strip(df, y="total_bill", x="day") fig.update_layout(shapes=[dict(type='line', x0=.1, y0=30, x1=.15, y1=30, xref='paper', yref='y', line_width=3, line_color='red'), dict(type='line', x0=.4, y0=30, x1=.45, y1=30, xref='paper', yref='y', line_width=3, line_color='red') ]) fig.show() A: Since the content is a boxplot, I will reuse it for the graph of the graph object. What needs a little work is that the boxplot is the x-axis of a categorical variable. The best way to programmatically create a line segment is in the line mode of a scatter plot; to make the x-axis coordinates numerical, I add a new column of code for the categorical variable. Once the x-axis is drawn numerically, the line segment to be added should be before or after the index of that x-axis. You can determine the required width. Finally, update the x-axis with the index of the x-axis and the scale string. import plotly.express as px import plotly.graph_objects as go df = px.data.tips() df['day_code'] = df['day'].astype('category').cat.codes fig1 = px.strip(df, x='day_code', y="total_bill") fig = go.Figure() fig.add_trace(fig1.data[0]) for i in [0,1,2,3]: fig.add_trace(go.Scatter( mode='lines', x=[i-0.1, i+0.1], y=[30,30], hovertemplate='%{y}<extra></extra>', line_color='red', line_width=2, showlegend=False) ) fig.update_xaxes(tickvals=[0,1,2,3], ticktext=df['day'].unique().tolist()) fig.show()
Adding multiple lines to a strip plot in plotly
I would like to add multiple short lines to a strip plot in plotly, preferably in a way that scales to adding more columns/categories. In my actual problem I have quite a few more columns. It would also be awesome if these lines could have their own hover label. I got the first one manually, but for the rest it is/would be hard to manual set each line, especially when there are 10 categories. import plotly.express as px df = px.data.tips() fig = px.strip(df, y="total_bill", x="day") fig.update_layout(shapes=[dict(type='line', x0=.1, y0=30, x1=.15, y1=30, xref='paper', yref='y', line_width=3, line_color='red'), dict(type='line', x0=.4, y0=30, x1=.45, y1=30, xref='paper', yref='y', line_width=3, line_color='red') ]) fig.show()
[ "Since the content is a boxplot, I will reuse it for the graph of the graph object. What needs a little work is that the boxplot is the x-axis of a categorical variable. The best way to programmatically create a line segment is in the line mode of a scatter plot; to make the x-axis coordinates numerical, I add a new column of code for the categorical variable. Once the x-axis is drawn numerically, the line segment to be added should be before or after the index of that x-axis. You can determine the required width. Finally, update the x-axis with the index of the x-axis and the scale string.\nimport plotly.express as px\nimport plotly.graph_objects as go\n\ndf = px.data.tips()\ndf['day_code'] = df['day'].astype('category').cat.codes\nfig1 = px.strip(df, x='day_code', y=\"total_bill\")\n\nfig = go.Figure()\nfig.add_trace(fig1.data[0])\n\nfor i in [0,1,2,3]:\n fig.add_trace(go.Scatter(\n mode='lines',\n x=[i-0.1, i+0.1],\n y=[30,30],\n hovertemplate='%{y}<extra></extra>',\n line_color='red',\n line_width=2,\n showlegend=False)\n )\n\nfig.update_xaxes(tickvals=[0,1,2,3], ticktext=df['day'].unique().tolist())\nfig.show()\n\n\n" ]
[ 0 ]
[]
[]
[ "graphics", "plotly", "plotly_python", "python" ]
stackoverflow_0074495538_graphics_plotly_plotly_python_python.txt
Q: Cannot plot this small dataset after transpose This is my data set after i transpose it. When I try to plot this dataset I get different type of errors based off of the codes I use: when using df.plot("Country Name", "China") I get KeyError: 'Country Name' df.plot.line() Gives KeyError: ('Country Name', 'China') x = dfg1_2_4.iloc[:,0] y = dfg1_2_4.iloc[:,1] plt.scatter(x, y) plt.show() gives 'single positional indexer is out-of-bounds'. anyway to plot line this dataset or fix any of these errors? I think i need to remove the first line of the data set but df = df.reindex(df.index.drop(0)) is not working A: Try df = df.reindex(df.index.drop('Country Name')) then df.plot()
Cannot plot this small dataset after transpose
This is my data set after i transpose it. When I try to plot this dataset I get different type of errors based off of the codes I use: when using df.plot("Country Name", "China") I get KeyError: 'Country Name' df.plot.line() Gives KeyError: ('Country Name', 'China') x = dfg1_2_4.iloc[:,0] y = dfg1_2_4.iloc[:,1] plt.scatter(x, y) plt.show() gives 'single positional indexer is out-of-bounds'. anyway to plot line this dataset or fix any of these errors? I think i need to remove the first line of the data set but df = df.reindex(df.index.drop(0)) is not working
[ "Try\ndf = df.reindex(df.index.drop('Country Name'))\n\nthen\ndf.plot()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "dataset", "pandas", "plot", "python" ]
stackoverflow_0074495748_dataframe_dataset_pandas_plot_python.txt
Q: How to match a string with pythons regex with optional character, but only if that optional character is preceded by another character I need to match a string that optionally ends with numbers, but only if the numbers aren't preceded by a 0. so AAAA should match, AAA1 should, AA20 should, but AA02 should not. I can figure out the optionality of it, but I'm not sure if python has a "preceded by" or "followed by" flag. if s.isalnum() and re.match("^[A-Z]+[1-9][0-9]*$", s): return True A: Try: ^[A-Z]+(?:[1-9][0-9]*)?$ Regex demo. ^[A-Z]+ - match letters from the beginning of string (?:[1-9][0-9]*)? - optionally match a number that doesn't start from 0 $ - end of string
How to match a string with pythons regex with optional character, but only if that optional character is preceded by another character
I need to match a string that optionally ends with numbers, but only if the numbers aren't preceded by a 0. so AAAA should match, AAA1 should, AA20 should, but AA02 should not. I can figure out the optionality of it, but I'm not sure if python has a "preceded by" or "followed by" flag. if s.isalnum() and re.match("^[A-Z]+[1-9][0-9]*$", s): return True
[ "Try:\n^[A-Z]+(?:[1-9][0-9]*)?$\n\nRegex demo.\n\n^[A-Z]+ - match letters from the beginning of string\n(?:[1-9][0-9]*)? - optionally match a number that doesn't start from 0\n$ - end of string\n" ]
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074497079_python_regex.txt
Q: How to connect points on a 3D plot using ax.scatter and ax.plot in Numpy? I have to make a 3D plot with multiple parallel line plots. I can put the points (for three lines) on plot using the following code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits import mplot3d ax = plt.gca(projection ='3d') ax.scatter(0, 0, 100, color = 'red') ax.scatter(0,1,128, color = 'red') ax.scatter(0,2,30, color = 'red') ax.scatter(0,3,15, color = 'red') ax.scatter(1, 0, 100, color = 'blue') ax.scatter(1, 1, 45, color = 'blue') ax.scatter(1,2,13, color = 'blue') ax.scatter(1,3,6, color = 'blue') ax.scatter(2, 0, 100, color = 'green') ax.scatter(2, 1, 55, color = 'green') ax.scatter(2, 2, 27, color = 'green') ax.scatter(2, 3, 26, color = 'green') plt.show() And the result is following: Now I'm stuck with connection of these points with a line (red points with red line, blue points with blue line etc.). I think this can be done with ax.plot? I want to get a 3D plot containing the points connected with segments. I tried to connect points via: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits import mplot3d ax = plt.gca(projection ='3d') p1,p2,p3,p4 = [0,0,100],[0,1,128],[0,2,30],[0,3,15] ax.scatter(p1,p2,p3,p4, c='r',s=10) ax.plot(p1,p2,p3,p4, color='r') plt.show() and I received a nonsense: A: The arguments to ax.plot() should not be the individual points, but the individual dimensions: first a list of all the x-values, then all the y-values, and then all the z-values. You can use the same syntax for ax.scatter(). import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits import mplot3d data = {'red': ([0] * 4, range(4), [100, 128, 30, 15]), 'blue': ([1] * 4, range(4), [100, 45, 13, 6]), 'green': ([2] * 4, range(4), [100, 55, 27, 26])} ax = plt.axes(projection='3d') for color, points in data.items(): ax.scatter(*points, color=color) ax.plot(*points, color=color) plt.show() However, the fact that these lines lie in parallel planes strongly suggests that you don't actually need a 3-dimensional plot. The third dimension is already encoded by the colors, so the 2-dimensional plot loses no information while making it much easier to compare the lines. data = {'red': (range(4), [100, 128, 30, 15]), 'blue': (range(4), [100, 45, 13, 6]), 'green': (range(4), [100, 55, 27, 26])} ax = plt.axes() for color, points in data.items(): ax.scatter(*points, color=color) ax.plot(*points, color=color) plt.show()
How to connect points on a 3D plot using ax.scatter and ax.plot in Numpy?
I have to make a 3D plot with multiple parallel line plots. I can put the points (for three lines) on plot using the following code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits import mplot3d ax = plt.gca(projection ='3d') ax.scatter(0, 0, 100, color = 'red') ax.scatter(0,1,128, color = 'red') ax.scatter(0,2,30, color = 'red') ax.scatter(0,3,15, color = 'red') ax.scatter(1, 0, 100, color = 'blue') ax.scatter(1, 1, 45, color = 'blue') ax.scatter(1,2,13, color = 'blue') ax.scatter(1,3,6, color = 'blue') ax.scatter(2, 0, 100, color = 'green') ax.scatter(2, 1, 55, color = 'green') ax.scatter(2, 2, 27, color = 'green') ax.scatter(2, 3, 26, color = 'green') plt.show() And the result is following: Now I'm stuck with connection of these points with a line (red points with red line, blue points with blue line etc.). I think this can be done with ax.plot? I want to get a 3D plot containing the points connected with segments. I tried to connect points via: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits import mplot3d ax = plt.gca(projection ='3d') p1,p2,p3,p4 = [0,0,100],[0,1,128],[0,2,30],[0,3,15] ax.scatter(p1,p2,p3,p4, c='r',s=10) ax.plot(p1,p2,p3,p4, color='r') plt.show() and I received a nonsense:
[ "The arguments to ax.plot() should not be the individual points, but the individual dimensions: first a list of all the x-values, then all the y-values, and then all the z-values. You can use the same syntax for ax.scatter().\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits import mplot3d\n\ndata = {'red': ([0] * 4,\n range(4),\n [100, 128, 30, 15]),\n 'blue': ([1] * 4,\n range(4),\n [100, 45, 13, 6]),\n 'green': ([2] * 4,\n range(4),\n [100, 55, 27, 26])}\n\nax = plt.axes(projection='3d')\n\nfor color, points in data.items():\n ax.scatter(*points, color=color)\n ax.plot(*points, color=color)\n\nplt.show()\n\n\nHowever, the fact that these lines lie in parallel planes strongly suggests that you don't actually need a 3-dimensional plot. The third dimension is already encoded by the colors, so the 2-dimensional plot loses no information while making it much easier to compare the lines.\ndata = {'red': (range(4),\n [100, 128, 30, 15]),\n 'blue': (range(4),\n [100, 45, 13, 6]),\n 'green': (range(4),\n [100, 55, 27, 26])}\n\nax = plt.axes()\n\nfor color, points in data.items():\n ax.scatter(*points, color=color)\n ax.plot(*points, color=color)\n\nplt.show()\n\n\n" ]
[ 1 ]
[]
[]
[ "plot", "python", "scatter_plot" ]
stackoverflow_0074491620_plot_python_scatter_plot.txt
Q: printing test grades and test score average within functions using python The assignment is to get 5 test score and use them to display the corresponding letter grade and test score average using functions. I don't know if I'm on the right track and I was having trouble calling the other functions within the main function. def main(): s1 = int(input('Enter score one: ')) s2 = int(input('Enter score two: ')) s3 = int(input('Enter score three: ')) s4 = int(input('Enter score four: ')) s5 = int(input('Enter score five: ')) return s1, s2, s3, s4, s5 test_grade = determine_grade(s1, s2, s3, s4, s5) print(test_grade) average_num = calc_average(s1, s2, s3, s4, s5) print(average_num) def calc_average(s1, s2, s3, s4, s5): average = s1 + s2 + s3 +s4 +s5 / 5 return average def determine_grade(s1, s2, s3, s4, s5): if (90 <= s1, s2, s3, s4, s5 <= 100): grade_a = "A" return grade_a elif (80 <= s1, s2, s3, s4, s5 <= 89): grade_b = "B" return grade_b elif (70 <= s1, s2, s3, s4, s5 <= 79): grade_c = "C" return grade_c elif (60 <= s1, s2, s3, s4, s5 <= 69): grade_d = "D" return grade_d elif (s1, s2, s3, s4, s5 < 60): grade_f = "F" return grade_f main() A: return should be at the end of the main function def main(): s1 = int(input('Enter score one: ')) s2 = int(input('Enter score two: ')) s3 = int(input('Enter score three: ')) s4 = int(input('Enter score four: ')) s5 = int(input('Enter score five: ')) test_grade = determine_grade(s1, s2, s3, s4, s5) print(test_grade) average_num = calc_average(s1, s2, s3, s4, s5) print(average_num) return s1, s2, s3, s4, s5 You were missing brackets in average that's why it was giving wrong average def calc_average(s1, s2, s3, s4, s5): average = (s1 + s2 + s3 +s4 +s5) / 5 return average Your if syntax was wrong for comparing all values. def determine_grade(s1, s2, s3, s4, s5): if all(item >= 90 and item <= 100 for item in (s1, s2, s3 ,s4 ,s5)): grade_a = "A" return grade_a elif all(item >= 80 and item <= 89 for item in (s1, s2, s3 ,s4 ,s5)): grade_b = "B" return grade_b elif all(item >= 70 and item <= 79 for item in (s1, s2, s3 ,s4 ,s5)): grade_c = "C" return grade_c elif all(item >= 60 and item <= 69 for item in (s1, s2, s3 ,s4 ,s5)): grade_d = "D" return grade_d else : grade_f = "F" return grade_f main()
printing test grades and test score average within functions using python
The assignment is to get 5 test score and use them to display the corresponding letter grade and test score average using functions. I don't know if I'm on the right track and I was having trouble calling the other functions within the main function. def main(): s1 = int(input('Enter score one: ')) s2 = int(input('Enter score two: ')) s3 = int(input('Enter score three: ')) s4 = int(input('Enter score four: ')) s5 = int(input('Enter score five: ')) return s1, s2, s3, s4, s5 test_grade = determine_grade(s1, s2, s3, s4, s5) print(test_grade) average_num = calc_average(s1, s2, s3, s4, s5) print(average_num) def calc_average(s1, s2, s3, s4, s5): average = s1 + s2 + s3 +s4 +s5 / 5 return average def determine_grade(s1, s2, s3, s4, s5): if (90 <= s1, s2, s3, s4, s5 <= 100): grade_a = "A" return grade_a elif (80 <= s1, s2, s3, s4, s5 <= 89): grade_b = "B" return grade_b elif (70 <= s1, s2, s3, s4, s5 <= 79): grade_c = "C" return grade_c elif (60 <= s1, s2, s3, s4, s5 <= 69): grade_d = "D" return grade_d elif (s1, s2, s3, s4, s5 < 60): grade_f = "F" return grade_f main()
[ "return should be at the end of the main function\ndef main():\n s1 = int(input('Enter score one: '))\n s2 = int(input('Enter score two: '))\n s3 = int(input('Enter score three: '))\n s4 = int(input('Enter score four: '))\n s5 = int(input('Enter score five: '))\n \n \n test_grade = determine_grade(s1, s2, s3, s4, s5)\n print(test_grade)\n \n average_num = calc_average(s1, s2, s3, s4, s5)\n print(average_num)\n return s1, s2, s3, s4, s5\n\nYou were missing brackets in average that's why it was giving wrong average\ndef calc_average(s1, s2, s3, s4, s5):\n average = (s1 + s2 + s3 +s4 +s5) / 5\n return average\n\nYour if syntax was wrong for comparing all values.\ndef determine_grade(s1, s2, s3, s4, s5):\n if all(item >= 90 and item <= 100 for item in (s1, s2, s3 ,s4 ,s5)):\n grade_a = \"A\"\n return grade_a\n elif all(item >= 80 and item <= 89 for item in (s1, s2, s3 ,s4 ,s5)):\n grade_b = \"B\"\n return grade_b\n elif all(item >= 70 and item <= 79 for item in (s1, s2, s3 ,s4 ,s5)):\n grade_c = \"C\"\n return grade_c\n elif all(item >= 60 and item <= 69 for item in (s1, s2, s3 ,s4 ,s5)):\n grade_d = \"D\"\n return grade_d\n else :\n grade_f = \"F\"\n return grade_f\n\nmain()\n\n" ]
[ 0 ]
[]
[]
[ "average", "function", "if_statement", "input", "python" ]
stackoverflow_0074497006_average_function_if_statement_input_python.txt
Q: Python; User Prompts; choose multiple files I would like to have my code bring up a window where you can select multiple files within a folder and it assigns these filenames to elements of a list. Currently, I can only select a single file at a time and it assigns the filename to a single variable. from Tkinter import Tk from tkFileDialog import askopenfilename Tk().withdraw() filename = askopenfilename() Thank you. A: You need to use the askopenfilenames method instead. A: You can encapsulate all that in a function: def get_filename_from_user(message): root = Tk() root.withdraw() filename = tkFileDialog.askopenfilename(title=message) return filename Then you can call it as many times as you like: filename1 = get_filename_from_user('select the first file!') filename2 = get_filename_from_user('select another one!') filename3 = get_filename_from_user('select one more!') Unless you have tons of files you want to select. Then you probably want to use askopenfilenames: files = tkFileDialog.askopenfilenames(parent=root,title='Choose a file or LOTS!')
Python; User Prompts; choose multiple files
I would like to have my code bring up a window where you can select multiple files within a folder and it assigns these filenames to elements of a list. Currently, I can only select a single file at a time and it assigns the filename to a single variable. from Tkinter import Tk from tkFileDialog import askopenfilename Tk().withdraw() filename = askopenfilename() Thank you.
[ "You need to use the askopenfilenames method instead.\n", "You can encapsulate all that in a function:\ndef get_filename_from_user(message):\n root = Tk()\n root.withdraw()\n filename = tkFileDialog.askopenfilename(title=message)\n return filename\n\nThen you can call it as many times as you like:\nfilename1 = get_filename_from_user('select the first file!')\nfilename2 = get_filename_from_user('select another one!')\nfilename3 = get_filename_from_user('select one more!')\n\nUnless you have tons of files you want to select. Then you probably want to use askopenfilenames:\nfiles = tkFileDialog.askopenfilenames(parent=root,title='Choose a file or LOTS!')\n\n" ]
[ 2, 0 ]
[ "from easygui import fileopenbox\nfiles = []\n#how many file you want choice\nfileCount = int(input(\"How many file need open\"))\nfor x in range(fileCount):\n files.append(fileopenbox())\nprint(files)\n\n" ]
[ -1 ]
[ "file", "prompt", "python", "user_interface" ]
stackoverflow_0017958230_file_prompt_python_user_interface.txt
Q: Extract two specified words from the dataframe and place them in a new column, then delete the rows This is the dataframe: data = {"Company" : [["ConsenSys"] , ["Cognizant"], ["IBM"], ["IBM"], ["Reddit, Inc"], ["Reddit, Inc"], ["IBM"]], "skills" : [['services', 'scientist technical expertise', 'databases'], ['datacomputing tools experience', 'deep learning models', 'cloud services'], ['quantitative analytical projects', 'financial services', 'field experience'], ['filesystems server architectures', 'systems', 'statistical analysis', 'data analytics', 'workflows', 'aws cloud services'], ['aws services'], ['data mining statistics', 'statistical analysis', 'aws cloud', 'services', 'data discovery', 'visualization'], ['communication skills experience', 'services', 'manufacturing environment', 'sox compliance']]} dff = pd.DataFrame(data) dff I need to create a new column, and I want to start by taking specific words out of the skills column. The row that does not include those specific words should then be deleted. Specific words: 'services', 'statistical analysis' Expected Output: Company skills new_col 0 [ConsenSys] [services, scientist technical expertise, databases] [services] 1 [IBM] [filesystems server architectures, systems, statistical analysis, data analytics, workflows, aws cloud services] [services, statistical analysis] 2 [Reddit, Inc] [data mining statistics, statistical analysis, aws cloud, services, data discovery, visualization] [statistical analysis] 3 [IBM] ['communication skills experience', 'services', 'manufacturing environment', 'sox compliance'] [services] I tried quite a lot of code in an effort to extract a specific word from the one that was available on Stack Overflow, but I was unsuccessful. A: You can use a lambda with a list comp words = ["services", "statistical analysis"] dff["found"] = dff["skills"].apply(lambda x: ", ".join(set([i for i in x if i in words])).split(", ")) A: word = ['services', 'statistical analysis'] s1 = df['skills'].apply(lambda x: [i for i in word if i in x]) output(s1): 0 [services] 1 [] 2 [] 3 [statistical analysis] 4 [] 5 [services, statistical analysis] 6 [services] Name: skills, dtype: object make s1 to new_col and boolean indexing df.assign(new_col=s1)[lambda x: x['new_col'].astype('bool')] result: Company skills new_col 0 [ConsenSys] [services, scientist technical expertise, data... [services] 3 [IBM] [filesystems server architectures, systems, st... [statistical analysis] 5 [Reddit, Inc] [data mining statistics, statistical analysis,... [services, statistical analysis] 6 [IBM] [communication skills experience, services, ma... [services] i think you should make more simple example
Extract two specified words from the dataframe and place them in a new column, then delete the rows
This is the dataframe: data = {"Company" : [["ConsenSys"] , ["Cognizant"], ["IBM"], ["IBM"], ["Reddit, Inc"], ["Reddit, Inc"], ["IBM"]], "skills" : [['services', 'scientist technical expertise', 'databases'], ['datacomputing tools experience', 'deep learning models', 'cloud services'], ['quantitative analytical projects', 'financial services', 'field experience'], ['filesystems server architectures', 'systems', 'statistical analysis', 'data analytics', 'workflows', 'aws cloud services'], ['aws services'], ['data mining statistics', 'statistical analysis', 'aws cloud', 'services', 'data discovery', 'visualization'], ['communication skills experience', 'services', 'manufacturing environment', 'sox compliance']]} dff = pd.DataFrame(data) dff I need to create a new column, and I want to start by taking specific words out of the skills column. The row that does not include those specific words should then be deleted. Specific words: 'services', 'statistical analysis' Expected Output: Company skills new_col 0 [ConsenSys] [services, scientist technical expertise, databases] [services] 1 [IBM] [filesystems server architectures, systems, statistical analysis, data analytics, workflows, aws cloud services] [services, statistical analysis] 2 [Reddit, Inc] [data mining statistics, statistical analysis, aws cloud, services, data discovery, visualization] [statistical analysis] 3 [IBM] ['communication skills experience', 'services', 'manufacturing environment', 'sox compliance'] [services] I tried quite a lot of code in an effort to extract a specific word from the one that was available on Stack Overflow, but I was unsuccessful.
[ "You can use a lambda with a list comp\nwords = [\"services\", \"statistical analysis\"]\ndff[\"found\"] = dff[\"skills\"].apply(lambda x: \", \".join(set([i for i in x if i in words])).split(\", \"))\n\n", "word = ['services', 'statistical analysis']\ns1 = df['skills'].apply(lambda x: [i for i in word if i in x])\n\noutput(s1):\n0 [services]\n1 []\n2 []\n3 [statistical analysis]\n4 []\n5 [services, statistical analysis]\n6 [services]\nName: skills, dtype: object\n\nmake s1 to new_col and boolean indexing\ndf.assign(new_col=s1)[lambda x: x['new_col'].astype('bool')]\n\nresult:\n Company skills new_col\n0 [ConsenSys] [services, scientist technical expertise, data... [services]\n3 [IBM] [filesystems server architectures, systems, st... [statistical analysis]\n5 [Reddit, Inc] [data mining statistics, statistical analysis,... [services, statistical analysis]\n6 [IBM] [communication skills experience, services, ma... [services]\n\ni think you should make more simple example\n" ]
[ 1, 0 ]
[]
[]
[ "dataframe", "nlp", "pandas", "python" ]
stackoverflow_0074497075_dataframe_nlp_pandas_python.txt
Q: Python rising/falling edge oscilloscope-like trigger I'm trying to detect rising and/or falling edges in a numpy vector, based on a trigger value. This is kinda like how oscilloscope triggering works. The numpy vector contains floating point values. The trigger itself is a floating point value. I would expect this to work as such: import numpy as np data = np.array([-1, -0.5, 0, 0.5, 1, 1.5, 2]) trigger = rising_edge(data, 0.3) print(trigger) [3] In other words, it would work like np.where, returning a vector containing the positions where the condition is true. I know i can simply iterate over the vector and get the same result (which is what i'm doing), but it isn't ideal, as you can imagine. Is there some functionality built into numpy that can do this using optimized C code? Or maybe in some other library? Thank you. A: We could slice one-off and compare against the trigger for smaller than and greater than, like so - In [41]: data = np.array([-1, -0.5, 0, 0.5, 1, 1.5, 2, 0, 0.5]) In [43]: trigger_val = 0.3 In [44]: np.flatnonzero((data[:-1] < trigger_val) & (data[1:] > trigger_val))+1 Out[44]: array([3, 8]) If you would like to include equality as well, i.e. <= or >=, simply add that into the comparison. To include for both rising and falling edges, add the comparison the other way - In [75]: data = np.array([-1, -0.5, 0, 0.5, 1, 1.5, 2, 0.5, 0]) In [76]: trigger_val = 0.3 In [77]: mask1 = (data[:-1] < trigger_val) & (data[1:] > trigger_val) In [78]: mask2 = (data[:-1] > trigger_val) & (data[1:] < trigger_val) In [79]: np.flatnonzero(mask1 | mask2)+1 Out[79]: array([3, 8]) A: So I was just watching the latest 3Blue1Brown video on convolution when I realized a new way of doing this: def rising_edge(data, thresh): sign = data >= thresh pos = np.where(np.convolve(sign, [1, -1]) == 1) return pos So, get all the positions where the data is larger or equal to the threshold, do a convolution over it with [1, -1], and then just find where the convolution returns a 1 for a rising edge. Want a falling edge? Look for -1 instead. Pretty neat, if I do say so myself. And it's about 5-10% faster.
Python rising/falling edge oscilloscope-like trigger
I'm trying to detect rising and/or falling edges in a numpy vector, based on a trigger value. This is kinda like how oscilloscope triggering works. The numpy vector contains floating point values. The trigger itself is a floating point value. I would expect this to work as such: import numpy as np data = np.array([-1, -0.5, 0, 0.5, 1, 1.5, 2]) trigger = rising_edge(data, 0.3) print(trigger) [3] In other words, it would work like np.where, returning a vector containing the positions where the condition is true. I know i can simply iterate over the vector and get the same result (which is what i'm doing), but it isn't ideal, as you can imagine. Is there some functionality built into numpy that can do this using optimized C code? Or maybe in some other library? Thank you.
[ "We could slice one-off and compare against the trigger for smaller than and greater than, like so -\nIn [41]: data = np.array([-1, -0.5, 0, 0.5, 1, 1.5, 2, 0, 0.5])\n\nIn [43]: trigger_val = 0.3\n\nIn [44]: np.flatnonzero((data[:-1] < trigger_val) & (data[1:] > trigger_val))+1\nOut[44]: array([3, 8])\n\nIf you would like to include equality as well, i.e. <= or >=, simply add that into the comparison.\nTo include for both rising and falling edges, add the comparison the other way -\nIn [75]: data = np.array([-1, -0.5, 0, 0.5, 1, 1.5, 2, 0.5, 0])\n\nIn [76]: trigger_val = 0.3\n\nIn [77]: mask1 = (data[:-1] < trigger_val) & (data[1:] > trigger_val)\n\nIn [78]: mask2 = (data[:-1] > trigger_val) & (data[1:] < trigger_val)\n\nIn [79]: np.flatnonzero(mask1 | mask2)+1\nOut[79]: array([3, 8])\n\n", "So I was just watching the latest 3Blue1Brown video on convolution when I realized a new way of doing this:\ndef rising_edge(data, thresh):\n sign = data >= thresh\n pos = np.where(np.convolve(sign, [1, -1]) == 1)\n return pos\n\nSo, get all the positions where the data is larger or equal to the threshold, do a convolution over it with [1, -1], and then just find where the convolution returns a 1 for a rising edge. Want a falling edge? Look for -1 instead.\nPretty neat, if I do say so myself. And it's about 5-10% faster.\n" ]
[ 8, 0 ]
[]
[]
[ "edge_detection", "numpy", "python" ]
stackoverflow_0050365310_edge_detection_numpy_python.txt
Q: How to create list of dictionary from nested list of strings in python? I have dataframe with sparse columns values and I vectorized it, now I want to create key-value dictionary by row-wise. However, I need to create dictionary where column name is key and column value is value by each row of dataframe. How to create such dictionary from my current attempt? any thoughts? approach 1 here is minimal reproducible data that I used: df_dict={'order': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10}, 'code0': {0: nan, 1: " '40'", 2: " '98'", 3: " '98'", 4: " '52'", 5: " '52'", 6: " '52'", 7: " '52'", 8: " '40'", 9: " '58'"}, 'code1': {0: " ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL')", 1: nan, 2: " ('ATT','NC')", 3: " ('ATT','VA','NC')", 4: " 'NC'", 5: " 'NC'", 6: " 'NC'", 7: " 'NC'", 8: " 'VA'", 9: " 'CE'"}, 'code2': {0: nan, 1: nan, 2: " ('103','104','105','106','31')", 3: " ('104','105','106','31')", 4: " '109'", 5: " '109'", 6: " '109'", 7: " '109'", 8: " '11'", 9: " ('109')"}, 'code3': {0: nan, 1: " '518'", 2: " '810'", 3: nan, 4: " ('610','620','682','642','621','611')", 5: " ('396','340','394','393','240')", 6: " ('612','790','110')", 7: " ('730','320','350','379','812','374')", 8: " ('113','174','131','115')", 9: " ('423','114')"}, 'code4': {0: nan, 1: nan, 2: " 'computer science'", 3: " 'computer science'", 4: " 'biology'", 5: " 'biology'", 6: "biology'", 7: "biology'", 8: nan, 9: nan}, 'code5': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: " ('12','18')", 6: " ('12','16','18','19')", 7: " ('12','18','19')", 8: " ('11','19','31')", 9: " '31'"}, 'code6': {0: nan, 1: " '594'", 2: nan, 3: nan, 4: " ('712','479','297','639','452','172')", 5: nan, 6: " ('285','295','236','239','269','284','237')", 7: nan, 8: " ('164','157','388','158')", 9: " ('372','238')"}, 'rules_desc': {0: 'rules1', 1: 'rules2', 2: 'rules2', 3: 'rules2', 4: 'rules2', 5: 'rules2', 6: 'rules2', 7: 'rules2', 8: 'rules2', 9: 'rules2'}} import pandas as pd df1=pd.DataFrame.from_dict(df_dict()) cols = df1.columns.values res=[",".join("{}:{}".format(*t) for t in zip(cols, row)) for _, row in df1[cols].iterrows()] for now I am getting list but needs to have key such as column name as key and column value bounded to it. How can I do this in python? Instead, I tried like this also: res=[df1.iloc[i].astype(str).tolist() for i in range(0, len(df1))] I am getting error when I tried res.to_dict(): AttributeError: 'list' object has no attribute 'to_dict' this is fine, but I need column name assign to it and create dictionary. how can I do this in python? any idea? approach 2: new update - much better but still incorrect cols = df1.columns.values for i in range(0, len(df1)): ss=df1.iloc[i][cols].dropna().astype(str).tolist() # this is good my_dict = {k: cols for k in ss} # doing this incorrect print(my_dict ) but here able to drop the column with nan but don't know how to get correct key which is column name. I think I need somewhere between approach 1 and approach 2, don't know how to get my desired output. any idea? desired output I want to create key-value list for each rows of dataframe, like dictionary. here is my part of my expected output after clean up nan values: {{'order':1, 'code': ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'), 'rules_desc': rules1}, {'order':2, 'code0': 40, 'code3':518, 'code6':594, 'rules_desc': rules2}, {'order':3, 'code0':98, 'code1':('ATT','NC'), 'code2':('103','104','105','106','31'), 'code3':810, 'code4': computer_science, 'rules_desc': rules2}, ... } A: There exists a technical problem that you hope one or more people will solve, possibly including yourself. Here is my current understanding of the problem as presented. The "expected" values apparently don't match your expectation. It would be helpful if you could describe them in code. Maybe you wish to json.loads some of those columns? import json import unittest import pandas as pd from pandas import NA as nan class NestTest(unittest.TestCase): @staticmethod def _get_dictionary(): return { "order": {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10}, "code0": { 0: nan, 1: " '40'", 2: " '98'", 3: " '98'", 4: " '52'", 5: " '52'", 6: " '52'", 7: " '52'", 8: " '40'", 9: " '58'", }, "code1": { 0: " ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL')", 1: nan, 2: " ('ATT','NC')", 3: " ('ATT','VA','NC')", 4: " 'NC'", 5: " 'NC'", 6: " 'NC'", 7: " 'NC'", 8: " 'VA'", 9: " 'CE'", }, "code2": { 0: nan, 1: nan, 2: " ('103','104','105','106','31')", 3: " ('104','105','106','31')", 4: " '109'", 5: " '109'", 6: " '109'", 7: " '109'", 8: " '11'", 9: " ('109')", }, "code3": { 0: nan, 1: " '518'", 2: " '810'", 3: nan, 4: " ('610','620','682','642','621','611')", 5: " ('396','340','394','393','240')", 6: " ('612','790','110')", 7: " ('730','320','350','379','812','374')", 8: " ('113','174','131','115')", 9: " ('423','114')", }, "code4": { 0: nan, 1: nan, 2: " 'computer science'", 3: " 'computer science'", 4: " 'biology'", 5: " 'biology'", 6: "biology'", 7: "biology'", 8: nan, 9: nan, }, "code5": { 0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: " ('12','18')", 6: " ('12','16','18','19')", 7: " ('12','18','19')", 8: " ('11','19','31')", 9: " '31'", }, "code6": { 0: nan, 1: " '594'", 2: nan, 3: nan, 4: " ('712','479','297','639','452','172')", 5: nan, 6: " ('285','295','236','239','269','284','237')", 7: nan, 8: " ('164','157','388','158')", 9: " ('372','238')", }, "rules_desc": { 0: "rules1", 1: "rules2", 2: "rules2", 3: "rules2", 4: "rules2", 5: "rules2", 6: "rules2", 7: "rules2", 8: "rules2", 9: "rules2", }, } def test_how_to_create_list_of_dictionary_from_nested_list_of_strings(self): df1 = pd.DataFrame.from_dict(self._get_dictionary()) df1 = df1[:3] # Let's focus on just a subset, the first 3 rows self.assertEqual( [ { "code0": None, "code1": " ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL')", "code2": None, "code3": None, "code4": None, "code5": None, "code6": None, "order": 1, "rules_desc": "rules1", }, { "code0": " '40'", "code1": None, "code2": None, "code3": " '518'", "code4": None, "code5": None, "code6": " '594'", "order": 2, "rules_desc": "rules2", }, { "code0": " '98'", "code1": " ('ATT','NC')", "code2": " ('103','104','105','106','31')", "code3": " '810'", "code4": " 'computer science'", "code5": None, "code6": None, "order": 3, "rules_desc": "rules2", }, ], json.loads(df1.to_json(orient="records")), )
How to create list of dictionary from nested list of strings in python?
I have dataframe with sparse columns values and I vectorized it, now I want to create key-value dictionary by row-wise. However, I need to create dictionary where column name is key and column value is value by each row of dataframe. How to create such dictionary from my current attempt? any thoughts? approach 1 here is minimal reproducible data that I used: df_dict={'order': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10}, 'code0': {0: nan, 1: " '40'", 2: " '98'", 3: " '98'", 4: " '52'", 5: " '52'", 6: " '52'", 7: " '52'", 8: " '40'", 9: " '58'"}, 'code1': {0: " ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL')", 1: nan, 2: " ('ATT','NC')", 3: " ('ATT','VA','NC')", 4: " 'NC'", 5: " 'NC'", 6: " 'NC'", 7: " 'NC'", 8: " 'VA'", 9: " 'CE'"}, 'code2': {0: nan, 1: nan, 2: " ('103','104','105','106','31')", 3: " ('104','105','106','31')", 4: " '109'", 5: " '109'", 6: " '109'", 7: " '109'", 8: " '11'", 9: " ('109')"}, 'code3': {0: nan, 1: " '518'", 2: " '810'", 3: nan, 4: " ('610','620','682','642','621','611')", 5: " ('396','340','394','393','240')", 6: " ('612','790','110')", 7: " ('730','320','350','379','812','374')", 8: " ('113','174','131','115')", 9: " ('423','114')"}, 'code4': {0: nan, 1: nan, 2: " 'computer science'", 3: " 'computer science'", 4: " 'biology'", 5: " 'biology'", 6: "biology'", 7: "biology'", 8: nan, 9: nan}, 'code5': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan, 5: " ('12','18')", 6: " ('12','16','18','19')", 7: " ('12','18','19')", 8: " ('11','19','31')", 9: " '31'"}, 'code6': {0: nan, 1: " '594'", 2: nan, 3: nan, 4: " ('712','479','297','639','452','172')", 5: nan, 6: " ('285','295','236','239','269','284','237')", 7: nan, 8: " ('164','157','388','158')", 9: " ('372','238')"}, 'rules_desc': {0: 'rules1', 1: 'rules2', 2: 'rules2', 3: 'rules2', 4: 'rules2', 5: 'rules2', 6: 'rules2', 7: 'rules2', 8: 'rules2', 9: 'rules2'}} import pandas as pd df1=pd.DataFrame.from_dict(df_dict()) cols = df1.columns.values res=[",".join("{}:{}".format(*t) for t in zip(cols, row)) for _, row in df1[cols].iterrows()] for now I am getting list but needs to have key such as column name as key and column value bounded to it. How can I do this in python? Instead, I tried like this also: res=[df1.iloc[i].astype(str).tolist() for i in range(0, len(df1))] I am getting error when I tried res.to_dict(): AttributeError: 'list' object has no attribute 'to_dict' this is fine, but I need column name assign to it and create dictionary. how can I do this in python? any idea? approach 2: new update - much better but still incorrect cols = df1.columns.values for i in range(0, len(df1)): ss=df1.iloc[i][cols].dropna().astype(str).tolist() # this is good my_dict = {k: cols for k in ss} # doing this incorrect print(my_dict ) but here able to drop the column with nan but don't know how to get correct key which is column name. I think I need somewhere between approach 1 and approach 2, don't know how to get my desired output. any idea? desired output I want to create key-value list for each rows of dataframe, like dictionary. here is my part of my expected output after clean up nan values: {{'order':1, 'code': ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL'), 'rules_desc': rules1}, {'order':2, 'code0': 40, 'code3':518, 'code6':594, 'rules_desc': rules2}, {'order':3, 'code0':98, 'code1':('ATT','NC'), 'code2':('103','104','105','106','31'), 'code3':810, 'code4': computer_science, 'rules_desc': rules2}, ... }
[ "There exists a technical problem\nthat you hope one or more people will solve, possibly\nincluding yourself.\nHere is my current understanding\nof the problem as presented.\nThe \"expected\" values apparently\ndon't match your expectation.\nIt would be helpful if you could\ndescribe them in code.\nMaybe you wish to json.loads\nsome of those columns?\nimport json\nimport unittest\n\nimport pandas as pd\nfrom pandas import NA as nan\n\n\nclass NestTest(unittest.TestCase):\n\n @staticmethod\n def _get_dictionary():\n return {\n \"order\": {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9, 9: 10},\n \"code0\": {\n 0: nan,\n 1: \" '40'\",\n 2: \" '98'\",\n 3: \" '98'\",\n 4: \" '52'\",\n 5: \" '52'\",\n 6: \" '52'\",\n 7: \" '52'\",\n 8: \" '40'\",\n 9: \" '58'\",\n },\n \"code1\": {\n 0: \" ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL')\",\n 1: nan,\n 2: \" ('ATT','NC')\",\n 3: \" ('ATT','VA','NC')\",\n 4: \" 'NC'\",\n 5: \" 'NC'\",\n 6: \" 'NC'\",\n 7: \" 'NC'\",\n 8: \" 'VA'\",\n 9: \" 'CE'\",\n },\n \"code2\": {\n 0: nan,\n 1: nan,\n 2: \" ('103','104','105','106','31')\",\n 3: \" ('104','105','106','31')\",\n 4: \" '109'\",\n 5: \" '109'\",\n 6: \" '109'\",\n 7: \" '109'\",\n 8: \" '11'\",\n 9: \" ('109')\",\n },\n \"code3\": {\n 0: nan,\n 1: \" '518'\",\n 2: \" '810'\",\n 3: nan,\n 4: \" ('610','620','682','642','621','611')\",\n 5: \" ('396','340','394','393','240')\",\n 6: \" ('612','790','110')\",\n 7: \" ('730','320','350','379','812','374')\",\n 8: \" ('113','174','131','115')\",\n 9: \" ('423','114')\",\n },\n \"code4\": {\n 0: nan,\n 1: nan,\n 2: \" 'computer science'\",\n 3: \" 'computer science'\",\n 4: \" 'biology'\",\n 5: \" 'biology'\",\n 6: \"biology'\",\n 7: \"biology'\",\n 8: nan,\n 9: nan,\n },\n \"code5\": {\n 0: nan,\n 1: nan,\n 2: nan,\n 3: nan,\n 4: nan,\n 5: \" ('12','18')\",\n 6: \" ('12','16','18','19')\",\n 7: \" ('12','18','19')\",\n 8: \" ('11','19','31')\",\n 9: \" '31'\",\n },\n \"code6\": {\n 0: nan,\n 1: \" '594'\",\n 2: nan,\n 3: nan,\n 4: \" ('712','479','297','639','452','172')\",\n 5: nan,\n 6: \" ('285','295','236','239','269','284','237')\",\n 7: nan,\n 8: \" ('164','157','388','158')\",\n 9: \" ('372','238')\",\n },\n \"rules_desc\": {\n 0: \"rules1\",\n 1: \"rules2\",\n 2: \"rules2\",\n 3: \"rules2\",\n 4: \"rules2\",\n 5: \"rules2\",\n 6: \"rules2\",\n 7: \"rules2\",\n 8: \"rules2\",\n 9: \"rules2\",\n },\n }\n\n def test_how_to_create_list_of_dictionary_from_nested_list_of_strings(self):\n df1 = pd.DataFrame.from_dict(self._get_dictionary())\n df1 = df1[:3] # Let's focus on just a subset, the first 3 rows\n\n self.assertEqual(\n [\n {\n \"code0\": None,\n \"code1\": \" ('VA','HC','NIH','SAP','AUS','HOL','ATT','COL','UCL')\",\n \"code2\": None,\n \"code3\": None,\n \"code4\": None,\n \"code5\": None,\n \"code6\": None,\n \"order\": 1,\n \"rules_desc\": \"rules1\",\n },\n {\n \"code0\": \" '40'\",\n \"code1\": None,\n \"code2\": None,\n \"code3\": \" '518'\",\n \"code4\": None,\n \"code5\": None,\n \"code6\": \" '594'\",\n \"order\": 2,\n \"rules_desc\": \"rules2\",\n },\n {\n \"code0\": \" '98'\",\n \"code1\": \" ('ATT','NC')\",\n \"code2\": \" ('103','104','105','106','31')\",\n \"code3\": \" '810'\",\n \"code4\": \" 'computer science'\",\n \"code5\": None,\n \"code6\": None,\n \"order\": 3,\n \"rules_desc\": \"rules2\",\n },\n ],\n json.loads(df1.to_json(orient=\"records\")),\n )\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074496442_dataframe_list_pandas_python.txt
Q: Convert scientific to decimal - dynamic float precision? I have a random set of numbers in a SQL database: 1.2 0.4 5.1 0.0000000000232 1 7.54 0.000000000000006534 The decimals way below zero are displayed as scientific notation num = 0.0000000000232 print(num) > 2.23e-11 But that causes the rest of my code to bug out as the api behind it expects a decimal number. I checked it as I increased the precision with :.20f - that works fine. Since the very small numbers are not constant with their precision, It would be unwise to simply set a static .20f. What is a more elegant way to translate this to the correct decimal, always dynamic with the precision? A: If Python provides a way to do this, they've hidden it very well. But a simple function can do it. def float_to_str(x): to_the_left = 1 + floor(log(x, 10)) to_the_right = sys.float_info.dig - to_the_left if to_the_right <= 0: s = str(int(x)) else: s = format(x, f'0.{to_the_right}f').rstrip('0') return s >>> for num in [1.2, 0.4, 5.1, 0.0000000000232, 1, 7.54, 0.000000000000006534]: print(float_to_str(num)) 1.2 0.4 5.1 0.0000000000232 1. 7.54 0.000000000000006534 The first part uses the logarithm base 10 to figure out how many digits will be on the left of the decimal point, or the number of zeros to the right of it if the number is negative. To find out how many digits can be to the right, we take the total number of significant digits that a float can hold as given by sys.float_info.dig which should be 15 on most Python implementations, and subtract the digits on the left. If this number is negative there won't be anything but garbage after the decimal point, so we can rely on integer conversion instead - it never uses scientific notation. Otherwise we simply conjure up the proper string to use with format. For the final step we strip off the redundant trailing zeros. Using integers for large numbers isn't perfect because we lose the rounding that naturally occurs with floating point string conversion. float_to_str(1e25) for example will return '10000000000000000905969664'. Since your examples didn't contain any such large numbers I didn't worry about it, but it could be fixed with a little more work. For the reasons behind this see Is floating point math broken?
Convert scientific to decimal - dynamic float precision?
I have a random set of numbers in a SQL database: 1.2 0.4 5.1 0.0000000000232 1 7.54 0.000000000000006534 The decimals way below zero are displayed as scientific notation num = 0.0000000000232 print(num) > 2.23e-11 But that causes the rest of my code to bug out as the api behind it expects a decimal number. I checked it as I increased the precision with :.20f - that works fine. Since the very small numbers are not constant with their precision, It would be unwise to simply set a static .20f. What is a more elegant way to translate this to the correct decimal, always dynamic with the precision?
[ "If Python provides a way to do this, they've hidden it very well. But a simple function can do it.\ndef float_to_str(x):\n to_the_left = 1 + floor(log(x, 10))\n to_the_right = sys.float_info.dig - to_the_left\n if to_the_right <= 0:\n s = str(int(x))\n else:\n s = format(x, f'0.{to_the_right}f').rstrip('0')\n return s\n\n>>> for num in [1.2, 0.4, 5.1, 0.0000000000232, 1, 7.54, 0.000000000000006534]:\n print(float_to_str(num))\n\n1.2\n0.4\n5.1\n0.0000000000232\n1.\n7.54\n0.000000000000006534\n\nThe first part uses the logarithm base 10 to figure out how many digits will be on the left of the decimal point, or the number of zeros to the right of it if the number is negative. To find out how many digits can be to the right, we take the total number of significant digits that a float can hold as given by sys.float_info.dig which should be 15 on most Python implementations, and subtract the digits on the left. If this number is negative there won't be anything but garbage after the decimal point, so we can rely on integer conversion instead - it never uses scientific notation. Otherwise we simply conjure up the proper string to use with format. For the final step we strip off the redundant trailing zeros.\nUsing integers for large numbers isn't perfect because we lose the rounding that naturally occurs with floating point string conversion. float_to_str(1e25) for example will return '10000000000000000905969664'. Since your examples didn't contain any such large numbers I didn't worry about it, but it could be fixed with a little more work. For the reasons behind this see Is floating point math broken?\n" ]
[ 1 ]
[]
[]
[ "floating_point", "precision", "python" ]
stackoverflow_0074495972_floating_point_precision_python.txt
Q: How do I fix this: TypeError: Entry.get() takes 1 positional argument but 3 were given I am very new to coding and can't figure out what is wrong. I am just trying to print something that the user types in a text box. I have a button that calls a function to take the info from the textbox, do some math with the number, then print its output in the console. When I run the program it starts off fine but when I enter a digit into the first box and press the button this error appears. File "/Users/Owner/PycharmProjects/gui thing/venv/new gui.py", line 29, in <lambda> printbutton = Button(bottomframe, text="Run Algorithm", command=lambda: get_input()) File "/Users/Owner/PycharmProjects/gui thing/venv/new gui.py", line 6, in get_input year = boxYear.get("1.0", "end-1c") TypeError: Entry.get() takes 1 positional argument but 3 were given from tkinter import * root = Tk() root.geometry("500x500") def get_input(): year = boxYear.get("1.0", "end-1c") p1 = (int(year) // 12) p2 = (int(year) % 12) p3 = (p2 // 4) p4 = (p1 + p2 + p3) days = ['wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'monday', 'tuesday'] p5 = (p4 // 7) if p4 >= 7 and p4 <= 14: p6 = (int(p4 - 7)) elif p4 >= 7 and p4 > 14: p6 = (int(p4 - 14)) else: p6 = (int(p4)) if p6 == 7: p6 = 0 print(days[int(p6)]) topframe = Frame(root) topframe.pack() bottomframe = Frame(root) bottomframe.pack(side=BOTTOM) quitbutton = Button(bottomframe, text= "Quit Program", command=bottomframe.quit) quitbutton.grid() printbutton = Button(bottomframe, text="Run Algorithm", command=lambda: get_input()) printbutton.grid() boxYear = Entry(topframe) boxMonth = Entry(topframe) boxDay = Entry(topframe) boxYear.grid(row=0, column=1, padx=10, pady=10) boxMonth.grid(row=1, column=1, padx=10, pady=10) boxDay.grid(row=2, column=1, padx=10, pady=10) l1 = Label(topframe, text="Year: ") l2 = Label(topframe, text="Month: ") l3 = Label(topframe, text="Day: ") l1.grid(row=0, column=0) l2.grid(row=1, column=0) l3.grid(row=2, column=0) I have tried moving things around and Turing on and off certain part to see what's causing the issue. I've looked at it for a while and can't see anything wrong but as I said I have no idea what I am doing as I just started coding two weeks ago. A: The get method takes no parameters (other than self, which is why the error mentions one parameter). You are calling it as if the widget was a Text widget, but it's an Entry widget. The way to call get on an entry widget is by passing no parameters: year = boxYear.get()
How do I fix this: TypeError: Entry.get() takes 1 positional argument but 3 were given
I am very new to coding and can't figure out what is wrong. I am just trying to print something that the user types in a text box. I have a button that calls a function to take the info from the textbox, do some math with the number, then print its output in the console. When I run the program it starts off fine but when I enter a digit into the first box and press the button this error appears. File "/Users/Owner/PycharmProjects/gui thing/venv/new gui.py", line 29, in <lambda> printbutton = Button(bottomframe, text="Run Algorithm", command=lambda: get_input()) File "/Users/Owner/PycharmProjects/gui thing/venv/new gui.py", line 6, in get_input year = boxYear.get("1.0", "end-1c") TypeError: Entry.get() takes 1 positional argument but 3 were given from tkinter import * root = Tk() root.geometry("500x500") def get_input(): year = boxYear.get("1.0", "end-1c") p1 = (int(year) // 12) p2 = (int(year) % 12) p3 = (p2 // 4) p4 = (p1 + p2 + p3) days = ['wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'monday', 'tuesday'] p5 = (p4 // 7) if p4 >= 7 and p4 <= 14: p6 = (int(p4 - 7)) elif p4 >= 7 and p4 > 14: p6 = (int(p4 - 14)) else: p6 = (int(p4)) if p6 == 7: p6 = 0 print(days[int(p6)]) topframe = Frame(root) topframe.pack() bottomframe = Frame(root) bottomframe.pack(side=BOTTOM) quitbutton = Button(bottomframe, text= "Quit Program", command=bottomframe.quit) quitbutton.grid() printbutton = Button(bottomframe, text="Run Algorithm", command=lambda: get_input()) printbutton.grid() boxYear = Entry(topframe) boxMonth = Entry(topframe) boxDay = Entry(topframe) boxYear.grid(row=0, column=1, padx=10, pady=10) boxMonth.grid(row=1, column=1, padx=10, pady=10) boxDay.grid(row=2, column=1, padx=10, pady=10) l1 = Label(topframe, text="Year: ") l2 = Label(topframe, text="Month: ") l3 = Label(topframe, text="Day: ") l1.grid(row=0, column=0) l2.grid(row=1, column=0) l3.grid(row=2, column=0) I have tried moving things around and Turing on and off certain part to see what's causing the issue. I've looked at it for a while and can't see anything wrong but as I said I have no idea what I am doing as I just started coding two weeks ago.
[ "The get method takes no parameters (other than self, which is why the error mentions one parameter). You are calling it as if the widget was a Text widget, but it's an Entry widget. The way to call get on an entry widget is by passing no parameters:\nyear = boxYear.get()\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter", "tkinter_button", "tkinter_entry", "typeerror" ]
stackoverflow_0074496351_python_tkinter_tkinter_button_tkinter_entry_typeerror.txt
Q: How do I remove items from a list based off of class data class Student: def __init__(self, name, major, gpa, onProbation): self.name = name self.major = major self.gpa = gpa self.onProbation = onProbation Student1 = Student("Josh", "Business", 3.8, False) Student2 = Student("Maya", "Accountancy", 2.5, True) Student3 = Student("Dan", "Psychology", 1.2, True) Student4 = Student("Keon", "Biomedical Engineering", 4.0, False) Student5 = Student("Michelle", "Medicine", 3.7, False) Student6 = Student("Joey", "Law", 4.0, False) Students = ["Josh", "Maya", "Dan", "Keon", "Michelle", "Joey"] I want to figure out how to remove all the students who are on probation from the list, so if I were to type print(Students) it would only give me the students that are not on probation (Josh, Keon, Michelle, and Joey) A: I believe I have found an answer to your question. I would also like to note that it is best not to create your student objects in the init method and storing all the students in a list is useful.. Here it is: class Student: def __init__(self, name, major, gpa, onProbation): self.name = name self.major = major self.gpa = gpa self.onProbation = onProbation students = [ Student("Josh", "Business", 3.8, False), Student("Maya", "Accountancy", 2.5, True), Student("Dan", "Psychology", 1.2, True), Student("Keon", "Biomedical Engineering", 4.0, False), Student("Michelle", "Medicine", 3.7, False), Student("Joey", "Law", 4.0, False) ] # I created a list for new students because it will mess up the for loop if you remove objects from a list while iterating new_students = [] for student in students: if student.onProbation == False: new_students.append(student) # print(students) will return an unreadable list with encoded numbers and such so I did this instead for student in new_students: print(student.name, student.onProbation) I hope this was useful. A: class Student: def __init__(self, name, major, gpa, onProbation): self.name = name self.major = major self.gpa = gpa self.onProbation = onProbation @staticmethod def getStudentsNotOnProbation(students): res = [] for student in students: if not student.onProbation: res.append(student) return res Student1 = Student("Josh", "Business", 3.8, False) Student2 = Student("Maya", "Accountancy", 2.5, True) Student3 = Student("Dan", "Psychology", 1.2, True) Student4 = Student("Keon", "Biomedical Engineering", 4.0, False) Student5 = Student("Michelle", "Medicine", 3.7, False) Student6 = Student("Joey", "Law", 4.0, False) Students = [Student1, Student2, Student3, Student4, Student5, Student6] print(Student.getStudentsNotOnProbation(Students)) The reason I've used staticmethod so the logic should be encapsulated in Student class itself.
How do I remove items from a list based off of class data
class Student: def __init__(self, name, major, gpa, onProbation): self.name = name self.major = major self.gpa = gpa self.onProbation = onProbation Student1 = Student("Josh", "Business", 3.8, False) Student2 = Student("Maya", "Accountancy", 2.5, True) Student3 = Student("Dan", "Psychology", 1.2, True) Student4 = Student("Keon", "Biomedical Engineering", 4.0, False) Student5 = Student("Michelle", "Medicine", 3.7, False) Student6 = Student("Joey", "Law", 4.0, False) Students = ["Josh", "Maya", "Dan", "Keon", "Michelle", "Joey"] I want to figure out how to remove all the students who are on probation from the list, so if I were to type print(Students) it would only give me the students that are not on probation (Josh, Keon, Michelle, and Joey)
[ "I believe I have found an answer to your question. I would also like to note that it is best not to create your student objects in the init method and storing all the students in a list is useful.. Here it is:\nclass Student:\n\n def __init__(self, name, major, gpa, onProbation):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\nstudents = [\n Student(\"Josh\", \"Business\", 3.8, False),\n Student(\"Maya\", \"Accountancy\", 2.5, True),\n Student(\"Dan\", \"Psychology\", 1.2, True),\n Student(\"Keon\", \"Biomedical Engineering\", 4.0, False),\n Student(\"Michelle\", \"Medicine\", 3.7, False),\n Student(\"Joey\", \"Law\", 4.0, False)\n]\n\n# I created a list for new students because it will mess up the for loop if you remove objects from a list while iterating\nnew_students = []\nfor student in students:\n if student.onProbation == False:\n new_students.append(student)\n\n# print(students) will return an unreadable list with encoded numbers and such so I did this instead\nfor student in new_students:\n print(student.name, student.onProbation)\n\nI hope this was useful.\n", "class Student:\n\n def __init__(self, name, major, gpa, onProbation):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n @staticmethod\n def getStudentsNotOnProbation(students):\n res = []\n for student in students:\n if not student.onProbation:\n res.append(student)\n return res\n\nStudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nStudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nStudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nStudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nStudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nStudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nStudents = [Student1, Student2, Student3, Student4, Student5, Student6]\n\n\nprint(Student.getStudentsNotOnProbation(Students))\n\nThe reason I've used staticmethod so the logic should be encapsulated in Student class itself.\n" ]
[ 0, 0 ]
[ "this is kinda how i do it. When you make classes it remembers the attribute assignments even in lists. There called pylist in cpython\n\nclass Student:\n\n def __init__(self, name: str, major: str, gpa:float, onProbation: bool):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n# in your example you placed the class instances in the class, \n# notice how mine are placed outside. The __init__ method initializes\n# the object, having it within the object is infinitly recursive i believe\n\nstudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nstudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nstudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nstudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nstudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nstudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nstudents = [student1,student2,student3,student4,student5, student6]\n\nmylist = students\nfor index, student in enumerate(students):\n if student.onProbation: # if the boolean isnt specified, defaults to true as is\n mylist.remove(students[index])\n\n\nas John Gordon Pointed out, you could use list comprehension\nclass Student:\n\n def __init__(self, name: str, major: str, gpa:float, onProbation: bool):\n self.name = name\n self.major = major\n self.gpa = gpa\n self.onProbation = onProbation\n\n\n\nstudent1 = Student(\"Josh\", \"Business\", 3.8, False)\nstudent2 = Student(\"Maya\", \"Accountancy\", 2.5, True)\nstudent3 = Student(\"Dan\", \"Psychology\", 1.2, True)\nstudent4 = Student(\"Keon\", \"Biomedical Engineering\", 4.0, False)\nstudent5 = Student(\"Michelle\", \"Medicine\", 3.7, False)\nstudent6 = Student(\"Joey\", \"Law\", 4.0, False)\n\nstudents = [student1,student2,student3,student4,student5, student6]\n\ngood_students = [x for x in students if not student.onProbation]\n\n\n" ]
[ -1 ]
[ "class", "list", "python", "python_3.x" ]
stackoverflow_0074497208_class_list_python_python_3.x.txt
Q: Data download from a REST API directly on AWS S3 bucket I need to download data from a REST api by making a GET request from AWS cloud and land the data in S3. Do we have a REST connector available in AWS to make direct connection to API? If not, then I plan to write Python code using requests library to make GET request to API using BASIC auth, write the response json into dataframe, flatten it and finally use **AWSwrangler **library to write the dataframe directly on to S3 bucket. Is there any other simpler way to achieve it specially considering that the data may be over 5GB in size? A: You need to create a presigned url first, then you can upload files directly to s3. Everytime your api gets an upload request it will create a presigned url first then use that to upload data to s3. This might help.
Data download from a REST API directly on AWS S3 bucket
I need to download data from a REST api by making a GET request from AWS cloud and land the data in S3. Do we have a REST connector available in AWS to make direct connection to API? If not, then I plan to write Python code using requests library to make GET request to API using BASIC auth, write the response json into dataframe, flatten it and finally use **AWSwrangler **library to write the dataframe directly on to S3 bucket. Is there any other simpler way to achieve it specially considering that the data may be over 5GB in size?
[ "You need to create a presigned url first, then you can upload files directly to s3.\nEverytime your api gets an upload request it will create a presigned url first then use that to upload data to s3.\nThis might help.\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "api", "python", "rest" ]
stackoverflow_0074489867_amazon_s3_amazon_web_services_api_python_rest.txt
Q: How to use cmp() in Python 3? I cannot get the command cmp() to work. Here is the code: a = [1,2,3] b = [1,2,3] c = cmp(a,b) print (c) I am getting the error: Traceback (most recent call last): File "G:\Dropbox\Code\a = [1,2,3]", line 3, in <module> c = cmp(a,b) NameError: name 'cmp' is not defined [Finished in 0.1s] A: As mentioned in the comments, cmp doesn't exist in Python 3. If you really want it, you could define it yourself: def cmp(a, b): return (a > b) - (a < b) which is taken from the original What's New In Python 3.0. It's pretty rare -- though not unheard of -- that it's really needed, though, so you might want to think about whether it's actually the best way to do whatever it is you're up to. A: In Python 3.x you can import operator and use operator module's eq(), lt(), etc... instead of cmp() A: When the sign is needed, probably safest alternative is using math.copysign: import math ang = -2 # alternative for cmp(ang, 0): math.copysign(1, ang) # Result: -1 In particular if ang is of np.float64 type because of depreciation of the '-' operator. Example: import numpy as np def cmp_0(a, b): return (a > b) - (a < b) ang = np.float64(-2) cmp_0(ang, 0) # Result: # DeprecationWarning: numpy boolean subtract, the `-` operator, is deprecated, # use the bitwise_xor, the `^` operator, or the logical_xor function instead. instead one could use: def cmp_0(a, b): return bool(a > b) - bool(a < b) ang = np.float64(-2) cmp(ang, 0) # Result: -1 A: adding to @maxin's answer, in python 3.x, if you want to compare two lists of tuples a and b import operator a = [(1,2),(3,4)] b = [(3,4),(1,2)] # convert both lists to sets before calling the eq function print(operator.eq(set(a),set(b))) #True A: While in the general case, these are all good replacements for cmp(), for the actual use case given by the original poster, surely a = [1,2,3] b = [1,2,3] c = a != b print(c) or just a = [1,2,3] b = [1,2,3] print(a != b) would work quite well. A: you could use this easier way a=[1,2,3] b=[1,2,3] c=not(a!=b) c True
How to use cmp() in Python 3?
I cannot get the command cmp() to work. Here is the code: a = [1,2,3] b = [1,2,3] c = cmp(a,b) print (c) I am getting the error: Traceback (most recent call last): File "G:\Dropbox\Code\a = [1,2,3]", line 3, in <module> c = cmp(a,b) NameError: name 'cmp' is not defined [Finished in 0.1s]
[ "As mentioned in the comments, cmp doesn't exist in Python 3. If you really want it, you could define it yourself:\ndef cmp(a, b):\n return (a > b) - (a < b) \n\nwhich is taken from the original What's New In Python 3.0. It's pretty rare -- though not unheard of -- that it's really needed, though, so you might want to think about whether it's actually the best way to do whatever it is you're up to.\n", "In Python 3.x you can import operator and use operator module's eq(), lt(), etc... instead of cmp()\n", "When the sign is needed, probably safest alternative is using math.copysign:\nimport math\nang = -2\n# alternative for cmp(ang, 0):\nmath.copysign(1, ang)\n\n# Result: -1\n\nIn particular if ang is of np.float64 type because of depreciation of the '-' operator.\nExample:\nimport numpy as np\n\ndef cmp_0(a, b):\n return (a > b) - (a < b)\n\nang = np.float64(-2)\ncmp_0(ang, 0)\n\n# Result:\n# DeprecationWarning: numpy boolean subtract, the `-` operator, is deprecated, \n# use the bitwise_xor, the `^` operator, or the logical_xor function instead.\n\ninstead one could use:\ndef cmp_0(a, b):\n return bool(a > b) - bool(a < b)\n\nang = np.float64(-2)\ncmp(ang, 0)\n# Result: -1\n\n", "adding to @maxin's answer, in python 3.x, if you want to compare two lists of tuples\na and b\nimport operator\n\na = [(1,2),(3,4)]\nb = [(3,4),(1,2)]\n# convert both lists to sets before calling the eq function\nprint(operator.eq(set(a),set(b))) #True\n\n", "While in the general case, these are all good replacements for cmp(), for the actual use case given by the original poster, surely\na = [1,2,3]\nb = [1,2,3]\nc = a != b\nprint(c)\n\nor just\na = [1,2,3]\nb = [1,2,3]\nprint(a != b)\n\nwould work quite well.\n", "you could use this easier way\na=[1,2,3]\nb=[1,2,3]\nc=not(a!=b)\nc\nTrue\n\n" ]
[ 93, 10, 1, 0, 0, 0 ]
[ "If a or b is a class object,\nthen the above answers will have the compilation error as below:\nFor example: a is Class Clock:\n File \"01_ClockClass_lab16.py\", line 14, in cmp\n return (a > b) - (a < b)\nTypeError: '>' not supported between instances of 'Clock' and 'Clock'\n\nChange the type with int() to remove the error:\ndef cmp(a, b):\n return (int(a) > int(b)) - (int(a) < int(b)) \n\n", "One simple way is to use a - b and check the sign.\ndef cmp(a, b):\n return a - b\n\nif a < b, negative\n\nif a = b, zero\n\nif a > b, positive\n\n", "This cmp() function works only on Python version 2.x, if you try to use it in version 3.x it will give an error:\nNameError: name 'cmp' is not defined\n[Finished in 0.1s with exit code 1]\n\nSee the code below:\na=60\nb=90\nprint(cmp(a,b))\n\noutput:\n-1\n\nWhile comparing integers cmp() just performs subtraction of its argument i.e in this case a-b, if subtraction is -ve it returns -1 i.e a<b\nif subtraction is +ve it returns 1 i.e a>b\na=90\nb=60\nprint(cmp(a,b))\n\noutput:\n1\n\nAgain:\na=\"abc\"\nb=\"abc\"\nprint(cmp(a,b))\n\noutput:\n0\n\nwhen both the arguments are equal i.e a=b, it returns 0 as output. Here, we have passed two string type of values. Here, cmp() compares both the strings character by character and if found same then returns 0.\n" ]
[ -1, -1, -3 ]
[ "python", "python_3.x" ]
stackoverflow_0022490366_python_python_3.x.txt
Q: Overriding parent methods Programmatically I need to use a company logger library that requires a Message object as an argument instead of a plain string like vanilla python logging library (the rest works exactly like vanilla logging). To avoid having to migrate each log individually across all the applications I maintain, I am trying to extend this custom logger class to accept either a Message or a plain string. I was able to do this by overriding explicitly each log level method from companylogging.logger import CompanyLogger, Message class CustomLogger(CompanyLogger): def __init__(self, *args, **kwargs): super().__init__(*args, *kwargs) def debug(self, message): if isinstance(message, Message): super().debug(message) else: super().debug(Message(message)) ... def critical(self, message): if isinstance(message, Message): super().critical(message) else: super().critical(Message(message)) I would like to do this programmatically for each level, with levels being a list of strings depicting how the logging methods in the parent class are named: from companylogging.logger import CompanyLogger, Message class CustomLogger(CompanyLogger): def __init__(self, *args, **kwargs): super().__init__(*args, *kwargs) for level in levels: setattr(self, level, self.override_loglevels(level)) def override_loglevels(self, level): def log(message): logger = getattr(CompanyLogger, level) if isinstance(message, Message): logger(message) else : logger(Message(message)) return log This approach didn't work. When used, an error occurs saying I am not providing the message argument: TypeError: debug() missing 1 required positional argument: 'msg' But I am passing it... logger.debug(f"test message") logger.debug(Message(f"test message")) Any ideas of what I'm doing wrong? Or maybe an alternative approach to achieve this "programmatic method override"? A: Since I'm overriding a method, I needed to pass self as well when overriding def override_loglevels(self, level): def log(message): logger = getattr(SantanderLogger, level) if isinstance(message, Message): logger(self, message) else : logger(self, Message(message))
Overriding parent methods Programmatically
I need to use a company logger library that requires a Message object as an argument instead of a plain string like vanilla python logging library (the rest works exactly like vanilla logging). To avoid having to migrate each log individually across all the applications I maintain, I am trying to extend this custom logger class to accept either a Message or a plain string. I was able to do this by overriding explicitly each log level method from companylogging.logger import CompanyLogger, Message class CustomLogger(CompanyLogger): def __init__(self, *args, **kwargs): super().__init__(*args, *kwargs) def debug(self, message): if isinstance(message, Message): super().debug(message) else: super().debug(Message(message)) ... def critical(self, message): if isinstance(message, Message): super().critical(message) else: super().critical(Message(message)) I would like to do this programmatically for each level, with levels being a list of strings depicting how the logging methods in the parent class are named: from companylogging.logger import CompanyLogger, Message class CustomLogger(CompanyLogger): def __init__(self, *args, **kwargs): super().__init__(*args, *kwargs) for level in levels: setattr(self, level, self.override_loglevels(level)) def override_loglevels(self, level): def log(message): logger = getattr(CompanyLogger, level) if isinstance(message, Message): logger(message) else : logger(Message(message)) return log This approach didn't work. When used, an error occurs saying I am not providing the message argument: TypeError: debug() missing 1 required positional argument: 'msg' But I am passing it... logger.debug(f"test message") logger.debug(Message(f"test message")) Any ideas of what I'm doing wrong? Or maybe an alternative approach to achieve this "programmatic method override"?
[ "Since I'm overriding a method, I needed to pass self as well when overriding\ndef override_loglevels(self, level):\n\n def log(message):\n logger = getattr(SantanderLogger, level)\n if isinstance(message, Message):\n logger(self, message)\n else :\n logger(self, Message(message))\n\n" ]
[ 1 ]
[]
[]
[ "inheritance", "overriding", "python" ]
stackoverflow_0074497254_inheritance_overriding_python.txt
Q: How can I use torch.fft.fft2 to output the same result as troch.fft? In the documentation of pytorch 1.1.0, the description of the return of torch.fft is "Returns the real and the imaginary part together as an tensor of the same shape input" In pytorch1.8.1, torch.fft is replaced by torch.fft.fft2, and torch.fft.fft2 outputs the result in complex For the same data, the output of torch.fft is tensor([32779.2891]) tensor([67.1836]) tensor([11.9802]) tensor([-47.5729]) tensor([-101.7718]) tensor([-5.7989]) tensor([17.5259]) tensor([41.0830]) tensor([-5.1960]) tensor([42.2860]) The output result of torch.fft.fft2 is tensor(32779.2891+0.j) tensor(36.2154-25.2860j) tensor(22.9704-39.8544j) tensor(-62.9149+6.8637j) tensor(-87.2122-94.2708j) tensor(-3.2740+52.0396j) tensor(-32.4686+46.9949j) tensor(-50.1910-30.1725j) tensor(-8.8877+19.0709j) tensor(39.9689-32.3084j) Input is a 256x256 data generated by input = numpy.random.rand(256,256) and the above result is part of the data generated by using this data(256x256) as input. Using this data(256x256), Matlab and torch.fft.fft2 output the same result How torch.fft stores the real and imaginary parts of the result in a tensor of the same shape? How can I use torch.fft.fft2 to output the same result as torch.fft? A: I was struggle in this for few days, then i try all parameters in torch.fft.fft2,finally i found set norm='ortho' make the same result with old pytorch torch.fft . Hope this will help you.
How can I use torch.fft.fft2 to output the same result as troch.fft?
In the documentation of pytorch 1.1.0, the description of the return of torch.fft is "Returns the real and the imaginary part together as an tensor of the same shape input" In pytorch1.8.1, torch.fft is replaced by torch.fft.fft2, and torch.fft.fft2 outputs the result in complex For the same data, the output of torch.fft is tensor([32779.2891]) tensor([67.1836]) tensor([11.9802]) tensor([-47.5729]) tensor([-101.7718]) tensor([-5.7989]) tensor([17.5259]) tensor([41.0830]) tensor([-5.1960]) tensor([42.2860]) The output result of torch.fft.fft2 is tensor(32779.2891+0.j) tensor(36.2154-25.2860j) tensor(22.9704-39.8544j) tensor(-62.9149+6.8637j) tensor(-87.2122-94.2708j) tensor(-3.2740+52.0396j) tensor(-32.4686+46.9949j) tensor(-50.1910-30.1725j) tensor(-8.8877+19.0709j) tensor(39.9689-32.3084j) Input is a 256x256 data generated by input = numpy.random.rand(256,256) and the above result is part of the data generated by using this data(256x256) as input. Using this data(256x256), Matlab and torch.fft.fft2 output the same result How torch.fft stores the real and imaginary parts of the result in a tensor of the same shape? How can I use torch.fft.fft2 to output the same result as torch.fft?
[ "I was struggle in this for few days, then i try all parameters in torch.fft.fft2,finally i found set norm='ortho' make the same result with old pytorch torch.fft . Hope this will help you.\n" ]
[ 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0069764891_python_pytorch.txt
Q: mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) I am following along with lecturer's code and videos. He has this set up, and I have followed exactly. His works, mine doesn't and I cant figure out why. It is set up as user "root" and password is blank. I have tried pip install mysql-connector-python. I want to keep the same user and password as his so as to follow along better. I am using python and mysql via Wampserver64. When I try to run the python file through cmd I get the error "mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)". I am new to this so trying to figure it out as I go along. Does the (using password: YES) mean that the passwords match? And how to I get script to connect to mysql? db = mysql.connector.connect( host = "localhost", user= "root", password = " " #database ='datarepresentation' ) #print ("connection made") cursor = db.cursor() cursor.execute("CREATE DATABASE datarepresentation") A: The same problem occurred when my friend tried to run a python script in the Ubuntu Windows Linux Subsystem that uses a MySQL database set up. We fixed the problem by running the following three commands in the MySQL 8.0 Command Line Client and then restarting the machine to reboot everything. We are using Flask in our project and not Wamp so hopefully it will work the same. These commands were found here. SELECT user, authentication_string, plugin, host FROM mysql.user; ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Current-Root-Password'; FLUSH PRIVILEGES; According to MySQL documentation(MySQL Documentation), it states that (using password: YES) just means that you are in fact using a password. If you would have tried to login without using a password, it would say 'NO'. As far as how to connect your script to your database, you pretty much have it. You can write a query to retrieve something from the database to check. Here is an example using the database you mentioned to retrieve some kind of data and make sure it's in the table. cnx = mysql.connector.connect( host="localhost", user='root', password=" ", database='datarepresentation') cursor = cnx.cursor() query = ("SELECT * FROM table-name WHERE key1 = %s") dataName = 'randomValue' cursor.execute(query, (dataName)) result = cursor.fetchone() if result[0] == 1: return True else: return False A: Don't assign any value to password argument and pass as i.e password='' A: try to create new user mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass'; mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' -> WITH GRANT OPTION; mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass'; mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' -> WITH GRANT OPTION; A: I also encountered it and solve such as below. import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", #remove this line or password="" ) It's remove the line of the password. if you want to insert the line of the password,it's unwanted the spase(for instance,password="", this isn't password=" "). this program is (using password: YES). Why can't i solve? I thought that this error is indicating already "The passwords match." so,description of the password is unwanted in mydb=mysql.connector.connect( ) . I have specified how to solve on my site [troubleshooting] ProgrammingError: **** (*****): Access denied for user 'root'@'localhost' (using password: YES) mysql-connector of python.
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
I am following along with lecturer's code and videos. He has this set up, and I have followed exactly. His works, mine doesn't and I cant figure out why. It is set up as user "root" and password is blank. I have tried pip install mysql-connector-python. I want to keep the same user and password as his so as to follow along better. I am using python and mysql via Wampserver64. When I try to run the python file through cmd I get the error "mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)". I am new to this so trying to figure it out as I go along. Does the (using password: YES) mean that the passwords match? And how to I get script to connect to mysql? db = mysql.connector.connect( host = "localhost", user= "root", password = " " #database ='datarepresentation' ) #print ("connection made") cursor = db.cursor() cursor.execute("CREATE DATABASE datarepresentation")
[ "The same problem occurred when my friend tried to run a python script in the Ubuntu Windows Linux Subsystem that uses a MySQL database set up.\nWe fixed the problem by running the following three commands in the MySQL 8.0 Command Line Client and then restarting the machine to reboot everything. We are using Flask in our project and not Wamp so hopefully it will work the same. These commands were found here.\nSELECT user, authentication_string, plugin, host FROM mysql.user;\nALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Current-Root-Password';\nFLUSH PRIVILEGES;\n\nAccording to MySQL documentation(MySQL Documentation), it states that (using password: YES) just means that you are in fact using a password. If you would have tried to login without using a password, it would say 'NO'.\nAs far as how to connect your script to your database, you pretty much have it. You can write a query to retrieve something from the database to check. Here is an example using the database you mentioned to retrieve some kind of data and make sure it's in the table.\ncnx = mysql.connector.connect(\n host=\"localhost\", \n user='root', \n password=\" \", \n database='datarepresentation')\ncursor = cnx.cursor()\nquery = (\"SELECT * FROM table-name WHERE key1 = %s\")\ndataName = 'randomValue'\ncursor.execute(query, (dataName))\nresult = cursor.fetchone()\nif result[0] == 1:\n return True\nelse:\n return False\n\n", "Don't assign any value to password argument and pass as i.e password=''\n", "try to create new user\nmysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';\nmysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'\n -> WITH GRANT OPTION;\nmysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';\nmysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'\n -> WITH GRANT OPTION;\n\n", "I also encountered it and solve such as below.\nimport mysql.connector\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n #remove this line or password=\"\" \n)\n\nIt's remove the line of the password. if you want to insert the line of the password,it's unwanted the spase(for instance,password=\"\", this isn't password=\" \").\nthis program is (using password: YES).\nWhy can't i solve?\nI thought that this error is indicating already \"The passwords match.\"\nso,description of the password is unwanted in mydb=mysql.connector.connect( ) .\nI have specified how to solve on my site [troubleshooting] ProgrammingError: **** (*****): Access denied for user 'root'@'localhost' (using password: YES) mysql-connector of python.\n\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "mysql", "python", "wampserver" ]
stackoverflow_0064936683_mysql_python_wampserver.txt
Q: Slow Requests on Local Flask Server Just starting to play around with Flask on a local server and I'm noticing the request/response times are way slower than I feel they should be. Just a simple server like the following takes close to 5 seconds to respond. from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "index" if __name__ == "__main__": app.run() Any ideas? Or is this just how the local server is? A: Ok I figured it out. It appears to be an issue with Werkzeug and os's that support ipv6. From the Werkzeug site http://werkzeug.pocoo.org/docs/serving/: On operating systems that support ipv6 and have it configured such as modern Linux systems, OS X 10.4 or higher as well as Windows Vista some browsers can be painfully slow if accessing your local server. The reason for this is that sometimes “localhost” is configured to be available on both ipv4 and ipv6 socktes and some browsers will try to access ipv6 first and then ivp4. So the fix is to disable ipv6 from the localhost by commenting out the following line from my hosts file: ::1 localhost Once I do this the latency problems go away. I'm really digging Flask and I'm glad that it's not a problem with the framework. I knew it couldn't be. A: Add "threaded=True" as an argument to app.run(), as suggested here: http://arusahni.net/blog/2013/10/flask-multithreading.html For example: app.run(host="0.0.0.0", port=8080, threaded=True) The ipv6-disabling solution did not work for me, but this did. A: Instead of calling http://localhost:port/endpoint call http://127.0.0.1:port/endpoint. This removed the initial 500ms delay for me. A: The solution from @sajid-siddiqi is technically correct, but keep in mind that the built-in WSGI server in Werkzeug (which is packaged into Flask and what it uses for app.run()) is only single-threaded. Install a WSGI server to be able to handle multi-threaded behavior. I did a bunch of research on various WSGI server performances. Your needs may vary, but if all you're using is Flask, then I would recommend one of the following webservers. Update (2020-07-25): It looks like gevent started supporting python3 5 years ago, shortly after I commented that it didn't, so you can use gevent now. gevent You can install gevent through pip with the command pip install gevent or pip3 with the command pip3 install gevent. Instructions on how to modify your code accordingly are here: https://flask.palletsprojects.com/en/1.1.x/deploying/wsgi-standalone/#gevent meinheld gevent is better, but from all the benchmarks I've looked at that involve real-world testing, meinheld seems to be the most straightforward, simplistic WSGI server. (You could also take a look at uWSGI if you don't mind some more configuration.) You can also install meinheld through pip3 with the command pip3 install meinheld. From there, look at the sample provided in the meinheld source to integrate Flask: https://github.com/mopemope/meinheld/blob/master/example/flask_sample.py *NOTE: From my use of PyCharm, the line from meinheld import server highlights as an error, but the server will run, so you can ignore the error. A: My problem was solved by "threaded=True", but I want to give some background to distinguish my problem from others for which this may not do it. My issue only arose when running Flask with python3. Switching to python2, I no longer had this issue. My problem manifested only when accessing the api with Chrome, at which point, Chrome displayed the expected screen, but everything else hung (curl, ffx, etc) until I either reloaded or closed the Chrome tab, at which point everything else that was waiting around returned a result. My best guess is that Chrome was trying to keep the session open and Flask was blocking the subsequent requests. As soon as the connection from Chrome was stopped or reset, everything else was processed. In my case, threading fixed it. Of course, I'm now going through some of the links others have provided to make sure that it's not going to cause any other issues. A: threaded=True works for me, but finally I figured out that the issue is due to foxyproxy on firefox. Since when the flask app is running on localhost, slow response happens if foxyproxy is enabled on firefox slow response won't happen if foxyproxy is disabled on firefox access the website using other browsers The only solution I found is to disable foxyproxy, tried to add localhost to proxy blacklist and tweak settings but none of them worked. A: I used Miheko's response to solve my issue. ::1 localhost was already commented out on my hosts file, and setting Threaded=true didn't work for me. Every REST request was taking 1 second to process instead of being instant. I'm using python 3.6, and I got flask to be fast and responsive to REST requests by making flask use gevent as its WSGI. To use gevent, install it with pip install gevent Afterwards, I used the https://gist.github.com/viksit/b6733fe1afdf5bb84a40#file-async_flask-py-L41 to set flask to use gevent. Incase the link goes down, here's the important parts of the script: from flask import Flask, Response from gevent.pywsgi import WSGIServer from gevent import monkey # need to patch sockets to make requests async # you may also need to call this before importing other packages that setup ssl monkey.patch_all() app = Flask(__name__) # define some REST endpoints... def main(): # use gevent WSGI server instead of the Flask # instead of 5000, you can define whatever port you want. http = WSGIServer(('', 5000), app.wsgi_app) # Serve your application http.serve_forever() if __name__ == '__main__': main() A: I got this error when running on hosts other than localhost as well, so for some, different underlying problems may exhibit the same symptoms. I switched most of the things I've been using to Tornado, and anecdotally it's helped an amount. I've had a few slow page loads, but things seem generally more responsive. Also, very anecdotal, but I seem to notice that Flask alone will slow down over time, but Flask + Tornado less so. I imagine using Apache and mod_wsgi would make things even better, but Tornado's really simple to set up (see http://flask.pocoo.org/docs/deploying/others/). (Also, a related question: Flask app occasionally hanging) A: I had a different solution here. I just deleted all .pyc from the server's directory and started it again. By the way, localhost was already commented out in my hosts file (Windows 8). The server was freezing the whole time and now it works fine again. A: I run Python 3.8.10 which works fine, but as soon as I switch to Python 3.10.6 responses will be awful slow. I could get around this problem with changing the precedence to IPv4 in /etc/gai.conf
Slow Requests on Local Flask Server
Just starting to play around with Flask on a local server and I'm noticing the request/response times are way slower than I feel they should be. Just a simple server like the following takes close to 5 seconds to respond. from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "index" if __name__ == "__main__": app.run() Any ideas? Or is this just how the local server is?
[ "Ok I figured it out. It appears to be an issue with Werkzeug and os's that support ipv6.\nFrom the Werkzeug site http://werkzeug.pocoo.org/docs/serving/:\n\nOn operating systems that support ipv6 and have it configured such as modern Linux systems, OS X 10.4 or higher as well as Windows Vista some browsers can be painfully slow if accessing your local server. The reason for this is that sometimes “localhost” is configured to be available on both ipv4 and ipv6 socktes and some browsers will try to access ipv6 first and then ivp4. \n\nSo the fix is to disable ipv6 from the localhost by commenting out the following line from my hosts file:\n::1 localhost \n\nOnce I do this the latency problems go away.\nI'm really digging Flask and I'm glad that it's not a problem with the framework. I knew it couldn't be.\n", "Add \"threaded=True\" as an argument to app.run(), as suggested here:\nhttp://arusahni.net/blog/2013/10/flask-multithreading.html\nFor example: app.run(host=\"0.0.0.0\", port=8080, threaded=True)\nThe ipv6-disabling solution did not work for me, but this did. \n", "Instead of calling http://localhost:port/endpoint call http://127.0.0.1:port/endpoint. \nThis removed the initial 500ms delay for me.\n", "The solution from @sajid-siddiqi is technically correct, but keep in mind that the built-in WSGI server in Werkzeug (which is packaged into Flask and what it uses for app.run()) is only single-threaded.\nInstall a WSGI server to be able to handle multi-threaded behavior. I did a bunch of research on various WSGI server performances. Your needs may vary, but if all you're using is Flask, then I would recommend one of the following webservers.\nUpdate (2020-07-25): It looks like gevent started supporting python3 5 years ago, shortly after I commented that it didn't, so you can use gevent now.\ngevent\nYou can install gevent through pip with the command pip install gevent or pip3 with the command pip3 install gevent. Instructions on how to modify your code accordingly are here: https://flask.palletsprojects.com/en/1.1.x/deploying/wsgi-standalone/#gevent\nmeinheld\ngevent is better, but from all the benchmarks I've looked at that involve real-world testing, meinheld seems to be the most straightforward, simplistic WSGI server. (You could also take a look at uWSGI if you don't mind some more configuration.)\nYou can also install meinheld through pip3 with the command pip3 install meinheld. From there, look at the sample provided in the meinheld source to integrate Flask: https://github.com/mopemope/meinheld/blob/master/example/flask_sample.py\n*NOTE: From my use of PyCharm, the line from meinheld import server highlights as an error, but the server will run, so you can ignore the error.\n", "My problem was solved by \"threaded=True\", but I want to give some background to distinguish my problem from others for which this may not do it.\n\nMy issue only arose when running Flask with python3. Switching to python2, I no longer had this issue.\nMy problem manifested only when accessing the api with Chrome, at which point, Chrome displayed the expected screen, but everything else hung (curl, ffx, etc) until I either reloaded or closed the Chrome tab, at which point everything else that was waiting around returned a result.\n\nMy best guess is that Chrome was trying to keep the session open and Flask was blocking the subsequent requests. As soon as the connection from Chrome was stopped or reset, everything else was processed.\nIn my case, threading fixed it. Of course, I'm now going through some of the links others have provided to make sure that it's not going to cause any other issues.\n", "threaded=True works for me, but finally I figured out that the issue is due to foxyproxy on firefox. Since when the flask app is running on localhost, slow response happens if\n\nfoxyproxy is enabled on firefox\n\nslow response won't happen if\n\nfoxyproxy is disabled on firefox\naccess the website using other browsers\n\nThe only solution I found is to disable foxyproxy, tried to add localhost to proxy blacklist and tweak settings but none of them worked.\n", "I used Miheko's response to solve my issue. \n::1 localhost was already commented out on my hosts file, and setting Threaded=true didn't work for me. Every REST request was taking 1 second to process instead of being instant.\nI'm using python 3.6, and I got flask to be fast and responsive to REST requests by making flask use gevent as its WSGI.\nTo use gevent, install it with pip install gevent\nAfterwards, I used the https://gist.github.com/viksit/b6733fe1afdf5bb84a40#file-async_flask-py-L41 to set flask to use gevent.\nIncase the link goes down, here's the important parts of the script:\nfrom flask import Flask, Response\nfrom gevent.pywsgi import WSGIServer\nfrom gevent import monkey\n\n# need to patch sockets to make requests async\n# you may also need to call this before importing other packages that setup ssl\nmonkey.patch_all()\n\napp = Flask(__name__) \n\n\n# define some REST endpoints... \n\ndef main():\n\n # use gevent WSGI server instead of the Flask\n # instead of 5000, you can define whatever port you want.\n http = WSGIServer(('', 5000), app.wsgi_app) \n\n # Serve your application\n http.serve_forever()\n\n\nif __name__ == '__main__':\n main()\n\n", "I got this error when running on hosts other than localhost as well, so for some, different underlying problems may exhibit the same symptoms.\nI switched most of the things I've been using to Tornado, and anecdotally it's helped an amount. I've had a few slow page loads, but things seem generally more responsive. Also, very anecdotal, but I seem to notice that Flask alone will slow down over time, but Flask + Tornado less so. I imagine using Apache and mod_wsgi would make things even better, but Tornado's really simple to set up (see http://flask.pocoo.org/docs/deploying/others/).\n(Also, a related question: Flask app occasionally hanging)\n", "I had a different solution here. I just deleted all .pyc from the server's directory and started it again.\nBy the way, localhost was already commented out in my hosts file (Windows 8).\nThe server was freezing the whole time and now it works fine again.\n", "I run Python 3.8.10 which works fine, but as soon as I switch to Python 3.10.6 responses will be awful slow.\nI could get around this problem with changing the precedence to IPv4 in /etc/gai.conf\n" ]
[ 99, 97, 17, 14, 8, 5, 4, 0, 0, 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0011150343_flask_python.txt
Q: PyQt6 - Dummy child class not showing when inheriting from QWidget (but shows when inheriting from QLabel) I'm learning PyQt / Qt and I am facing a basic problem. I want to make a child class that inherits from QWidget but for some reason it does not show. For trouble shooting, I've used a simple dummy child class. from PyQt6.QtWidgets import QWidget, QApplication,QMainWindow, QLabel import sys class TestWidget(QWidget): pass class TestLabel(QLabel): pass app = QApplication(sys.argv) w = QMainWindow() w.resize(500,500) w.setStyleSheet('background-color: white;') w.show() #frame = QWidget(w) # SHOWS frame = TestWidget(w) # DOES NOT SHOW #frame = TestLabel(w) # SHOWS frame.resize(200,200) frame.setStyleSheet('background-color: red;') frame.show() app.exec() In the code sample I have tested the following scenarios (by commenting out the other two options). The expected result is a red rectangle in the upper left corner: Using a simple QWidget; it shows Using a dummy child class of QWidget; it does not show Using a dummy child class of QLabel; it shows The code is really simple so I'm struggling to understand what's going on. I'm using Python 3.11 on Mac OS Ventura (Apple Silicon). Any ideas? A: It's because the QWidget class is the base class of all widgets and designed to have no drawing(painting) logic in it even for the background by default. In most cases of deriving from the QWidget, you either implement a custom drawing logic by overriding paintEvent() or use it as an invisible event receiver. The behavior that a QWidget instance(not a derived one) with the background specified by the style sheet draws the background is documented in the official Qt wiki at this, or in the official reference at this.(The second link was given by musicamante.) But it is rather controversial because it should not draw the background in the view point that the QWidget does not have drawing logic in paintEvent(), but it should draw the background in the view point that an HTML element with the CSS background is drawn with the background. If you want to draw the background without overriding paintEvent(), use the autoFillBackground property like this. from PyQt6.QtCore import Qt from PyQt6.QtGui import QPalette ... class TestWidget(QWidget): pass ... frame = TestWidget(w) frame.setAutoFillBackground(True) pal = QPalette() pal.setColor(QPalette.ColorRole.Window, Qt.GlobalColor.red) frame.setPalette(pal) ... Of course, simply deriving your class from the QFrame or QLabel will be much easier.
PyQt6 - Dummy child class not showing when inheriting from QWidget (but shows when inheriting from QLabel)
I'm learning PyQt / Qt and I am facing a basic problem. I want to make a child class that inherits from QWidget but for some reason it does not show. For trouble shooting, I've used a simple dummy child class. from PyQt6.QtWidgets import QWidget, QApplication,QMainWindow, QLabel import sys class TestWidget(QWidget): pass class TestLabel(QLabel): pass app = QApplication(sys.argv) w = QMainWindow() w.resize(500,500) w.setStyleSheet('background-color: white;') w.show() #frame = QWidget(w) # SHOWS frame = TestWidget(w) # DOES NOT SHOW #frame = TestLabel(w) # SHOWS frame.resize(200,200) frame.setStyleSheet('background-color: red;') frame.show() app.exec() In the code sample I have tested the following scenarios (by commenting out the other two options). The expected result is a red rectangle in the upper left corner: Using a simple QWidget; it shows Using a dummy child class of QWidget; it does not show Using a dummy child class of QLabel; it shows The code is really simple so I'm struggling to understand what's going on. I'm using Python 3.11 on Mac OS Ventura (Apple Silicon). Any ideas?
[ "It's because the QWidget class is the base class of all widgets and designed to have no drawing(painting) logic in it even for the background by default. In most cases of deriving from the QWidget, you either implement a custom drawing logic by overriding paintEvent() or use it as an invisible event receiver.\nThe behavior that a QWidget instance(not a derived one) with the background specified by the style sheet draws the background is documented in the official Qt wiki at this, or in the official reference at this.(The second link was given by musicamante.) But it is rather controversial because it should not draw the background in the view point that the QWidget does not have drawing logic in paintEvent(), but it should draw the background in the view point that an HTML element with the CSS background is drawn with the background.\nIf you want to draw the background without overriding paintEvent(), use the autoFillBackground property like this.\nfrom PyQt6.QtCore import Qt\nfrom PyQt6.QtGui import QPalette\n...\n\nclass TestWidget(QWidget):\n pass\n\n...\nframe = TestWidget(w)\nframe.setAutoFillBackground(True)\npal = QPalette()\npal.setColor(QPalette.ColorRole.Window, Qt.GlobalColor.red)\nframe.setPalette(pal)\n...\n\nOf course, simply deriving your class from the QFrame or QLabel will be much easier.\n" ]
[ 0 ]
[]
[]
[ "pyqt6", "python" ]
stackoverflow_0074496042_pyqt6_python.txt
Q: Why my code is not accepted in the contest? def is_the_same(palavraa): i=0 j=1 n=2 while len(palavraa)!=0: if palavraa[0]==palavraa[i] and palavraa[1]==palavraa[j] and palavraa[2]==palavraa[n]: if i+3<len(palavraa): i=i+3 elif j+3<len(palavraa): j=j+3 elif n+3<len(palavraa): n=n+3 else: break else: return False return True x = input() t = int(x) if t>=1 and t<=1000 : while t!=0: palavra = input() if len(palavra)>=3 and len(palavra)<=50: if palavra[0]=='Y' and palavra[1]=='e' and palavra[2]=='s': if is_the_same(palavra)==True: print("YES") else: print("NO") elif palavra[0]=='s' and palavra[1]=='Y' and palavra[2]=='e': if is_the_same(palavra)==True: print("YES") else: print("NO") elif palavra[0]=='e' and palavra[1]=='s' and palavra[2]=='Y': if is_the_same(palavra)==True: print("YES") else: print("NO") elif palavra[0]=='e' and palavra[1]=='s' and palavra[2]=='Y': if is_the_same(palavra)==True: print("YES") else: print("NO") else: print("NO") elif len(palavra)==2: if palavra[0]=='s' and palavra[1]=='Y': print("YES") elif palavra[0]=='e' and palavra[1]=='s': print("YES") else: print("NO") else: print("NO") t=t-1 Did I write this code in order to solve the Sim-Sim problem? from codeforces Rond 834 Div 3 and when testing it with the inputs given by the site, they all gave the expected output but when I submitted the code it gave the wrong answer. Where did I go wrong? The problem is: A: def is_the_same(palavraa): i=0 j=1 n=2 while len(palavraa)!=0: if palavraa[0]==palavraa[i] and palavraa[1]==palavraa[j] and palavraa[2]==palavraa[n]: if i+3<len(palavraa): i=i+3 elif j+3<len(palavraa): j=j+3 elif n+3<len(palavraa): n=n+3 else: break else: return False return True This block of code is very strange. After staring at it for a while I understand what it's trying to do, but you're going about it in a very confusing way. First, the condition on your while statement len(palavraa)!=0 isn't modified by anything inside the loop - this makes it very difficult to read. Second, the if/elif structure means that you'll only be updating one of the three variables per loop iteration, when really, you want to want to be doing all three. This would be much simpler as: i = 0 while(i + 3 < len(palvara)): if (palvara[i] != palvara[i+3]): return False i = i + 1 return True Your basic algorithm seems to be to check if the string is a repition of the same three characters, and then see if the first three characters are "Y", "e" and "s" rotated in any manner. Right? Moving on, you repeat this clause: elif palavra[0]=='e' and palavra[1]=='s' and palavra[2]=='Y': if is_the_same(palavra)==True: print("YES") else: print("NO") Finally, you don't cover all of the shorter clauses - you miss one of the 2-length strings, and have nothing for length 1. By the way, in general coding contests will run some number of public tests, then some number of hidden tests. You'll be shown what went wrong if you fail a public test, but if you fail a hidden test it will be up to you to figure out what went wrong by reviewing your code and the problem statement.
Why my code is not accepted in the contest?
def is_the_same(palavraa): i=0 j=1 n=2 while len(palavraa)!=0: if palavraa[0]==palavraa[i] and palavraa[1]==palavraa[j] and palavraa[2]==palavraa[n]: if i+3<len(palavraa): i=i+3 elif j+3<len(palavraa): j=j+3 elif n+3<len(palavraa): n=n+3 else: break else: return False return True x = input() t = int(x) if t>=1 and t<=1000 : while t!=0: palavra = input() if len(palavra)>=3 and len(palavra)<=50: if palavra[0]=='Y' and palavra[1]=='e' and palavra[2]=='s': if is_the_same(palavra)==True: print("YES") else: print("NO") elif palavra[0]=='s' and palavra[1]=='Y' and palavra[2]=='e': if is_the_same(palavra)==True: print("YES") else: print("NO") elif palavra[0]=='e' and palavra[1]=='s' and palavra[2]=='Y': if is_the_same(palavra)==True: print("YES") else: print("NO") elif palavra[0]=='e' and palavra[1]=='s' and palavra[2]=='Y': if is_the_same(palavra)==True: print("YES") else: print("NO") else: print("NO") elif len(palavra)==2: if palavra[0]=='s' and palavra[1]=='Y': print("YES") elif palavra[0]=='e' and palavra[1]=='s': print("YES") else: print("NO") else: print("NO") t=t-1 Did I write this code in order to solve the Sim-Sim problem? from codeforces Rond 834 Div 3 and when testing it with the inputs given by the site, they all gave the expected output but when I submitted the code it gave the wrong answer. Where did I go wrong? The problem is:
[ "def is_the_same(palavraa):\ni=0\nj=1\nn=2\nwhile len(palavraa)!=0:\n if palavraa[0]==palavraa[i] and palavraa[1]==palavraa[j] and palavraa[2]==palavraa[n]:\n if i+3<len(palavraa):\n i=i+3\n elif j+3<len(palavraa):\n j=j+3\n elif n+3<len(palavraa):\n n=n+3\n else:\n break\n else:\n return False\nreturn True\n\nThis block of code is very strange. After staring at it for a while I understand what it's trying to do, but you're going about it in a very confusing way. First, the condition on your while statement len(palavraa)!=0 isn't modified by anything inside the loop - this makes it very difficult to read. Second, the if/elif structure means that you'll only be updating one of the three variables per loop iteration, when really, you want to want to be doing all three. This would be much simpler as:\ni = 0\nwhile(i + 3 < len(palvara)):\n if (palvara[i] != palvara[i+3]):\n return False\n i = i + 1\nreturn True\n\nYour basic algorithm seems to be to check if the string is a repition of the same three characters, and then see if the first three characters are \"Y\", \"e\" and \"s\" rotated in any manner. Right?\nMoving on, you repeat this clause:\n elif palavra[0]=='e' and palavra[1]=='s' and palavra[2]=='Y':\n if is_the_same(palavra)==True:\n print(\"YES\")\n else:\n print(\"NO\")\n\nFinally, you don't cover all of the shorter clauses - you miss one of the 2-length strings, and have nothing for length 1.\nBy the way, in general coding contests will run some number of public tests, then some number of hidden tests. You'll be shown what went wrong if you fail a public test, but if you fail a hidden test it will be up to you to figure out what went wrong by reviewing your code and the problem statement.\n" ]
[ 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074497310_python_string.txt
Q: Change the output shape of Pytorch GAN Generator? I'm trying to build a GAN model that outputs sound, specifically the speech of the digits 0-9. I'm basing my GAN model on a conditional GAN used for the regular image MNIST dataset. One of the main differences is that the shape of my data is 256x64, where as MNIST is 64x64. How can I modify the Generator to output 256x64? Can this be done by modifying the values of the Convtranspose2d layers? Or would it work to create a linear layer at the end of the sequential layer? Do convolutional layers always need to be square? As in the dimensions need be the same value i.e. 64x64? This is what the Generator looked like for the regular MNIST dataset: class Generator(nn.Module): def __init__(self, channels_noise, channels_img, features_g, num_classes, x1_size, x2_size, embed_size): super(Generator, self).__init__() self.x1_size = x1_size self.x1_size = x1_size self.net = nn.Sequential( # Input: N x channels_noise x 1 x 1 self._block(channels_noise+embed_size, features_g * 16, 4, 1, 0), # img: 4x4 self._block(features_g * 16, features_g * 8, 4, 2, 1), # img: 8x8 self._block(features_g * 8, features_g * 4, 4, 2, 1), # img: 16x16 self._block(features_g * 4, features_g * 2, 4, 2, 1), # img: 32x32 nn.ConvTranspose2d( features_g * 2, channels_img, kernel_size=4, stride=2, padding=1 ), # Output: N x channels_img x 64 x 64 nn.Tanh(), ) self.embed = nn.Embedding(num_classes, embed_size) def _block(self, in_channels, out_channels, kernel_size, stride, padding): return nn.Sequential( nn.ConvTranspose2d( in_channels, out_channels, kernel_size, stride, padding, bias=False, ), nn.BatchNorm2d(out_channels), nn.ReLU(), ) def forward(self, x, labels): # latent vector z = num_samples x noise_dim x 1 x 1 embedding = self.embed(labels).unsqueeze(2).unsqueeze(3) x = torch.cat([x, embedding], dim=1) return self.net(x).to(device) A: There are a number of ways to do this - using a linear layer at the end of the sequential layer will work but it will be the equivalent of stretching a 64 x 64 output to a 256 x 64 output. A more effective method would be to set the kernel size of the first convolutional layer so that the subsequent image resolutions are of the ratio 4N x N (since the expected resolution is (4*64) x (64) = 256 x 64). This can be done by defining the initial layers as: self._block(channels_noise+embed_size, features_g * 16, (4, 1), 1, 0), # img: 4x1 self._block(features_g * 16, features_g * 16, 4, 1, 0), # 16x4 self._block(features_g * 16, features_g * 8, 4, 2, 1), # img: 32x8
Change the output shape of Pytorch GAN Generator?
I'm trying to build a GAN model that outputs sound, specifically the speech of the digits 0-9. I'm basing my GAN model on a conditional GAN used for the regular image MNIST dataset. One of the main differences is that the shape of my data is 256x64, where as MNIST is 64x64. How can I modify the Generator to output 256x64? Can this be done by modifying the values of the Convtranspose2d layers? Or would it work to create a linear layer at the end of the sequential layer? Do convolutional layers always need to be square? As in the dimensions need be the same value i.e. 64x64? This is what the Generator looked like for the regular MNIST dataset: class Generator(nn.Module): def __init__(self, channels_noise, channels_img, features_g, num_classes, x1_size, x2_size, embed_size): super(Generator, self).__init__() self.x1_size = x1_size self.x1_size = x1_size self.net = nn.Sequential( # Input: N x channels_noise x 1 x 1 self._block(channels_noise+embed_size, features_g * 16, 4, 1, 0), # img: 4x4 self._block(features_g * 16, features_g * 8, 4, 2, 1), # img: 8x8 self._block(features_g * 8, features_g * 4, 4, 2, 1), # img: 16x16 self._block(features_g * 4, features_g * 2, 4, 2, 1), # img: 32x32 nn.ConvTranspose2d( features_g * 2, channels_img, kernel_size=4, stride=2, padding=1 ), # Output: N x channels_img x 64 x 64 nn.Tanh(), ) self.embed = nn.Embedding(num_classes, embed_size) def _block(self, in_channels, out_channels, kernel_size, stride, padding): return nn.Sequential( nn.ConvTranspose2d( in_channels, out_channels, kernel_size, stride, padding, bias=False, ), nn.BatchNorm2d(out_channels), nn.ReLU(), ) def forward(self, x, labels): # latent vector z = num_samples x noise_dim x 1 x 1 embedding = self.embed(labels).unsqueeze(2).unsqueeze(3) x = torch.cat([x, embedding], dim=1) return self.net(x).to(device)
[ "There are a number of ways to do this - using a linear layer at the end of the sequential layer will work but it will be the equivalent of stretching a 64 x 64 output to a 256 x 64 output.\nA more effective method would be to set the kernel size of the first convolutional layer so that the subsequent image resolutions are of the ratio 4N x N (since the expected resolution is (4*64) x (64) = 256 x 64). This can be done by defining the initial layers as:\nself._block(channels_noise+embed_size, features_g * 16, (4, 1), 1, 0), # img: 4x1\nself._block(features_g * 16, features_g * 16, 4, 1, 0), # 16x4\nself._block(features_g * 16, features_g * 8, 4, 2, 1), # img: 32x8\n\n" ]
[ 0 ]
[]
[]
[ "generative_adversarial_network", "python", "pytorch" ]
stackoverflow_0074497317_generative_adversarial_network_python_pytorch.txt
Q: Can i use input while using write mode for files crud operation in Python? """10-3. Guest: Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt.""" filename2 = "../Data/guest.txt" with open(filename2, "w") as guest_info: filename = input(str(guest_info)) for info in guest_info: print(f"name: {info}") I already created empty txt file. I need to let user fill with info. How would you solve this? 10-3. Guest: Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt.""" filename2 = "../Data/guest.txt" with open(filename2, "w") as guest_info: filename = input(str(guest_info)) for info in guest_info: print(f"name: {info}") I was expecting, that input would work but it says it isn't readable.
Can i use input while using write mode for files crud operation in Python?
"""10-3. Guest: Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt.""" filename2 = "../Data/guest.txt" with open(filename2, "w") as guest_info: filename = input(str(guest_info)) for info in guest_info: print(f"name: {info}") I already created empty txt file. I need to let user fill with info. How would you solve this? 10-3. Guest: Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt.""" filename2 = "../Data/guest.txt" with open(filename2, "w") as guest_info: filename = input(str(guest_info)) for info in guest_info: print(f"name: {info}") I was expecting, that input would work but it says it isn't readable.
[]
[]
[ "Take a look at the responses to this question: reading and writing to the same file simultaneously in python\nIt is possible to perform read and write operations with w+, you may find it more straightforward to add the new entry in write mode, then open in read mode to check the contents.\nDouble-check how you are working with your input function. The value you pass into the str() function is the prompt that will be displayed. e.g. to prompt for a name and enter it into your file, the following is a common approach:\nfilename = input(str(\"what is your name? \"))\nguest_info.write(filename)\n\n" ]
[ -1 ]
[ "file", "python" ]
stackoverflow_0074497123_file_python.txt
Q: resample data each column together in dataframe i have a dataframe named zz zz columns name ['Ancolmekar','Cidurian','Dayeuhkolot','Hantap','Kertasari','Meteolembang','Sapan'] for col in zz.columns: df = pd.DataFrame(zz[col],index=pd.date_range('2017-01-01 00:00:00', '2021-12-31 23:50:00', freq='10T')) df.resample('1M').mean() error : invalid syntax i want to know the mean value by month in 10 minutes data interval. when i run this just sapan values appear with NaN. before, i have replace the NaN data 1 else 0. Sapan 2017-01-31 NaN 2017-02-28 NaN 2017-03-31 NaN 2017-04-30 NaN 2017-05-31 NaN 2017-06-30 NaN 2017-07-31 NaN 2017-08-31 NaN 2017-09-30 NaN 2017-10-31 NaN 2017-11-30 NaN 2017-12-31 NaN 2018-01-31 NaN 2018-02-28 NaN 2018-03-31 NaN 2018-04-30 NaN 2018-05-31 NaN 2018-06-30 NaN 2018-07-31 NaN 2018-08-31 NaN 2018-09-30 NaN 2018-10-31 NaN 2018-11-30 NaN 2018-12-31 NaN 2019-01-31 NaN 2019-02-28 NaN 2019-03-31 NaN 2019-04-30 NaN 2019-05-31 NaN 2019-06-30 NaN 2019-07-31 NaN 2019-08-31 NaN 2019-09-30 NaN 2019-10-31 NaN 2019-11-30 NaN 2019-12-31 NaN 2020-01-31 NaN 2020-02-29 NaN 2020-03-31 NaN 2020-04-30 NaN 2020-05-31 NaN 2020-06-30 NaN 2020-07-31 NaN 2020-08-31 NaN 2020-09-30 NaN 2020-10-31 NaN 2020-11-30 NaN 2020-12-31 NaN 2021-01-31 NaN 2021-02-28 NaN 2021-03-31 NaN 2021-04-30 NaN 2021-05-31 NaN 2021-06-30 NaN 2021-07-31 NaN 2021-08-31 NaN 2021-09-30 NaN 2021-10-31 NaN 2021-11-30 NaN 2021-12-31 NaN what should i do? thanks before A: You are re-assigninig variable df to a dataframe with a single column during each pass through the for loop. The last column is sapan. Hence, only this column is shown. Additionally, you are setting the index on df that probably isn't the index in zz, therefore you get Not A Number NaN for non-existing values. If the index in zz is corresponding to the one you are setting, this should work: df = zz.copy() df['new_column'] = pd.Series(pd.date_range('2017-01-01 00:00:00', '2021-12-31 23:50:00', freq='10T')) df = df.set_index('new_column') df.resample('1M').mean()
resample data each column together in dataframe
i have a dataframe named zz zz columns name ['Ancolmekar','Cidurian','Dayeuhkolot','Hantap','Kertasari','Meteolembang','Sapan'] for col in zz.columns: df = pd.DataFrame(zz[col],index=pd.date_range('2017-01-01 00:00:00', '2021-12-31 23:50:00', freq='10T')) df.resample('1M').mean() error : invalid syntax i want to know the mean value by month in 10 minutes data interval. when i run this just sapan values appear with NaN. before, i have replace the NaN data 1 else 0. Sapan 2017-01-31 NaN 2017-02-28 NaN 2017-03-31 NaN 2017-04-30 NaN 2017-05-31 NaN 2017-06-30 NaN 2017-07-31 NaN 2017-08-31 NaN 2017-09-30 NaN 2017-10-31 NaN 2017-11-30 NaN 2017-12-31 NaN 2018-01-31 NaN 2018-02-28 NaN 2018-03-31 NaN 2018-04-30 NaN 2018-05-31 NaN 2018-06-30 NaN 2018-07-31 NaN 2018-08-31 NaN 2018-09-30 NaN 2018-10-31 NaN 2018-11-30 NaN 2018-12-31 NaN 2019-01-31 NaN 2019-02-28 NaN 2019-03-31 NaN 2019-04-30 NaN 2019-05-31 NaN 2019-06-30 NaN 2019-07-31 NaN 2019-08-31 NaN 2019-09-30 NaN 2019-10-31 NaN 2019-11-30 NaN 2019-12-31 NaN 2020-01-31 NaN 2020-02-29 NaN 2020-03-31 NaN 2020-04-30 NaN 2020-05-31 NaN 2020-06-30 NaN 2020-07-31 NaN 2020-08-31 NaN 2020-09-30 NaN 2020-10-31 NaN 2020-11-30 NaN 2020-12-31 NaN 2021-01-31 NaN 2021-02-28 NaN 2021-03-31 NaN 2021-04-30 NaN 2021-05-31 NaN 2021-06-30 NaN 2021-07-31 NaN 2021-08-31 NaN 2021-09-30 NaN 2021-10-31 NaN 2021-11-30 NaN 2021-12-31 NaN what should i do? thanks before
[ "You are re-assigninig variable df to a dataframe with a single column during each pass through the for loop. The last column is sapan. Hence, only this column is shown.\nAdditionally, you are setting the index on df that probably isn't the index in zz, therefore you get Not A Number NaN for non-existing values.\nIf the index in zz is corresponding to the one you are setting, this should work:\ndf = zz.copy()\ndf['new_column'] = pd.Series(pd.date_range('2017-01-01 00:00:00', '2021-12-31 23:50:00', freq='10T'))\ndf = df.set_index('new_column')\ndf.resample('1M').mean()\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074497216_pandas_python.txt
Q: Abstracting away pyodbc connection in a function Python I'm running a lot of python scripts that need to access different servers of a SQL database. I'm hoping to be ab le to abstract away some of the heavy lifting of connecting using pyodbc. In a separate py file I'm defining the default driver and server (in the future I want to be able to add to this file so that different servers are easy to access) And trying to write a function that returns a pandas dataframe as the result so that I'm not constantly connecting and disconnecting from our servers just to query some data. Here is what I was thinking. ` #imports import pyodbc import pandas as pd default_driver = 'driverName' default_server = 'serverName' def sql_query(query, driver = default_driver, server = default_server): #accepts a T-SQL query, connects to the default server using the default driver #returns a pandas datafram of the data try: driver_server_string = 'DRIVER={' + str(driver) + '}; SERVER=' + str(server) +';TRUSTED_CONNECTION=YES;' conn = pyodbc.connect(driver_server_string) cursor = conn.cursor() result = cursor.execute(query) data = cursor.fetchall() result = pd.DataFrame(data=data) return result except pyodbc.ProgrammingError: print('SQL Query returned an error') finally: cursor.close() conn.close() Right now Im running into two errors And I'm also not sure if this is even the best way to accomplish my goal. Importing this function with: from environments import sql_query returns NameError: name 'sql_query' is not defined And even in the same script I get a module not found Original error was: DLL load failed while importing _multiarray_umath: The specified module could not be found. Ideally I wanted to be able to have connection to a sql server as simple as from pyFile import SomeClassOrFunction data = sql_query('query',server = 'serverName') and get a pandas df from the result. Thanks! A: Depending on the context, I would say what you're doing is fine. error 1: i don't think we have enough information to answer. an import error like this is likely the cause of something like how the file structure is set up that is making the other script not be able to see it. error 2 (_multiarray_umath): specifically what line is giving that error? FYI, Pandas has a function that you can just give a connection and a query to and it'll just return an data frame: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html
Abstracting away pyodbc connection in a function Python
I'm running a lot of python scripts that need to access different servers of a SQL database. I'm hoping to be ab le to abstract away some of the heavy lifting of connecting using pyodbc. In a separate py file I'm defining the default driver and server (in the future I want to be able to add to this file so that different servers are easy to access) And trying to write a function that returns a pandas dataframe as the result so that I'm not constantly connecting and disconnecting from our servers just to query some data. Here is what I was thinking. ` #imports import pyodbc import pandas as pd default_driver = 'driverName' default_server = 'serverName' def sql_query(query, driver = default_driver, server = default_server): #accepts a T-SQL query, connects to the default server using the default driver #returns a pandas datafram of the data try: driver_server_string = 'DRIVER={' + str(driver) + '}; SERVER=' + str(server) +';TRUSTED_CONNECTION=YES;' conn = pyodbc.connect(driver_server_string) cursor = conn.cursor() result = cursor.execute(query) data = cursor.fetchall() result = pd.DataFrame(data=data) return result except pyodbc.ProgrammingError: print('SQL Query returned an error') finally: cursor.close() conn.close() Right now Im running into two errors And I'm also not sure if this is even the best way to accomplish my goal. Importing this function with: from environments import sql_query returns NameError: name 'sql_query' is not defined And even in the same script I get a module not found Original error was: DLL load failed while importing _multiarray_umath: The specified module could not be found. Ideally I wanted to be able to have connection to a sql server as simple as from pyFile import SomeClassOrFunction data = sql_query('query',server = 'serverName') and get a pandas df from the result. Thanks!
[ "Depending on the context, I would say what you're doing is fine.\nerror 1: i don't think we have enough information to answer. an import error like this is likely the cause of something like how the file structure is set up that is making the other script not be able to see it.\nerror 2 (_multiarray_umath): specifically what line is giving that error?\nFYI, Pandas has a function that you can just give a connection and a query to and it'll just return an data frame: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html\n" ]
[ 0 ]
[]
[]
[ "abstraction", "pyodbc", "python" ]
stackoverflow_0074497385_abstraction_pyodbc_python.txt
Q: Iterating two lists with two different sliding windows in one loop I have two very large lists, and I want use one loop for iterating over two of them with the different sliding windows. Is that possible? if not, what is the best way? For example, I have A and B, I want a loop which provide the summation of sliding window 2 of list B and sliding window of size 3 of A. A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13] B = [-1,2, 3, 14, 51, 16, 7, 18 ] Sliding window of size 3 in A = [1,4,7,10] Sliding window of size 2 in B = [-1,3,5,7] Out: A + B = [0, 7, 12, 17] A: You could write this as a map over slices as follows: from operator import add res = map(add, A[::3], B[::2]) Another option is with a list comprehension / generator expression: res = [a + b for a, b in zip(A[::3], B[::2])] A: I found my answer with this way: for those, who maybe have same problem in future: w1 = 3 w2 = 2 t = [] for i in range(0, 12, w1): index_w = int(i/w1) sum_temp = A[i]+ B[w2*index_w] t.append(sum_temp)
Iterating two lists with two different sliding windows in one loop
I have two very large lists, and I want use one loop for iterating over two of them with the different sliding windows. Is that possible? if not, what is the best way? For example, I have A and B, I want a loop which provide the summation of sliding window 2 of list B and sliding window of size 3 of A. A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13] B = [-1,2, 3, 14, 51, 16, 7, 18 ] Sliding window of size 3 in A = [1,4,7,10] Sliding window of size 2 in B = [-1,3,5,7] Out: A + B = [0, 7, 12, 17]
[ "You could write this as a map over slices as follows:\nfrom operator import add\nres = map(add, A[::3], B[::2])\n\nAnother option is with a list comprehension / generator expression:\nres = [a + b for a, b in zip(A[::3], B[::2])]\n\n", "I found my answer with this way: for those, who maybe have same problem in future:\nw1 = 3\nw2 = 2\nt = []\nfor i in range(0, 12, w1):\n index_w = int(i/w1)\n sum_temp = A[i]+ B[w2*index_w]\n t.append(sum_temp)\n\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074497401_python.txt
Q: ModuleNotFoundError: No module named 'tensorflow_docs' when creating TensorFlow docs I'm trying to follow the contribution guide for documentation. The required steps are: git clone https://github.com/tensorflow/tensorflow tensorflow cd tensorflow/tensorflow/tools/docs pip install tensorflow==2.0.0-alpha0 python generate2.py --output_dir=/tmp/out But the last command gives me: Traceback (most recent call last): File "generate2.py", line 36, in from tensorflow_docs.api_generator import doc_controls ModuleNotFoundError: No module named 'tensorflow_docs' This is in line 36 of generate2.py: from tensorflow_docs.api_generator import doc_controls I haven't found a pip package containing tensorflow_docs. Any ideas? A: First install tensorflow_docs using this command: pip install git+https://github.com/tensorflow/docs A: first, you need to install git. install git by using this command conda install git in anaconda prompt. then run the following command !pip install -q git+https://github.com/tensorflow/docs in jupyter notebook OR pip install -q git+https://github.com/tensorflow/docs in anaconda prompt. A: I have a try and figure out how to solve the problem. Since I have multuple Python versions by checking "conda list" and "pip list", either the Jupyter or IDE installation method could not install tensorflow_docs into the correct directory. 1.For Jupyter $ conda install git $ !pip install -q git+https://github.com/tensorflow/docs 2.For IDE $ conda install git $ pip install -q git+https://github.com/tensorflow/docs The problem is that pip has installed tensorflow_docs into the default directory of Python 3.6 with the following path: /home/user/local/lib/python3.6/site-packages. However, I use Python 3.9 in the conda environment in the most of the time. 3.Copy tensorflow_docs into Python 3.9 site-packages It is applicable after putting tensorflow_docs to the designated directory of Python 3.9. So I can use tensorflow_docs after the following operations: First.Download tensorflow_docs https://github.com/tensorflow/docs/tree/master/tools/tensorflow_docs Second.Save tensorflow_docs in Python 3.9 directory /home/user/miniconda3/lib/python3.9/site-packages/tensorflow_docs
ModuleNotFoundError: No module named 'tensorflow_docs' when creating TensorFlow docs
I'm trying to follow the contribution guide for documentation. The required steps are: git clone https://github.com/tensorflow/tensorflow tensorflow cd tensorflow/tensorflow/tools/docs pip install tensorflow==2.0.0-alpha0 python generate2.py --output_dir=/tmp/out But the last command gives me: Traceback (most recent call last): File "generate2.py", line 36, in from tensorflow_docs.api_generator import doc_controls ModuleNotFoundError: No module named 'tensorflow_docs' This is in line 36 of generate2.py: from tensorflow_docs.api_generator import doc_controls I haven't found a pip package containing tensorflow_docs. Any ideas?
[ "First install tensorflow_docs using this command:\npip install git+https://github.com/tensorflow/docs \n", "first, you need to install git.\ninstall git by using this command conda install git in anaconda prompt. then run the following command\n!pip install -q git+https://github.com/tensorflow/docs \n\nin jupyter notebook\nOR\npip install -q git+https://github.com/tensorflow/docs\n\nin anaconda prompt.\n", "I have a try and figure out how to solve the problem. Since I have multuple Python versions by checking \"conda list\" and \"pip list\", either the Jupyter or IDE installation method could not install tensorflow_docs into the correct directory.\n1.For Jupyter\n$ conda install git\n$ !pip install -q git+https://github.com/tensorflow/docs\n\n2.For IDE\n$ conda install git\n$ pip install -q git+https://github.com/tensorflow/docs\n\nThe problem is that pip has installed tensorflow_docs into the default directory of Python 3.6 with the following path: /home/user/local/lib/python3.6/site-packages. However, I use Python 3.9 in the conda environment in the most of the time.\n3.Copy tensorflow_docs into Python 3.9 site-packages\nIt is applicable after putting tensorflow_docs to the designated directory of Python 3.9. So I can use tensorflow_docs after the following operations:\nFirst.Download tensorflow_docs\nhttps://github.com/tensorflow/docs/tree/master/tools/tensorflow_docs\nSecond.Save tensorflow_docs in Python 3.9 directory\n/home/user/miniconda3/lib/python3.9/site-packages/tensorflow_docs\n\n" ]
[ 18, 3, 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0055535518_python_tensorflow.txt
Q: The view basket.views.basket_add didn't return an HttpResponse object. It returned None instead So when previously i tried to add the price, it worked. When I added the quantity of the product something failed. I watched it many times but without luck. If someone can help me I would be grateful. So that is my the error:enter image description here Then there are my views: enter image description here The HTML, and jquery/css: enter image description here and finally my add func: enter image description here I have to return the quantity with the success console log in the ajax in the chrome console. I tried to change the data type, adding a more advanced error func to show me more in-depth errors in the browser, refreshing the session, watched all the names that I have to see if I typed some names wrong. A: In your view, you are returning JsonResponse from the POST request. For the GET request, you are not producing any response. By default, the request is GET. Most probably you are making a GET request. Just add return HttpReponse('') at the end of the view or make sure you are making a proper POST request. def add_basket(request): if request.method == 'POST': # Add In basket return JsonResponse(data) return render(request,"app_name/add_basket.html")
The view basket.views.basket_add didn't return an HttpResponse object. It returned None instead
So when previously i tried to add the price, it worked. When I added the quantity of the product something failed. I watched it many times but without luck. If someone can help me I would be grateful. So that is my the error:enter image description here Then there are my views: enter image description here The HTML, and jquery/css: enter image description here and finally my add func: enter image description here I have to return the quantity with the success console log in the ajax in the chrome console. I tried to change the data type, adding a more advanced error func to show me more in-depth errors in the browser, refreshing the session, watched all the names that I have to see if I typed some names wrong.
[ "In your view, you are returning JsonResponse from the POST request. For the GET request, you are not producing any response. By default, the request is GET. Most probably you are making a GET request. Just add return HttpReponse('') at the end of the view or make sure you are making a proper POST request.\ndef add_basket(request):\n if request.method == 'POST':\n # Add In basket\n return JsonResponse(data)\n \n return render(request,\"app_name/add_basket.html\")\n\n" ]
[ 0 ]
[]
[]
[ "ajax", "django", "jquery", "python" ]
stackoverflow_0074494556_ajax_django_jquery_python.txt
Q: Does Python have a maximum group refer for regex (like Perl)? Context: When running a regex match in Perl, $1, $2 can be used as references to captured regex references from the match, similarly in Python \g<0>,\g<1> can be used Perl also has a $+ special reference which refers to the captured group with highest numerical value My question: Does Python have an equivalent of $+ ? I tried \g<+> and tried looking in the documentation which only says: There’s also a syntax for referring to named groups as defined by the (?P<name>...) syntax. \g<name> will use the substring matched by the group named name, and \g<number> uses the corresponding group number. \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement string such as \g<2>0. (\20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'.) The following substitutions are all equivalent, but use all three variations of the replacement string. A: The method captures in the regex module provides the same functionality: it "returns a list of all the captures of a group." So get the last one >>> import regex >>> str = 'fza' >>> m = regex.search(r'(a)|(f)', str) >>> print(m.captures()[-1]) f When the str has a before f this code prints a. This is the exact equivalent of Per's $+. Here we do get all captures, not only the highest one, and other related methods. Follow the word "captures" in the linked docs. Another option that fits the intended use, explained in a comment, is the branch reset group, (?|pattern). It is also available in the regex module. >>> import regex >>> m = regex.search(r'(?|(a)|(b))', 'zba') >>> m.group(1) 'b' In short, with the branch reset (?|(pA)|(pB)|(pC)) the whole pattern is one capture group (with three alternations), not three. So you always know which is the "last" capture as there is only one, which has the match. This can be used with named capture groups as well. This feature adds far more power as the pattern in (?|...) gets more complex. Find it in your favorite regex documentation. Here it is in regular-expressions.info, for example, and here are some Perl resources, in perlre and an article in The Effective Perler. A: In most case, you'd just use one capture around the alternation. (foo|bar|baz) In more complex cases, you could filter out None results. import re s = 'bar4' m = re.search( r'foo([12])|bar([34])|baz([56])', s ) [ g for g in m.groups() if g is not None ] # ['4']
Does Python have a maximum group refer for regex (like Perl)?
Context: When running a regex match in Perl, $1, $2 can be used as references to captured regex references from the match, similarly in Python \g<0>,\g<1> can be used Perl also has a $+ special reference which refers to the captured group with highest numerical value My question: Does Python have an equivalent of $+ ? I tried \g<+> and tried looking in the documentation which only says: There’s also a syntax for referring to named groups as defined by the (?P<name>...) syntax. \g<name> will use the substring matched by the group named name, and \g<number> uses the corresponding group number. \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement string such as \g<2>0. (\20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'.) The following substitutions are all equivalent, but use all three variations of the replacement string.
[ "The method captures in the regex module provides the same functionality: it \"returns a list of all the captures of a group.\" So get the last one\n>>> import regex\n>>> str = 'fza'\n>>> m = regex.search(r'(a)|(f)', str)\n>>> print(m.captures()[-1])\nf\n\nWhen the str has a before f this code prints a. This is the exact equivalent of Per's $+. Here we do get all captures, not only the highest one, and other related methods. Follow the word \"captures\" in the linked docs.\n\nAnother option that fits the intended use, explained in a comment, is the branch reset group, (?|pattern). It is also available in the regex module.\n>>> import regex\n>>> m = regex.search(r'(?|(a)|(b))', 'zba')\n>>> m.group(1)\n'b'\n\nIn short, with the branch reset (?|(pA)|(pB)|(pC)) the whole pattern is one capture group (with three alternations), not three. So you always know which is the \"last\" capture as there is only one, which has the match. This can be used with named capture groups as well.\nThis feature adds far more power as the pattern in (?|...) gets more complex. Find it in your favorite regex documentation. Here it is in regular-expressions.info, for example, and here are some Perl resources, in perlre and an article in The Effective Perler.\n", "In most case, you'd just use one capture around the alternation.\n(foo|bar|baz)\n\nIn more complex cases, you could filter out None results.\nimport re\ns = 'bar4'\nm = re.search( r'foo([12])|bar([34])|baz([56])', s )\n[ g for g in m.groups() if g is not None ] # ['4']\n\n" ]
[ 3, 2 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0074496411_perl_python_regex.txt
Q: What am I doing wrong turning Pandas DF to dict? I have a csv that looks like AccountExternalID Customer 1 RogerInc 2 FredLLC I am turning that into a Pandas DF, and I want to turn that into a dict that looks like {'RogerInc': 1, 'FredLLC': 2} This is what I tried; def build_custid_dict(csv_path: str=None) -> dict[str]: csv_path = r'\\path\CustomerIDs.csv' df = pd.read_csv(csv_path) # Strip whitespace df[df.columns] = df.apply(lambda x: x.str.strip()) df_dict = df.to_dict('list') return df_dict A: Example data = {'AccountExternalID': {0: 1, 1: 2}, 'Customer': {0: 'RogerInc', 1: 'FredLLC'}} df = pd.DataFrame(data) output(df): AccountExternalID Customer 0 1 RogerInc 1 2 FredLLC Code use following code in your func: dict(df.iloc[:, [1, 0]].values) result: {'RogerInc': 1, 'FredLLC': 2} A: The to_dict method will map the column headers to the column data. You don't want that for what you're trying to do. Instead, you can do something like this: ids = df['AccountExternalID'].values customers = df['Customer'].values df_dict = {customer:id for customer, id in zip(customers, ids)} A: Try this one you can select one column of the dataframe as the key and another one as the value of dict. def build_custid_dict(csv_path: str=None) -> dict[str]: csv_path = r'\\path\CustomerIDs.csv' df = pd.read_csv(csv_path) # Strip whitespace df['AccountExternalID'].str.strip() df['Customer'].str.strip() df = df.set_index('AccountExternalID') df_dict = df.to_dict('Customer') dict((v, k) for k, v in df_dict.items()) #reversing the keys and values return df_dict Also refer to this Stack overflow question A: You could also use the to_dict method on a series, e.g. df.set_index('Customer').AccountExternalID.to_dict()
What am I doing wrong turning Pandas DF to dict?
I have a csv that looks like AccountExternalID Customer 1 RogerInc 2 FredLLC I am turning that into a Pandas DF, and I want to turn that into a dict that looks like {'RogerInc': 1, 'FredLLC': 2} This is what I tried; def build_custid_dict(csv_path: str=None) -> dict[str]: csv_path = r'\\path\CustomerIDs.csv' df = pd.read_csv(csv_path) # Strip whitespace df[df.columns] = df.apply(lambda x: x.str.strip()) df_dict = df.to_dict('list') return df_dict
[ "Example\ndata = {'AccountExternalID': {0: 1, 1: 2}, 'Customer': {0: 'RogerInc', 1: 'FredLLC'}}\ndf = pd.DataFrame(data)\n\noutput(df):\n AccountExternalID Customer\n0 1 RogerInc\n1 2 FredLLC\n\nCode\nuse following code in your func:\ndict(df.iloc[:, [1, 0]].values)\n\nresult:\n{'RogerInc': 1, 'FredLLC': 2}\n\n", "The to_dict method will map the column headers to the column data. You don't want that for what you're trying to do.\nInstead, you can do something like this:\nids = df['AccountExternalID'].values\ncustomers = df['Customer'].values\ndf_dict = {customer:id for customer, id in zip(customers, ids)}\n\n", "Try this one you can select one column of the dataframe as the key and another one as the value of dict.\ndef build_custid_dict(csv_path: str=None) -> dict[str]:\n csv_path = r'\\\\path\\CustomerIDs.csv'\n df = pd.read_csv(csv_path)\n # Strip whitespace\n df['AccountExternalID'].str.strip()\n df['Customer'].str.strip()\n df = df.set_index('AccountExternalID') \n df_dict = df.to_dict('Customer')\n dict((v, k) for k, v in df_dict.items()) #reversing the keys and values\n return df_dict\n\nAlso refer to this Stack overflow question\n", "You could also use the to_dict method on a series, e.g.\ndf.set_index('Customer').AccountExternalID.to_dict()\n\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074497395_dictionary_pandas_python.txt
Q: I have this issue with my vscode executing a python file I can enter into my terminal (wsl) python3 filename.py and the code executes in the terminal just fine. But when I hit the play button (Run Python File) I get errors C:/Users/user1/AppData/Local/Programs/Python/Python311/python.exe "c:/Online Learning/Coder Academy/Python/Lesson-3/test.py" zsh: no such file or directory: C:/Users/user1/AppData/Local/Programs/Python/Python311/python.exe I don't see why if the code is executing fine from the terminal by typing in the command. Why can't I hit the play button without error? I've tried a lot of things including using extension Code-Runner. Uninstalling and re-installing various versions of python. I've tried pyenv, defining various different interpreter paths. I'm thinking it's not the set up of my python in wsl it's something to do with a setting in VSCode. A: I'm not totally sure, but it seems to be coughing up that "python.exe" doesn't exist. What I remember doing is checking if "py.exe" works and see if the problem is resolved. If so, go to where VSCode says Python is and copy py.exe to your desktop, rename it to python.exe and paste it back to the folder where py.exe was. It may not be good practice, but was my workaround. I guess the best thing to do is just to reinstall Python. A: I would agree with the setting in vscode. hitting cntrl+shift+p, type python, hit 'select' interpreter will let you pinpoint exactly where vscode thinks the interpreter is. For many reasons I would strongly recommend using a virtual env. For the purposes of this discussion, you know that you'll be creating a folder that has a version of python in it that you can select. Best of luck. these issues can be very frustrating
I have this issue with my vscode executing a python file
I can enter into my terminal (wsl) python3 filename.py and the code executes in the terminal just fine. But when I hit the play button (Run Python File) I get errors C:/Users/user1/AppData/Local/Programs/Python/Python311/python.exe "c:/Online Learning/Coder Academy/Python/Lesson-3/test.py" zsh: no such file or directory: C:/Users/user1/AppData/Local/Programs/Python/Python311/python.exe I don't see why if the code is executing fine from the terminal by typing in the command. Why can't I hit the play button without error? I've tried a lot of things including using extension Code-Runner. Uninstalling and re-installing various versions of python. I've tried pyenv, defining various different interpreter paths. I'm thinking it's not the set up of my python in wsl it's something to do with a setting in VSCode.
[ "I'm not totally sure, but it seems to be coughing up that \"python.exe\" doesn't exist. What I remember doing is checking if \"py.exe\" works and see if the problem is resolved. If so, go to where VSCode says Python is and copy py.exe to your desktop, rename it to python.exe and paste it back to the folder where py.exe was. It may not be good practice, but was my workaround. I guess the best thing to do is just to reinstall Python.\n", "I would agree with the setting in vscode.\nhitting cntrl+shift+p, type python, hit 'select' interpreter will let you pinpoint exactly where vscode thinks the interpreter is.\nFor many reasons I would strongly recommend using a virtual env. For the purposes of this discussion, you know that you'll be creating a folder that has a version of python in it that you can select.\nBest of luck. these issues can be very frustrating\n" ]
[ 0, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074497048_python_visual_studio_code.txt
Q: I have 40 columns and I want to concatenate every 2 columns of those 40 columns into 2 columns by using a loop How do I load the data and rearrange them so that x of shape (2000, 2) values and y of shape (2000,) that represent the labels? This is what I am currently doing now. This is the info I know: The dataframe has 100 rows × 40 columns so I p1 = q2_data.iloc[:,0:2] p2 = q2_data.iloc[:,2:4] ....... p20 = q2_data.iloc[:,38:40] new_columns = ["x1", "x2"] p1.columns = new_columns p2.columns = new_columns ..... p40.columns = new_columns print( pd.concat([p1, p2,.....,p20], ignore_index=True)) [2000 rows x 2 columns] How do I also had labels to each of the columns of p1, p2, .. p40? so I can create another column with labels ranging form (0,19) A: If you are looking for the loop logic, this probably works, not the best looking script tho. columns_name = ["x1", "x2"] # initiate the column name new_df = pd.DataFrame(columns=columns_name) # create an empty dataframe with column name for col_index in range(0,len(q2_data.columns))[::2]: # create a loop with sliding windows of 2 temp = q2_data.iloc[:,col_index:col_index+2] # create a temporary df to store the value temp.rename(dict(zip(list(temp.columns), columns_name)), inplace = True) # rename for concatenating purpose new_df = pd.concat([new_df, temp], ignore_index = True)
I have 40 columns and I want to concatenate every 2 columns of those 40 columns into 2 columns by using a loop
How do I load the data and rearrange them so that x of shape (2000, 2) values and y of shape (2000,) that represent the labels? This is what I am currently doing now. This is the info I know: The dataframe has 100 rows × 40 columns so I p1 = q2_data.iloc[:,0:2] p2 = q2_data.iloc[:,2:4] ....... p20 = q2_data.iloc[:,38:40] new_columns = ["x1", "x2"] p1.columns = new_columns p2.columns = new_columns ..... p40.columns = new_columns print( pd.concat([p1, p2,.....,p20], ignore_index=True)) [2000 rows x 2 columns] How do I also had labels to each of the columns of p1, p2, .. p40? so I can create another column with labels ranging form (0,19)
[ "If you are looking for the loop logic, this probably works, not the best looking script tho.\ncolumns_name = [\"x1\", \"x2\"] # initiate the column name\nnew_df = pd.DataFrame(columns=columns_name) # create an empty dataframe with column name\n\nfor col_index in range(0,len(q2_data.columns))[::2]: # create a loop with sliding windows of 2\n temp = q2_data.iloc[:,col_index:col_index+2] # create a temporary df to store the value\n \n temp.rename(dict(zip(list(temp.columns), columns_name)), inplace = True) # rename for concatenating purpose\n \n new_df = pd.concat([new_df, temp], ignore_index = True)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074497104_python.txt
Q: How to patch/mock import? I'm writing tests for airflow dag and running into issue mocking/patching the dag. # dag.py from airflow.models import Variable ENVIRONMENT = Variable.get("environment") # test_dag.py import dag class TestDAG(TestCase): def test_something(self): pass Because I'm just setting variable outside of function or class, it runs Variable.get() during import. This will be give me a SQLAlchemy error cause it's trying to connect to a db and fetch variable. sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: variable [SQL: SELECT variable.val AS variable_val, variable.id AS variable_id, variable."key" AS variable_key, variable.is_encrypted AS variable_is_encrypted FROM variable WHERE variable."key" = ? LIMIT ? OFFSET ?] [parameters: ('environment', 1, 0)] Is there a way to patch/mock airflow.models.Variable before it's imported? A: You'll need to defer importing the file until you can set a Variable value into the test database. A startTestRun method would be the perfect place. A: I have some workarounds but not a definite answer: You can move this line ENVIRONMENT = Variable.get("environment") into inside a function, instead of global. This way, it will not be executed when imported and you can add this mock to conftest.py: @pytest.fixture(autouse=True) def mock_airflow_variables(mocker): mocker.patch.object(target=Variable, attribute="get", return_value="test") You can import the module inside the test function. This way, the mock will be set before calling import. A: You can mock the import before importing the file import unittest from unittest.mock import MagicMock import sys class TestDAG(unittest.TestCase): def test_something(self): sys.modules['airflow.models'] = MagicMock() # This returns the MagicMock instance from airflow.models import Variable # Set the return_value of the .get() call Variable.get.return_value = "TEST" # import the dag after import dag Variable.get.assert_called_once() assert dag.ENVIRONMENT == "TEST" if __name__ == '__main__': unittest.main()
How to patch/mock import?
I'm writing tests for airflow dag and running into issue mocking/patching the dag. # dag.py from airflow.models import Variable ENVIRONMENT = Variable.get("environment") # test_dag.py import dag class TestDAG(TestCase): def test_something(self): pass Because I'm just setting variable outside of function or class, it runs Variable.get() during import. This will be give me a SQLAlchemy error cause it's trying to connect to a db and fetch variable. sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: variable [SQL: SELECT variable.val AS variable_val, variable.id AS variable_id, variable."key" AS variable_key, variable.is_encrypted AS variable_is_encrypted FROM variable WHERE variable."key" = ? LIMIT ? OFFSET ?] [parameters: ('environment', 1, 0)] Is there a way to patch/mock airflow.models.Variable before it's imported?
[ "You'll need to defer importing the file until you can set a Variable value into the test database. A startTestRun method would be the perfect place. \n", "I have some workarounds but not a definite answer:\n\nYou can move this line ENVIRONMENT = Variable.get(\"environment\") into inside a function, instead of global. This way, it will not be executed when imported and you can add this mock to conftest.py:\n\n@pytest.fixture(autouse=True)\ndef mock_airflow_variables(mocker):\n mocker.patch.object(target=Variable, attribute=\"get\", return_value=\"test\")\n\n\nYou can import the module inside the test function. This way, the mock will be set before calling import.\n\n", "You can mock the import before importing the file\nimport unittest\nfrom unittest.mock import MagicMock\n\nimport sys\n\n\nclass TestDAG(unittest.TestCase):\n\n def test_something(self):\n sys.modules['airflow.models'] = MagicMock()\n \n # This returns the MagicMock instance\n from airflow.models import Variable \n\n # Set the return_value of the .get() call\n Variable.get.return_value = \"TEST\" \n\n # import the dag after\n import dag\n\n Variable.get.assert_called_once()\n assert dag.ENVIRONMENT == \"TEST\"\n\n\nif __name__ == '__main__':\n unittest.main()\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "airflow", "mocking", "python", "testing", "unit_testing" ]
stackoverflow_0062314746_airflow_mocking_python_testing_unit_testing.txt
Q: Read all Excel sheets except one of them I'm using this line code to get all sheets from an Excel file: excel_file = pd.read_excel('path_file',skiprows=35,sheet_name=None) sheet_name=None option gets all the sheets. How do I get all sheets except one of them? A: If all you want to do is exclude one of the sheets, there is not much to change from your base code. Assume file.xlsx is an excel file with multiple sheets, and you want to skip 'Sheet1'. One possible solution is as follows: import pandas as pd # Returns a dictionary with key:value := sheet_name:df xlwb = pd.read_excel('file.xlsx', sheet_name=None) unwanted_sheet = 'Sheet1' # list comprehension that filters out unwanted sheet # all other sheets are kept in df_generator df_generator = (items for keys, items in xlwb.items() if keys != unwanted_sheet) # get to the actual dataframes for df in df_generator: print(df.head())
Read all Excel sheets except one of them
I'm using this line code to get all sheets from an Excel file: excel_file = pd.read_excel('path_file',skiprows=35,sheet_name=None) sheet_name=None option gets all the sheets. How do I get all sheets except one of them?
[ "If all you want to do is exclude one of the sheets, there is not much to change from your base code.\nAssume file.xlsx is an excel file with multiple sheets, and you want to skip 'Sheet1'.\nOne possible solution is as follows:\nimport pandas as pd\n\n# Returns a dictionary with key:value := sheet_name:df\nxlwb = pd.read_excel('file.xlsx', sheet_name=None)\nunwanted_sheet = 'Sheet1'\n\n# list comprehension that filters out unwanted sheet\n# all other sheets are kept in df_generator\ndf_generator = (items for keys, items in xlwb.items() \n if keys != unwanted_sheet)\n\n# get to the actual dataframes\nfor df in df_generator:\n print(df.head())\n\n" ]
[ 1 ]
[]
[]
[ "google_colaboratory", "pandas", "python" ]
stackoverflow_0074451953_google_colaboratory_pandas_python.txt
Q: How do i generate a string consisting of m number of rows and n number of cols, using random function Write a function named place_random_bricks(m, n, colours) that randomly places bricks row-wise (completes the current row placement before moving to the next row) on the baseplate. It must have three parameters: m - the number of rows on the base-plate, n - the number of columns on the base-plate, and colours - a random string constructed over “G, R, B, Y, C” (G-Green, R-Red, Blue-B, Y-Yellow, C-Cyan). This function should return a string of length m * n, where a character at any position i represents the colour of a brick placed on the baseplate (0 ≤ i < (m x n), i ∈ “colours′′); a value “G” (Green colour) represents no brick was placed. All colours have an equal probability of being selected. import random import colorama import string def place_random_bricks(m, n, colours): v_string=['G', 'R', 'B', 'Y', 'C'] for i in range(m * n): colours = string.ascii_uppercase a = print(''.join(random.choices(colours))) I am expecting a random number of RYBCG. A: I would recommend using numpy to generate random 2d arrays since. and the using a lookup string to convert those numbers to the list of random colours you want it to be converted to. import numpy as np def place_random_bricks(m,n, colors): ar = np.random.randint(0,len(colors),(m,n)) return '\n'.join([''.join([colors[j] for j in i]) for i in ar]) print(place_random_bricks(4,5,['G','R','B','Y','C'])) A: It seems odd that you wouldn't have to return an m*n matrix, but it clearly says it wants one string. import random def place_random_bricks(m, n, colours): row = [random.choice(colours) for _ in range(m*n)] return ''.join(row) print(place_random_bricks(5,5,'GRBYC')) Output: GGYGYBBCBGYCCGYGCRRRCBGCB
How do i generate a string consisting of m number of rows and n number of cols, using random function
Write a function named place_random_bricks(m, n, colours) that randomly places bricks row-wise (completes the current row placement before moving to the next row) on the baseplate. It must have three parameters: m - the number of rows on the base-plate, n - the number of columns on the base-plate, and colours - a random string constructed over “G, R, B, Y, C” (G-Green, R-Red, Blue-B, Y-Yellow, C-Cyan). This function should return a string of length m * n, where a character at any position i represents the colour of a brick placed on the baseplate (0 ≤ i < (m x n), i ∈ “colours′′); a value “G” (Green colour) represents no brick was placed. All colours have an equal probability of being selected. import random import colorama import string def place_random_bricks(m, n, colours): v_string=['G', 'R', 'B', 'Y', 'C'] for i in range(m * n): colours = string.ascii_uppercase a = print(''.join(random.choices(colours))) I am expecting a random number of RYBCG.
[ "I would recommend using numpy to generate random 2d arrays since. and the using a lookup string to convert those numbers to the list of random colours you want it to be converted to.\nimport numpy as np\ndef place_random_bricks(m,n, colors):\n ar = np.random.randint(0,len(colors),(m,n))\n return '\\n'.join([''.join([colors[j] for j in i]) for i in ar])\n\nprint(place_random_bricks(4,5,['G','R','B','Y','C']))\n\n", "It seems odd that you wouldn't have to return an m*n matrix, but it clearly says it wants one string.\nimport random\n\ndef place_random_bricks(m, n, colours):\n row = [random.choice(colours) for _ in range(m*n)]\n return ''.join(row)\n\nprint(place_random_bricks(5,5,'GRBYC'))\n\nOutput:\nGGYGYBBCBGYCCGYGCRRRCBGCB\n\n" ]
[ 1, 1 ]
[]
[]
[ "import", "python", "random", "string" ]
stackoverflow_0074480998_import_python_random_string.txt
Q: How can i print a function contained within another function and called by a third function? I would like to print 10, but I get the error: AttributeError: 'function' object has no attribute 'x' How to fix? Thank you def function1(): def x(): a=10 return a def function2(): y = function1.x() return y function2() A: Functions are not containers you can reference into - classes, objects, structs or records (depending on your language) provide that, but never functions. All a function can or should do is take parameters, run and return a result. BTW, one very good reason for this is that functions only have memory for their local values while they're running (this is called a "stack frame"). A value defined locally within a function does not exist except while that function is running. A: You can make use of class as shown below: class function1(object): def x(): a=10 return a def function2(): y = function1.x() return y function2() #works now and returns 10 Working demo A: You need to return x and call function1 as a function def function1(): def x(): a=10 return a return x def function2(): y = function1()() return y function2()
How can i print a function contained within another function and called by a third function?
I would like to print 10, but I get the error: AttributeError: 'function' object has no attribute 'x' How to fix? Thank you def function1(): def x(): a=10 return a def function2(): y = function1.x() return y function2()
[ "Functions are not containers you can reference into - classes, objects, structs or records (depending on your language) provide that, but never functions. All a function can or should do is take parameters, run and return a result.\nBTW, one very good reason for this is that functions only have memory for their local values while they're running (this is called a \"stack frame\"). A value defined locally within a function does not exist except while that function is running.\n", "You can make use of class as shown below:\nclass function1(object):\n def x(): \n a=10\n return a\n \ndef function2():\n y = function1.x()\n return y\n\n\nfunction2() #works now and returns 10\n\nWorking demo\n", "You need to return x and call function1 as a function\ndef function1():\n def x(): \n a=10\n return a\n return x\n \ndef function2():\n y = function1()()\n return y\n\nfunction2()\n\n" ]
[ 0, 0, -1 ]
[ "def function1(func):\n def x():\n a=10\n return func(a)\n return x\n\n@function1\ndef function2(y):\n return y\n\n\nprint(function2())\n \n\nThis should work...\n" ]
[ -1 ]
[ "function", "python", "python_3.x" ]
stackoverflow_0074497414_function_python_python_3.x.txt
Q: How can I isolate the capacitor in these images? I'm having a lot of difficulty isolating these capacitors, yellow squares, in these images. The end goal would be to draw a minAreaRectangle around it and get the location and rotation. I can dim the brightness a bit but that's the least desirable outcome as other inspections rely on that same level of brightness. I've tried thresholding, color extraction, morphological processes, line detection, edge detection, shape detection but everything I've tried hasn't been able to consistently get at the capacitors. Capacitor 1: Capacitor 2: Capacitor 3: Lower brightness Capacitor: A: I think you are too quick to exclude color thresholding and morphology to clean up in Python/OpenCV. I get the following from color thresholding using cv2.inRange() for yellow color range. Input: lower = (100,200,200) upper = (160,255,255) result = cv2.inRange(input, lower, upper) From that you should be able to use morphology to remove the partial ring and close up the white in the square
How can I isolate the capacitor in these images?
I'm having a lot of difficulty isolating these capacitors, yellow squares, in these images. The end goal would be to draw a minAreaRectangle around it and get the location and rotation. I can dim the brightness a bit but that's the least desirable outcome as other inspections rely on that same level of brightness. I've tried thresholding, color extraction, morphological processes, line detection, edge detection, shape detection but everything I've tried hasn't been able to consistently get at the capacitors. Capacitor 1: Capacitor 2: Capacitor 3: Lower brightness Capacitor:
[ "I think you are too quick to exclude color thresholding and morphology to clean up in Python/OpenCV.\nI get the following from color thresholding using cv2.inRange() for yellow color range.\nInput:\n\nlower = (100,200,200)\nupper = (160,255,255)\nresult = cv2.inRange(input, lower, upper)\n\nFrom that you should be able to use morphology to remove the partial ring and close up the white in the square\n" ]
[ 3 ]
[]
[]
[ "computer_vision", "image_processing", "opencv", "python" ]
stackoverflow_0074496980_computer_vision_image_processing_opencv_python.txt
Q: Check if a file is modified in Python I am trying to create a box that tells me if a file text is modified or not, if it is modified it prints out the new text inside of it. This should be in an infinite loop (the bot sleeps until the text file is modified). I have tried this code but it doesn't work. while True: tfile1 = open("most_recent_follower.txt", "r") SMRF1 = tfile1.readline() if tfile1.readline() == SMRF1: print(tfile1.readline()) But this is totally not working... I am new to Python, can anyone help me? A: def read_file(): with open("most_recent_follower.txt", "r") as f: SMRF1 = f.readlines() return SMRF1 initial = read_file() while True: current = read_file() if initial != current: for line in current: if line not in initial: print(line) initial = current Read the file in once, to get it's initial state. Then continuously repeat reading of the file. When it changes, print out its contents. I don't know what bot you are referring to, but this code, and yours, will continuously read the file. It never seems to exit. A: I might suggest copying the file to a safe duplicate location, and possibly using a diff program to determine if the current file is different from the original copy, and print the added lines. If you just want lines appended you might try to utilize a utility like tail You can also use a library like pyinotify to only trigger when the filesystem detects the file has been modified A: This is the first result on Google for "check if a file is modified in python" so I'm gonna add an extra solution here. If you're curious if a file is modified in the sense that its contents have changed, OR it was touched, then you can use os.stat: import os get_time = lambda f: os.stat(f).st_ctime fn = 'file.name' prev_time = get_time(fn) while True: t = get_time(fn) if t != prev_time: do_stuff() prev_time = t
Check if a file is modified in Python
I am trying to create a box that tells me if a file text is modified or not, if it is modified it prints out the new text inside of it. This should be in an infinite loop (the bot sleeps until the text file is modified). I have tried this code but it doesn't work. while True: tfile1 = open("most_recent_follower.txt", "r") SMRF1 = tfile1.readline() if tfile1.readline() == SMRF1: print(tfile1.readline()) But this is totally not working... I am new to Python, can anyone help me?
[ "def read_file():\n with open(\"most_recent_follower.txt\", \"r\") as f:\n SMRF1 = f.readlines()\n return SMRF1\n\ninitial = read_file()\nwhile True:\n current = read_file()\n if initial != current:\n for line in current:\n if line not in initial:\n print(line)\n initial = current\n\nRead the file in once, to get it's initial state. Then continuously repeat reading of the file. When it changes, print out its contents.\nI don't know what bot you are referring to, but this code, and yours, will continuously read the file. It never seems to exit.\n", "I might suggest copying the file to a safe duplicate location, and possibly using a diff program to determine if the current file is different from the original copy, and print the added lines. If you just want lines appended you might try to utilize a utility like tail\nYou can also use a library like pyinotify to only trigger when the filesystem detects the file has been modified\n", "This is the first result on Google for \"check if a file is modified in python\" so I'm gonna add an extra solution here.\nIf you're curious if a file is modified in the sense that its contents have changed, OR it was touched, then you can use os.stat:\nimport os\nget_time = lambda f: os.stat(f).st_ctime\n\nfn = 'file.name'\nprev_time = get_time(fn)\n\nwhile True:\n t = get_time(fn)\n if t != prev_time:\n do_stuff()\n prev_time = t\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0028057308_file_python.txt