content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
35
137
Q: Using Arduino Ultrasonic Sensor with Pyfirmata I'm trying to use pyfirmata to use an Arduino Ultrasonic sensor. I used Arduino Uno board and HC-SR04 Ultrasonic sensor. Here is the code I'm using. The code ran smoothly, it's just that it seems the echo pin failed to get an impulse from the trigger ultrasonic sound, so it keeps on getting False (LOW reading) and thus giving me false distance reading. Does anyone have a solution for this problem? import pyfirmata import time board = pyfirmata.Arduino('COM16') start = 0 end = 0 echo = board.get_pin('d:11:i') trig = board.get_pin('d:12:o') LED = board.get_pin('d:13:o') it = pyfirmata.util.Iterator(board) it.start() trig.write(0) time.sleep(2) while True: time.sleep(0.5) trig.write(1) time.sleep(0.00001) trig.write(0) print(echo.read()) while echo.read() == False: start = time.time() while echo.read() == True: end = time.time() TimeElapsed = end - start distance = (TimeElapsed * 34300) / 2 print("Measured Distance = {} cm".format(distance) ) I've tried changing the time.sleep() to several value and it still doesn't work. It works just fine when I'm using Arduino code dirrectly from Arduino IDE. A: I haven't done the exact math but given a range of 50cm you're at about 3ms travel time. That would mean you need to turn off the pulse and poll the pin state within that time. That's not going to happen. The echo probably arrives befor you have turned off the emitter through PyFirmata. You should do the delay measurement on the Arduino. A: I solve this false data problem by counting. I observe that false data comes after 2 or 3 sec. So if it takes More than 2 or 3 sec I clear count and restarts it from 0; Sudo code: cnt = 0; if sensorvalue <= 20 && sensorvalue <= 30: cnt++; if cnt>=5: detected = true; cnt =0; if cnt<5 && lastDecttime>2 (2 sec): cnt = 0; // Here we handle the false value and clear the data A: I'm currently trying to work this exact problem out. I can get the sensor to work using the Arduino IDE directly, but not with python and pyfirmata. I am getting some output, but its mostly non-sensical. Here's an example output I'm getting, while keeping the sensor at the same distance from my object: 817.1010613441467 536.828875541687 0.0 546.0820078849792 0.0 0.0 1060.0213408470154 Regarding your code, the only thing I can see that you could do differently is to use the board.pass_time function instead of time.sleep(). Let me know if you get anywhere! import pyfirmata as pyf import time def ultra_test(): board = pyf.Arduino("COM10") it = pyf.util.Iterator(board) it.start() trigpin = board.get_pin("d:7:o") echopin = board.get_pin("d:8:i") while True: trigpin.write(0) board.pass_time(0.5) trigpin.write(1) board.pass_time(0.00001) trigpin.write(0) limit_start = time.time() while echopin.read() != 1: if time.time() - limit_start > 1: break pass start = time.time() while echopin.read() != 0: pass stop = time.time() time_elapsed = stop - start print((time_elapsed) * 34300 / 2) board.pass_time(1)
Using Arduino Ultrasonic Sensor with Pyfirmata
I'm trying to use pyfirmata to use an Arduino Ultrasonic sensor. I used Arduino Uno board and HC-SR04 Ultrasonic sensor. Here is the code I'm using. The code ran smoothly, it's just that it seems the echo pin failed to get an impulse from the trigger ultrasonic sound, so it keeps on getting False (LOW reading) and thus giving me false distance reading. Does anyone have a solution for this problem? import pyfirmata import time board = pyfirmata.Arduino('COM16') start = 0 end = 0 echo = board.get_pin('d:11:i') trig = board.get_pin('d:12:o') LED = board.get_pin('d:13:o') it = pyfirmata.util.Iterator(board) it.start() trig.write(0) time.sleep(2) while True: time.sleep(0.5) trig.write(1) time.sleep(0.00001) trig.write(0) print(echo.read()) while echo.read() == False: start = time.time() while echo.read() == True: end = time.time() TimeElapsed = end - start distance = (TimeElapsed * 34300) / 2 print("Measured Distance = {} cm".format(distance) ) I've tried changing the time.sleep() to several value and it still doesn't work. It works just fine when I'm using Arduino code dirrectly from Arduino IDE.
[ "I haven't done the exact math but given a range of 50cm you're at about 3ms travel time. That would mean you need to turn off the pulse and poll the pin state within that time.\nThat's not going to happen. The echo probably arrives befor you have turned off the emitter through PyFirmata. You should do the delay measurement on the Arduino.\n", "I solve this false data problem by counting. I observe that false data comes after 2 or 3 sec. So if it takes More than 2 or 3 sec I clear count and restarts it from 0;\nSudo code:\n\ncnt = 0;\n\nif sensorvalue <= 20 && sensorvalue <= 30:\n cnt++;\nif cnt>=5:\n detected = true;\n cnt =0;\n\nif cnt<5 && lastDecttime>2 (2 sec):\n cnt = 0; // Here we handle the false value and clear the data\n\n", "I'm currently trying to work this exact problem out. I can get the sensor to work using the Arduino IDE directly, but not with python and pyfirmata. I am getting some output, but its mostly non-sensical.\nHere's an example output I'm getting, while keeping the sensor at the same distance from my object:\n817.1010613441467\n536.828875541687\n0.0\n546.0820078849792\n0.0\n0.0\n1060.0213408470154\n\nRegarding your code, the only thing I can see that you could do differently is to use the board.pass_time function instead of time.sleep(). Let me know if you get anywhere!\nimport pyfirmata as pyf\nimport time\n\ndef ultra_test():\n\nboard = pyf.Arduino(\"COM10\")\nit = pyf.util.Iterator(board)\nit.start()\ntrigpin = board.get_pin(\"d:7:o\")\nechopin = board.get_pin(\"d:8:i\")\nwhile True:\n trigpin.write(0)\n board.pass_time(0.5)\n trigpin.write(1)\n board.pass_time(0.00001)\n trigpin.write(0)\n limit_start = time.time()\n \n while echopin.read() != 1:\n if time.time() - limit_start > 1:\n break\n pass\n \n start = time.time()\n while echopin.read() != 0:\n pass\n stop = time.time()\n time_elapsed = stop - start\n print((time_elapsed) * 34300 / 2)\n board.pass_time(1)\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "arduino", "arduino_ultra_sonic", "arduino_uno", "pyfirmata", "python" ]
stackoverflow_0074443453_arduino_arduino_ultra_sonic_arduino_uno_pyfirmata_python.txt
Q: FastApi returning response take long time and block everything I got problem with my api FastApi, I got a big request that return me 700k rows. This request take 50 sec to be treat. But, the return response take 2mins and completely block the server who can't handle other request during those 2 mins. And I don't Know how to handle this ... Here is my code : @app.get("/request") async def request_db(data): dict_of_result = await run_in_threadpool(get_data_from_pgsql, data) # After 50 sec the code above is done with even others requests coming working # But this return below block the server for 2min ! return dict_of_result I can't add limit or pagination system that request is for specefic purpose. Thank you for help A: You should not make a 700k row database request from FastAPI or any other web server. I would update this application logic / query to offload the processing to the database or to an external worker and only make a query for the result. AsyncIO prevents the application from blocking while waiting for IO, not processing what must be a huge amount of IO. This is especially worse in Python where you are single process bound by the GIL (Global Interpreter Lock). A: This is a bit late. But here's some info for other readers. There are 2 problems here. Running the query returning a giant result. Seems like this is not the problem here Returning the result. The problem is serializing a giant dataframe/dict all at once and in memory. This is what streaming is for and ideally should start at the db level where you can stream out the data as you are processing it. @app.get("/request") async def request_db(data): dict_of_result = await run_in_threadpool(get_data_from_pgsql, data) # After 50 sec the code above is done with even others requests coming working def chunk_emitter(): # How to split() will depend on the data since this is a dict for chunk in split(dict_of_result, CHUNK_SIZE): yield chunk headers = {'Content-Disposition': 'attachment'} return StreamingResponse(iterfile(), headers=headers, media_type='application/json') More examples here: How to download a large file using FastAPI?.
FastApi returning response take long time and block everything
I got problem with my api FastApi, I got a big request that return me 700k rows. This request take 50 sec to be treat. But, the return response take 2mins and completely block the server who can't handle other request during those 2 mins. And I don't Know how to handle this ... Here is my code : @app.get("/request") async def request_db(data): dict_of_result = await run_in_threadpool(get_data_from_pgsql, data) # After 50 sec the code above is done with even others requests coming working # But this return below block the server for 2min ! return dict_of_result I can't add limit or pagination system that request is for specefic purpose. Thank you for help
[ "You should not make a 700k row database request from FastAPI or any other web server.\nI would update this application logic / query to offload the processing to the database or to an external worker and only make a query for the result.\nAsyncIO prevents the application from blocking while waiting for IO, not processing what must be a huge amount of IO. This is especially worse in Python where you are single process bound by the GIL (Global Interpreter Lock).\n", "This is a bit late. But here's some info for other readers. There are 2 problems here.\n\nRunning the query returning a giant result. Seems like this is not the problem here\nReturning the result.\n\nThe problem is serializing a giant dataframe/dict all at once and in memory. This is what streaming is for and ideally should start at the db level where you can stream out the data as you are processing it.\n\[email protected](\"/request\")\nasync def request_db(data):\n dict_of_result = await run_in_threadpool(get_data_from_pgsql, data)\n # After 50 sec the code above is done with even others requests coming working\n def chunk_emitter():\n # How to split() will depend on the data since this is a dict\n for chunk in split(dict_of_result, CHUNK_SIZE):\n yield chunk\n\n headers = {'Content-Disposition': 'attachment'}\n return StreamingResponse(iterfile(), headers=headers, media_type='application/json')\n\nMore examples here: How to download a large file using FastAPI?.\n" ]
[ 1, 0 ]
[]
[]
[ "fastapi", "python" ]
stackoverflow_0072576972_fastapi_python.txt
Q: How to use Python Fitz detect Hyphen when using search_for? I'm new to the Fitz library and am working on a project where I need to find a string in a PDF page. I'm running into a case where the text on the page that I'm searching on is hyphenated. I am aware of the TEXT_DEHYPHENATE flag that I can use in the search for function, but that doesn't work for me (as shown in the image here https://postimg.cc/zHZPdd6v ). I'm getting no cases when I search for the hyphenated string. Python Script LOC = "./test.pdf" doc = fitz.open(LOC) page = doc[1] print(page.get_text()) found = page.search_for("lowcost", flags=TEXT_DEHYPHENATE) print("DONE") print(len(found)) found = page.search_for("low-cost", flags=TEXT_DEHYPHENATE) print("DONE") print(len(found)) found = page.search_for("low cost", flags=TEXT_DEHYPHENATE) print("DONE") print(len(found)) for rect in found: print(rect) Output Abstract The objective of “XXXXXXXXXXXXXXXXXX” was design and assemble a low- cost and efficient tool. DONE 0 DONE 0 DONE 0 Can someone please point me to how I might be able to detect the hyphen in my file? Thank you! A: Your first approach should work, look here: # insert some hyphenated text page.insert_textbox((100,100,300,300),"The objective of 'xxx' was design and assemble a low-\ncost and efficient tool.") 157.94699853658676 # now search for it again page.search_for("lowcost") # 2 rectangles! [Rect(159.3009796142578, 116.24800109863281, 175.8009796142578, 131.36199951171875), Rect(100.0, 132.49501037597656, 120.17399597167969, 147.6090087890625)] # each containing a text portion with hyphen removed for rect in page.search_for("lowcost"): print(page.get_textbox(rect)) low cost Without the original file there is no way to tell the reason for your failure. Are you sure there really is text - and not e.g. an image or other hickups? Edited: As per the comment of user @KJ below: PyMuPDF's C base library MuPDF regards all of the unicodes '-', 0xAD, 0x2010, 0x2011 as hyphens in this context. They all should work the same. Just reconfirmed it in an example.
How to use Python Fitz detect Hyphen when using search_for?
I'm new to the Fitz library and am working on a project where I need to find a string in a PDF page. I'm running into a case where the text on the page that I'm searching on is hyphenated. I am aware of the TEXT_DEHYPHENATE flag that I can use in the search for function, but that doesn't work for me (as shown in the image here https://postimg.cc/zHZPdd6v ). I'm getting no cases when I search for the hyphenated string. Python Script LOC = "./test.pdf" doc = fitz.open(LOC) page = doc[1] print(page.get_text()) found = page.search_for("lowcost", flags=TEXT_DEHYPHENATE) print("DONE") print(len(found)) found = page.search_for("low-cost", flags=TEXT_DEHYPHENATE) print("DONE") print(len(found)) found = page.search_for("low cost", flags=TEXT_DEHYPHENATE) print("DONE") print(len(found)) for rect in found: print(rect) Output Abstract The objective of “XXXXXXXXXXXXXXXXXX” was design and assemble a low- cost and efficient tool. DONE 0 DONE 0 DONE 0 Can someone please point me to how I might be able to detect the hyphen in my file? Thank you!
[ "Your first approach should work, look here:\n# insert some hyphenated text\npage.insert_textbox((100,100,300,300),\"The objective of 'xxx' was design and assemble a low-\\ncost and efficient tool.\")\n157.94699853658676\n\n# now search for it again\npage.search_for(\"lowcost\") # 2 rectangles!\n[Rect(159.3009796142578, 116.24800109863281, 175.8009796142578, 131.36199951171875),\n Rect(100.0, 132.49501037597656, 120.17399597167969, 147.6090087890625)]\n\n# each containing a text portion with hyphen removed\nfor rect in page.search_for(\"lowcost\"):\n print(page.get_textbox(rect))\n\n \nlow\ncost\n\nWithout the original file there is no way to tell the reason for your failure.\nAre you sure there really is text - and not e.g. an image or other hickups?\nEdited: As per the comment of user @KJ below: PyMuPDF's C base library MuPDF regards all of the unicodes '-', 0xAD, 0x2010, 0x2011 as hyphens in this context. They all should work the same. Just reconfirmed it in an example.\n" ]
[ 0 ]
[]
[]
[ "pymupdf", "python", "python_pdfkit", "python_pdfreader" ]
stackoverflow_0074647583_pymupdf_python_python_pdfkit_python_pdfreader.txt
Q: How to get url .pdf + text from ... class + onclick ... Can someone give me a tip how to find the way? I need to get link of pdf file + the text("Instructions (DE)") from this tag: <td class="col-download-data" onclick="openPdf('https://www.roco.cc/static/version1662032330/frontend/Casisoft/Roco/en_GB/doc/AN/1/DE/62200-BA_7937.pdf');">Instructions (DE)</td> No, I am getting this output: openPdf('https://www.roco.cc/static/version1662032330/frontend/Casisoft/Roco/en_GB/doc/ET/1/DE/69255_11395.pdf'); Here is my code: import requests from bs4 import BeautifulSoup import pandas as pd import xlsxwriter productlinks = [] for x in range(1, 2): r = requests.get( f'https://www.roco.cc/ren/products/locomotives/steam-locomotives.html?p={x}&verfuegbarkeit_status=41%2C42%2C43%2C45%2C44') soup = BeautifulSoup(r.content, 'lxml') productlist = soup.find_all('li', class_='item product product-item') for item in productlist: for link in item.find_all('a', class_='product-item-link', href=True): productlinks.append(link['href']) for url in productlinks: r = requests.get(url, allow_redirects=False) content = BeautifulSoup(r.text, 'lxml') for tag in content.find_all('a'): on_click = tag.get('onclick') if on_click: print(on_click) A: for url in productlinks: r = requests.get(url, allow_redirects=False) content = BeautifulSoup(r.text, 'lxml') for tag in content.find_all('a'): on_click = tag.get('onclick') if on_click: pdf = re.findall(r"'([^']*)'", on_click) print(pdf)
How to get url .pdf + text from ... class + onclick ...
Can someone give me a tip how to find the way? I need to get link of pdf file + the text("Instructions (DE)") from this tag: <td class="col-download-data" onclick="openPdf('https://www.roco.cc/static/version1662032330/frontend/Casisoft/Roco/en_GB/doc/AN/1/DE/62200-BA_7937.pdf');">Instructions (DE)</td> No, I am getting this output: openPdf('https://www.roco.cc/static/version1662032330/frontend/Casisoft/Roco/en_GB/doc/ET/1/DE/69255_11395.pdf'); Here is my code: import requests from bs4 import BeautifulSoup import pandas as pd import xlsxwriter productlinks = [] for x in range(1, 2): r = requests.get( f'https://www.roco.cc/ren/products/locomotives/steam-locomotives.html?p={x}&verfuegbarkeit_status=41%2C42%2C43%2C45%2C44') soup = BeautifulSoup(r.content, 'lxml') productlist = soup.find_all('li', class_='item product product-item') for item in productlist: for link in item.find_all('a', class_='product-item-link', href=True): productlinks.append(link['href']) for url in productlinks: r = requests.get(url, allow_redirects=False) content = BeautifulSoup(r.text, 'lxml') for tag in content.find_all('a'): on_click = tag.get('onclick') if on_click: print(on_click)
[ "for url in productlinks:\n r = requests.get(url, allow_redirects=False)\n content = BeautifulSoup(r.text, 'lxml')\n for tag in content.find_all('a'):\n on_click = tag.get('onclick')\n if on_click:\n pdf = re.findall(r\"'([^']*)'\", on_click)\n print(pdf)\n\n" ]
[ 0 ]
[]
[]
[ "onclick", "output", "pdf", "python", "web_scraping" ]
stackoverflow_0074661995_onclick_output_pdf_python_web_scraping.txt
Q: Grouping Python dictionaries in hierarchical form with multiple keys? Here is my list of dicts: [{'subtopic': 'IAM', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_iam_policies_info","workflow.parameters": {"region": "us-east"}}'], 'text': 'Sure! I can help with AWS IAM policies info'}, {'subtopic': 'ECS', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_ecs_restart_service","workflow.parameters": {"region": "us-east"}}'], 'text': 'Sure! I can help with restarting AWS ECS Service'}, {'subtopic': 'EC2', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_ec2_create_instance","workflow.parameters": {"region": "us-east"}}'], 'text': 'Sure, I can help creating an EC2 machine'}, {'subtopic': 'EC2', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_ec2_security_group_info","workflow.parameters": {"region": "us-east"}}'], 'text': 'Sure, I can help with various information about AWS security groups'}, {'subtopic': 'S3', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_s3_file_copy","workflow.parameters": {"region": "us-west"}}'], 'text': 'Sure, I can help you with the process of copying on S3'}, {'subtopic': 'GitHub', 'topic': 'AWS', 'attachments': ['{"workflow.name": "view_pull_request","workflow.parameters": {"region": "us-west"}}'], 'text': 'Sure, I can help with GitHub pull requests'}, {'subtopic': 'Subtopic Title', 'topic': 'Topic Title', 'attachments': [], 'text': 'This is another fact'}, {'subtopic': 'Subtopic Title', 'topic': 'Topic Title', 'attachments': [], 'text': 'This is a fact'}] I would like to group by topic and subtopic to get a final result: { "AWS": { "GitHub": { 'attachments': ['{"workflow.name": "view_pull_request","workflow.parameters": {"region": "us-west"}}'], 'text': ['Sure, I can help with GitHub pull requests'] }, "S3": { 'attachments': ['{"workflow.name": "aws_s3_file_copy","workflow.parameters": {"region": "us-west"}}'], 'text': ['Sure, I can help you with the process of copying on S3'] }, "EC2": { 'attachments': ['{"workflow.name": "aws_ec2_create_instance","workflow.parameters": {"region": "us-east"}}', '{"workflow.name": "aws_ec2_security_group_info","workflow.parameters": {"region": "us-east"}}'], 'text': ['Sure, I can help creating an EC2 machine', 'Sure, I can help with various information about AWS security groups'] }, "ECS": { 'attachments': ['{"workflow.name": "aws_ecs_restart_service","workflow.parameters": {"region": "us-east"}}'], 'text': ['Sure! I can help with restarting AWS ECS Service'] }, "IAM": { 'attachments': ['{"workflow.name": "aws_iam_policies_info","workflow.parameters": {"region": "us-east"}}'], 'text': ['Sure! I can help with AWS IAM policies info'] } }, "Topic Title": { "Subtopic Title": { 'attachments': [], 'text': ['This is another fact'] } } } I am using: groups = ['topic', 'subtopic', "text", "attachments"] groups.reverse() def hierachical_data(data, groups): g = groups[-1] g_list = [] for key, items in itertools.groupby(data, operator.itemgetter(g)): g_list.append({key:list(items)}) groups = groups[0:-1] if(len(groups) != 0): for e in g_list: for k, v in e.items(): e[k] = hierachical_data(v, groups) return g_list print(hierachical_data(filtered_top_facts_dicts, groups)) But getting an error for hashing lists. Please advise how to transform my json to the desired format. A: To group the list of dictionaries by topic and subtopic, you can create an empty dictionary and then loop through the list of dictionaries to add each item to the appropriate nested level in the dictionary. result = {} for item in data: topic = item['topic'] subtopic = item['subtopic'] if topic not in result: result[topic] = {} if subtopic not in result[topic]: result[topic][subtopic] = {} result[topic][subtopic]['attachments'] = [] result[topic][subtopic]['text'] = [] result[topic][subtopic]['attachments'].extend(item['attachments']) result[topic][subtopic]['text'].append(item['text']) # Reverse the order of the sub-dictionaries within each topic for topic, subtopics in result.items(): result[topic] = dict(reversed(list(subtopics.items()))) After this loop has completed, the result dictionary will be in the format you described, with topic and subtopic as the keys and the attachments and text as the values within each sub-dictionary. Output: {'AWS': {'GitHub': {'attachments': ['{"workflow.name": "view_pull_request","workflow.parameters": {"region": "us-west"}}'], 'text': ['Sure, I can help with GitHub pull requests']}, 'S3': {'attachments': ['{"workflow.name": "aws_s3_file_copy","workflow.parameters": {"region": "us-west"}}'], 'text': ['Sure, I can help you with the process of copying on S3']}, 'EC2': {'attachments': ['{"workflow.name": "aws_ec2_create_instance","workflow.parameters": {"region": "us-east"}}', '{"workflow.name": "aws_ec2_security_group_info","workflow.parameters": {"region": "us-east"}}'], 'text': ['Sure, I can help creating an EC2 machine', 'Sure, I can help with various information about AWS security groups']}, 'ECS': {'attachments': ['{"workflow.name": "aws_ecs_restart_service","workflow.parameters": {"region": "us-east"}}'], 'text': ['Sure! I can help with restarting AWS ECS Service']}, 'IAM': {'attachments': ['{"workflow.name": "aws_iam_policies_info","workflow.parameters": {"region": "us-east"}}'], 'text': ['Sure! I can help with AWS IAM policies info']}}, 'Topic Title': {'Subtopic Title': {'attachments': [], 'text': ['This is another fact', 'This is a fact']}}} A: I think the cleanest solution is to use dictlib with reduce in one line: from functools import reduce import dictlib reduce( lambda x, y: dictlib.union_setadd(x, y), [ { x["topic"]: { x["subtopic"]: { list(x.keys())[2]: list(x.values())[2], list(x.keys())[3]: [list(x.values())[3]], } } } for x in d ], ) where d is your initial list and dictlib.union_setadd() merges dictionaries by doing setadd logic like with str and int. Note that when put in reduce, merge is sequential and cumulative for all your list entries. Hope this helps.
Grouping Python dictionaries in hierarchical form with multiple keys?
Here is my list of dicts: [{'subtopic': 'IAM', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_iam_policies_info","workflow.parameters": {"region": "us-east"}}'], 'text': 'Sure! I can help with AWS IAM policies info'}, {'subtopic': 'ECS', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_ecs_restart_service","workflow.parameters": {"region": "us-east"}}'], 'text': 'Sure! I can help with restarting AWS ECS Service'}, {'subtopic': 'EC2', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_ec2_create_instance","workflow.parameters": {"region": "us-east"}}'], 'text': 'Sure, I can help creating an EC2 machine'}, {'subtopic': 'EC2', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_ec2_security_group_info","workflow.parameters": {"region": "us-east"}}'], 'text': 'Sure, I can help with various information about AWS security groups'}, {'subtopic': 'S3', 'topic': 'AWS', 'attachments': ['{"workflow.name": "aws_s3_file_copy","workflow.parameters": {"region": "us-west"}}'], 'text': 'Sure, I can help you with the process of copying on S3'}, {'subtopic': 'GitHub', 'topic': 'AWS', 'attachments': ['{"workflow.name": "view_pull_request","workflow.parameters": {"region": "us-west"}}'], 'text': 'Sure, I can help with GitHub pull requests'}, {'subtopic': 'Subtopic Title', 'topic': 'Topic Title', 'attachments': [], 'text': 'This is another fact'}, {'subtopic': 'Subtopic Title', 'topic': 'Topic Title', 'attachments': [], 'text': 'This is a fact'}] I would like to group by topic and subtopic to get a final result: { "AWS": { "GitHub": { 'attachments': ['{"workflow.name": "view_pull_request","workflow.parameters": {"region": "us-west"}}'], 'text': ['Sure, I can help with GitHub pull requests'] }, "S3": { 'attachments': ['{"workflow.name": "aws_s3_file_copy","workflow.parameters": {"region": "us-west"}}'], 'text': ['Sure, I can help you with the process of copying on S3'] }, "EC2": { 'attachments': ['{"workflow.name": "aws_ec2_create_instance","workflow.parameters": {"region": "us-east"}}', '{"workflow.name": "aws_ec2_security_group_info","workflow.parameters": {"region": "us-east"}}'], 'text': ['Sure, I can help creating an EC2 machine', 'Sure, I can help with various information about AWS security groups'] }, "ECS": { 'attachments': ['{"workflow.name": "aws_ecs_restart_service","workflow.parameters": {"region": "us-east"}}'], 'text': ['Sure! I can help with restarting AWS ECS Service'] }, "IAM": { 'attachments': ['{"workflow.name": "aws_iam_policies_info","workflow.parameters": {"region": "us-east"}}'], 'text': ['Sure! I can help with AWS IAM policies info'] } }, "Topic Title": { "Subtopic Title": { 'attachments': [], 'text': ['This is another fact'] } } } I am using: groups = ['topic', 'subtopic', "text", "attachments"] groups.reverse() def hierachical_data(data, groups): g = groups[-1] g_list = [] for key, items in itertools.groupby(data, operator.itemgetter(g)): g_list.append({key:list(items)}) groups = groups[0:-1] if(len(groups) != 0): for e in g_list: for k, v in e.items(): e[k] = hierachical_data(v, groups) return g_list print(hierachical_data(filtered_top_facts_dicts, groups)) But getting an error for hashing lists. Please advise how to transform my json to the desired format.
[ "To group the list of dictionaries by topic and subtopic, you can create an empty dictionary and then loop through the list of dictionaries to add each item to the appropriate nested level in the dictionary.\nresult = {}\n\nfor item in data:\n topic = item['topic']\n subtopic = item['subtopic']\n\n if topic not in result:\n result[topic] = {}\n\n if subtopic not in result[topic]:\n result[topic][subtopic] = {}\n result[topic][subtopic]['attachments'] = []\n result[topic][subtopic]['text'] = []\n\n result[topic][subtopic]['attachments'].extend(item['attachments'])\n result[topic][subtopic]['text'].append(item['text'])\n\n# Reverse the order of the sub-dictionaries within each topic\nfor topic, subtopics in result.items():\n result[topic] = dict(reversed(list(subtopics.items())))\n\nAfter this loop has completed, the result dictionary will be in the format you described, with topic and subtopic as the keys and the attachments and text as the values within each sub-dictionary.\nOutput:\n{'AWS': {'GitHub': {'attachments': ['{\"workflow.name\": \"view_pull_request\",\"workflow.parameters\": {\"region\": \"us-west\"}}'],\n 'text': ['Sure, I can help with GitHub pull requests']},\n 'S3': {'attachments': ['{\"workflow.name\": \"aws_s3_file_copy\",\"workflow.parameters\": {\"region\": \"us-west\"}}'],\n 'text': ['Sure, I can help you with the process of copying on S3']},\n 'EC2': {'attachments': ['{\"workflow.name\": \"aws_ec2_create_instance\",\"workflow.parameters\": {\"region\": \"us-east\"}}',\n '{\"workflow.name\": \"aws_ec2_security_group_info\",\"workflow.parameters\": {\"region\": \"us-east\"}}'],\n 'text': ['Sure, I can help creating an EC2 machine',\n 'Sure, I can help with various information about AWS security groups']},\n 'ECS': {'attachments': ['{\"workflow.name\": \"aws_ecs_restart_service\",\"workflow.parameters\": {\"region\": \"us-east\"}}'],\n 'text': ['Sure! I can help with restarting AWS ECS Service']},\n 'IAM': {'attachments': ['{\"workflow.name\": \"aws_iam_policies_info\",\"workflow.parameters\": {\"region\": \"us-east\"}}'],\n 'text': ['Sure! I can help with AWS IAM policies info']}},\n 'Topic Title': {'Subtopic Title': {'attachments': [],\n 'text': ['This is another fact', 'This is a fact']}}}\n\n", "I think the cleanest solution is to use dictlib with reduce in one line:\nfrom functools import reduce\nimport dictlib\n\nreduce(\n lambda x, y: dictlib.union_setadd(x, y),\n [\n {\n x[\"topic\"]: {\n x[\"subtopic\"]: {\n list(x.keys())[2]: list(x.values())[2],\n list(x.keys())[3]: [list(x.values())[3]],\n }\n }\n }\n for x in d\n ],\n)\n\nwhere d is your initial list and dictlib.union_setadd() merges dictionaries by doing setadd logic like with str and int. Note that when put in reduce, merge is sequential and cumulative for all your list entries.\nHope this helps.\n" ]
[ 1, 1 ]
[]
[]
[ "dictionary", "itertools_groupby", "python", "python_3.x", "python_itertools" ]
stackoverflow_0074662274_dictionary_itertools_groupby_python_python_3.x_python_itertools.txt
Q: How to replace .append with .concat in pandas dataframe? Here is my code dataframe = pd.DataFrame(columns = my_columns) for stock in stocks['Ticker'][:1]: api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote/?token={IEX_CLOUD_API_TOKEN}' data = requests.get(api_url).json() dataframe = dataframe.append( pd.Series([stock, data['latestPrice'], marketCap/1000000000000], index = my_columns), ignore_index = True ) dataframe Returns this BUT! Ticker Stock Price Market Cap A 153.57 2.37218 Also returns : FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead. dataframe = dataframe.append( I understand I want to make dataframe a list but how do I parse through the Series? A: dataframe = pd.DataFrame(columns = my_columns) for stock in stocks['Ticker'][:1]: api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote/?token={IEX_CLOUD_API_TOKEN}' data = requests.get(api_url).json() new_row = pd.DataFrame( [ [stock, data["latestPrice"], marketCap / 1000000000000] ], columns=my_columns ) dataframe = pd.concat([dataframe, new_row], ignore_index = True) dataframe
How to replace .append with .concat in pandas dataframe?
Here is my code dataframe = pd.DataFrame(columns = my_columns) for stock in stocks['Ticker'][:1]: api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote/?token={IEX_CLOUD_API_TOKEN}' data = requests.get(api_url).json() dataframe = dataframe.append( pd.Series([stock, data['latestPrice'], marketCap/1000000000000], index = my_columns), ignore_index = True ) dataframe Returns this BUT! Ticker Stock Price Market Cap A 153.57 2.37218 Also returns : FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead. dataframe = dataframe.append( I understand I want to make dataframe a list but how do I parse through the Series?
[ "dataframe = pd.DataFrame(columns = my_columns)\nfor stock in stocks['Ticker'][:1]:\n api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote/?token={IEX_CLOUD_API_TOKEN}'\n data = requests.get(api_url).json()\n new_row = pd.DataFrame(\n [\n [stock, data[\"latestPrice\"], marketCap / 1000000000000]\n ],\n columns=my_columns\n )\n dataframe = pd.concat([dataframe, new_row], ignore_index = True)\n\ndataframe\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074662439_dataframe_pandas_python.txt
Q: Sympy intersection of FiniteSets with strings Define two sympy FiniteSet sets a and b with each of them containing only one string element: a = FiniteSet('red') b = FiniteSet('yellow') If I ask for the Intersection of those sets: Intersection(a,b) I was expecting to get as result an empty set {}, but I just get Intersection({red}, {yellow}). Why is that? It works well for Union: Union(a,b) = {'red', 'yellow'}. Even if I define those sets: a = FiniteSet('red', 'yellow') b = FiniteSet('red') I get the expected result: Intersection(a,b) = {'red'}. I was planing to use those set manipulations to reduce/simplify rather long symbolic representations of combinations of different sets. But with this behavior it will not work. It also works well with the built-in python sets: a = {'red'} b = {'yellow'} a.intersection(b) leads to set(). Is this a bug in sympy? A: The intersection cannot unambiguously give a result for objects which are variables. Your strings became Symbols with color names and a might equal b or it might not. If your elements were 'a+1' and 'a+2' the intersection would be an empty set because those two cannot be the same for finite values. If you intend that distinct items are distinct, then map them to integers, allow simplification to take place, and then map them back to sybols: reps = {s:i for i, s in expr.atoms(Symbol)} expr = expr.xreplace(reps).xreplace({i:s for s,i in reps.items()})
Sympy intersection of FiniteSets with strings
Define two sympy FiniteSet sets a and b with each of them containing only one string element: a = FiniteSet('red') b = FiniteSet('yellow') If I ask for the Intersection of those sets: Intersection(a,b) I was expecting to get as result an empty set {}, but I just get Intersection({red}, {yellow}). Why is that? It works well for Union: Union(a,b) = {'red', 'yellow'}. Even if I define those sets: a = FiniteSet('red', 'yellow') b = FiniteSet('red') I get the expected result: Intersection(a,b) = {'red'}. I was planing to use those set manipulations to reduce/simplify rather long symbolic representations of combinations of different sets. But with this behavior it will not work. It also works well with the built-in python sets: a = {'red'} b = {'yellow'} a.intersection(b) leads to set(). Is this a bug in sympy?
[ "The intersection cannot unambiguously give a result for objects which are variables. Your strings became Symbols with color names and a might equal b or it might not. If your elements were 'a+1' and 'a+2' the intersection would be an empty set because those two cannot be the same for finite values.\nIf you intend that distinct items are distinct, then map them to integers, allow simplification to take place, and then map them back to sybols:\nreps = {s:i for i, s in expr.atoms(Symbol)}\nexpr = expr.xreplace(reps).xreplace({i:s for s,i in reps.items()})\n\n" ]
[ 1 ]
[]
[]
[ "python", "set", "set_theory", "sympy" ]
stackoverflow_0074662655_python_set_set_theory_sympy.txt
Q: Django and adding a static image Good evening, I've just completed this tutorial: https://docs.djangoproject.com/en/4.1/intro/tutorial01/ and I need to add a new directory to display a dataset (unrelated to the polls app) I've set up my new directory as I did the first steps in the tutorial. My steps: ...\> py manage.py startapp newendpoint newendpoint/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py path('newendpoint/', include('newendpoint.urls')) **Once this is setup I've tried these tutorials: ** https://youtu.be/u1FR1nZ6Ng4 I've tried this tutorial and had no luck https://adiramadhan17.medium.com/django-load-image-from-static-directory-27f002b1bdf1 I've also tried this one My server goes down or nothing displays. I could really use some help getting this figured out, before I tried the static image I was trying to add a csv via SQLite3 with no luck either. A: Step 1: Install pillow $ pip install pillow Step 2: Add the model for the image in your apps models.py class Imagemodel(models.Model): # ..... pic = models.ImageField(upload_to='images/', null=True) # U can change to `FileField` for files Step 3: Make migrations and migrate: $ py manage.py makemigrations && migrate Step 4: open settings.py and add the following code. This code tells Django where to store the images. import os # at the top # Other settings .. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR , 'media') Step 5: In your project directory level, create the media folder: $ mkdir media Step 6: Open the project level urls.py and add the code below to add our media folder to the static files. # other imports from . import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # URL patterns urlpatterns +=staticfiles_urlpatterns() urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Step 7: In your app directory level (newendpoint), add a forms.py file and add the code below: from django import forms from .models import * class PicForm(forms.ModelForm): class Meta: model = Imagemodel fields = ['pic'] Step 8: In your app (newendpoint), create a folder called templates and add a file called pic.html inside. In pic.html, add the code below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>image</title> </head> <body> <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> </body> </html> Step 9: In your app's views.py add the code below: from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import * # Create your views here. def pic_view(request): if request.method == 'POST': form = PicForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('success') else: form = PicForm() return render(request, 'pic.html', {'form': form}) def success(request): return HttpResponse('successfully uploaded') Step 10: In your app's urls.py add the code below: # .. other imports from django.urls import path from .views import * urlpatterns = [ path('image_upload', pic_view, name='image_upload'), path('success', success, name='success'), ] Step 11: Run the server: $ python3 manage.py runserver Upload the image through: http://127.0.0.1:8000/image_upload
Django and adding a static image
Good evening, I've just completed this tutorial: https://docs.djangoproject.com/en/4.1/intro/tutorial01/ and I need to add a new directory to display a dataset (unrelated to the polls app) I've set up my new directory as I did the first steps in the tutorial. My steps: ...\> py manage.py startapp newendpoint newendpoint/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py path('newendpoint/', include('newendpoint.urls')) **Once this is setup I've tried these tutorials: ** https://youtu.be/u1FR1nZ6Ng4 I've tried this tutorial and had no luck https://adiramadhan17.medium.com/django-load-image-from-static-directory-27f002b1bdf1 I've also tried this one My server goes down or nothing displays. I could really use some help getting this figured out, before I tried the static image I was trying to add a csv via SQLite3 with no luck either.
[ "Step 1:\n\nInstall pillow\n\n$ pip install pillow\n\nStep 2:\nAdd the model for the image in your apps models.py\n\nclass Imagemodel(models.Model):\n # .....\n pic = models.ImageField(upload_to='images/', null=True) # U can change to `FileField` for files\n\nStep 3:\nMake migrations and migrate:\n$ py manage.py makemigrations && migrate\n\nStep 4:\nopen settings.py and add the following code. This code tells Django where to store the images.\nimport os # at the top\n# Other settings ..\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR , 'media')\n\n\nStep 5:\nIn your project directory level, create the media folder:\n$ mkdir media \n\nStep 6:\nOpen the project level urls.py and add the code below to add our media folder to the static files.\n# other imports\nfrom . import settings\nfrom django.contrib.staticfiles.urls import static\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\n# URL patterns\n\nurlpatterns +=staticfiles_urlpatterns()\nurlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nStep 7:\nIn your app directory level (newendpoint), add a forms.py file and add the code below:\nfrom django import forms\nfrom .models import *\n \n \nclass PicForm(forms.ModelForm):\n \n class Meta:\n model = Imagemodel\n fields = ['pic']\n\nStep 8:\nIn your app (newendpoint), create a folder called templates and add a file called pic.html inside. In pic.html, add the code below:\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>image</title>\n</head>\n<body>\n <form method = \"post\" enctype=\"multipart/form-data\">\n {% csrf_token %}\n {{ form.as_p }}\n <button type=\"submit\">Upload</button>\n </form>\n</body>\n</html>\n\nStep 9:\nIn your app's views.py add the code below:\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom .forms import *\n \n# Create your views here.\n \n \ndef pic_view(request):\n \n if request.method == 'POST':\n form = PicForm(request.POST, request.FILES)\n \n if form.is_valid():\n form.save()\n return redirect('success')\n else:\n form = PicForm()\n return render(request, 'pic.html', {'form': form})\n \n \ndef success(request):\n return HttpResponse('successfully uploaded')\n\nStep 10:\nIn your app's urls.py add the code below:\n# .. other imports\nfrom django.urls import path\nfrom .views import *\n\n\nurlpatterns = [\n path('image_upload', pic_view, name='image_upload'),\n path('success', success, name='success'),\n]\n\nStep 11:\nRun the server:\n$ python3 manage.py runserver \n\nUpload the image through:\nhttp://127.0.0.1:8000/image_upload\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074662462_django_python.txt
Q: Call compound.finance api with parameters I'm trying to simply call the compound.finance api "https://api.compound.finance/api/v2/account" with the parameter max_health. the doc says "If provided, should be given as { "value": "...string formatted number..." }". (https://compound.finance/docs/api#account-service) So I tried 4 methods here below: response = requests.get( 'https://api.compound.finance/api/v2/account', params={ "max_health": "1.0" # method 1 "max_health": {"value":"1.0"} # method 2 "max_health": json.dumps({"value":"1.0"}) # method 3 } ) but it does not work, and I get HTTPError: 500 Server Error: Internal Server Error for url:... Any idea I should format it please? A: They did not update the API docs. You should send a POST request and provide params as a request body. import json import requests url = "https://api.compound.finance/api/v2/account" data = { "max_health": {"value": "1.0"} } response = requests.post(url, data=json.dumps(data)) # <Response [200]> response = response.json() # {'accounts': ...} Edit notes The problem was that the API expects raw JSON so I used json.dumps. A: As Artyom already explained his beautiful answer, indeed their API documentation unfortunately outdated. In addition to his answer I'd like to add that requests library supports json argument that accepts raw JSON arguments starting with requests version 2.4.2. Therefore data=json.dumps(params) is not necessary anymore. See my code below. api_base = "https://api.compound.finance/api/v2/account" params = {'max_health': {'value':'0.95'}, 'min_borrow_value_in_eth': { 'value': '0.002' }, 'page_number':19, } response = requests.post(api_base, json=params).json()
Call compound.finance api with parameters
I'm trying to simply call the compound.finance api "https://api.compound.finance/api/v2/account" with the parameter max_health. the doc says "If provided, should be given as { "value": "...string formatted number..." }". (https://compound.finance/docs/api#account-service) So I tried 4 methods here below: response = requests.get( 'https://api.compound.finance/api/v2/account', params={ "max_health": "1.0" # method 1 "max_health": {"value":"1.0"} # method 2 "max_health": json.dumps({"value":"1.0"}) # method 3 } ) but it does not work, and I get HTTPError: 500 Server Error: Internal Server Error for url:... Any idea I should format it please?
[ "They did not update the API docs. You should send a POST request and provide params as a request body.\nimport json\nimport requests\n\nurl = \"https://api.compound.finance/api/v2/account\"\ndata = {\n \"max_health\": {\"value\": \"1.0\"}\n}\n\nresponse = requests.post(url, data=json.dumps(data)) # <Response [200]>\nresponse = response.json() # {'accounts': ...}\n\nEdit notes\nThe problem was that the API expects raw JSON so I used json.dumps.\n", "As Artyom already explained his beautiful answer, indeed their API documentation unfortunately outdated. In addition to his answer I'd like to add that requests library supports json argument that accepts raw JSON arguments starting with requests version 2.4.2. Therefore data=json.dumps(params) is not necessary anymore.\nSee my code below.\napi_base = \"https://api.compound.finance/api/v2/account\"\nparams = {'max_health': {'value':'0.95'},\n 'min_borrow_value_in_eth': { 'value': '0.002' },\n 'page_number':19,\n }\nresponse = requests.post(api_base, json=params).json()\n\n" ]
[ 2, 0 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0072715891_python_python_requests.txt
Q: How to change the "shape" of pairplot in Seaborn? I plotted this pairplot correlating only one features with all the others, how can i visualize it in a better way? I need to visualize 4 columns. In the official documentation of pairplot i can't find the option. This is the df: This is the part of the code: sns.pairplot(data=dftrain, y_vars=['medv'], x_vars=dftrain.columns[:-1]) This is the plot: A: The shape of a pairplot can't be changed. But, you can create a similar relplot if you convert the dataframe to long form. Here is some simple example code, starting from dummy data: import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(300, 14), columns=[*"abcdefghijklmn"]) df_long = df.melt(id_vars=df.columns[-1], value_vars=df.columns[:-1]) g = sns.relplot(df_long, x=df.columns[-1], y='value', col='variable', col_wrap=4, height=2) A: You can use seaborn.FacetGrid and set a value of the parameter col_wrap. col_wrap (int): “Wrap” the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet. Try this : cols= dftrain.columns[:-1].tolist() g = sns.FacetGrid(pd.DataFrame(cols), col=0, col_wrap=3, sharex=False) for ax, varx in zip(g.axes, cols): sns.scatterplot(data=dftrain, x=varx, y="medv", ax=ax) g.tight_layout() # Output :
How to change the "shape" of pairplot in Seaborn?
I plotted this pairplot correlating only one features with all the others, how can i visualize it in a better way? I need to visualize 4 columns. In the official documentation of pairplot i can't find the option. This is the df: This is the part of the code: sns.pairplot(data=dftrain, y_vars=['medv'], x_vars=dftrain.columns[:-1]) This is the plot:
[ "The shape of a pairplot can't be changed. But, you can create a similar relplot if you convert the dataframe to long form.\nHere is some simple example code, starting from dummy data:\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.rand(300, 14), columns=[*\"abcdefghijklmn\"])\ndf_long = df.melt(id_vars=df.columns[-1], value_vars=df.columns[:-1])\n\ng = sns.relplot(df_long, x=df.columns[-1], y='value', col='variable', col_wrap=4, height=2)\n\n\n", "You can use seaborn.FacetGrid and set a value of the parameter col_wrap.\n\ncol_wrap (int): “Wrap” the column variable at this width, so that the\ncolumn facets span multiple rows. Incompatible with a row facet.\n\nTry this :\ncols= dftrain.columns[:-1].tolist()\n\ng = sns.FacetGrid(pd.DataFrame(cols), col=0, col_wrap=3, sharex=False)\n\nfor ax, varx in zip(g.axes, cols):\n sns.scatterplot(data=dftrain, x=varx, y=\"medv\", ax=ax)\n \ng.tight_layout()\n\n# Output :\n\n" ]
[ 2, 2 ]
[]
[]
[ "pairplot", "pandas", "python", "seaborn", "shapes" ]
stackoverflow_0074662654_pairplot_pandas_python_seaborn_shapes.txt
Q: Is there a way to loop through an entire Python script with an Input function? I have a very basic Blackjack simulator where I input whether I want to Hit or Stay. When I choose it, it then tells me the result. I want to run this over multiple times. Is there a function where after I get the result of the hand, it will restart from the top of the script? I am using Jupyter notebook and am currently just restarting and running all cells and then input my choice A: You can use a basic game play pattern such as the following to do what you want. # Function to request input and verify input type is valid def getInput(prompt, respType= None): while True: resp = input(prompt) if respType == str or respType == None: break else: try: resp = respType(resp) break except ValueError: print('Invalid input, please try again') return resp # function to initiate game play and control game termination def playgame(): if getInput('Do you want to play? (y/n)').lower() == 'y': while True: game_input = getInput('Enter an Integer', int) # . . . Place your game logic here . . . # if getInput("Play Again? (y/n)").lower() == 'n': break print('Good bye')
Is there a way to loop through an entire Python script with an Input function?
I have a very basic Blackjack simulator where I input whether I want to Hit or Stay. When I choose it, it then tells me the result. I want to run this over multiple times. Is there a function where after I get the result of the hand, it will restart from the top of the script? I am using Jupyter notebook and am currently just restarting and running all cells and then input my choice
[ "You can use a basic game play pattern such as the following to do what you want.\n# Function to request input and verify input type is valid\ndef getInput(prompt, respType= None):\n while True:\n resp = input(prompt)\n if respType == str or respType == None:\n break\n else:\n try:\n resp = respType(resp)\n break\n except ValueError:\n print('Invalid input, please try again')\n return resp \n\n# function to initiate game play and control game termination\ndef playgame():\n if getInput('Do you want to play? (y/n)').lower() == 'y':\n while True:\n game_input = getInput('Enter an Integer', int)\n # . . . Place your game logic here . . . #\n if getInput(\"Play Again? (y/n)\").lower() == 'n':\n break\n print('Good bye') \n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074662285_python.txt
Q: Python3 find position/index of a name/element in a list with more than one of the same name I am having a problem that I just don't know how to solve and nothing I'm finding is helping. My problem is that I have a list of names (strings), in this list I will have the same name show up more than once. lst = ['hello.com', 'hello.com', 'hello.com', 'world.com', 'test1.com'] index = web_lst.index(domain)+1 print(index) The issue with this code is that index() will always find and use the first 'hello.com' instead of any of the other "hello.com's", so index will always be 1. If I were asking for any of the other names then it'd work I think. I am trying to get the integer representation of the 'hello.com' names (1, 2, 3, etc.), and I don't know how to do that or what else to use besides python lists. This, I don't think is going to work and I'm asking for any other ideas on what to do or use instead of using a list. (if what I'm trying to do is not possible with lists) My main goal is basically a login manager using sqlite3 and I want to have the ability to have multiple logins with some having the same domain name (but with different data and notes, etc.), because we like to have multiple logins/accounts for 1 website. I have a TUI (beaupy) for selecting the domain/option you want to get the login for but if you have more than 1 of the same domain name it doesn't know which one to pick. I have managed to use integers as IDs in the sqlite3 database to help but the main issue is the picking of an element from a list to get a number, to then plug into the read() function. So the list options will correlate to the "IDs" in the database. List index 0+1 would be option/row 1 in the database (and so on). def clear(): os.system('clear||cls') def add(encrypted_data): ID = 1 database = sqlite3.connect('vault.gter') c = database.cursor() #Check to see if IDs exist and if yes then get how many/length of list and add 1 and use that instead. c.execute("SELECT id FROM logins") all_ids = c.fetchall() out = list(itertools.chain(*all_ids)) list_length = len(out) if not all_ids: pass else: for x in out: if x == list_length: ID = x+1 else: pass c.execute(f"INSERT INTO logins VALUES ('{ID}', '{encrypted_data}')") database.commit() database.close() def domains(dKey): database = sqlite3.connect('vault.gter') c = database.cursor() c.execute("SELECT data FROM logins") websites = c.fetchall() enc_output = list(itertools.chain(*websites)) web_lst = [] note_lst = [] for x in enc_output: result = gcm.stringD(x, dKey) #decrypt encrypted json string. obj_result = json.loads(result) #turns back into json object website = obj_result['Domain'] notes = obj_result['Notes'] web_lst.append(website) note_lst.append(notes) for w,n in zip(web_lst, note_lst): with open('.lst', 'a') as fa: fa.writelines(f"{w} ({n})\n") fa.close() with open(".lst", "r+") as fr: data = fr.read() fnlst = data.strip().split('\n') fr.truncate(0) fr.close() os.remove(".lst") print(f'(Press "ctrl+c" to exit)\n-----------------------------------------------------------\n\nWebsite domain/name to get login for?\n') domain = beaupy.select(fnlst, cursor_style="#ffa533") clear() if domain == None: clear() return else: domain = domain.split(' ', 1)[0] #get first word in a string. print(domain) #debug index = web_lst.index(domain)+1 input(index) #debug pwd = read(index) return pwd # Come up with new way to show available options to chose from and then get number from that to use here for "db_row". def read(db_row): database = sqlite3.connect('vault.gter') c = database.cursor() c.execute("SELECT id FROM logins") all_ids = c.fetchall() lst_output = list(itertools.chain(*all_ids)) if not all_ids: input("No IDS") #debug database.commit() database.close() return else: for x in lst_output: if x == db_row: c.execute(f"SELECT data FROM logins WHERE id LIKE '{db_row}'") #to prevent my main issue of it not knowing what I want when two domain names are the same. stoof = c.fetchone() database.commit() database.close() return stoof[0] else: #(debug) - input(f"error, x is not the same as db_row. x = {x} & db_row = {db_row}") pass If anyone has a better way of doing this whole login manager thing, I'll be very very appreciative. From handling the database and sqlite3 commands, better IDs? to perhaps completely a different (and free) way of storage. And finding a better way to handle my main problem here (with or without having to use lists). Anything is helpful. <3 If anyone has questions then feel free to ask away and I'll respond when I can with the best of my knowledge. A: You can get both the index and the element using a for-loop. for i in range(len(lst)): element = lst[i] if element == domain: print(i) This should give you all indexes of domain. Edited Code: d = {} c = 0 for i in range(len(lst)): element = lst[i] if element == domain: c += 1 d[c] = i for number, index in d.items(): # Do something here. Remember to use number and index instead of c and i! c is the occurence number, and i is the index. A: Here is a one-liner: [{item:[i for i, x in enumerate(lst) if x == item]} for item in set(lst)]
Python3 find position/index of a name/element in a list with more than one of the same name
I am having a problem that I just don't know how to solve and nothing I'm finding is helping. My problem is that I have a list of names (strings), in this list I will have the same name show up more than once. lst = ['hello.com', 'hello.com', 'hello.com', 'world.com', 'test1.com'] index = web_lst.index(domain)+1 print(index) The issue with this code is that index() will always find and use the first 'hello.com' instead of any of the other "hello.com's", so index will always be 1. If I were asking for any of the other names then it'd work I think. I am trying to get the integer representation of the 'hello.com' names (1, 2, 3, etc.), and I don't know how to do that or what else to use besides python lists. This, I don't think is going to work and I'm asking for any other ideas on what to do or use instead of using a list. (if what I'm trying to do is not possible with lists) My main goal is basically a login manager using sqlite3 and I want to have the ability to have multiple logins with some having the same domain name (but with different data and notes, etc.), because we like to have multiple logins/accounts for 1 website. I have a TUI (beaupy) for selecting the domain/option you want to get the login for but if you have more than 1 of the same domain name it doesn't know which one to pick. I have managed to use integers as IDs in the sqlite3 database to help but the main issue is the picking of an element from a list to get a number, to then plug into the read() function. So the list options will correlate to the "IDs" in the database. List index 0+1 would be option/row 1 in the database (and so on). def clear(): os.system('clear||cls') def add(encrypted_data): ID = 1 database = sqlite3.connect('vault.gter') c = database.cursor() #Check to see if IDs exist and if yes then get how many/length of list and add 1 and use that instead. c.execute("SELECT id FROM logins") all_ids = c.fetchall() out = list(itertools.chain(*all_ids)) list_length = len(out) if not all_ids: pass else: for x in out: if x == list_length: ID = x+1 else: pass c.execute(f"INSERT INTO logins VALUES ('{ID}', '{encrypted_data}')") database.commit() database.close() def domains(dKey): database = sqlite3.connect('vault.gter') c = database.cursor() c.execute("SELECT data FROM logins") websites = c.fetchall() enc_output = list(itertools.chain(*websites)) web_lst = [] note_lst = [] for x in enc_output: result = gcm.stringD(x, dKey) #decrypt encrypted json string. obj_result = json.loads(result) #turns back into json object website = obj_result['Domain'] notes = obj_result['Notes'] web_lst.append(website) note_lst.append(notes) for w,n in zip(web_lst, note_lst): with open('.lst', 'a') as fa: fa.writelines(f"{w} ({n})\n") fa.close() with open(".lst", "r+") as fr: data = fr.read() fnlst = data.strip().split('\n') fr.truncate(0) fr.close() os.remove(".lst") print(f'(Press "ctrl+c" to exit)\n-----------------------------------------------------------\n\nWebsite domain/name to get login for?\n') domain = beaupy.select(fnlst, cursor_style="#ffa533") clear() if domain == None: clear() return else: domain = domain.split(' ', 1)[0] #get first word in a string. print(domain) #debug index = web_lst.index(domain)+1 input(index) #debug pwd = read(index) return pwd # Come up with new way to show available options to chose from and then get number from that to use here for "db_row". def read(db_row): database = sqlite3.connect('vault.gter') c = database.cursor() c.execute("SELECT id FROM logins") all_ids = c.fetchall() lst_output = list(itertools.chain(*all_ids)) if not all_ids: input("No IDS") #debug database.commit() database.close() return else: for x in lst_output: if x == db_row: c.execute(f"SELECT data FROM logins WHERE id LIKE '{db_row}'") #to prevent my main issue of it not knowing what I want when two domain names are the same. stoof = c.fetchone() database.commit() database.close() return stoof[0] else: #(debug) - input(f"error, x is not the same as db_row. x = {x} & db_row = {db_row}") pass If anyone has a better way of doing this whole login manager thing, I'll be very very appreciative. From handling the database and sqlite3 commands, better IDs? to perhaps completely a different (and free) way of storage. And finding a better way to handle my main problem here (with or without having to use lists). Anything is helpful. <3 If anyone has questions then feel free to ask away and I'll respond when I can with the best of my knowledge.
[ "You can get both the index and the element using a for-loop.\nfor i in range(len(lst)):\n element = lst[i]\n if element == domain:\n print(i)\n\nThis should give you all indexes of domain.\nEdited Code:\nd = {}\nc = 0\nfor i in range(len(lst)):\n element = lst[i]\n if element == domain:\n c += 1\n d[c] = i\n\nfor number, index in d.items():\n # Do something here. Remember to use number and index instead of c and i!\n\nc is the occurence number, and i is the index.\n", "Here is a one-liner:\n[{item:[i for i, x in enumerate(lst) if x == item]} for item in set(lst)]\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "sqlite3_python" ]
stackoverflow_0074662809_python_python_3.x_sqlite3_python.txt
Q: Pagination on pandas dataframe.to_html() I have a huge pandas dataframe I am converting to html table i.e. dataframe.to_html(), its about 1000 rows. Any easy way to use pagination so that I dont have to scroll the whole 1000 rows. Say, view the first 50 rows then click next to see subsequent 50 rows? A: Update 2022 It seems that there is now a simple and modern solution, using itables. Installation: pip install itables Basic usage (from the GitHub readme): from itables import show show(df) Result: There is also a command for displaying all tables in the notebook like this by default. Original answer (exporting table to HTML file) The best solution I can think of involves a couple of external JS libraries: JQuery and its DataTables plugin. This will allow for much more than pagination, with very little effort. Let's set up some HTML, JS and python: from tempfile import NamedTemporaryFile import webbrowser base_html = """ <!doctype html> <html><head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css"> <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script> </head><body>%s<script type="text/javascript">$(document).ready(function(){$('table').DataTable({ "pageLength": 50 });});</script> </body></html> """ def df_html(df): """HTML table with pagination and other goodies""" df_html = df.to_html() return base_html % df_html def df_window(df): """Open dataframe in browser window using a temporary file""" with NamedTemporaryFile(delete=False, suffix='.html') as f: f.write(df_html(df)) webbrowser.open(f.name) And now we can load a sample dataset to test it: from sklearn.datasets import load_iris import pandas as pd iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) df_window(df) The beautiful result: A few notes: Notice the pageLength parameter in the base_html string. This is where I defined the default number of rows per page. You can find other optional parameters in the DataTable options page. The df_window function was tested in a Jupyter Notebook, but should work in plain python as well. You can skip df_window and simply write the returned value from df_html into an HTML file. Edit: how to make this work with a remote session (e.g. Colab) When working on a remote notebook, like in Colab or Kaggle the temporary file approach won't work, since the file is saved on the remote machine and not accessible by your browser. A workaround for that would be to download the constructed HTML and open it locally (adding to the previous code): import base64 from IPython.core.display import display, HTML my_html = df_html(df) my_html_base64 = base64.b64encode(my_html.encode()).decode('utf-8') display(HTML(f'<a download href="data:text/html;base64,{my_html_base64}" target="_blank">Download HTML</a>')) This will result in a link containing the entire HTML encoded as a base64 string. Clicking it will download the HTML file and you can then open it directly and view the table. A: I developed a solution for this out of necessity: paginate_pandas, a much simpler package than itables, leveraging on ipywidgets. With some obvious bias, I feel itables might be a bit overkill. I can already filter and sort with pandas when I'm in Jupyter, so the only thing I need is pagination. paginate_pandas gives you that with a nice slider:
Pagination on pandas dataframe.to_html()
I have a huge pandas dataframe I am converting to html table i.e. dataframe.to_html(), its about 1000 rows. Any easy way to use pagination so that I dont have to scroll the whole 1000 rows. Say, view the first 50 rows then click next to see subsequent 50 rows?
[ "Update 2022\nIt seems that there is now a simple and modern solution, using itables.\nInstallation:\npip install itables\n\nBasic usage (from the GitHub readme):\nfrom itables import show\n\nshow(df)\n\nResult:\n\nThere is also a command for displaying all tables in the notebook like this by default.\nOriginal answer (exporting table to HTML file)\nThe best solution I can think of involves a couple of external JS libraries: JQuery and its DataTables plugin. This will allow for much more than pagination, with very little effort.\nLet's set up some HTML, JS and python:\nfrom tempfile import NamedTemporaryFile\nimport webbrowser\n\nbase_html = \"\"\"\n<!doctype html>\n<html><head>\n<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\">\n<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js\"></script>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css\">\n<script type=\"text/javascript\" src=\"https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js\"></script>\n</head><body>%s<script type=\"text/javascript\">$(document).ready(function(){$('table').DataTable({\n \"pageLength\": 50\n});});</script>\n</body></html>\n\"\"\"\n\ndef df_html(df):\n \"\"\"HTML table with pagination and other goodies\"\"\"\n df_html = df.to_html()\n return base_html % df_html\n\ndef df_window(df):\n \"\"\"Open dataframe in browser window using a temporary file\"\"\"\n with NamedTemporaryFile(delete=False, suffix='.html') as f:\n f.write(df_html(df))\n webbrowser.open(f.name)\n\nAnd now we can load a sample dataset to test it:\nfrom sklearn.datasets import load_iris\nimport pandas as pd\n\niris = load_iris()\ndf = pd.DataFrame(iris.data, columns=iris.feature_names)\n\ndf_window(df)\n\nThe beautiful result:\n\nA few notes:\n\nNotice the pageLength parameter in the base_html string. This is where I defined the default number of rows per page. You can find other optional parameters in the DataTable options page.\nThe df_window function was tested in a Jupyter Notebook, but should work in plain python as well.\nYou can skip df_window and simply write the returned value from df_html into an HTML file.\n\nEdit: how to make this work with a remote session (e.g. Colab)\nWhen working on a remote notebook, like in Colab or Kaggle the temporary file approach won't work, since the file is saved on the remote machine and not accessible by your browser. A workaround for that would be to download the constructed HTML and open it locally (adding to the previous code):\nimport base64\nfrom IPython.core.display import display, HTML\n\nmy_html = df_html(df)\nmy_html_base64 = base64.b64encode(my_html.encode()).decode('utf-8')\ndisplay(HTML(f'<a download href=\"data:text/html;base64,{my_html_base64}\" target=\"_blank\">Download HTML</a>'))\n\nThis will result in a link containing the entire HTML encoded as a base64 string. Clicking it will download the HTML file and you can then open it directly and view the table.\n", "I developed a solution for this out of necessity: paginate_pandas, a much simpler package than itables, leveraging on ipywidgets.\nWith some obvious bias, I feel itables might be a bit overkill. I can already filter and sort with pandas when I'm in Jupyter, so the only thing I need is pagination. paginate_pandas gives you that with a nice slider:\n\n" ]
[ 13, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0038893448_pandas_python.txt
Q: Python - Find x and y values of a 2D gaussian given a value for the function I have a 2D gaussian function f(x,y). I know the values x₀ and y₀ at which the peak g₀ of the function occurs. But then I want to find xₑ and yₑ values at which f(xₑ, yₑ) = g₀ / e¹. I know there are multiple solutions to this, but at least one is sufficient. So far I have def f(x, y, g0,x0,y0,sigma_x,sigma_y,offset): return offset + g0* np.exp(-(((x-x0)**(2)/(2*sigma_x**(2))) + ((y-y0)**(2)/(2*sigma_y**(2))))) All variables taken as parameters are known as they were extracted from a curve fit. I understand that taking the derivative in x and setting f() = 0 and similarly in y, gives a solvable linear system for (x,y), but this seems like overkill to manually implement, there must be some library or tool out there that can do what I am trying to achieve? A: There are an infinite number of possibilities (or possibly 1 trivial or none in special cases regarding the value of g0). A solution can be computed analytically in constant time using a direct method. No need for approximations or iterative methods to find roots of a given function. It is just pure maths. Gaussian kernel have interesting symmetries. One of them is the invariance to the rotation when the peak is translated to (0,0). Another on is that the 1D section of a 2D gaussian surface is a gaussian curve. Lets ignore offset for a moment: it does not really change the problem (it is just a Z-axis translation) and add additional useless term for the resolution. The geometric solution to is problem is an ellipse so the solution (xe, ye) follows the conic expression : (xe-x0)² / a² + (ye-y0)² / b² = 1. If sigma_x = sigma_y, then the solution is simpler : this is a circle with the expression (xe-x0)² + (ye-y0)² = r. Note that a, b and r are dependant of the searched value and the kernel parameters (eg. sigma_x). Changing sigma_x and sigma_y is like stretching the space, and so the solution similarly. Changing x0 and y0 is like translating the space and so the solution too. In fact, we could solve the problem for the simpler case where x0=0, y0=0, sigma_x=1 and sigma_y=1. Then we can apply a translation, followed by a linear transformation using a transformation matrix. A basic multiplication 4x4 matrix can do that. Solving the simpler case is much easier since there are are less parameter to consider. Actually, g0 and offset can also be partially discarded of f since it is on both side of the expression and one just need to solve the linear equation offset + g0 * h(xe,ye) = g0 / e so h(x,y) = 1 / e - offset / g0 where h(xe, ye) = exp(-(xe² + ye²)/2). Assuming we forget the translation and linear transformation for a moment, the problem can be solve quite easily: h(xe, ye) = 1 / e - offset / g0 exp(-(xe² + ye²)/2) = 1 / e - offset / g0 -(xe² + ye²)/2 = ln(1 / e - offset / g0) xe² + ye² = -2 * ln(1 / e - offset / g0) That's it! We got our circle expression where the radius r is -2*ln(1 / e - offset / g0)! Note that ln in the expression is basically the natural logarithm. Now we could try to find the 4x4 matrix coefficients, or actually try to directly solve the full expression which is finally not so difficult. offset + g0 * exp(-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²))) = g0 / e exp(-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²))) = 1 / e - offset / g0 -((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²)) = ln(1 / e - offset / g0) ((x-x0)²/sigma_x² + (y-y0)²/sigma_y²)/2 = -ln(1 / e - offset / g0) (x-x0)²/sigma_x² + (y-y0)²/sigma_y² = -2 * ln(1 / e - offset / g0) That's it! We got you conic expression where r = -2 * ln(1 / e - offset / g0) is a constant, a = sigma_x and b = sigma_y are the unknown parameter in the above expression. It can be normalized using a = sigma_x/sqrt(r) and b = sigma_y/sqrt(r) so the right hand side is 1 fitting exactly with the above expression but this is just some math details. You can find one point of the ellipse easily since you know the centre of the ellipse (x0, y0) and there is at least 1 point at the intersection of the line y=y0 and the above conic expression. Lets find it: (x-x0)²/sigma_x² + (y0-y0)²/sigma_y² = -2 * ln(1 / e - offset / g0) (x-x0)²/sigma_x² = -2 * ln(1 / e - offset / g0) (x-x0)² = -2 * ln(1 / e - offset / g0) * sigma_x² x = sqrt(-2 * ln(1 / e - offset / g0) * sigma_x²) + x0 Note there are two solutions (-sqrt(...) + x0) but you only need one of them. I hope I did not make any mistake in the computation (at least the details should be enough to find it easily) and the solution is not a complex number in your case. The benefit of this solution is that it is very very fast to compute. The final solution is: (xe, ye) = (sqrt(-2*ln(1/e-offset/g0)*sigma_x²)+x0, y0) A: You can use the scipy.optimize.fsolve function to find the (xₑ, yₑ) values that satisfy the equation f(xₑ, yₑ) = g₀ / e¹. This function uses a numerical root-finding algorithm to find the roots of a system of non-linear equations. Here's an example of how you can use scipy.optimize.fsolve to find the (xₑ, yₑ) values that satisfy the equation f(xₑ, yₑ) = g₀ / e¹: from scipy.optimize import fsolve # Define the function f(x, y) def f(x, y, g0, x0, y0, sigma_x, sigma_y, offset): return offset + g0 * np.exp(-(((x-x0)**(2)/(2*sigma_x**(2))) + ((y-y0)**(2)/(2*sigma_y**(2))))) # Define the function that we want to find the roots of def g(xy, g0, x0, y0, sigma_x, sigma_y, offset): x, y = xy return f(x, y, g0, x0, y0, sigma_x, sigma_y, offset) - g0 / np.exp(1) # Define the initial guess for the root x0_guess = x0 y0_guess = y0 # Find the roots of the function g(x, y) x, y = fsolve(g, (x0_guess, y0_guess), args=(g0, x0, y0, sigma_x, sigma_y, offset)) # Print the result print(f"x = {x}, y = {y}") In this example, fsolve will use the initial guess (x0_guess, y0_guess) as a starting point and iteratively try to find the roots of the function g(x, y). If the function g(x, y) has multiple roots, fsolve will return only one of them (the one closest to the initial guess).
Python - Find x and y values of a 2D gaussian given a value for the function
I have a 2D gaussian function f(x,y). I know the values x₀ and y₀ at which the peak g₀ of the function occurs. But then I want to find xₑ and yₑ values at which f(xₑ, yₑ) = g₀ / e¹. I know there are multiple solutions to this, but at least one is sufficient. So far I have def f(x, y, g0,x0,y0,sigma_x,sigma_y,offset): return offset + g0* np.exp(-(((x-x0)**(2)/(2*sigma_x**(2))) + ((y-y0)**(2)/(2*sigma_y**(2))))) All variables taken as parameters are known as they were extracted from a curve fit. I understand that taking the derivative in x and setting f() = 0 and similarly in y, gives a solvable linear system for (x,y), but this seems like overkill to manually implement, there must be some library or tool out there that can do what I am trying to achieve?
[ "There are an infinite number of possibilities (or possibly 1 trivial or none in special cases regarding the value of g0). A solution can be computed analytically in constant time using a direct method. No need for approximations or iterative methods to find roots of a given function. It is just pure maths.\nGaussian kernel have interesting symmetries. One of them is the invariance to the rotation when the peak is translated to (0,0). Another on is that the 1D section of a 2D gaussian surface is a gaussian curve.\nLets ignore offset for a moment: it does not really change the problem (it is just a Z-axis translation) and add additional useless term for the resolution.\nThe geometric solution to is problem is an ellipse so the solution (xe, ye) follows the conic expression : (xe-x0)² / a² + (ye-y0)² / b² = 1. If sigma_x = sigma_y, then the solution is simpler : this is a circle with the expression (xe-x0)² + (ye-y0)² = r. Note that a, b and r are dependant of the searched value and the kernel parameters (eg. sigma_x). Changing sigma_x and sigma_y is like stretching the space, and so the solution similarly. Changing x0 and y0 is like translating the space and so the solution too.\nIn fact, we could solve the problem for the simpler case where x0=0, y0=0, sigma_x=1 and sigma_y=1. Then we can apply a translation, followed by a linear transformation using a transformation matrix. A basic multiplication 4x4 matrix can do that. Solving the simpler case is much easier since there are are less parameter to consider. Actually, g0 and offset can also be partially discarded of f since it is on both side of the expression and one just need to solve the linear equation offset + g0 * h(xe,ye) = g0 / e so h(x,y) = 1 / e - offset / g0 where h(xe, ye) = exp(-(xe² + ye²)/2). Assuming we forget the translation and linear transformation for a moment, the problem can be solve quite easily:\nh(xe, ye) = 1 / e - offset / g0 \nexp(-(xe² + ye²)/2) = 1 / e - offset / g0 \n-(xe² + ye²)/2 = ln(1 / e - offset / g0) \nxe² + ye² = -2 * ln(1 / e - offset / g0)\nThat's it! We got our circle expression where the radius r is -2*ln(1 / e - offset / g0)! Note that ln in the expression is basically the natural logarithm.\nNow we could try to find the 4x4 matrix coefficients, or actually try to directly solve the full expression which is finally not so difficult.\noffset + g0 * exp(-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²))) = g0 / e \nexp(-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²))) = 1 / e - offset / g0 \n-((x-x0)²/(2*sigma_x²) + (y-y0)²/(2*sigma_y²)) = ln(1 / e - offset / g0) \n((x-x0)²/sigma_x² + (y-y0)²/sigma_y²)/2 = -ln(1 / e - offset / g0) \n(x-x0)²/sigma_x² + (y-y0)²/sigma_y² = -2 * ln(1 / e - offset / g0)\nThat's it! We got you conic expression where r = -2 * ln(1 / e - offset / g0) is a constant, a = sigma_x and b = sigma_y are the unknown parameter in the above expression. It can be normalized using a = sigma_x/sqrt(r) and b = sigma_y/sqrt(r) so the right hand side is 1 fitting exactly with the above expression but this is just some math details.\nYou can find one point of the ellipse easily since you know the centre of the ellipse (x0, y0) and there is at least 1 point at the intersection of the line y=y0 and the above conic expression. Lets find it:\n(x-x0)²/sigma_x² + (y0-y0)²/sigma_y² = -2 * ln(1 / e - offset / g0) \n(x-x0)²/sigma_x² = -2 * ln(1 / e - offset / g0) \n(x-x0)² = -2 * ln(1 / e - offset / g0) * sigma_x² \nx = sqrt(-2 * ln(1 / e - offset / g0) * sigma_x²) + x0\nNote there are two solutions (-sqrt(...) + x0) but you only need one of them. I hope I did not make any mistake in the computation (at least the details should be enough to find it easily) and the solution is not a complex number in your case. The benefit of this solution is that it is very very fast to compute.\nThe final solution is: \n(xe, ye) = (sqrt(-2*ln(1/e-offset/g0)*sigma_x²)+x0, y0)\n", "You can use the scipy.optimize.fsolve function to find the (xₑ, yₑ) values that satisfy the equation f(xₑ, yₑ) = g₀ / e¹. This function uses a numerical root-finding algorithm to find the roots of a system of non-linear equations.\nHere's an example of how you can use scipy.optimize.fsolve to find the (xₑ, yₑ) values that satisfy the equation f(xₑ, yₑ) = g₀ / e¹:\nfrom scipy.optimize import fsolve\n\n# Define the function f(x, y)\ndef f(x, y, g0, x0, y0, sigma_x, sigma_y, offset):\n return offset + g0 * np.exp(-(((x-x0)**(2)/(2*sigma_x**(2))) + ((y-y0)**(2)/(2*sigma_y**(2)))))\n\n# Define the function that we want to find the roots of\ndef g(xy, g0, x0, y0, sigma_x, sigma_y, offset):\n x, y = xy\n return f(x, y, g0, x0, y0, sigma_x, sigma_y, offset) - g0 / np.exp(1)\n\n# Define the initial guess for the root\nx0_guess = x0\ny0_guess = y0\n\n# Find the roots of the function g(x, y)\nx, y = fsolve(g, (x0_guess, y0_guess), args=(g0, x0, y0, sigma_x, sigma_y, offset))\n\n# Print the result\nprint(f\"x = {x}, y = {y}\")\n\nIn this example, fsolve will use the initial guess (x0_guess, y0_guess) as a starting point and iteratively try to find the roots of the function g(x, y). If the function g(x, y) has multiple roots, fsolve will return only one of them (the one closest to the initial guess).\n" ]
[ 2, 1 ]
[]
[]
[ "gaussian", "numpy", "python" ]
stackoverflow_0074660993_gaussian_numpy_python.txt
Q: How do I print values by sections? How do I print values like this: I'm making program that returns a store invoice, but I don't know how to print the result like that. I tried .format but the values don't have the same length. A: num = 142 print("This is right-aligned by 10 units. {:>10}".format(num))
How do I print values by sections?
How do I print values like this: I'm making program that returns a store invoice, but I don't know how to print the result like that. I tried .format but the values don't have the same length.
[ "num = 142\nprint(\"This is right-aligned by 10 units. {:>10}\".format(num))\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074662835_python_python_3.x.txt
Q: Why won't the second pushed tile show? I placed the rectangles over the images. I then bound a click to a call that flipped tiles over by lowering the rectangle below the image. It works for the first call to the function, but when I click another tile, that one won't flip over. The program still registers the second flip because it'll flip everything back over if it's an incorrect match; the only problem is that it won't have the rectangle go under the image. # ======================================= import statements import tkinter as tk import time import random import PIL import PIL.Image as Image import PIL.ImageTk as ImageTk # ======================================= class def class MemoryGame: def __init__(self): #initialize window self.window = tk.Tk() self.window.title("Sea Life Memory Game") self.window.minsize(590, 600) self.window.maxsize(590, 600) #set main canvas as background self.canvas = tk.Canvas(self.window, bg="lightblue", bd=0, highlightthickness=0, width=590, height=600) self.canvas.grid(row=0, column=0) self.canvas.bind("<Button-1>", self.chooseTile) #establish coordinates for tiles and shuffle image placement coordinates = [(5,30,105,130), (5,160,105,260), (5,290,105,390), (5,420,105,520), (125,30,225,130), (125,160,225,260), (125,290,225,390), (125,420,225,520), (245,30,345,130), (245,160,345,260), (245,290,345,390), (245,420,345,520), (365,30,465,130), (365,160,465,260), (365,290,465,390), (365,420,465,520), (485,30,585,130), (485,160,585,260), (485,290,585,390), (485,420,585,520)] imageChoices = ['cropped images/001-turtle.png','cropped images/007-blowfish.png','cropped images/010-jellyfish.png','cropped images/011-starfish.png','cropped images/018-lobster.png','cropped images/028-fish.png','cropped images/033-walrus.png','cropped images/042-goldfish.png','cropped images/045-seal.png','cropped images/046-penguin.png'] random.shuffle(coordinates) #write title to top of canvas self.canvas.create_text(295, 15, text="Sea Life Memory Game!", anchor="center", fill="white", font="Times 24 bold") self.selectedTile = None #initialize counts coordinateCount = 0 imageCount = 0 self.imageCollection = {} #for loop to attach images to each rectangle on the canvas for i in range(len(imageChoices)): otherDict = {} x1, y1, x2, y2 = coordinates[coordinateCount] # if imageCount <= 9: self.image = ImageTk.PhotoImage(Image.open(imageChoices[imageCount])) self.image.img = self.image self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 x1, y1, x2, y2 = coordinates[coordinateCount] self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 imageCount += 1 otherDict["faceDown"] = True self.imageCollection[self.id] = otherDict #create instructional text self.canvas.create_text(295, 550, text="Find all the pairs as fast as possible.", fill="white", font="Times 18", anchor="center") self.canvas.create_text(295, 570, text="Click on a card to turn it over and find the same matching card.", fill="white", font="Times 18", anchor="center") def run(self): self.window.mainloop() global list list = [] def chooseTile(self, event): # global list x = event.x y = event.y item = self.canvas.find_overlapping(x-5,y-5,x+5,y+5) list.append(item) print(len(list)) if len(list) < 2: self.canvas.tag_lower(list[0][1]) elif len(list) == 2: self.canvas.tag_lower(list[1][1]) if self.canvas.itemcget(list[0][0], "image") == self.canvas.itemcget(list[1][0], "image"): list.clear() else: time.sleep(1.0) self.canvas.lower(list[0][0], list[0][1]) self.canvas.lower(list[1][0], list[1][1]) list.clear() # ======================================= script calls game = MemoryGame() game.run() A: It is because the update will be performed after chooseTile() returns to tkinter mainloop(). But the images are already reset to lower layer when the function returns, so you cannot see the second selected image. The simple fix is calling self.canvas.update_idletasks() to force the update to show the second selected image before time.sleep(1.0): def chooseTile(self, event): # global list x = event.x y = event.y item = self.canvas.find_overlapping(x-5,y-5,x+5,y+5) list.append(item) print(len(list)) if len(list) < 2: self.canvas.tag_lower(list[0][1]) elif len(list) == 2: self.canvas.tag_lower(list[1][1]) if self.canvas.itemcget(list[0][0], "image") == self.canvas.itemcget(list[1][0], "image"): list.clear() else: # force the canvas to show the second selected image self.canvas.update_idletasks() time.sleep(1.0) self.canvas.lower(list[0][0], list[0][1]) self.canvas.lower(list[1][0], list[1][1]) list.clear() A: I finally got it to work!! # ======================================= import statements import tkinter as tk import random import PIL.Image as Image import PIL.ImageTk as ImageTk # ======================================= class def class MemoryGame: def __init__(self): #initialize window self.window = tk.Tk() self.window.title("Sea Life Memory Game") self.window.minsize(590, 600) self.window.maxsize(590, 600) #set main canvas as background self.canvas = tk.Canvas(self.window, bg="lightblue", bd=0, highlightthickness=0, width=590, height=600) self.canvas.grid(row=0, column=0) self.canvas.bind("<Button-1>", self.chooseTile) #establish coordinates for tiles and shuffle image placement coordinates = [(5,30,105,130), (5,160,105,260), (5,290,105,390), (5,420,105,520), (125,30,225,130), (125,160,225,260), (125,290,225,390), (125,420,225,520), (245,30,345,130), (245,160,345,260), (245,290,345,390), (245,420,345,520), (365,30,465,130), (365,160,465,260), (365,290,465,390), (365,420,465,520), (485,30,585,130), (485,160,585,260), (485,290,585,390), (485,420,585,520)] imageChoices = ['cropped images/001-turtle.png','cropped images/007-blowfish.png','cropped images/010-jellyfish.png','cropped images/011-starfish.png','cropped images/018-lobster.png','cropped images/028-fish.png','cropped images/033-walrus.png','cropped images/042-goldfish.png','cropped images/045-seal.png','cropped images/046-penguin.png'] random.shuffle(coordinates) #write title to top of canvas self.canvas.create_text(295, 15, text="Sea Life Memory Game!", anchor="center", fill="white", font="Times 24 bold") #initialize counts coordinateCount = 0 imageCount = 0 self.imageCollection = [] #for loop to attach images to each rectangle on the canvas for i in range(len(imageChoices)): x1, y1, x2, y2 = coordinates[coordinateCount] self.image = ImageTk.PhotoImage(Image.open(imageChoices[imageCount])) self.image.img = self.image self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.imageCollection.append(self.id) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 x1, y1, x2, y2 = coordinates[coordinateCount] self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 imageCount += 1 self.imageCollection.append(self.id) #create instructional text self.canvas.create_text(295, 550, text="Find all the pairs as fast as possible.", fill="white", font="Times 18", anchor="center") self.canvas.create_text(295, 570, text="Click on a card to turn it over and find the same matching card.", fill="white", font="Times 18", anchor="center") def run(self): self.window.mainloop() global lst lst = [] global matches matches = 0 def chooseTile(self, event): global lst global matches x = event.x y = event.y item = self.canvas.find_overlapping(x-1,y-1,x+1,y+1) lst.append(item) if len(lst) < 2: self.canvas.tag_lower(lst[0][1], lst[0][0]) elif len(lst) == 2: self.canvas.tag_lower(lst[1][1],lst[1][0]) if self.canvas.itemcget(lst[0][0], "image") == self.canvas.itemcget(lst[1][0], "image"): matches += 2 lst.clear() else: self.window.update_idletasks() self.window.after(1500) self.canvas.lower(lst[0][0], lst[0][1]) self.canvas.lower(lst[1][0], lst[1][1]) lst.clear() if matches == 20: self.window.update_idletasks() self.window.after(1000) self.window.destroy() # ======================================= script calls game = MemoryGame() game.window.mainloop()
Why won't the second pushed tile show?
I placed the rectangles over the images. I then bound a click to a call that flipped tiles over by lowering the rectangle below the image. It works for the first call to the function, but when I click another tile, that one won't flip over. The program still registers the second flip because it'll flip everything back over if it's an incorrect match; the only problem is that it won't have the rectangle go under the image. # ======================================= import statements import tkinter as tk import time import random import PIL import PIL.Image as Image import PIL.ImageTk as ImageTk # ======================================= class def class MemoryGame: def __init__(self): #initialize window self.window = tk.Tk() self.window.title("Sea Life Memory Game") self.window.minsize(590, 600) self.window.maxsize(590, 600) #set main canvas as background self.canvas = tk.Canvas(self.window, bg="lightblue", bd=0, highlightthickness=0, width=590, height=600) self.canvas.grid(row=0, column=0) self.canvas.bind("<Button-1>", self.chooseTile) #establish coordinates for tiles and shuffle image placement coordinates = [(5,30,105,130), (5,160,105,260), (5,290,105,390), (5,420,105,520), (125,30,225,130), (125,160,225,260), (125,290,225,390), (125,420,225,520), (245,30,345,130), (245,160,345,260), (245,290,345,390), (245,420,345,520), (365,30,465,130), (365,160,465,260), (365,290,465,390), (365,420,465,520), (485,30,585,130), (485,160,585,260), (485,290,585,390), (485,420,585,520)] imageChoices = ['cropped images/001-turtle.png','cropped images/007-blowfish.png','cropped images/010-jellyfish.png','cropped images/011-starfish.png','cropped images/018-lobster.png','cropped images/028-fish.png','cropped images/033-walrus.png','cropped images/042-goldfish.png','cropped images/045-seal.png','cropped images/046-penguin.png'] random.shuffle(coordinates) #write title to top of canvas self.canvas.create_text(295, 15, text="Sea Life Memory Game!", anchor="center", fill="white", font="Times 24 bold") self.selectedTile = None #initialize counts coordinateCount = 0 imageCount = 0 self.imageCollection = {} #for loop to attach images to each rectangle on the canvas for i in range(len(imageChoices)): otherDict = {} x1, y1, x2, y2 = coordinates[coordinateCount] # if imageCount <= 9: self.image = ImageTk.PhotoImage(Image.open(imageChoices[imageCount])) self.image.img = self.image self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 x1, y1, x2, y2 = coordinates[coordinateCount] self.id = self.canvas.create_image(x1, y1, anchor="nw", image=self.image.img) self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="white") coordinateCount += 1 imageCount += 1 otherDict["faceDown"] = True self.imageCollection[self.id] = otherDict #create instructional text self.canvas.create_text(295, 550, text="Find all the pairs as fast as possible.", fill="white", font="Times 18", anchor="center") self.canvas.create_text(295, 570, text="Click on a card to turn it over and find the same matching card.", fill="white", font="Times 18", anchor="center") def run(self): self.window.mainloop() global list list = [] def chooseTile(self, event): # global list x = event.x y = event.y item = self.canvas.find_overlapping(x-5,y-5,x+5,y+5) list.append(item) print(len(list)) if len(list) < 2: self.canvas.tag_lower(list[0][1]) elif len(list) == 2: self.canvas.tag_lower(list[1][1]) if self.canvas.itemcget(list[0][0], "image") == self.canvas.itemcget(list[1][0], "image"): list.clear() else: time.sleep(1.0) self.canvas.lower(list[0][0], list[0][1]) self.canvas.lower(list[1][0], list[1][1]) list.clear() # ======================================= script calls game = MemoryGame() game.run()
[ "It is because the update will be performed after chooseTile() returns to tkinter mainloop(). But the images are already reset to lower layer when the function returns, so you cannot see the second selected image.\nThe simple fix is calling self.canvas.update_idletasks() to force the update to show the second selected image before time.sleep(1.0):\n def chooseTile(self, event):\n # global list\n x = event.x\n y = event.y\n item = self.canvas.find_overlapping(x-5,y-5,x+5,y+5)\n list.append(item)\n print(len(list))\n if len(list) < 2:\n self.canvas.tag_lower(list[0][1])\n elif len(list) == 2:\n self.canvas.tag_lower(list[1][1])\n if self.canvas.itemcget(list[0][0], \"image\") == self.canvas.itemcget(list[1][0], \"image\"):\n list.clear()\n else:\n # force the canvas to show the second selected image\n self.canvas.update_idletasks()\n time.sleep(1.0)\n self.canvas.lower(list[0][0], list[0][1])\n self.canvas.lower(list[1][0], list[1][1])\n list.clear()\n\n", "I finally got it to work!!\n# ======================================= import statements \nimport tkinter as tk\nimport random\nimport PIL.Image as Image\nimport PIL.ImageTk as ImageTk\n# ======================================= class def\n\nclass MemoryGame:\n\n def __init__(self):\n #initialize window\n self.window = tk.Tk()\n self.window.title(\"Sea Life Memory Game\")\n self.window.minsize(590, 600)\n self.window.maxsize(590, 600)\n\n #set main canvas as background\n self.canvas = tk.Canvas(self.window, bg=\"lightblue\",\n bd=0, highlightthickness=0,\n width=590, height=600)\n self.canvas.grid(row=0, column=0)\n self.canvas.bind(\"<Button-1>\", self.chooseTile)\n\n #establish coordinates for tiles and shuffle image placement\n coordinates = [(5,30,105,130), (5,160,105,260), (5,290,105,390), (5,420,105,520), (125,30,225,130), (125,160,225,260), (125,290,225,390), (125,420,225,520), (245,30,345,130), (245,160,345,260), (245,290,345,390), (245,420,345,520), (365,30,465,130), (365,160,465,260), (365,290,465,390), (365,420,465,520), (485,30,585,130), (485,160,585,260), (485,290,585,390), (485,420,585,520)]\n imageChoices = ['cropped images/001-turtle.png','cropped images/007-blowfish.png','cropped images/010-jellyfish.png','cropped images/011-starfish.png','cropped images/018-lobster.png','cropped images/028-fish.png','cropped images/033-walrus.png','cropped images/042-goldfish.png','cropped images/045-seal.png','cropped images/046-penguin.png']\n random.shuffle(coordinates)\n\n #write title to top of canvas\n self.canvas.create_text(295, 15, text=\"Sea Life Memory Game!\",\n anchor=\"center\", fill=\"white\",\n font=\"Times 24 bold\")\n\n\n #initialize counts\n coordinateCount = 0\n imageCount = 0\n self.imageCollection = []\n #for loop to attach images to each rectangle on the canvas\n for i in range(len(imageChoices)):\n x1, y1, x2, y2 = coordinates[coordinateCount]\n self.image = ImageTk.PhotoImage(Image.open(imageChoices[imageCount]))\n self.image.img = self.image\n self.id = self.canvas.create_image(x1, y1, anchor=\"nw\",\n image=self.image.img)\n self.imageCollection.append(self.id)\n self.canvas.create_rectangle(x1, y1, x2, y2, fill=\"white\", outline=\"white\")\n coordinateCount += 1\n x1, y1, x2, y2 = coordinates[coordinateCount]\n self.id = self.canvas.create_image(x1, y1, anchor=\"nw\",\n image=self.image.img)\n self.canvas.create_rectangle(x1, y1, x2, y2, fill=\"white\", outline=\"white\")\n coordinateCount += 1\n imageCount += 1\n\n self.imageCollection.append(self.id)\n\n #create instructional text\n self.canvas.create_text(295, 550, text=\"Find all the pairs as fast as possible.\",\n fill=\"white\", font=\"Times 18\", anchor=\"center\")\n self.canvas.create_text(295, 570, text=\"Click on a card to turn it over and find the same matching card.\",\n fill=\"white\", font=\"Times 18\", anchor=\"center\")\n\n\n def run(self):\n self.window.mainloop()\n\n global lst\n lst = []\n global matches\n matches = 0\n\n def chooseTile(self, event):\n global lst\n global matches\n x = event.x\n y = event.y\n item = self.canvas.find_overlapping(x-1,y-1,x+1,y+1)\n lst.append(item)\n if len(lst) < 2:\n self.canvas.tag_lower(lst[0][1], lst[0][0])\n elif len(lst) == 2:\n self.canvas.tag_lower(lst[1][1],lst[1][0])\n if self.canvas.itemcget(lst[0][0], \"image\") == self.canvas.itemcget(lst[1][0], \"image\"):\n matches += 2\n lst.clear()\n else:\n self.window.update_idletasks()\n self.window.after(1500)\n self.canvas.lower(lst[0][0], lst[0][1])\n self.canvas.lower(lst[1][0], lst[1][1])\n lst.clear()\n if matches == 20:\n self.window.update_idletasks()\n self.window.after(1000)\n self.window.destroy()\n\n# ======================================= script calls\n\ngame = MemoryGame()\ngame.window.mainloop()\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074650846_python_tkinter.txt
Q: I have a list of list. Need to merge all the elements that is only "a" letters into a single string, moving the other elements down a position x1 = ['a','1','2','b','4'] x2 = ['a','a','2','b','4'] x3 = ['a','a','a','b','4'] x4 = ['a','1','2','b','4'] xxxx = x1,x2,x3,x4 name2f = [] for i in xxxx: a1 = i[0] b1 = i[1] c1 = i[2] if a1.isalpha: if b1.isalpha: if c1.isalpha: print("false 3") p = i[0]+" "+i[1]+" "+i[2] i.remove(a1) i.remove(b1) i.remove(c1) name2f.append(p) elif a1.isalpha: if b1.isalpha: p = i[0]+" "+i[1] i.remove(a1) i.remove(b1) name2f.append(p) elif a1.isalpha: name2f.append(a1) i.remove(a1) print("false 1") else: print("broken") isalpha and isdigit route does not seem to work nor does regex, not sure what is up. My results are print3 down the line. Not sure where the issue lies. A: Figured it out, went through the elements as a range and it worked: item = [] for items in xxxx: for i in items[0:3]: if re.match(r'[A-Z]', i) and bool(re.search(r'[0-9]', i)) == False: item.append(i) items.remove(i) w = " ".join(item) print(w) print("") print(items) A: The first problem with code shown is isalpha() is a function. The function object isalpha is always non falsy. Secondly, each of your if conditions check the exact same thing, so only the top one will run. Also, your logic is only trying to generate something like name2f = ['a', 'aa', 'aaa', 'a'] since you only check first 3 elements, so the b strings are never looked at. Break your code into two parts. You can filter non-digits simply with all_chars = [x for x in lst if not x.isdigit()] Then, write a function to join all adjacent characters, such as def collect_chars(lst): combined = lst[:1] result = [] for val in lst[1:]: if val != combined[-1]: # current char not last seen char, dump the collected values so far result.append(''.join(combined)) # and start a new string combined = [val] else: # keep adding matching strings combined.append(val) # if reached end of string, dump what has been collected so far result.append(''.join(combined)) del combined return result Then run both over the original list. for i in xxxx: all_chars = [x for x in i if not x.isdigit()] lst = collect_chars(all_chars) print(lst) Outputs ['a', 'b'] ['aa', 'b'] ['aaa', 'b'] ['a', 'b']
I have a list of list. Need to merge all the elements that is only "a" letters into a single string, moving the other elements down a position
x1 = ['a','1','2','b','4'] x2 = ['a','a','2','b','4'] x3 = ['a','a','a','b','4'] x4 = ['a','1','2','b','4'] xxxx = x1,x2,x3,x4 name2f = [] for i in xxxx: a1 = i[0] b1 = i[1] c1 = i[2] if a1.isalpha: if b1.isalpha: if c1.isalpha: print("false 3") p = i[0]+" "+i[1]+" "+i[2] i.remove(a1) i.remove(b1) i.remove(c1) name2f.append(p) elif a1.isalpha: if b1.isalpha: p = i[0]+" "+i[1] i.remove(a1) i.remove(b1) name2f.append(p) elif a1.isalpha: name2f.append(a1) i.remove(a1) print("false 1") else: print("broken") isalpha and isdigit route does not seem to work nor does regex, not sure what is up. My results are print3 down the line. Not sure where the issue lies.
[ "Figured it out, went through the elements as a range and it worked:\n item = []\n for items in xxxx:\n for i in items[0:3]:\n if re.match(r'[A-Z]', i) and bool(re.search(r'[0-9]', i)) == False:\n item.append(i)\n items.remove(i)\n\n w = \" \".join(item)\n print(w)\n print(\"\")\n print(items)\n\n", "The first problem with code shown is isalpha() is a function. The function object isalpha is always non falsy.\nSecondly, each of your if conditions check the exact same thing, so only the top one will run.\nAlso, your logic is only trying to generate something like name2f = ['a', 'aa', 'aaa', 'a'] since you only check first 3 elements, so the b strings are never looked at.\n\nBreak your code into two parts.\nYou can filter non-digits simply with\nall_chars = [x for x in lst if not x.isdigit()]\n\nThen, write a function to join all adjacent characters, such as\ndef collect_chars(lst):\n combined = lst[:1]\n result = []\n for val in lst[1:]:\n if val != combined[-1]:\n # current char not last seen char, dump the collected values so far\n result.append(''.join(combined))\n # and start a new string\n combined = [val]\n else:\n # keep adding matching strings\n combined.append(val)\n # if reached end of string, dump what has been collected so far\n result.append(''.join(combined))\n del combined\n\n return result\n\nThen run both over the original list.\nfor i in xxxx:\n all_chars = [x for x in i if not x.isdigit()]\n lst = collect_chars(all_chars)\n print(lst)\n\nOutputs\n['a', 'b']\n['aa', 'b']\n['aaa', 'b']\n['a', 'b']\n\n" ]
[ 1, 0 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0074662229_list_loops_python.txt
Q: Add decorator to component decorator in KFP v2 in Vertex AI Usually, KFP v2 supports adding a component decorator like this: @component def test(): print("hello world") I would like to add an additional decorator to add new functionality like this: @component @added_functionality def test(): print("hello world") Where added_functionality is imported and looks like this: from functools import wraps def added_functionality(func): print("starting added functionality") @wraps(func) def wrapper(*args, **kwargs): print("starting wrapper") return func(*args, **kwargs) return wrapper The issue is that when I compile the pipeline, I see 'starting added functionality' printed to the console, but "starting wrapper" doesn't show up in the log in Vertex AI. Am I doing something wrong? A: You aren't. This is a disappointing limitation of Kubeflow currently.
Add decorator to component decorator in KFP v2 in Vertex AI
Usually, KFP v2 supports adding a component decorator like this: @component def test(): print("hello world") I would like to add an additional decorator to add new functionality like this: @component @added_functionality def test(): print("hello world") Where added_functionality is imported and looks like this: from functools import wraps def added_functionality(func): print("starting added functionality") @wraps(func) def wrapper(*args, **kwargs): print("starting wrapper") return func(*args, **kwargs) return wrapper The issue is that when I compile the pipeline, I see 'starting added functionality' printed to the console, but "starting wrapper" doesn't show up in the log in Vertex AI. Am I doing something wrong?
[ "You aren't. This is a disappointing limitation of Kubeflow currently.\n" ]
[ 0 ]
[]
[]
[ "google_cloud_vertex_ai", "kfp", "python" ]
stackoverflow_0071959035_google_cloud_vertex_ai_kfp_python.txt
Q: Adding edges to Graph by iterating through adjacency matrix I have this code, which adds edges with a weight to a graph from adjacency matrix: matrix = [[0, 1, 2, 3, 4], [1, 0, 5, 6, 0], [2, 5, 0, 0, 0], [3, 0, 0, 0, 6], [4, 0, 0, 6, 0]] g1 = Graph(len(matrix)) for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] > 0: g1.add_edge(i, j, matrix[i][j]) The problem with this code is that it adds same edges twice, f.e it adds edge 0 - 1 and 1 -0, 0 - 2 and 2 - 0. What I want is to add those edges only once. Is this possible somehow? I added this print print(f'Addind edge {i}-{j} with weight {matrix[i][j]}') statement so you could see what is happening. Output: Addind edge 0-1 with weight 1 Addind edge 0-2 with weight 2 Addind edge 0-3 with weight 3 Addind edge 0-4 with weight 4 Addind edge 1-0 with weight 1 Addind edge 1-2 with weight 5 Addind edge 1-3 with weight 6 Addind edge 2-0 with weight 2 Addind edge 2-1 with weight 5 Addind edge 3-0 with weight 3 Addind edge 3-4 with weight 6 Addind edge 4-0 with weight 4 Addind edge 4-3 with weight 6 A: One way to solve this is to add an additional check for the edge that is being added, before actually adding the edge. For example, you can add a check to make sure the edge is not already present in the graph. You can do this by looping through the graph and checking if the edge is already present before adding it. Here is an example of how to do this: g1 = Graph(len(matrix)) for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] > 0: # check if the edge is already present if not g1.has_edge(i, j): g1.add_edge(i, j, matrix[i][j]) A: To add edges to a graph from an adjacency matrix such that each edge is added only once, you can use the following approach: Check if the value at the current matrix[i][j] position is greater than 0. This indicates that there is an edge between the vertices i and j with weight matrix[i][j]. If matrix[i][j] is greater than 0, check if j is greater than i. This ensures that we only add each edge once, since for an undirected graph, the edge i-j is the same as the edge j-i. If j is greater than i, add the edge i-j to the graph with weight matrix[i][j]. Here is an example of how you can modify your code to implement this approach: matrix = [[0, 1, 2, 3, 4], [1, 0, 5, 6, 0], [2, 5, 0, 0, 0], [3, 0, 0, 0, 6], [4, 0, 0, 6, 0]] g1 = Graph(len(matrix)) for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] > 0 and j > i: # Check if matrix[i][j] is greater than 0 and j is greater than i g1.add_edge(i, j, matrix[i][j]) # Add edge i-j with weight matrix[i][j] With this change, the code will only add each edge once, resulting in the following output when you print the edges in the graph: Addind edge 0-1 with weight 1 Addind edge 0-2 with weight 2 Addind edge 0-3 with weight 3 Addind edge 0-4 with weight 4 Addind edge 1-2 with weight 5 Addind edge 1-3 with weight 6 Addind edge 3-4 with weight 6
Adding edges to Graph by iterating through adjacency matrix
I have this code, which adds edges with a weight to a graph from adjacency matrix: matrix = [[0, 1, 2, 3, 4], [1, 0, 5, 6, 0], [2, 5, 0, 0, 0], [3, 0, 0, 0, 6], [4, 0, 0, 6, 0]] g1 = Graph(len(matrix)) for i in range(len(matrix)): for j in range(len(matrix)): if matrix[i][j] > 0: g1.add_edge(i, j, matrix[i][j]) The problem with this code is that it adds same edges twice, f.e it adds edge 0 - 1 and 1 -0, 0 - 2 and 2 - 0. What I want is to add those edges only once. Is this possible somehow? I added this print print(f'Addind edge {i}-{j} with weight {matrix[i][j]}') statement so you could see what is happening. Output: Addind edge 0-1 with weight 1 Addind edge 0-2 with weight 2 Addind edge 0-3 with weight 3 Addind edge 0-4 with weight 4 Addind edge 1-0 with weight 1 Addind edge 1-2 with weight 5 Addind edge 1-3 with weight 6 Addind edge 2-0 with weight 2 Addind edge 2-1 with weight 5 Addind edge 3-0 with weight 3 Addind edge 3-4 with weight 6 Addind edge 4-0 with weight 4 Addind edge 4-3 with weight 6
[ "One way to solve this is to add an additional check for the edge that is being added, before actually adding the edge. For example, you can add a check to make sure the edge is not already present in the graph. You can do this by looping through the graph and checking if the edge is already present before adding it.\nHere is an example of how to do this:\ng1 = Graph(len(matrix))\nfor i in range(len(matrix)):\n for j in range(len(matrix)):\n if matrix[i][j] > 0:\n # check if the edge is already present\n if not g1.has_edge(i, j):\n g1.add_edge(i, j, matrix[i][j])\n\n", "To add edges to a graph from an adjacency matrix such that each edge is added only once, you can use the following approach:\n\nCheck if the value at the current matrix[i][j] position is greater than 0. This indicates that there is an edge between the vertices i and j with weight matrix[i][j].\nIf matrix[i][j] is greater than 0, check if j is greater than i. This ensures that we only add each edge once, since for an undirected graph, the edge i-j is the same as the edge j-i.\nIf j is greater than i, add the edge i-j to the graph with weight matrix[i][j].\nHere is an example of how you can modify your code to implement this approach:\n\nmatrix = [[0, 1, 2, 3, 4],\n [1, 0, 5, 6, 0],\n [2, 5, 0, 0, 0],\n [3, 0, 0, 0, 6],\n [4, 0, 0, 6, 0]]\n\ng1 = Graph(len(matrix))\nfor i in range(len(matrix)):\n for j in range(len(matrix)):\n if matrix[i][j] > 0 and j > i: # Check if matrix[i][j] is greater than 0 and j is greater than i\n g1.add_edge(i, j, matrix[i][j]) # Add edge i-j with weight matrix[i][j]\n\nWith this change, the code will only add each edge once, resulting in the following output when you print the edges in the graph:\nAddind edge 0-1 with weight 1\nAddind edge 0-2 with weight 2\nAddind edge 0-3 with weight 3\nAddind edge 0-4 with weight 4\nAddind edge 1-2 with weight 5\nAddind edge 1-3 with weight 6\nAddind edge 3-4 with weight 6\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074663056_python_python_3.x.txt
Q: No module named 'tensorflow.tsl' I'm trying to install Tensorflow. I did the installation using the cmd.exe prompt and the installation was a success. But when I try to import TensorFlow appear the following error ModuleNotFoundError: No module named 'tensorflow.tsl' I follow this steps to install tensorflow: $ pip install -U pip $ pip install tensorflow How can I solve the issue? A: Check the version of tensorflow-serving-api and update it with $ pip install tensorflow-serving-api==X.Y.0 X and Y should match your TensorFlow version. You can determine your TensorFlow version with $ pip freeze | grep tensorflow
No module named 'tensorflow.tsl'
I'm trying to install Tensorflow. I did the installation using the cmd.exe prompt and the installation was a success. But when I try to import TensorFlow appear the following error ModuleNotFoundError: No module named 'tensorflow.tsl' I follow this steps to install tensorflow: $ pip install -U pip $ pip install tensorflow How can I solve the issue?
[ "Check the version of tensorflow-serving-api and update it with\n$ pip install tensorflow-serving-api==X.Y.0\n\nX and Y should match your TensorFlow version. You can determine your TensorFlow version with\n$ pip freeze | grep tensorflow\n\n" ]
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074632821_python_tensorflow.txt
Q: Why doesn't mean square error work in case of angular data? Suppose, the following is a dataset for solving a regression problem: H -9.118 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 7.470 6.452 6.069 6.197 6.434 8.264 9.047 2.222 H 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 -8.536 6.452 6.069 6.197 6.434 8.264 9.047 11.954 2.416 C 5.166 4.852 5.164 4.943 8.103 -9.152 -8.536 5.433 6.069 6.197 6.434 8.264 9.047 11.954 6.703 3.028 C 4.852 5.164 4.943 8.103 -9.152 -8.536 5.433 4.924 6.197 6.434 8.264 9.047 11.954 6.703 6.407 -1.235 C 5.164 4.943 8.103 -9.152 -8.536 5.433 4.924 5.007 6.434 8.264 9.047 11.954 6.703 6.407 6.088 -0.953 H 4.943 8.103 -9.152 -8.536 5.433 4.924 5.007 5.057 8.264 9.047 11.954 6.703 6.407 6.088 6.410 2.233 H 8.103 -9.152 -8.536 5.433 4.924 5.007 5.057 5.026 9.047 11.954 6.703 6.407 6.088 6.410 6.206 2.313 H -9.152 -8.536 5.433 4.924 5.007 5.057 5.026 5.154 11.954 6.703 6.407 6.088 6.410 6.206 6.000 2.314 H -8.536 5.433 4.924 5.007 5.057 5.026 5.154 5.173 6.703 6.407 6.088 6.410 6.206 6.000 6.102 2.244 H 5.433 4.924 5.007 5.057 5.026 5.154 5.173 5.279 6.407 6.088 6.410 6.206 6.000 6.102 6.195 2.109 the left-most column is the class data. The rest of the features are all angular data. My initial setup for the model was as follows: def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss="mean_squared_error", optimizer=opt, metrics=["mean_squared_error"] ) # return model return model This model didn't produce the correct outcome. Someone told me that MSE doesn't work in the case of angular data. So, I need to use a custom output layer and a custom error function. Why doesn't mean square error work in the case of angular data? How can I solve this issue? A: Data that represent angles like 180 degrees, causes problems with most loss functions because they are not meant for radiants. MSE calculates a huge error between 0 and 359 although 0=360. It simply doesn’t understand the concepts of radiants and angles. There are a number of ways to fix this depending on what you want to predict. The easiest would be to transform your data via sinus function and then use the transformed data for training. You would need to apply the inverse function to your predictions. The other option is to customise the MSE loss function to transform x via the sinus function. A: The mean squared error (MSE) loss function is not well-suited for regression tasks involving angular data because it treats all errors (i.e. differences between predicted and true values) equally, regardless of their direction. This is problematic when working with angular data, because the difference between two angles (e.g. 0° and 359°) is not the same as the difference between 359° and 0°. To address this issue, you can use a custom loss function that accounts for the periodicity of angular data. For example, you can use the mean angular error (MAE) loss function, which calculates the mean absolute difference between the predicted and true angles in radians. The MAE loss function is defined as: MAE = 1/N * Σ|yₜ - yₚ| where N is the number of samples, yₜ is the true angle, and yₚ is the predicted angle. Here's an example of how you can use the MAE loss function in a Keras model for regression tasks involving angular data: # Define the MAE loss function def mae_loss(y_true, y_pred): # Convert the true and predicted angles from degrees to radians y_true_rad = tf.math.deg2rad(y_true) y_pred_rad = tf.math.deg2rad(y_pred) # Calculate the absolute difference between the predicted and true angles in radians diff = tf.math.abs(y_true_rad - y_pred_rad) # Calculate the mean absolute error mae = tf.reduce_mean(diff) # Return the mean absolute error return mae # Define the model architecture def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss=mae_loss, optimizer=opt, metrics=["mean_squared_error"] ) # return model return model In this example, we define a custom loss function called mae_loss that calculates the mean absolute error between the predicted and true angles in radians. We then use this loss function when compiling the model. A: Mean squared error (MSE) is a common loss function used for regression problems. It calculates the difference between the predicted value and the true value, squares it, and then takes the average across all the data points. MSE works well for regression problems with continuous, numeric data, but it may not be appropriate for regression problems with angular data. In the case of angular data, MSE can produce misleading results because it treats all directions equally, regardless of the direction's angle. For example, if the true value is 0 degrees and the predicted value is 5 degrees, the difference is 5 degrees and the squared error is 25. However, if the true value is 175 degrees and the predicted value is 180 degrees, the difference is also 5 degrees, but the squared error is 625 because the 175 degrees and 180 degrees are almost opposite directions. In this case, MSE would produce a much larger error even though the prediction is almost correct. To properly handle angular data, you can use a custom output layer and a custom error function that accounts for the circular nature of the data. For example, you could use a sine and cosine output layer to represent the angle as a complex number, and then use the complex error (CE) loss function to calculate the error. CE calculates the absolute difference between the predicted and true complex numbers, which accounts for the circular nature of the data and produces more accurate results for angular data. Here is an example of how you could modify the model to use a sine and cosine output layer and the CE loss function: def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) # Add a sine and cosine output layer model.add(tf.keras.layers.Dense(1, activation="sin")) model.add(tf.keras.layers.Dense(1, activation="cos")) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss=complex_error, # use the complex error loss function optimizer=opt, metrics=["mean_squared_error"] ) # return model return model This modified model will use a sine and cosine output layer to represent the angle as a complex number, and it will use the CE loss function to calculate the error. This should produce more accurate results for regression problems with angular data. A: The mean squared error (MSE) loss function is commonly used for regression tasks, but it is not suitable for data with angular features. This is because the MSE function treats all features as if they are linear, but angular features are not linear. To properly handle angular features in your regression model, you can use a custom loss function that takes the circular nature of the data into account. One such loss function is the circular mean squared error (CMSE) loss function. This loss function is defined as follows: CMSE = (1 / N) * sum(min(2 * pi, |y - y_pred|))^2 where N is the number of samples, y is the true value, and y_pred is the predicted value. To use the CMSE loss function in your model, you can modify your create_model function as follows: import tensorflow as tf def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # define the CMSE loss function def cmse(y_true, y_pred): pi = tf.constant(np.pi) return tf.reduce_mean(tf.square(tf.minimum(2 * pi, tf.abs(y_true - y_pred)))) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss=cmse, optimizer=opt, metrics=["mean_squared_error"] ) # return model return model This will use the CMSE loss function instead of the MSE loss function, which should improve the performance of your model on angular data. You can also consider using other metrics, such as the circular mean absolute error (CMAE) or the circular mean absolute percentage error (CMAPE), to evaluate the performance of your model. I hope this helps! Let me know if you have any other questions. A: Mean squared error (MSE) is a loss function that is often used in regression tasks, where the goal is to predict a continuous value. MSE works by calculating the square of the difference between the predicted value and the true value, and then taking the mean of those squared differences. In the case of angular data, MSE may not be the best loss function to use because it does not take into account the circular nature of angles. For example, the angles 0 and 360 degrees are essentially the same, but MSE would treat them as being very different. One solution to this problem is to use a loss function that is specifically designed for angular data, such as the sine squared error or the cosine squared error. These loss functions take into account the circular nature of angles and can produce better results in regression tasks involving angular data. In a Keras/TensorFlow-based model, you can use these loss functions by defining a custom loss function and passing it to the model.compile method when you compile the model. Here is an example of how you might do this: def sine_squared_error(y_true, y_pred): # calculate the sine of the difference between the true angle and the predicted angle error = tf.sin(y_true - y_pred) # square the error and return the mean return tf.reduce_mean(tf.square(error)) # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model using the sine squared error as the loss function model.compile( loss=sine_squared_error, optimizer=opt, metrics=["mean_squared_error"] ) I hope this helps! My donation addresses: BTC:178vgzZkLNV9NPxZiQqabq5crzBSgQWmvs,ETH:0x99753577c4ae89e7043addf7abbbdf7258a74697 A: I am assuming that by "angular" you mean some form of representation of an angle. If this is the case, then MSE does not work well because it does not have a concept of 0 == 360 (or equivalent regularities in radians), thus e.g. predicting 359.999999 for a correct label of 0 will create a huge error, while it should produce a tiny error. A: import tensorflow as tf import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import MinMaxScaler %matplotlib inline def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = tf.keras.Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='sigmoid')) # relu ignores data information, so we choose sigmoid. model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss="mean_squared_error", optimizer="adam", # metrics=["mean_squared_error"] ) # return model return model ss = [['H',-9.118,5.488,5.166,4.852,5.164,4.943,8.103,-9.152,7.470,6.452,6.069,6.197,6.434,8.264,9.047, 2.222], ['H',5.488,5.166,4.852,5.164,4.943,8.103,-9.152,-8.536,6.452,6.069,6.197,6.434,8.264,9.047,11.954, 2.416], ['C',5.166,4.852,5.164,4.943,8.103,-9.152,-8.536,5.433,6.069,6.197,6.434,8.264,9.047,11.954,6.703, 3.028], ['C',4.852,5.164,4.943,8.103,-9.152,-8.536,5.433,4.924,6.197,6.434,8.264,9.047,11.954,6.703,6.407,-1.235], ['C',5.164,4.943,8.103,-9.152,-8.536,5.433,4.924,5.007,6.434,8.264,9.047,11.954,6.703,6.407,6.088,-0.953], ['H',4.943,8.103,-9.152,-8.536,5.433,4.924,5.007,5.057,8.264,9.047,11.954,6.703,6.407,6.088,6.410, 2.233], ['H',8.103,-9.152,-8.536,5.433,4.924,5.007,5.057,5.026,9.047,11.954,6.703,6.407,6.088,6.410,6.206, 2.313], ['H',-9.152,-8.536,5.433,4.924,5.007,5.057,5.026,5.154,11.954,6.703,6.407,6.088,6.410,6.206,6.000, 2.314], ['H',-8.536,5.433,4.924,5.007,5.057,5.026,5.154,5.173,6.703,6.407,6.088,6.410,6.206,6.000,6.102, 2.244], ['H',5.433,4.924,5.007,5.057,5.026,5.154,5.173,5.279,6.407,6.088,6.410,6.206,6.000,6.102,6.195, 2.109]] data = pd.DataFrame(ss) y =data.iloc[:,-1:] x = data.iloc[:,1:-1] # scaler, Accelerating model convergence scaler = MinMaxScaler() x_model = scaler.fit(x) x = scaler.transform(x) y_model = scaler.fit(y) y = scaler.transform(y) # model LEARNING_RATE = 0.001 model = create_model(n_hidden_1=4, n_hidden_2=2, num_features=15) model.fit(x,y,epochs=1000) # predict y_pre = model.predict(x) print('predict: ',y_model.inverse_transform(y_pre)) print('y: ',y_model.inverse_transform(y)) predict: [[ 2.2238724 ] [ 2.415551 ] [ 3.0212667 ] [-1.1861311 ] [-0.98702306] [ 2.2277246 ] [ 2.3132346 ] [ 2.3148017 ] [ 2.235104 ] [ 2.1206288 ]] y: [[ 2.222] [ 2.416] [ 3.028] [-1.235] [-0.953] [ 2.233] [ 2.313] [ 2.314] [ 2.244] [ 2.109]] I wrote a piece of code and annotated it. In terms of the results, the difference is very small. Friendly tip: pay attention to the over fitting of the model. A: In general, mean squared error (MSE) is a suitable loss function for regression problems, including regression problems with angular data. However, MSE has some limitations when it comes to angular data. One issue with using MSE for regression with angular data is that MSE is not invariant under circular shifts. This means that if you shift all of the angular data by a constant angle, the MSE will change, even though the underlying data has not changed. This can lead to issues with convergence and inaccurate predictions. Another issue with using MSE for angular data is that MSE is not sensitive to the order of the data. For example, if you have two angular data points that are 180 degrees apart, the MSE will be the same regardless of which point comes first. This can cause problems with certain types of regression models that rely on the order of the data. For these reasons, it can be useful to use a custom loss function that is specifically designed for angular data. There are several options for custom loss functions that can be used for angular data, including the von Mises loss and the wrapped normal loss. These loss functions are invariant under circular shifts and are sensitive to the order of the data, which can improve the accuracy of the model. It's worth noting that using a custom loss function is not always necessary for regression with angular data. In some cases, MSE may be sufficient, depending on the specific characteristics of the data and the goals of the model. It's always a good idea to experiment with different loss functions and evaluate their performance on your data to determine the best option for your particular use case.
Why doesn't mean square error work in case of angular data?
Suppose, the following is a dataset for solving a regression problem: H -9.118 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 7.470 6.452 6.069 6.197 6.434 8.264 9.047 2.222 H 5.488 5.166 4.852 5.164 4.943 8.103 -9.152 -8.536 6.452 6.069 6.197 6.434 8.264 9.047 11.954 2.416 C 5.166 4.852 5.164 4.943 8.103 -9.152 -8.536 5.433 6.069 6.197 6.434 8.264 9.047 11.954 6.703 3.028 C 4.852 5.164 4.943 8.103 -9.152 -8.536 5.433 4.924 6.197 6.434 8.264 9.047 11.954 6.703 6.407 -1.235 C 5.164 4.943 8.103 -9.152 -8.536 5.433 4.924 5.007 6.434 8.264 9.047 11.954 6.703 6.407 6.088 -0.953 H 4.943 8.103 -9.152 -8.536 5.433 4.924 5.007 5.057 8.264 9.047 11.954 6.703 6.407 6.088 6.410 2.233 H 8.103 -9.152 -8.536 5.433 4.924 5.007 5.057 5.026 9.047 11.954 6.703 6.407 6.088 6.410 6.206 2.313 H -9.152 -8.536 5.433 4.924 5.007 5.057 5.026 5.154 11.954 6.703 6.407 6.088 6.410 6.206 6.000 2.314 H -8.536 5.433 4.924 5.007 5.057 5.026 5.154 5.173 6.703 6.407 6.088 6.410 6.206 6.000 6.102 2.244 H 5.433 4.924 5.007 5.057 5.026 5.154 5.173 5.279 6.407 6.088 6.410 6.206 6.000 6.102 6.195 2.109 the left-most column is the class data. The rest of the features are all angular data. My initial setup for the model was as follows: def create_model(n_hidden_1, n_hidden_2, num_features): # create the model model = Sequential() model.add(tf.keras.layers.InputLayer(input_shape=(num_features,))) model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu')) model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu')) model.add(tf.keras.layers.Dense(1)) # instantiate the optimizer opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE) # compile the model model.compile( loss="mean_squared_error", optimizer=opt, metrics=["mean_squared_error"] ) # return model return model This model didn't produce the correct outcome. Someone told me that MSE doesn't work in the case of angular data. So, I need to use a custom output layer and a custom error function. Why doesn't mean square error work in the case of angular data? How can I solve this issue?
[ "Data that represent angles like 180 degrees, causes problems with most loss functions because they are not meant for radiants. MSE calculates a huge error between 0 and 359 although 0=360. It simply doesn’t understand the concepts of radiants and angles.\nThere are a number of ways to fix this depending on what you want to predict. The easiest would be to transform your data via sinus function and then use the transformed data for training. You would need to apply the inverse function to your predictions.\nThe other option is to customise the MSE loss function to transform x via the sinus function.\n", "The mean squared error (MSE) loss function is not well-suited for regression tasks involving angular data because it treats all errors (i.e. differences between predicted and true values) equally, regardless of their direction. This is problematic when working with angular data, because the difference between two angles (e.g. 0° and 359°) is not the same as the difference between 359° and 0°.\nTo address this issue, you can use a custom loss function that accounts for the periodicity of angular data. For example, you can use the mean angular error (MAE) loss function, which calculates the mean absolute difference between the predicted and true angles in radians. The MAE loss function is defined as:\nMAE = 1/N * Σ|yₜ - yₚ|\nwhere N is the number of samples, yₜ is the true angle, and yₚ is the predicted angle.\nHere's an example of how you can use the MAE loss function in a Keras model for regression tasks involving angular data:\n# Define the MAE loss function\ndef mae_loss(y_true, y_pred):\n # Convert the true and predicted angles from degrees to radians\n y_true_rad = tf.math.deg2rad(y_true)\n y_pred_rad = tf.math.deg2rad(y_pred)\n\n # Calculate the absolute difference between the predicted and true angles in radians\n diff = tf.math.abs(y_true_rad - y_pred_rad)\n\n # Calculate the mean absolute error\n mae = tf.reduce_mean(diff)\n\n # Return the mean absolute error\n return mae\n\n# Define the model architecture\ndef create_model(n_hidden_1, n_hidden_2, num_features):\n # create the model\n model = Sequential()\n model.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\n model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\n model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu'))\n model.add(tf.keras.layers.Dense(1))\n\n # instantiate the optimizer\n opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n # compile the model\n model.compile(\n loss=mae_loss,\n optimizer=opt,\n metrics=[\"mean_squared_error\"]\n )\n\n # return model\n return model\n\nIn this example, we define a custom loss function called mae_loss that calculates the mean absolute error between the predicted and true angles in radians. We then use this loss function when compiling the model.\n", "Mean squared error (MSE) is a common loss function used for regression problems. It calculates the difference between the predicted value and the true value, squares it, and then takes the average across all the data points. MSE works well for regression problems with continuous, numeric data, but it may not be appropriate for regression problems with angular data.\nIn the case of angular data, MSE can produce misleading results because it treats all directions equally, regardless of the direction's angle. For example, if the true value is 0 degrees and the predicted value is 5 degrees, the difference is 5 degrees and the squared error is 25. However, if the true value is 175 degrees and the predicted value is 180 degrees, the difference is also 5 degrees, but the squared error is 625 because the 175 degrees and 180 degrees are almost opposite directions. In this case, MSE would produce a much larger error even though the prediction is almost correct.\nTo properly handle angular data, you can use a custom output layer and a custom error function that accounts for the circular nature of the data. For example, you could use a sine and cosine output layer to represent the angle as a complex number, and then use the complex error (CE) loss function to calculate the error. CE calculates the absolute difference between the predicted and true complex numbers, which accounts for the circular nature of the data and produces more accurate results for angular data.\nHere is an example of how you could modify the model to use a sine and cosine output layer and the CE loss function:\ndef create_model(n_hidden_1, n_hidden_2, num_features):\n # create the model\n model = Sequential()\n model.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\n model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\n model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu'))\n \n # Add a sine and cosine output layer\n model.add(tf.keras.layers.Dense(1, activation=\"sin\"))\n model.add(tf.keras.layers.Dense(1, activation=\"cos\"))\n\n # instantiate the optimizer\n opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n # compile the model\n model.compile(\n loss=complex_error, # use the complex error loss function\n optimizer=opt,\n metrics=[\"mean_squared_error\"]\n )\n\n # return model\n return model\n\n\nThis modified model will use a sine and cosine output layer to represent the angle as a complex number, and it will use the CE loss function to calculate the error. This should produce more accurate results for regression problems with angular data.\n", "The mean squared error (MSE) loss function is commonly used for regression tasks, but it is not suitable for data with angular features. This is because the MSE function treats all features as if they are linear, but angular features are not linear.\nTo properly handle angular features in your regression model, you can use a custom loss function that takes the circular nature of the data into account. One such loss function is the circular mean squared error (CMSE) loss function. This loss function is defined as follows:\nCMSE = (1 / N) * sum(min(2 * pi, |y - y_pred|))^2\nwhere N is the number of samples, y is the true value, and y_pred is the predicted value.\nTo use the CMSE loss function in your model, you can modify your create_model function as follows:\nimport tensorflow as tf\n\ndef create_model(n_hidden_1, n_hidden_2, num_features):\n # create the model\n model = Sequential()\n model.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\n model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\n model.add(tf.keras.layers.Dense(n_hidden_2, activation='relu'))\n model.add(tf.keras.layers.Dense(1))\n\n # define the CMSE loss function\n def cmse(y_true, y_pred):\n pi = tf.constant(np.pi)\n return tf.reduce_mean(tf.square(tf.minimum(2 * pi, tf.abs(y_true - y_pred))))\n\n # instantiate the optimizer\n opt = keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n # compile the model\n model.compile(\n loss=cmse,\n optimizer=opt,\n metrics=[\"mean_squared_error\"]\n )\n\n # return model\n return model\n\nThis will use the CMSE loss function instead of the MSE loss function, which should improve the performance of your model on angular data. You can also consider using other metrics, such as the circular mean absolute error (CMAE) or the circular mean absolute percentage error (CMAPE), to evaluate the performance of your model.\nI hope this helps! Let me know if you have any other questions.\n", "Mean squared error (MSE) is a loss function that is often used in regression tasks, where the goal is to predict a continuous value. MSE works by calculating the square of the difference between the predicted value and the true value, and then taking the mean of those squared differences.\nIn the case of angular data, MSE may not be the best loss function to use because it does not take into account the circular nature of angles. For example, the angles 0 and 360 degrees are essentially the same, but MSE would treat them as being very different.\nOne solution to this problem is to use a loss function that is specifically designed for angular data, such as the sine squared error or the cosine squared error. These loss functions take into account the circular nature of angles and can produce better results in regression tasks involving angular data.\nIn a Keras/TensorFlow-based model, you can use these loss functions by defining a custom loss function and passing it to the model.compile method when you compile the model. Here is an example of how you might do this:\ndef sine_squared_error(y_true, y_pred):\n # calculate the sine of the difference between the true angle and the predicted angle\n error = tf.sin(y_true - y_pred)\n\n # square the error and return the mean\n return tf.reduce_mean(tf.square(error))\n\n# create the model\nmodel = Sequential()\nmodel.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\nmodel.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\nmodel.add(tf.keras.layers.Dense(n_hidden_2, activation='relu'))\nmodel.add(tf.keras.layers.Dense(1))\n\n# instantiate the optimizer\nopt = keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n# compile the model using the sine squared error as the loss function\nmodel.compile(\n loss=sine_squared_error,\n optimizer=opt,\n metrics=[\"mean_squared_error\"]\n)\n\nI hope this helps!\nMy donation addresses: BTC:178vgzZkLNV9NPxZiQqabq5crzBSgQWmvs,ETH:0x99753577c4ae89e7043addf7abbbdf7258a74697\n", "I am assuming that by \"angular\" you mean some form of representation of an angle. If this is the case, then MSE does not work well because it does not have a concept of 0 == 360 (or equivalent regularities in radians), thus e.g. predicting 359.999999 for a correct label of 0 will create a huge error, while it should produce a tiny error.\n", "import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import MinMaxScaler\n%matplotlib inline\n\ndef create_model(n_hidden_1, n_hidden_2, num_features):\n # create the model\n model = tf.keras.Sequential()\n model.add(tf.keras.layers.InputLayer(input_shape=(num_features,)))\n model.add(tf.keras.layers.Dense(n_hidden_1, activation='relu'))\n model.add(tf.keras.layers.Dense(n_hidden_2, activation='sigmoid')) # relu ignores data information, so we choose sigmoid.\n model.add(tf.keras.layers.Dense(1))\n\n # instantiate the optimizer\n opt = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n\n # compile the model\n model.compile(\n loss=\"mean_squared_error\",\n optimizer=\"adam\",\n# metrics=[\"mean_squared_error\"]\n )\n\n # return model\n return model\n\nss = [['H',-9.118,5.488,5.166,4.852,5.164,4.943,8.103,-9.152,7.470,6.452,6.069,6.197,6.434,8.264,9.047, 2.222],\n['H',5.488,5.166,4.852,5.164,4.943,8.103,-9.152,-8.536,6.452,6.069,6.197,6.434,8.264,9.047,11.954, 2.416],\n['C',5.166,4.852,5.164,4.943,8.103,-9.152,-8.536,5.433,6.069,6.197,6.434,8.264,9.047,11.954,6.703, 3.028],\n['C',4.852,5.164,4.943,8.103,-9.152,-8.536,5.433,4.924,6.197,6.434,8.264,9.047,11.954,6.703,6.407,-1.235],\n['C',5.164,4.943,8.103,-9.152,-8.536,5.433,4.924,5.007,6.434,8.264,9.047,11.954,6.703,6.407,6.088,-0.953],\n['H',4.943,8.103,-9.152,-8.536,5.433,4.924,5.007,5.057,8.264,9.047,11.954,6.703,6.407,6.088,6.410, 2.233],\n['H',8.103,-9.152,-8.536,5.433,4.924,5.007,5.057,5.026,9.047,11.954,6.703,6.407,6.088,6.410,6.206, 2.313],\n['H',-9.152,-8.536,5.433,4.924,5.007,5.057,5.026,5.154,11.954,6.703,6.407,6.088,6.410,6.206,6.000, 2.314],\n['H',-8.536,5.433,4.924,5.007,5.057,5.026,5.154,5.173,6.703,6.407,6.088,6.410,6.206,6.000,6.102, 2.244],\n['H',5.433,4.924,5.007,5.057,5.026,5.154,5.173,5.279,6.407,6.088,6.410,6.206,6.000,6.102,6.195, 2.109]]\n\ndata = pd.DataFrame(ss)\ny =data.iloc[:,-1:]\nx = data.iloc[:,1:-1]\n\n# scaler, Accelerating model convergence\nscaler = MinMaxScaler()\nx_model = scaler.fit(x)\nx = scaler.transform(x)\n\ny_model = scaler.fit(y)\ny = scaler.transform(y)\n\n# model \nLEARNING_RATE = 0.001\nmodel = create_model(n_hidden_1=4, n_hidden_2=2, num_features=15)\n\nmodel.fit(x,y,epochs=1000)\n\n# predict \ny_pre = model.predict(x)\nprint('predict: ',y_model.inverse_transform(y_pre))\nprint('y: ',y_model.inverse_transform(y))\npredict: [[ 2.2238724 ]\n [ 2.415551 ]\n [ 3.0212667 ]\n [-1.1861311 ]\n [-0.98702306]\n [ 2.2277246 ]\n [ 2.3132346 ]\n [ 2.3148017 ]\n [ 2.235104 ]\n [ 2.1206288 ]]\ny: [[ 2.222]\n [ 2.416]\n [ 3.028]\n [-1.235]\n [-0.953]\n [ 2.233]\n [ 2.313]\n [ 2.314]\n [ 2.244]\n [ 2.109]]\n\nI wrote a piece of code and annotated it. In terms of the results, the difference is very small. Friendly tip: pay attention to the over fitting of the model.\n", "In general, mean squared error (MSE) is a suitable loss function for regression problems, including regression problems with angular data. However, MSE has some limitations when it comes to angular data.\nOne issue with using MSE for regression with angular data is that MSE is not invariant under circular shifts. This means that if you shift all of the angular data by a constant angle, the MSE will change, even though the underlying data has not changed. This can lead to issues with convergence and inaccurate predictions.\nAnother issue with using MSE for angular data is that MSE is not sensitive to the order of the data. For example, if you have two angular data points that are 180 degrees apart, the MSE will be the same regardless of which point comes first. This can cause problems with certain types of regression models that rely on the order of the data.\nFor these reasons, it can be useful to use a custom loss function that is specifically designed for angular data. There are several options for custom loss functions that can be used for angular data, including the von Mises loss and the wrapped normal loss. These loss functions are invariant under circular shifts and are sensitive to the order of the data, which can improve the accuracy of the model.\nIt's worth noting that using a custom loss function is not always necessary for regression with angular data. In some cases, MSE may be sufficient, depending on the specific characteristics of the data and the goals of the model. It's always a good idea to experiment with different loss functions and evaluate their performance on your data to determine the best option for your particular use case.\n" ]
[ 2, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "mean_square_error", "neural_network", "python", "radians" ]
stackoverflow_0071187809_mean_square_error_neural_network_python_radians.txt
Q: Problem with coding multi-frame jump animation (GDScript) So I am a beginner programmer using GDScript and got stuck with playing jump animation. All my animations are like 2 frames and where easy to code, but my jump is multi-frame and I couldn't find a tutorial to help. Also I'm not comfortable with anim.tree -s, I prefer to hard code them in. My code (I know its basic): extends KinematicBody2D const SPD = 100 const GRV = 15 const JUMPF = -350 const SPD_B = 50 var valocity = Vector2(0,0) func _process(delta): if Input.is_action_pressed("ui_right"): valocity.x = SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_left"): valocity.x = -SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true else: $AnimatedSprite.play("idle") valocity.y = valocity.y + GRV if Input.is_action_pressed("ui_sprint") and Input.is_action_pressed("ui_right"): valocity.x = SPD + SPD_B $AnimatedSprite.play("run") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_sprint") and Input.is_action_pressed("ui_left"): valocity.x = -SPD + -SPD_B $AnimatedSprite.play("run") $AnimatedSprite.flip_h = true if Input.is_action_just_pressed("ui_up") and is_on_floor(): valocity.y = JUMPF valocity = move_and_slide(valocity, Vector2.UP) valocity.x = lerp(valocity.x, 0, 0.3) func _on_Area2D_body_entered(body): get_tree().reload_current_scene() SPD_B is speed bonus for sprint Game is 2d platformer I tried anim.tree but couldn't use it. It was to confusing. Also I tried to code it like other but it didn't work. Any help is appreciated. A: I presume you would insert a line $AnimatedSprite.play("jump") or similar to play your jump animation. Correct? Then the issue is that it gets replaced by the "walk" (or "run") or "idle" animation the next frame. Well, do you want those animations to play while the character is on the air (not is_on_floor())? If you don't, then don't. usually the animations that play on the air are for jumping and falling, not for walking/running nor for idle. That could be for example: if is_on_floor(): if Input.is_action_pressed("ui_right"): valocity.x = SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_left"): valocity.x = -SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true else: $AnimatedSprite.play("idle") # … Now, presumably you still want air control (allow the player to move with the directions while it is on the air)… Thus I suggest to separate the animation concern. So, one block of code will set the motion. And another will set the animations. Something like this: if Input.is_action_pressed("ui_right"): valocity.x = SPD elif Input.is_action_pressed("ui_left"): valocity.x = -SPD # … if is_zero_approx(valocity.x): $AnimatedSprite.play("idle") elif valocity.x > 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif valocity.x < 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true The above code also makes it easy for the animation to change to "idle" automatically when the speed falls to zero. For example if you have some deceleration code such as valocity.x *= 0.7 (which, notice, is not frame rate independent, but you get the idea). And then it is easy to have a set of animations for the air and another for ground: if Input.is_action_pressed("ui_right"): valocity.x = SPD elif Input.is_action_pressed("ui_left"): valocity.x = -SPD # … if is_on_floor(): if is_zero_approx(valocity.x): $AnimatedSprite.play("idle") elif valocity.x > 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif valocity.x < 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true # … else: $AnimatedSprite.play("jump") # … You can, of course, define a thresholds for using the "run" animation instead of the "walk" animation. For example: if is_on_floor(): if is_zero_approx(valocity.x): $AnimatedSprite.play("idle") elif valocity.x > SPD: $AnimatedSprite.play("run") $AnimatedSprite.flip_h = false elif valocity.x < -SPD: $AnimatedSprite.play("run") $AnimatedSprite.flip_h = true elif valocity.x > 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif valocity.x < 0.0: $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true And of course, you would have to call `move_and_slide``, and also insert the code for jumps, gravity, and so on.
Problem with coding multi-frame jump animation (GDScript)
So I am a beginner programmer using GDScript and got stuck with playing jump animation. All my animations are like 2 frames and where easy to code, but my jump is multi-frame and I couldn't find a tutorial to help. Also I'm not comfortable with anim.tree -s, I prefer to hard code them in. My code (I know its basic): extends KinematicBody2D const SPD = 100 const GRV = 15 const JUMPF = -350 const SPD_B = 50 var valocity = Vector2(0,0) func _process(delta): if Input.is_action_pressed("ui_right"): valocity.x = SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_left"): valocity.x = -SPD $AnimatedSprite.play("walk") $AnimatedSprite.flip_h = true else: $AnimatedSprite.play("idle") valocity.y = valocity.y + GRV if Input.is_action_pressed("ui_sprint") and Input.is_action_pressed("ui_right"): valocity.x = SPD + SPD_B $AnimatedSprite.play("run") $AnimatedSprite.flip_h = false elif Input.is_action_pressed("ui_sprint") and Input.is_action_pressed("ui_left"): valocity.x = -SPD + -SPD_B $AnimatedSprite.play("run") $AnimatedSprite.flip_h = true if Input.is_action_just_pressed("ui_up") and is_on_floor(): valocity.y = JUMPF valocity = move_and_slide(valocity, Vector2.UP) valocity.x = lerp(valocity.x, 0, 0.3) func _on_Area2D_body_entered(body): get_tree().reload_current_scene() SPD_B is speed bonus for sprint Game is 2d platformer I tried anim.tree but couldn't use it. It was to confusing. Also I tried to code it like other but it didn't work. Any help is appreciated.
[ "I presume you would insert a line $AnimatedSprite.play(\"jump\") or similar to play your jump animation. Correct?\nThen the issue is that it gets replaced by the \"walk\" (or \"run\") or \"idle\" animation the next frame.\nWell, do you want those animations to play while the character is on the air (not is_on_floor())? If you don't, then don't. usually the animations that play on the air are for jumping and falling, not for walking/running nor for idle.\nThat could be for example:\nif is_on_floor():\n if Input.is_action_pressed(\"ui_right\"):\n valocity.x = SPD\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = false\n elif Input.is_action_pressed(\"ui_left\"):\n valocity.x = -SPD\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = true\n else:\n $AnimatedSprite.play(\"idle\")\n\n # …\n\nNow, presumably you still want air control (allow the player to move with the directions while it is on the air)… Thus I suggest to separate the animation concern.\nSo, one block of code will set the motion. And another will set the animations. Something like this:\nif Input.is_action_pressed(\"ui_right\"):\n valocity.x = SPD\nelif Input.is_action_pressed(\"ui_left\"):\n valocity.x = -SPD\n\n# …\n\nif is_zero_approx(valocity.x):\n $AnimatedSprite.play(\"idle\")\nelif valocity.x > 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = false\nelif valocity.x < 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = true\n\nThe above code also makes it easy for the animation to change to \"idle\" automatically when the speed falls to zero. For example if you have some deceleration code such as valocity.x *= 0.7 (which, notice, is not frame rate independent, but you get the idea).\nAnd then it is easy to have a set of animations for the air and another for ground:\nif Input.is_action_pressed(\"ui_right\"):\n valocity.x = SPD\nelif Input.is_action_pressed(\"ui_left\"):\n valocity.x = -SPD\n\n# …\n\nif is_on_floor():\n if is_zero_approx(valocity.x):\n $AnimatedSprite.play(\"idle\")\n elif valocity.x > 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = false\n elif valocity.x < 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = true\n\n # …\nelse:\n $AnimatedSprite.play(\"jump\")\n # …\n\nYou can, of course, define a thresholds for using the \"run\" animation instead of the \"walk\" animation. For example:\nif is_on_floor():\n if is_zero_approx(valocity.x):\n $AnimatedSprite.play(\"idle\")\n elif valocity.x > SPD:\n $AnimatedSprite.play(\"run\")\n $AnimatedSprite.flip_h = false\n elif valocity.x < -SPD:\n $AnimatedSprite.play(\"run\")\n $AnimatedSprite.flip_h = true\n elif valocity.x > 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = false\n elif valocity.x < 0.0:\n $AnimatedSprite.play(\"walk\")\n $AnimatedSprite.flip_h = true\n\nAnd of course, you would have to call `move_and_slide``, and also insert the code for jumps, gravity, and so on.\n" ]
[ 0 ]
[]
[]
[ "animation", "gdscript", "godot", "python" ]
stackoverflow_0074660243_animation_gdscript_godot_python.txt
Q: BeautifulSoup find a href in marquee I'm using bs4 to scrape links from a scrolling marquee. I'm able to get the marquee data, which is returned as a bs4 resultSet element. However, I cannot seem to access the href's within the data. I'm sure I'm missing something as I'm new to web scraping, and appreciate any guidance anyone has. Note: I can get the links easy peasy with selenium and chrome driver, but it takes forever. This returns all of the marquee data: url = 'https://drugs.globalincidentmap.com/' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') marquee = soup.select('div', class_='h-48') print(marquee) However when I try to drill down further into the data, I get the empty list or NoneType/KeyError or AttributeError. for a in marquee.find_all('a', href=True): link = a.find('div', class_=':nth-child') or for a in marquee.find_all('a', href=True): link = a.find('div', class_='flex p-2') Links in marquee A: I can get the links easy peasy with selenium and chrome driver Probably because the div with h-48 class is loaded with JavaScript; even if it wasn't, I don't think soup.find('div', class_='h-48') would work because that element has more classes, and you need to pass all of them as class_ [and I don't think soup.select('div', class_='h-48') gives the exact results you expect it to - select isn't really supposed to have a class_ argument - just a CSS selector string]. soup.find('div', attrs={'class':'h-48'}) or soup.select('div.h-48') can be expected to work on the html that is formed after JS loading, but you need selenium to get that... Fortunately, I think the data you want is already in the fetched html, just in a different format - you can extract a list of dictionaries (mqCont) with # import json marq = soup.find('marquee', attrs={'class':'h-48'}) if marq is None: print('Could Not Find marquee.h-48') if not marq.get(':contents'): print('marquee.h-48 has no [:contents] attr') try: mqCont = json.loads(marq.get(':contents', '[]')) except Exception as e: mqCont = [] print('failed to parse marquee.h-48[:contents] <---', e) or, more shortly (if you're confident there won't be any error to debug/breakdown): mqCont = json.loads(soup.select_one('marquee.h-48').get(':contents', '[]')) You can get a list of links to news articles with [m['url'] for m in mqCont if 'url' in m], but since you were trying to get find with class_='flex p-2', you probably want the .../event_detail?id=... links. You can form them as below evtUrls = [f"{url.strip('/')}/event_detail?id={m['id']}" for m in mqCont if 'id' in m] You can also view the list of dictionaries as a table [with pandas] by doing something like: # import pandas omitKeys = ['domain_event_types', 'country'] for i, m in enumerate(mqCont): mDesc = ' '.join(w for w in BeautifulSoup( m['description'] if 'description' in m else '' ).get_text().split() if w) if mDesc: m['description'] = mDesc if 'id' in m: m['eventUrl'] = f"{url.strip('/')}/event_detail?id={m['id']}" mqCont[i] = {k:v for k, v in m.items() if k not in omitKeys} mqcDF = pandas.DataFrame(mqCont).dropna(axis='columns', how='all').set_index('id') and the first 5 rows [of 100 rows total] of mqcDF: id country_id address event_gmt_time severity infrastructure tip_text url description latitude longitude created_user_id location_granularity_id is_approved created_at updated_at eventUrl 11919404 231 Pennsylvania, USA 2022-12-01 18:36:53 Severe Unknown PENNSYLVANIA - Photos - Suspects - Evidence In Multi-County Drug Bust https://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1 [69 NEWS] PENNSYLVANIA - PHOTOS: Suspects, evidence in multi-county drug bust "Authorities said they seized evidence that included 27.5 kilograms of cocaine with a potential street value of $2.7 million and 5.5 kilograms of fentanyl with a potential street value of $1.6 million." Read full article at: https://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1 41.2033 -77.1945 14 8 1 2022-12-02T18:44:43.000000Z 2022-12-02T18:44:43.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919404 11919401 40 Vancouver Island, British Columbia, Canada 2022-12-01 18:33:01 Severe Unknown CANADA - Drugs - Guns Seized As 4 BC Men With Hells Angels Ties Face Serious Charges https://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/ [terracestandard.com] CANADA - Drugs, guns seized as 4 B.C. men with Hells Angels ties face ‘serious charges’ "CFSEU said the seized drugs included 7.75kg of cocaine, 4kg of cannabis, 1.9kg of methamphetamine, 248 oxycodone pills, and more." Read full article at: https://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/ 49.6506 -125.449 14 5 1 2022-12-02T18:36:37.000000Z 2022-12-02T18:36:37.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919401 11919397 133 Male, Maldives 2022-11-20 18:29:26 Severe Unknown MALDIVES - Drugs Worth Mvr 2 Mln Seized By Customs https://avas.mv/en/125385 [avas.mv] MALDIVES - Drugs worth MVR 2 mln seized by Customs "Maldives Customs Service has seized 1.34 kg of drugs smuggled into the Maldives via courier." Read full article at: https://avas.mv/en/125385 4.1755 73.5093 14 5 1 2022-12-02T18:32:45.000000Z 2022-12-02T18:32:45.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919397 11919394 231 100 South Willow Avenue, Compton, CA, USA 2022-11-29 18:23:50 Severe Unknown CALIFORNIA - USD4 Million Worth Of Illegal Drugs Seized In Compton https://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton [foxla] CALIFORNIA - $4 million worth of illegal drugs seized in Compton "A search warrant at the home resulted in the seizure of about 5.5 lbs. of suspected tar heroin, 10 kilos of suspected powder cocaine, 6 kilos of suspected powder fentanyl, 6,000 suspected ecstasy pills containing fentanyl, and 254,000 suspected fentanyl pills all worth a combined estimated street value of $4.17 million, authorities said. " Read full article at: https://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton 33.896 -118.218 14 5 1 2022-12-02T18:29:25.000000Z 2022-12-02T18:29:25.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919394 11919392 166 Gwadar, Pakistan 2022-12-01 18:22:00 Severe Unknown PAKISTAN - Convoy Of Camels Loaded With Drugs Seized https://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/ [pakobserver.net] PAKISTAN - Convoy Of Camels Loaded With Drugs Seized "While searching the goods carried by the camels, ANF officials found them to be full of drugs (hashish). The drugs weighed around 1.4 tons." Read full article at: https://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/ 25.1313 62.325 14 5 1 2022-12-02T18:23:49.000000Z 2022-12-02T18:23:49.000000Z https://drugs.globalincidentmap.com/event_detail?id=11919392 Markdown for the above table was printed with print(mqcDf.loc[mqcDf.index[:5]].to_markdown())
BeautifulSoup find a href in marquee
I'm using bs4 to scrape links from a scrolling marquee. I'm able to get the marquee data, which is returned as a bs4 resultSet element. However, I cannot seem to access the href's within the data. I'm sure I'm missing something as I'm new to web scraping, and appreciate any guidance anyone has. Note: I can get the links easy peasy with selenium and chrome driver, but it takes forever. This returns all of the marquee data: url = 'https://drugs.globalincidentmap.com/' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') marquee = soup.select('div', class_='h-48') print(marquee) However when I try to drill down further into the data, I get the empty list or NoneType/KeyError or AttributeError. for a in marquee.find_all('a', href=True): link = a.find('div', class_=':nth-child') or for a in marquee.find_all('a', href=True): link = a.find('div', class_='flex p-2') Links in marquee
[ "\nI can get the links easy peasy with selenium and chrome driver\n\nProbably because the div with h-48 class is loaded with JavaScript; even if it wasn't, I don't think soup.find('div', class_='h-48') would work because that element has more classes, and you need to pass all of them as class_ [and I don't think soup.select('div', class_='h-48') gives the exact results you expect it to - select isn't really supposed to have a class_ argument - just a CSS selector string].\nsoup.find('div', attrs={'class':'h-48'}) or soup.select('div.h-48') can be expected to work on the html that is formed after JS loading, but you need selenium to get that...\n\n\nFortunately, I think the data you want is already in the fetched html, just in a different format - you can extract a list of dictionaries (mqCont) with\n# import json\n\nmarq = soup.find('marquee', attrs={'class':'h-48'})\nif marq is None: print('Could Not Find marquee.h-48')\nif not marq.get(':contents'): print('marquee.h-48 has no [:contents] attr')\n\ntry: mqCont = json.loads(marq.get(':contents', '[]'))\nexcept Exception as e:\n mqCont = []\n print('failed to parse marquee.h-48[:contents] <---', e)\n\nor, more shortly (if you're confident there won't be any error to debug/breakdown):\nmqCont = json.loads(soup.select_one('marquee.h-48').get(':contents', '[]'))\n\n\nYou can get a list of links to news articles with [m['url'] for m in mqCont if 'url' in m], but since you were trying to get find with class_='flex p-2', you probably want the .../event_detail?id=... links. You can form them as below\nevtUrls = [f\"{url.strip('/')}/event_detail?id={m['id']}\" for m in mqCont if 'id' in m]\n\n\nYou can also view the list of dictionaries as a table [with pandas] by doing something like:\n# import pandas\n\nomitKeys = ['domain_event_types', 'country']\nfor i, m in enumerate(mqCont):\n mDesc = ' '.join(w for w in BeautifulSoup(\n m['description'] if 'description' in m else ''\n ).get_text().split() if w)\n if mDesc: m['description'] = mDesc\n if 'id' in m: m['eventUrl'] = f\"{url.strip('/')}/event_detail?id={m['id']}\"\n mqCont[i] = {k:v for k, v in m.items() if k not in omitKeys}\n\nmqcDF = pandas.DataFrame(mqCont).dropna(axis='columns', how='all').set_index('id')\n\nand the first 5 rows [of 100 rows total] of mqcDF:\n\n\n\n\nid\ncountry_id\naddress\nevent_gmt_time\nseverity\ninfrastructure\ntip_text\nurl\ndescription\nlatitude\nlongitude\ncreated_user_id\nlocation_granularity_id\nis_approved\ncreated_at\nupdated_at\neventUrl\n\n\n\n\n11919404\n231\nPennsylvania, USA\n2022-12-01 18:36:53\nSevere\nUnknown\nPENNSYLVANIA - Photos - Suspects - Evidence In Multi-County Drug Bust\nhttps://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1\n[69 NEWS] PENNSYLVANIA - PHOTOS: Suspects, evidence in multi-county drug bust \"Authorities said they seized evidence that included 27.5 kilograms of cocaine with a potential street value of $2.7 million and 5.5 kilograms of fentanyl with a potential street value of $1.6 million.\" Read full article at: https://www.wfmz.com/news/area/berks/photos-suspects-evidence-in-multi-county-drug-bust/collection_bf795c98-71ad-11ed-99fe-4305f426699b.html#1\n41.2033\n-77.1945\n14\n8\n1\n2022-12-02T18:44:43.000000Z\n2022-12-02T18:44:43.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919404\n\n\n11919401\n40\nVancouver Island, British Columbia, Canada\n2022-12-01 18:33:01\nSevere\nUnknown\nCANADA - Drugs - Guns Seized As 4 BC Men With Hells Angels Ties Face Serious Charges\nhttps://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/\n[terracestandard.com] CANADA - Drugs, guns seized as 4 B.C. men with Hells Angels ties face ‘serious charges’ \"CFSEU said the seized drugs included 7.75kg of cocaine, 4kg of cannabis, 1.9kg of methamphetamine, 248 oxycodone pills, and more.\" Read full article at: https://www.terracestandard.com/news/alleged-drug-traffickers-on-vancouver-island-with-hells-angels-ties-face-serious-charges/\n49.6506\n-125.449\n14\n5\n1\n2022-12-02T18:36:37.000000Z\n2022-12-02T18:36:37.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919401\n\n\n11919397\n133\nMale, Maldives\n2022-11-20 18:29:26\nSevere\nUnknown\nMALDIVES - Drugs Worth Mvr 2 Mln Seized By Customs\nhttps://avas.mv/en/125385\n[avas.mv] MALDIVES - Drugs worth MVR 2 mln seized by Customs \"Maldives Customs Service has seized 1.34 kg of drugs smuggled into the Maldives via courier.\" Read full article at: https://avas.mv/en/125385\n4.1755\n73.5093\n14\n5\n1\n2022-12-02T18:32:45.000000Z\n2022-12-02T18:32:45.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919397\n\n\n11919394\n231\n100 South Willow Avenue, Compton, CA, USA\n2022-11-29 18:23:50\nSevere\nUnknown\nCALIFORNIA - USD4 Million Worth Of Illegal Drugs Seized In Compton\nhttps://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton\n[foxla] CALIFORNIA - $4 million worth of illegal drugs seized in Compton \"A search warrant at the home resulted in the seizure of about 5.5 lbs. of suspected tar heroin, 10 kilos of suspected powder cocaine, 6 kilos of suspected powder fentanyl, 6,000 suspected ecstasy pills containing fentanyl, and 254,000 suspected fentanyl pills all worth a combined estimated street value of $4.17 million, authorities said. \" Read full article at: https://www.foxla.com/news/4-million-worth-of-illegal-drugs-seized-in-compton\n33.896\n-118.218\n14\n5\n1\n2022-12-02T18:29:25.000000Z\n2022-12-02T18:29:25.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919394\n\n\n11919392\n166\nGwadar, Pakistan\n2022-12-01 18:22:00\nSevere\nUnknown\nPAKISTAN - Convoy Of Camels Loaded With Drugs Seized\nhttps://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/\n[pakobserver.net] PAKISTAN - Convoy Of Camels Loaded With Drugs Seized \"While searching the goods carried by the camels, ANF officials found them to be full of drugs (hashish). The drugs weighed around 1.4 tons.\" Read full article at: https://pakobserver.net/convoy-of-camels-loaded-with-drugs-seized/\n25.1313\n62.325\n14\n5\n1\n2022-12-02T18:23:49.000000Z\n2022-12-02T18:23:49.000000Z\nhttps://drugs.globalincidentmap.com/event_detail?id=11919392\n\n\n\n\nMarkdown for the above table was printed with print(mqcDf.loc[mqcDf.index[:5]].to_markdown())\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074661666_beautifulsoup_python_web_scraping.txt
Q: Why doesn't it work I'm trying to make a simple calculator def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = input("enter choice 1/2") a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == 1: print(a, "+", b, "=", add(a, b)) I don't know why it doesn't wanna add A: You need to convert the select variable to integer. By default, the input is taken as string value. You can also use f-string (see more at Formatted String Literals documentation) for printing values from variables in the print statement which gives you much more flexibility to format the string: def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = int(input("enter choice 1/2: ")) a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == 1: print(f"{a} + {b} = {add(a, b)}") Output: choose 1 to add and 2 to subtract enter choice 1/2: 1 enter 1st nunber: 21 enter 2nd number: 3 21.0 + 3.0 = 24.0 A: You need to convert select into an int def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = int(input("enter choice 1/2")) a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == 1: print(a, "+", b, "=", add(a, b)) A: input returns a string, but in the line if select == 1 you are comparing it to an int. There are several solutions to this, but the solution I would go with is to use only strings, i.e. if select == "1". 1 and 2 are arbitrary values, so it isn't really necessary for them to be converted to numbers. You could just as easily use a and b to accomplish the same goal. Another useful thing you can do is validate the user input. I would do that with something like this: while select not in ["1", "2"]: print(f"you entered {select}, which is not a valid option") select = input("enter choice 1/2") This will continue to ask the user to select one of the choices until they enter a valid one, and also has the added bonus of helping you catch errors in your code like the int vs str issue. A: As others mentioned, since input returns a str, it should be compared with an object of same type. Just changing 1 to str(1) on line 10 will solve the issue. def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = input("enter choice 1/2") a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == str(1): print(a, "+", b, "=", add(a, b))
Why doesn't it work I'm trying to make a simple calculator
def add(a, b): return a + b print("choose 1 to add and 2 to subtract") select = input("enter choice 1/2") a = float(input("enter 1st nunber: ")) b = float(input("enter 2nd number: ")) if select == 1: print(a, "+", b, "=", add(a, b)) I don't know why it doesn't wanna add
[ "You need to convert the select variable to integer. By default, the input is taken as string value. You can also use f-string (see more at Formatted String Literals documentation) for printing values from variables in the print statement which gives you much more flexibility to format the string:\ndef add(a, b):\n return a + b\n\n\nprint(\"choose 1 to add and 2 to subtract\")\nselect = int(input(\"enter choice 1/2: \"))\na = float(input(\"enter 1st nunber: \"))\nb = float(input(\"enter 2nd number: \"))\nif select == 1:\n print(f\"{a} + {b} = {add(a, b)}\")\n\nOutput:\nchoose 1 to add and 2 to subtract\nenter choice 1/2: 1\nenter 1st nunber: 21\nenter 2nd number: 3\n21.0 + 3.0 = 24.0\n\n", "You need to convert select into an int\ndef add(a, b):\n return a + b\n\nprint(\"choose 1 to add and 2 to subtract\")\nselect = int(input(\"enter choice 1/2\"))\n\na = float(input(\"enter 1st nunber: \"))\nb = float(input(\"enter 2nd number: \"))\n\nif select == 1:\n print(a, \"+\", b, \"=\", add(a, b))\n\n", "input returns a string, but in the line if select == 1 you are comparing it to an int. There are several solutions to this, but the solution I would go with is to use only strings, i.e. if select == \"1\". 1 and 2 are arbitrary values, so it isn't really necessary for them to be converted to numbers. You could just as easily use a and b to accomplish the same goal.\nAnother useful thing you can do is validate the user input. I would do that with something like this:\nwhile select not in [\"1\", \"2\"]:\n print(f\"you entered {select}, which is not a valid option\")\n select = input(\"enter choice 1/2\")\n\nThis will continue to ask the user to select one of the choices until they enter a valid one, and also has the added bonus of helping you catch errors in your code like the int vs str issue.\n", "As others mentioned, since input returns a str, it should be compared with an object of same type. Just changing 1 to str(1) on line 10 will solve the issue.\ndef add(a, b):\n return a + b\n\nprint(\"choose 1 to add and 2 to subtract\")\nselect = input(\"enter choice 1/2\")\n\na = float(input(\"enter 1st nunber: \"))\nb = float(input(\"enter 2nd number: \"))\n\nif select == str(1):\n print(a, \"+\", b, \"=\", add(a, b))\n\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "calculator", "python", "python_3.x" ]
stackoverflow_0074662980_calculator_python_python_3.x.txt
Q: By-pass 'Select a Certificate' prompt in Chrome using Selenium (Python) When going to a specific site and logging in, it then requires me (through a prompt which I can't access the web elements of) to validate it using a specific certificate to authenticate myself. The certificate itself already appears to be loaded but the issue is just submitting / clicking the "Ok" response. So, I've tried looking online and there does appear to be answers but they conflict with me. I'm running Chrome in headless mode which doesn't allow me to use the autoit or pyautogui libs. I have the certificate itself in my Keychain and also within my VSCode but not sure how I'd supply that to my driver to perhaps get rid of that prompt. Here's a portion of my code: def webdriverSetup(): chrome_options = Options() #chrome_options.add_argument('--headless') chrome_options.add_argument("--window-size=1920,1080") chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument('--allow-running-insecure-content') chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(options=chrome_options) return driver Here's the prompt I'm referring to: Note: Some of the other answers found are exclusive to Windows. Would appreciate a Mac or "mixed" solution for the time being, thanks. A: I would suggest trying Following : from selenium.webdriver.chrome.options import Options as ChromeOptions chrome_options = ChromeOptions() chrome_options.add_experimental_option( 'prefs', { 'required_client_certificate_for_user': <Path_to_certificate> } ) I got the prefs list from here https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/pref_names.cc following is the list of prefs which can be tried :- "required_client_certificate_for_user" and "required_client_certificate_for_device" A: Selenium doesn't support certificate authentication natively, but you can use the Selenium WebDriver to download the certificate and then use the Selenium WebDriver to import the certificate into your browser.
By-pass 'Select a Certificate' prompt in Chrome using Selenium (Python)
When going to a specific site and logging in, it then requires me (through a prompt which I can't access the web elements of) to validate it using a specific certificate to authenticate myself. The certificate itself already appears to be loaded but the issue is just submitting / clicking the "Ok" response. So, I've tried looking online and there does appear to be answers but they conflict with me. I'm running Chrome in headless mode which doesn't allow me to use the autoit or pyautogui libs. I have the certificate itself in my Keychain and also within my VSCode but not sure how I'd supply that to my driver to perhaps get rid of that prompt. Here's a portion of my code: def webdriverSetup(): chrome_options = Options() #chrome_options.add_argument('--headless') chrome_options.add_argument("--window-size=1920,1080") chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument('--allow-running-insecure-content') chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(options=chrome_options) return driver Here's the prompt I'm referring to: Note: Some of the other answers found are exclusive to Windows. Would appreciate a Mac or "mixed" solution for the time being, thanks.
[ "I would suggest trying Following :\nfrom selenium.webdriver.chrome.options import Options as ChromeOptions\n\n chrome_options = ChromeOptions()\n chrome_options.add_experimental_option(\n 'prefs', {\n 'required_client_certificate_for_user': <Path_to_certificate>\n }\n )\n\nI got the prefs list from here https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/pref_names.cc following is the list of prefs which can be tried :-\n\"required_client_certificate_for_user\" and \"required_client_certificate_for_device\"\n", "Selenium doesn't support certificate authentication natively, but you can use the Selenium WebDriver to download the certificate and then use the Selenium WebDriver to import the certificate into your browser.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "webdriver" ]
stackoverflow_0074587029_python_selenium_selenium_chromedriver_selenium_webdriver_webdriver.txt
Q: Python- Read values from CSV file and add columns values to REST API iteration calls I'm new to python, I'm reading csv file having 2 columns as ID and Filepath (headers not present). Trying to enter the ID into the URL and filepath into the below rest api call. Can't get the values of the row. If the value at row[0] is TDEVOPS-1 it's returning numeric value. import csv filename1 = 'E:\\Upload-PM\\attachment.csv' with open(filename1, 'rb') as csvfile: datareader = csv.reader(csvfile) for row in csvfile.readlines(): urlvalue = "https://<url>.atlassian.com/rest/api/3/issue/" + str({row[0]}) + "/attachments" url = urlvalue print(url) headers = {"X-Atlassian-Token": "nocheck"} files = {'file': open(row[1], 'rb')} r = requests.post(url, auth=('<email>','<token>'), files=files, headers=headers) print(r.status_code) print(r.text) Input: TDEVOPST-5,E:\Upload-PM\att.csv TDEVOPST-2,E:\Upload-PM\att2.csv TDEVOPST-3,E:\Upload-PM\att3.csv Error: A: It is not clear to me what is the exact error you are getting. But did you try using format? urlvalue = "https://<url>.atlassian.com/rest/api/3/issue/{}/attachments".format(row[0]) UPDATE - corresponding to the comments, the issue seems to be with how you read the csv file. Id recommend to use the “r” flag for better string parsing. See - Difference between parsing a text file in r and rb mode for more details In addition I'd suggest to use python os.path to make sure the path is valid A: If your file has not header then try to read it as symply .txt file: attachment = ["TDEVOPST-5,E:\\Upload-PM\\att.csv","TDEVOPST-2,E:\\Upload-PM\\att2.csv","TDEVOPST-3,E:\\Upload-PM\\att3.csv"] fn = "temp.txt" with open(fn, "w") as f: f.write("\n".join(attachment)) with open(fn,"r") as f: for row in f: print(row.replace("\n","")) # optional string for test els = row.split(",") print(els[0],"->",els[1]) # optional string for test Then you can use: els[0],els[1] as you need. May be like this: urlvalue = f"https://<url>.atlassian.com/rest/api/3/issue/{els[0]}/attachments"
Python- Read values from CSV file and add columns values to REST API iteration calls
I'm new to python, I'm reading csv file having 2 columns as ID and Filepath (headers not present). Trying to enter the ID into the URL and filepath into the below rest api call. Can't get the values of the row. If the value at row[0] is TDEVOPS-1 it's returning numeric value. import csv filename1 = 'E:\\Upload-PM\\attachment.csv' with open(filename1, 'rb') as csvfile: datareader = csv.reader(csvfile) for row in csvfile.readlines(): urlvalue = "https://<url>.atlassian.com/rest/api/3/issue/" + str({row[0]}) + "/attachments" url = urlvalue print(url) headers = {"X-Atlassian-Token": "nocheck"} files = {'file': open(row[1], 'rb')} r = requests.post(url, auth=('<email>','<token>'), files=files, headers=headers) print(r.status_code) print(r.text) Input: TDEVOPST-5,E:\Upload-PM\att.csv TDEVOPST-2,E:\Upload-PM\att2.csv TDEVOPST-3,E:\Upload-PM\att3.csv Error:
[ "It is not clear to me what is the exact error you are getting. But did you try using format?\nurlvalue = \"https://<url>.atlassian.com/rest/api/3/issue/{}/attachments\".format(row[0])\n\nUPDATE - corresponding to the comments, the issue seems to be with how you read the csv file. Id recommend to use the “r” flag for better string parsing. See - Difference between parsing a text file in r and rb mode for more details\nIn addition I'd suggest to use python os.path to make sure the path is valid\n", "If your file has not header then try to read it as symply .txt file:\nattachment = [\"TDEVOPST-5,E:\\\\Upload-PM\\\\att.csv\",\"TDEVOPST-2,E:\\\\Upload-PM\\\\att2.csv\",\"TDEVOPST-3,E:\\\\Upload-PM\\\\att3.csv\"]\n\nfn = \"temp.txt\"\nwith open(fn, \"w\") as f:\n f.write(\"\\n\".join(attachment))\n\nwith open(fn,\"r\") as f:\n for row in f:\n print(row.replace(\"\\n\",\"\")) # optional string for test\n els = row.split(\",\")\n print(els[0],\"->\",els[1]) # optional string for test\n\nThen you can use: els[0],els[1] as you need. May be like this:\nurlvalue = f\"https://<url>.atlassian.com/rest/api/3/issue/{els[0]}/attachments\"\n\n" ]
[ 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074658350_csv_python.txt
Q: Results called before closing connection are not showing / error: sqlite3.ProgrammingError: Cannot operate on a closed database The following code is throwing the error 'sqlite3.ProgrammingError: Cannot operate on a closed database.' Considering that I close the connection after the queries are done, I don't understand why this is happening. import sqlite3 def database(): connection = sqlite3.connect('database.db') connection.row_factory = sqlite3.Row return connection def _index(): connection = database() posts = connection.execute('SELECT P.title, P.content, P.created, U.username FROM posts P JOIN users U ON P.author_id = U.id').fetchall() users = connection.execute('SELECT U.fullname as "username", C.fullname as "committeename" FROM users U JOIN committees C ON U.committee_id = C.id') connection.close() I was trying to query the users database and posts database (2 queries) and then close the connection but an error is happening that doesn't let me do this.
Results called before closing connection are not showing / error: sqlite3.ProgrammingError: Cannot operate on a closed database
The following code is throwing the error 'sqlite3.ProgrammingError: Cannot operate on a closed database.' Considering that I close the connection after the queries are done, I don't understand why this is happening. import sqlite3 def database(): connection = sqlite3.connect('database.db') connection.row_factory = sqlite3.Row return connection def _index(): connection = database() posts = connection.execute('SELECT P.title, P.content, P.created, U.username FROM posts P JOIN users U ON P.author_id = U.id').fetchall() users = connection.execute('SELECT U.fullname as "username", C.fullname as "committeename" FROM users U JOIN committees C ON U.committee_id = C.id') connection.close() I was trying to query the users database and posts database (2 queries) and then close the connection but an error is happening that doesn't let me do this.
[]
[]
[ "The issue was that i had not added a .fetchall() clause at the end of the query.\nCorrected code:\nimport sqlite3\n\ndef database():\n connection = sqlite3.connect('database.db')\n connection.row_factory = sqlite3.Row\n return connection\n\ndef _index():\n connection = database()\n posts = connection.execute('SELECT P.title, P.content, P.created, U.username FROM posts P JOIN users U ON P.author_id = U.id').fetchall()\n users = connection.execute('SELECT U.fullname as \"username\", C.fullname as \"committeename\" FROM users U JOIN committees C ON U.committee_id = C.id')\n connection.close()\n\n" ]
[ -1 ]
[ "python", "sqlite" ]
stackoverflow_0074662203_python_sqlite.txt
Q: Python PIL 0.5 opacity, transparency, alpha Is there any way to make an image half transparent? the pseudo code is something like this: from PIL import Image image = Image.open('image.png') image = alpha(image, 0.5) I googled it for a couple of hours but I can't find anything useful. A: I realize this question is really old, but with the current version of Pillow (v4.2.1), there is a function called putalpha. It seems to work fine for me. I don't know if will work for every situation where you need to change the alpha, but it does work. It sets the alpha value for every pixel in the image. It seems, though that you can use a mask: http://www.leancrew.com/all-this/2013/11/transparency-with-pil/. Use putalpha like this: from PIL import Image img = Image.open(image) img.putalpha(127) # Half alpha; alpha argument must be an int img.save(dest) A: Could you do something like this? from PIL import Image image = Image.open('image.png') #open image image = image.convert("RGBA") #convert to RGBA rgb = image.getpixel(x,y) #Get the rgba value at coordinates x,y rgb[3] = int(rgb[3] / 2) or you could do rgb[3] = 50 maybe? #set alpha to half somehow image.putpixel((x,y), rgb) #put back the modified reba values at same pixel coordinates Definitely not the most efficient way of doing things but it might work. I wrote the code in browser so it might not be error free but hopefully it can give you an idea. EDIT: Just noticed how old this question was. Leaving answer anyways for future help. :) A: I put together Pecan's answer and cr333's question from this question: Using PIL to make all white pixels transparent? ... and came up with this: from PIL import Image opacity_level = 170 # Opaque is 255, input between 0-255 img = Image.open('img1.png') img = img.convert("RGBA") datas = img.getdata() newData = [] for item in datas: newData.append((0, 0, 0, opacity_level)) else: newData.append(item) img.putdata(newData) img.save("img2.png", "PNG") In my case, I have text with black background and wanted only the background semi-transparent, in which case: from PIL import Image opacity_level = 170 # Opaque is 255, input between 0-255 img = Image.open('img1.png') img = img.convert("RGBA") datas = img.getdata() newData = [] for item in datas: if item[0] == 0 and item[1] == 0 and item[2] == 0: newData.append((0, 0, 0, opacity_level)) else: newData.append(item) img.putdata(newData) img.save("img2.png", "PNG") A: I had an issue, where black boxes were appearing around my image when applying putalpha(). This workaround (applying alpha in a copied layer) solved it for me. from PIL import Image with Image.open("file.png") as im: im2 = im.copy() im2.putalpha(180) im.paste(im2, im) im.save("file2.png") Explanation: Like I said, putalpha modifies all pixels by setting their alpha value, so fully transparent pixels become only partially transparent. The code I posted above first sets (putalpha) all pixels to semi-transparent in a copy, then copies (paste) all pixels to the original image using the original alpha values as a mask. This means that fully transparent pixels in the original image are skipped during the paste. Credit: https://github.com/nulano @ https://github.com/python-pillow/Pillow/issues/4687#issuecomment-643567573 A: I just did this by myself...even though my code maybe a little bit weird...But it works fine. So I share it here. Hopes it could help anybody. =) The idea: To transparent a pic means lower alpha which is the 4th element in the tuple. my frame code: from PIL import Image img=open(image) img=img.convert('RGBA') #you can make sure your pic is in the right mode by check img.mode data=img.getdata() #you'll get a list of tuples newData=[] for a in data: a=a[:3] #you'll get your tuple shorten to RGB a=a+(100,) #change the 100 to any transparency number you like between (0,255) newData.append(a) img.putdata(newData) #you'll get your new img ready img.save(filename.filetype) I didn't find the right command to fulfil this job automatically, so I write this by myself. Hopes it'll help again. XD A: This method helps to reduce opacity of logo with transparency before pasting it over image # pip install Pillow # PIL.__version__ is 9.3.0 from PIL import Image, ImageEnhance im = Image.open('logo.png').convert('RGBA') alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(.5) im.putalpha(alpha)
Python PIL 0.5 opacity, transparency, alpha
Is there any way to make an image half transparent? the pseudo code is something like this: from PIL import Image image = Image.open('image.png') image = alpha(image, 0.5) I googled it for a couple of hours but I can't find anything useful.
[ "I realize this question is really old, but with the current version of Pillow (v4.2.1), there is a function called putalpha. It seems to work fine for me. I don't know if will work for every situation where you need to change the alpha, but it does work. It sets the alpha value for every pixel in the image. It seems, though that you can use a mask: http://www.leancrew.com/all-this/2013/11/transparency-with-pil/.\nUse putalpha like this:\nfrom PIL import Image\nimg = Image.open(image)\nimg.putalpha(127) # Half alpha; alpha argument must be an int\nimg.save(dest)\n\n", "Could you do something like this?\nfrom PIL import Image\nimage = Image.open('image.png') #open image\nimage = image.convert(\"RGBA\") #convert to RGBA\nrgb = image.getpixel(x,y) #Get the rgba value at coordinates x,y\nrgb[3] = int(rgb[3] / 2) or you could do rgb[3] = 50 maybe? #set alpha to half somehow\nimage.putpixel((x,y), rgb) #put back the modified reba values at same pixel coordinates\n\nDefinitely not the most efficient way of doing things but it might work. I wrote the code in browser so it might not be error free but hopefully it can give you an idea.\nEDIT: Just noticed how old this question was. Leaving answer anyways for future help. :)\n", "I put together Pecan's answer and cr333's question from this question:\nUsing PIL to make all white pixels transparent?\n... and came up with this:\nfrom PIL import Image\n\nopacity_level = 170 # Opaque is 255, input between 0-255\n\nimg = Image.open('img1.png')\nimg = img.convert(\"RGBA\")\ndatas = img.getdata()\n\nnewData = []\nfor item in datas:\n newData.append((0, 0, 0, opacity_level))\nelse:\n newData.append(item)\n\nimg.putdata(newData)\nimg.save(\"img2.png\", \"PNG\")\n\nIn my case, I have text with black background and wanted only the background semi-transparent, in which case:\nfrom PIL import Image\n\nopacity_level = 170 # Opaque is 255, input between 0-255\n\nimg = Image.open('img1.png')\nimg = img.convert(\"RGBA\")\ndatas = img.getdata()\n\nnewData = []\nfor item in datas:\n if item[0] == 0 and item[1] == 0 and item[2] == 0:\n newData.append((0, 0, 0, opacity_level))\n else:\n newData.append(item)\n\nimg.putdata(newData)\nimg.save(\"img2.png\", \"PNG\")\n\n", "I had an issue, where black boxes were appearing around my image when applying putalpha().\nThis workaround (applying alpha in a copied layer) solved it for me.\nfrom PIL import Image\nwith Image.open(\"file.png\") as im:\n im2 = im.copy()\n im2.putalpha(180)\n im.paste(im2, im)\n im.save(\"file2.png\")\n\nExplanation:\n\nLike I said, putalpha modifies all pixels by setting their alpha value, so fully transparent pixels become only partially transparent. The code I posted above first sets (putalpha) all pixels to semi-transparent in a copy, then copies (paste) all pixels to the original image using the original alpha values as a mask. This means that fully transparent pixels in the original image are skipped during the paste.\n\nCredit: https://github.com/nulano @ https://github.com/python-pillow/Pillow/issues/4687#issuecomment-643567573\n\n\n", "I just did this by myself...even though my code maybe a little bit weird...But it works fine. So I share it here. Hopes it could help anybody. =)\nThe idea: To transparent a pic means lower alpha which is the 4th element in the tuple.\nmy frame code:\nfrom PIL import Image \nimg=open(image)\nimg=img.convert('RGBA') #you can make sure your pic is in the right mode by check img.mode\ndata=img.getdata() #you'll get a list of tuples\nnewData=[]\nfor a in data:\n a=a[:3] #you'll get your tuple shorten to RGB\n a=a+(100,) #change the 100 to any transparency number you like between (0,255)\n newData.append(a)\nimg.putdata(newData) #you'll get your new img ready\nimg.save(filename.filetype)\n\nI didn't find the right command to fulfil this job automatically, so I write this by myself. Hopes it'll help again. XD\n", "This method helps to reduce opacity of logo with transparency before pasting it over image\n# pip install Pillow\n# PIL.__version__ is 9.3.0\n\nfrom PIL import Image, ImageEnhance\n\nim = Image.open('logo.png').convert('RGBA')\nalpha = im.split()[3]\nalpha = ImageEnhance.Brightness(alpha).enhance(.5)\nim.putalpha(alpha)\n\n" ]
[ 25, 4, 2, 1, 0, 0 ]
[]
[]
[ "alpha", "opacity", "python", "python_imaging_library", "transparency" ]
stackoverflow_0024731035_alpha_opacity_python_python_imaging_library_transparency.txt
Q: how to run loader on successful form submission only? I want that the loader should start ONLY and ONLY when the form has been successfully submitted (instead of just the onclick submit button event that the code does currently). How can I do so? <div id="loader" class= "lds-dual-ring hidden overlay" > <div class="lds-dual-ring hidden overlay"> </div> <div class="loadcontent"><div><strong>Working on your request...it may take up to 2 minutes.</strong></div></div> </div> Code below is the part where loader kicks upon submit button event. $('#submitBtn').click(function () { $('#loader').removeClass('hidden') // $('#loader').html('Loading').addClass('loadcontent') // $("#loading").html("Loading"); }) </script> Code below is one of the form fields that takes a value from user: <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'Port' %} {% render_field field class="rowforinput marginforfields form-control" style="height: 23px; margin-left: 0; margin-right: 0" title=" For eg. 1/1/48 or 2/1/16" pattern="^[12]/1/(?:[1-3]\d|4[0-8]|[1-9])$" required=true %} {% endifequal %} </div> </div> A: To show the loader when the AJAX call is successful, you can move the code that shows the loader from the click event handler for the submit button to the success callback function in the AJAX call. Here is an example of how you can modify your code to do this: $('#submitBtn').click(function () { // Submit the form using AJAX $.ajax({ url: $(this).attr('action'), // The URL to submit the form to type: $(this).attr('method'), // The method to use when submitting the form data: $(this).serialize(), // The data to submit with the form success: function (response) { // Show the loader $('#loader').removeClass('hidden'); // Handle the successful submission of the form here // For example, you can display a success message }, error: function (error) { // Handle any errors that occurred when submitting the form here // For example, you can display an error message } }); }); This code moves the code that shows the loader from the click event handler for the submit button to the success callback function in the AJAX call. As a result, the loader will only be shown when the AJAX call is successful and the success callback function is called. Note that this code assumes that the form has a method attribute and an action attribute that specify the method and URL to submit the form to, respectively. You may need to adjust these values depending on your specific form and setup.
how to run loader on successful form submission only?
I want that the loader should start ONLY and ONLY when the form has been successfully submitted (instead of just the onclick submit button event that the code does currently). How can I do so? <div id="loader" class= "lds-dual-ring hidden overlay" > <div class="lds-dual-ring hidden overlay"> </div> <div class="loadcontent"><div><strong>Working on your request...it may take up to 2 minutes.</strong></div></div> </div> Code below is the part where loader kicks upon submit button event. $('#submitBtn').click(function () { $('#loader').removeClass('hidden') // $('#loader').html('Loading').addClass('loadcontent') // $("#loading").html("Loading"); }) </script> Code below is one of the form fields that takes a value from user: <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'Port' %} {% render_field field class="rowforinput marginforfields form-control" style="height: 23px; margin-left: 0; margin-right: 0" title=" For eg. 1/1/48 or 2/1/16" pattern="^[12]/1/(?:[1-3]\d|4[0-8]|[1-9])$" required=true %} {% endifequal %} </div> </div>
[ "To show the loader when the AJAX call is successful, you can move the code that shows the loader from the click event handler for the submit button to the success callback function in the AJAX call. Here is an example of how you can modify your code to do this:\n$('#submitBtn').click(function () {\n // Submit the form using AJAX\n $.ajax({\n url: $(this).attr('action'), // The URL to submit the form to\n type: $(this).attr('method'), // The method to use when submitting the form\n data: $(this).serialize(), // The data to submit with the form\n success: function (response) {\n // Show the loader\n $('#loader').removeClass('hidden');\n\n // Handle the successful submission of the form here\n // For example, you can display a success message\n },\n error: function (error) {\n // Handle any errors that occurred when submitting the form here\n // For example, you can display an error message\n }\n });\n});\n\nThis code moves the code that shows the loader from the click event handler for the submit button to the success callback function in the AJAX call. As a result, the loader will only be shown when the AJAX call is successful and the success callback function is called.\nNote that this code assumes that the form has a method attribute and an action attribute that specify the method and URL to submit the form to, respectively. You may need to adjust these values depending on your specific form and setup.\n" ]
[ 0 ]
[]
[]
[ "django", "flask", "html", "javascript", "python" ]
stackoverflow_0074662942_django_flask_html_javascript_python.txt
Q: 'numpy.ndarray' object has no attribute 'xaxis' - not sure why I have the following code. I am trying to loop through a dataframe 'out' and create a separate subplot for each group and level. There are 35 groups and 5 levels, producing 175 plots in total. I thus want to create 5 figures each with 35 subplots (7 rows and 5 columns). However, when I try to assign specific plots to different axes, I get the error: 'numpy.ndarray' object has no attribute 'xaxis' I would be so grateful for a helping hand! I have attached some example data below. for j in range(0,len(individualoutliers)): fig = plt.figure(figsize=(50,50)) fig,axes = plt.subplots(7,5) for i in range(0,len(individualoutliers[j])): individualoutliersnew = individualoutliers[j] out = individualoutliersnew.loc[:, ["newID", "x", "y","level"]].apply(lambda x: pd.Series(x).explode()) for k,g in out.groupby("newID"): globals()['interestingvariable'] = g newframe = interestingvariable sns.lineplot(data=newframe,x='x',y='y',ax=axes[i]) axes[i].set_xlabel('x-coordinate',labelpad = 40,fontsize=70,weight='bold') axes[i].set_ylabel('y-coordinate',labelpad = 40,fontsize=70,weight='bold') plt.xticks(weight='bold',fontsize=60,rotation = 30) plt.yticks(weight='bold',fontsize=60) title = (newframe.iloc[0,0]+' '+'level'+' '+str(newframe.iloc[i,3])) axes[i].set_title(title,fontsize=70,pad=40,weight='bold') dir_name = "/Users/macbook/Desktop/" plt.rcParams["savefig.directory"] = os.chdir(os.path.dirname(dir_name)) plt.savefig(newframe.iloc[0,0]+' '+'level'+' '+str(newframe.iloc[i,3])+'individualoutlierplot') plt.show() out.head(10) newID x y level 24 610020 55 60 1 24 610020 55 60 1 24 610020 55 60 1 24 610020 60 60 1 24 610020 60 65 1 24 610020 60 65 1 24 610020 65 70 1 24 610020 70 70 1 24 610020 70 75 1 24 610020 75 75 1 newframe.head(10) newID x y level 3313 5d254d 55 60 1 3313 5d254d 55 60 1 3313 5d254d 55 60 1 3313 5d254d 60 60 1 3313 5d254d 60 65 1 3313 5d254d 60 65 1 3313 5d254d 65 65 1 3313 5d254d 65 70 1 3313 5d254d 70 75 1 3313 5d254d 75 75 1 A: In fig,axes = plt.subplots(7,5), axes is a 2D array of axes (actually pairs of x, y axes). In sns.lineplot(data=newframe,x='x',y='y',ax=axes[i]) you are passing a 1D array axes[i], not a single axis (pair) as lineplot may expect.
'numpy.ndarray' object has no attribute 'xaxis' - not sure why
I have the following code. I am trying to loop through a dataframe 'out' and create a separate subplot for each group and level. There are 35 groups and 5 levels, producing 175 plots in total. I thus want to create 5 figures each with 35 subplots (7 rows and 5 columns). However, when I try to assign specific plots to different axes, I get the error: 'numpy.ndarray' object has no attribute 'xaxis' I would be so grateful for a helping hand! I have attached some example data below. for j in range(0,len(individualoutliers)): fig = plt.figure(figsize=(50,50)) fig,axes = plt.subplots(7,5) for i in range(0,len(individualoutliers[j])): individualoutliersnew = individualoutliers[j] out = individualoutliersnew.loc[:, ["newID", "x", "y","level"]].apply(lambda x: pd.Series(x).explode()) for k,g in out.groupby("newID"): globals()['interestingvariable'] = g newframe = interestingvariable sns.lineplot(data=newframe,x='x',y='y',ax=axes[i]) axes[i].set_xlabel('x-coordinate',labelpad = 40,fontsize=70,weight='bold') axes[i].set_ylabel('y-coordinate',labelpad = 40,fontsize=70,weight='bold') plt.xticks(weight='bold',fontsize=60,rotation = 30) plt.yticks(weight='bold',fontsize=60) title = (newframe.iloc[0,0]+' '+'level'+' '+str(newframe.iloc[i,3])) axes[i].set_title(title,fontsize=70,pad=40,weight='bold') dir_name = "/Users/macbook/Desktop/" plt.rcParams["savefig.directory"] = os.chdir(os.path.dirname(dir_name)) plt.savefig(newframe.iloc[0,0]+' '+'level'+' '+str(newframe.iloc[i,3])+'individualoutlierplot') plt.show() out.head(10) newID x y level 24 610020 55 60 1 24 610020 55 60 1 24 610020 55 60 1 24 610020 60 60 1 24 610020 60 65 1 24 610020 60 65 1 24 610020 65 70 1 24 610020 70 70 1 24 610020 70 75 1 24 610020 75 75 1 newframe.head(10) newID x y level 3313 5d254d 55 60 1 3313 5d254d 55 60 1 3313 5d254d 55 60 1 3313 5d254d 60 60 1 3313 5d254d 60 65 1 3313 5d254d 60 65 1 3313 5d254d 65 65 1 3313 5d254d 65 70 1 3313 5d254d 70 75 1 3313 5d254d 75 75 1
[ "In fig,axes = plt.subplots(7,5), axes is a 2D array of axes (actually pairs of x, y axes).\nIn sns.lineplot(data=newframe,x='x',y='y',ax=axes[i]) you are passing a 1D array axes[i], not a single axis (pair) as lineplot may expect.\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "loops", "matplotlib", "pandas", "python" ]
stackoverflow_0074659542_jupyter_notebook_loops_matplotlib_pandas_python.txt
Q: d.py number of bans in a guild So I tried using embed.add_field(name="Ban Count", value=f"{len(await ctx.guild.bans())} Bans",inline=False) but I get this error object async_generator can't be used in 'await' expression How do I display the amount of bans? A: You must first convert the bans into a list, then get the length of the list: bans_list = [entry async for entry in ctx.guild.bans()] number_of_bans = len(bans_list) # output number of bans, etc...
d.py number of bans in a guild
So I tried using embed.add_field(name="Ban Count", value=f"{len(await ctx.guild.bans())} Bans",inline=False) but I get this error object async_generator can't be used in 'await' expression How do I display the amount of bans?
[ "You must first convert the bans into a list, then get the length of the list:\nbans_list = [entry async for entry in ctx.guild.bans()]\nnumber_of_bans = len(bans_list)\n\n# output number of bans, etc...\n\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074663211_discord_discord.py_python.txt
Q: Python program not working - simple mathematic function cat Prog4CCM.py numberArray = [] count = 0 #filename = input("Please enter the file name: ") filename = "t.txt" # for testing purposes file = open(filename, "r") for each_line in file: numberArray.append(each_line) for i in numberArray: print(i) count = count + 1 def findMaxValue(numberArray, count): maxval = numberArray[0] for i in range(0, count): if numberArray[i] > maxval: maxval = numberArray[i] return maxval def findMinValue(numberArray, count): minval = numberArray[0] for i in range(0, count): if numberArray[i] < minval: minval = numberArray[i] return minval def findFirstOccurence(numberArray, vtf, count): for i in range(0, count): if numberArray[i] == vtf: return i break i = i + 1 # Function calls start print("The maxiumum value in the file is "+ str(findMaxValue(numberArray, count))) print("The minimum value in the file is "+str(findMinValue(numberArray, count))) vtf = input("Please insert the number you would like to find the first occurence of: ") print("First occurence is at "+str(findFirstOccurence(numberArray, vtf, count))) This is supposed to call a function (Find First Occurrence) and check for the first occurrence in my array. It should return a proper value, but just returns "None". Why might this be? The file reading, and max and min value all seem to work perfectly. A: At a quick glance, the function findFirstOccurence miss return statement. If you want us to help you debug the code in detail, you may need to provide your test data, like t.txt A: You forgot to add a return in the findFirstOccurence() function, in case the vtf response is not in the list and there is an error with adding one to the iterator and use break, the for loop will do that for you. The correct code would look like this: ... def findFirstOccurence(numberArray, vtf, count): for i in range(0, count): if numberArray[i] == vtf: return i # break # <== # i = i + 1 # It's errors return "Can't find =(" # Function calls start print("The maxiumum value in the file is "+ str(findMaxValue(numberArray, count))) print("The minimum value in the file is "+str(findMinValue(numberArray, count))) vtf = input("Please insert the number you would like to find the first occurence of: ") print("First occurence is at "+str(findFirstOccurence(numberArray, vtf, count)))
Python program not working - simple mathematic function
cat Prog4CCM.py numberArray = [] count = 0 #filename = input("Please enter the file name: ") filename = "t.txt" # for testing purposes file = open(filename, "r") for each_line in file: numberArray.append(each_line) for i in numberArray: print(i) count = count + 1 def findMaxValue(numberArray, count): maxval = numberArray[0] for i in range(0, count): if numberArray[i] > maxval: maxval = numberArray[i] return maxval def findMinValue(numberArray, count): minval = numberArray[0] for i in range(0, count): if numberArray[i] < minval: minval = numberArray[i] return minval def findFirstOccurence(numberArray, vtf, count): for i in range(0, count): if numberArray[i] == vtf: return i break i = i + 1 # Function calls start print("The maxiumum value in the file is "+ str(findMaxValue(numberArray, count))) print("The minimum value in the file is "+str(findMinValue(numberArray, count))) vtf = input("Please insert the number you would like to find the first occurence of: ") print("First occurence is at "+str(findFirstOccurence(numberArray, vtf, count))) This is supposed to call a function (Find First Occurrence) and check for the first occurrence in my array. It should return a proper value, but just returns "None". Why might this be? The file reading, and max and min value all seem to work perfectly.
[ "At a quick glance, the function findFirstOccurence miss return statement. If you want us to help you debug the code in detail, you may need to provide your test data, like t.txt\n", "You forgot to add a return in the findFirstOccurence() function, in case the vtf response is not in the list and there is an error with adding one to the iterator and use break, the for loop will do that for you.\nThe correct code would look like this:\n...\n\ndef findFirstOccurence(numberArray, vtf, count):\n for i in range(0, count):\n if numberArray[i] == vtf:\n return i\n # break # <==\n # i = i + 1 # It's errors\n return \"Can't find =(\"\n\n\n# Function calls start\n\n\nprint(\"The maxiumum value in the file is \"+ str(findMaxValue(numberArray, count)))\nprint(\"The minimum value in the file is \"+str(findMinValue(numberArray, count)))\n\nvtf = input(\"Please insert the number you would like to find the first occurence of: \")\nprint(\"First occurence is at \"+str(findFirstOccurence(numberArray, vtf, count)))\n\n" ]
[ 1, 1 ]
[]
[]
[ "algorithm", "python", "python_3.x" ]
stackoverflow_0074663165_algorithm_python_python_3.x.txt
Q: (matplot, 3d, plot_surface, Animation) How can I freez z axis from moving in the animaton I want to make an animation of a drum vibration in python. My problem is that the zero point of the z_axis keeps moving. How can I freeze the z_axis? video link fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) z=sol[0] def init(): surf,=ax.plot_surface(xv,yv,z0) ax.set_xlim(0,1) ax.set_ylim(0,1) #ax.set_zlim3d(-1,1) ax.set_zlim(-1,1) return surf def animate(i): u=add_boundry(z[i+1]) ax.clear() surf=ax.plot_surface(xv, yv, u) return surf anim = FuncAnimation(fig, animate,frames=200, interval=200, blit=False) anim.save('drum.gif', writer='ffmpeg') A: I find a solution. fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) z=sol[0] z0=add_boundry(z[0]) #surf=ax.plot_surface(np.empty_like(xv),np.empty_like(yv),np.empty_like(z0)) def init(): surf=ax.plot_surface(xv,yv,z0) ax.set_xlim(0,1) ax.set_ylim(0,1) ax.set_zlim(-0.2,0.2) ax._autoscaleZon = False return surf def animate(i): u=add_boundry(z[i+1]) ax.clear() surf=ax.plot_surface(xv, yv, u) ax.set_xlim(0,1) ax.set_ylim(0,1) ax.set_zlim(-0.2,0.2) ax._autoscaleZon = False return surf anim = FuncAnimation(fig, animate, init_func=init, frames=200, interval=200, blit=False) anim.save('drum.gif', writer='ffmpeg')
(matplot, 3d, plot_surface, Animation) How can I freez z axis from moving in the animaton
I want to make an animation of a drum vibration in python. My problem is that the zero point of the z_axis keeps moving. How can I freeze the z_axis? video link fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) z=sol[0] def init(): surf,=ax.plot_surface(xv,yv,z0) ax.set_xlim(0,1) ax.set_ylim(0,1) #ax.set_zlim3d(-1,1) ax.set_zlim(-1,1) return surf def animate(i): u=add_boundry(z[i+1]) ax.clear() surf=ax.plot_surface(xv, yv, u) return surf anim = FuncAnimation(fig, animate,frames=200, interval=200, blit=False) anim.save('drum.gif', writer='ffmpeg')
[ "I find a solution.\nfig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})\nz=sol[0]\nz0=add_boundry(z[0])\n#surf=ax.plot_surface(np.empty_like(xv),np.empty_like(yv),np.empty_like(z0))\n\ndef init():\n surf=ax.plot_surface(xv,yv,z0)\n ax.set_xlim(0,1)\n ax.set_ylim(0,1)\n ax.set_zlim(-0.2,0.2)\n ax._autoscaleZon = False\n return surf\ndef animate(i):\n u=add_boundry(z[i+1])\n ax.clear()\n surf=ax.plot_surface(xv, yv, u)\n ax.set_xlim(0,1)\n ax.set_ylim(0,1)\n ax.set_zlim(-0.2,0.2)\n ax._autoscaleZon = False\n return surf\n\n\n \nanim = FuncAnimation(fig, animate, init_func=init, frames=200, interval=200, blit=False)\n\n\nanim.save('drum.gif', writer='ffmpeg')\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "matplotlib_animation", "python" ]
stackoverflow_0074662936_matplotlib_matplotlib_animation_python.txt
Q: XGBoost Error when saving and loading xgboost model using Pickle, JSON and JobLib I have trained and saved an xgboost regressor model in Jupyter Notebook (Google Colab) and tried to load it in my local machine without success. I have tried to save and load the model in multiple formats: .pkl using pickle library, .sav using joblib library or .json. When I load the model in VS Code, I get the following error: raise XGBoostError(py_str(_LIB.XGBGetLastError())) xgboost.core.XGBoostError: [10:56:21] ../src/c_api/c_api.cc:846: Check failed: str[0] == '{' ( What is the problem here? A: The issue was a mismatch between the two versions of xgboost when saving the model in Google Colab (xgboost version 0.9) and loading the model in my local Python environment (xgboost version 1.5.1). I managed to solve the problem by upgrading my xgboost package to the latest version (xgboost version 1.7.1) both on Google Colab and on my local Python environment. I resaved the model and re-loaded it using the newly saved file. Now the loading works well without any errors. I will leave my post here on Stackoverflow just in case it may be useful for someone else.
XGBoost Error when saving and loading xgboost model using Pickle, JSON and JobLib
I have trained and saved an xgboost regressor model in Jupyter Notebook (Google Colab) and tried to load it in my local machine without success. I have tried to save and load the model in multiple formats: .pkl using pickle library, .sav using joblib library or .json. When I load the model in VS Code, I get the following error: raise XGBoostError(py_str(_LIB.XGBGetLastError())) xgboost.core.XGBoostError: [10:56:21] ../src/c_api/c_api.cc:846: Check failed: str[0] == '{' ( What is the problem here?
[ "The issue was a mismatch between the two versions of xgboost when saving the model in Google Colab (xgboost version 0.9) and loading the model in my local Python environment (xgboost version 1.5.1).\nI managed to solve the problem by upgrading my xgboost package to the latest version (xgboost version 1.7.1) both on Google Colab and on my local Python environment. I resaved the model and re-loaded it using the newly saved file.\nNow the loading works well without any errors.\nI will leave my post here on Stackoverflow just in case it may be useful for someone else.\n" ]
[ 0 ]
[]
[]
[ "data_science", "python", "visual_studio_code", "xgboost" ]
stackoverflow_0074662799_data_science_python_visual_studio_code_xgboost.txt
Q: Sagemaker Regex pattern matching In Sagemaker validation:auc metric monitor has the following regex .*\[[0-9]+\].*#011validation-auc:([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?).* that searches the logs and extracts the matching metrics. I have to log the metrics, so that, they can match the above regex. For this, I tried the following [2]#011validation-auc:+0.89 Actually I have a list of AUC values like [2]#011validation-auc: [+0.89, +0.90] to be logged. I can't modify the regex as it is predefined by the AWS Sagemaker. How do I format my log entries, so that, they can match the above regex? Thanks Raj. A: I assume you are using a SageMaker Training Job, if you are using the SageMaker SDK you can set metric_definitions in your Estimator object to set the metric's regex. Kindly see this link for more information: https://docs.aws.amazon.com/sagemaker/latest/dg/training-metrics.html#define-train-metrics
Sagemaker Regex pattern matching
In Sagemaker validation:auc metric monitor has the following regex .*\[[0-9]+\].*#011validation-auc:([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?).* that searches the logs and extracts the matching metrics. I have to log the metrics, so that, they can match the above regex. For this, I tried the following [2]#011validation-auc:+0.89 Actually I have a list of AUC values like [2]#011validation-auc: [+0.89, +0.90] to be logged. I can't modify the regex as it is predefined by the AWS Sagemaker. How do I format my log entries, so that, they can match the above regex? Thanks Raj.
[ "I assume you are using a SageMaker Training Job, if you are using the SageMaker SDK you can set metric_definitions in your Estimator object to set the metric's regex.\nKindly see this link for more information: https://docs.aws.amazon.com/sagemaker/latest/dg/training-metrics.html#define-train-metrics\n" ]
[ 0 ]
[]
[]
[ "amazon_sagemaker", "python", "regex" ]
stackoverflow_0074662448_amazon_sagemaker_python_regex.txt
Q: How to send specifically an IMAGE file from client to server using Python Paramiko So I want to send and IMAGE file from client to server using Python Paramiko. For example: .jpeg, .jpg, .png I don't get an error, but, it does print this message: Failure Here is example code: from PIL import ImageGrab import paramiko class Client: def __init__(self, hostname, username, password): self.hostname = hostname self.username = username self.password = password self.client = paramiko.SSHClient() def connect(self): self.client.load_system_host_keys() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client.connect(hostname=self.hostname, username=self.username, password=self.password, port=22) def close(self): self.client.close() ImageGrab.grab().save("screenshot.png") # Saves a screenshot client = Client("hostname", "username", "password") client.connect() sftp_client = client.client.open_sftp() sftp_client.put("screenshot.png", "/home") # Line that has the error The line that I believe is messed up is the last line. Feel free to run this code and test it. If you have any questions about this, go ahead and ask. If I did not include enough information, please say something. A: Based on the issue post on paramiko github repo, you need to specify the destination parameter to the file name instead of the directory name, such as sftp_client.put("screenshot.png", "/home/screenshot.png")
How to send specifically an IMAGE file from client to server using Python Paramiko
So I want to send and IMAGE file from client to server using Python Paramiko. For example: .jpeg, .jpg, .png I don't get an error, but, it does print this message: Failure Here is example code: from PIL import ImageGrab import paramiko class Client: def __init__(self, hostname, username, password): self.hostname = hostname self.username = username self.password = password self.client = paramiko.SSHClient() def connect(self): self.client.load_system_host_keys() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client.connect(hostname=self.hostname, username=self.username, password=self.password, port=22) def close(self): self.client.close() ImageGrab.grab().save("screenshot.png") # Saves a screenshot client = Client("hostname", "username", "password") client.connect() sftp_client = client.client.open_sftp() sftp_client.put("screenshot.png", "/home") # Line that has the error The line that I believe is messed up is the last line. Feel free to run this code and test it. If you have any questions about this, go ahead and ask. If I did not include enough information, please say something.
[ "Based on the issue post on paramiko github repo, you need to specify the destination parameter to the file name instead of the directory name, such as\nsftp_client.put(\"screenshot.png\", \"/home/screenshot.png\")\n" ]
[ 0 ]
[]
[]
[ "class", "function", "python", "python_3.x", "server" ]
stackoverflow_0074663210_class_function_python_python_3.x_server.txt
Q: How come a variable in a function is able to reference from outside it's scope? In this case, the "all_lines" variable is initalised in the context manager, and it is accessible from the function "part_1". total = 0 with open("advent_input.txt", "r") as txt: all_lines = [] context_total = 0 for line in txt: all_lines.append((line.rstrip().split(" "))) def part_1(): # total = 0 for line in all_lines: if line[0] == "A": if line[1] == "Y": total += 8 elif line[1] == "X": context_total += 4 However, "context_total", which is also initalised in the context manager, does not work in the function "part_1". And "total" from the global scope does not work either. How come "all_lines" works? A: Python does not have general block scope, so anything assigned within the with will be accessible outside of the block. context_total is different though since you're reassigning it within the function. If you assign within a function, the variable will be treated as a local unless you use global to specify otherwise. That's problematic here though since += necessarily must refer to an existing variable (or else what are you adding to?), but there is no local variable with that name. Add global context_total to use it within the function, or pass it in as an argument if you don't need the reassigned value externally. A: It works because inside the function, the all_lines variable is referenced but not assigned. The other two variables are assigned. If a variable is assigned inside a function, then that variable is treated as local throughout the function, even if there is a global variable of the same name.
How come a variable in a function is able to reference from outside it's scope?
In this case, the "all_lines" variable is initalised in the context manager, and it is accessible from the function "part_1". total = 0 with open("advent_input.txt", "r") as txt: all_lines = [] context_total = 0 for line in txt: all_lines.append((line.rstrip().split(" "))) def part_1(): # total = 0 for line in all_lines: if line[0] == "A": if line[1] == "Y": total += 8 elif line[1] == "X": context_total += 4 However, "context_total", which is also initalised in the context manager, does not work in the function "part_1". And "total" from the global scope does not work either. How come "all_lines" works?
[ "Python does not have general block scope, so anything assigned within the with will be accessible outside of the block.\ncontext_total is different though since you're reassigning it within the function. If you assign within a function, the variable will be treated as a local unless you use global to specify otherwise. That's problematic here though since += necessarily must refer to an existing variable (or else what are you adding to?), but there is no local variable with that name.\nAdd global context_total to use it within the function, or pass it in as an argument if you don't need the reassigned value externally.\n", "It works because inside the function, the all_lines variable is referenced but not assigned. The other two variables are assigned.\nIf a variable is assigned inside a function, then that variable is treated as local throughout the function, even if there is a global variable of the same name.\n" ]
[ 1, 0 ]
[]
[]
[ "function", "python", "scope" ]
stackoverflow_0074663272_function_python_scope.txt
Q: How do I close a full-screen matplotlib figure? How may I close a full-screen matplotlib window? I spawned the figure using: plt.ion() fig = plt.figure('Optimizer') plt.tight_layout() mng = plt.get_current_fig_manager() mng.full_screen_toggle() However, plt.close("all") does not seem to do anything, and I couldn't find many things online to try that are relevant to full-screen figures. Seems like the behavior of closing figures differs for full-screen plots? I have to manually kill -9 the entire script for it to close. (Running on a Raspberry Pi if that matters) A: Alt F4 does the trick for me (Ubuntu / Windows). But I have not tried it on a Pi.
How do I close a full-screen matplotlib figure?
How may I close a full-screen matplotlib window? I spawned the figure using: plt.ion() fig = plt.figure('Optimizer') plt.tight_layout() mng = plt.get_current_fig_manager() mng.full_screen_toggle() However, plt.close("all") does not seem to do anything, and I couldn't find many things online to try that are relevant to full-screen figures. Seems like the behavior of closing figures differs for full-screen plots? I have to manually kill -9 the entire script for it to close. (Running on a Raspberry Pi if that matters)
[ "Alt F4 does the trick for me (Ubuntu / Windows). But I have not tried it on a Pi.\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0070239693_matplotlib_python.txt
Q: Alternatives to .explode() when turning a colum of list into a single colum So by far whenever I had a dataframe that has a column of list such as the following: 'category_id' [030000, 010403, 010402, 030604, 234440] [030000, 010405, 010402, 030604, 033450] [030000, 010403, 010407, 030604, 030600] [030000, 010403, 010402, 030609, 032600] Usually whenever I want to make this category_id column become like: 'category_id' 030000 010403 010402 030604 234440 030000 010405 010402 030604 033450 I would usually use the following code: df2 = df.explode('category_id') But whenever my data size gets really big, likes the sales data over the course of an entire month, .explode() becomes extremely slow and I am always worried whether I would encounter any OOM issues related to memory leaks. Is there any other alternative solutions to .explode that would somehow perform better? I tried to to use flatMap() but I'm stuck on how to exactly turn a dataframe to rdd format and then change it back to dataframe format that I can utilize. Any info would be appreciated. A: It might not be the fastest method, but you can simply explode each row of the pandas frame, and combine: import pandas df = pandas.DataFrame({"col1":[[12,34,12,34,45,56], [12,14,154,6]], "col2":['a','b']}) # col1 col2 #0 [12, 34, 12, 34, 45, 56] a #1 [12, 14, 154, 6] b # df.explode('col1') # col1 col2 #0 12 a #0 34 a #0 12 a #0 34 a #0 45 a #0 56 a #1 12 b #1 14 b #1 154 b #1 6 b new_df = pandas.DataFrame() for i in range(len(df)): df_i = df.iloc[i:i+1].explode('col1') new_df = pandas.concat((new_df, df_i)) # new_df # col1 col2 #0 12 a #0 34 a #0 12 a #0 34 a #0 45 a #0 56 a #1 12 b #1 14 b #1 154 b #1 6 b To optimize performance, you can step through the dataframe in chunks (e.g. df_chunk = df.iloc[start: start+chunk_size]; start += chunk_size; etc) An alternative approach (probably similar in performance) that avoids explode altogether: from itertools import product new_df = pandas.DataFrame() for i, row in df.iterrows(): p = product(*row.to_list()) sub_df = pandas.DataFrame.from_records(p, columns=list(df)) sub_df.index = pandas.Index([i]*len(sub_df)) new_df = pandas.concat((new_df, sub_df)) I "think" this should generalize but I did not test it. A: A fast and memory-efficient solution is to lean on numpy's .flatten() method. This one line will give you your new dataframe: df2 = pd.DataFrame({'category_id': np.array([np.array(row) for row in df['category_id']]).flatten()}) To break that down a bit, .flatten() creates a flat array out of nested arrays. But first, you have to convert from list to array, which is where the list comprehension comes in handy. Here's a more self-explanatory version of the same code: list_of_arrays = [np.array(row) for row in df['category_id']] array_of_arrays = np.array(list_of_arrays) flat_array = array_of_arrays.flatten() df2 = pd.DataFrame({'category_id': flat_array})
Alternatives to .explode() when turning a colum of list into a single colum
So by far whenever I had a dataframe that has a column of list such as the following: 'category_id' [030000, 010403, 010402, 030604, 234440] [030000, 010405, 010402, 030604, 033450] [030000, 010403, 010407, 030604, 030600] [030000, 010403, 010402, 030609, 032600] Usually whenever I want to make this category_id column become like: 'category_id' 030000 010403 010402 030604 234440 030000 010405 010402 030604 033450 I would usually use the following code: df2 = df.explode('category_id') But whenever my data size gets really big, likes the sales data over the course of an entire month, .explode() becomes extremely slow and I am always worried whether I would encounter any OOM issues related to memory leaks. Is there any other alternative solutions to .explode that would somehow perform better? I tried to to use flatMap() but I'm stuck on how to exactly turn a dataframe to rdd format and then change it back to dataframe format that I can utilize. Any info would be appreciated.
[ "It might not be the fastest method, but you can simply explode each row of the pandas frame, and combine:\nimport pandas\n\ndf = pandas.DataFrame({\"col1\":[[12,34,12,34,45,56], [12,14,154,6]], \"col2\":['a','b']})\n# col1 col2\n#0 [12, 34, 12, 34, 45, 56] a\n#1 [12, 14, 154, 6] b\n\n# df.explode('col1')\n# col1 col2\n#0 12 a\n#0 34 a\n#0 12 a\n#0 34 a\n#0 45 a\n#0 56 a\n#1 12 b\n#1 14 b\n#1 154 b\n#1 6 b\n\nnew_df = pandas.DataFrame()\nfor i in range(len(df)):\n df_i = df.iloc[i:i+1].explode('col1')\n new_df = pandas.concat((new_df, df_i)) \n\n# new_df\n# col1 col2\n#0 12 a\n#0 34 a\n#0 12 a\n#0 34 a\n#0 45 a\n#0 56 a\n#1 12 b\n#1 14 b\n#1 154 b\n#1 6 b\n\nTo optimize performance, you can step through the dataframe in chunks (e.g. df_chunk = df.iloc[start: start+chunk_size]; start += chunk_size; etc)\nAn alternative approach (probably similar in performance) that avoids explode altogether:\nfrom itertools import product\n\nnew_df = pandas.DataFrame()\nfor i, row in df.iterrows():\n p = product(*row.to_list())\n sub_df = pandas.DataFrame.from_records(p, columns=list(df))\n sub_df.index = pandas.Index([i]*len(sub_df))\n new_df = pandas.concat((new_df, sub_df))\n\nI \"think\" this should generalize but I did not test it.\n", "A fast and memory-efficient solution is to lean on numpy's .flatten() method. This one line will give you your new dataframe:\ndf2 = pd.DataFrame({'category_id': np.array([np.array(row) for row in df['category_id']]).flatten()})\n\nTo break that down a bit, .flatten() creates a flat array out of nested arrays. But first, you have to convert from list to array, which is where the list comprehension comes in handy. Here's a more self-explanatory version of the same code:\nlist_of_arrays = [np.array(row) for row in df['category_id']]\narray_of_arrays = np.array(list_of_arrays)\nflat_array = array_of_arrays.flatten()\ndf2 = pd.DataFrame({'category_id': flat_array})\n\n" ]
[ 0, 0 ]
[]
[]
[ "databricks", "pandas", "pyspark", "python" ]
stackoverflow_0074662147_databricks_pandas_pyspark_python.txt
Q: How do you use OpenAI Gym 'wrappers' with a custom Gym environment in Ray Tune? How do you use OpenAI Gym 'wrappers' with a custom Gym environment in Ray Tune? Let's say I built a Python class called CustomEnv (similar to the 'CartPoleEnv' class used to create the OpenAI Gym "CartPole-v1" environment) to create my own (custom) reinforcement learning environment, and I am using tune.run() from Ray Tune (in Ray 2.1.0 with Python 3.9.15) to train an agent in my environment using the 'PPO' algorithm: import ray from ray import tune tune.run( "PPO", # 'PPO' algorithm config={"env": CustomEnv, # custom class used to create an environment "framework": "tf2", "evaluation_interval": 100, "evaluation_duration": 100, }, checkpoint_freq = 100, # Save checkpoint at every evaluation local_dir=checkpoint_dir, # Save results to a local directory stop{"episode_reward_mean": 250}, # Stopping criterion ) This works fine, and I can use TensorBoard to monitor training progress, etc., but as it turns out, learning is slow, so I want to try using 'wrappers' from Gym to scale observations, rewards, and/or actions, limit variance, and speed-up learning. So I've got an ObservationWrapper, a RewardWrapper, and an ActionWrapper to do that--for example, something like this (the exact nature of the scaling is not central to my question): import gym class ObservationWrapper(gym.ObservationWrapper): def __init__(self, env): super().__init__(env) self.o_min = 0. self.o_max = 5000. def observation(self, ob): # Normalize observations ob = (ob - self.o_min)/(self.o_max - self.o_min) return ob class RewardWrapper(gym.RewardWrapper): def __init__(self, env): super().__init__(env) self.r_min = -500 self.r_max = 100 def reward(self, reward): # Scale rewards: reward = reward/(self.r_max - self.r_min) return reward class ActionWrapper(gym.ActionWrapper): def __init__(self, env): super().__init__(env) def action(self, action): # Scale actions action = action/10 return action Wrappers like these work fine with my custom class when I create an instance of the class on my local machine and use it in traditional training loops, like this: from my_file import CustomEnv env = CustomEnv() wrapped_env = ObservationWrapper(RewardWrapper(ActionWrapper(env))) episodes = 10 for episode in range(1,episodes+1): obs = wrapped_env.reset() done = False score = 0 while not done: action = wrapped_env.action_space.sample() obs, reward, done, info = wrapped_env.step(action) score += reward print(f'Episode: {episode}, Score: {score:.3f}') My question is: How can I use wrappers like these with my custom class (CustomEnv) and ray.tune()? This particular method expects the value for "env" to be passed either (1) as a class (such as CustomEnv) or (2) as a string associated with a registered Gym environment (such as "CartPole-v1"), as I found out while trying various incorrect ways to pass a wrapped version of my custom class: ValueError: >>> is an invalid env specifier. You can specify a custom env as either a class (e.g., YourEnvCls) or a registered env id (e.g., "your_env"). So I am not sure how to do it (assuming it is possible). I would prefer to solve this problem without having to register my custom Gym environment, but I am open to any solution. In learning about wrappers, I leveraged mostly 'Getting Started With OpenAI Gym: The Basic Building Blocks' by Ayoosh Kathuria, and 'TF 2.0 for Reinforcement Learning: Gym Wrappers'. A: I was able to answer my own question about how to get Ray's tune.run() to work with a wrapped custom class for a Gym environment. The documentation for Ray Environments was helpful. The solution was to register the custom class through Ray. Assuming you have defined your Gym wrappers (classes) as discussed above, it works like this: from ray.tune.registry import register_env from your_file import CustomEnv # import your custom class def env_creator(env_config): # wrap and return an instance of your custom class return ObservationWrapper(RewardWrapper(ActionWrapper(CustomEnv()))) # Choose a name and register your custom environment register_env('WrappedCustomEnv-v0', env_creator) Now, in tune.run(), you can submit the name of the registered instance as you would any other registered Gym environment: import ray from ray import tune tune.run( "PPO", # 'PPO' algorithm (for example) config={"env": "WrappedCustomEnv-v0", # the registered instance #other options here as desired }, # other options here as desired ) tune.run() will work with no errors--problem solved!
How do you use OpenAI Gym 'wrappers' with a custom Gym environment in Ray Tune?
How do you use OpenAI Gym 'wrappers' with a custom Gym environment in Ray Tune? Let's say I built a Python class called CustomEnv (similar to the 'CartPoleEnv' class used to create the OpenAI Gym "CartPole-v1" environment) to create my own (custom) reinforcement learning environment, and I am using tune.run() from Ray Tune (in Ray 2.1.0 with Python 3.9.15) to train an agent in my environment using the 'PPO' algorithm: import ray from ray import tune tune.run( "PPO", # 'PPO' algorithm config={"env": CustomEnv, # custom class used to create an environment "framework": "tf2", "evaluation_interval": 100, "evaluation_duration": 100, }, checkpoint_freq = 100, # Save checkpoint at every evaluation local_dir=checkpoint_dir, # Save results to a local directory stop{"episode_reward_mean": 250}, # Stopping criterion ) This works fine, and I can use TensorBoard to monitor training progress, etc., but as it turns out, learning is slow, so I want to try using 'wrappers' from Gym to scale observations, rewards, and/or actions, limit variance, and speed-up learning. So I've got an ObservationWrapper, a RewardWrapper, and an ActionWrapper to do that--for example, something like this (the exact nature of the scaling is not central to my question): import gym class ObservationWrapper(gym.ObservationWrapper): def __init__(self, env): super().__init__(env) self.o_min = 0. self.o_max = 5000. def observation(self, ob): # Normalize observations ob = (ob - self.o_min)/(self.o_max - self.o_min) return ob class RewardWrapper(gym.RewardWrapper): def __init__(self, env): super().__init__(env) self.r_min = -500 self.r_max = 100 def reward(self, reward): # Scale rewards: reward = reward/(self.r_max - self.r_min) return reward class ActionWrapper(gym.ActionWrapper): def __init__(self, env): super().__init__(env) def action(self, action): # Scale actions action = action/10 return action Wrappers like these work fine with my custom class when I create an instance of the class on my local machine and use it in traditional training loops, like this: from my_file import CustomEnv env = CustomEnv() wrapped_env = ObservationWrapper(RewardWrapper(ActionWrapper(env))) episodes = 10 for episode in range(1,episodes+1): obs = wrapped_env.reset() done = False score = 0 while not done: action = wrapped_env.action_space.sample() obs, reward, done, info = wrapped_env.step(action) score += reward print(f'Episode: {episode}, Score: {score:.3f}') My question is: How can I use wrappers like these with my custom class (CustomEnv) and ray.tune()? This particular method expects the value for "env" to be passed either (1) as a class (such as CustomEnv) or (2) as a string associated with a registered Gym environment (such as "CartPole-v1"), as I found out while trying various incorrect ways to pass a wrapped version of my custom class: ValueError: >>> is an invalid env specifier. You can specify a custom env as either a class (e.g., YourEnvCls) or a registered env id (e.g., "your_env"). So I am not sure how to do it (assuming it is possible). I would prefer to solve this problem without having to register my custom Gym environment, but I am open to any solution. In learning about wrappers, I leveraged mostly 'Getting Started With OpenAI Gym: The Basic Building Blocks' by Ayoosh Kathuria, and 'TF 2.0 for Reinforcement Learning: Gym Wrappers'.
[ "I was able to answer my own question about how to get Ray's tune.run() to work with a wrapped custom class for a Gym environment. The documentation for Ray Environments was helpful.\nThe solution was to register the custom class through Ray. Assuming you have defined your Gym wrappers (classes) as discussed above, it works like this:\nfrom ray.tune.registry import register_env\nfrom your_file import CustomEnv # import your custom class\n\ndef env_creator(env_config):\n # wrap and return an instance of your custom class\n return ObservationWrapper(RewardWrapper(ActionWrapper(CustomEnv())))\n\n# Choose a name and register your custom environment\nregister_env('WrappedCustomEnv-v0', env_creator)\n\nNow, in tune.run(), you can submit the name of the registered instance as you would any other registered Gym environment:\nimport ray\nfrom ray import tune\n\ntune.run(\n \"PPO\", # 'PPO' algorithm (for example)\n config={\"env\": \"WrappedCustomEnv-v0\", # the registered instance\n #other options here as desired\n },\n # other options here as desired\n )\n\ntune.run() will work with no errors--problem solved!\n" ]
[ 0 ]
[]
[]
[ "openai_gym", "python", "ray", "tensorflow" ]
stackoverflow_0074637712_openai_gym_python_ray_tensorflow.txt
Q: How can I make it so you input a "Worker code" and get the worker details same as when you "print(Worker_36.details)"? - Python I am new to python and just playing around please help! Worker_31 = Worker('David', 'Williamson',31 , 92500, 5, 37) Worker_32 = Worker('Frank', 'Murphy',32 , 58500, 6, 27) Worker_33 = Worker('Josephine', 'Dover',33 , 69500, 2, 30) Worker_34 = Worker('Chester', 'Cohen',34 , 88500, 3, 52) Worker_35 = Worker('Saba', "Brenland",35 , 96500, 4, 35) Worker_36 = Worker('Tommy-Lee', 'Briggs',36 , 98500, 3, 57) Worker_37 = Worker('Li', 'Hu-Tao',37 , 55000, 3, 22) Worker_38 = Worker('Qin', 'Shi-Huang',38 ,14 ,1500000 , 34) Worker_39 = Worker('Maximillian', 'Mendoza',39 , 200000, 13, 33) Worker_40 = Worker('Sarah', 'Patel',40 , 86500 , 8, 29) Worker_41 = Worker('Sumaiya', 'Johns',41 ,77900 , 10, 32) So you see I was able to make the workers def details(self): return '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' .format("Your worker ", self.fullname(), " (Worker number ", self.number, ") ", "is paid a yearly salary of ", "$"+str(self.pay), " Dollars. ", "This worker has been with your company for ", self.time_with, " years, unfortunately however, they are due to retire in ", self.time_left, " years (aged 65).", " In the mean time however you can contact this worker with the email address ", self.email) And able to print(Worker_36.details) for example and it works... print("You have 50 workers what worker would you like to check the details of?") Worker_Number_Check = input("Please input there worker number ") If the user inputs 36 for example I want it to return the equavilent of the "print(Worker_36.details)" I don't want to have to do a long else if for every single possible input number with a worker who has that as there "Worker number", please help? A: Instead of declaring many separate Worker variables, make a list of them: workers = [ Worker(...), Worker(...), Worker(...), Worker(...), ] And then you can refer to workers[36].
How can I make it so you input a "Worker code" and get the worker details same as when you "print(Worker_36.details)"? - Python
I am new to python and just playing around please help! Worker_31 = Worker('David', 'Williamson',31 , 92500, 5, 37) Worker_32 = Worker('Frank', 'Murphy',32 , 58500, 6, 27) Worker_33 = Worker('Josephine', 'Dover',33 , 69500, 2, 30) Worker_34 = Worker('Chester', 'Cohen',34 , 88500, 3, 52) Worker_35 = Worker('Saba', "Brenland",35 , 96500, 4, 35) Worker_36 = Worker('Tommy-Lee', 'Briggs',36 , 98500, 3, 57) Worker_37 = Worker('Li', 'Hu-Tao',37 , 55000, 3, 22) Worker_38 = Worker('Qin', 'Shi-Huang',38 ,14 ,1500000 , 34) Worker_39 = Worker('Maximillian', 'Mendoza',39 , 200000, 13, 33) Worker_40 = Worker('Sarah', 'Patel',40 , 86500 , 8, 29) Worker_41 = Worker('Sumaiya', 'Johns',41 ,77900 , 10, 32) So you see I was able to make the workers def details(self): return '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' '{}' .format("Your worker ", self.fullname(), " (Worker number ", self.number, ") ", "is paid a yearly salary of ", "$"+str(self.pay), " Dollars. ", "This worker has been with your company for ", self.time_with, " years, unfortunately however, they are due to retire in ", self.time_left, " years (aged 65).", " In the mean time however you can contact this worker with the email address ", self.email) And able to print(Worker_36.details) for example and it works... print("You have 50 workers what worker would you like to check the details of?") Worker_Number_Check = input("Please input there worker number ") If the user inputs 36 for example I want it to return the equavilent of the "print(Worker_36.details)" I don't want to have to do a long else if for every single possible input number with a worker who has that as there "Worker number", please help?
[ "Instead of declaring many separate Worker variables, make a list of them:\nworkers = [\n Worker(...),\n Worker(...),\n Worker(...),\n Worker(...),\n]\n\nAnd then you can refer to workers[36].\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074663319_python.txt
Q: SymPy: Replace all ints with floats in expression Seems like SymPy makes it pretty easy to do the opposite - convert all floats to ints, but I'm curious how to do the reverse? The specific problem I'm running into is with the RustCodeGen spitting out expressions with mixed f64/int types, which makes the compiler unhappy. Any suggestions on ways to get around this programmatically would be greatly appreciated! Simple example: >> variables = [symbols('x1')] >> expression = 'x1 % 0.5' >> expr = parse_expr(expression, evaluate=0) >> print(expr) # Notice it has injected a multiply by 2 0.5*(Mod(2*x1, 1)) >> CG = RustCodeGen() >> routine = CG.routine("", expr, variables, {}) >> CG._call_printer(routine) ['let out1 = 0.5*(2*x1 - (2*x1).floor());\n', 'out1', '\n'] which doesn't compile: error[E0277]: cannot multiply `{integer}` by `{float}` --> src/main.rs:5:22 | 5 | let out1 = 0.5*(2*x1 - (2*x1).floor()); | ^ no implementation for `{integer} * {float}` A: I would recommend faking the integer with a symbol having desired float name: >>> f= expr.xreplace({i:Symbol(str(i)+".") for i in expr.atoms(Integer)}) >>> routine = CG.routine("", f, variables, {}) >>> CG._call_printer(routine)```
SymPy: Replace all ints with floats in expression
Seems like SymPy makes it pretty easy to do the opposite - convert all floats to ints, but I'm curious how to do the reverse? The specific problem I'm running into is with the RustCodeGen spitting out expressions with mixed f64/int types, which makes the compiler unhappy. Any suggestions on ways to get around this programmatically would be greatly appreciated! Simple example: >> variables = [symbols('x1')] >> expression = 'x1 % 0.5' >> expr = parse_expr(expression, evaluate=0) >> print(expr) # Notice it has injected a multiply by 2 0.5*(Mod(2*x1, 1)) >> CG = RustCodeGen() >> routine = CG.routine("", expr, variables, {}) >> CG._call_printer(routine) ['let out1 = 0.5*(2*x1 - (2*x1).floor());\n', 'out1', '\n'] which doesn't compile: error[E0277]: cannot multiply `{integer}` by `{float}` --> src/main.rs:5:22 | 5 | let out1 = 0.5*(2*x1 - (2*x1).floor()); | ^ no implementation for `{integer} * {float}`
[ "I would recommend faking the integer with a symbol having desired float name:\n>>> f= expr.xreplace({i:Symbol(str(i)+\".\") for i in expr.atoms(Integer)})\n>>> routine = CG.routine(\"\", f, variables, {})\n>>> CG._call_printer(routine)```\n\n" ]
[ 0 ]
[]
[]
[ "codegen", "python", "rust", "sympy" ]
stackoverflow_0074663159_codegen_python_rust_sympy.txt
Q: Close or Switch Tabs in Playwright/Python I'm doing an automation, at the time of download it opens a tab, sometimes it doesn't close automatically, so how can I close a tab in playwright using python? A: I managed to make a code that closes only a specific tab! all_pages = page.context.pages await all_pages[1].close() A: You can also use the close method on the Page object that represents the tab you want to close. Here is an example of how you might do this: # launch a browser and create a new context browser = await playwright[browserType].launch() context = await browser.newContext() # create a new page and go to the URL you want to download from page = await context.newPage() await page.goto("https://www.example.com") # download a file from the page await page.click("#download-button") # wait for the download to finish and the new tab to be created await page.waitForSelector("#download-complete") # get a list of pages in the current context pages = await context.pages() # assume the last page in the list is the new tab that was created # (you may need to adapt this to your specific use case) newTab = pages[-1] # close the new tab await newTab.close()
Close or Switch Tabs in Playwright/Python
I'm doing an automation, at the time of download it opens a tab, sometimes it doesn't close automatically, so how can I close a tab in playwright using python?
[ "I managed to make a code that closes only a specific tab!\nall_pages = page.context.pages\nawait all_pages[1].close()\n\n", "You can also use the close method on the Page object that represents the tab you want to close. Here is an example of how you might do this:\n# launch a browser and create a new context\nbrowser = await playwright[browserType].launch()\ncontext = await browser.newContext()\n\n# create a new page and go to the URL you want to download from\npage = await context.newPage()\nawait page.goto(\"https://www.example.com\")\n\n# download a file from the page\nawait page.click(\"#download-button\")\n\n# wait for the download to finish and the new tab to be created\nawait page.waitForSelector(\"#download-complete\")\n\n# get a list of pages in the current context\npages = await context.pages()\n\n# assume the last page in the list is the new tab that was created\n# (you may need to adapt this to your specific use case)\nnewTab = pages[-1]\n\n# close the new tab\nawait newTab.close()\n\n" ]
[ 1, 0 ]
[]
[]
[ "browser", "playwright", "playwright_python", "python", "tabs" ]
stackoverflow_0073209567_browser_playwright_playwright_python_python_tabs.txt
Q: How to create a working progress bar using Bootstrap and Flask I have simple textarea form, outputs the result below the form, and I'd like to have a progress bar display upon clicking submit. I've searched else where to no avail and no idea where to start. Can someone guide this poor soul in the right direction? (novice by the way) A: First, you will need to create a Flask route that returns the current progress value. This route can be called using an AJAX request from the progress bar element to update the progress bar value dynamically. from flask import Flask, jsonify app = Flask(__name__) @app.route('/progress') def progress(): # Return the current progress value as JSON return jsonify({'progress': current_progress}) Next, you can create the progress bar element using the progress class from Bootstrap. You can use the data-value attribute to specify the initial progress value, and the data-url attribute to specify the URL of the Flask route that returns the current progress value. Here is an example of a progress bar element using Bootstrap: <div class="progress" data-value="0" data-url="/progress"> <div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div> </div> Finally, you can use JavaScript to update the progress bar value dynamically by making an AJAX request to the Flask route that returns the current progress value. You can use the setInterval function to make the AJAX request at regular intervals, and update the data-value and style attributes of the progress bar element with the new progress value // Set the initial progress value var progress = $('.progress').data('value'); // Set the URL of the Flask route that returns the current progress value var url = $('.progress').data('url'); // Update the progress bar value every 1000 milliseconds (1 second) setInterval(function() { // Make an AJAX request to the Flask route $.get(url, function(data) { // Update the progress bar value progress = data.progress; $('.progress-bar').attr('data-value', progress); $('.progress-bar').css('width', progress + '%'); }); }, 1000); Not sure what you want to show with the progress bar but I hope that helps you :)
How to create a working progress bar using Bootstrap and Flask
I have simple textarea form, outputs the result below the form, and I'd like to have a progress bar display upon clicking submit. I've searched else where to no avail and no idea where to start. Can someone guide this poor soul in the right direction? (novice by the way)
[ "First, you will need to create a Flask route that returns the current progress value. This route can be called using an AJAX request from the progress bar element to update the progress bar value dynamically.\nfrom flask import Flask, jsonify\n\napp = Flask(__name__)\n\[email protected]('/progress')\ndef progress():\n # Return the current progress value as JSON\n return jsonify({'progress': current_progress})\n\nNext, you can create the progress bar element using the progress class from Bootstrap. You can use the data-value attribute to specify the initial progress value, and the data-url attribute to specify the URL of the Flask route that returns the current progress value. Here is an example of a progress bar element using Bootstrap:\n<div class=\"progress\" data-value=\"0\" data-url=\"/progress\">\n <div class=\"progress-bar\" role=\"progressbar\" style=\"width: 0%;\" aria-valuenow=\"0\" \n aria-valuemin=\"0\" aria-valuemax=\"100\"></div>\n</div>\n\nFinally, you can use JavaScript to update the progress bar value dynamically by making an AJAX request to the Flask route that returns the current progress value. You can use the setInterval function to make the AJAX request at regular intervals, and update the data-value and style attributes of the progress bar element with the new progress value\n// Set the initial progress value\nvar progress = $('.progress').data('value');\n\n// Set the URL of the Flask route that returns the current progress value\nvar url = $('.progress').data('url');\n\n// Update the progress bar value every 1000 milliseconds (1 second)\nsetInterval(function() {\n // Make an AJAX request to the Flask route\n $.get(url, function(data) {\n // Update the progress bar value\n progress = data.progress;\n $('.progress-bar').attr('data-value', progress);\n $('.progress-bar').css('width', progress + '%');\n });\n}, 1000);\n\nNot sure what you want to show with the progress bar but I hope that helps you :)\n" ]
[ 0 ]
[]
[]
[ "bootstrap_5", "python" ]
stackoverflow_0074662867_bootstrap_5_python.txt
Q: How to update new line colours in Plotly from a button click and access results? I want to plot an image, draw freehand over the image, then be able to press a custom button so that freehand drawing is now in a different colour. I cannot figure out how to make the button press change the line colour though. The code I have tried is here below. I've tried using all four button methods described in the documentation, but none of them have any effect when pressed. Furthermore, I can't find anywhere in the documentation how to access the lines that have been drawn over the image once finished (other than having to save the image manually using the GUI which I want to avoid). # Imports import plotly import plotly.graph_objects as go import plotly.express as px # Show image img = cv2.imread(fpath) fig = px.imshow(img) # Enable freehand drawing on mouse drag fig.update_layout(overwrite=True, dragmode='drawopenpath', newshape_line_color='cyan', modebar_add=['drawopenpath',"eraseshape"]) # Add two buttons, 'r' and 'b' which attempt to update newshape_line_color... fig.update_layout( updatemenus=[ dict( type="buttons", direction="right", active=0, showactive=True, x=0.57, y=1.2, buttons=list([ { 'label':"r", 'method':"relayout", 'args':[{'newshape_line_color':'red'}], }, dict(label="b", method="restyle", args=[{"newshape_line_color": 'blue'}]), ]), ) ]) # Show figure config = dict({'scrollZoom': True}) fig.show(config = config) Any help would be greatly appreciated! A: If I understand correctly, you want all of the drawn lines to change color when the button is selected. I've got two solutions for you. The first doesn't do exactly what you're asking for, but it's entirely in Python. Instead of changing the last line drawn, all subsequent lines are drawn with the selected color. The second does do what you're looking for but requires JS. Pythonic...but not quite what you're looking for Here's the updated updatemenus. You were pretty close, actually. I've created two color buttons: red and green. fig.update_layout( updatemenus = list([ dict(type = "buttons", direction = "right", active = 0, showactive = True, x = 0.57, y = 1.2, buttons = list([ # change future colors dict(label = "Make Me Red", method = "relayout", args = [{'newshape.line.color': 'red'}] ), dict(label = "Make Me Green", method = "relayout", args = [{'newshape.line.color': 'green'}] ) ]) ) ]) ) When you select the color button, all lines drawn after will be in the color selected. Here's the entire chunk of code used to make this: from skimage import io import plotly.graph_objects as go import plotly.express as px # Show image img = io.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg') fig = px.imshow(img) # Enable freehand drawing on mouse drag fig.update_layout(overwrite=True, dragmode='drawopenpath', newshape_line_color='cyan', modebar_add=['drawopenpath',"eraseshape"]) fig.add_shape(dict(editable = True, type = "line", line = dict(color = "white"), layer = 'above', x0 = 0, x1 = 200.0000001, y0 = 0, y1 = 200.0000001)) # Add two buttons, 'r' and 'b' which attempt to update newshape_line_color... fig.update_layout( updatemenus = list([ dict(type = "buttons", direction = "right", active = 0, showactive = True, x = 0.57, y = 1.2, buttons = list([ # change future colors dict(label = "Make Me Red", method = "relayout", args = [{'newshape.line.color': 'red'}] ), dict(label = "Make Me Green", method = "relayout", args = [{'newshape.line.color': 'green'}] ) ]) ) ]) ) # Show figure config = dict({'scrollZoom': True}) fig.show(config = config) Embedded JS Changing the Drawn Line Color You'll use everything up to fig.show() then you'll use the following. Yes, it creates an external file, but it will immediately open in your browser, as well. This piggybacks off of your buttons. When green is clicked now, it will change all of the lines, not just what's drawn next. There are two events here, one for each color. In the JS, you'll notice two for loops in each event. These serve very different purposes. Because there doesn't seem to be a built-in event to do this for me, the first loop changes the actual attributes of the plot. However, that won't be visible immediately. So the second loop changes what you actually see at that moment. This requires the Plotly io package. You had called import plotly, so you could just change pio to plotly.io instead of calling it though. import plotly.io as pio pio.write_html(fig, file = 'index2.html', auto_open = True, config = config, include_plotlyjs = 'cdn', include_mathjax = 'cdn', post_script = "setTimeout(function() {" + "btns = document.querySelectorAll('g.updatemenu-button');" + "btns[0].addEventListener('click', function() {" + "ch = document.getElementById('thisCh');" + "shapes = ch.layout.shapes; /* update the plot attributes */" + "for(i = 0; i < shapes.length; i++) {" + "shapes[i].line.color = 'red';" + "} /* update the current appearance immediately */" + "chart = document.querySelectorAll('g.shapelayer')[2];" + "for(i = 0; i < chart.children.length; i++) {" + "chart.children[i].style.stroke = 'red';" + "}" + "});" + "btns[1].addEventListener('click', function() {" + "ch = document.getElementById('thisCh');" + "shapes = ch.layout.shapes; /* update the plot attributes */" + "for(i = 0; i < shapes.length; i++) {" + "shapes[i].line.color = 'green';" + "} /* update the current appearance immediately */" + "chart = document.querySelectorAll('g.shapelayer')[2];" + "for(i = 0; i < chart.children.length; i++) {" + "chart.children[i].style.stroke = 'green';" + "}" + "});" + "}, 200)", full_html = True, div_id = "thisCh") If I've misunderstood what you're looking for or if you have any questions, let me know. Oh, and if you go with the second solution but wanted many colors, I can make it color dynamic, I didn't do that with only two colors that I used for this demonstration.
How to update new line colours in Plotly from a button click and access results?
I want to plot an image, draw freehand over the image, then be able to press a custom button so that freehand drawing is now in a different colour. I cannot figure out how to make the button press change the line colour though. The code I have tried is here below. I've tried using all four button methods described in the documentation, but none of them have any effect when pressed. Furthermore, I can't find anywhere in the documentation how to access the lines that have been drawn over the image once finished (other than having to save the image manually using the GUI which I want to avoid). # Imports import plotly import plotly.graph_objects as go import plotly.express as px # Show image img = cv2.imread(fpath) fig = px.imshow(img) # Enable freehand drawing on mouse drag fig.update_layout(overwrite=True, dragmode='drawopenpath', newshape_line_color='cyan', modebar_add=['drawopenpath',"eraseshape"]) # Add two buttons, 'r' and 'b' which attempt to update newshape_line_color... fig.update_layout( updatemenus=[ dict( type="buttons", direction="right", active=0, showactive=True, x=0.57, y=1.2, buttons=list([ { 'label':"r", 'method':"relayout", 'args':[{'newshape_line_color':'red'}], }, dict(label="b", method="restyle", args=[{"newshape_line_color": 'blue'}]), ]), ) ]) # Show figure config = dict({'scrollZoom': True}) fig.show(config = config) Any help would be greatly appreciated!
[ "If I understand correctly, you want all of the drawn lines to change color when the button is selected.\nI've got two solutions for you.\nThe first doesn't do exactly what you're asking for, but it's entirely in Python. Instead of changing the last line drawn, all subsequent lines are drawn with the selected color.\nThe second does do what you're looking for but requires JS.\nPythonic...but not quite what you're looking for\nHere's the updated updatemenus. You were pretty close, actually. I've created two color buttons: red and green.\nfig.update_layout(\n updatemenus = list([\n dict(type = \"buttons\",\n direction = \"right\",\n active = 0,\n showactive = True,\n x = 0.57,\n y = 1.2,\n buttons = list([ # change future colors\n dict(label = \"Make Me Red\", \n method = \"relayout\", \n args = [{'newshape.line.color': 'red'}]\n ),\n dict(label = \"Make Me Green\", \n method = \"relayout\", \n args = [{'newshape.line.color': 'green'}]\n )\n ]) \n )\n ])\n)\n\nWhen you select the color button, all lines drawn after will be in the color selected.\n\nHere's the entire chunk of code used to make this:\nfrom skimage import io\nimport plotly.graph_objects as go\nimport plotly.express as px\n\n# Show image\nimg = io.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')\nfig = px.imshow(img)\n\n# Enable freehand drawing on mouse drag\nfig.update_layout(overwrite=True,\n dragmode='drawopenpath',\n newshape_line_color='cyan',\n modebar_add=['drawopenpath',\"eraseshape\"])\n\nfig.add_shape(dict(editable = True, type = \"line\", \n line = dict(color = \"white\"), \n layer = 'above',\n x0 = 0, x1 = 200.0000001, \n y0 = 0, y1 = 200.0000001))\n\n# Add two buttons, 'r' and 'b' which attempt to update newshape_line_color...\nfig.update_layout(\n updatemenus = list([\n dict(type = \"buttons\",\n direction = \"right\",\n active = 0,\n showactive = True,\n x = 0.57,\n y = 1.2,\n buttons = list([ # change future colors\n dict(label = \"Make Me Red\", \n method = \"relayout\", \n args = [{'newshape.line.color': 'red'}]\n ),\n dict(label = \"Make Me Green\", \n method = \"relayout\", \n args = [{'newshape.line.color': 'green'}]\n )\n ]) \n )\n ])\n)\n\n# Show figure\nconfig = dict({'scrollZoom': True})\nfig.show(config = config)\n\nEmbedded JS Changing the Drawn Line Color\nYou'll use everything up to fig.show() then you'll use the following. Yes, it creates an external file, but it will immediately open in your browser, as well.\nThis piggybacks off of your buttons. When green is clicked now, it will change all of the lines, not just what's drawn next. There are two events here, one for each color.\nIn the JS, you'll notice two for loops in each event. These serve very different purposes. Because there doesn't seem to be a built-in event to do this for me, the first loop changes the actual attributes of the plot. However, that won't be visible immediately. So the second loop changes what you actually see at that moment.\nThis requires the Plotly io package. You had called import plotly, so you could just change pio to plotly.io instead of calling it though.\nimport plotly.io as pio\n\npio.write_html(fig, file = 'index2.html', auto_open = True, \n config = config, include_plotlyjs = 'cdn', include_mathjax = 'cdn',\n post_script = \"setTimeout(function() {\" +\n \"btns = document.querySelectorAll('g.updatemenu-button');\" +\n \"btns[0].addEventListener('click', function() {\" + \n \"ch = document.getElementById('thisCh');\" +\n \"shapes = ch.layout.shapes; /* update the plot attributes */\" +\n \"for(i = 0; i < shapes.length; i++) {\" +\n \"shapes[i].line.color = 'red';\" +\n \"} /* update the current appearance immediately */\" +\n \"chart = document.querySelectorAll('g.shapelayer')[2];\" +\n \"for(i = 0; i < chart.children.length; i++) {\" +\n \"chart.children[i].style.stroke = 'red';\" +\n \"}\" +\n \"});\" +\n \"btns[1].addEventListener('click', function() {\" +\n \"ch = document.getElementById('thisCh');\" +\n \"shapes = ch.layout.shapes; /* update the plot attributes */\" +\n \"for(i = 0; i < shapes.length; i++) {\" +\n \"shapes[i].line.color = 'green';\" +\n \"} /* update the current appearance immediately */\" + \n \"chart = document.querySelectorAll('g.shapelayer')[2];\" +\n \"for(i = 0; i < chart.children.length; i++) {\" +\n \"chart.children[i].style.stroke = 'green';\" +\n \"}\" +\n \"});\" +\n \"}, 200)\", full_html = True, div_id = \"thisCh\")\n\n\n\nIf I've misunderstood what you're looking for or if you have any questions, let me know. Oh, and if you go with the second solution but wanted many colors, I can make it color dynamic, I didn't do that with only two colors that I used for this demonstration.\n" ]
[ 0 ]
[]
[]
[ "google_colaboratory", "interactive", "plotly", "python" ]
stackoverflow_0074659489_google_colaboratory_interactive_plotly_python.txt
Q: Swap position of keys in a dictionary for same value I have a dictionary cost = { (0,1):70, (0,2):40, (1,2):65 } I would like a dictionary where the values for the opposite keys are also the same. To clarify, (0,1):70 is also the same as (1,0):70 I tried to flip the values of the keys using this: for i,j in cost.keys(): cost [j,i]==cost[i,j] This gives a key error of (1,0) but that is the key that I want the code to add. I further tried cost1 = {tuple(y): x for x, y in cost.keys()} This resulted in a TypeError:'int' object not iterable How can I then further append all the values to a dictionary? Thank you for your time and help. A: Try this code snippet, to see if that's what you want: # make a new dict to reflect the swap keys: cost1 = {} for key, val in cost.items(): x, y = key # unpack the key cost1[(y, x)] = val # swap x, y - tuple as the new key print(cost1) # {(1, 0): 70, (2, 0): 40, (2, 1): 65}
Swap position of keys in a dictionary for same value
I have a dictionary cost = { (0,1):70, (0,2):40, (1,2):65 } I would like a dictionary where the values for the opposite keys are also the same. To clarify, (0,1):70 is also the same as (1,0):70 I tried to flip the values of the keys using this: for i,j in cost.keys(): cost [j,i]==cost[i,j] This gives a key error of (1,0) but that is the key that I want the code to add. I further tried cost1 = {tuple(y): x for x, y in cost.keys()} This resulted in a TypeError:'int' object not iterable How can I then further append all the values to a dictionary? Thank you for your time and help.
[ "Try this code snippet, to see if that's what you want:\n# make a new dict to reflect the swap keys:\ncost1 = {}\n\nfor key, val in cost.items():\n x, y = key # unpack the key\n cost1[(y, x)] = val # swap x, y - tuple as the new key\n \nprint(cost1)\n# {(1, 0): 70, (2, 0): 40, (2, 1): 65}\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074663417_dictionary_python.txt
Q: Is there a way to format a json byte array and write it to a file? I have a byte array that I made, and I am writing it to a json file. This works, but I want to have a formatted JSON file instead of a massive wall of text. I have tried decoding the byte array with utf-8, but instead I get UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte. My plan was to then take this string and use json.dumps() to format it. Trying json.dumps() without any other formatting gives this: TypeError: Object of type bytearray is not JSON serializable content = bytearray() content_idx = 0 try: with open(arguments.input_file, 'rb') as input_file: while (byte:=input_file.read(1)): content += bytes([ord(byte) ^ xor_key[content_idx % (len(xor_key))]]) content_idx += 1 except (IOError, OSError) as exception: print('Error: could not read input file') exit() try: with open(arguments.output_file, 'wb') as output_file: output_file.write(json.dumps(content.decode('utf-8'), indent=4)) except (IOError, OSError) as exception: print('Error: could not create output file') exit() A: The error is that you are trying to pass then bytes, and json.dumps() is trying to serialize them somehow, but can't, which is written in the error output. To save the file in JSON you need to translate the byte stream into a Python dictionary, which will already accept JSON perfectly and without problems. It would help if you could show what the input data looks like and what you want to save to JSON Python has an off-the-shelf Base64 library that can translate an array of bytes into a string, and here's an example usage article. But the problem may arise later when parsing that string into the dictionary, so maybe I'd advise you to google what libraries are probably ready for such parsing, but otherwise you can use regular expressions A: The JSON encoder and decoder can be extended to support other types. Here's one way to support byte strings by converting them to a BASE64 str and serializing it as a dict with special key. The key is used to flag the decoder to convert the JSON object with that key back to a byte string. import json import base64 class B64Encoder(json.JSONEncoder): '''Recognize a bytes object and return a dictionary with a special key to indicate its value is a BASE64 string. ''' def default(self, obj): if isinstance(obj, bytes): return {'__B64__': base64.b64encode(obj).decode('ascii')} return super().default(obj) def B64Decoder(obj): '''Recognize a dictionary with the special BASE64 key and return its BASE64-decoded value. ''' if '__B64__' in obj: return base64.b64decode(obj['__B64__']) return obj d = {'key1': bytes.fromhex('0102030405'), 'key2': b'\xaa\x55\x00\xff'} print(f'Python IN: {d}') print('\nJSON:') s = json.dumps(d, indent=2, cls=B64Encoder) print(s) d2 = json.loads(s, object_hook=B64Decoder) print(f'\nPython OUT: {d}') Output: Python IN: {'key1': b'\x01\x02\x03\x04\x05', 'key2': b'\xaaU\x00\xff'} JSON: { "key1": { "__B64__": "AQIDBAU=" }, "key2": { "__B64__": "qlUA/w==" } } Python OUT: {'key1': b'\x01\x02\x03\x04\x05', 'key2': b'\xaaU\x00\xff'}
Is there a way to format a json byte array and write it to a file?
I have a byte array that I made, and I am writing it to a json file. This works, but I want to have a formatted JSON file instead of a massive wall of text. I have tried decoding the byte array with utf-8, but instead I get UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte. My plan was to then take this string and use json.dumps() to format it. Trying json.dumps() without any other formatting gives this: TypeError: Object of type bytearray is not JSON serializable content = bytearray() content_idx = 0 try: with open(arguments.input_file, 'rb') as input_file: while (byte:=input_file.read(1)): content += bytes([ord(byte) ^ xor_key[content_idx % (len(xor_key))]]) content_idx += 1 except (IOError, OSError) as exception: print('Error: could not read input file') exit() try: with open(arguments.output_file, 'wb') as output_file: output_file.write(json.dumps(content.decode('utf-8'), indent=4)) except (IOError, OSError) as exception: print('Error: could not create output file') exit()
[ "The error is that you are trying to pass then bytes, and json.dumps() is trying to serialize them somehow, but can't, which is written in the error output.\nTo save the file in JSON you need to translate the byte stream into a Python dictionary, which will already accept JSON perfectly and without problems.\nIt would help if you could show what the input data looks like and what you want to save to JSON\nPython has an off-the-shelf Base64 library that can translate an array of bytes into a string, and here's an example usage article. But the problem may arise later when parsing that string into the dictionary, so maybe I'd advise you to google what libraries are probably ready for such parsing, but otherwise you can use regular expressions\n", "The JSON encoder and decoder can be extended to support other types. Here's one way to support byte strings by converting them to a BASE64 str and serializing it as a dict with special key. The key is used to flag the decoder to convert the JSON object with that key back to a byte string.\nimport json\nimport base64\n\nclass B64Encoder(json.JSONEncoder):\n '''Recognize a bytes object and return a dictionary with\n a special key to indicate its value is a BASE64 string.\n '''\n def default(self, obj):\n if isinstance(obj, bytes):\n return {'__B64__': base64.b64encode(obj).decode('ascii')}\n return super().default(obj)\n\ndef B64Decoder(obj):\n '''Recognize a dictionary with the special BASE64 key\n and return its BASE64-decoded value.\n '''\n if '__B64__' in obj:\n return base64.b64decode(obj['__B64__'])\n return obj\n\nd = {'key1': bytes.fromhex('0102030405'), 'key2': b'\\xaa\\x55\\x00\\xff'}\nprint(f'Python IN: {d}')\nprint('\\nJSON:')\ns = json.dumps(d, indent=2, cls=B64Encoder)\nprint(s)\nd2 = json.loads(s, object_hook=B64Decoder)\nprint(f'\\nPython OUT: {d}')\n\nOutput:\nPython IN: {'key1': b'\\x01\\x02\\x03\\x04\\x05', 'key2': b'\\xaaU\\x00\\xff'}\n\nJSON:\n{\n \"key1\": {\n \"__B64__\": \"AQIDBAU=\"\n },\n \"key2\": {\n \"__B64__\": \"qlUA/w==\"\n }\n}\n\nPython OUT: {'key1': b'\\x01\\x02\\x03\\x04\\x05', 'key2': b'\\xaaU\\x00\\xff'}\n\n" ]
[ 0, 0 ]
[]
[]
[ "arrays", "json", "python" ]
stackoverflow_0074663109_arrays_json_python.txt
Q: How to call a Python function from Node.js I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application to make use of the power of machine learning libraries? A: Easiest way I know of is to use "child_process" package which comes packaged with node. Then you can do something like: const spawn = require("child_process").spawn; const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]); Then all you have to do is make sure that you import sys in your python script, and then you can access arg1 using sys.argv[1], arg2 using sys.argv[2], and so on. To send data back to node just do the following in the python script: print(dataToSendBack) sys.stdout.flush() And then node can listen for data using: pythonProcess.stdout.on('data', (data) => { // Do something with the data returned from python script }); Since this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc. Hope this was clear. Let me know if something needs clarification. A: Example for people who are from Python background and want to integrate their machine learning model in the Node.js application: It uses the child_process core module: const express = require('express') const app = express() app.get('/', (req, res) => { const { spawn } = require('child_process'); const pyProg = spawn('python', ['./../pypy.py']); pyProg.stdout.on('data', function(data) { console.log(data.toString()); res.write(data); res.end('end'); }); }) app.listen(4000, () => console.log('Application listening on port 4000!')) It doesn't require sys module in your Python script. Below is a more modular way of performing the task using Promise: const express = require('express') const app = express() let runPy = new Promise(function(success, nosuccess) { const { spawn } = require('child_process'); const pyprog = spawn('python', ['./../pypy.py']); pyprog.stdout.on('data', function(data) { success(data); }); pyprog.stderr.on('data', (data) => { nosuccess(data); }); }); app.get('/', (req, res) => { res.write('welcome\n'); runPy.then(function(fromRunpy) { console.log(fromRunpy.toString()); res.end(fromRunpy); }); }) app.listen(4000, () => console.log('Application listening on port 4000!')) A: The python-shell module by extrabacon is a simple way to run Python scripts from Node.js with basic, but efficient inter-process communication and better error handling. Installation: With npm: npm install python-shell. Or with yarn: yarn add python-shell Running a simple Python script: const PythonShell = require('python-shell').PythonShell; PythonShell.run('my_script.py', null, function (err) { if (err) throw err; console.log('finished'); }); Running a Python script with arguments and options: const PythonShell = require('python-shell').PythonShell; var options = { mode: 'text', pythonPath: 'path/to/python', pythonOptions: ['-u'], scriptPath: 'path/to/my/scripts', args: ['value1', 'value2', 'value3'] }; PythonShell.run('my_script.py', options, function (err, results) { if (err) throw err; // Results is an array consisting of messages collected during execution console.log('results: %j', results); }); For the full documentation and source code, check out https://github.com/extrabacon/python-shell A: You can now use RPC libraries that support Python and Javascript such as zerorpc From their front page: Node.js Client var zerorpc = require("zerorpc"); var client = new zerorpc.Client(); client.connect("tcp://127.0.0.1:4242"); client.invoke("hello", "RPC", function(error, res, more) { console.log(res); }); Python Server import zerorpc class HelloRPC(object): def hello(self, name): return "Hello, %s" % name s = zerorpc.Server(HelloRPC()) s.bind("tcp://0.0.0.0:4242") s.run() A: Many of the examples are years out of date and involve complex setup. You can give JSPyBridge/pythonia a try (full disclosure: I'm the author). It's vanilla JS that lets you operate on foreign Python objects as if they existed in JS. In fact, it does interoperability so Python code can in return call JS through callbacks and passed functions. numpy + matplotlib example, with the ES6 import system: import { py, python } from 'pythonia' const np = await python('numpy') const plot = await python('matplotlib.pyplot') // Fixing random state for reproducibility await np.random.seed(19680801) const [mu, sigma] = [100, 15] // Inline expression evaluation for operator overloading const x = await py`${mu} + ${sigma} * ${np.random.randn(10000)}` // the histogram of the data const [n, bins, patches] = await plot.hist$(x, 50, { density: true, facecolor: 'g', alpha: 0.75 }) console.log('Distribution', await n) // Always await for all Python access await plot.show() python.exit() Through CommonJS (without top level await): const { py, python } = require('pythonia') async function main() { const np = await python('numpy') const plot = await python('matplotlib.pyplot') ... // the rest of the code } main().then(() => python.exit()) // If you don't call this, the process won't quit by itself. A: Most of previous answers call the success of the promise in the on("data"), it is not the proper way to do it because if you receive a lot of data you will only get the first part. Instead you have to do it on the end event. const { spawn } = require('child_process'); const pythonDir = (__dirname + "/../pythonCode/"); // Path of python script folder const python = pythonDir + "pythonEnv/bin/python"; // Path of the Python interpreter /** remove warning that you don't care about */ function cleanWarning(error) { return error.replace(/Detector is not able to detect the language reliably.\n/g,""); } function callPython(scriptName, args) { return new Promise(function(success, reject) { const script = pythonDir + scriptName; const pyArgs = [script, JSON.stringify(args) ] const pyprog = spawn(python, pyArgs ); let result = ""; let resultError = ""; pyprog.stdout.on('data', function(data) { result += data.toString(); }); pyprog.stderr.on('data', (data) => { resultError += cleanWarning(data.toString()); }); pyprog.stdout.on("end", function(){ if(resultError == "") { success(JSON.parse(result)); }else{ console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`); const error = new Error(resultError); console.error(error); reject(resultError); } }) }); } module.exports.callPython = callPython; Call: const pythonCaller = require("../core/pythonCaller"); const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value}); python: try: argu = json.loads(sys.argv[1]) except: raise Exception("error while loading argument") A: I'm on node 10 and child process 1.0.2. The data from python is a byte array and has to be converted. Just another quick example of making a http request in python. node const process = spawn("python", ["services/request.py", "https://www.google.com"]) return new Promise((resolve, reject) =>{ process.stdout.on("data", data =>{ resolve(data.toString()); // <------------ by default converts to utf-8 }) process.stderr.on("data", reject) }) request.py import urllib.request import sys def karl_morrison_is_a_pedant(): response = urllib.request.urlopen(sys.argv[1]) html = response.read() print(html) sys.stdout.flush() karl_morrison_is_a_pedant() p.s. not a contrived example since node's http module doesn't load a few requests I need to make A: You could take your python, transpile it, and then call it as if it were javascript. I have done this succesfully for screeps and even got it to run in the browser a la brython. A: The Boa is good for your needs, see the example which extends Python tensorflow keras.Sequential class in JavaScript. const fs = require('fs'); const boa = require('@pipcook/boa'); const { tuple, enumerate } = boa.builtins(); const tf = boa.import('tensorflow'); const tfds = boa.import('tensorflow_datasets'); const { keras } = tf; const { layers } = keras; const [ [ train_data, test_data ], info ] = tfds.load('imdb_reviews/subwords8k', boa.kwargs({ split: tuple([ tfds.Split.TRAIN, tfds.Split.TEST ]), with_info: true, as_supervised: true })); const encoder = info.features['text'].encoder; const padded_shapes = tuple([ [ null ], tuple([]) ]); const train_batches = train_data.shuffle(1000) .padded_batch(10, boa.kwargs({ padded_shapes })); const test_batches = test_data.shuffle(1000) .padded_batch(10, boa.kwargs({ padded_shapes })); const embedding_dim = 16; const model = keras.Sequential([ layers.Embedding(encoder.vocab_size, embedding_dim), layers.GlobalAveragePooling1D(), layers.Dense(16, boa.kwargs({ activation: 'relu' })), layers.Dense(1, boa.kwargs({ activation: 'sigmoid' })) ]); model.summary(); model.compile(boa.kwargs({ optimizer: 'adam', loss: 'binary_crossentropy', metrics: [ 'accuracy' ] })); The complete example is at: https://github.com/alibaba/pipcook/blob/master/example/boa/tf2/word-embedding.js I used Boa in another project Pipcook, which is to address the machine learning problems for JavaScript developers, we implemented ML/DL models upon the Python ecosystem(tensorflow,keras,pytorch) by the boa library. A: /*eslint-env es6*/ /*global require*/ /*global console*/ var express = require('express'); var app = express(); // Creates a server which runs on port 3000 and // can be accessed through localhost:3000 app.listen(3000, function() { console.log('server running on port 3000'); } ) app.get('/name', function(req, res) { console.log('Running'); // Use child_process.spawn method from // child_process module and assign it // to variable spawn var spawn = require("child_process").spawn; // Parameters passed in spawn - // 1. type_of_script // 2. list containing Path of the script // and arguments for the script // E.g : http://localhost:3000/name?firstname=Levente var process = spawn('python',['apiTest.py', req.query.firstname]); // Takes stdout data from script which executed // with arguments and send this data to res object var output = ''; process.stdout.on('data', function(data) { console.log("Sending Info") res.end(data.toString('utf8')); }); console.log(output); }); This worked for me. Your python.exe must be added to you path variables for this code snippet. Also, make sure your python script is in your project folder. A: const util = require('util'); const exec = util.promisify(require('child_process').exec); function runPythonFile() { const { stdout, stderr } = await exec('py ./path_to_python_file -s asdf -d pqrs'); if (stdout) { // do something } if (stderr) { // do something } } For more information visit official Nodejs child process page: https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback A: Yes, there are several ways that you can call Python functions from your Node.js application to use machine learning libraries. One way to do this is to use the child_process module in Node.js to run a Python script as a separate process and pass data to it through standard input (stdin) and receive data back through standard output (stdout). Here is an example of how you could do this: // Import the child_process module const { spawn } = require('child_process'); // Define the data to pass to the Python script const data = { input: [1, 2, 3, 4, 5] }; // Spawn a new Python process const python = spawn('python', ['script.py']); // Write the data to the stdin of the Python process python.stdin.write(JSON.stringify(data)); python.stdin.end(); // Listen for data from the stdout of the Python process python.stdout.on('data', (output) => { // Parse the output data as JSON const result = JSON.parse(output); // Use the result from the Python script console.log(result); }); In this example, the spawn() function is used to start a new Python process and run the script.py script. The data to be passed to the script is defined in the data variable, and then written to the stdin of the Python process using the write() method. The data event is listened for on the stdout of the Python process, and the output data is parsed as JSON and used as needed. Another way to call Python functions from your Node.js application is to use a third-party library like python-shell or python-bridge. These libraries provide an API for calling Python functions directly from Node.js, without the need to spawn a separate Python process. I hope this helps! Let me know if you have any other questions.
How to call a Python function from Node.js
I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application to make use of the power of machine learning libraries?
[ "Easiest way I know of is to use \"child_process\" package which comes packaged with node.\nThen you can do something like:\nconst spawn = require(\"child_process\").spawn;\nconst pythonProcess = spawn('python',[\"path/to/script.py\", arg1, arg2, ...]);\n\nThen all you have to do is make sure that you import sys in your python script, and then you can access arg1 using sys.argv[1], arg2 using sys.argv[2], and so on.\nTo send data back to node just do the following in the python script:\nprint(dataToSendBack)\nsys.stdout.flush()\n\nAnd then node can listen for data using:\npythonProcess.stdout.on('data', (data) => {\n // Do something with the data returned from python script\n});\n\nSince this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc.\nHope this was clear. Let me know if something needs clarification.\n", "Example for people who are from Python background and want to integrate their machine learning model in the Node.js application:\nIt uses the child_process core module:\nconst express = require('express')\nconst app = express()\n\napp.get('/', (req, res) => {\n\n const { spawn } = require('child_process');\n const pyProg = spawn('python', ['./../pypy.py']);\n\n pyProg.stdout.on('data', function(data) {\n\n console.log(data.toString());\n res.write(data);\n res.end('end');\n });\n})\n\napp.listen(4000, () => console.log('Application listening on port 4000!'))\n\nIt doesn't require sys module in your Python script.\nBelow is a more modular way of performing the task using Promise:\nconst express = require('express')\nconst app = express()\n\nlet runPy = new Promise(function(success, nosuccess) {\n\n const { spawn } = require('child_process');\n const pyprog = spawn('python', ['./../pypy.py']);\n\n pyprog.stdout.on('data', function(data) {\n\n success(data);\n });\n\n pyprog.stderr.on('data', (data) => {\n\n nosuccess(data);\n });\n});\n\napp.get('/', (req, res) => {\n\n res.write('welcome\\n');\n\n runPy.then(function(fromRunpy) {\n console.log(fromRunpy.toString());\n res.end(fromRunpy);\n });\n})\n\napp.listen(4000, () => console.log('Application listening on port 4000!'))\n\n", "The python-shell module by extrabacon is a simple way to run Python scripts from Node.js with basic, but efficient inter-process communication and better error handling.\nInstallation:\nWith npm:\nnpm install python-shell.\nOr with yarn:\nyarn add python-shell\nRunning a simple Python script:\nconst PythonShell = require('python-shell').PythonShell;\n\nPythonShell.run('my_script.py', null, function (err) {\n if (err) throw err;\n console.log('finished');\n});\n\nRunning a Python script with arguments and options:\nconst PythonShell = require('python-shell').PythonShell;\n\nvar options = {\n mode: 'text',\n pythonPath: 'path/to/python',\n pythonOptions: ['-u'],\n scriptPath: 'path/to/my/scripts',\n args: ['value1', 'value2', 'value3']\n};\n\nPythonShell.run('my_script.py', options, function (err, results) {\n if (err) \n throw err;\n // Results is an array consisting of messages collected during execution\n console.log('results: %j', results);\n});\n\nFor the full documentation and source code, check out https://github.com/extrabacon/python-shell\n", "You can now use RPC libraries that support Python and Javascript such as zerorpc\nFrom their front page:\nNode.js Client\nvar zerorpc = require(\"zerorpc\");\n\nvar client = new zerorpc.Client();\nclient.connect(\"tcp://127.0.0.1:4242\");\n\nclient.invoke(\"hello\", \"RPC\", function(error, res, more) {\n console.log(res);\n});\n\nPython Server\nimport zerorpc\n\nclass HelloRPC(object):\n def hello(self, name):\n return \"Hello, %s\" % name\n\ns = zerorpc.Server(HelloRPC())\ns.bind(\"tcp://0.0.0.0:4242\")\ns.run()\n\n", "Many of the examples are years out of date and involve complex setup. You can give JSPyBridge/pythonia a try (full disclosure: I'm the author). It's vanilla JS that lets you operate on foreign Python objects as if they existed in JS. In fact, it does interoperability so Python code can in return call JS through callbacks and passed functions.\nnumpy + matplotlib example, with the ES6 import system:\nimport { py, python } from 'pythonia'\nconst np = await python('numpy')\nconst plot = await python('matplotlib.pyplot')\n\n// Fixing random state for reproducibility\nawait np.random.seed(19680801)\nconst [mu, sigma] = [100, 15]\n// Inline expression evaluation for operator overloading\nconst x = await py`${mu} + ${sigma} * ${np.random.randn(10000)}`\n\n// the histogram of the data\nconst [n, bins, patches] = await plot.hist$(x, 50, { density: true, facecolor: 'g', alpha: 0.75 })\nconsole.log('Distribution', await n) // Always await for all Python access\nawait plot.show()\npython.exit()\n\nThrough CommonJS (without top level await):\nconst { py, python } = require('pythonia')\nasync function main() {\n const np = await python('numpy')\n const plot = await python('matplotlib.pyplot')\n ...\n // the rest of the code\n}\nmain().then(() => python.exit()) // If you don't call this, the process won't quit by itself.\n\n", "Most of previous answers call the success of the promise in the on(\"data\"), it is not the proper way to do it because if you receive a lot of data you will only get the first part. Instead you have to do it on the end event.\nconst { spawn } = require('child_process');\nconst pythonDir = (__dirname + \"/../pythonCode/\"); // Path of python script folder\nconst python = pythonDir + \"pythonEnv/bin/python\"; // Path of the Python interpreter\n\n/** remove warning that you don't care about */\nfunction cleanWarning(error) {\n return error.replace(/Detector is not able to detect the language reliably.\\n/g,\"\");\n}\n\nfunction callPython(scriptName, args) {\n return new Promise(function(success, reject) {\n const script = pythonDir + scriptName;\n const pyArgs = [script, JSON.stringify(args) ]\n const pyprog = spawn(python, pyArgs );\n let result = \"\";\n let resultError = \"\";\n pyprog.stdout.on('data', function(data) {\n result += data.toString();\n });\n\n pyprog.stderr.on('data', (data) => {\n resultError += cleanWarning(data.toString());\n });\n\n pyprog.stdout.on(\"end\", function(){\n if(resultError == \"\") {\n success(JSON.parse(result));\n }else{\n console.error(`Python error, you can reproduce the error with: \\n${python} ${script} ${pyArgs.join(\" \")}`);\n const error = new Error(resultError);\n console.error(error);\n reject(resultError);\n }\n })\n });\n}\nmodule.exports.callPython = callPython;\n\nCall: \nconst pythonCaller = require(\"../core/pythonCaller\");\nconst result = await pythonCaller.callPython(\"preprocessorSentiment.py\", {\"thekeyYouwant\": value});\n\npython:\ntry:\n argu = json.loads(sys.argv[1])\nexcept:\n raise Exception(\"error while loading argument\")\n\n", "I'm on node 10 and child process 1.0.2. The data from python is a byte array and has to be converted. Just another quick example of making a http request in python.\nnode\nconst process = spawn(\"python\", [\"services/request.py\", \"https://www.google.com\"])\n\nreturn new Promise((resolve, reject) =>{\n process.stdout.on(\"data\", data =>{\n resolve(data.toString()); // <------------ by default converts to utf-8\n })\n process.stderr.on(\"data\", reject)\n})\n\nrequest.py\nimport urllib.request\nimport sys\n\ndef karl_morrison_is_a_pedant(): \n response = urllib.request.urlopen(sys.argv[1])\n html = response.read()\n print(html)\n sys.stdout.flush()\n\nkarl_morrison_is_a_pedant()\n\np.s. not a contrived example since node's http module doesn't load a few requests I need to make\n", "You could take your python, transpile it, and then call it as if it were javascript. I have done this succesfully for screeps and even got it to run in the browser a la brython.\n", "The Boa is good for your needs, see the example which extends Python tensorflow keras.Sequential class in JavaScript.\nconst fs = require('fs');\nconst boa = require('@pipcook/boa');\nconst { tuple, enumerate } = boa.builtins();\n\nconst tf = boa.import('tensorflow');\nconst tfds = boa.import('tensorflow_datasets');\n\nconst { keras } = tf;\nconst { layers } = keras;\n\nconst [\n [ train_data, test_data ],\n info\n] = tfds.load('imdb_reviews/subwords8k', boa.kwargs({\n split: tuple([ tfds.Split.TRAIN, tfds.Split.TEST ]),\n with_info: true,\n as_supervised: true\n}));\n\nconst encoder = info.features['text'].encoder;\nconst padded_shapes = tuple([\n [ null ], tuple([])\n]);\nconst train_batches = train_data.shuffle(1000)\n .padded_batch(10, boa.kwargs({ padded_shapes }));\nconst test_batches = test_data.shuffle(1000)\n .padded_batch(10, boa.kwargs({ padded_shapes }));\n\nconst embedding_dim = 16;\nconst model = keras.Sequential([\n layers.Embedding(encoder.vocab_size, embedding_dim),\n layers.GlobalAveragePooling1D(),\n layers.Dense(16, boa.kwargs({ activation: 'relu' })),\n layers.Dense(1, boa.kwargs({ activation: 'sigmoid' }))\n]);\n\nmodel.summary();\nmodel.compile(boa.kwargs({\n optimizer: 'adam',\n loss: 'binary_crossentropy',\n metrics: [ 'accuracy' ]\n}));\n\n\nThe complete example is at: https://github.com/alibaba/pipcook/blob/master/example/boa/tf2/word-embedding.js\n\nI used Boa in another project Pipcook, which is to address the machine learning problems for JavaScript developers, we implemented ML/DL models upon the Python ecosystem(tensorflow,keras,pytorch) by the boa library.\n", "/*eslint-env es6*/\n/*global require*/\n/*global console*/\nvar express = require('express'); \nvar app = express();\n\n// Creates a server which runs on port 3000 and \n// can be accessed through localhost:3000\napp.listen(3000, function() { \n console.log('server running on port 3000'); \n} ) \n\napp.get('/name', function(req, res) {\n\n console.log('Running');\n\n // Use child_process.spawn method from \n // child_process module and assign it \n // to variable spawn \n var spawn = require(\"child_process\").spawn; \n // Parameters passed in spawn - \n // 1. type_of_script \n // 2. list containing Path of the script \n // and arguments for the script \n\n // E.g : http://localhost:3000/name?firstname=Levente\n var process = spawn('python',['apiTest.py', \n req.query.firstname]);\n\n // Takes stdout data from script which executed \n // with arguments and send this data to res object\n var output = '';\n process.stdout.on('data', function(data) {\n\n console.log(\"Sending Info\")\n res.end(data.toString('utf8'));\n });\n\n console.log(output);\n}); \n\nThis worked for me. Your python.exe must be added to you path variables for this code snippet. Also, make sure your python script is in your project folder.\n", "const util = require('util');\nconst exec = util.promisify(require('child_process').exec);\n \nfunction runPythonFile() {\n const { stdout, stderr } = await exec('py ./path_to_python_file -s asdf -d pqrs');\n if (stdout) { // do something }\n if (stderr) { // do something }\n}\n\nFor more information visit official Nodejs child process page: https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback\n", "Yes, there are several ways that you can call Python functions from your Node.js application to use machine learning libraries. One way to do this is to use the child_process module in Node.js to run a Python script as a separate process and pass data to it through standard input (stdin) and receive data back through standard output (stdout). Here is an example of how you could do this:\n// Import the child_process module\nconst { spawn } = require('child_process');\n\n// Define the data to pass to the Python script\nconst data = {\n input: [1, 2, 3, 4, 5]\n};\n\n// Spawn a new Python process\nconst python = spawn('python', ['script.py']);\n\n// Write the data to the stdin of the Python process\npython.stdin.write(JSON.stringify(data));\npython.stdin.end();\n\n// Listen for data from the stdout of the Python process\npython.stdout.on('data', (output) => {\n // Parse the output data as JSON\n const result = JSON.parse(output);\n\n // Use the result from the Python script\n console.log(result);\n});\n\n\nIn this example, the spawn() function is used to start a new Python process and run the script.py script. The data to be passed to the script is defined in the data variable, and then written to the stdin of the Python process using the write() method. The data event is listened for on the stdout of the Python process, and the output data is parsed as JSON and used as needed.\nAnother way to call Python functions from your Node.js application is to use a third-party library like python-shell or python-bridge. These libraries provide an API for calling Python functions directly from Node.js, without the need to spawn a separate Python process.\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 357, 201, 55, 15, 10, 9, 4, 3, 3, 2, 0, 0 ]
[]
[]
[ "express", "node.js", "python" ]
stackoverflow_0023450534_express_node.js_python.txt
Q: Create new column using custom function pandas df error I want to create a new column which gives every row a category based on their value in one specific column. Here is the function: def assign_category(df): if df['AvgVAA'] >= -4: return 'Elite' elif df['AvgVAA'] <= -4 and df['AvgVAA'] > -4.5: return 'Above Average' elif df['AvgVAA'] <= -4.5 and df['AvgVAA'] > -5: return 'Average' elif df['AvgVAA'] <= -5 and df['AvgVAA'] > -5.5: return 'Below Average' elif df['AvgVAA'] <= -5.5: return 'Mediocre' I get this error message in the second line: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). This is the code to create the new column: df_upd['VAA Category'] = df_upd.apply(assign_category(df_upd), axis = 1) I did some research on it, but the explanation did not help me because it was mainly about and operators, which are not used in that line. I do not know why, but the error message did not come up when I first ran the code. But even at that time, the function did not work. Every row in that new column was filled with 'Unknown'. Can someoen help me out here? A: You're so close. Instead of: df_upd.apply(assign_category(df_upd), axis = 1) Use: df_upd.apply(assign_category, axis = 1) In the updated approach, you are applying the function to df_upd (as intended), whereas in the original approach, you are essentially doing: x = assign_category(df) df.apply(x, axis = 1) The error comes when you try to calculate x since you need to apply along axis 1.
Create new column using custom function pandas df error
I want to create a new column which gives every row a category based on their value in one specific column. Here is the function: def assign_category(df): if df['AvgVAA'] >= -4: return 'Elite' elif df['AvgVAA'] <= -4 and df['AvgVAA'] > -4.5: return 'Above Average' elif df['AvgVAA'] <= -4.5 and df['AvgVAA'] > -5: return 'Average' elif df['AvgVAA'] <= -5 and df['AvgVAA'] > -5.5: return 'Below Average' elif df['AvgVAA'] <= -5.5: return 'Mediocre' I get this error message in the second line: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). This is the code to create the new column: df_upd['VAA Category'] = df_upd.apply(assign_category(df_upd), axis = 1) I did some research on it, but the explanation did not help me because it was mainly about and operators, which are not used in that line. I do not know why, but the error message did not come up when I first ran the code. But even at that time, the function did not work. Every row in that new column was filled with 'Unknown'. Can someoen help me out here?
[ "You're so close. Instead of:\ndf_upd.apply(assign_category(df_upd), axis = 1)\n\nUse:\ndf_upd.apply(assign_category, axis = 1)\n\nIn the updated approach, you are applying the function to df_upd (as intended), whereas in the original approach, you are essentially doing:\nx = assign_category(df)\ndf.apply(x, axis = 1)\n\nThe error comes when you try to calculate x since you need to apply along axis 1.\n" ]
[ 2 ]
[]
[]
[ "apply", "function", "pandas", "python" ]
stackoverflow_0074663358_apply_function_pandas_python.txt
Q: How do I separate text after using BeautifulSoup in order to plot? I am trying to make a program that scrapes the data from open insider and take that data and plot it. Open insider shows what insiders of the company are buying or selling the stock. I want to be able to show, in an easy to read format, what company, insider type and how much of the stock was purchased. Here is my code so far: from bs4 import BeautifulSoup import requests page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month") '''print(page.status_code) checks to see if the page was downloaded successfully''' soup = BeautifulSoup(page.content,'html.parser') table = soup.find(class_="tinytable") data = table.get_text() #results = data.prettify print(data, '\n') Here is an example of some of the results: X Filing Date Trade Date Ticker Company NameInsider NameTitle Trade Type   Price Qty Owned ΔOwn Value 1d 1w 1m 6m 2022-12-01 16:10:122022-11-30 AKUSAkouos, Inc.Kearny Acquisition Corp10%P - Purchase$12.50+29,992,668100-100%+$374,908,350 2022-11-30 20:57:192022-11-29 HHCHoward Hughes CorpPershing Square Capital Management, L.P.Dir, 10%P - Purchase$70.00+1,560,20515,180,369+11%+$109,214,243 2022-12-02 17:29:182022-12-02 IOVAIovance Biotherapeutics, Inc.Rothbaum Wayne P.DirP - Purchase$6.50+10,000,00018,067,333+124%+$65,000,000 However, for me each year starts a new line. Is there a better way to use BeautifulSoup? Or is there an easy way to sort through this data and retrieve the specific information I am looking for? Thank You in advance I have been stuck on this for a while. A: What Julian said then store values in a dict, load it into a Pandas dataframe and visualize it with plotly.express.
How do I separate text after using BeautifulSoup in order to plot?
I am trying to make a program that scrapes the data from open insider and take that data and plot it. Open insider shows what insiders of the company are buying or selling the stock. I want to be able to show, in an easy to read format, what company, insider type and how much of the stock was purchased. Here is my code so far: from bs4 import BeautifulSoup import requests page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month") '''print(page.status_code) checks to see if the page was downloaded successfully''' soup = BeautifulSoup(page.content,'html.parser') table = soup.find(class_="tinytable") data = table.get_text() #results = data.prettify print(data, '\n') Here is an example of some of the results: X Filing Date Trade Date Ticker Company NameInsider NameTitle Trade Type   Price Qty Owned ΔOwn Value 1d 1w 1m 6m 2022-12-01 16:10:122022-11-30 AKUSAkouos, Inc.Kearny Acquisition Corp10%P - Purchase$12.50+29,992,668100-100%+$374,908,350 2022-11-30 20:57:192022-11-29 HHCHoward Hughes CorpPershing Square Capital Management, L.P.Dir, 10%P - Purchase$70.00+1,560,20515,180,369+11%+$109,214,243 2022-12-02 17:29:182022-12-02 IOVAIovance Biotherapeutics, Inc.Rothbaum Wayne P.DirP - Purchase$6.50+10,000,00018,067,333+124%+$65,000,000 However, for me each year starts a new line. Is there a better way to use BeautifulSoup? Or is there an easy way to sort through this data and retrieve the specific information I am looking for? Thank You in advance I have been stuck on this for a while.
[ "What Julian said then store values in a dict, load it into a Pandas dataframe and visualize it with plotly.express.\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074663423_beautifulsoup_python.txt
Q: What is a pandas.core.Frame.DataFrame, and how to convert it to pd.DataFrame? Currently I was trying to do a machine learning classification of 6 time series datasets (in .csv format) using MiniRocket, an sktime machine learning package. However, when I imported the .csv files using pd.read_csv and run them through MiniRocket, the error "TypeError: X must be in an sktime compatible format" pops up, and it says that the following data types are sktime compatible: ['pd.Series', 'pd.DataFrame', 'np.ndarray', 'nested_univ', 'numpy3D', 'pd-multiindex', 'df-list', 'pd_multiindex_hier'] Then I checked the data type of my imported .csv files and got "pandas.core.Frame.DataFrame", which is a data type that I never saw before and is obviously different from the sktime compatible pd.DataFrame. What is the difference between pandas.core.Frame.DataFrame and pd.DataFrame, and how to convert pandas.core.Frame.DataFrame to the sktime compatible pd.DataFrame? I tried to convert pandas.core.Frame.DataFrame to pd.DataFrame using df.join and df.pop functions, but neither of them was able to convert my data from pandas.core.Frame.DataFrame to pd.DataFrame (after conversion I checked the type again and it is still the same). A: If you just take the values from your old DataFrame with .values, you can create a new DataFrame the standard way. If you want to keep the same columns and index values, just set those when you declare your new DataFrame. df_new = pd.DataFrame(df_old.values, columns=df_old.columns, index=df_old.index) A: Most of the pandas classes are defined under pandas.core folder: https://github.com/pandas-dev/pandas/tree/main/pandas/core. For example, class DataFrame is defined in pandas.core.frame.py: class DataFrame(NDFrame, OpsMixin): ... def __init__(...) ... Pandas is not yet a py.typed library PEP 561, hence the public API documentation uses pandas.DataFrame but internally all error messages still refer to the source file structure such as pandas.core.frame.DataFrame.
What is a pandas.core.Frame.DataFrame, and how to convert it to pd.DataFrame?
Currently I was trying to do a machine learning classification of 6 time series datasets (in .csv format) using MiniRocket, an sktime machine learning package. However, when I imported the .csv files using pd.read_csv and run them through MiniRocket, the error "TypeError: X must be in an sktime compatible format" pops up, and it says that the following data types are sktime compatible: ['pd.Series', 'pd.DataFrame', 'np.ndarray', 'nested_univ', 'numpy3D', 'pd-multiindex', 'df-list', 'pd_multiindex_hier'] Then I checked the data type of my imported .csv files and got "pandas.core.Frame.DataFrame", which is a data type that I never saw before and is obviously different from the sktime compatible pd.DataFrame. What is the difference between pandas.core.Frame.DataFrame and pd.DataFrame, and how to convert pandas.core.Frame.DataFrame to the sktime compatible pd.DataFrame? I tried to convert pandas.core.Frame.DataFrame to pd.DataFrame using df.join and df.pop functions, but neither of them was able to convert my data from pandas.core.Frame.DataFrame to pd.DataFrame (after conversion I checked the type again and it is still the same).
[ "If you just take the values from your old DataFrame with .values, you can create a new DataFrame the standard way. If you want to keep the same columns and index values, just set those when you declare your new DataFrame.\ndf_new = pd.DataFrame(df_old.values, columns=df_old.columns, index=df_old.index)\n\n", "Most of the pandas classes are defined under pandas.core folder: https://github.com/pandas-dev/pandas/tree/main/pandas/core.\nFor example, class DataFrame is defined in pandas.core.frame.py:\nclass DataFrame(NDFrame, OpsMixin):\n ...\n\ndef __init__(...)\n ...\n\nPandas is not yet a py.typed library PEP 561, hence the public API documentation uses pandas.DataFrame but internally all error messages still refer to the source file structure such as pandas.core.frame.DataFrame.\n" ]
[ 0, 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074663328_csv_dataframe_pandas_python_python_3.x.txt
Q: What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow? What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow? In my opinion, 'VALID' means there will be no zero padding outside the edges when we do max pool. According to A guide to convolution arithmetic for deep learning, it says that there will be no padding in pool operator, i.e. just use 'VALID' of tensorflow. But what is 'SAME' padding of max pool in tensorflow? A: If you like ascii art: "VALID" = without padding: inputs: 1 2 3 4 5 6 7 8 9 10 11 (12 13) |________________| dropped |_________________| "SAME" = with zero padding: pad| |pad inputs: 0 |1 2 3 4 5 6 7 8 9 10 11 12 13|0 0 |________________| |_________________| |________________| In this example: Input width = 13 Filter width = 6 Stride = 5 Notes: "VALID" only ever drops the right-most columns (or bottom-most rows). "SAME" tries to pad evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right, as is the case in this example (the same logic applies vertically: there may be an extra row of zeros at the bottom). Edit: About the name: With "SAME" padding, if you use a stride of 1, the layer's outputs will have the same spatial dimensions as its inputs. With "VALID" padding, there's no "made-up" padding inputs. The layer only uses valid input data. A: When stride is 1 (more typical with convolution than pooling), we can think of the following distinction: "SAME": output size is the same as input size. This requires the filter window to slip outside input map, hence the need to pad. "VALID": Filter window stays at valid position inside input map, so output size shrinks by filter_size - 1. No padding occurs. A: I'll give an example to make it clearer: x: input image of shape [2, 3], 1 channel valid_pad: max pool with 2x2 kernel, stride 2 and VALID padding. same_pad: max pool with 2x2 kernel, stride 2 and SAME padding (this is the classic way to go) The output shapes are: valid_pad: here, no padding so the output shape is [1, 1] same_pad: here, we pad the image to the shape [2, 4] (with -inf and then apply max pool), so the output shape is [1, 2] x = tf.constant([[1., 2., 3.], [4., 5., 6.]]) x = tf.reshape(x, [1, 2, 3, 1]) # give a shape accepted by tf.nn.max_pool valid_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID') same_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME') valid_pad.get_shape() == [1, 1, 1, 1] # valid_pad is [5.] same_pad.get_shape() == [1, 1, 2, 1] # same_pad is [5., 6.] A: The TensorFlow Convolution example gives an overview about the difference between SAME and VALID : For the SAME padding, the output height and width are computed as: out_height = ceil(float(in_height) / float(strides[1])) out_width = ceil(float(in_width) / float(strides[2])) And For the VALID padding, the output height and width are computed as: out_height = ceil(float(in_height - filter_height + 1) / float(strides[1])) out_width = ceil(float(in_width - filter_width + 1) / float(strides[2])) A: Complementing YvesgereY's great answer, I found this visualization extremely helpful: Padding 'valid' is the first figure. The filter window stays inside the image. Padding 'same' is the third figure. The output is the same size. Found it on this article Visualization credits: vdumoulin@GitHub A: Padding is an operation to increase the size of the input data. In case of 1-dimensional data you just append/prepend the array with a constant, in 2-dim you surround matrix with these constants. In n-dim you surround your n-dim hypercube with the constant. In most of the cases this constant is zero and it is called zero-padding. Here is an example of zero-padding with p=1 applied to 2-d tensor: You can use arbitrary padding for your kernel but some of the padding values are used more frequently than others they are: VALID padding. The easiest case, means no padding at all. Just leave your data the same it was. SAME padding sometimes called HALF padding. It is called SAME because for a convolution with a stride=1, (or for pooling) it should produce output of the same size as the input. It is called HALF because for a kernel of size k FULL padding is the maximum padding which does not result in a convolution over just padded elements. For a kernel of size k, this padding is equal to k - 1. To use arbitrary padding in TF, you can use tf.pad() A: Quick Explanation VALID: Don't apply any padding, i.e., assume that all dimensions are valid so that input image fully gets covered by filter and stride you specified. SAME: Apply padding to input (if needed) so that input image gets fully covered by filter and stride you specified. For stride 1, this will ensure that output image size is same as input. Notes This applies to conv layers as well as max pool layers in same way The term "valid" is bit of a misnomer because things don't become "invalid" if you drop part of the image. Sometime you might even want that. This should have probably be called NO_PADDING instead. The term "same" is a misnomer too because it only makes sense for stride of 1 when output dimension is same as input dimension. For stride of 2, output dimensions will be half, for example. This should have probably be called AUTO_PADDING instead. In SAME (i.e. auto-pad mode), Tensorflow will try to spread padding evenly on both left and right. In VALID (i.e. no padding mode), Tensorflow will drop right and/or bottom cells if your filter and stride doesn't full cover input image. A: I am quoting this answer from official tensorflow docs https://www.tensorflow.org/api_guides/python/nn#Convolution For the 'SAME' padding, the output height and width are computed as: out_height = ceil(float(in_height) / float(strides[1])) out_width = ceil(float(in_width) / float(strides[2])) and the padding on the top and left are computed as: pad_along_height = max((out_height - 1) * strides[1] + filter_height - in_height, 0) pad_along_width = max((out_width - 1) * strides[2] + filter_width - in_width, 0) pad_top = pad_along_height // 2 pad_bottom = pad_along_height - pad_top pad_left = pad_along_width // 2 pad_right = pad_along_width - pad_left For the 'VALID' padding, the output height and width are computed as: out_height = ceil(float(in_height - filter_height + 1) / float(strides[1])) out_width = ceil(float(in_width - filter_width + 1) / float(strides[2])) and the padding values are always zero. A: There are three choices of padding: valid (no padding), same (or half), full. You can find explanations (in Theano) here: http://deeplearning.net/software/theano/tutorial/conv_arithmetic.html Valid or no padding: The valid padding involves no zero padding, so it covers only the valid input, not including artificially generated zeros. The length of output is ((the length of input) - (k-1)) for the kernel size k if the stride s=1. Same or half padding: The same padding makes the size of outputs be the same with that of inputs when s=1. If s=1, the number of zeros padded is (k-1). Full padding: The full padding means that the kernel runs over the whole inputs, so at the ends, the kernel may meet the only one input and zeros else. The number of zeros padded is 2(k-1) if s=1. The length of output is ((the length of input) + (k-1)) if s=1. Therefore, the number of paddings: (valid) <= (same) <= (full) A: VALID padding: this is with zero padding. Hope there is no confusion. x = tf.constant([[1., 2., 3.], [4., 5., 6.],[ 7., 8., 9.], [ 7., 8., 9.]]) x = tf.reshape(x, [1, 4, 3, 1]) valid_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID') print (valid_pad.get_shape()) # output-->(1, 2, 1, 1) SAME padding: This is kind of tricky to understand in the first place because we have to consider two conditions separately as mentioned in the official docs. Let's take input as , output as , padding as , stride as and kernel size as (only a single dimension is considered) Case 01: : Case 02: : is calculated such that the minimum value which can be taken for padding. Since value of is known, value of can be found using this formula . Let's work out this example: x = tf.constant([[1., 2., 3.], [4., 5., 6.],[ 7., 8., 9.], [ 7., 8., 9.]]) x = tf.reshape(x, [1, 4, 3, 1]) same_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME') print (same_pad.get_shape()) # --> output (1, 2, 2, 1) Here the dimension of x is (3,4). Then if the horizontal direction is taken (3): If the vertial direction is taken (4): Hope this will help to understand how actually SAME padding works in TF. A: To sum up, 'valid' padding means no padding. The output size of the convolutional layer shrinks depending on the input size & kernel size. On the contrary, 'same' padding means using padding. When the stride is set as 1, the output size of the convolutional layer maintains as the input size by appending a certain number of '0-border' around the input data when calculating convolution. Hope this intuitive description helps. A: Based on the explanation here and following up on Tristan's answer, I usually use these quick functions for sanity checks. # a function to help us stay clean def getPaddings(pad_along_height,pad_along_width): # if even.. easy.. if pad_along_height%2 == 0: pad_top = pad_along_height / 2 pad_bottom = pad_top # if odd else: pad_top = np.floor( pad_along_height / 2 ) pad_bottom = np.floor( pad_along_height / 2 ) +1 # check if width padding is odd or even # if even.. easy.. if pad_along_width%2 == 0: pad_left = pad_along_width / 2 pad_right= pad_left # if odd else: pad_left = np.floor( pad_along_width / 2 ) pad_right = np.floor( pad_along_width / 2 ) +1 # return pad_top,pad_bottom,pad_left,pad_right # strides [image index, y, x, depth] # padding 'SAME' or 'VALID' # bottom and right sides always get the one additional padded pixel (if padding is odd) def getOutputDim (inputWidth,inputHeight,filterWidth,filterHeight,strides,padding): if padding == 'SAME': out_height = np.ceil(float(inputHeight) / float(strides[1])) out_width = np.ceil(float(inputWidth) / float(strides[2])) # pad_along_height = ((out_height - 1) * strides[1] + filterHeight - inputHeight) pad_along_width = ((out_width - 1) * strides[2] + filterWidth - inputWidth) # # now get padding pad_top,pad_bottom,pad_left,pad_right = getPaddings(pad_along_height,pad_along_width) # print 'output height', out_height print 'output width' , out_width print 'total pad along height' , pad_along_height print 'total pad along width' , pad_along_width print 'pad at top' , pad_top print 'pad at bottom' ,pad_bottom print 'pad at left' , pad_left print 'pad at right' ,pad_right elif padding == 'VALID': out_height = np.ceil(float(inputHeight - filterHeight + 1) / float(strides[1])) out_width = np.ceil(float(inputWidth - filterWidth + 1) / float(strides[2])) # print 'output height', out_height print 'output width' , out_width print 'no padding' # use like so getOutputDim (80,80,4,4,[1,1,1,1],'SAME') A: Padding on/off. Determines the effective size of your input. VALID: No padding. Convolution etc. ops are only performed at locations that are "valid", i.e. not too close to the borders of your tensor. With a kernel of 3x3 and image of 10x10, you would be performing convolution on the 8x8 area inside the borders. SAME: Padding is provided. Whenever your operation references a neighborhood (no matter how big), zero values are provided when that neighborhood extends outside the original tensor to allow that operation to work also on border values. With a kernel of 3x3 and image of 10x10, you would be performing convolution on the full 10x10 area. A: Here, W and H are width and height of input, F are filter dimensions, P is padding size (i.e., number of rows or columns to be padded) For SAME padding: For VALID padding: A: Tensorflow 2.0 Compatible Answer: Detailed Explanations have been provided above, about "Valid" and "Same" Padding. However, I will specify different Pooling Functions and their respective Commands in Tensorflow 2.x (>= 2.0), for the benefit of the community. Functions in 1.x: tf.nn.max_pool tf.keras.layers.MaxPool2D Average Pooling => None in tf.nn, tf.keras.layers.AveragePooling2D Functions in 2.x: tf.nn.max_pool if used in 2.x and tf.compat.v1.nn.max_pool_v2 or tf.compat.v2.nn.max_pool, if migrated from 1.x to 2.x. tf.keras.layers.MaxPool2D if used in 2.x and tf.compat.v1.keras.layers.MaxPool2D or tf.compat.v1.keras.layers.MaxPooling2D or tf.compat.v2.keras.layers.MaxPool2D or tf.compat.v2.keras.layers.MaxPooling2D, if migrated from 1.x to 2.x. Average Pooling => tf.nn.avg_pool2d or tf.keras.layers.AveragePooling2D if used in TF 2.x and tf.compat.v1.nn.avg_pool_v2 or tf.compat.v2.nn.avg_pool or tf.compat.v1.keras.layers.AveragePooling2D or tf.compat.v1.keras.layers.AvgPool2D or tf.compat.v2.keras.layers.AveragePooling2D or tf.compat.v2.keras.layers.AvgPool2D , if migrated from 1.x to 2.x. For more information about Migration from Tensorflow 1.x to 2.x, please refer to this Migration Guide. A: valid padding is no padding. same padding is padding in a way the output has the same size as input. A: In the TensorFlow function tf.nn.max_pool, the padding parameter determines how the input tensor is padded before the max pooling operation is applied. The 'VALID' padding option means that no padding will be applied to the input tensor, and the output tensor will have dimensions that are smaller than the input tensor. For example, if the input tensor has dimensions [batch_size, height, width, channels] and the max pooling window has dimensions [pool_height, pool_width], then the output tensor will have dimensions [batch_size, (height - pool_height + 1), (width - pool_width + 1), channels]. The 'SAME' padding option, on the other hand, means that the input tensor will be padded with zeros in such a way that the output tensor will have the same dimensions as the input tensor. The amount of padding applied to the input tensor will depend on the dimensions of the max pooling window and the stride size. For example, if the input tensor has dimensions [batch_size, height, width, channels] and the max pooling window has dimensions [pool_height, pool_width], and the stride is set to 1, then the output tensor will also have dimensions [batch_size, height, width, channels], and the input tensor will be padded with zeros on the top, bottom, left, and right sides as needed. In summary, the 'VALID' padding option means that no padding will be applied to the input tensor, and the output tensor will have dimensions that are smaller than the input tensor. The 'SAME' padding option means that the input tensor will be padded with zeros as needed to ensure that the output tensor has the same dimensions as the input tensor.
What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?
What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow? In my opinion, 'VALID' means there will be no zero padding outside the edges when we do max pool. According to A guide to convolution arithmetic for deep learning, it says that there will be no padding in pool operator, i.e. just use 'VALID' of tensorflow. But what is 'SAME' padding of max pool in tensorflow?
[ "If you like ascii art:\n\n\"VALID\" = without padding:\n inputs: 1 2 3 4 5 6 7 8 9 10 11 (12 13)\n |________________| dropped\n |_________________|\n\n\"SAME\" = with zero padding:\n pad| |pad\n inputs: 0 |1 2 3 4 5 6 7 8 9 10 11 12 13|0 0\n |________________|\n |_________________|\n |________________|\n\n\nIn this example:\n\nInput width = 13\nFilter width = 6\nStride = 5\n\nNotes:\n\n\"VALID\" only ever drops the right-most columns (or bottom-most rows).\n\"SAME\" tries to pad evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right, as is the case in this example (the same logic applies vertically: there may be an extra row of zeros at the bottom).\n\nEdit:\nAbout the name:\n\nWith \"SAME\" padding, if you use a stride of 1, the layer's outputs will have the same spatial dimensions as its inputs.\nWith \"VALID\" padding, there's no \"made-up\" padding inputs. The layer only uses valid input data.\n\n", "When stride is 1 (more typical with convolution than pooling), we can think of the following distinction:\n\n\"SAME\": output size is the same as input size. This requires the filter window to slip outside input map, hence the need to pad. \n\"VALID\": Filter window stays at valid position inside input map, so output size shrinks by filter_size - 1. No padding occurs.\n\n", "I'll give an example to make it clearer:\n\nx: input image of shape [2, 3], 1 channel\nvalid_pad: max pool with 2x2 kernel, stride 2 and VALID padding.\nsame_pad: max pool with 2x2 kernel, stride 2 and SAME padding (this is the classic way to go)\n\nThe output shapes are:\n\nvalid_pad: here, no padding so the output shape is [1, 1]\nsame_pad: here, we pad the image to the shape [2, 4] (with -inf and then apply max pool), so the output shape is [1, 2]\n\n\nx = tf.constant([[1., 2., 3.],\n [4., 5., 6.]])\n\nx = tf.reshape(x, [1, 2, 3, 1]) # give a shape accepted by tf.nn.max_pool\n\nvalid_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')\nsame_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n\nvalid_pad.get_shape() == [1, 1, 1, 1] # valid_pad is [5.]\nsame_pad.get_shape() == [1, 1, 2, 1] # same_pad is [5., 6.]\n\n\n", "The TensorFlow Convolution example gives an overview about the difference between SAME and VALID :\n\nFor the SAME padding, the output height and width are computed as:\n out_height = ceil(float(in_height) / float(strides[1]))\n out_width = ceil(float(in_width) / float(strides[2]))\n\n\n\nAnd\n\nFor the VALID padding, the output height and width are computed as:\n out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))\n out_width = ceil(float(in_width - filter_width + 1) / float(strides[2]))\n\n\n\n", "Complementing YvesgereY's great answer, I found this visualization extremely helpful:\n\nPadding 'valid' is the first figure. The filter window stays inside the image.\nPadding 'same' is the third figure. The output is the same size.\n\nFound it on this article\nVisualization credits: vdumoulin@GitHub\n", "Padding is an operation to increase the size of the input data. In case of 1-dimensional data you just append/prepend the array with a constant, in 2-dim you surround matrix with these constants. In n-dim you surround your n-dim hypercube with the constant. In most of the cases this constant is zero and it is called zero-padding.\nHere is an example of zero-padding with p=1 applied to 2-d tensor:\n\n\nYou can use arbitrary padding for your kernel but some of the padding values are used more frequently than others they are:\n\nVALID padding. The easiest case, means no padding at all. Just leave your data the same it was.\nSAME padding sometimes called HALF padding. It is called SAME because for a convolution with a stride=1, (or for pooling) it should produce output of the same size as the input. It is called HALF because for a kernel of size k \nFULL padding is the maximum padding which does not result in a convolution over just padded elements. For a kernel of size k, this padding is equal to k - 1.\n\n\nTo use arbitrary padding in TF, you can use tf.pad()\n", "Quick Explanation\nVALID: Don't apply any padding, i.e., assume that all dimensions are valid so that input image fully gets covered by filter and stride you specified.\nSAME: Apply padding to input (if needed) so that input image gets fully covered by filter and stride you specified. For stride 1, this will ensure that output image size is same as input.\nNotes\n\nThis applies to conv layers as well as max pool layers in same way\nThe term \"valid\" is bit of a misnomer because things don't become \"invalid\" if you drop part of the image. Sometime you might even want that. This should have probably be called NO_PADDING instead.\nThe term \"same\" is a misnomer too because it only makes sense for stride of 1 when output dimension is same as input dimension. For stride of 2, output dimensions will be half, for example. This should have probably be called AUTO_PADDING instead.\nIn SAME (i.e. auto-pad mode), Tensorflow will try to spread padding evenly on both left and right.\nIn VALID (i.e. no padding mode), Tensorflow will drop right and/or bottom cells if your filter and stride doesn't full cover input image.\n\n", "I am quoting this answer from official tensorflow docs https://www.tensorflow.org/api_guides/python/nn#Convolution\nFor the 'SAME' padding, the output height and width are computed as:\nout_height = ceil(float(in_height) / float(strides[1]))\nout_width = ceil(float(in_width) / float(strides[2]))\n\nand the padding on the top and left are computed as:\npad_along_height = max((out_height - 1) * strides[1] +\n filter_height - in_height, 0)\npad_along_width = max((out_width - 1) * strides[2] +\n filter_width - in_width, 0)\npad_top = pad_along_height // 2\npad_bottom = pad_along_height - pad_top\npad_left = pad_along_width // 2\npad_right = pad_along_width - pad_left\n\nFor the 'VALID' padding, the output height and width are computed as:\nout_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))\nout_width = ceil(float(in_width - filter_width + 1) / float(strides[2]))\n\nand the padding values are always zero.\n", "There are three choices of padding: valid (no padding), same (or half), full. You can find explanations (in Theano) here:\nhttp://deeplearning.net/software/theano/tutorial/conv_arithmetic.html\n\nValid or no padding:\n\nThe valid padding involves no zero padding, so it covers only the valid input, not including artificially generated zeros. The length of output is ((the length of input) - (k-1)) for the kernel size k if the stride s=1.\n\nSame or half padding:\n\nThe same padding makes the size of outputs be the same with that of inputs when s=1. If s=1, the number of zeros padded is (k-1).\n\nFull padding:\n\nThe full padding means that the kernel runs over the whole inputs, so at the ends, the kernel may meet the only one input and zeros else. The number of zeros padded is 2(k-1) if s=1. The length of output is ((the length of input) + (k-1)) if s=1.\nTherefore, the number of paddings: (valid) <= (same) <= (full)\n", "VALID padding: this is with zero padding. Hope there is no confusion. \nx = tf.constant([[1., 2., 3.], [4., 5., 6.],[ 7., 8., 9.], [ 7., 8., 9.]])\nx = tf.reshape(x, [1, 4, 3, 1])\nvalid_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='VALID')\nprint (valid_pad.get_shape()) # output-->(1, 2, 1, 1)\n\nSAME padding: This is kind of tricky to understand in the first place because we have to consider two conditions separately as mentioned in the official docs. \nLet's take input as , output as , padding as , stride as and kernel size as (only a single dimension is considered)\nCase 01: :\nCase 02: : \n is calculated such that the minimum value which can be taken for padding. Since value of is known, value of can be found using this formula . \nLet's work out this example:\nx = tf.constant([[1., 2., 3.], [4., 5., 6.],[ 7., 8., 9.], [ 7., 8., 9.]])\nx = tf.reshape(x, [1, 4, 3, 1])\nsame_pad = tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\nprint (same_pad.get_shape()) # --> output (1, 2, 2, 1)\n\nHere the dimension of x is (3,4). Then if the horizontal direction is taken (3):\n\nIf the vertial direction is taken (4):\n\nHope this will help to understand how actually SAME padding works in TF. \n", "To sum up, 'valid' padding means no padding. The output size of the convolutional layer shrinks depending on the input size & kernel size. \nOn the contrary, 'same' padding means using padding. When the stride is set as 1, the output size of the convolutional layer maintains as the input size by appending a certain number of '0-border' around the input data when calculating convolution.\nHope this intuitive description helps.\n", "Based on the explanation here and following up on Tristan's answer, I usually use these quick functions for sanity checks.\n# a function to help us stay clean\ndef getPaddings(pad_along_height,pad_along_width):\n # if even.. easy..\n if pad_along_height%2 == 0:\n pad_top = pad_along_height / 2\n pad_bottom = pad_top\n # if odd\n else:\n pad_top = np.floor( pad_along_height / 2 )\n pad_bottom = np.floor( pad_along_height / 2 ) +1\n # check if width padding is odd or even\n # if even.. easy..\n if pad_along_width%2 == 0:\n pad_left = pad_along_width / 2\n pad_right= pad_left\n # if odd\n else:\n pad_left = np.floor( pad_along_width / 2 )\n pad_right = np.floor( pad_along_width / 2 ) +1\n #\n return pad_top,pad_bottom,pad_left,pad_right\n\n# strides [image index, y, x, depth]\n# padding 'SAME' or 'VALID'\n# bottom and right sides always get the one additional padded pixel (if padding is odd)\ndef getOutputDim (inputWidth,inputHeight,filterWidth,filterHeight,strides,padding):\n if padding == 'SAME':\n out_height = np.ceil(float(inputHeight) / float(strides[1]))\n out_width = np.ceil(float(inputWidth) / float(strides[2]))\n #\n pad_along_height = ((out_height - 1) * strides[1] + filterHeight - inputHeight)\n pad_along_width = ((out_width - 1) * strides[2] + filterWidth - inputWidth)\n #\n # now get padding\n pad_top,pad_bottom,pad_left,pad_right = getPaddings(pad_along_height,pad_along_width)\n #\n print 'output height', out_height\n print 'output width' , out_width\n print 'total pad along height' , pad_along_height\n print 'total pad along width' , pad_along_width\n print 'pad at top' , pad_top\n print 'pad at bottom' ,pad_bottom\n print 'pad at left' , pad_left\n print 'pad at right' ,pad_right\n\n elif padding == 'VALID':\n out_height = np.ceil(float(inputHeight - filterHeight + 1) / float(strides[1]))\n out_width = np.ceil(float(inputWidth - filterWidth + 1) / float(strides[2]))\n #\n print 'output height', out_height\n print 'output width' , out_width\n print 'no padding'\n\n\n# use like so\ngetOutputDim (80,80,4,4,[1,1,1,1],'SAME')\n\n", "Padding on/off. Determines the effective size of your input.\nVALID: No padding. Convolution etc. ops are only performed at locations that are \"valid\", i.e. not too close to the borders of your tensor. With a kernel of 3x3 and image of 10x10, you would be performing convolution on the 8x8 area inside the borders.\nSAME: Padding is provided. Whenever your operation references a neighborhood (no matter how big), zero values are provided when that neighborhood extends outside the original tensor to allow that operation to work also on border values. With a kernel of 3x3 and image of 10x10, you would be performing convolution on the full 10x10 area.\n", "\nHere, W and H are width and height of input,\n F are filter dimensions, \n P is padding size (i.e., number of rows or columns to be padded)\nFor SAME padding: \n\nFor VALID padding: \n\n", "Tensorflow 2.0 Compatible Answer: Detailed Explanations have been provided above, about \"Valid\" and \"Same\" Padding. \nHowever, I will specify different Pooling Functions and their respective Commands in Tensorflow 2.x (>= 2.0), for the benefit of the community.\nFunctions in 1.x:\ntf.nn.max_pool\ntf.keras.layers.MaxPool2D\nAverage Pooling => None in tf.nn, tf.keras.layers.AveragePooling2D\nFunctions in 2.x:\ntf.nn.max_pool if used in 2.x and tf.compat.v1.nn.max_pool_v2 or tf.compat.v2.nn.max_pool, if migrated from 1.x to 2.x.\ntf.keras.layers.MaxPool2D if used in 2.x and \ntf.compat.v1.keras.layers.MaxPool2D or tf.compat.v1.keras.layers.MaxPooling2D or tf.compat.v2.keras.layers.MaxPool2D or tf.compat.v2.keras.layers.MaxPooling2D, if migrated from 1.x to 2.x.\nAverage Pooling => tf.nn.avg_pool2d or tf.keras.layers.AveragePooling2D if used in TF 2.x and \ntf.compat.v1.nn.avg_pool_v2 or tf.compat.v2.nn.avg_pool or tf.compat.v1.keras.layers.AveragePooling2D or tf.compat.v1.keras.layers.AvgPool2D or tf.compat.v2.keras.layers.AveragePooling2D or tf.compat.v2.keras.layers.AvgPool2D , if migrated from 1.x to 2.x.\nFor more information about Migration from Tensorflow 1.x to 2.x, please refer to this Migration Guide.\n", "valid padding is no padding.\nsame padding is padding in a way the output has the same size as input.\n", "In the TensorFlow function tf.nn.max_pool, the padding parameter determines how the input tensor is padded before the max pooling operation is applied. The 'VALID' padding option means that no padding will be applied to the input tensor, and the output tensor will have dimensions that are smaller than the input tensor. For example, if the input tensor has dimensions [batch_size, height, width, channels] and the max pooling window has dimensions [pool_height, pool_width], then the output tensor will have dimensions [batch_size, (height - pool_height + 1), (width - pool_width + 1), channels].\nThe 'SAME' padding option, on the other hand, means that the input tensor will be padded with zeros in such a way that the output tensor will have the same dimensions as the input tensor. The amount of padding applied to the input tensor will depend on the dimensions of the max pooling window and the stride size. For example, if the input tensor has dimensions [batch_size, height, width, channels] and the max pooling window has dimensions [pool_height, pool_width], and the stride is set to 1, then the output tensor will also have dimensions [batch_size, height, width, channels], and the input tensor will be padded with zeros on the top, bottom, left, and right sides as needed.\nIn summary, the 'VALID' padding option means that no padding will be applied to the input tensor, and the output tensor will have dimensions that are smaller than the input tensor. The 'SAME' padding option means that the input tensor will be padded with zeros as needed to ensure that the output tensor has the same dimensions as the input tensor.\n" ]
[ 748, 200, 187, 106, 80, 59, 38, 28, 13, 12, 12, 9, 9, 9, 2, 1, 0 ]
[]
[]
[ "deep_learning", "python", "tensorflow" ]
stackoverflow_0037674306_deep_learning_python_tensorflow.txt
Q: How to pass a parameter from client side to server in python I am using flask and flask-restx try to create a protocol to get a specific string from another service. I am wonder if there is a way I can pass the parameter from another function to server side. For example, here's my server side: from flask_restx import Api,fields,Resource from flask import Flask app = Flask(__name__) api = Api(app) parent = api.model('Parent', { 'name': fields.String(get_answer(a,b)), 'class': fields.String(discriminator=True) }) @api.route('/language') class Language(Resource): # @api.marshal_with(data_stream_request) @api.marshal_with(parent) @api.response(403, "Unauthorized") def get(self): return {"happy": "good"} get_answer function in a different file: get_answer(a,b): return a + b What I expect is to get the result of get_answer from a file, and then my API is generated so that the GET request can get it. I know that if there is a web page, we can use render_template( or form to get it. But what if I want to get the value from another function? I know we only run the server with app.run(), but are we able to pass any value into the server? Guessing app.run(a,b) should not work in this case. We definite need to pass two parameter into the server. Or we can store the answer of get_answer(a,b) in main with specific value of a and b, then pass the number into the server side. But it will need the parameter either way. One thing I've tested is wrapping up the server into a function. But in our case, is it a good idea to wrap a class inside a function as we have class Language(Resource):? A: You can use request parameters or the request body to pass in data to your endpoints. For example, you could define your endpoint like this: @api.route('/language') class Language(Resource): @api.marshal_with(parent) @api.response(403, "Unauthorized") def get(self): a = request.args.get('a') b = request.args.get('b') result = get_answer(a, b) return {"result": result} In this example, you can call the endpoint with a query string like this: /language?a=1&b=2 and the get_answer() function will be called with a=1 and b=2. Alternatively, you could use the request body to pass in the data, like this: @api.route('/language') class Language(Resource): @api.expect(parent) @api.response(403, "Unauthorized") def post(self): data = request.get_json() a = data['a'] b = data['b'] result = get_answer(a, b) return {"result": result} In this case, you would call the endpoint with a POST request and include a JSON object in the request body with the values for a and b. As for your question about wrapping your Flask app in a function, this is generally not recommended. Flask is designed to be run as a standalone web application, and wrapping it in a function can cause issues with how Flask manages its internal state. It is better to define your Flask app and its endpoints in the global scope, and then run the app with app.run() when you are ready to start the server. (just sharing my opinion) If you still want to do this, you can define a function that creates and runs a Flask app like this: def create_app(): app = Flask(__name__) api = Api(app) parent = api.model('Parent', { 'name': fields.String(get_answer(a,b)), 'class': fields.String(discriminator=True) }) @api.route('/language') class Language(Resource): # @api.marshal_with(data_stream_request) @api.marshal_with(parent) @api.response(403, "Unauthorized") def get(self): return {"happy": "good"} return app You can then call this function to create your Flask app and run it like this: app = create_app() app.run() A: get_answer function in a different file Then import and call it from other_file import get_answer ... def get(self): return {"answer": get_answer(2,2)} As the other answer shows, if you want to use custom arguments, parse them from the request object
How to pass a parameter from client side to server in python
I am using flask and flask-restx try to create a protocol to get a specific string from another service. I am wonder if there is a way I can pass the parameter from another function to server side. For example, here's my server side: from flask_restx import Api,fields,Resource from flask import Flask app = Flask(__name__) api = Api(app) parent = api.model('Parent', { 'name': fields.String(get_answer(a,b)), 'class': fields.String(discriminator=True) }) @api.route('/language') class Language(Resource): # @api.marshal_with(data_stream_request) @api.marshal_with(parent) @api.response(403, "Unauthorized") def get(self): return {"happy": "good"} get_answer function in a different file: get_answer(a,b): return a + b What I expect is to get the result of get_answer from a file, and then my API is generated so that the GET request can get it. I know that if there is a web page, we can use render_template( or form to get it. But what if I want to get the value from another function? I know we only run the server with app.run(), but are we able to pass any value into the server? Guessing app.run(a,b) should not work in this case. We definite need to pass two parameter into the server. Or we can store the answer of get_answer(a,b) in main with specific value of a and b, then pass the number into the server side. But it will need the parameter either way. One thing I've tested is wrapping up the server into a function. But in our case, is it a good idea to wrap a class inside a function as we have class Language(Resource):?
[ "You can use request parameters or the request body to pass in data to your endpoints. For example, you could define your endpoint like this:\[email protected]('/language')\nclass Language(Resource):\n @api.marshal_with(parent)\n @api.response(403, \"Unauthorized\")\n def get(self):\n a = request.args.get('a')\n b = request.args.get('b')\n result = get_answer(a, b)\n return {\"result\": result}\n\nIn this example, you can call the endpoint with a query string like this: /language?a=1&b=2 and the get_answer() function will be called with a=1 and b=2.\nAlternatively, you could use the request body to pass in the data, like this:\[email protected]('/language')\nclass Language(Resource):\n @api.expect(parent)\n @api.response(403, \"Unauthorized\")\n def post(self):\n data = request.get_json()\n a = data['a']\n b = data['b']\n result = get_answer(a, b)\n return {\"result\": result}\n\nIn this case, you would call the endpoint with a POST request and include a JSON object in the request body with the values for a and b.\nAs for your question about wrapping your Flask app in a function, this is generally not recommended. Flask is designed to be run as a standalone web application, and wrapping it in a function can cause issues with how Flask manages its internal state.\nIt is better to define your Flask app and its endpoints in the global scope, and then run the app with app.run() when you are ready to start the server. (just sharing my opinion)\nIf you still want to do this, you can define a function that creates and runs a Flask app like this:\ndef create_app():\n app = Flask(__name__)\n api = Api(app)\n\n parent = api.model('Parent', {\n 'name': fields.String(get_answer(a,b)),\n 'class': fields.String(discriminator=True)\n })\n\n @api.route('/language')\n class Language(Resource):\n # @api.marshal_with(data_stream_request)\n @api.marshal_with(parent)\n @api.response(403, \"Unauthorized\")\n def get(self):\n return {\"happy\": \"good\"}\n\n return app\n\nYou can then call this function to create your Flask app and run it like this:\napp = create_app()\napp.run()\n\n", "\nget_answer function in a different file\n\nThen import and call it\nfrom other_file import get_answer\n\n... \ndef get(self):\n return {\"answer\": get_answer(2,2)}\n\nAs the other answer shows, if you want to use custom arguments, parse them from the request object\n" ]
[ 0, 0 ]
[]
[]
[ "flask", "flask_restplus", "flask_restx", "python" ]
stackoverflow_0074663441_flask_flask_restplus_flask_restx_python.txt
Q: ValueError when trying to write a for loop in python When I run this: import pandas as pd data = {'id': ['earn', 'earn','lose', 'earn'], 'game': ['darts', 'balloons', 'balloons', 'darts'] } df = pd.DataFrame(data) print(df) print(df.loc[[1],['id']] == 'earn') The output is: id game 0 earn darts 1 earn balloons 2 lose balloons 3 earn darts id 1 True But when I try to run this loop: for i in range(len(df)): if (df.loc[[i],['id']] == 'earn'): print('yes') else: print('no') I get the error 'ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().' I am not sure what the problem is. Any help or advice is appreciated -- I am just starting. I expected the output to be 'yes' from the loop. But I just got the 'ValueError' message. But, when I run the condition by itself, the output is 'True' so I'm not sure what is wrong. A: for i,row in df.iterrows(): if row.id == "earn": print("yes") A: Its complicated. pandas is geared towards operating on entire groups of data, not individual cells. df.loc may create a new DataFrame, a Series or a single value, depending on how its indexed. And those produce DataFrame, Series or scalar results for the == comparison. If the indexers are both lists, you get a new DataFrame and the compare is also a dataframe >>> foo = df.loc[[1], ['id']] >>> type(foo) <class 'pandas.core.frame.DataFrame'> >>> foo id 1 earn >>> foo == "earn" id 1 True If one indexer is scalar, you get a new Series >>> foo = df.loc[[1], 'id'] >>> type(foo) <class 'pandas.core.series.Series'> >>> foo 1 earn Name: id, dtype: object >>> foo == 'earn' 1 True Name: id, dtype: bool If both indexers are scalar, you get a single cell's value >>> foo = df.loc[1, 'id'] >>> type(foo) <class 'str'> >>> foo 'earn' >>> foo == 'earn' True That last is the one you want. The first two produce containers where True is ambiguous (you need to decide if any or all values need to be True). for i in range(len(df)): if (df.loc[i,'id'] == 'earn'): print('yes') else: print('no') Or maybe not. Depending on what you intend to do next, create a series of boolean values for all of the rows at once >>> earn = df[id'] == 'earn' >>> earn 0 True 1 True 2 False 3 True Name: id, dtype: bool now you can continue to make calculations on the dataframe as a whole.
ValueError when trying to write a for loop in python
When I run this: import pandas as pd data = {'id': ['earn', 'earn','lose', 'earn'], 'game': ['darts', 'balloons', 'balloons', 'darts'] } df = pd.DataFrame(data) print(df) print(df.loc[[1],['id']] == 'earn') The output is: id game 0 earn darts 1 earn balloons 2 lose balloons 3 earn darts id 1 True But when I try to run this loop: for i in range(len(df)): if (df.loc[[i],['id']] == 'earn'): print('yes') else: print('no') I get the error 'ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().' I am not sure what the problem is. Any help or advice is appreciated -- I am just starting. I expected the output to be 'yes' from the loop. But I just got the 'ValueError' message. But, when I run the condition by itself, the output is 'True' so I'm not sure what is wrong.
[ "for i,row in df.iterrows():\n if row.id == \"earn\":\n print(\"yes\")\n\n", "Its complicated. pandas is geared towards operating on entire groups of data, not individual cells. df.loc may create a new DataFrame, a Series or a single value, depending on how its indexed. And those produce DataFrame, Series or scalar results for the == comparison.\nIf the indexers are both lists, you get a new DataFrame and the compare is also a dataframe\n>>> foo = df.loc[[1], ['id']]\n>>> type(foo)\n<class 'pandas.core.frame.DataFrame'>\n>>> foo\n id\n1 earn\n>>> foo == \"earn\"\n id\n1 True\n\nIf one indexer is scalar, you get a new Series\n>>> foo = df.loc[[1], 'id']\n>>> type(foo)\n<class 'pandas.core.series.Series'>\n>>> foo\n1 earn\nName: id, dtype: object\n>>> foo == 'earn'\n1 True\nName: id, dtype: bool\n\nIf both indexers are scalar, you get a single cell's value\n>>> foo = df.loc[1, 'id']\n>>> type(foo)\n<class 'str'>\n>>> foo\n'earn'\n>>> foo == 'earn'\nTrue\n\nThat last is the one you want. The first two produce containers where True is ambiguous (you need to decide if any or all values need to be True).\nfor i in range(len(df)): \n if (df.loc[i,'id'] == 'earn'): \n print('yes') \n else: \n print('no')\n\nOr maybe not. Depending on what you intend to do next, create a series of boolean values for all of the rows at once\n>>> earn = df[id'] == 'earn'\n>>> earn\n0 True\n1 True\n2 False\n3 True\nName: id, dtype: bool\n\nnow you can continue to make calculations on the dataframe as a whole.\n" ]
[ 1, 0 ]
[]
[]
[ "loops", "python", "valueerror" ]
stackoverflow_0074663367_loops_python_valueerror.txt
Q: I am trying to figure out a grading system and cant seem to get it to work (python) i have a problem which i am trying to solve and cant for the life of me figure it out. I feel like its the simplest answer but yet i'm still stuck. The instructions stated that the application must do the following: Ask the user to input the marks for the five subjects in a list/array. The program must ensure that the marks are between 0 and 100 Display the list/array of marks entered. Find the sum of all the marks in the list (all five subjects) and display the output as: The sum of your marks is: [sum] Find the average of all the marks in the list (all five subjects) and display the output as: The average of your marks is: [average mark] this is what i have tried print("please enter your 5 marks below") # read 5 inputs mark1 = int(input("enter mark 1: ")) if mark1 <= 0 or mark1 <= 100: print("Mark is acceptable") else: print("Mark is not acceptable") mark1 = int(input("enter mark 1: ")) mark2 = int(input("enter mark 2: ")) if mark2 <= 0 or mark2 <= 100: print("Mark is acceptable") else: print("Mark is not acceptable") mark2 = int(input("enter mark 2: ")) mark3 = int(input("enter mark 3: ")) if mark3 <= 0 or mark3 <= 100: print("Mark is acceptable") else: print("Mark is not acceptable") mark3 = int(input("enter mark 3: ")) mark4 = int(input("enter mark 4: ")) if mark4 <= 0 or mark4 <= 100: print("Mark is acceptable") else: print("Mark is not acceptable") mark4 = int(input("enter mark 4: ")) mark5 = int(input("enter mark 5: ")) if mark5 <= 0 or mark5 <= 100: print("Mark is acceptable") # create array/list with five marks marksList = [mark1, mark2, mark3, mark4, mark5] # print the array/list print(marksList) # calculate the sum and average sumOfMarks = sum(marksList) averageOfMarks = sum(marksList) / 5 # display results print("The sum of your marks is: " + str(sumOfMarks)) print("The average of your marks is: " + str(averageOfMarks)) A: Firstly, you can use a while loop so that you don't have to manually copy & paste for each mark. e.g.: marksList = [] i = 1 while len(marksList) < 5: mark = int(input(f"Input mark {i}")) if 0 <= mark <= 100: print("Mark is acceptable") marksList.append(mark) i += 1 else: print("Mark is not acceptable") The above while loop keeps iterating through the loop unless the condition is met. The rest should be simple: print(marksList) sum = sum(marksList) # sum average = average(marksList) # there is a built-in average() function! print(...) Edit: If you wish to add some error handling, you can use try-except, like this: # ... (same code) while len(marksList) < 5: try: mark = int(input(f"Input mark {i}")) except ValueError: print("Please enter an integer.") continue # ... (same code) A: This is really unorthodox code. If you need to get a series of inputs, use a loop and after each iteration, store the value into a list. marks = [] for i in range(1, 6): # needs to be 1 to 6 since the 6 won't be included but the 1 will mark = int(input(f"Enter mark number {i}: ") while mark<0 or mark>100: print("Invalid mark") mark = int(input(f"Enter mark number {i}: ") marks+=mark sums = sum(marks) print(f"The sum of your marks is {sums}") print(f"The average of your marks is {sums/5}") What did I change? I made the print statements into formatted strings for more clarity. I also used a loop to get inputs instead of just a series of inputs. A: Use while loop combine with try except to revalidate user input. You can use walrus operator (:=) to ask for each input and check if the value within range() print("please enter your 5 marks below") marks, nth= list(), 1 while len(marks) < 5: try: if not (mark := int(input(f"enter mark {nth}: "))) in range(101): print("Mark is not acceptable") else: print("Mark is acceptable") marks += [mark] nth += 1 except ValueError: print("Mark is not acceptable") print("Your marks: ", *marks) print("The sum of your marks is: ", sum(marks)) print("The average of your marks is: ", sum(marks)/len(marks)) Output: please enter your 5 marks below enter mark 1: no Mark is not acceptable enter mark 1: 67 Mark is acceptable enter mark 2: 0 Mark is acceptable enter mark 3: Mark is not acceptable enter mark 3: 56 Mark is acceptable enter mark 4: 101 Mark is not acceptable enter mark 4: 75 Mark is acceptable enter mark 5: 81 Mark is acceptable Your marks: 67 0 56 75 81 The sum of your marks is: 279 The average of your marks is: 55.8
I am trying to figure out a grading system and cant seem to get it to work (python)
i have a problem which i am trying to solve and cant for the life of me figure it out. I feel like its the simplest answer but yet i'm still stuck. The instructions stated that the application must do the following: Ask the user to input the marks for the five subjects in a list/array. The program must ensure that the marks are between 0 and 100 Display the list/array of marks entered. Find the sum of all the marks in the list (all five subjects) and display the output as: The sum of your marks is: [sum] Find the average of all the marks in the list (all five subjects) and display the output as: The average of your marks is: [average mark] this is what i have tried print("please enter your 5 marks below") # read 5 inputs mark1 = int(input("enter mark 1: ")) if mark1 <= 0 or mark1 <= 100: print("Mark is acceptable") else: print("Mark is not acceptable") mark1 = int(input("enter mark 1: ")) mark2 = int(input("enter mark 2: ")) if mark2 <= 0 or mark2 <= 100: print("Mark is acceptable") else: print("Mark is not acceptable") mark2 = int(input("enter mark 2: ")) mark3 = int(input("enter mark 3: ")) if mark3 <= 0 or mark3 <= 100: print("Mark is acceptable") else: print("Mark is not acceptable") mark3 = int(input("enter mark 3: ")) mark4 = int(input("enter mark 4: ")) if mark4 <= 0 or mark4 <= 100: print("Mark is acceptable") else: print("Mark is not acceptable") mark4 = int(input("enter mark 4: ")) mark5 = int(input("enter mark 5: ")) if mark5 <= 0 or mark5 <= 100: print("Mark is acceptable") # create array/list with five marks marksList = [mark1, mark2, mark3, mark4, mark5] # print the array/list print(marksList) # calculate the sum and average sumOfMarks = sum(marksList) averageOfMarks = sum(marksList) / 5 # display results print("The sum of your marks is: " + str(sumOfMarks)) print("The average of your marks is: " + str(averageOfMarks))
[ "Firstly, you can use a while loop so that you don't have to manually copy & paste for each mark. e.g.:\nmarksList = []\ni = 1\n\nwhile len(marksList) < 5:\n mark = int(input(f\"Input mark {i}\"))\n if 0 <= mark <= 100:\n print(\"Mark is acceptable\")\n marksList.append(mark)\n i += 1\n else:\n print(\"Mark is not acceptable\")\n\nThe above while loop keeps iterating through the loop unless the condition is met.\nThe rest should be simple:\nprint(marksList)\n\nsum = sum(marksList) # sum\naverage = average(marksList) # there is a built-in average() function!\n\nprint(...)\n\nEdit: If you wish to add some error handling, you can use try-except, like this:\n# ... (same code)\nwhile len(marksList) < 5:\n try:\n mark = int(input(f\"Input mark {i}\"))\n except ValueError:\n print(\"Please enter an integer.\")\n continue\n # ... (same code)\n\n", "This is really unorthodox code. If you need to get a series of inputs, use a loop and after each iteration, store the value into a list.\nmarks = []\nfor i in range(1, 6): # needs to be 1 to 6 since the 6 won't be included but the 1 will \n mark = int(input(f\"Enter mark number {i}: \")\n while mark<0 or mark>100:\n print(\"Invalid mark\")\n mark = int(input(f\"Enter mark number {i}: \")\n marks+=mark\n\n\nsums = sum(marks)\nprint(f\"The sum of your marks is {sums}\")\nprint(f\"The average of your marks is {sums/5}\")\n\nWhat did I change?\nI made the print statements into formatted strings for more clarity. I also used a loop to get inputs instead of just a series of inputs.\n", "Use while loop combine with try except to revalidate user input. You can use walrus operator (:=) to ask for each input and check if the value within range()\nprint(\"please enter your 5 marks below\")\nmarks, nth= list(), 1\nwhile len(marks) < 5:\n try:\n if not (mark := int(input(f\"enter mark {nth}: \"))) in range(101):\n print(\"Mark is not acceptable\")\n else:\n print(\"Mark is acceptable\")\n marks += [mark]\n nth += 1\n except ValueError:\n print(\"Mark is not acceptable\")\n\nprint(\"Your marks: \", *marks)\nprint(\"The sum of your marks is: \", sum(marks))\nprint(\"The average of your marks is: \", sum(marks)/len(marks))\n\nOutput:\nplease enter your 5 marks below\nenter mark 1: no\nMark is not acceptable\nenter mark 1: 67\nMark is acceptable\nenter mark 2: 0\nMark is acceptable\nenter mark 3: \nMark is not acceptable\nenter mark 3: 56\nMark is acceptable\nenter mark 4: 101\nMark is not acceptable\nenter mark 4: 75\nMark is acceptable\nenter mark 5: 81\nMark is acceptable\nYour marks: 67 0 56 75 81\nThe sum of your marks is: 279\nThe average of your marks is: 55.8\n\n" ]
[ 0, 0, 0 ]
[ "We can use the map function for the input. Map syntax looks like this: map(function, iter). By replacing function with int. We apply int to each element in input().split()\nAssuming all marks have to be between 0-100, we can use all() which checks if all items in a list are True. If x == True, we then print our results.\nn = list(map(int, input().split()))\nx = all(i >= 0 and i <= 100 for i in n)\nif x == True:\n print('The sum of your marks is: ', sum(n))\n print('The average of your marks is:', sum(n) / 5)\n\nIf you want to keep trying till you meet the requirement, you can use try/except/else. As we can see below, we raise an exception if x == False(This can be custom) and keep trying till x == True and only then print(..)\nwhile True:\n try:\n n = list(map(int, input().split()))\n x = all(i >= 0 and i <= 100 for i in n)\n if x == False:\n raise Exception\n except Exception:\n pass\n else:\n print('The sum of your marks is: ', sum(n))\n print('The average of your marks is:', sum(n) / 5)\n break\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074663209_python.txt
Q: How to add a cooldown time in between commands so that user's can't spam my bot with commands Like the title says. I need to make a way to force users to wait maybe 15 or 30 seconds between commands. So if they run it again it will let them know how much longer they need to wait. A: I figured it out by referencing the following code: from time import time MAX_USAGE = 5 async def callback(update: Update, context: ContextTypes.DEFAULT_TYPE): count = context.user_data.get("usageCount", 0) restrict_since = context.user_data.get("restrictSince", 0) if restrict_since: if (time() - restrict_since) >= 60 * 5: # 5 minutes del context.user_data["restrictSince"] del context.user_data["usageCount"] await update.effective_message.reply_text("I have unrestricted you. Please behave well.") else: await update.effective_message.reply_text("Back off! Wait for your restriction to expire...") raise ApplicationHandlerStop else: if count == MAX_USAGE: context.user_data["restrictSince"] = time() await update.effective_message.reply_text("Stop flooding! Don't bother me for 5 minutes...") raise ApplicationHandlerStop else: context.user_data["usageCount"] = count + 1
How to add a cooldown time in between commands so that user's can't spam my bot with commands
Like the title says. I need to make a way to force users to wait maybe 15 or 30 seconds between commands. So if they run it again it will let them know how much longer they need to wait.
[ "I figured it out by referencing the following code:\nfrom time import time\n\nMAX_USAGE = 5\n\n\nasync def callback(update: Update, context: ContextTypes.DEFAULT_TYPE):\n count = context.user_data.get(\"usageCount\", 0)\n restrict_since = context.user_data.get(\"restrictSince\", 0)\n\n if restrict_since:\n if (time() - restrict_since) >= 60 * 5: # 5 minutes\n del context.user_data[\"restrictSince\"]\n del context.user_data[\"usageCount\"]\n await update.effective_message.reply_text(\"I have unrestricted you. Please behave well.\")\n else:\n await update.effective_message.reply_text(\"Back off! Wait for your restriction to expire...\")\n raise ApplicationHandlerStop\n else:\n if count == MAX_USAGE:\n context.user_data[\"restrictSince\"] = time()\n await update.effective_message.reply_text(\"Stop flooding! Don't bother me for 5 minutes...\")\n raise ApplicationHandlerStop\n else:\n context.user_data[\"usageCount\"] = count + 1\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_telegram_bot" ]
stackoverflow_0074661186_python_python_telegram_bot.txt
Q: storing a variable from turtle.onclick(turtle.textinput()) I'm trying to program a slidepuzzle game and I've been given several potential files to load. The files need to be loaded from a clickable button within turtle itself. Ive written the following code- def button_click(x,y): if (x > 247 and x < 315) and (y > -292 and y < -246): #exit on click exit turtle.onclick(quit(1)) elif (x > 143 and x < 213) and (y > -302 and y < -236): #load on click load = turtle.onclick(turtle.textinput('Prompt',"prompt")) print(load) The quit button is working when clicked and the load prompt is showing up when the load button is clicked, but when the print(load) variable statement goes off in the terminal it keeps returning "none". Ideally, load should be returning a valid string file name (entered by the user) that I can use as input into another function to begin loading the parameters of the puzzle. No matter what you type into the prompt box now, it just returns none. Any assistance is greatly appreciated! A: load has now successfully become a variable, I just had to remove the turtle.onclick- now the code looks like this. def button_click(x,y): if (x > 247 and x < 315) and (y > -292 and y < -246): #exit on click exit turtle.onclick(quit(1)) elif (x > 143 and x < 213) and (y > -302 and y < -236): #load on click load = turtle.textinput('prompt','prompt') print (load)
storing a variable from turtle.onclick(turtle.textinput())
I'm trying to program a slidepuzzle game and I've been given several potential files to load. The files need to be loaded from a clickable button within turtle itself. Ive written the following code- def button_click(x,y): if (x > 247 and x < 315) and (y > -292 and y < -246): #exit on click exit turtle.onclick(quit(1)) elif (x > 143 and x < 213) and (y > -302 and y < -236): #load on click load = turtle.onclick(turtle.textinput('Prompt',"prompt")) print(load) The quit button is working when clicked and the load prompt is showing up when the load button is clicked, but when the print(load) variable statement goes off in the terminal it keeps returning "none". Ideally, load should be returning a valid string file name (entered by the user) that I can use as input into another function to begin loading the parameters of the puzzle. No matter what you type into the prompt box now, it just returns none. Any assistance is greatly appreciated!
[ "load has now successfully become a variable, I just had to remove the turtle.onclick- now the code looks like this.\ndef button_click(x,y):\nif (x > 247 and x < 315) and (y > -292 and y < -246): #exit on click exit\n turtle.onclick(quit(1))\nelif (x > 143 and x < 213) and (y > -302 and y < -236): #load on click\n load = turtle.textinput('prompt','prompt')\n print (load)\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074663018_python_python_turtle_turtle_graphics.txt
Q: how to extract data from the database and pass it to the function in Django I`m beginner Django user, please help me. I have multiple records in a sqlite3 data table. Please tell me how to read this data from the database in Django and write it to the views.py function. This is my models.py class Value(models.Model): capacity = models.FloatField('Емкость конденсатора') amplitude = models.FloatField('Амплитуда') frequency = models.FloatField('Частота') This is my views.py def voltage(array, a, c, w, tim): t = 0 for i in range(100): array.append(c * a * math.sin(w * t - math.pi / 2)) tim.append(t) t = t + 0.1 someArray = [] tim = [] voltage(someArray, a, c, tim) in c I want to write capacity, in a - amplitude, in w - frequency. I hope I can get data from the database into the views.py function A: #views.py from models import Value #in the view vals = Value.objects.all() for v in vals: c = v.capacity #and so on
how to extract data from the database and pass it to the function in Django
I`m beginner Django user, please help me. I have multiple records in a sqlite3 data table. Please tell me how to read this data from the database in Django and write it to the views.py function. This is my models.py class Value(models.Model): capacity = models.FloatField('Емкость конденсатора') amplitude = models.FloatField('Амплитуда') frequency = models.FloatField('Частота') This is my views.py def voltage(array, a, c, w, tim): t = 0 for i in range(100): array.append(c * a * math.sin(w * t - math.pi / 2)) tim.append(t) t = t + 0.1 someArray = [] tim = [] voltage(someArray, a, c, tim) in c I want to write capacity, in a - amplitude, in w - frequency. I hope I can get data from the database into the views.py function
[ "\n#views.py\n\nfrom models import Value\n\n#in the view\nvals = Value.objects.all()\nfor v in vals:\n c = v.capacity #and so on\n\n" ]
[ 1 ]
[]
[]
[ "django", "python", "sqlite" ]
stackoverflow_0074662676_django_python_sqlite.txt
Q: CSV using '-' as NULL. Error to convert column to INT I have a CSV df = pd.read_csv('data.csv') Table: Column A Column B Column C 4068744 -1472525 2596219 198366 - - The file is using '-' for nul values I tried converting to int without handling that '-'. My question is: how do I strip the string '-' without changing the negative values? df['Column B'] = df['Column B'].astype(int) ValueError: invalid literal for int() with base 10: '-' A: Higher version of pandas can hold integer dtypes with missing values. Normal int conversion doesn't support null values. # replace - with null df.replace('-', pd.NA, inplace=True) # and use Int surrounding with '' df['Column B'] = df['Column B'].astype('Int64') output: > df Column A Column B Column C 0 4068744 -1472525 2596219 1 198366 <NA> <NA> > df['Column B'].info Name: Column B, dtype: Int64>
CSV using '-' as NULL. Error to convert column to INT
I have a CSV df = pd.read_csv('data.csv') Table: Column A Column B Column C 4068744 -1472525 2596219 198366 - - The file is using '-' for nul values I tried converting to int without handling that '-'. My question is: how do I strip the string '-' without changing the negative values? df['Column B'] = df['Column B'].astype(int) ValueError: invalid literal for int() with base 10: '-'
[ "Higher version of pandas can hold integer dtypes with missing values. Normal int conversion doesn't support null values.\n# replace - with null\ndf.replace('-', pd.NA, inplace=True)\n# and use Int surrounding with ''\ndf['Column B'] = df['Column B'].astype('Int64')\n\noutput:\n> df\n\n Column A Column B Column C\n0 4068744 -1472525 2596219\n1 198366 <NA> <NA>\n\n> df['Column B'].info\n\nName: Column B, dtype: Int64>\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "nul", "pandas", "python" ]
stackoverflow_0074663597_dataframe_nul_pandas_python.txt
Q: How do I fix TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'? I'm trying to remake Tic-Tac-Toe on python. But, it wont work. I tried ` game_board = ['_'] * 9 print(game_board[0]) + " | " + (game_board[1]) + ' | ' + (game_board[2]) print(game_board[3]) + ' | ' + (game_board[4]) + ' | ' + (game_board[5]) print(game_board[6]) + ' | ' + (game_board[7]) + ' | ' + (game_board[8]) ` but it returns ` Traceback (most recent call last): File "C:\Users\username\PycharmProjects\pythonProject\tutorial.py", line 2, in <module> print(game_board[0]) + " | " + (game_board[1]) + ' | ' + (game_board[2]) ~~~~~~~~~~~~~~~~~~~~~^~~~~~~ TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' ` A: Is this you want..!? Code:- game_board = ['_']*9 print(game_board[0]+" | "+(game_board[1])+' | '+(game_board[2])) print(game_board[3]+' | '+(game_board[4])+' | '+(game_board[5])) print(game_board[6]+' | '+(game_board[7])+' | '+(game_board[8])) Output:- _ | _ | _ _ | _ | _ _ | _ | _ A: This is because you put the parenthesis wrongly. It should be game_board = ['_'] * 9 print(game_board[0] + " | " + (game_board[1]) + ' | ' + (game_board[2])) print(game_board[3] + ' | ' + (game_board[4]) + ' | ' + (game_board[5])) print(game_board[6] + ' | ' + (game_board[7]) + ' | ' + (game_board[8])) A: Please look at the error carefully to find your answer. print(game_board[0]) + " | " + (game_board[1]) + ' | ' + (game_board[2]) ~~~~~~~~~~~~~~~~~~~~~^~~~~~~ you have closed the bracket for game_board[0]. An additional '(' is to be used. print( (game_board[0]) + " | " .....
How do I fix TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'?
I'm trying to remake Tic-Tac-Toe on python. But, it wont work. I tried ` game_board = ['_'] * 9 print(game_board[0]) + " | " + (game_board[1]) + ' | ' + (game_board[2]) print(game_board[3]) + ' | ' + (game_board[4]) + ' | ' + (game_board[5]) print(game_board[6]) + ' | ' + (game_board[7]) + ' | ' + (game_board[8]) ` but it returns ` Traceback (most recent call last): File "C:\Users\username\PycharmProjects\pythonProject\tutorial.py", line 2, in <module> print(game_board[0]) + " | " + (game_board[1]) + ' | ' + (game_board[2]) ~~~~~~~~~~~~~~~~~~~~~^~~~~~~ TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' `
[ "Is this you want..!?\nCode:-\ngame_board = ['_']*9\nprint(game_board[0]+\" | \"+(game_board[1])+' | '+(game_board[2]))\nprint(game_board[3]+' | '+(game_board[4])+' | '+(game_board[5]))\nprint(game_board[6]+' | '+(game_board[7])+' | '+(game_board[8]))\n\nOutput:-\n_ | _ | _\n_ | _ | _\n_ | _ | _\n\n", "This is because you put the parenthesis wrongly. It should be\ngame_board = ['_'] * 9\nprint(game_board[0] + \" | \" + (game_board[1]) + ' | ' + (game_board[2]))\nprint(game_board[3] + ' | ' + (game_board[4]) + ' | ' + (game_board[5]))\nprint(game_board[6] + ' | ' + (game_board[7]) + ' | ' + (game_board[8]))\n\n", "Please look at the error carefully to find your answer.\nprint(game_board[0]) + \" | \" + (game_board[1]) + ' | ' + (game_board[2])\n~~~~~~~~~~~~~~~~~~~~~^~~~~~~\n\nyou have closed the bracket for game_board[0]. An additional '(' is to be used.\nprint( (game_board[0]) + \" | \" .....\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074663591_python.txt
Q: How can I count the digits of a number with leading zeroes in python In a number without leading zeroes I would do this import math num = 1001 digits = int(math.log10(num))+1 print (digits) >>> 4 but if use a number with leading zeroes like "0001" I get SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers I would like to be able to count the digits including the leading zeroes. What would be the best way to achieve this? A: You can't reasonably have a number with leading digits unless it's a string! Therefore, if you're accepting a string, just remove them and check the difference in length >>> value = input("enter a number: ") enter a number: 0001 >>> value_clean = value.lstrip("0") >>> leading_zeros = len(value) - len(value_clean) >>> print("leading zeros: {}".format(leading_zeros)) 3 If you only wanted the number from a bad input, int() can directly convert it for you instead >>> int("0001") 1 A: I'm dumb. The answer was simple. All I needed was: num = 0001 num_string = str(num) print (len(num_string)) result: >>> 4
How can I count the digits of a number with leading zeroes in python
In a number without leading zeroes I would do this import math num = 1001 digits = int(math.log10(num))+1 print (digits) >>> 4 but if use a number with leading zeroes like "0001" I get SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers I would like to be able to count the digits including the leading zeroes. What would be the best way to achieve this?
[ "You can't reasonably have a number with leading digits unless it's a string!\nTherefore, if you're accepting a string, just remove them and check the difference in length\n>>> value = input(\"enter a number: \")\nenter a number: 0001\n>>> value_clean = value.lstrip(\"0\")\n>>> leading_zeros = len(value) - len(value_clean)\n>>> print(\"leading zeros: {}\".format(leading_zeros))\n3\n\nIf you only wanted the number from a bad input, int() can directly convert it for you instead\n>>> int(\"0001\")\n1\n\n", "I'm dumb. The answer was simple. All I needed was:\nnum = 0001\nnum_string = str(num) \nprint (len(num_string))\n\n\nresult:\n>>> 4\n\n" ]
[ 1, 0 ]
[]
[]
[ "digits", "python" ]
stackoverflow_0074663343_digits_python.txt
Q: getting tensorflow to run on GPU I've been trying to get this to work forever and still no luck I have: GTX 1050 Ti (on Lenovo Legion laptop) the laptop also has an Intel UHD Graphics 630 (i'm not sure if maybe this is interfering?) Anaconda Visual Studio Python 3.9.13 CUDA 11.2 cuDNN 8.1 I added these to the PATH: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\bin C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\libnvvp finally I installed tensorflow and created its own environment and I still can't get it to read my GPU basically followed https://www.youtube.com/watch?v=hHWkvEcDBO0&t=295s AND I'm still having no luck. from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) yields only information on the CPU Can anyone please help? A: You can upgrade tensorflow to 2.0. It should solve your problem. A: Check your tensorflow version and compatability with GPU, update your GPU drivers. CUDA 9/10 would do the job. follow the official tensorflow link: https://www.tensorflow.org/install/pip#windows-native_1 Do all the steps in the same environment in anaconda.
getting tensorflow to run on GPU
I've been trying to get this to work forever and still no luck I have: GTX 1050 Ti (on Lenovo Legion laptop) the laptop also has an Intel UHD Graphics 630 (i'm not sure if maybe this is interfering?) Anaconda Visual Studio Python 3.9.13 CUDA 11.2 cuDNN 8.1 I added these to the PATH: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\bin C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\libnvvp finally I installed tensorflow and created its own environment and I still can't get it to read my GPU basically followed https://www.youtube.com/watch?v=hHWkvEcDBO0&t=295s AND I'm still having no luck. from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) yields only information on the CPU Can anyone please help?
[ "You can upgrade tensorflow to 2.0. It should solve your problem.\n", "Check your tensorflow version and compatability with GPU, update your GPU drivers. CUDA 9/10 would do the job.\nfollow the official tensorflow link:\nhttps://www.tensorflow.org/install/pip#windows-native_1\nDo all the steps in the same environment in anaconda.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074663667_python_tensorflow.txt
Q: How to get the scoreboard to work in Turtle Graphics? **I just need to update the score constantly when the ball crashes into the platform. What also I do not know is how to clone the ball to make multiple balls in the arena If anyone can give some input that would be great also Here is the code I have:** import turtle import random from random import randint import time from turtle import Turtle HEIGHT, WIDTH = 500, 500 screen = turtle.Screen() screen.screensize(HEIGHT, WIDTH) COLORS = 'white', 'green' ,'cyan', 'orange', 'skyblue' screen.bgcolor(random.choice(COLORS)) screen.title("Bounce a ball") CURSOR_SIZE = 20 def tDirection(direct): t.setheading(direct) # make arena def rectangle(): t.pendown() for i in range(2): t.forward(600) t.left(90) t.forward(600) t.left(90) t.penup() #defines new turtle pen = turtle.Turtle() #right and left keys def move_left(): pen.penup() pen.setheading(0) pen.bk(100) def move_right(): pen.penup() pen.setheading(0) pen.fd(100) #plaform########################### pen.penup() pen.goto(0, -250) pen.shape("square") pen.color("black") pen.shapesize(1, 5) screen.listen() screen.onkey(move_right, "Right") screen.onkey(move_left, "Left") ##################################### n = turtle.Turtle() score = 0 n.penup() n.goto(-50,250) n.write("Your score:", font=20) n.hideturtle() #circle###################################### t = Turtle("circle", visible=False) t.speed('fastest') t.pensize(5) t.penup() t.goto(-300, -300) ########################################### rectangle() index = 0 ##################################### t.color('black') t.home() t.showturtle() ##################################### direct = randint(1, 600) tDirection(direct) while True: t.forward(2) ty = t.ycor() def is_collided_with(a, b): return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10 # breaking out top or bottom if is_collided_with(t, pen): score += 1 print("Coll") continue if not CURSOR_SIZE - 300 <= ty <= 300 - CURSOR_SIZE: index += 1 t.color('pink') angleCurr = t.heading() if 0 < angleCurr < 180: tDirection(0 - angleCurr) else: tDirection(360 - angleCurr) t.forward(2) n.getscreen().update() tx = t.xcor() # breaking out left or right if not CURSOR_SIZE - 300 <= tx <= 300 - CURSOR_SIZE: index += 1 t.color('blue') angleCurr = t.heading() if 0 < angleCurr < 180: tDirection(180 - angleCurr) else: tDirection(540 - angleCurr) t.forward(2) Most of game is working I just do not know how to write a scoreboard and how to make it run smoothly. A: To create a scoreboard in this code, you can add a variable to keep track of the score and display it on the screen. Here is how you can do that: Add a variable to keep track of the score. You can do this by adding the following line at the top of the code, after the import statements: score = 0 Add code to update the score when the ball collides with the platform. You can do this by modifying the is_collided_with() function to increment the score variable by 1 when a collision is detected. The modified function should look like this: def is_collided_with(a, b): if abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10: score += 1 return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10 Add code to display the score on the screen. You can do this by creating a new Turtle object and using its write() method to write the score to the screen. You can add the following code after the rectangle() function to create the Turtle object and write the score to the screen: # Create a new Turtle object to write the score score_turtle = turtle.Turtle() score_turtle.penup() score_turtle.goto(-50, 250) score_turtle.write("Your score: {}".format(score), font=20) score_turtle.hideturtle() Add code to update the score on the screen. You can do this by adding a line of code to the while loop that updates the score written on the screen. You can add the following line of code inside the while loop, after the continue statement: score_turtle.clear() score_turtle.write("Your score: {}".format(score), font -chatgpt
How to get the scoreboard to work in Turtle Graphics?
**I just need to update the score constantly when the ball crashes into the platform. What also I do not know is how to clone the ball to make multiple balls in the arena If anyone can give some input that would be great also Here is the code I have:** import turtle import random from random import randint import time from turtle import Turtle HEIGHT, WIDTH = 500, 500 screen = turtle.Screen() screen.screensize(HEIGHT, WIDTH) COLORS = 'white', 'green' ,'cyan', 'orange', 'skyblue' screen.bgcolor(random.choice(COLORS)) screen.title("Bounce a ball") CURSOR_SIZE = 20 def tDirection(direct): t.setheading(direct) # make arena def rectangle(): t.pendown() for i in range(2): t.forward(600) t.left(90) t.forward(600) t.left(90) t.penup() #defines new turtle pen = turtle.Turtle() #right and left keys def move_left(): pen.penup() pen.setheading(0) pen.bk(100) def move_right(): pen.penup() pen.setheading(0) pen.fd(100) #plaform########################### pen.penup() pen.goto(0, -250) pen.shape("square") pen.color("black") pen.shapesize(1, 5) screen.listen() screen.onkey(move_right, "Right") screen.onkey(move_left, "Left") ##################################### n = turtle.Turtle() score = 0 n.penup() n.goto(-50,250) n.write("Your score:", font=20) n.hideturtle() #circle###################################### t = Turtle("circle", visible=False) t.speed('fastest') t.pensize(5) t.penup() t.goto(-300, -300) ########################################### rectangle() index = 0 ##################################### t.color('black') t.home() t.showturtle() ##################################### direct = randint(1, 600) tDirection(direct) while True: t.forward(2) ty = t.ycor() def is_collided_with(a, b): return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10 # breaking out top or bottom if is_collided_with(t, pen): score += 1 print("Coll") continue if not CURSOR_SIZE - 300 <= ty <= 300 - CURSOR_SIZE: index += 1 t.color('pink') angleCurr = t.heading() if 0 < angleCurr < 180: tDirection(0 - angleCurr) else: tDirection(360 - angleCurr) t.forward(2) n.getscreen().update() tx = t.xcor() # breaking out left or right if not CURSOR_SIZE - 300 <= tx <= 300 - CURSOR_SIZE: index += 1 t.color('blue') angleCurr = t.heading() if 0 < angleCurr < 180: tDirection(180 - angleCurr) else: tDirection(540 - angleCurr) t.forward(2) Most of game is working I just do not know how to write a scoreboard and how to make it run smoothly.
[ "To create a scoreboard in this code, you can add a variable to keep track of the score and display it on the screen. Here is how you can do that:\nAdd a variable to keep track of the score. You can do this by adding the following line at the top of the code, after the import statements:\nscore = 0\n\nAdd code to update the score when the ball collides with the platform. You can do this by modifying the is_collided_with() function to increment the score variable by 1 when a collision is detected. The modified function should look like this:\ndef is_collided_with(a, b):\n if abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10:\n score += 1\n return abs(a.xcor() - b.xcor()) < 10 and abs(a.ycor() - b.ycor()) < 10\n\nAdd code to display the score on the screen. You can do this by creating a new Turtle object and using its write() method to write the score to the screen. You can add the following code after the rectangle() function to create the Turtle object and write the score to the screen:\n# Create a new Turtle object to write the score\nscore_turtle = turtle.Turtle()\nscore_turtle.penup()\nscore_turtle.goto(-50, 250)\nscore_turtle.write(\"Your score: {}\".format(score), font=20)\nscore_turtle.hideturtle()\n\nAdd code to update the score on the screen. You can do this by adding a line of code to the while loop that updates the score written on the screen. You can add the following line of code inside the while loop, after the continue statement:\nscore_turtle.clear()\nscore_turtle.write(\"Your score: {}\".format(score), font\n\n\n-chatgpt\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_turtle", "turtle_graphics" ]
stackoverflow_0074663758_python_python_3.x_python_turtle_turtle_graphics.txt
Q: I don't understand why my class variables are undefined and can't be accessed I am trying to create a poker game in python using classes. the first thing i am trying to do is to create a deck. this is my code : class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for i in rank for j in suit] def __init__(self): pass Here, I want the deck to be a class variable since it will never change in my program. Since it'll stay constant, I don't want to include it in my init function. However, when I try to do this, I get this error : Traceback (most recent call last): File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 2, in <module> class Poker: File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 5, in Poker original_deck = [(i + j) for i in rank for j in suit] File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 5, in <listcomp> original_deck = [(i + j) for i in rank for j in suit] NameError: name 'suit' is not defined. Did you mean: 'quit'? When I include my original deck in my init function, it magically works, which I don't understand. Why can't I do this ? A: Use self to reference class attributes. In Python, class attributes should be accessed using the self keyword. This makes the code more readable and helps avoid naming conflicts. You can modify your code to use self to reference the rank and suit attributes like this: class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for I in self.rank for j in self.suit] def __init__(self): pass Use a list comprehension to create the deck of cards. Your code uses a for loop to create the deck of cards, but this can be done more efficiently using a list comprehension. You can modify your code to use a list comprehension like this: class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for I in self.rank for j in self.suit] def __init__(self): pass def create_deck(self): self.deck = [card for card in self.original_deck] Use random.shuffle() to shuffle the deck of cards. In Python, the random.shuffle() function can be used to shuffle a list of items in place. This is more efficient than creating a new list of shuffled items and is also more convenient because it modifies the existing list. You can use random.shuffle() to shuffle the deck of cards like this: import random class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for I in self.rank for j in self.suit] def __init__(self): pass def create_deck(self): self.deck = [card for card in self.original_deck] random.shuffle(self.deck)
I don't understand why my class variables are undefined and can't be accessed
I am trying to create a poker game in python using classes. the first thing i am trying to do is to create a deck. this is my code : class Poker: rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K'] suit = ["D", "C", "S", "H"] original_deck = [(i + j) for i in rank for j in suit] def __init__(self): pass Here, I want the deck to be a class variable since it will never change in my program. Since it'll stay constant, I don't want to include it in my init function. However, when I try to do this, I get this error : Traceback (most recent call last): File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 2, in <module> class Poker: File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 5, in Poker original_deck = [(i + j) for i in rank for j in suit] File "C:\Users\14384\PycharmProjects\Assignment 4\scrap.py", line 5, in <listcomp> original_deck = [(i + j) for i in rank for j in suit] NameError: name 'suit' is not defined. Did you mean: 'quit'? When I include my original deck in my init function, it magically works, which I don't understand. Why can't I do this ?
[ "Use self to reference class attributes. In Python, class attributes should be accessed using the self keyword. This makes the code more readable and helps avoid naming conflicts. You can modify your code to use self to reference the rank and suit attributes like this:\nclass Poker:\n rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']\n suit = [\"D\", \"C\", \"S\", \"H\"]\n original_deck = [(i + j) for I in self.rank for j in self.suit]\n def __init__(self):\n pass\n\n\nUse a list comprehension to create the deck of cards. Your code uses a for loop to create the deck of cards, but this can be done more efficiently using a list comprehension. You can modify your code to use a list comprehension like this:\nclass Poker:\n rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']\n suit = [\"D\", \"C\", \"S\", \"H\"]\n original_deck = [(i + j) for I in self.rank for j in self.suit]\n def __init__(self):\n pass\n\n def create_deck(self):\n self.deck = [card for card in self.original_deck]\n\n\nUse random.shuffle() to shuffle the deck of cards. In Python, the random.shuffle() function can be used to shuffle a list of items in place. This is more efficient than creating a new list of shuffled items and is also more convenient because it modifies the existing list. You can use random.shuffle() to shuffle the deck of cards like this:\nimport random\n\nclass Poker:\n rank = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']\n suit = [\"D\", \"C\", \"S\", \"H\"]\n original_deck = [(i + j) for I in self.rank for j in self.suit]\n def __init__(self):\n pass\n\n def create_deck(self):\n self.deck = [card for card in self.original_deck]\n random.shuffle(self.deck)\n\n\n" ]
[ 1 ]
[]
[]
[ "class", "oop", "python", "python_3.x", "scope" ]
stackoverflow_0074663772_class_oop_python_python_3.x_scope.txt
Q: How do I create a function that will end the program? I have difficulties creating a counter (which is errorCount) for my while loop statement. I want my counter to function so that if the user answered a question incorrectly 5 times the program will terminate. furthermore, I have 3 questions for the user and I want to accumulate all the errorCounts so that if it hit 5 the program will terminate. for example: if the user answers question 1 incorrectly twice then the errorCount will be two. If the user answers question 2 incorrectly three times then the program will be terminated. However, the program is allowing the user to make 5 mistakes for every problem. # Level 5: print("You have the jewel in your possession, and defeated Joker at his own game") print("You now hold the precious jewel in your hands, but it's not over, you must leave the maze!") print("*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*") # put an error limit # space everything out to make it look more neat # Make sure you can fail the level **errorCount = 0** position = 0 while True: answer1 = input("Choose either Right, Left, Straight: ") try: if answer1.lower() == "right": print("You have chosen the correct path, now you proceed to the next step!") print() break * if errorCount == 5: print("you made too many mistakes and got captured, you have to restart")* elif answer1.lower() == "left": print("You see a boulder blocking your path which forces you to go back.") errorCount = 1 + errorCount elif answer1.lower() == "straight": print("On your way to the next stage you are exposed to a toxic gas that forces you to go back .") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") # if errors >= 5: while True: answer1 = input("Choose either Right, Left, Straight: ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if answer1.lower() == "straight": print("You have chosen the correct path, now you proceed to the next step!") break elif answer1.lower() == "left": print("You chose the wrong path, go back") errorCount = 1 + errorCount elif answer1.lower() == "right": print("You chose the wrong path, go back") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") print("You are now on the third stage, you notice a screen that is asking you a riddle") while True: riddle1 = input("What gets wet when drying? ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if riddle1.lower() == "towel": print("You have chosen the correct answer") print("The giant stone blocking the entrance of the maze opens, and the outside lights shine through..") break else: print("Incorrect! Try again..") errorCount = 1 + errorCount print("Heres a hint: You use it after taking a shower...") except Exception: print("Incorrect! Try again..") errorCount = 1 + errorCount I do not know how to fix this issue A: You have overly complicated the code. questions = ["You have the jewel in your possession, and defeated Joker at his own game", "You now hold the precious jewel in your hands, but it's not over, you must leave the maze!", "*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*"] error_count = 0 for id, query in enumerate(questions): if id == 0: # call method for query 1 # write your while error_count < 5 loop inside the method # return error_count to check. pass elif id == 1: pass elif id == 2: pass if error_count > 5: break You can also raise a User warning if you use try/except. except UserWarning: if error_count > 5: print("you made too many mistakes and got captured, you have to restart") break A: You just forgot to put the errorCount conditional in the last loop, also it is better that you put this before the user input so that it doesn't ask the question 6 times instead of the 5 you want. Finally, it is necessary to add a break at the end of the conditional so that there is not an infinite loop # Level 5: print("You have the jewel in your possession, and defeated Joker at his own game") print("You now hold the precious jewel in your hands, but it's not over, you must leave the maze!") print("*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*") # put an error limit # space everything out to make it look more neat # Make sure you can fail the level errorCount = 0 position = 0 while True: if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") break answer1 = input("Choose either Right, Left, Straight: ") try: if answer1.lower() == "right": print("You have chosen the correct path, now you proceed to the next step!") print() break elif answer1.lower() == "left": print("You see a boulder blocking your path which forces you to go back.") errorCount = 1 + errorCount elif answer1.lower() == "straight": print("On your way to the next stage you are exposed to a toxic gas that forces you to go back .") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") # if errors >= 5: while True: if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") break answer1 = input("Choose either Right, Left, Straight: ") try: if answer1.lower() == "straight": print("You have chosen the correct path, now you proceed to the next step!") break elif answer1.lower() == "left": print("You chose the wrong path, go back") errorCount = 1 + errorCount elif answer1.lower() == "right": print("You chose the wrong path, go back") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") print("You are now on the third stage, you notice a screen that is asking you a riddle") while True: if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") break riddle1 = input("What gets wet when drying? ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if riddle1.lower() == "towel": print("You have chosen the correct answer") print("The giant stone blocking the entrance of the maze opens, and the outside lights shine through..") break else: print("Incorrect! Try again..") errorCount = 1 + errorCount print("Heres a hint: You use it after taking a shower...") except Exception: print("Incorrect! Try again..") errorCount = 1 + errorCount I recommend that instead of using: errorcount = 1 + errorcount It is better to use: errorcount += 1
How do I create a function that will end the program?
I have difficulties creating a counter (which is errorCount) for my while loop statement. I want my counter to function so that if the user answered a question incorrectly 5 times the program will terminate. furthermore, I have 3 questions for the user and I want to accumulate all the errorCounts so that if it hit 5 the program will terminate. for example: if the user answers question 1 incorrectly twice then the errorCount will be two. If the user answers question 2 incorrectly three times then the program will be terminated. However, the program is allowing the user to make 5 mistakes for every problem. # Level 5: print("You have the jewel in your possession, and defeated Joker at his own game") print("You now hold the precious jewel in your hands, but it's not over, you must leave the maze!") print("*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*") # put an error limit # space everything out to make it look more neat # Make sure you can fail the level **errorCount = 0** position = 0 while True: answer1 = input("Choose either Right, Left, Straight: ") try: if answer1.lower() == "right": print("You have chosen the correct path, now you proceed to the next step!") print() break * if errorCount == 5: print("you made too many mistakes and got captured, you have to restart")* elif answer1.lower() == "left": print("You see a boulder blocking your path which forces you to go back.") errorCount = 1 + errorCount elif answer1.lower() == "straight": print("On your way to the next stage you are exposed to a toxic gas that forces you to go back .") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") # if errors >= 5: while True: answer1 = input("Choose either Right, Left, Straight: ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if answer1.lower() == "straight": print("You have chosen the correct path, now you proceed to the next step!") break elif answer1.lower() == "left": print("You chose the wrong path, go back") errorCount = 1 + errorCount elif answer1.lower() == "right": print("You chose the wrong path, go back") errorCount = 1 + errorCount else: print("Wrong input. Please try again..") errorCount = 1 + errorCount except Exception: print("Wrong input. Please try again..") print("You are now on the third stage, you notice a screen that is asking you a riddle") while True: riddle1 = input("What gets wet when drying? ") if errorCount == 5: print("you made too many mistakes and got captured, you have to restart") try: if riddle1.lower() == "towel": print("You have chosen the correct answer") print("The giant stone blocking the entrance of the maze opens, and the outside lights shine through..") break else: print("Incorrect! Try again..") errorCount = 1 + errorCount print("Heres a hint: You use it after taking a shower...") except Exception: print("Incorrect! Try again..") errorCount = 1 + errorCount I do not know how to fix this issue
[ "You have overly complicated the code.\nquestions = [\"You have the jewel in your possession, and defeated Joker at his own game\",\n\"You now hold the precious jewel in your hands, but it's not over, you must leave the maze!\",\n\"*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*\"]\n\nerror_count = 0\n\nfor id, query in enumerate(questions):\n\n if id == 0:\n # call method for query 1\n # write your while error_count < 5 loop inside the method\n # return error_count to check.\n pass\n elif id == 1:\n pass\n elif id == 2:\n pass\n \n if error_count > 5:\n break\n\nYou can also raise a User warning if you use try/except.\nexcept UserWarning:\n if error_count > 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n break\n\n", "You just forgot to put the errorCount conditional in the last loop, also it is better that you put this before the user input so that it doesn't ask the question 6 times instead of the 5 you want. Finally, it is necessary to add a break at the end of the conditional so that there is not an infinite loop\n# Level 5:\nprint(\"You have the jewel in your possession, and defeated Joker at his own game\")\nprint(\"You now hold the precious jewel in your hands, but it's not over, you must leave the maze!\")\nprint(\"*You must now choose 'Right', 'Left', or 'Straight' as you exit the maze. Keep trying until you find your path.*\")\n\n# put an error limit\n# space everything out to make it look more neat\n# Make sure you can fail the level\n\nerrorCount = 0\n\nposition = 0\nwhile True:\n if errorCount == 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n break\n \n answer1 = input(\"Choose either Right, Left, Straight: \")\n \n try:\n if answer1.lower() == \"right\":\n print(\"You have chosen the correct path, now you proceed to the next step!\")\n print()\n break\n \n elif answer1.lower() == \"left\":\n print(\"You see a boulder blocking your path which forces you to go back.\")\n errorCount = 1 + errorCount\n \n elif answer1.lower() == \"straight\":\n print(\"On your way to the next stage you are exposed to a toxic gas that forces you to go back .\")\n errorCount = 1 + errorCount\n \n else:\n print(\"Wrong input. Please try again..\")\n errorCount = 1 + errorCount\n except Exception:\n print(\"Wrong input. Please try again..\")\n\n# if errors >= 5:\n\nwhile True:\n if errorCount == 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n break\n \n answer1 = input(\"Choose either Right, Left, Straight: \")\n \n try:\n if answer1.lower() == \"straight\":\n print(\"You have chosen the correct path, now you proceed to the next step!\")\n break\n \n elif answer1.lower() == \"left\":\n print(\"You chose the wrong path, go back\")\n errorCount = 1 + errorCount\n \n elif answer1.lower() == \"right\":\n print(\"You chose the wrong path, go back\")\n errorCount = 1 + errorCount\n \n else:\n print(\"Wrong input. Please try again..\")\n errorCount = 1 + errorCount\n \n except Exception:\n print(\"Wrong input. Please try again..\")\n\nprint(\"You are now on the third stage, you notice a screen that is asking you a riddle\")\n\nwhile True:\n if errorCount == 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n break\n \n riddle1 = input(\"What gets wet when drying? \")\n \n if errorCount == 5:\n print(\"you made too many mistakes and got captured, you have to restart\")\n\n try:\n if riddle1.lower() == \"towel\":\n print(\"You have chosen the correct answer\")\n print(\"The giant stone blocking the entrance of the maze opens, and the outside lights shine through..\")\n break\n \n else:\n print(\"Incorrect! Try again..\")\n errorCount = 1 + errorCount\n print(\"Heres a hint: You use it after taking a shower...\")\n \n except Exception:\n print(\"Incorrect! Try again..\")\n errorCount = 1 + errorCount\n\nI recommend that instead of using:\nerrorcount = 1 + errorcount\n\nIt is better to use:\nerrorcount += 1\n\n" ]
[ 0, 0 ]
[]
[]
[ "for_loop", "if_statement", "python", "spyder", "while_loop" ]
stackoverflow_0074663626_for_loop_if_statement_python_spyder_while_loop.txt
Q: reviews of a firm My goal is to scrape the entire reviews of this firm. I tried manipulating @Driftr95 codes: def extract(pg): headers = {'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'} url = f'https://www.glassdoor.com/Reviews/3M-Reviews-E446_P{pg}.htm?filter.iso3Language=eng' # f'https://www.glassdoor.com/Reviews/Google-Engineering-Reviews-EI_IE9079.0,6_DEPT1007_IP{pg}.htm?sort.sortType=RD&sort.ascending=false&filter.iso3Language=eng' r = requests.get(url, headers, timeout=(3.05, 27)) soup = BeautifulSoup(r.content, 'html.parser')# this a soup function that retuen the whole html return soup for j in range(1,21,10): for i in range(j+1,j+11,1): #3M: 4251 reviews soup = extract( f'https://www.glassdoor.com/Reviews/3M-Reviews-E446_P{i}.htm?filter.iso3Language=eng') print(f' page {i}') for r in soup.select('li[id^="empReview_"]'): rDet = {'reviewId': r.get('id')} for sr in r.select(subRatSel): k = sr.select_one('div:first-of-type').get_text(' ').strip() sval = getDECstars(sr.select_one('div:nth-of-type(2)'), soup) rDet[f'[rating] {k}'] = sval for k, sel in refDict.items(): sval = r.select_one(sel) if sval: sval = sval.get_text(' ').strip() rDet[k] = sval empRevs.append(rDet) In the case where not all the subratings are always available, all four subratings will turn out to be N.A. A: All four subratings will turn out to be N.A. there were some things that I didn't account for because I hadn't encountered them before, but the updated version of getDECstars shouldn't have that issue. (If you use the longer version with argument isv=True, it's easier to debug and figure out what's missing from the code...) I scraped 200 reviews in this case, and it turned out that only 170 unique reviews Duplicates are fairly easy to avoid by maintaining a list of reviewIds that have already been added and checking against it before adding a new review to empRevs scrapedIds = [] # for... # for ### # soup = extract... # for r in ... if r.get('id') in scrapedIds: continue # skip duplicate ## rDet = ..... ## AND REST OF INNER FOR-LOOP ## empRevs.append(rDet) scrapedIds.append(rDet['reviewId']) # add to list of ids to check against Https tends to time out after 100 rounds... You could try adding breaks and switching out user-agents every 50 [or 5 or 10 or...] requests, but I'm quick to resort to selenium at times like this; this is my suggested solution - if you just call it like this and pass a url to start with: ## PASTE [OR DOWNLOAD&IMPORT] from https://pastebin.com/RsFHWNnt ## startUrl = 'https://www.glassdoor.com/Reviews/3M-Reviews-E446.htm?sort.sortType=RD&sort.ascending=false&filter.iso3Language=eng' scrape_gdRevs(startUrl, 'empRevs_3M.csv', maxScrapes=1000, constBreak=False) [last 3 lines of] printed output: total reviews: 4252 total reviews scraped this run: 4252 total reviews scraped over all time: 4252 It clicks through the pages until it reaches the last page (or maxes out maxScrapes). You do have to log in at the beginning though, so fill out login_to_gd with your username and password or log in manually by replacing the login_to_gd(driverG) line with the input(...) line that waits for you to login [then press ENTER in the terminal] before continuing. I think cookies can also be used instead (with requests), but I'm not good at handling that. If you figure it out, then you can use some version of linkToSoup or your extract(pg); then, you'll have to comment out or remove the lines ending in ## for selenium and uncomment [or follow instructions from] the lines that end with ## without selenium. [But please note that I've only fully tested the selenium version.] The CSVs [like "empRevs_3M.csv" and "scrapeLogs_empRevs_3M.csv" in this example] are updated after every page-scrape, so even if the program crashes [or you decide to interrupt it], it will have saved upto the previous scrape. Since it also tries to load form the CSVs at the beginning, you can just continue it later (just set startUrl to the url of the page you want to continue from - but even if it's at page 1, remember that duplicates will be ignored, so it's okay - it'll just waste some time though).
reviews of a firm
My goal is to scrape the entire reviews of this firm. I tried manipulating @Driftr95 codes: def extract(pg): headers = {'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'} url = f'https://www.glassdoor.com/Reviews/3M-Reviews-E446_P{pg}.htm?filter.iso3Language=eng' # f'https://www.glassdoor.com/Reviews/Google-Engineering-Reviews-EI_IE9079.0,6_DEPT1007_IP{pg}.htm?sort.sortType=RD&sort.ascending=false&filter.iso3Language=eng' r = requests.get(url, headers, timeout=(3.05, 27)) soup = BeautifulSoup(r.content, 'html.parser')# this a soup function that retuen the whole html return soup for j in range(1,21,10): for i in range(j+1,j+11,1): #3M: 4251 reviews soup = extract( f'https://www.glassdoor.com/Reviews/3M-Reviews-E446_P{i}.htm?filter.iso3Language=eng') print(f' page {i}') for r in soup.select('li[id^="empReview_"]'): rDet = {'reviewId': r.get('id')} for sr in r.select(subRatSel): k = sr.select_one('div:first-of-type').get_text(' ').strip() sval = getDECstars(sr.select_one('div:nth-of-type(2)'), soup) rDet[f'[rating] {k}'] = sval for k, sel in refDict.items(): sval = r.select_one(sel) if sval: sval = sval.get_text(' ').strip() rDet[k] = sval empRevs.append(rDet) In the case where not all the subratings are always available, all four subratings will turn out to be N.A.
[ "\nAll four subratings will turn out to be N.A.\n\nthere were some things that I didn't account for because I hadn't encountered them before, but the updated version of getDECstars shouldn't have that issue. (If you use the longer version with argument isv=True, it's easier to debug and figure out what's missing from the code...)\n\n\nI scraped 200 reviews in this case, and it turned out that only 170 unique reviews\n\nDuplicates are fairly easy to avoid by maintaining a list of reviewIds that have already been added and checking against it before adding a new review to empRevs\nscrapedIds = []\n# for...\n # for ###\n # soup = extract...\n\n # for r in ...\n if r.get('id') in scrapedIds: continue # skip duplicate\n ## rDet = ..... ## AND REST OF INNER FOR-LOOP ##\n\n empRevs.append(rDet) \n scrapedIds.append(rDet['reviewId']) # add to list of ids to check against\n\n\n\nHttps tends to time out after 100 rounds...\n\nYou could try adding breaks and switching out user-agents every 50 [or 5 or 10 or...] requests, but I'm quick to resort to selenium at times like this; this is my suggested solution - if you just call it like this and pass a url to start with:\n## PASTE [OR DOWNLOAD&IMPORT] from https://pastebin.com/RsFHWNnt ##\n\nstartUrl = 'https://www.glassdoor.com/Reviews/3M-Reviews-E446.htm?sort.sortType=RD&sort.ascending=false&filter.iso3Language=eng'\nscrape_gdRevs(startUrl, 'empRevs_3M.csv', maxScrapes=1000, constBreak=False)\n\n\n[last 3 lines of] printed output:\n total reviews: 4252\ntotal reviews scraped this run: 4252\ntotal reviews scraped over all time: 4252\n\n\nIt clicks through the pages until it reaches the last page (or maxes out maxScrapes). You do have to log in at the beginning though, so fill out login_to_gd with your username and password or log in manually by replacing the login_to_gd(driverG) line with the input(...) line that waits for you to login [then press ENTER in the terminal] before continuing.\nI think cookies can also be used instead (with requests), but I'm not good at handling that. If you figure it out, then you can use some version of linkToSoup or your extract(pg); then, you'll have to comment out or remove the lines ending in ## for selenium and uncomment [or follow instructions from] the lines that end with ## without selenium. [But please note that I've only fully tested the selenium version.]\nThe CSVs [like \"empRevs_3M.csv\" and \"scrapeLogs_empRevs_3M.csv\" in this example] are updated after every page-scrape, so even if the program crashes [or you decide to interrupt it], it will have saved upto the previous scrape. Since it also tries to load form the CSVs at the beginning, you can just continue it later (just set startUrl to the url of the page you want to continue from - but even if it's at page 1, remember that duplicates will be ignored, so it's okay - it'll just waste some time though).\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "web_scraping" ]
stackoverflow_0074650912_beautifulsoup_python_selenium_web_scraping.txt
Q: I'm finding it hard to understand how functions work. Would someome mind explaining them? Please excuse the extra modulus. I've taken a small part of my code out to convert it into functions to make my code less messy. However I'm finding it really hard to understand how I put values in and take them out to print or do things with. See the code I'm using below. VideoURL would be replaced with a url of a video. ` from urllib.request import urlopen from bs4 import BeautifulSoup import requests from pytube import YouTube from pytube import Channel channelURL = "videoURL" YouTubeDomain = "https://www.youtube.com/channel/" def BeautifulSoup(Link): soup = BeautifulSoup(requests.get(Link, cookies={'CONSENT': 'YES+1'}).text, "html.parser") data = re.search(r"var ytInitialData = ({.*});", str(soup.prettify())).group(1) json_data = json.loads(data) channel_id = json_data["header"]["c4TabbedHeaderRenderer"]["channelId"] channel_name = json_data["header"]["c4TabbedHeaderRenderer"]["title"] channel_logo = json_data["header"]["c4TabbedHeaderRenderer"]["avatar"]["thumbnails"][2]["url"] channel_id_link = YouTubeDomain+channel_id print("Channel ID: "+channel_id) print("Channel Name: "+channel_name) print("Channel Logo: "+channel_logo) print("Channel ID: "+channel_id_link) def vVersion(*arg): YTV = YouTube(channelURL) channel_id = YTV.channel_id channel_id_link = YTV.channel_url c = Channel(channel_id_link) channel_name =c.channel_name return channel_id_link, channelURL channel_id_link, video = vVersion() print(channel_id_link) Link = channel_id_link print(Link) Test = print(BeautifulSoup(Link)) Test() So the errors I keep getting are about having too many or too few args for the functions . Here's the current error: ` BeautifulSoup() takes 1 positional argument but 2 were given File "C:\Users\Admin\test\video1.py", line 26, in BeautifulSoup soup = BeautifulSoup(requests.get(Link, cookies={'CONSENT': 'YES+1'}).text, "html.parser") File "C:\Users\Admin\test\video1.py", line 53, in <module> Test = print(BeautifulSoup(Link)) `I know I'm missing something very simple. Any help would be welcome, thank you! ` I have tried to take the code out of my main code to isolate the issue. I was expecting to gain a perspective on the issue. I tried the following code to train myself on functions but it didn't really help me fix the issue I'm having with my project. def test(): name = (input("Enter your name?")) favNumber = (input("Please enter your best number?")) return name, favNumber name, favNumber = test() print(name) print(float(favNumber)) A: It's because you have named your function as BeautifulSoup which is as same as the name of the function from the library you have imported. Instead of using the function BeautifulSoup from bs4, it is now running the code you have defined which takes only one argument. So give your function another name.
I'm finding it hard to understand how functions work. Would someome mind explaining them?
Please excuse the extra modulus. I've taken a small part of my code out to convert it into functions to make my code less messy. However I'm finding it really hard to understand how I put values in and take them out to print or do things with. See the code I'm using below. VideoURL would be replaced with a url of a video. ` from urllib.request import urlopen from bs4 import BeautifulSoup import requests from pytube import YouTube from pytube import Channel channelURL = "videoURL" YouTubeDomain = "https://www.youtube.com/channel/" def BeautifulSoup(Link): soup = BeautifulSoup(requests.get(Link, cookies={'CONSENT': 'YES+1'}).text, "html.parser") data = re.search(r"var ytInitialData = ({.*});", str(soup.prettify())).group(1) json_data = json.loads(data) channel_id = json_data["header"]["c4TabbedHeaderRenderer"]["channelId"] channel_name = json_data["header"]["c4TabbedHeaderRenderer"]["title"] channel_logo = json_data["header"]["c4TabbedHeaderRenderer"]["avatar"]["thumbnails"][2]["url"] channel_id_link = YouTubeDomain+channel_id print("Channel ID: "+channel_id) print("Channel Name: "+channel_name) print("Channel Logo: "+channel_logo) print("Channel ID: "+channel_id_link) def vVersion(*arg): YTV = YouTube(channelURL) channel_id = YTV.channel_id channel_id_link = YTV.channel_url c = Channel(channel_id_link) channel_name =c.channel_name return channel_id_link, channelURL channel_id_link, video = vVersion() print(channel_id_link) Link = channel_id_link print(Link) Test = print(BeautifulSoup(Link)) Test() So the errors I keep getting are about having too many or too few args for the functions . Here's the current error: ` BeautifulSoup() takes 1 positional argument but 2 were given File "C:\Users\Admin\test\video1.py", line 26, in BeautifulSoup soup = BeautifulSoup(requests.get(Link, cookies={'CONSENT': 'YES+1'}).text, "html.parser") File "C:\Users\Admin\test\video1.py", line 53, in <module> Test = print(BeautifulSoup(Link)) `I know I'm missing something very simple. Any help would be welcome, thank you! ` I have tried to take the code out of my main code to isolate the issue. I was expecting to gain a perspective on the issue. I tried the following code to train myself on functions but it didn't really help me fix the issue I'm having with my project. def test(): name = (input("Enter your name?")) favNumber = (input("Please enter your best number?")) return name, favNumber name, favNumber = test() print(name) print(float(favNumber))
[ "It's because you have named your function as BeautifulSoup which is as same as the name of the function from the library you have imported. Instead of using the function BeautifulSoup from bs4, it is now running the code you have defined which takes only one argument. So give your function another name.\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "function", "python", "pytube" ]
stackoverflow_0074663775_beautifulsoup_function_python_pytube.txt
Q: How to Split a column into two by comma delimiter, and put a value without comma in second column and not in first? I have a column in a df that I want to split into two columns splitting by comma delimiter. If the value in that column does not have a comma I want to put that into the second column instead of first. Origin New York, USA England Russia London, England California, USA USA I want the result to be: Location Country New York USA NaN England NaN Russia London England California USA NaN USA I used this code df['Location'], df['Country'] = df['Origin'].str.split(',', 1) A: We can try using str.extract here: df["Location"] = df["Origin"].str.extract(r'(.*),') df["Country"] = df["Origin"].str.extract(r'(\w+(?: \w+)*)$') A: Here is a way by using str.extract() and named groups df['Origin'].str.extract(r'(?P<Location>[A-Za-z ]+(?=,))?(?:, )?(?P<Country>\w+)') Output: Location Country 0 New York USA 1 NaN England 2 NaN Russia 3 London England 4 California USA 5 NaN USA
How to Split a column into two by comma delimiter, and put a value without comma in second column and not in first?
I have a column in a df that I want to split into two columns splitting by comma delimiter. If the value in that column does not have a comma I want to put that into the second column instead of first. Origin New York, USA England Russia London, England California, USA USA I want the result to be: Location Country New York USA NaN England NaN Russia London England California USA NaN USA I used this code df['Location'], df['Country'] = df['Origin'].str.split(',', 1)
[ "We can try using str.extract here:\ndf[\"Location\"] = df[\"Origin\"].str.extract(r'(.*),')\ndf[\"Country\"] = df[\"Origin\"].str.extract(r'(\\w+(?: \\w+)*)$')\n\n", "Here is a way by using str.extract() and named groups\ndf['Origin'].str.extract(r'(?P<Location>[A-Za-z ]+(?=,))?(?:, )?(?P<Country>\\w+)')\n\nOutput:\n Location Country\n0 New York USA\n1 NaN England\n2 NaN Russia\n3 London England\n4 California USA\n5 NaN USA\n\n" ]
[ 2, 0 ]
[]
[]
[ "multiple_columns", "pandas", "python", "split" ]
stackoverflow_0070795642_multiple_columns_pandas_python_split.txt
Q: python requests not work with vpn ProxyError('Cannot connect to proxy.', I use requests with vpn and it show error (Caused by ProxyError('Cannot connect to proxy.', OSError(0, 'Error'))) this is code import requests con = requests.get(url) I can visit url in browser with vpn. I hav to use vpn to requests. use Python 3.7.9 A: using pyPAC works for me... https://pypac.readthedocs.io/en/latest/ from pypac import PACSession from requests.auth import HTTPProxyAuth session = PACSession() r = session.get('http://google.com') you may need to update your python version or use an older version of pyPAC that matches your python version.
python requests not work with vpn ProxyError('Cannot connect to proxy.',
I use requests with vpn and it show error (Caused by ProxyError('Cannot connect to proxy.', OSError(0, 'Error'))) this is code import requests con = requests.get(url) I can visit url in browser with vpn. I hav to use vpn to requests. use Python 3.7.9
[ "using pyPAC works for me...\nhttps://pypac.readthedocs.io/en/latest/\nfrom pypac import PACSession\nfrom requests.auth import HTTPProxyAuth\nsession = PACSession()\nr = session.get('http://google.com')\n\nyou may need to update your python version or use an older version of pyPAC that matches your python version.\n" ]
[ 0 ]
[]
[]
[ "networking", "python", "python_requests", "urllib", "vpn" ]
stackoverflow_0074106849_networking_python_python_requests_urllib_vpn.txt
Q: How do I find the other elements in a list given one of them? Given one element in a list, what is the most efficient way that I can find the other elements? (e.g. if a list is l=["A","B","C","D"] and you're given "B", it outputs "A", "C" and "D")? A: Your question-: How do I find the other elements in a list given one of them? Think like.. How can i remove that element in a list to get all other elements in a list [Quite simple to approach now!!] Some methods are:- def method1(test_list, item): #List Comprehension res = [i for i in test_list if i != item] return res def method2(test_list,item): #Filter Function res = list(filter((item).__ne__, test_list)) return res def method3(test_list,item): #Remove Function c=test_list.count(item) for i in range(c): test_list.remove(item) return test_list print(method1(["A","B","C","D"],"B")) print(method2(["A","B","C","D"],"B")) print(method3(["A","B","C","D"],"B")) Output:- ['A', 'C', 'D'] ['A', 'C', 'D'] ['A', 'C', 'D'] A: There are few ways to achieve this, you want to find the other elements excluding the value. eg l1=[1,2,3,4,5] 2 to excluded l1=[1,3,4,5] # a list l1 =["a","b","C","d"] #input of the value to exclude jo = input() l2=[] for i in range(len(l1)): if l1[i]!=jo: l2.append(l1[i]) print(l2)
How do I find the other elements in a list given one of them?
Given one element in a list, what is the most efficient way that I can find the other elements? (e.g. if a list is l=["A","B","C","D"] and you're given "B", it outputs "A", "C" and "D")?
[ "Your question-: How do I find the other elements in a list given one of them?\nThink like.. How can i remove that element in a list to get all other elements in a list [Quite simple to approach now!!]\nSome methods are:-\ndef method1(test_list, item):\n #List Comprehension\n res = [i for i in test_list if i != item]\n return res\n\ndef method2(test_list,item):\n #Filter Function\n res = list(filter((item).__ne__, test_list))\n return res\n\ndef method3(test_list,item):\n #Remove Function\n c=test_list.count(item)\n for i in range(c):\n test_list.remove(item)\n return test_list\n \nprint(method1([\"A\",\"B\",\"C\",\"D\"],\"B\"))\nprint(method2([\"A\",\"B\",\"C\",\"D\"],\"B\"))\nprint(method3([\"A\",\"B\",\"C\",\"D\"],\"B\"))\n\nOutput:-\n['A', 'C', 'D']\n['A', 'C', 'D']\n['A', 'C', 'D']\n\n", "There are few ways to achieve this, you want to find the other elements excluding the value.\neg l1=[1,2,3,4,5]\n2 to excluded\nl1=[1,3,4,5]\n# a list\nl1 =[\"a\",\"b\",\"C\",\"d\"]\n#input of the value to exclude \njo = input()\nl2=[]\nfor i in range(len(l1)):\n if l1[i]!=jo:\n l2.append(l1[i])\nprint(l2) \n\n \n\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074663785_python.txt
Q: How do I loop through this dictionary correctly in python? favorite_foods = {'bill': 'cake', 'alex': 'patacones'} for name in favorite_foods: print(f"I dont agree with your favorite food {name.title()}.") for food in (favorite_foods.values()): print(f"{food.title()} is delicious, but not that good!") if food in (favorite_foods.values() endswith(s) print(f"{food.title()} are delicous, but not that good!") How do I loop through this dictionary correctly? I want it to say I dont agree with your favorite food Bill. Cake is delicious but not that good! I dont agree with your favorite food Alex. Patacones are delicious, but not that good! I appreciate all the help. Thank you. The code cycles through all of the values instead of stopping after one. I googled the endswith function to see if I could get the code to print something different if the value ended in 's' but it didnt work. Before I added that line it printed the following. I dont agree with your favorite food Bill. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good! I dont agree with your favorite food Alex. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good! I wanted to find a way to trigger "are" when the value was plural and "is" if the value was singular. A: use .items() to loop through dict. Also, if you want the output to be a long string (i.e., no new line), you can use list and join. favorite_foods = {'bill': 'cake', 'alex': 'patacones'} output = [] for k,v in favorite_foods.items(): output.append(f"I dont agree with your favorite food {k.title()}.") if v[-1] == 's': output.append(f"{v.title()} are delicious, but not that good!") else: output.append(f"{v.title()} is delicious, but not that good!") print(" ".join(output)) output: I dont agree with your favorite food Bill. Cake is delicious, but not that good! I dont agree with your favorite food Alex. Patacones are delicious, but not that good! A: you can use 2 things to make this correct and simpler. Use for key, val in <dict_name>.items() to loop through key, value pairs at the same time. Use ternary operator in cases when you need to choose a value based on a boolean. So for example print(("yum!" if tasteGood else "gross!")) will print "yum!" when tasteGood is True, but print "gross!" when tasteGood is false. So to put everything together favFoods = { 'bill':'cake','alex':'patacones' } for name, food in favFoods.items(): print(f"I dont agree with your favorite food {name.title()}.") print(f"{food.title()} {('are' if food.endswith('s') else 'is')} delicious, but not that good!") A: You had a ton of syntax errors, and also your if statement was trying to be a for loop. This works: favorite_foods = {'bill': 'cake', 'alex': 'patacones'} for name in favorite_foods: print(f"I dont agree with your favorite food {name.title()}.") for food in (favorite_foods.values()): if food.endswith('s'): print(f"{food.title()} are delicous, but not that good!") else: print(f"{food.title()} is delicious, but not that good!")
How do I loop through this dictionary correctly in python?
favorite_foods = {'bill': 'cake', 'alex': 'patacones'} for name in favorite_foods: print(f"I dont agree with your favorite food {name.title()}.") for food in (favorite_foods.values()): print(f"{food.title()} is delicious, but not that good!") if food in (favorite_foods.values() endswith(s) print(f"{food.title()} are delicous, but not that good!") How do I loop through this dictionary correctly? I want it to say I dont agree with your favorite food Bill. Cake is delicious but not that good! I dont agree with your favorite food Alex. Patacones are delicious, but not that good! I appreciate all the help. Thank you. The code cycles through all of the values instead of stopping after one. I googled the endswith function to see if I could get the code to print something different if the value ended in 's' but it didnt work. Before I added that line it printed the following. I dont agree with your favorite food Bill. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good! I dont agree with your favorite food Alex. Cake is delicious, but not that good! Cake are delicous, but not that good! Patacones is delicious, but not that good! Patacones are delicous, but not that good! I wanted to find a way to trigger "are" when the value was plural and "is" if the value was singular.
[ "use .items() to loop through dict. Also, if you want the output to be a long string (i.e., no new line), you can use list and join.\nfavorite_foods = {'bill': 'cake', 'alex': 'patacones'}\n\noutput = []\nfor k,v in favorite_foods.items():\n output.append(f\"I dont agree with your favorite food {k.title()}.\")\n if v[-1] == 's':\n output.append(f\"{v.title()} are delicious, but not that good!\")\n else:\n output.append(f\"{v.title()} is delicious, but not that good!\")\n\nprint(\" \".join(output))\n\noutput:\nI dont agree with your favorite food Bill. Cake is delicious, but not that good! I dont agree with your favorite food Alex. Patacones are delicious, but not that good! \n\n", "you can use 2 things to make this correct and simpler.\nUse for key, val in <dict_name>.items() to loop through key, value pairs at the same time.\nUse ternary operator in cases when you need to choose a value based on a boolean. So for example print((\"yum!\" if tasteGood else \"gross!\")) will print \"yum!\" when tasteGood is True, but print \"gross!\" when tasteGood is false.\nSo to put everything together\nfavFoods = {\n'bill':'cake','alex':'patacones'\n}\n\nfor name, food in favFoods.items():\n print(f\"I dont agree with your favorite food {name.title()}.\")\n print(f\"{food.title()} {('are' if food.endswith('s') else 'is')} delicious, but not that good!\")\n\n", "You had a ton of syntax errors, and also your if statement was trying to be a for loop. This works:\nfavorite_foods = {'bill': 'cake', 'alex': 'patacones'}\n\nfor name in favorite_foods:\n print(f\"I dont agree with your favorite food {name.title()}.\")\n \n for food in (favorite_foods.values()):\n if food.endswith('s'):\n print(f\"{food.title()} are delicous, but not that good!\")\n else:\n print(f\"{food.title()} is delicious, but not that good!\")\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "loops", "python" ]
stackoverflow_0074663867_dictionary_loops_python.txt
Q: What is happening inside of my printFun function that is causing this behaviour I am trying to figure out recursion and how it operates and I cant seem to figure out what is happening in this code. def printFun(test): if (test < 1): return else: print(test, end="a ") printFun(test-1) # statement 2 print(test, end="n ") return # Driver Code test = 3 printFun(test) This outputs 3a 2a 1a 1n 2n 3n I can make sense of the first 4 outputs. test = 3, which not less than 1, so print test(1a), then re-call the printFun function with test-1 being 2, which is not less than 1, so print test (2a), then (1a) then 0, which IS less than 1 so return. I assume this brings you back to the print(test, end='n') line? which now prints 1n. This is where I am left perplexed... what is happening beyond this??? How does it start ascending and then stop again at 3? What is the flow and logic of this? Sorry if this is a ridiculous question and I am overlooking something blatantly obvious. But I cannot wrap my mind around this... Anyone? Thanks! A: Its because the stack unwinds depth first. In pseudocode, with each indentation being a new call to the function, you get call printFun(3) print 3a call printFun(2) print 2a call printFun(1) print 1a call printFun(0) print nothing return (test still = 1 in this frame) print 1n return (test still = 2 in this frame) print 2n return (test still = 3 in this frame) print 3n return When you return from the most recently called printFun, you get back to an older set of local variables holding the older value. A: You call printFun three times and each of it prints twice, so we should have 6 prints, isn't it? Sometimes it's hard to unsolve recursion but it doesn't differ as calling another function: def foo(): print("before") other_foo() print("after") Do you agree everything that is printed by other_foo will be between "before" and "after"? It's the same case, you could write it that way: def printFun1(): print("1a") print("1n") def printFun2(): print("2a") printFun1() # it prints "1a" and "1n" between "2a" and "2n" print("2n") def printFun3(): print("3a") printFun2() print("3n") printFun3()
What is happening inside of my printFun function that is causing this behaviour
I am trying to figure out recursion and how it operates and I cant seem to figure out what is happening in this code. def printFun(test): if (test < 1): return else: print(test, end="a ") printFun(test-1) # statement 2 print(test, end="n ") return # Driver Code test = 3 printFun(test) This outputs 3a 2a 1a 1n 2n 3n I can make sense of the first 4 outputs. test = 3, which not less than 1, so print test(1a), then re-call the printFun function with test-1 being 2, which is not less than 1, so print test (2a), then (1a) then 0, which IS less than 1 so return. I assume this brings you back to the print(test, end='n') line? which now prints 1n. This is where I am left perplexed... what is happening beyond this??? How does it start ascending and then stop again at 3? What is the flow and logic of this? Sorry if this is a ridiculous question and I am overlooking something blatantly obvious. But I cannot wrap my mind around this... Anyone? Thanks!
[ "Its because the stack unwinds depth first. In pseudocode, with each indentation being a new call to the function, you get\ncall printFun(3)\n print 3a\n call printFun(2)\n print 2a\n call printFun(1)\n print 1a\n call printFun(0)\n print nothing\n return\n (test still = 1 in this frame)\n print 1n\n return\n (test still = 2 in this frame)\n print 2n\n return\n (test still = 3 in this frame)\n print 3n\n return\n\nWhen you return from the most recently called printFun, you get back to an older set of local variables holding the older value.\n", "You call printFun three times and each of it prints twice, so we should have 6 prints, isn't it?\nSometimes it's hard to unsolve recursion but it doesn't differ as calling another function:\ndef foo():\n print(\"before\")\n other_foo()\n print(\"after\")\n\nDo you agree everything that is printed by other_foo will be between \"before\" and \"after\"? It's the same case, you could write it that way:\ndef printFun1():\n print(\"1a\")\n print(\"1n\")\n\n\ndef printFun2():\n print(\"2a\")\n printFun1() # it prints \"1a\" and \"1n\" between \"2a\" and \"2n\"\n print(\"2n\")\n\n\ndef printFun3():\n print(\"3a\")\n printFun2()\n print(\"3n\")\n\nprintFun3()\n\n" ]
[ 2, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074663859_python_recursion.txt
Q: Python: cv2 can't open USB camera. "error: (-215:Assertion failed)" I'd like to use cv2 with a Desktop PC that I build myself. I've bought a USB webcamera and successufuly installed it since it works smoothly when I access it. My probem is that it seems that cv2 is not able to open my camera. This is the error I'm getting: rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor So I've tried using various index (from -1 to 5) in this line of code: cap = cv2.VideoCapture(0) But nothing changed, I've also tried to use: cd /dev ls video But this is the error I'm getting: ls: cannot access 'video': No such file or directory Is there a way to fix this problem? A: rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) Before this line of code, did you also write something like cv2.imread(...)? I experienced the error exactly the same with yours when I mistakenly put a wrong image address in the cv2.imread(), so my advice is to double check if you pass a correct image address if there is any. Best:)
Python: cv2 can't open USB camera. "error: (-215:Assertion failed)"
I'd like to use cv2 with a Desktop PC that I build myself. I've bought a USB webcamera and successufuly installed it since it works smoothly when I access it. My probem is that it seems that cv2 is not able to open my camera. This is the error I'm getting: rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor So I've tried using various index (from -1 to 5) in this line of code: cap = cv2.VideoCapture(0) But nothing changed, I've also tried to use: cd /dev ls video But this is the error I'm getting: ls: cannot access 'video': No such file or directory Is there a way to fix this problem?
[ "rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\nBefore this line of code, did you also write something like cv2.imread(...)? I experienced the error exactly the same with yours when I mistakenly put a wrong image address in the cv2.imread(), so my advice is to double check if you pass a correct image address if there is any. Best:)\n" ]
[ 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074358640_opencv_python.txt
Q: How to merge csv file with xlsx file and save it into a new combined file The files of both csv and xlsx contain same context, with same header and all. But would like to combine all under one file and then having another column to identify which is csv, which is xlsx. How do I go about doing so? extension = 'csv' all_filenames = [i for i in glob.glob('*.{}.format(extension))] combined)csv = pd.concat([pd.read_csv(f) for f in all_filenames]) combined)csv.to_csv("combined_csv.csv", index= False, encoding= 'utf-8-sig') A: To merge CSV and XLSX files and save them into a new combined file using the code you provided, you can use the pandas library in Python to read the CSV and XLSX files, concatenate them into a single DataFrame, and then write the resulting DataFrame to a new CSV file. Here is an example of how you could modify your code to do this: import glob import pandas as pd # Set the file extension extension = 'csv' # Get the list of filenames with the specified extension all_filenames = [i for i in glob.glob('*.{}'.format(extension))] # Read the CSV and XLSX files using pandas combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames]) combined_xlsx = pd.read_excel('combined_xlsx.xlsx') # Concatenate the CSV and XLSX data into a single DataFrame combined = pd.concat([combined_csv, combined_xlsx]) # Write the combined DataFrame to a new CSV file combined.to_csv("combined_csv.csv", index=False, encoding='utf-8-sig') In this example, the code uses the pandas library to read the CSV and XLSX files and concatenate them into a single DataFrame. It then writes the resulting DataFrame to a new CSV file using the to_csv() method. This will create a new CSV file that contains the combined data from the original CSV and XLSX files. A: In addition to the answer by aHelpfucoder, Use the below queries just before you concatenate the combined_csv & combined_xlsx dataframes to create a new column that can tell you whether a row from a csv file or from an xlsx file. combined_csv['file_type'] = 'CSV' combined_xlsx['file_type] = 'XLSX' Next you can concatenate these dataframes, combined = pd.concat([combined_csv, combined_xlsx])
How to merge csv file with xlsx file and save it into a new combined file
The files of both csv and xlsx contain same context, with same header and all. But would like to combine all under one file and then having another column to identify which is csv, which is xlsx. How do I go about doing so? extension = 'csv' all_filenames = [i for i in glob.glob('*.{}.format(extension))] combined)csv = pd.concat([pd.read_csv(f) for f in all_filenames]) combined)csv.to_csv("combined_csv.csv", index= False, encoding= 'utf-8-sig')
[ "To merge CSV and XLSX files and save them into a new combined file using the code you provided, you can use the pandas library in Python to read the CSV and XLSX files, concatenate them into a single DataFrame, and then write the resulting DataFrame to a new CSV file. Here is an example of how you could modify your code to do this:\nimport glob\nimport pandas as pd\n\n# Set the file extension\nextension = 'csv'\n\n# Get the list of filenames with the specified extension\nall_filenames = [i for i in glob.glob('*.{}'.format(extension))]\n\n# Read the CSV and XLSX files using pandas\ncombined_csv = pd.concat([pd.read_csv(f) for f in all_filenames])\ncombined_xlsx = pd.read_excel('combined_xlsx.xlsx')\n\n# Concatenate the CSV and XLSX data into a single DataFrame\ncombined = pd.concat([combined_csv, combined_xlsx])\n\n# Write the combined DataFrame to a new CSV file\ncombined.to_csv(\"combined_csv.csv\", index=False, encoding='utf-8-sig')\n\nIn this example, the code uses the pandas library to read the CSV and XLSX files and concatenate them into a single DataFrame. It then writes the resulting DataFrame to a new CSV file using the to_csv() method. This will create a new CSV file that contains the combined data from the original CSV and XLSX files.\n", "In addition to the answer by aHelpfucoder,\nUse the below queries just before you concatenate the combined_csv & combined_xlsx dataframes to create a new column that can tell you whether a row from a csv file or from an xlsx file.\ncombined_csv['file_type'] = 'CSV'\ncombined_xlsx['file_type] = 'XLSX'\n\nNext you can concatenate these dataframes,\ncombined = pd.concat([combined_csv, combined_xlsx])\n\n" ]
[ 1, 1 ]
[]
[]
[ "csv", "python", "xlsx" ]
stackoverflow_0074663750_csv_python_xlsx.txt
Q: Creating a scipy-dev environment I am following steps in the contributor guide to create a development environment. I am up to step 2. The Python-level dependencies for building SciPy will be installed as part of the conda environment creation - see environment.yml Note that we’re installing SciPy’s build dependencies and some other software, but not (yet) SciPy itself. Also note that you’ll need to have this virtual environment active whenever you want to work with the development version of SciPy. To create the environment with all dependencies and compilers, from the root of the SciPy folder, do conda env create -f environment.yml However this gives an error that the environment file does not exist. https://github.com/scipy/scipy/blob/main/environment.yml <-- environment.yml should look like this, so I have copied and put an environment.yml file in the envs folder. I am unsure whether I should put this file in the envs folder or if I need to go to the root of the scipy version that already exist in my pkgs folder. C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml EnvironmentFileNotFound: 'C:\\Users\\micha\\anaconda3\\envs\\environment.yml' file not found After inserting the environment.yml file: C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml Collecting package metadata (repodata.json): done Solving environment: / I am still awaiting the reults, however not sure if I have done the correct thing with the directory. A: It doesn't matter where the environment file is, one just needs to ensure the path they provide exists. In fact, Conda can even create it from a URL: conda env create -f https://github.com/scipy/scipy/raw/main/environment.yml Note that most users find it useful to name their environments by passing an --name,-n argument (see conda env create --help). This is arbitrary, so pick something semantic/easy to remember. A: The instruction is to run that command from the root of the SciPy folder. The "SciPy folder" is what you just checked out, and the root is the top-level folder of that checkout. Doing this all from the command-line would look something like: C:\Users\User> git clone https://github.com/scipy/scipy.git [git output omitted] C:\Users\User> cd scipy C:\Users\User\scipy> conda env create -f environment.yml That root folder is also where you'll run the "dev.py" script from.
Creating a scipy-dev environment
I am following steps in the contributor guide to create a development environment. I am up to step 2. The Python-level dependencies for building SciPy will be installed as part of the conda environment creation - see environment.yml Note that we’re installing SciPy’s build dependencies and some other software, but not (yet) SciPy itself. Also note that you’ll need to have this virtual environment active whenever you want to work with the development version of SciPy. To create the environment with all dependencies and compilers, from the root of the SciPy folder, do conda env create -f environment.yml However this gives an error that the environment file does not exist. https://github.com/scipy/scipy/blob/main/environment.yml <-- environment.yml should look like this, so I have copied and put an environment.yml file in the envs folder. I am unsure whether I should put this file in the envs folder or if I need to go to the root of the scipy version that already exist in my pkgs folder. C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml EnvironmentFileNotFound: 'C:\\Users\\micha\\anaconda3\\envs\\environment.yml' file not found After inserting the environment.yml file: C:\\Users\\micha\\anaconda3\\envs\>conda env create -f environment.yml Collecting package metadata (repodata.json): done Solving environment: / I am still awaiting the reults, however not sure if I have done the correct thing with the directory.
[ "It doesn't matter where the environment file is, one just needs to ensure the path they provide exists. In fact, Conda can even create it from a URL:\nconda env create -f https://github.com/scipy/scipy/raw/main/environment.yml\n\nNote that most users find it useful to name their environments by passing an --name,-n argument (see conda env create --help). This is arbitrary, so pick something semantic/easy to remember.\n", "The instruction is to run that command from the root of the SciPy folder. The \"SciPy folder\" is what you just checked out, and the root is the top-level folder of that checkout. Doing this all from the command-line would look something like:\nC:\\Users\\User> git clone https://github.com/scipy/scipy.git\n[git output omitted]\nC:\\Users\\User> cd scipy\nC:\\Users\\User\\scipy> conda env create -f environment.yml\n\nThat root folder is also where you'll run the \"dev.py\" script from.\n" ]
[ 0, 0 ]
[]
[]
[ "conda", "python", "scipy" ]
stackoverflow_0074621983_conda_python_scipy.txt
Q: Kivy: laptop touch pad - mouse cursor move My problem is simple and certainly isn't any news: I can manage my Kivy desktop app with a mouse pretty reasonably. Unfortunately, touch pad is a different story: a single finger move is interpreted as a swipe so there's no way to just move the mouse cursor where it's needed. Google isn't very cooperative; maybe I don't know the keywords? The desktop is KDE on Linux. Is there a way to make a Kivy desktop app respond to the touch pad the way ordinary desktop apps do? Input management looks close, but low level. I'm sorry, I'm new to Kivy. A: A solution: comment out probesysfs line in ~/.kivy/config.ini. ... [input] mouse = mouse #%(name)s = probesysfs ...
Kivy: laptop touch pad - mouse cursor move
My problem is simple and certainly isn't any news: I can manage my Kivy desktop app with a mouse pretty reasonably. Unfortunately, touch pad is a different story: a single finger move is interpreted as a swipe so there's no way to just move the mouse cursor where it's needed. Google isn't very cooperative; maybe I don't know the keywords? The desktop is KDE on Linux. Is there a way to make a Kivy desktop app respond to the touch pad the way ordinary desktop apps do? Input management looks close, but low level. I'm sorry, I'm new to Kivy.
[ "A solution: comment out probesysfs line in ~/.kivy/config.ini.\n...\n[input]\nmouse = mouse\n#%(name)s = probesysfs\n...\n\n" ]
[ 1 ]
[]
[]
[ "desktop_application", "gesture", "kivy", "python", "touchpad" ]
stackoverflow_0074646535_desktop_application_gesture_kivy_python_touchpad.txt
Q: Python: How to ffill and bfill a column with nan? How might I ffill and bfill a column that contains nans? Consider this example: # data df = pd.DataFrame([ [np.nan, '2019-01-01', 'P', 'O', 'A'], [np.nan, '2019-01-02', 'O', 'O', 'A'], ['A', '2019-01-03', 'O', 'O', 'A'], ['A', '2019-01-04', 'O', 'P', 'A'], [np.nan, '2019-01-05', 'O', 'P', 'A'], [np.nan, '2019-01-01', 'P', 'O', 'B'], ['B', '2019-01-02', 'O', 'O', 'B'], ['B', '2019-01-03', 'O', 'O', 'B'], ['B', '2019-01-04', 'O', 'P', 'B'], [np.nan, '2019-01-05', 'O', 'P', 'B'], ], columns=['ID', 'Time', 'FromState', 'ToState', 'Expected']) # updated try df['ID'] = df['ID'].transform(lambda x: x.ffill().bfill() ) A: The following works for me: df['ID'] = df['ID'].ffill(limit=1).bfill(limit=2)
Python: How to ffill and bfill a column with nan?
How might I ffill and bfill a column that contains nans? Consider this example: # data df = pd.DataFrame([ [np.nan, '2019-01-01', 'P', 'O', 'A'], [np.nan, '2019-01-02', 'O', 'O', 'A'], ['A', '2019-01-03', 'O', 'O', 'A'], ['A', '2019-01-04', 'O', 'P', 'A'], [np.nan, '2019-01-05', 'O', 'P', 'A'], [np.nan, '2019-01-01', 'P', 'O', 'B'], ['B', '2019-01-02', 'O', 'O', 'B'], ['B', '2019-01-03', 'O', 'O', 'B'], ['B', '2019-01-04', 'O', 'P', 'B'], [np.nan, '2019-01-05', 'O', 'P', 'B'], ], columns=['ID', 'Time', 'FromState', 'ToState', 'Expected']) # updated try df['ID'] = df['ID'].transform(lambda x: x.ffill().bfill() )
[ "The following works for me:\ndf['ID'] = df['ID'].ffill(limit=1).bfill(limit=2)\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074663824_pandas_python.txt
Q: Error with while (cap.isopened()): in python using cv2 There are a lot of examples using while (cap.isopened()): to loop through a video, but I've found that it always errors out on the last frame. I'm currently using this instead while (cap.get(1) < cap.get(7)): but is there something I need to do to get the first method to work and not error out? I'm just doing normal things within the while loop; an example is below: while (cap.get(1) < cap.get(7)): #(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break A: The first method is most likely failing because you're reading a frame after the video is over (and thus getting a blank frame), and then trying to do things to that blank frame which aren't allowed. You can add a check to see if the frame you got was blank: while(cap.isOpened()): ret, frame = cap.read() if frame is None: break I believe this should fix the issue. A: while cap.isOpened(): # reading frames success, img = cap.read() # success will be true if the images are read successfully. if success: # Do your work here else: print("Did not read the frame")
Error with while (cap.isopened()): in python using cv2
There are a lot of examples using while (cap.isopened()): to loop through a video, but I've found that it always errors out on the last frame. I'm currently using this instead while (cap.get(1) < cap.get(7)): but is there something I need to do to get the first method to work and not error out? I'm just doing normal things within the while loop; an example is below: while (cap.get(1) < cap.get(7)): #(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break
[ "The first method is most likely failing because you're reading a frame after the video is over (and thus getting a blank frame), and then trying to do things to that blank frame which aren't allowed. You can add a check to see if the frame you got was blank:\n while(cap.isOpened()):\n ret, frame = cap.read()\n if frame is None:\n break\n\nI believe this should fix the issue.\n", "while cap.isOpened():\n# reading frames\nsuccess, img = cap.read()\n# success will be true if the images are read successfully.\nif success:\n # Do your work here\nelse:\n print(\"Did not read the frame\")\n\n" ]
[ 4, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0027148047_opencv_python.txt
Q: Python TypeError: Unhashable type when inheriting from subclass with __hash__ I have a base class and a subclass, such as: class Base: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x def __hash__(self): return hash(self.x) class Subclass(Base): def __init__(self, x, y): super().__init__(x) self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y Since the parent class implements __hash__, it should be hashable. However, when I try to put two copies in a set, such as {Subclass(1, 2), Subclass(1, 3)}, I get this error: TypeError: unhashable type: 'Subclass' I know if an object implements __eq__ but not __hash__ then it throws the TypeError, but there is a clearly implemented hash function. What's going on? A: The __eq__ rule applies both to classes without any subclasses implementing __hash__ and to classes that have a parent class with a hash function. If a class overrides __eq__, it must override __hash__ alongside it. To fix your sample: class Base: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x def __hash__(self): return hash(self.x) class Subclass(Base): def __init__(self, x, y): super().__init__(x) self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y def __hash__(self): return hash((self.x, self.y))
Python TypeError: Unhashable type when inheriting from subclass with __hash__
I have a base class and a subclass, such as: class Base: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x def __hash__(self): return hash(self.x) class Subclass(Base): def __init__(self, x, y): super().__init__(x) self.y = y def __eq__(self, other): return self.x == other.x and self.y == other.y Since the parent class implements __hash__, it should be hashable. However, when I try to put two copies in a set, such as {Subclass(1, 2), Subclass(1, 3)}, I get this error: TypeError: unhashable type: 'Subclass' I know if an object implements __eq__ but not __hash__ then it throws the TypeError, but there is a clearly implemented hash function. What's going on?
[ "The __eq__ rule applies both to classes without any subclasses implementing __hash__ and to classes that have a parent class with a hash function. If a class overrides __eq__, it must override __hash__ alongside it.\nTo fix your sample:\nclass Base:\n def __init__(self, x):\n self.x = x\n def __eq__(self, other):\n return self.x == other.x\n def __hash__(self):\n return hash(self.x)\n\nclass Subclass(Base):\n def __init__(self, x, y):\n super().__init__(x)\n self.y = y\n def __eq__(self, other):\n return self.x == other.x and self.y == other.y\n def __hash__(self):\n return hash((self.x, self.y))\n\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074664008_python_python_3.x.txt
Q: How do I write all my BeautifulSoup data from a website to a text file? Python I am trying to read data from open insider and put it into an easy to read text file. Here is my code so far: from bs4 import BeautifulSoup import requests page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month") '''print(page.status_code) checks to see if the page was downloaded successfully''' soup = BeautifulSoup(page.content,'html.parser') # Find the table with the insider purchase data table = soup.find(class_="tinytable") # Find all rows of the table rows = table.find_all('tr') # Loop through each row for row in rows: # Extract the company name, insider name, and trade type from the row data = row.find_all("td") ticker = data[3].get_text() if len(data) > 3 else "Ticker representing the company" company = data[4].get_text() if len(data) > 4 else "Name" insider = data[6].get_text() if len(data) > 6 else "Position of trader" trade_type = data[7].get_text() if len(data) > 7 else "Buy or sell" value = data[12].get_text() if len(data) > 12 else "Monetary value" # Print the extracted data print(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') with open('TopInsiderMonth.txt', 'w') as f: f.write(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') My print function is giving me the results I want but when I try to write it I only write one line of the information instead of the 100 lines I am looking for. Any ideas? A: Open file then the for loop and added \n for new line: from bs4 import BeautifulSoup import requests page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month") '''print(page.status_code) checks to see if the page was downloaded successfully''' soup = BeautifulSoup(page.content,'html.parser') # Find the table with the insider purchase data table = soup.find(class_="tinytable") # Find all rows of the table rows = table.find_all('tr') with open('TopInsiderMonth.txt', 'w') as f: # Loop through each row for row in rows: # Extract the company name, insider name, and trade type from the row data = row.find_all("td") ticker = data[3].get_text() if len(data) > 3 else "Ticker representing the company" company = data[4].get_text() if len(data) > 4 else "Name" insider = data[6].get_text() if len(data) > 6 else "Position of trader" trade_type = data[7].get_text() if len(data) > 7 else "Buy or sell" value = data[12].get_text() if len(data) > 12 else "Monetary value" # Print the extracted data print(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') f.write( f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}\n')
How do I write all my BeautifulSoup data from a website to a text file? Python
I am trying to read data from open insider and put it into an easy to read text file. Here is my code so far: from bs4 import BeautifulSoup import requests page = requests.get("http://openinsider.com/top-insider-purchases-of-the-month") '''print(page.status_code) checks to see if the page was downloaded successfully''' soup = BeautifulSoup(page.content,'html.parser') # Find the table with the insider purchase data table = soup.find(class_="tinytable") # Find all rows of the table rows = table.find_all('tr') # Loop through each row for row in rows: # Extract the company name, insider name, and trade type from the row data = row.find_all("td") ticker = data[3].get_text() if len(data) > 3 else "Ticker representing the company" company = data[4].get_text() if len(data) > 4 else "Name" insider = data[6].get_text() if len(data) > 6 else "Position of trader" trade_type = data[7].get_text() if len(data) > 7 else "Buy or sell" value = data[12].get_text() if len(data) > 12 else "Monetary value" # Print the extracted data print(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') with open('TopInsiderMonth.txt', 'w') as f: f.write(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}') My print function is giving me the results I want but when I try to write it I only write one line of the information instead of the 100 lines I am looking for. Any ideas?
[ "Open file then the for loop and added \\n for new line:\nfrom bs4 import BeautifulSoup\nimport requests\n\npage = requests.get(\"http://openinsider.com/top-insider-purchases-of-the-month\")\n\n'''print(page.status_code)\nchecks to see if the page was downloaded successfully'''\n\nsoup = BeautifulSoup(page.content,'html.parser')\n\n# Find the table with the insider purchase data\ntable = soup.find(class_=\"tinytable\")\n\n# Find all rows of the table\nrows = table.find_all('tr')\n\nwith open('TopInsiderMonth.txt', 'w') as f:\n \n # Loop through each row\n for row in rows:\n # Extract the company name, insider name, and trade type from the row\n data = row.find_all(\"td\")\n ticker = data[3].get_text() if len(data) > 3 else \"Ticker representing the company\"\n company = data[4].get_text() if len(data) > 4 else \"Name\"\n insider = data[6].get_text() if len(data) > 6 else \"Position of trader\"\n trade_type = data[7].get_text() if len(data) > 7 else \"Buy or sell\"\n value = data[12].get_text() if len(data) > 12 else \"Monetary value\"\n # Print the extracted data\n print(f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}')\n\n f.write(\n f'Ticker : {ticker} | Company: {company} | Title: {insider} | Trade Type: {trade_type} | Value: {value}\\n')\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "txt" ]
stackoverflow_0074663991_beautifulsoup_python_txt.txt
Q: Is there a way to transform a list of tuples into a dictionary in python? I am doing an assignment in which I need to open a raw mailing list, saved in a CSV file, filter the users that have been unsubscribed, and print back the resulting mailing list to another CSV file. To do so, I first need to create tuples with each row in the original list, and then transform the tuples into a dictionary. Can I have some help filling out the blank parts of this code? mailing_list.csv: uuid,username,email,subscribe_status 307919e9-d6f0-4ecf-9bef-c1320db8941a,afarrimond0,[email protected],opt-out 8743d75d-c62a-4bae-8990-3390fefbe5c7,tdelicate1,[email protected],opt-out 68a32cae-847a-47c5-a77c-0d14ccf11e70,edelahuntyk,[email protected],OPT-OUT a50bd76f-bc4d-4141-9b5d-3bfb9cb4c65d,tdelicate10,[email protected],active 26edd0b3-0040-4ba9-8c19-9b69d565df36,ogelder2,[email protected],unsubscribed 5c96189f-95fe-4638-9753-081a6e1a82e8,bnornable3,[email protected],opt-out 480fb04a-d7cd-47c5-8079-b580cb14b4d9,csheraton4,[email protected],active d08649ee-62ae-4d1a-b578-fdde309bb721,tstodart5,[email protected],active 5772c293-c2a9-41ff-a8d3-6c666fc19d9a,mbaudino6,[email protected],unsubscribed 9e8fb253-d80d-47b5-8e1d-9a89b5bcc41b,paspling7,[email protected],active 055dff79-7d09-4194-95f2-48dd586b8bd7,mknapton8,[email protected],active 5216dc65-05bb-4aba-a516-3c1317091471,ajelf9,[email protected],unsubscribed 41c30786-aa84-4d60-9879-0c53f8fad970,cgoodleyh,[email protected],active 3fd55224-dbff-4c89-baec-629a3442d8f7,smcgonnelli,[email protected],opt-out 2ac17a63-a64b-42fc-8780-02c5549f23a7,mmayoralj,[email protected],unsubscribed import csv base_url = '../dataset/' def read_mailing_list_file(): with open('mailing_list.csv', 'r') as csv_file: hdr = csv.Sniffer().has_header(csv_file.read()) csv_file.seek(0) file_reader = csv.reader(csv_file) line_count = 0 mailing_list = [] if hdr: next(file_reader) for row in file_reader: mailing_list.append(row) line_count += 1 mailing_list_buffer = # Create another list variable that will be used as a temporary buffer to transform # our previous list into a dictionary, which is the data structure expected from the `update_mailing_list_extended` # function # Looping through the mailing list object for item in mailing_list: # Creating tuples with each row in the original list mailing_dict = # Transforming the list of tuples into a python dictionary I am trying to transform a list of tuples into a dictionary. A: This seems like an XY problem - you are trying to solve problem X (filter csv) with solution Y (a dictionary) when there is a better way to solve X. Going from the description of your problem, there is no need for a dictionary. You can filter the CSV row by row and write directly to the new file. with open("mailing_list.csv") as infile: with open("mailing_list_filtered.csv", "w") as outfile: csv.writer(outfile).writerows(row for row in csv.reader(infile) if row[0] != "unsubscribed")
Is there a way to transform a list of tuples into a dictionary in python?
I am doing an assignment in which I need to open a raw mailing list, saved in a CSV file, filter the users that have been unsubscribed, and print back the resulting mailing list to another CSV file. To do so, I first need to create tuples with each row in the original list, and then transform the tuples into a dictionary. Can I have some help filling out the blank parts of this code? mailing_list.csv: uuid,username,email,subscribe_status 307919e9-d6f0-4ecf-9bef-c1320db8941a,afarrimond0,[email protected],opt-out 8743d75d-c62a-4bae-8990-3390fefbe5c7,tdelicate1,[email protected],opt-out 68a32cae-847a-47c5-a77c-0d14ccf11e70,edelahuntyk,[email protected],OPT-OUT a50bd76f-bc4d-4141-9b5d-3bfb9cb4c65d,tdelicate10,[email protected],active 26edd0b3-0040-4ba9-8c19-9b69d565df36,ogelder2,[email protected],unsubscribed 5c96189f-95fe-4638-9753-081a6e1a82e8,bnornable3,[email protected],opt-out 480fb04a-d7cd-47c5-8079-b580cb14b4d9,csheraton4,[email protected],active d08649ee-62ae-4d1a-b578-fdde309bb721,tstodart5,[email protected],active 5772c293-c2a9-41ff-a8d3-6c666fc19d9a,mbaudino6,[email protected],unsubscribed 9e8fb253-d80d-47b5-8e1d-9a89b5bcc41b,paspling7,[email protected],active 055dff79-7d09-4194-95f2-48dd586b8bd7,mknapton8,[email protected],active 5216dc65-05bb-4aba-a516-3c1317091471,ajelf9,[email protected],unsubscribed 41c30786-aa84-4d60-9879-0c53f8fad970,cgoodleyh,[email protected],active 3fd55224-dbff-4c89-baec-629a3442d8f7,smcgonnelli,[email protected],opt-out 2ac17a63-a64b-42fc-8780-02c5549f23a7,mmayoralj,[email protected],unsubscribed import csv base_url = '../dataset/' def read_mailing_list_file(): with open('mailing_list.csv', 'r') as csv_file: hdr = csv.Sniffer().has_header(csv_file.read()) csv_file.seek(0) file_reader = csv.reader(csv_file) line_count = 0 mailing_list = [] if hdr: next(file_reader) for row in file_reader: mailing_list.append(row) line_count += 1 mailing_list_buffer = # Create another list variable that will be used as a temporary buffer to transform # our previous list into a dictionary, which is the data structure expected from the `update_mailing_list_extended` # function # Looping through the mailing list object for item in mailing_list: # Creating tuples with each row in the original list mailing_dict = # Transforming the list of tuples into a python dictionary I am trying to transform a list of tuples into a dictionary.
[ "This seems like an XY problem - you are trying to solve problem X (filter csv) with solution Y (a dictionary) when there is a better way to solve X.\nGoing from the description of your problem, there is no need for a dictionary. You can filter the CSV row by row and write directly to the new file.\nwith open(\"mailing_list.csv\") as infile:\n with open(\"mailing_list_filtered.csv\", \"w\") as outfile:\n csv.writer(outfile).writerows(row for row in csv.reader(infile)\n if row[0] != \"unsubscribed\")\n\n" ]
[ 0 ]
[ "you can try to use dict class , such as my_dict = dict(tuple_list)\n" ]
[ -1 ]
[ "csv", "dictionary", "python", "tuples" ]
stackoverflow_0074663927_csv_dictionary_python_tuples.txt
Q: rich.table prints unicode when I want ascii I am trying to print MAC address using python rich library. Below is code. The ":cd" in the MAC address get converted to an actual CD disk emoji. How to prevent that from happening? from rich.console import Console from rich.table import Table table = Table(safe_box=True) table.add_column("MAC address") table.add_row("08:00:27:cd:af:88") console = Console() console.print(table) Output: ┏━━━━━━━━━━━━━━━━━┓ ┃ MAC address ┃ ┡━━━━━━━━━━━━━━━━━┩ │ 08:00:27af:88 │ └─────────────────┘ I tried using safe_box=True option to not print Unicode but that did not work. I want the final output to look like ┏━━━━━━━━━━━━━--━━━━┓ ┃ MAC address ┃ ┡━━━━━━━━━━━━━━━--━━┩ │ 08:00:27:cd:af:88 │ └───────────--──────┘ A: The documentation describes this. You use backslash to escape characters that would otherwise be recognized. table.add_row("08:00:27\\:cd:af:88") If you have a string, do s = s.replace(':cd','\\:cd') https://rich.readthedocs.io/en/stable/markup.html FOLLOWUP I looked at the full emoji list in the source code. There are two possible paths. First, they look for the Unicode "zero-width joiner" as a way to interrupt the emoji search. So, you could do: s = s.replace(':cd',':\u200dcd') Second, "cd" is, in fact, the only two-letter emoji code in their list that is also a hex number. So, you can add this at the top, and this also works: from rich._emoji_codes import EMOJI del EMOJI["cd"] I've tested both of these. What a very strange problem.
rich.table prints unicode when I want ascii
I am trying to print MAC address using python rich library. Below is code. The ":cd" in the MAC address get converted to an actual CD disk emoji. How to prevent that from happening? from rich.console import Console from rich.table import Table table = Table(safe_box=True) table.add_column("MAC address") table.add_row("08:00:27:cd:af:88") console = Console() console.print(table) Output: ┏━━━━━━━━━━━━━━━━━┓ ┃ MAC address ┃ ┡━━━━━━━━━━━━━━━━━┩ │ 08:00:27af:88 │ └─────────────────┘ I tried using safe_box=True option to not print Unicode but that did not work. I want the final output to look like ┏━━━━━━━━━━━━━--━━━━┓ ┃ MAC address ┃ ┡━━━━━━━━━━━━━━━--━━┩ │ 08:00:27:cd:af:88 │ └───────────--──────┘
[ "The documentation describes this. You use backslash to escape characters that would otherwise be recognized.\ntable.add_row(\"08:00:27\\\\:cd:af:88\")\n\nIf you have a string, do\ns = s.replace(':cd','\\\\:cd')\n\nhttps://rich.readthedocs.io/en/stable/markup.html\nFOLLOWUP\nI looked at the full emoji list in the source code. There are two possible paths.\nFirst, they look for the Unicode \"zero-width joiner\" as a way to interrupt the emoji search. So, you could do:\ns = s.replace(':cd',':\\u200dcd')\n\nSecond, \"cd\" is, in fact, the only two-letter emoji code in their list that is also a hex number. So, you can add this at the top, and this also works:\nfrom rich._emoji_codes import EMOJI\ndel EMOJI[\"cd\"]\n\nI've tested both of these. What a very strange problem.\n" ]
[ 0 ]
[]
[]
[ "python", "rich" ]
stackoverflow_0074663714_python_rich.txt
Q: How to get rid of python in VS Code's sidebar? I tried python and didn't like it, but under the "Explorer" sidebar in VS Code, it still has a python section. I tried deleting the python extensions, reloading VS Code and looking in settings. It's possible I missed it in settings.
How to get rid of python in VS Code's sidebar?
I tried python and didn't like it, but under the "Explorer" sidebar in VS Code, it still has a python section. I tried deleting the python extensions, reloading VS Code and looking in settings. It's possible I missed it in settings.
[]
[]
[ "Holy Sh*t i am stupid. My folder containing the code was Named \"Python.\" sorry y'all\n" ]
[ -2 ]
[ "c#", "python", "visual_studio_code" ]
stackoverflow_0074664012_c#_python_visual_studio_code.txt
Q: Can you open a Python shell in Atom editor? You can open multiple tabs in the Atom editor, and have a multiple column layout as well. However, I am not being able to find out how to open a Python shell inside Atom so that I can load a Python script in the Python interactive shell. Does anyone know the steps to achieve this? A: The script package is likely what you want, it allows you to test your code by running part or all of it at a time: You can install it by opening the settings view with Ctrl-, switching to the Install panel and searching for script. You can also install from the command line by running: apm install script Technically what you are asking for is closer to the Terminal Plus package, as opens up a terminal pane from which you can load the python interactive environment by entering python. A: Good day. Type Python in the editor command line to use the interactive shell, exit() to leave interactive mode. It is that easy.
Can you open a Python shell in Atom editor?
You can open multiple tabs in the Atom editor, and have a multiple column layout as well. However, I am not being able to find out how to open a Python shell inside Atom so that I can load a Python script in the Python interactive shell. Does anyone know the steps to achieve this?
[ "The script package is likely what you want, it allows you to test your code by running part or all of it at a time:\n\nYou can install it by opening the settings view with Ctrl-, switching to the Install panel and searching for script. You can also install from the command line by running:\napm install script\n\nTechnically what you are asking for is closer to the Terminal Plus package, as opens up a terminal pane from which you can load the python interactive environment by entering python.\n\n", "Good day. Type Python in the editor command line to use the interactive shell, exit() to leave interactive mode. It is that easy.\n" ]
[ 31, 0 ]
[ "You need to go into: Packages --> Settings view --> Install packages and themes and then type \"terminal\" and install the one that starts with \"platformio\":\n\nInstall it and then you will have the + button down there.\n" ]
[ -1 ]
[ "atom_editor", "python" ]
stackoverflow_0033708758_atom_editor_python.txt
Q: telegram bot location python How to get location from user using telegram bot? I tried this: location_keyboard = KeyboardButton(text="send_location", request_location=True) contact_keyboard = KeyboardButton(text ='Share contact', request_contact=True) custom_keyboard = [[ location_keyboard], [contact_keyboard ]] A: You need to do the following: Call sendMessage function with the following params: { chat_id : 1234, text: "your message", reply_markup: {keyboard: [ [{text: "Send Your Mobile", request_contact: true}], [{text: "Send Your Location", request_location: true}] ] } } A: It appears user7870818 is using the library python-telegram-bot. For documentation see here. Here is a minimal working example of how to request location and contact from a user: # -*- coding: utf-8 -*- from telegram import ( Update, KeyboardButton, ReplyKeyboardMarkup ) from telegram.ext import ( Updater, CommandHandler, MessageHandler, CallbackContext, ) def request_location(update: Update, context: CallbackContext) -> None: keyboard = [[ KeyboardButton(text="Send Your Mobile", request_contact=True), KeyboardButton(text="Send Your Location", request_location=True), ] ] reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True) update.message.reply_text(f'Hello {update.effective_user.first_name}', reply_markup=reply_markup) def receive_location(update: Update, context: CallbackContext) -> None: print(f"Location is: {update.message.location}") def main(): updater = Updater("BOT_TOKEN") updater.dispatcher.add_handler(CommandHandler('location', request_location)) updater.dispatcher.add_handler(MessageHandler(None, receive_location)) updater.start_polling() updater.idle() if __name__=="__main__": main()
telegram bot location python
How to get location from user using telegram bot? I tried this: location_keyboard = KeyboardButton(text="send_location", request_location=True) contact_keyboard = KeyboardButton(text ='Share contact', request_contact=True) custom_keyboard = [[ location_keyboard], [contact_keyboard ]]
[ "You need to do the following:\nCall sendMessage function with the following params:\n{\n chat_id : 1234,\n text: \"your message\",\n reply_markup: \n {keyboard: \n [\n [{text: \"Send Your Mobile\", request_contact: true}],\n [{text: \"Send Your Location\", request_location: true}]\n ]\n }\n}\n\n", "It appears user7870818 is using the library python-telegram-bot. For documentation see here.\nHere is a minimal working example of how to request location and contact from a user:\n# -*- coding: utf-8 -*-\nfrom telegram import (\n Update,\n KeyboardButton,\n ReplyKeyboardMarkup\n )\nfrom telegram.ext import (\n Updater,\n CommandHandler,\n MessageHandler,\n CallbackContext,\n )\n \ndef request_location(update: Update, context: CallbackContext) -> None: \n keyboard = [[\n KeyboardButton(text=\"Send Your Mobile\", request_contact=True),\n KeyboardButton(text=\"Send Your Location\", request_location=True),\n ]\n ]\n reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True)\n update.message.reply_text(f'Hello {update.effective_user.first_name}',\n reply_markup=reply_markup)\n \ndef receive_location(update: Update, context: CallbackContext) -> None: \n print(f\"Location is: {update.message.location}\") \n\ndef main():\n updater = Updater(\"BOT_TOKEN\")\n updater.dispatcher.add_handler(CommandHandler('location', request_location))\n updater.dispatcher.add_handler(MessageHandler(None, receive_location)) \n updater.start_polling()\n updater.idle()\n\nif __name__==\"__main__\":\n main()\n\n" ]
[ 1, 0 ]
[]
[]
[ "bots", "location", "python", "telegram" ]
stackoverflow_0043424621_bots_location_python_telegram.txt
Q: How to use Class to iterate over an array? I'm working on Python classes, but I'm running into a "not iterable" error; however, at least from what I can tell, it should iterable. class Stuff: def __init__(self, values): self.values = values def vari(self): mean = sum(self.values)/len(self.values) _var = sum((v - mean)**2 for v in self.values) / len(self.values) return _var def std_dev(self): print(sqrt(vari(self.values))) Basically, I have a class called stuff that takes in "values," which in this case will be x = [12, 20, 56, 34, 3, 17, 23, 43, 54] from there, values are fed into a function for variance and then a function for std_dev, but I'm still getting the nor iterable error. I know I can use numpy and stats for std_dev and variance, but I'm trying to work on classes. Any help would be appreciated. A: Is this what you wanted !? Code:- import math class Stuff: def __init__(self,values): self.values = values def vari(self): mean = sum(self.values)/len(self.values) _var = sum((v - mean)**2 for v in self.values) / len(self.values) return _var def std_dev(self): return math.sqrt(self.vari()) x=[12, 20, 56, 34, 3, 17, 23, 43, 54] a=Stuff(x) print(a.vari()) print(a.std_dev()) Output:- 311.2098765432099 17.64114158843497
How to use Class to iterate over an array?
I'm working on Python classes, but I'm running into a "not iterable" error; however, at least from what I can tell, it should iterable. class Stuff: def __init__(self, values): self.values = values def vari(self): mean = sum(self.values)/len(self.values) _var = sum((v - mean)**2 for v in self.values) / len(self.values) return _var def std_dev(self): print(sqrt(vari(self.values))) Basically, I have a class called stuff that takes in "values," which in this case will be x = [12, 20, 56, 34, 3, 17, 23, 43, 54] from there, values are fed into a function for variance and then a function for std_dev, but I'm still getting the nor iterable error. I know I can use numpy and stats for std_dev and variance, but I'm trying to work on classes. Any help would be appreciated.
[ "Is this what you wanted !?\nCode:-\nimport math\nclass Stuff:\n def __init__(self,values):\n self.values = values\n \n def vari(self):\n mean = sum(self.values)/len(self.values)\n _var = sum((v - mean)**2 for v in self.values) / len(self.values)\n return _var\n\n def std_dev(self):\n return math.sqrt(self.vari())\nx=[12, 20, 56, 34, 3, 17, 23, 43, 54]\na=Stuff(x)\nprint(a.vari())\nprint(a.std_dev())\n\nOutput:-\n311.2098765432099\n17.64114158843497\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074664020_python.txt
Q: Starting w/ python 3.8, Pandas won't let me reassign value in a DataFrame Code that works under Pandas 1.3.5 and python 3.7 or earlier: import pandas as pd import numpy as np hex_name = '123456abc' multi_sub_dir_id_list = [hex_name, hex_name, hex_name] multi_leaf_node_dirs = ['one', 'two', 'three'] x_dir_multi_index = pd.MultiIndex.from_arrays ([multi_sub_dir_id_list, multi_leaf_node_dirs], names = ['hex_name', 'leaf_name']) leaf_name = 'one' dirpath = '/a/string/path' task_path_str = 'thepath' multi_exec_df = pd.DataFrame (data = None, columns = x_dir_multi_index) multi_exec_df.loc[task_path_str] = np.nan multi_exec_df.loc[task_path_str][hex_name, leaf_name] = dirpath Starting with python 3.8, once something has been assigned anything, all future assignments are ignored. Current code is failing under Python 3.11.0 and Pandas 1.5.1 Is this formulation no longer allowed? What it should look like after the above: hex_name leaf_name 123456abc one /a/string/path two NaN three NaN What it does look like after the above: > multi_exec_df.loc[task_path_str] hex_name leaf_name 123456abc one NaN two NaN three NaN Name: thepath, dtype: float64 What I'm running for this test Python 3.10.8 (main, Oct 13 2022, 09:48:40) [Clang 14.0.0 (clang-1400.0.29.102)] on darwin print(pd.__version__) 1.5.2 A: Here is my interpretation of what your code does. Your setup code: import pandas as pd import numpy as np hex_name = '123456abc' multi_sub_dir_id_list = [hex_name, hex_name, hex_name] multi_leaf_node_dirs = ['one', 'two', 'three'] x_dir_multi_index = pd.MultiIndex.from_arrays ([multi_sub_dir_id_list, multi_leaf_node_dirs], names = ['hex_name', 'leaf_name']) leaf_name = 'one' dirpath = '/a/string/path' task_path_str = 'thepath' multi_exec_df = pd.DataFrame (data = None, columns = x_dir_multi_index) multi_exec_df.loc[task_path_str] = np.nan At this point multi_exec_df is a dataframe with one row full of nans: hex_name 123456abc leaf_name one two three thepath NaN NaN NaN and multi_exec_df.loc[task_path_str] is a series containing the data from the first row: hex_name leaf_name 123456abc one NaN two NaN three NaN Name: thepath, dtype: float64 Based on your example of "what it should look like after the above" I assume you are trying to assign the value "/a/string/path" to the column ('123456abc', 'one'). Here is how I would do that: col = (hex_name, leaf_name) multi_exec_df.loc[task_path_str, col] = dirpath As far as I know, using loc or similar methods is the only way to assign values to the dataframe. Is there a reason you can't do that here? Now to the question of what your code is doing... Instead of the above, you are executing the following line: multi_exec_df.loc[task_path_str][hex_name, leaf_name] = dirpath This is equivalent to: multi_exec_df.loc[task_path_str][(hex_name, leaf_name)] = dirpath The problem with it is that multi_exec_df.loc[task_path_str] is a copy of the row from the dataframe, not a view. When I execute above I get the following: <ipython-input-26-2d4fae3863b0>:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy multi_exec_df.loc[task_path_str][hex_name, leaf_name] = dirpath (Maybe you knew that but you didn't mention it so I pointed it out. Not sure why you didn't get this warning. If you are not familiar with what a view is read the documentation at the link above in the warning). You asked "Is this formulation no longer allowed?" Obviously it is allowed, but you must accept that you are assigning the new value to a copy of the row, not the row in the original dataframe. I don't know whether this making a copy instead of a view changed at some point in Pandas development, if that is what you are asking. This was done with Pandas 1.5.1.
Starting w/ python 3.8, Pandas won't let me reassign value in a DataFrame
Code that works under Pandas 1.3.5 and python 3.7 or earlier: import pandas as pd import numpy as np hex_name = '123456abc' multi_sub_dir_id_list = [hex_name, hex_name, hex_name] multi_leaf_node_dirs = ['one', 'two', 'three'] x_dir_multi_index = pd.MultiIndex.from_arrays ([multi_sub_dir_id_list, multi_leaf_node_dirs], names = ['hex_name', 'leaf_name']) leaf_name = 'one' dirpath = '/a/string/path' task_path_str = 'thepath' multi_exec_df = pd.DataFrame (data = None, columns = x_dir_multi_index) multi_exec_df.loc[task_path_str] = np.nan multi_exec_df.loc[task_path_str][hex_name, leaf_name] = dirpath Starting with python 3.8, once something has been assigned anything, all future assignments are ignored. Current code is failing under Python 3.11.0 and Pandas 1.5.1 Is this formulation no longer allowed? What it should look like after the above: hex_name leaf_name 123456abc one /a/string/path two NaN three NaN What it does look like after the above: > multi_exec_df.loc[task_path_str] hex_name leaf_name 123456abc one NaN two NaN three NaN Name: thepath, dtype: float64 What I'm running for this test Python 3.10.8 (main, Oct 13 2022, 09:48:40) [Clang 14.0.0 (clang-1400.0.29.102)] on darwin print(pd.__version__) 1.5.2
[ "Here is my interpretation of what your code does.\nYour setup code:\nimport pandas as pd\nimport numpy as np\nhex_name = '123456abc'\nmulti_sub_dir_id_list = [hex_name, hex_name, hex_name]\nmulti_leaf_node_dirs = ['one', 'two', 'three'] \nx_dir_multi_index = pd.MultiIndex.from_arrays ([multi_sub_dir_id_list, multi_leaf_node_dirs], names = ['hex_name', 'leaf_name'])\nleaf_name = 'one'\ndirpath = '/a/string/path'\ntask_path_str = 'thepath'\nmulti_exec_df = pd.DataFrame (data = None, columns = x_dir_multi_index)\nmulti_exec_df.loc[task_path_str] = np.nan\n\nAt this point multi_exec_df is a dataframe with one row full of nans:\nhex_name 123456abc \nleaf_name one two three\nthepath NaN NaN NaN\n\nand multi_exec_df.loc[task_path_str] is a series containing the data from the first row:\nhex_name leaf_name\n123456abc one NaN\n two NaN\n three NaN\nName: thepath, dtype: float64\n\nBased on your example of \"what it should look like after the above\" I assume you are trying to assign the value \"/a/string/path\" to the column ('123456abc', 'one').\nHere is how I would do that:\ncol = (hex_name, leaf_name)\nmulti_exec_df.loc[task_path_str, col] = dirpath\n\nAs far as I know, using loc or similar methods is the only way to assign values to the dataframe. Is there a reason you can't do that here?\nNow to the question of what your code is doing...\nInstead of the above, you are executing the following line:\nmulti_exec_df.loc[task_path_str][hex_name, leaf_name] = dirpath\n\nThis is equivalent to:\nmulti_exec_df.loc[task_path_str][(hex_name, leaf_name)] = dirpath\n\nThe problem with it is that multi_exec_df.loc[task_path_str] is a copy of the row from the dataframe, not a view. When I execute above I get the following:\n<ipython-input-26-2d4fae3863b0>:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n multi_exec_df.loc[task_path_str][hex_name, leaf_name] = dirpath\n\n(Maybe you knew that but you didn't mention it so I pointed it out. Not sure why you didn't get this warning. If you are not familiar with what a view is read the documentation at the link above in the warning).\nYou asked \"Is this formulation no longer allowed?\"\nObviously it is allowed, but you must accept that you are assigning the new value to a copy of the row, not the row in the original dataframe.\nI don't know whether this making a copy instead of a view changed at some point in Pandas development, if that is what you are asking.\nThis was done with Pandas 1.5.1.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074622796_dataframe_pandas_python.txt
Q: How do I create a directed graph from a csv file and use DFS to traverse and print it? How do I create a directed graph from a csv file and use DFS to traverse and print it? I have made the connect method but it keeps on showing error when I tried to connect elements. I have tried making edges method as well but keeps getting confused after I add that method Directedgraph.csv Directedgraph.csv Content of Code ` import csv class Vertex(): def __init__(self,key): self.key = key self.adjacencies = [] self.checked = False def adds(self,vertex): self.adjacencies.append(vertex) class Graph(): def __init__(self,key_list): self.vertices = [] for key in key_list: vert = Vertex(key) #print(vert) self.vertices.append(vert) #print(self.vertices) def parseCSV(self, csvfile): self.csvfile = csvfile with open(self.csvfile,'r') as f: reader = csv.reader(f) #reader.next() # discard column headers for row in reader: yield (row[0], row[1]) def find_vertex(self,key): for vert in self.vertices: # Slow. Is there a faster way? if vert.key == key: #print (vert.key) return vert return None def connect(self,key1,key2): v1 = self.find_vertex(key1) # Could raise an exception. v2 = self.find_vertex(key2) # We should handle that case. v1.adds(v2) def dfs(self,key1): '''Takes key, initializes checks, launches recursion.''' start = None for vert in self.vertices: vert.checked = False if vert.key==key1: start = vert return self.__dfs__(start,'') def __dfs__(self,v1,display): '''Takes vertex, assumes checks are initializes, recurses.''' if not v1.checked: # Visit this vertex if it hasn't already been visited display=display + str(v1.key) + ' ' v1.checked = True for v2 in v1.adjacencies: # Recursively visit all adjacent vertices display=self.__dfs__(v2,display) return display #Client Code: keys = [] csvFile = "Directedgraph.csv" ws = Graph(keys) ws.parseCSV(csvFile) traversal = ws.dfs(0) print("All components connected to key=0:",traversal) traversal = ws.dfs(1) print("All components connected to key=1:",traversal) traversal = g.dfs(2) print("All components connected to key=2:",traversal) traversal = g.dfs(3) print("All components connected to key=3:",traversal) traversal = g.dfs(4) print("All components connected to key=4:",traversal) ` A: Is parseCSV intended for any use? Seems like the vertices are not connected to each other when it is parsed. Also your CSV has multiple entries but parseCSV seems to be only taking in first 2 values.
How do I create a directed graph from a csv file and use DFS to traverse and print it?
How do I create a directed graph from a csv file and use DFS to traverse and print it? I have made the connect method but it keeps on showing error when I tried to connect elements. I have tried making edges method as well but keeps getting confused after I add that method Directedgraph.csv Directedgraph.csv Content of Code ` import csv class Vertex(): def __init__(self,key): self.key = key self.adjacencies = [] self.checked = False def adds(self,vertex): self.adjacencies.append(vertex) class Graph(): def __init__(self,key_list): self.vertices = [] for key in key_list: vert = Vertex(key) #print(vert) self.vertices.append(vert) #print(self.vertices) def parseCSV(self, csvfile): self.csvfile = csvfile with open(self.csvfile,'r') as f: reader = csv.reader(f) #reader.next() # discard column headers for row in reader: yield (row[0], row[1]) def find_vertex(self,key): for vert in self.vertices: # Slow. Is there a faster way? if vert.key == key: #print (vert.key) return vert return None def connect(self,key1,key2): v1 = self.find_vertex(key1) # Could raise an exception. v2 = self.find_vertex(key2) # We should handle that case. v1.adds(v2) def dfs(self,key1): '''Takes key, initializes checks, launches recursion.''' start = None for vert in self.vertices: vert.checked = False if vert.key==key1: start = vert return self.__dfs__(start,'') def __dfs__(self,v1,display): '''Takes vertex, assumes checks are initializes, recurses.''' if not v1.checked: # Visit this vertex if it hasn't already been visited display=display + str(v1.key) + ' ' v1.checked = True for v2 in v1.adjacencies: # Recursively visit all adjacent vertices display=self.__dfs__(v2,display) return display #Client Code: keys = [] csvFile = "Directedgraph.csv" ws = Graph(keys) ws.parseCSV(csvFile) traversal = ws.dfs(0) print("All components connected to key=0:",traversal) traversal = ws.dfs(1) print("All components connected to key=1:",traversal) traversal = g.dfs(2) print("All components connected to key=2:",traversal) traversal = g.dfs(3) print("All components connected to key=3:",traversal) traversal = g.dfs(4) print("All components connected to key=4:",traversal) `
[ "Is parseCSV intended for any use? Seems like the vertices are not connected to each other when it is parsed. Also your CSV has multiple entries but parseCSV seems to be only taking in first 2 values.\n" ]
[ 0 ]
[]
[]
[ "csv", "depth_first_search", "graph", "python", "python_3.x" ]
stackoverflow_0074663638_csv_depth_first_search_graph_python_python_3.x.txt
Q: Why am I getting an Attribute Error for my code when it should be working I have a class ScrollingCredits. In that, I have a method load_credits. Please have a look at the code class ScrollingCredits: def __init__(self): self.load_credits("end_credits.txt") (self.background, self.background_rect) = load_image("starfield.gif", True) self.font = pygame.font.Font(None, FONT_SIZE) self.scroll_speed = SCROLL_SPEED self.scroll_pause = SCROLL_PAUSE self.end_wait = END_WAIT self.reset() def load_credits(self, filename): f = open(filename) credits = [] while 1: line = f.readline() if not line: break line = string.rstrip(line) credits.append(line) f.close() self.lines = credits The first line after defining the function is where my attribute problem occurs I get this brought up when I try to run it: AttributeError: 'ScrollingCredits' object has no attribute 'load_credits' If anyone would be able to help me it would be much appreciated A: There is function definition and calling issue for load_credits, if you want to access the function with self Make the load_credits outside the __init__ function like below. class ScrollingCredits: def __init__(self): self.load_credits("end_credits.txt") ............ def load_credits(self, filename): ............
Why am I getting an Attribute Error for my code when it should be working
I have a class ScrollingCredits. In that, I have a method load_credits. Please have a look at the code class ScrollingCredits: def __init__(self): self.load_credits("end_credits.txt") (self.background, self.background_rect) = load_image("starfield.gif", True) self.font = pygame.font.Font(None, FONT_SIZE) self.scroll_speed = SCROLL_SPEED self.scroll_pause = SCROLL_PAUSE self.end_wait = END_WAIT self.reset() def load_credits(self, filename): f = open(filename) credits = [] while 1: line = f.readline() if not line: break line = string.rstrip(line) credits.append(line) f.close() self.lines = credits The first line after defining the function is where my attribute problem occurs I get this brought up when I try to run it: AttributeError: 'ScrollingCredits' object has no attribute 'load_credits' If anyone would be able to help me it would be much appreciated
[ "There is function definition and calling issue for load_credits, if you want to access the function with self\nMake the load_credits outside the __init__ function like below.\nclass ScrollingCredits:\n def __init__(self):\n self.load_credits(\"end_credits.txt\")\n............\n\n def load_credits(self, filename):\n............\n\n" ]
[ 1 ]
[]
[]
[ "attributeerror", "error_handling", "python", "python_3.x" ]
stackoverflow_0074664065_attributeerror_error_handling_python_python_3.x.txt
Q: Use list items in variable in python requests url I am trying to make a call to an API and then grab event_ids from the data. I then want to use those event ids as variables in another request, then parse that data. Then loop back and make another request using the next event id in the event_id variable for all the IDs. so far i have the following def nba_odds(): url = "https://xxxxx.com.au/sports/summary/basketball?api_key=xxxxx" response = requests.get(url) data = response.json() event_ids = [] for event in data['Events']: if event['Country'] == 'USA' and event['League'] == 'NBA': event_ids.append(event['EventID']) # print(event_ids) game_url = f'https://xxxxx.com.au/sports/detail/{event_ids}?api_key=xxxxx' game_response = requests.get(game_url) game_data = game_response.json() print(game_url) that gives me the result below in the terminal. https://xxxxx.com.au/sports/detail/['dbx-1425135', 'dbx-1425133', 'dbx-1425134', 'dbx-1425136', 'dbx-1425137', 'dbx-1425138', 'dbx-1425139', 'dbx-1425140', 'anyvsany-nba01-1670043600000000000', 'dbx-1425141', 'dbx-1425142', 'dbx-1425143', 'dbx-1425144', 'dbx-1425145', 'dbx-1425148', 'dbx-1425149', 'dbx-1425147', 'dbx-1425146', 'dbx-1425150', 'e95270f6-661b-46dc-80b9-cd1af75d38fb', '0c989be7-0802-4683-8bb2-d26569e6dcf9']?api_key=779ac51a-2fff-4ad6-8a3e-6a245a0a4cbb the URL above format should look like https://xxxx.com.au/sports/detail/dbx-1425135 If anyone can point me in the right direction it would be appreciated. thanks. A: event_ids is an entire list of event ids. You make a single URL with the full list converted to its string view (['dbx-1425135', 'dbx-1425133', ...]). But it looks like you want to get information on each event in turn. To do that, put the second request in the loop so that it runs for every event you find interesting. def nba_odds(): url = "https://xxxxx.com.au/sports/summary/basketball?api_key=xxxxx" response = requests.get(url) data = response.json() event_ids = [] for event in data['Events']: if event['Country'] == 'USA' and event['League'] == 'NBA': event_id = event['EventID'] # print(event_id) game_url = f'https://xxxxx.com.au/sports/detail/{event_id}?api_key=xxxxx' game_response = requests.get(game_url) game_data = game_response.json() # do something with game_data - it will be overwritten # on next round in the loop print(game_url) A: you need to loop over the event ID's again to call the API with one event_id if it is not supporting multiple event_ids like: all_events_response = [] for event_id in event_ids game_url = f'https://xxxxx.com.au/sports/detail/{event_id}?api_key=xxxxx' game_response = requests.get(game_url) game_data = game_response.json() all_events_response.append(game_data) print(game_url) You can find list of json responses under all_events_response
Use list items in variable in python requests url
I am trying to make a call to an API and then grab event_ids from the data. I then want to use those event ids as variables in another request, then parse that data. Then loop back and make another request using the next event id in the event_id variable for all the IDs. so far i have the following def nba_odds(): url = "https://xxxxx.com.au/sports/summary/basketball?api_key=xxxxx" response = requests.get(url) data = response.json() event_ids = [] for event in data['Events']: if event['Country'] == 'USA' and event['League'] == 'NBA': event_ids.append(event['EventID']) # print(event_ids) game_url = f'https://xxxxx.com.au/sports/detail/{event_ids}?api_key=xxxxx' game_response = requests.get(game_url) game_data = game_response.json() print(game_url) that gives me the result below in the terminal. https://xxxxx.com.au/sports/detail/['dbx-1425135', 'dbx-1425133', 'dbx-1425134', 'dbx-1425136', 'dbx-1425137', 'dbx-1425138', 'dbx-1425139', 'dbx-1425140', 'anyvsany-nba01-1670043600000000000', 'dbx-1425141', 'dbx-1425142', 'dbx-1425143', 'dbx-1425144', 'dbx-1425145', 'dbx-1425148', 'dbx-1425149', 'dbx-1425147', 'dbx-1425146', 'dbx-1425150', 'e95270f6-661b-46dc-80b9-cd1af75d38fb', '0c989be7-0802-4683-8bb2-d26569e6dcf9']?api_key=779ac51a-2fff-4ad6-8a3e-6a245a0a4cbb the URL above format should look like https://xxxx.com.au/sports/detail/dbx-1425135 If anyone can point me in the right direction it would be appreciated. thanks.
[ "event_ids is an entire list of event ids. You make a single URL with the full list converted to its string view (['dbx-1425135', 'dbx-1425133', ...]). But it looks like you want to get information on each event in turn. To do that, put the second request in the loop so that it runs for every event you find interesting.\ndef nba_odds():\n\n url = \"https://xxxxx.com.au/sports/summary/basketball?api_key=xxxxx\"\n response = requests.get(url)\n data = response.json()\n\n event_ids = []\n\n for event in data['Events']:\n if event['Country'] == 'USA' and event['League'] == 'NBA':\n event_id = event['EventID']\n # print(event_id)\n game_url = f'https://xxxxx.com.au/sports/detail/{event_id}?api_key=xxxxx'\n game_response = requests.get(game_url)\n game_data = game_response.json()\n # do something with game_data - it will be overwritten\n # on next round in the loop\n print(game_url)\n\n", "you need to loop over the event ID's again to call the API with one event_id if it is not supporting multiple event_ids like:\n all_events_response = []\n for event_id in event_ids\n game_url = f'https://xxxxx.com.au/sports/detail/{event_id}?api_key=xxxxx'\n game_response = requests.get(game_url)\n game_data = game_response.json()\n all_events_response.append(game_data)\n print(game_url)\n\nYou can find list of json responses under all_events_response\n" ]
[ 0, 0 ]
[]
[]
[ "python", "request" ]
stackoverflow_0074664098_python_request.txt
Q: Python Count Characters Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include the input character and use the plural form, n's if the number of times the characters appears is not exactly 1. Ex: If the input is: n Monday the output is: 1 n Ex: If the input is: z Today is Monday the output is: 0 z's Ex: If the input is: n It's a sunny day the output is: 2 n's Case matters. n is different than N. Ex: If the input is: n Nobody the output is: 0 n's This is what I have so far: user_string=input(str()) character=user_string[0] phrase=user_string[1] count=0 for i in phrase: if i == character: count = count+1 if count!= 1: print(str(count) + " " + character + "'s") else: print(str(count) + " " + character) This works great for the phrases that have 0 characters matching. But its not counting the ones that should match. A: user_string=input(str()) character=user_string[0] phrase=user_string[1:] count=0 for i in phrase: if i == character: count = count+1 if count != 1: print(str(count) + " " + character + "'s") else: print(str(count) + " " + character) A: Suggest just using str.count. user_string = input() character, phrase = user_string[0], user_string[1:] count = phrase.count(character) print(f"{count} {character}" + "'s" if count != 1 else '') A: We will take the user's input, with the assumption that the first letter is the one that you are counting, and find that character with user_string.split()[0]. We will then take all the other words from the user's input (with user_string.split()[1:]), join them with ''.join and then explode them into a list of letters with [*]. We will return a list of "hits" for the character we are looking for. The length of that list will be the number of "hits". user_string=input() numOfLetters = [letter for letter in [*''.join(user_string.split()[1:])] if user_string[0]==letter] print(f'Number of {user_string[0]} is: {len(numOfLetters)}') t This is a test # Input Number of t is: 2 # Output h Another test for comparison # Input Number of h is: 1 # Output A: user_string=input(str()) character=user_string[0] phrase=user_string[1:40] #if more characters are needed just make the 40 larger count=0 for i in phrase: if i == character: count=count+1 if count!= 1: print(str(count) + " " + character + "'s") else: print(str(count) + " " + character)
Python Count Characters
Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. The output should include the input character and use the plural form, n's if the number of times the characters appears is not exactly 1. Ex: If the input is: n Monday the output is: 1 n Ex: If the input is: z Today is Monday the output is: 0 z's Ex: If the input is: n It's a sunny day the output is: 2 n's Case matters. n is different than N. Ex: If the input is: n Nobody the output is: 0 n's This is what I have so far: user_string=input(str()) character=user_string[0] phrase=user_string[1] count=0 for i in phrase: if i == character: count = count+1 if count!= 1: print(str(count) + " " + character + "'s") else: print(str(count) + " " + character) This works great for the phrases that have 0 characters matching. But its not counting the ones that should match.
[ "user_string=input(str())\ncharacter=user_string[0]\nphrase=user_string[1:]\ncount=0\n\nfor i in phrase:\n if i == character:\n count = count+1\n\nif count != 1:\n print(str(count) + \" \" + character + \"'s\")\nelse:\n print(str(count) + \" \" + character)\n\n", "Suggest just using str.count.\nuser_string = input()\ncharacter, phrase = user_string[0], user_string[1:]\ncount = phrase.count(character)\n\nprint(f\"{count} {character}\" + \"'s\" if count != 1 else '')\n\n", "We will take the user's input, with the assumption that the first letter is the one that you are counting, and find that character with user_string.split()[0]. We will then take all the other words from the user's input (with user_string.split()[1:]), join them with ''.join and then explode them into a list of letters with [*]. We will return a list of \"hits\" for the character we are looking for. The length of that list will be the number of \"hits\".\nuser_string=input()\n\nnumOfLetters = [letter for letter in [*''.join(user_string.split()[1:])] \n if user_string[0]==letter]\nprint(f'Number of {user_string[0]} is: {len(numOfLetters)}')\n\nt This is a test # Input\nNumber of t is: 2 # Output\n\nh Another test for comparison # Input\nNumber of h is: 1 # Output\n\n", "user_string=input(str())\ncharacter=user_string[0]\nphrase=user_string[1:40] #if more characters are needed just make the 40 larger\ncount=0\nfor i in phrase:\nif i == character:\ncount=count+1\nif count!= 1:\nprint(str(count) + \" \" + character + \"'s\")\nelse:\nprint(str(count) + \" \" + character)\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0073437641_python.txt
Q: how to apply if conditional using def with multi parameter I am new to def function , I am trying to get the logic in def function with multiple if condition. I want x,y,z to be flexible parameter so I can change parameter value in x,y,z. but i can't get the desired output. anyone help ? df = date comp mark value score test1 0 2022-01-01 a 1 10 100 1 2022-01-02 b 2 20 200 2 2022-01-03 c 3 30 300 3 2022-01-04 d 4 40 400 4 2022-01-05 e 5 50 500 Desired ouput = date comp mark value score test1 0 2022-01-01 a 1 10 100 200 1 2022-01-02 b 2 20 200 400 2 2022-01-03 c 3 30 300 600 3 2022-01-04 d 4 40 400 4000 4 2022-01-05 e 5 50 500 5000 I can get the result use: def frml(df): if (df['mark'] > 3) and (df['value'] > 30): return df['score'] * 10 else: return df['score'] * 2 df['test1'] = df.apply(frml,axis=1) but i can't get the result use this: isn't the logic is the same? x = df['mark'] y = df['value'] z = df['score'] def frml(df): if (x > 3) and (y > 30): return z * 10 else: return z * 2 df['test1'] = df.apply(frml,axis=1) A: you can use mask instead apply cond1 = (df['mark'] > 3) & (df['value'] > 30) df['score'].mul(2).mask(cond1, df['score'].mul(10)) output: 0 200 1 400 2 600 3 4000 4 5000 Name: score, dtype: int64 make output to test1 column df.assign(test1=df['score'].mul(2).mask(cond1, df['score'].mul(10))) result: date comp mark value score test1 0 2022-01-01 a 1 10 100 200 1 2022-01-02 b 2 20 200 400 2 2022-01-03 c 3 30 300 600 3 2022-01-04 d 4 40 400 4000 4 2022-01-05 e 5 50 500 5000 It's possible to explain why your 2nd function doesn't work, but it's complicated. Also, making your output don't need apply def func. So tell you another way. use mask or np.where or np.select instead apply def func
how to apply if conditional using def with multi parameter
I am new to def function , I am trying to get the logic in def function with multiple if condition. I want x,y,z to be flexible parameter so I can change parameter value in x,y,z. but i can't get the desired output. anyone help ? df = date comp mark value score test1 0 2022-01-01 a 1 10 100 1 2022-01-02 b 2 20 200 2 2022-01-03 c 3 30 300 3 2022-01-04 d 4 40 400 4 2022-01-05 e 5 50 500 Desired ouput = date comp mark value score test1 0 2022-01-01 a 1 10 100 200 1 2022-01-02 b 2 20 200 400 2 2022-01-03 c 3 30 300 600 3 2022-01-04 d 4 40 400 4000 4 2022-01-05 e 5 50 500 5000 I can get the result use: def frml(df): if (df['mark'] > 3) and (df['value'] > 30): return df['score'] * 10 else: return df['score'] * 2 df['test1'] = df.apply(frml,axis=1) but i can't get the result use this: isn't the logic is the same? x = df['mark'] y = df['value'] z = df['score'] def frml(df): if (x > 3) and (y > 30): return z * 10 else: return z * 2 df['test1'] = df.apply(frml,axis=1)
[ "you can use mask instead apply\ncond1 = (df['mark'] > 3) & (df['value'] > 30)\ndf['score'].mul(2).mask(cond1, df['score'].mul(10))\n\noutput:\n0 200\n1 400\n2 600\n3 4000\n4 5000\nName: score, dtype: int64\n\nmake output to test1 column\ndf.assign(test1=df['score'].mul(2).mask(cond1, df['score'].mul(10)))\n\nresult:\n date comp mark value score test1\n0 2022-01-01 a 1 10 100 200\n1 2022-01-02 b 2 20 200 400\n2 2022-01-03 c 3 30 300 600\n3 2022-01-04 d 4 40 400 4000\n4 2022-01-05 e 5 50 500 5000\n\n\nIt's possible to explain why your 2nd function doesn't work, but it's complicated.\nAlso, making your output don't need apply def func.\nSo tell you another way.\n\nuse mask or np.where or np.select instead apply def func\n" ]
[ 0 ]
[]
[]
[ "function", "if_statement", "pandas", "python" ]
stackoverflow_0074664035_function_if_statement_pandas_python.txt
Q: What is a good way to generate all strings of length n over a given alphabet within a range in dictionary order? I want to write a generator s_generator(alphabet, length, start_s, end_s) that generates strings of length n over a given alphabet in dictionary order starting with start_s and ending at end_s. For example, s_generator('ab', 4, 'aaaa', 'bbbb') generates ['aaaa', 'aaab', 'aaba', 'aabb', 'abaa', 'abab', 'abba', 'abbb', 'baaa', 'baab', 'baba', 'babb', 'bbaa', 'bbab', 'bbba', 'bbbb']. And s_generator('ab', 4, 'abaa', 'abaa') generates ['abaa', 'abab', 'abba', 'abbb', 'baaa'] What is a good way to implement it? I thought about assigning a number to each character in alphabet, treating the string as a base-n number (n is size of alphabet) and using addition to get the next number, and then convert the number back to string. For example, 'abab' is [0, 1, 0, 1] and the next number is [0, 1, 1, 0], which is 'abba'. This method seems complicated. Is there a simpler solution? A: use itertools and comprehension list from itertools import product def s_generator(alphabet, length, start_s, end_s): products = product(alphabet, repeat=length) return [''.join(x) for x in products if ''.join(x) >= start_s and ''.join(x) <= end_s] print(s_generator('ab', 4, 'aaaa', 'bbbb'))
What is a good way to generate all strings of length n over a given alphabet within a range in dictionary order?
I want to write a generator s_generator(alphabet, length, start_s, end_s) that generates strings of length n over a given alphabet in dictionary order starting with start_s and ending at end_s. For example, s_generator('ab', 4, 'aaaa', 'bbbb') generates ['aaaa', 'aaab', 'aaba', 'aabb', 'abaa', 'abab', 'abba', 'abbb', 'baaa', 'baab', 'baba', 'babb', 'bbaa', 'bbab', 'bbba', 'bbbb']. And s_generator('ab', 4, 'abaa', 'abaa') generates ['abaa', 'abab', 'abba', 'abbb', 'baaa'] What is a good way to implement it? I thought about assigning a number to each character in alphabet, treating the string as a base-n number (n is size of alphabet) and using addition to get the next number, and then convert the number back to string. For example, 'abab' is [0, 1, 0, 1] and the next number is [0, 1, 1, 0], which is 'abba'. This method seems complicated. Is there a simpler solution?
[ "use itertools and comprehension list\nfrom itertools import product\n\ndef s_generator(alphabet, length, start_s, end_s):\n products = product(alphabet, repeat=length)\n return [''.join(x) for x in products if ''.join(x) >= start_s and ''.join(x) <= end_s]\n\n\nprint(s_generator('ab', 4, 'aaaa', 'bbbb'))\n\n" ]
[ 0 ]
[]
[]
[ "algorithm", "python", "string" ]
stackoverflow_0074664066_algorithm_python_string.txt
Q: Python vitual environment (venv): Share libraries in usage and dev/test venvs I am new in python venv, so sorry for possible stupid question. I am developing a small library. I've created dev virtual environment with all packages which is necessary for the library usage and freeze all versions of requirements to requirements.txt. I also would like to create requirements_test.txt with all packages needed for development and tests. So the user will install requirements from requirements.txt while the developer from requirements_test.txt with all nessesary libs (e.g. pytest, asv, sphinx). Now I've created dev venv and now I want to create test venv, of course I don't want to install the same libs twice. Is it possible to share some libs from one venv to another? A: Is it possible to share some libs from one venv to another? No. The same library (or application) will be installed once per virtual environment, the installations can not be shared between environments. And it is perfectly fine like this. That is the whole point of virtual environments, that two installations from the same library are isolated from each other, in particular for the case where two different versions of the same library are required for two different projects. To be completely fair, there are ways to share one installation of the same library between two virtual environments and reasons to do so. One famous example I know of currently is in the newer releases of virtualenv (versions 20+). In short: this tool creates virtual environments and (under specific conditions) is able to reuse (share) the installations of pip, setuptools, and wheel in multiple environments, see the app-data seeder for virtualenv. Some more discussions on the topic: https://discuss.python.org/t/proposal-sharing-distrbution-installations-in-general/2524 https://discuss.python.org/t/optimizing-installs-of-many-virtualenvs-by-symlinking-packages/2983 https://github.com/pypa/packaging-problems/issues/328 A: You can use virtualenv --system-site-packages to symlink from the base system for sharing between dev and user. Then add the dev specific testing packages.
Python vitual environment (venv): Share libraries in usage and dev/test venvs
I am new in python venv, so sorry for possible stupid question. I am developing a small library. I've created dev virtual environment with all packages which is necessary for the library usage and freeze all versions of requirements to requirements.txt. I also would like to create requirements_test.txt with all packages needed for development and tests. So the user will install requirements from requirements.txt while the developer from requirements_test.txt with all nessesary libs (e.g. pytest, asv, sphinx). Now I've created dev venv and now I want to create test venv, of course I don't want to install the same libs twice. Is it possible to share some libs from one venv to another?
[ "\nIs it possible to share some libs from one venv to another?\n\nNo. The same library (or application) will be installed once per virtual environment, the installations can not be shared between environments. And it is perfectly fine like this. That is the whole point of virtual environments, that two installations from the same library are isolated from each other, in particular for the case where two different versions of the same library are required for two different projects.\nTo be completely fair, there are ways to share one installation of the same library between two virtual environments and reasons to do so. One famous example I know of currently is in the newer releases of virtualenv (versions 20+). In short: this tool creates virtual environments and (under specific conditions) is able to reuse (share) the installations of pip, setuptools, and wheel in multiple environments, see the app-data seeder for virtualenv.\nSome more discussions on the topic:\n\nhttps://discuss.python.org/t/proposal-sharing-distrbution-installations-in-general/2524\nhttps://discuss.python.org/t/optimizing-installs-of-many-virtualenvs-by-symlinking-packages/2983\nhttps://github.com/pypa/packaging-problems/issues/328\n\n", "You can use virtualenv --system-site-packages to symlink from the base system for sharing between dev and user. Then add the dev specific testing packages.\n" ]
[ 3, 0 ]
[ "I think it is recommended and advised to have multiple venvs, and multiple environments, be it on the same machine. so just have another venv. Its okay to have same library being present in both venvs.\n", "Even with virtual environments, there are many libraries that come preinstalled with python and are not necessary in the package that you are developing, when I run pip freeze in a brand new virtual environment it dumps 30 packages, and surely they are not needed for my project.\nI recommend you to do the dependency maintenance manually (at least the production ones), this way you won't include useless libraries and you will keep your dependency file clean.\n" ]
[ -1, -1 ]
[ "python", "virtualenv" ]
stackoverflow_0060973272_python_virtualenv.txt
Q: How to import XOR function from Crypto.Cipher module? cannot import name 'XOR' from 'Crypto.Cipher' (/usr/local/lib/python3.8/dist-packages/Crypto/Cipher/__init__.py) I just tried importing XOR function into my code & this is the error that i have got when i executed my code in the google colab. Can i get the solution for this? I just need to import XOR function using Crypto.Cipher module. My code is as follows import Crypto from Crypto import Cipher from Crypto.Cipher import XOR key = "abcdefghijklij" xor = XOR.XORCipher(key) # To encrypt xor1 = XOR.XORCipher(key) # To decrypt def enc(sock, message, addr): abcd = str_xor.encrypt(message) print (message == dec(sock, abcd, addr)) sock.sendto(abcd, addr) return abcd def dec(sock, message, addr): abcd = str_xor1.decrypt(message) return abcd #message = "dfjsdfjsdfjdsfdfsk"4 #print message #newm = enc(1, message, message) #print newm #print dec(1, newm, newm) A: pip install crypto installs https://github.com/chrissimpkins/crypto which does not appear to be import-able class-library. Its examples and test scripts suggest crypto and decrypto should be executes as commands. Readme: https://github.com/chrissimpkins/crypto Tests/examples: https://github.com/chrissimpkins/crypto/tree/master/tests Please specify which crypto-library did you install? Make sure your installation matches the library you are supposed to install.
How to import XOR function from Crypto.Cipher module?
cannot import name 'XOR' from 'Crypto.Cipher' (/usr/local/lib/python3.8/dist-packages/Crypto/Cipher/__init__.py) I just tried importing XOR function into my code & this is the error that i have got when i executed my code in the google colab. Can i get the solution for this? I just need to import XOR function using Crypto.Cipher module. My code is as follows import Crypto from Crypto import Cipher from Crypto.Cipher import XOR key = "abcdefghijklij" xor = XOR.XORCipher(key) # To encrypt xor1 = XOR.XORCipher(key) # To decrypt def enc(sock, message, addr): abcd = str_xor.encrypt(message) print (message == dec(sock, abcd, addr)) sock.sendto(abcd, addr) return abcd def dec(sock, message, addr): abcd = str_xor1.decrypt(message) return abcd #message = "dfjsdfjsdfjdsfdfsk"4 #print message #newm = enc(1, message, message) #print newm #print dec(1, newm, newm)
[ "pip install crypto\n\ninstalls https://github.com/chrissimpkins/crypto which does not appear to be import-able class-library. Its examples and test scripts suggest crypto and decrypto should be executes as commands.\n\nReadme: https://github.com/chrissimpkins/crypto\nTests/examples: https://github.com/chrissimpkins/crypto/tree/master/tests\n\nPlease specify which crypto-library did you install?\nMake sure your installation matches the library you are supposed to install.\n" ]
[ 0 ]
[]
[]
[ "cryptography", "package", "python" ]
stackoverflow_0074664087_cryptography_package_python.txt
Q: Converting floats from input into integers within an equation python Program is supposed to take an integer and a factor of x and evaluate the polynomial a_nx^n+a_{n-1}x^{n-1}+a_{n-2}x^{n-2}+ ... a_2x^2+a_1x+a_0, where each a_i is a coefficient of the corresponding power of x. Basically, the polynomial 3x^4+2x^3+x+5 can be represented as the integer 32015 since the x^2 coefficient is 0. It is then evaluated by the x value. However, the program won't accept decimals for the first integer as input but wants all decimals to be included in the answer. I've written most of the program. while True: try: number = list(reversed(input())) if int("".join(number)): break except: print("Invalid Input") while True: try: x = float(input()) break except: print("Invalid Input") degree = len(number) result = 0 for i in range(degree): result += int(number[i]) * pow(x,i) print(result) However, for the inputs 341 and -2.9, the program expects 218.11999999999998 but is recieving 218.11999999999995 How can I stop the decimals in the answer from being rounded? A: I've researched about floating-point numbers and the docs also state this as an error. However, what they recommend is using repr() which is a built-in function to convert your input into 17 significant digits. You could also create an if condition that runs the repr() function only when required. Why does this problem occur? Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction 0.125 has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction 0.001 has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference being that the first is written in base 10 fractional notation, and the second in base 2.
Converting floats from input into integers within an equation python
Program is supposed to take an integer and a factor of x and evaluate the polynomial a_nx^n+a_{n-1}x^{n-1}+a_{n-2}x^{n-2}+ ... a_2x^2+a_1x+a_0, where each a_i is a coefficient of the corresponding power of x. Basically, the polynomial 3x^4+2x^3+x+5 can be represented as the integer 32015 since the x^2 coefficient is 0. It is then evaluated by the x value. However, the program won't accept decimals for the first integer as input but wants all decimals to be included in the answer. I've written most of the program. while True: try: number = list(reversed(input())) if int("".join(number)): break except: print("Invalid Input") while True: try: x = float(input()) break except: print("Invalid Input") degree = len(number) result = 0 for i in range(degree): result += int(number[i]) * pow(x,i) print(result) However, for the inputs 341 and -2.9, the program expects 218.11999999999998 but is recieving 218.11999999999995 How can I stop the decimals in the answer from being rounded?
[ "I've researched about floating-point numbers and the docs also state this as an error. However, what they recommend is using repr() which is a built-in function to convert your input into 17 significant digits. You could also create an if condition that runs the repr() function only when required.\nWhy does this problem occur? Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction 0.125 has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction 0.001 has value 0/2 + 0/4 + 1/8. These two fractions have identical values, the only real difference being that the first is written in base 10 fractional notation, and the second in base 2.\n" ]
[ 0 ]
[]
[]
[ "integer", "logic", "python" ]
stackoverflow_0074661744_integer_logic_python.txt
Q: How can I store current directory as variable in python? I'm trying to build a basic terminal that performs basic operations in python. I have made all the main functions, but the cd function isn't working to change my current directory. I suspect that the problem is in the way I store my current directory file. Perhaps I need to store it as variable instead of using function. This is the code. ##################################### # import modules. # pwd - view the current folder function. # ls - list files in a folder function. # touch (filename) - create new empty file function. # rm (filename) - delete a file function. # cd - go to another folder function. # cat (filename) - display the contents of a file function. ###################################### import os import pathlib from os.path import join path = os.getcwd() # DONE def ls(): os.listdir(path) print(os.listdir(path)) def pwd(): print(os.getcwd()) def touch(file_name): fp = open(join(path, file_name), 'a') fp.close() def rm(file_name): file = pathlib.Path(join(path, file_name)) file.unlink() def cd(file_name): os.chdir(join(path, file_name)) while True < 100: dirName = input() cmd = dirName.split(" ")[0] if cmd == "ls": ls() elif cmd == "pwd": pwd() elif cmd == "cd": file_name = dirName.split(" ")[1] cd(file_name) print(os.getcwd()) elif cmd == "touch": file_name = dirName.split(" ")[1] touch(file_name) elif cmd == "rm": file_name = dirName.split(" ")[1] rm(file_name) elif cmd == 'cd': # file_name = dirName.split(" ")[1] cd(file_name) print(pwd(file_name)) else: print("Command not found!") I tired to change directory using the cd function in my custom terminal, but it's not working. It is expected that cd function to work correctly. A: It looks like you are storing the current working directory in the path variable when you import it at the beginning of your code. However, when you call os.chdir in your cd function, it changes the current working directory, but it doesn't update the path variable to reflect this change. As a result, when you call os.listdir in your ls function, it still lists the files in the old working directory instead of the new one. One way to fix this is to update the path variable whenever you call os.chdir in the cd function. You can do this by assigning the result of os.chdir to path. This will update path to the new working directory, and the ls function will work as expected. Here is what the updated code might look like: import os import pathlib from os.path import join path = os.getcwd() def ls(): os.listdir(path) print(os.listdir(path)) def pwd(): print(os.getcwd()) def touch(file_name): fp = open(join(path, file_name), 'a') fp.close() def rm(file_name): file = pathlib.Path(join(path, file_name)) file.unlink() def cd(file_name): path = os.chdir(join(path, file_name)) # Update the path variable while True < 100: dirName = input() cmd = dirName.split(" ")[0] if cmd == "ls": ls() elif cmd == "pwd": pwd() elif cmd == "cd": file_name = dirName.split(" ")[1] cd(file_name) print(os.getcwd()) elif cmd == "touch": file_name = dirName.split(" ")[1] touch(file_name) elif cmd == "rm": file_name = dirName.split(" ")[1] rm(file_name) elif cmd == 'cd': # file_name = dirName.split(" ")[1] cd(file_name) print(pwd(file_name)) else: print("Command not found!") Another approach would be to use the os.getcwd function to get the current working directory inside each function instead of using the path variable. This way, the path variable won't be necessary, and you can remove it from your code. Here is an example of what this might look like: import os import pathlib from os.path import join def ls(): print(os.listdir(os.getcwd())) # Use os.getcwd() instead of path def pwd(): print(os.getcwd()) def touch(file_name): fp = open(join(os.getcwd(), file_name), 'a') # Use os.getcwd() instead of path fp.close() A: There are a few issues with your cd function. First, you are using the global path variable to store the current working directory, but you are not updating this variable when calling cd. Second, the cd function does not return anything, so the print statement in the while loop does not have any effect. Here is one way to fix these issues: Instead of using a global variable to store the current working directory, use a local variable current_dir that is initialized to the current working directory. This variable should be updated whenever the cd function is called. Inside the cd function, change the current working directory using the os.chdir function and update the current_dir variable. In the while loop, call the pwd function after calling the cd function to display the new current working directory. Here is the updated code that implements these changes: import os import pathlib from os.path import join # DONE def ls(): os.listdir(current_dir) print(os.listdir(current_dir)) def pwd(): print(current_dir) def touch(file_name): fp = open(join(current_dir, file_name), 'a') fp.close() def rm(file_name): file = pathlib.Path(join(current_dir, file_name)) file.unlink() def cd(file_name): os.chdir(join(current_dir, file_name)) current_dir = os.getcwd() current_dir = os.getcwd() while True < 100: dirName = input() cmd = dirName.split(" ")[0] if cmd == "ls": ls() elif cmd == "pwd": pwd() elif cmd == "cd": file_name = dirName.split(" ")[1] cd(file_name) pwd() elif cmd == "touch": file_name = dirName.split(" ")[1] touch(file_name) elif cmd == "rm": file_name = dirName.split(" ")[1] rm(file_name) else: print("Command not found!") With these changes, the cd function should work as expected. You can further improve the code by adding error handling for invalid directory names and making the input parsing more robust. A: You have to change the path value to the updated path value. Try this. import os import pathlib from os.path import join path = os.getcwd() # DONE def ls(): os.listdir(path) print(os.listdir(path)) def pwd(): print(os.getcwd()) def touch(file_name): fp = open(join(path, file_name), 'a') fp.close() def rm(file_name): file = pathlib.Path(join(path, file_name)) file.unlink() def cd(file_name): global path path = os.chdir(join(path, file_name)) while True < 100: dirName = input() cmd = dirName.split(" ")[0] if cmd == "ls": ls() elif cmd == "pwd": pwd() elif cmd == "cd": file_name = dirName.split(" ")[1] cd(file_name) print(os.getcwd()) elif cmd == "touch": file_name = dirName.split(" ")[1] touch(file_name) elif cmd == "rm": file_name = dirName.split(" ")[1] rm(file_name) elif cmd == 'cd': # file_name = dirName.split(" ")[1] cd(file_name) print(pwd(file_name)) else: print("Command not found!")
How can I store current directory as variable in python?
I'm trying to build a basic terminal that performs basic operations in python. I have made all the main functions, but the cd function isn't working to change my current directory. I suspect that the problem is in the way I store my current directory file. Perhaps I need to store it as variable instead of using function. This is the code. ##################################### # import modules. # pwd - view the current folder function. # ls - list files in a folder function. # touch (filename) - create new empty file function. # rm (filename) - delete a file function. # cd - go to another folder function. # cat (filename) - display the contents of a file function. ###################################### import os import pathlib from os.path import join path = os.getcwd() # DONE def ls(): os.listdir(path) print(os.listdir(path)) def pwd(): print(os.getcwd()) def touch(file_name): fp = open(join(path, file_name), 'a') fp.close() def rm(file_name): file = pathlib.Path(join(path, file_name)) file.unlink() def cd(file_name): os.chdir(join(path, file_name)) while True < 100: dirName = input() cmd = dirName.split(" ")[0] if cmd == "ls": ls() elif cmd == "pwd": pwd() elif cmd == "cd": file_name = dirName.split(" ")[1] cd(file_name) print(os.getcwd()) elif cmd == "touch": file_name = dirName.split(" ")[1] touch(file_name) elif cmd == "rm": file_name = dirName.split(" ")[1] rm(file_name) elif cmd == 'cd': # file_name = dirName.split(" ")[1] cd(file_name) print(pwd(file_name)) else: print("Command not found!") I tired to change directory using the cd function in my custom terminal, but it's not working. It is expected that cd function to work correctly.
[ "It looks like you are storing the current working directory in the path variable when you import it at the beginning of your code. However, when you call os.chdir in your cd function, it changes the current working directory, but it doesn't update the path variable to reflect this change. As a result, when you call os.listdir in your ls function, it still lists the files in the old working directory instead of the new one.\nOne way to fix this is to update the path variable whenever you call os.chdir in the cd function. You can do this by assigning the result of os.chdir to path. This will update path to the new working directory, and the ls function will work as expected. Here is what the updated code might look like:\nimport os\nimport pathlib\nfrom os.path import join\n\npath = os.getcwd()\n\n\ndef ls():\n os.listdir(path)\n print(os.listdir(path))\n\n\ndef pwd():\n print(os.getcwd())\n\n\ndef touch(file_name):\n fp = open(join(path, file_name), 'a')\n fp.close()\n\n\ndef rm(file_name):\n file = pathlib.Path(join(path, file_name))\n file.unlink()\n\n\ndef cd(file_name):\n path = os.chdir(join(path, file_name)) # Update the path variable\n\n\nwhile True < 100:\n dirName = input()\n cmd = dirName.split(\" \")[0]\n\n if cmd == \"ls\": \n ls()\n elif cmd == \"pwd\": \n pwd()\n elif cmd == \"cd\": \n file_name = dirName.split(\" \")[1]\n cd(file_name)\n print(os.getcwd())\n elif cmd == \"touch\": \n file_name = dirName.split(\" \")[1]\n touch(file_name)\n elif cmd == \"rm\": \n file_name = dirName.split(\" \")[1]\n rm(file_name)\n elif cmd == 'cd': #\n file_name = dirName.split(\" \")[1]\n cd(file_name)\n print(pwd(file_name))\n else:\n print(\"Command not found!\")\n\nAnother approach would be to use the os.getcwd function to get the current working directory inside each function instead of using the path variable. This way, the path variable won't be necessary, and you can remove it from your code. Here is an example of what this might look like:\nimport os\nimport pathlib\nfrom os.path import join\n\ndef ls():\n print(os.listdir(os.getcwd())) # Use os.getcwd() instead of path\n\n\ndef pwd():\n print(os.getcwd())\n\n\ndef touch(file_name):\n fp = open(join(os.getcwd(), file_name), 'a') # Use os.getcwd() instead of path\n fp.close()\n\n", "There are a few issues with your cd function. First, you are using the global path variable to store the current working directory, but you are not updating this variable when calling cd. Second, the cd function does not return anything, so the print statement in the while loop does not have any effect.\nHere is one way to fix these issues:\nInstead of using a global variable to store the current working directory, use a local variable current_dir that is initialized to the current working directory. This variable should be updated whenever the cd function is called.\nInside the cd function, change the current working directory using the os.chdir function and update the current_dir variable.\nIn the while loop, call the pwd function after calling the cd function to display the new current working directory.\nHere is the updated code that implements these changes:\nimport os\nimport pathlib\nfrom os.path import join\n\n# DONE\ndef ls():\n os.listdir(current_dir)\n print(os.listdir(current_dir))\n\ndef pwd():\n print(current_dir)\n\ndef touch(file_name):\n fp = open(join(current_dir, file_name), 'a')\n fp.close()\n\ndef rm(file_name):\n file = pathlib.Path(join(current_dir, file_name))\n file.unlink()\n\ndef cd(file_name):\n os.chdir(join(current_dir, file_name))\n current_dir = os.getcwd()\n\ncurrent_dir = os.getcwd()\nwhile True < 100:\n dirName = input()\n cmd = dirName.split(\" \")[0]\n\n if cmd == \"ls\": \n ls()\n elif cmd == \"pwd\": \n pwd()\n elif cmd == \"cd\": \n file_name = dirName.split(\" \")[1]\n cd(file_name)\n pwd()\n elif cmd == \"touch\": \n file_name = dirName.split(\" \")[1]\n touch(file_name)\n elif cmd == \"rm\": \n file_name = dirName.split(\" \")[1]\n rm(file_name)\n else:\n print(\"Command not found!\")\n\nWith these changes, the cd function should work as expected. You can further improve the code by adding error handling for invalid directory names and making the input parsing more robust.\n", "You have to change the path value to the updated path value.\nTry this.\n\nimport os\nimport pathlib\nfrom os.path import join\n\npath = os.getcwd()\n\n\n# DONE\ndef ls():\n os.listdir(path)\n print(os.listdir(path))\n\n\ndef pwd():\n print(os.getcwd())\n\n\ndef touch(file_name):\n fp = open(join(path, file_name), 'a')\n fp.close()\n\n\ndef rm(file_name):\n file = pathlib.Path(join(path, file_name))\n file.unlink()\n\n\ndef cd(file_name):\n global path\n path = os.chdir(join(path, file_name))\n\n\nwhile True < 100:\n dirName = input()\n cmd = dirName.split(\" \")[0]\n\n if cmd == \"ls\": \n ls()\n elif cmd == \"pwd\": \n pwd()\n elif cmd == \"cd\": \n file_name = dirName.split(\" \")[1]\n cd(file_name)\n print(os.getcwd())\n elif cmd == \"touch\": \n file_name = dirName.split(\" \")[1]\n touch(file_name)\n elif cmd == \"rm\": \n file_name = dirName.split(\" \")[1]\n rm(file_name)\n elif cmd == 'cd': #\n file_name = dirName.split(\" \")[1]\n cd(file_name)\n print(pwd(file_name))\n else:\n print(\"Command not found!\")\n\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074664156_python_web_scraping.txt
Q: How to nest a dictionary in another empty dictionary inside a nested for loop? I created two for loops where the loop for roi in rois is nested in the loop for subject in subjects. My aim is creating a dictionary called dict_subjects that includes yet another dictionary that, in turn, includes the key-value pair roi: comp. This is my current code: rois = ["roi_x", "roi_y", "roi_z" ...] # a long list of rois subjects = ["Subject1", "Subject2", "Subject3", "Subject4", "Subject5" ... ] # a long list of subjects dict_subjects = {} for subject in subjects: for roi in rois: data = np.loadtxt(f"/volumes/..../xyz.txt") # Loads data comp = ... # A computation with a numerical result dict_subjects[subject] = {roi:comp} My current coding issue is that the nested for loop creates the dictionary dict_subjects that, paradigmatically for the first two subjects, looks like this: {'Subject1': {'roi_z': -1.1508099817085136}, 'Subject2': {'roi_z': -0.5746447574557193}} Hence, the nested for loops only add the last roi from the list of rois. I understand that the problem is a constant overwriting of the last roi by the line dict_subjects[subject] = {roi:comp}. When changing this line of code to dict_subjects[subject] += [{roi:ple[0]}], I get the following key error KeyError: 'Subject1' since the dictionary dict_subjects is empty. Question: How is it possible to start with an empty dictionary, namely dict_subjects, yet adding the nested hierarchy of subjects and rois: comp to it? A: To fix your code, you need to create the inner dictionary for each subject before you start the loop for roi in rois. You can do this by adding the following code before the loop for roi in rois: dict_subjects[subject] = {} This will create an empty dictionary for each subject in the outer loop, and you can then add key-value pairs to that dictionary inside the inner loop. Your code should now look something like this: rois = ["roi_x", "roi_y", "roi_z" ...] # a long list of rois subjects = ["Subject1", "Subject2", "Subject3", "Subject4", "Subject5" ...] # a long list of subjects dict_subjects = {} for subject in subjects: dict_subjects[subject] = {} for roi in rois: data = np.loadtxt(f"/volumes/..../xyz.txt") # Loads data comp = ... # A computation with a numerical result dict_subjects[subject][roi] = comp This should create the dictionary you want, with a nested dictionary for each subject containing the key-value pairs of roi: comp for each roi in rois.
How to nest a dictionary in another empty dictionary inside a nested for loop?
I created two for loops where the loop for roi in rois is nested in the loop for subject in subjects. My aim is creating a dictionary called dict_subjects that includes yet another dictionary that, in turn, includes the key-value pair roi: comp. This is my current code: rois = ["roi_x", "roi_y", "roi_z" ...] # a long list of rois subjects = ["Subject1", "Subject2", "Subject3", "Subject4", "Subject5" ... ] # a long list of subjects dict_subjects = {} for subject in subjects: for roi in rois: data = np.loadtxt(f"/volumes/..../xyz.txt") # Loads data comp = ... # A computation with a numerical result dict_subjects[subject] = {roi:comp} My current coding issue is that the nested for loop creates the dictionary dict_subjects that, paradigmatically for the first two subjects, looks like this: {'Subject1': {'roi_z': -1.1508099817085136}, 'Subject2': {'roi_z': -0.5746447574557193}} Hence, the nested for loops only add the last roi from the list of rois. I understand that the problem is a constant overwriting of the last roi by the line dict_subjects[subject] = {roi:comp}. When changing this line of code to dict_subjects[subject] += [{roi:ple[0]}], I get the following key error KeyError: 'Subject1' since the dictionary dict_subjects is empty. Question: How is it possible to start with an empty dictionary, namely dict_subjects, yet adding the nested hierarchy of subjects and rois: comp to it?
[ "To fix your code, you need to create the inner dictionary for each subject before you start the loop for roi in rois. You can do this by adding the following code before the loop\nfor roi in rois:\n\ndict_subjects[subject] = {}\n\nThis will create an empty dictionary for each subject in the outer loop, and you can then add key-value pairs to that dictionary inside the inner loop. Your code should now look something like this:\nrois = [\"roi_x\", \"roi_y\", \"roi_z\" ...] # a long list of rois\nsubjects = [\"Subject1\", \"Subject2\", \"Subject3\", \"Subject4\", \"Subject5\" ...] # a long list of subjects\n\ndict_subjects = {}\n\nfor subject in subjects:\n dict_subjects[subject] = {}\n\n for roi in rois:\n data = np.loadtxt(f\"/volumes/..../xyz.txt\") # Loads data\n comp = ... # A computation with a numerical result\n\n dict_subjects[subject][roi] = comp\n\n\nThis should create the dictionary you want, with a nested dictionary for each subject containing the key-value pairs of roi: comp for each roi in rois.\n" ]
[ 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074664242_dictionary_python.txt
Q: UnboundLocalError: local variable 'dist' referenced before assignment I am trying to train a model for supervised learning for Hidden Markov Model (HMM)and test it on a set of observations however, keep getting this error. The goal is to predict the state based on the observations. How can I fix this and how can I view the transition matrix? The version for Pomegranate is 0.14.4 Trying this from the source: https://github.com/jmschrei/pomegranate/issues/1005 from pomegranate import * import numpy as np # Supervised method that calculates the transition matrix: d1 = State(UniformDistribution.from_samples([3.243221498397177, 3.210684537495482, 3.227662201472816, 3.286410817416738, 3.290573650708864, 3.286058136226862, 3.266480693857006])) d2 = State(UniformDistribution.from_samples([3.449282367485096, 1.97317859465635, 1.897551432353011, 3.454609351559659, 3.127357456033111, 1.779308337786426, 3.802891929694426, 3.359766157565077, 2.959428499979418])) d3 = State(UniformDistribution.from_samples([1.892812118441474, 1.589353118681066, 2.09269978285637, 2.104391496570218, 1.656771181054144])) model = HiddenMarkovModel() model.add_states(d1, d2, d3) # print(model.to_json()) model.bake() model.fit([3.2, 6.7, 10.55], labels=[1, 2, 3], algorithm='labeled') all_pred = model.predict([2.33, 1.22, 1.4, 10.6]) Error: File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile pydev_imports.execfile(filename, global_vars, local_vars) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/", line 774, in <module> model.bake() File "pomegranate/hmm.pyx", line 1047, in pomegranate.hmm.HiddenMarkovModel.bake UnboundLocalError: local variable 'dist' referenced before assignment A: To fix this error, you need to ensure that the transition matrix is defined before calling model.bake(). This can be done by using the following code to define the transition matrix: # Define the transition matrix transition_matrix = np.array([[0.7, 0.3, 0.0], [0.3, 0.7, 0.0], [0.0, 0.3, 0.7]]) model.set_transition_matrix(transition_matrix) # Bake the model model.bake() # Fit the model model.fit([3.2, 6.7, 10.55], labels=[1, 2, 3], algorithm='labeled') # Predict the states all_pred = model.predict([2.33, 1.22, 1.4, 10.6]) # View the transition matrix print(model.transitions) A: This error occurs because the bake() method is called before the model is properly defined. In particular, the error occurs because you are calling the bake() method before you have added any transitions between the states in your model. To fix this error, you need to add transitions between the states in your model before calling the bake() method. You can add transitions using the add_transition() method, like this: # Supervised method that calculates the transition matrix: d1 = State(UniformDistribution.from_samples([3.243221498397177, 3.210684537495482, 3.227662201472816, 3.286410817416738, 3.290573650708864, 3.286058136226862, 3.266480693857006])) d2 = State(UniformDistribution.from_samples([3.449282367485096, 1.97317859465635, 1.897551432353011, 3.454609351559659, 3.127357456033111, 1.779308337786426, 3.802891929694426, 3.359766157565077, 2.959428499979418])) d3 = State(UniformDistribution.from_samples([1.892812118441474, 1.589353118681066, 2.09269978285637, 2.104391496570218, 1.656771181054144])) model = HiddenMarkovModel() model.add_states(d1, d2, d3) # Add transitions between the states model.add_transition(model.start, d1, 0.33) model.add_transition(model.start, d2, 0.33) model.add_transition(model.start, d3, 0.33) model.add_transition(d1, d1, 0.33) model.add_transition(d1, d2, 0.33) model.add_transition(d1, d3, 0.33) model.add_transition(d2, d1, 0.33) model.add_transition(d2, d2, 0.33) model.add_transition(d2, d3, 0.33) model.add_transition(d3, d1, 0.33) model.add_transition(d3, d2, 0.33) model.add_transition(d3, d3, 0.33) # Call the bake() method to finalize the model model.bake() # Fit the model on the training data and labels model.fit([3.2, 6.7, 10.55], labels=[1, 2, 3], algorithm='labeled') # Use the model to predict the states for a set of observations all_pred = model.predict([2.33, 1.22, 1.4, 10.6]) # View the transition matrix for the model print(model.dense_transition_matrix())
UnboundLocalError: local variable 'dist' referenced before assignment
I am trying to train a model for supervised learning for Hidden Markov Model (HMM)and test it on a set of observations however, keep getting this error. The goal is to predict the state based on the observations. How can I fix this and how can I view the transition matrix? The version for Pomegranate is 0.14.4 Trying this from the source: https://github.com/jmschrei/pomegranate/issues/1005 from pomegranate import * import numpy as np # Supervised method that calculates the transition matrix: d1 = State(UniformDistribution.from_samples([3.243221498397177, 3.210684537495482, 3.227662201472816, 3.286410817416738, 3.290573650708864, 3.286058136226862, 3.266480693857006])) d2 = State(UniformDistribution.from_samples([3.449282367485096, 1.97317859465635, 1.897551432353011, 3.454609351559659, 3.127357456033111, 1.779308337786426, 3.802891929694426, 3.359766157565077, 2.959428499979418])) d3 = State(UniformDistribution.from_samples([1.892812118441474, 1.589353118681066, 2.09269978285637, 2.104391496570218, 1.656771181054144])) model = HiddenMarkovModel() model.add_states(d1, d2, d3) # print(model.to_json()) model.bake() model.fit([3.2, 6.7, 10.55], labels=[1, 2, 3], algorithm='labeled') all_pred = model.predict([2.33, 1.22, 1.4, 10.6]) Error: File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile pydev_imports.execfile(filename, global_vars, local_vars) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/", line 774, in <module> model.bake() File "pomegranate/hmm.pyx", line 1047, in pomegranate.hmm.HiddenMarkovModel.bake UnboundLocalError: local variable 'dist' referenced before assignment
[ "To fix this error, you need to ensure that the transition matrix is defined before calling model.bake(). This can be done by using the following code to define the transition matrix:\n# Define the transition matrix\ntransition_matrix = np.array([[0.7, 0.3, 0.0],\n [0.3, 0.7, 0.0],\n [0.0, 0.3, 0.7]])\n\nmodel.set_transition_matrix(transition_matrix)\n\n# Bake the model\nmodel.bake()\n\n# Fit the model\nmodel.fit([3.2, 6.7, 10.55], labels=[1, 2, 3], algorithm='labeled')\n\n# Predict the states\nall_pred = model.predict([2.33, 1.22, 1.4, 10.6])\n\n# View the transition matrix\nprint(model.transitions)\n\n", "This error occurs because the bake() method is called before the model is properly defined. In particular, the error occurs because you are calling the bake() method before you have added any transitions between the states in your model.\nTo fix this error, you need to add transitions between the states in your model before calling the bake() method. You can add transitions using the add_transition() method, like this:\n# Supervised method that calculates the transition matrix:\nd1 = State(UniformDistribution.from_samples([3.243221498397177, 3.210684537495482, 3.227662201472816,\n 3.286410817416738, 3.290573650708864, 3.286058136226862, 3.266480693857006]))\nd2 = State(UniformDistribution.from_samples([3.449282367485096, 1.97317859465635, 1.897551432353011,\n 3.454609351559659, 3.127357456033111, 1.779308337786426, 3.802891929694426, 3.359766157565077, 2.959428499979418]))\nd3 = State(UniformDistribution.from_samples([1.892812118441474, 1.589353118681066, 2.09269978285637,\n 2.104391496570218, 1.656771181054144]))\nmodel = HiddenMarkovModel()\nmodel.add_states(d1, d2, d3)\n\n# Add transitions between the states\nmodel.add_transition(model.start, d1, 0.33)\nmodel.add_transition(model.start, d2, 0.33)\nmodel.add_transition(model.start, d3, 0.33)\nmodel.add_transition(d1, d1, 0.33)\nmodel.add_transition(d1, d2, 0.33)\nmodel.add_transition(d1, d3, 0.33)\nmodel.add_transition(d2, d1, 0.33)\nmodel.add_transition(d2, d2, 0.33)\nmodel.add_transition(d2, d3, 0.33)\nmodel.add_transition(d3, d1, 0.33)\nmodel.add_transition(d3, d2, 0.33)\nmodel.add_transition(d3, d3, 0.33)\n\n# Call the bake() method to finalize the model\nmodel.bake()\n\n# Fit the model on the training data and labels\nmodel.fit([3.2, 6.7, 10.55], labels=[1, 2, 3], algorithm='labeled')\n\n# Use the model to predict the states for a set of observations\nall_pred = model.predict([2.33, 1.22, 1.4, 10.6])\n\n# View the transition matrix for the model\nprint(model.dense_transition_matrix())\n\n" ]
[ 1, 1 ]
[]
[]
[ "hidden_markov_models", "pomegranate", "python", "supervised_learning" ]
stackoverflow_0074538741_hidden_markov_models_pomegranate_python_supervised_learning.txt
Q: PyQT5 ui file, does not load properly from the executable file I am building a PyQt5 application by constructing the interfaces with the designer and the exporting to .ui files. The latter are then loaded by my main class. Here is an example of my source code under the name main.py: main.py import os.path import PyQt5.QtWidgets as qtw from PyQt5.uic import loadUi import sys class MainUI(qtw.QMainWindow): def __init__(self, parent=None): super(MainUI, self).__init__() self._ui_path = os.path.dirname(os.path.abspath(__file__)) loadUi(os.path.join(self._ui_path, 'main.ui'), self) if __name__ == "__main__": # Create the application app = qtw.QApplication(sys.argv) # Create and show the application's main window win = MainUI() win.show() sys.exit(app.exec()) main.ui <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>MainWindow</class> <widget class="QMainWindow" name="MainWindow"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>320</width> <height>240</height> </rect> </property> <property name="windowTitle"> <string>MainWindow</string> </property> <widget class="QWidget" name="centralwidget"> <widget class="QPushButton" name="pushButton"> <property name="geometry"> <rect> <x>110</x> <y>100</y> <width>88</width> <height>27</height> </rect> </property> <property name="text"> <string>ok</string> </property> </widget> </widget> <widget class="QMenuBar" name="menubar"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>320</width> <height>21</height> </rect> </property> </widget> <widget class="QStatusBar" name="statusbar"/> </widget> <resources/> <connections/> </ui> I generate an executable with pyinstaller by giving pyinstaller -F -w main.py. In the beginning the executable should be in the same folder with the ui. I have changed loadUI following the answer here. When I run the executable now it gives me an error message with the following traceback: Traceback (most recent call last): File "main.py", line 17, in <module> win = MainUI() File "main.py", line 11, in __init__ loadUi(os.path.join(self._ui_path, 'main.ui'), self) File "PyQt5\uic\__init__.py", line 238, in loadUi File "PyQt5\uic\Loader\loader.py", line 66, in loadUi File "PyQt5\uic\uiparser.py", line 1020, in parse File "xml\etree\ElementTree.py", line 1202, in parse File "xml\etree\ElementTree.py", line 584, in parse FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\username\\AppData\\Local\\Temp\\_MEI187162\\main.ui' What has happened is that after running the .exe file, a temporary directory is created having some dll files, and the program tries to locate the .ui file there, without success. What can be done to direct the executable to the place where the .ui file is? A: Add this somewhere at the top of your program: import sys import os if getattr(sys, 'frozen', False): RELATIVE_PATH = os.path.dirname(sys.executable) else: RELATIVE_PATH = os.path.dirname(__file__) Then when you go to call loadUi(): self._ui_path = RELATIVE_PATH + "/ui_path" # Update this as needed loadUi(os.path.join(self._ui_path, 'main.ui'), self) When programs are compiled and ran elsewhere the directories can get a little weird. See if this works for you, if not, let me know and I can help out further. A: I turn back from PyQt5 version 5.15.7 to version 5.15.1 by command "pip install PyQt5==5.15.1". My problem resolved. My Code Goes like this from PyQt5.QtWidgets import QApplication from PyQt5 import uic class UI(QWidget): def __init__(self): super(UI,self).__init__() # loading the ui file with uic module uic.loadUi("*xxxxxx*.ui", self) app = QApplication([]) window = UI() window.show() app.exec()
PyQT5 ui file, does not load properly from the executable file
I am building a PyQt5 application by constructing the interfaces with the designer and the exporting to .ui files. The latter are then loaded by my main class. Here is an example of my source code under the name main.py: main.py import os.path import PyQt5.QtWidgets as qtw from PyQt5.uic import loadUi import sys class MainUI(qtw.QMainWindow): def __init__(self, parent=None): super(MainUI, self).__init__() self._ui_path = os.path.dirname(os.path.abspath(__file__)) loadUi(os.path.join(self._ui_path, 'main.ui'), self) if __name__ == "__main__": # Create the application app = qtw.QApplication(sys.argv) # Create and show the application's main window win = MainUI() win.show() sys.exit(app.exec()) main.ui <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>MainWindow</class> <widget class="QMainWindow" name="MainWindow"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>320</width> <height>240</height> </rect> </property> <property name="windowTitle"> <string>MainWindow</string> </property> <widget class="QWidget" name="centralwidget"> <widget class="QPushButton" name="pushButton"> <property name="geometry"> <rect> <x>110</x> <y>100</y> <width>88</width> <height>27</height> </rect> </property> <property name="text"> <string>ok</string> </property> </widget> </widget> <widget class="QMenuBar" name="menubar"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>320</width> <height>21</height> </rect> </property> </widget> <widget class="QStatusBar" name="statusbar"/> </widget> <resources/> <connections/> </ui> I generate an executable with pyinstaller by giving pyinstaller -F -w main.py. In the beginning the executable should be in the same folder with the ui. I have changed loadUI following the answer here. When I run the executable now it gives me an error message with the following traceback: Traceback (most recent call last): File "main.py", line 17, in <module> win = MainUI() File "main.py", line 11, in __init__ loadUi(os.path.join(self._ui_path, 'main.ui'), self) File "PyQt5\uic\__init__.py", line 238, in loadUi File "PyQt5\uic\Loader\loader.py", line 66, in loadUi File "PyQt5\uic\uiparser.py", line 1020, in parse File "xml\etree\ElementTree.py", line 1202, in parse File "xml\etree\ElementTree.py", line 584, in parse FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\username\\AppData\\Local\\Temp\\_MEI187162\\main.ui' What has happened is that after running the .exe file, a temporary directory is created having some dll files, and the program tries to locate the .ui file there, without success. What can be done to direct the executable to the place where the .ui file is?
[ "Add this somewhere at the top of your program:\nimport sys\nimport os\n\nif getattr(sys, 'frozen', False):\n RELATIVE_PATH = os.path.dirname(sys.executable)\nelse:\n RELATIVE_PATH = os.path.dirname(__file__)\n\nThen when you go to call loadUi():\nself._ui_path = RELATIVE_PATH + \"/ui_path\" # Update this as needed\n\nloadUi(os.path.join(self._ui_path, 'main.ui'), self)\n\nWhen programs are compiled and ran elsewhere the directories can get a little weird. See if this works for you, if not, let me know and I can help out further.\n", "I turn back from PyQt5 version 5.15.7 to version 5.15.1 by command \"pip install PyQt5==5.15.1\". My problem resolved.\nMy Code Goes like this\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5 import uic\n\n\nclass UI(QWidget):\n def __init__(self):\n super(UI,self).__init__()\n\n # loading the ui file with uic module\n uic.loadUi(\"*xxxxxx*.ui\", self)\n\n\napp = QApplication([])\nwindow = UI()\nwindow.show()\napp.exec()\n\n" ]
[ 1, 0 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0071398328_pyqt5_python.txt