content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: TypeError: string indices must be integers JSON with backslash I'm try to scraping JSON data from script tags. And I was able to extract data from it. My Code. import requests, json from bs4 import BeautifulSoup head = { "Accept": 'application/json, text/plain, */*', "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8,km;q=0.7", "Connection": "keep-alive", "Host": "www.ixigua.com", "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 = "https://www.ixigua.com/home/58484635562" ree = requests.get(url, headers=head) soup = BeautifulSoup(ree.content, 'html.parser') script = soup.find_all('script')[-2].text print(script) with open('data.json', 'w', encoding='utf-8') as f: json.dump(script, f, ensure_ascii = False) Result below "window._SSR_HYDRATED_DATA={\"recommendFeed\":null,\"attentionFeed\":null,\"nbaFeed\":null,\"livingFeed\":null,\"channelFeed\":[],\"homeFeed\":null,\"adBanner\":[],\"channelInfo\":null,\"ChannelFeedList\":[],\"UserDetail\":{\"enableTabs\":[],\"hotPersonList\":[],\"userInfo\":{\"name\":\"-\",\"description\":\"-\",\"avatar\":\"\",\"followersCount\":0,\"followingCount\":0,\"user_id\":\"\",\"follow\":false},\"videoData\":{\"videoList\":[],\"loading\":true},\"hotsoonData\":{\"hotsoonList\":[]},\"preview_series\":[],\"seriesData\":{\"series_list\":[],\"hasMore\":false,\"nextCursor\":\"0\"}},\"FooterLinks\":[],\"LvideoChannel\":[],\"LvideoChannelOnTcc\":[],\"LvideoCategory\":[],\"AlbumInCategory\":[],\"ChannelFeedV2\":[],\"ChannelLevelOneConfig\":[],\"ChannelLevelTwoConfig\":[],\"HighQualityFeed\":[],\"ChannelBannerConfig\":[],\"Teleplay\":null,\"Projection\":{\"video\":{},\"series\":{},\"pSeries\":{},\"playlist\":{\"item_num\":0},\"shouldReturn404\":false,\"item_id\":\"\",\"key\":undefined},\"CinemaChannelFeed\":[],\"CinemaFeedRebojiemu\":[],\"CinemaFeedFromRedis\":[],\"MyWatchHistory\":[{\"type\":\"all\",\"videoFeed\":[],\"hasMore\":true},{\"type\":\"svideo\",\"videoFeed\":[],\"hasMore\":true},{\"type\":\"lvideo\",\"videoFeed\":[],\"hasMore\":true}],\"MyFavorite\":[{\"type\":\"all\",\"videoFeed\":[],\"hasMore\":true},{\"type\":\"svideo\",\"videoFeed\":[],\"hasMore\":true},{\"type\":\"lvideo\",\"videoFeed\":[],\"hasMore\":true}],\"AuthorDetailInfo\":{\"user_id\":\"58484635562\",\"media_id\":\"1562629337991170\",\"name\":\"鼎力推鉴王鼎杰工作室\",\"introduce\":\"小细节里的大战略,大格局里的小动作。\",\"avatar\":\"https:\\u002F\\u002Fsf3-cdn-tos.bdxiguastatic.... But whenever I try to print ["AuthorDetailInfo"] I got an error. print(script["AuthorDetailInfo"]) Error result print(script["AuthorDetailInfo"]) TypeError: string indices must be integers How can i print this? And how can i remove all backslash from JSON? Code print(script["AuthorDetailInfo"]) Expected result { "user_id":"58484635562", "media_id":"1562629337991170", "name":"鼎力推鉴王鼎杰工作室", "introduce":"小细节里的大战略"... } Edit: I solved the problem by using re module. Code import requests, json, re, base64 from bs4 import BeautifulSoup head = { "Accept": 'application/json, text/plain, */*', "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8,km;q=0.7", "Connection": "keep-alive", "Cookie": "", "Host": "www.ixigua.com", "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 = "" ree = requests.get(url, headers=head).text pattern = re.compile('(?<=window._SSR_HYDRATED_DATA=).*?(?=</script>)') jsonResult = pattern.findall(ree)[0] jsonResult = jsonResult.replace(':undefined', ':null') jsonData = json.loads(jsonResult) with open('data.json', 'w', encoding='utf-8') as f: json.dump(jsonData, f, ensure_ascii = False, indent=4) A: script is JavaScript code, not JSON. Notice the window._SSR_HYDRATED_DATA= before the {. Everything after that can be treated as JSON (even though technically it isn't.) You have to deal with the variable assignment first. One way is to use split(): _, my_json = script.split('=', maxsplit=1) Now you can use json.loads() to parse it: obj = my_json.loads(my_json) And finally you can get the part you want: print(obj['AuthorDetailInfo']) Note: The maxsplit=1 is just in case there are any other = characters in the string. Also, this only works if the JavaScript object in the assignment is valid JSON.
TypeError: string indices must be integers JSON with backslash
I'm try to scraping JSON data from script tags. And I was able to extract data from it. My Code. import requests, json from bs4 import BeautifulSoup head = { "Accept": 'application/json, text/plain, */*', "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8,km;q=0.7", "Connection": "keep-alive", "Host": "www.ixigua.com", "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 = "https://www.ixigua.com/home/58484635562" ree = requests.get(url, headers=head) soup = BeautifulSoup(ree.content, 'html.parser') script = soup.find_all('script')[-2].text print(script) with open('data.json', 'w', encoding='utf-8') as f: json.dump(script, f, ensure_ascii = False) Result below "window._SSR_HYDRATED_DATA={\"recommendFeed\":null,\"attentionFeed\":null,\"nbaFeed\":null,\"livingFeed\":null,\"channelFeed\":[],\"homeFeed\":null,\"adBanner\":[],\"channelInfo\":null,\"ChannelFeedList\":[],\"UserDetail\":{\"enableTabs\":[],\"hotPersonList\":[],\"userInfo\":{\"name\":\"-\",\"description\":\"-\",\"avatar\":\"\",\"followersCount\":0,\"followingCount\":0,\"user_id\":\"\",\"follow\":false},\"videoData\":{\"videoList\":[],\"loading\":true},\"hotsoonData\":{\"hotsoonList\":[]},\"preview_series\":[],\"seriesData\":{\"series_list\":[],\"hasMore\":false,\"nextCursor\":\"0\"}},\"FooterLinks\":[],\"LvideoChannel\":[],\"LvideoChannelOnTcc\":[],\"LvideoCategory\":[],\"AlbumInCategory\":[],\"ChannelFeedV2\":[],\"ChannelLevelOneConfig\":[],\"ChannelLevelTwoConfig\":[],\"HighQualityFeed\":[],\"ChannelBannerConfig\":[],\"Teleplay\":null,\"Projection\":{\"video\":{},\"series\":{},\"pSeries\":{},\"playlist\":{\"item_num\":0},\"shouldReturn404\":false,\"item_id\":\"\",\"key\":undefined},\"CinemaChannelFeed\":[],\"CinemaFeedRebojiemu\":[],\"CinemaFeedFromRedis\":[],\"MyWatchHistory\":[{\"type\":\"all\",\"videoFeed\":[],\"hasMore\":true},{\"type\":\"svideo\",\"videoFeed\":[],\"hasMore\":true},{\"type\":\"lvideo\",\"videoFeed\":[],\"hasMore\":true}],\"MyFavorite\":[{\"type\":\"all\",\"videoFeed\":[],\"hasMore\":true},{\"type\":\"svideo\",\"videoFeed\":[],\"hasMore\":true},{\"type\":\"lvideo\",\"videoFeed\":[],\"hasMore\":true}],\"AuthorDetailInfo\":{\"user_id\":\"58484635562\",\"media_id\":\"1562629337991170\",\"name\":\"鼎力推鉴王鼎杰工作室\",\"introduce\":\"小细节里的大战略,大格局里的小动作。\",\"avatar\":\"https:\\u002F\\u002Fsf3-cdn-tos.bdxiguastatic.... But whenever I try to print ["AuthorDetailInfo"] I got an error. print(script["AuthorDetailInfo"]) Error result print(script["AuthorDetailInfo"]) TypeError: string indices must be integers How can i print this? And how can i remove all backslash from JSON? Code print(script["AuthorDetailInfo"]) Expected result { "user_id":"58484635562", "media_id":"1562629337991170", "name":"鼎力推鉴王鼎杰工作室", "introduce":"小细节里的大战略"... } Edit: I solved the problem by using re module. Code import requests, json, re, base64 from bs4 import BeautifulSoup head = { "Accept": 'application/json, text/plain, */*', "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8,km;q=0.7", "Connection": "keep-alive", "Cookie": "", "Host": "www.ixigua.com", "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 = "" ree = requests.get(url, headers=head).text pattern = re.compile('(?<=window._SSR_HYDRATED_DATA=).*?(?=</script>)') jsonResult = pattern.findall(ree)[0] jsonResult = jsonResult.replace(':undefined', ':null') jsonData = json.loads(jsonResult) with open('data.json', 'w', encoding='utf-8') as f: json.dump(jsonData, f, ensure_ascii = False, indent=4)
[ "script is JavaScript code, not JSON. Notice the window._SSR_HYDRATED_DATA= before the {. Everything after that can be treated as JSON (even though technically it isn't.) You have to deal with the variable assignment first. One way is to use split():\n_, my_json = script.split('=', maxsplit=1)\n\nNow you can use json.loads() to parse it:\nobj = my_json.loads(my_json)\n\nAnd finally you can get the part you want:\nprint(obj['AuthorDetailInfo'])\n\nNote: The maxsplit=1 is just in case there are any other = characters in the string. Also, this only works if the JavaScript object in the assignment is valid JSON.\n" ]
[ 0 ]
[]
[]
[ "json", "python", "request", "web_scraping" ]
stackoverflow_0074549794_json_python_request_web_scraping.txt
Q: Python or math: How to count all possible combinations of a list's elements? Say there is a list [1,2,3,4,5], I would need to get the count of all possible combinations of the elements (or 'sub-lists'), e.g. 1, 2, 3, 4, 5, 12, 13, 14, ..., 123, 124, ..., 12345. I know how to get nCr, the count of combinations of r elements of a list with total n elements. Python 3.8 or above: from math import comb p, r = 5, 2 print(comb(p, r)) Then I could do nC1 + nC2 +...+ nCn. But is there a better/faster way? p, result = 5, 0 for r in range(1, 6): result += comb(p, r) print(result) Would appreciate your answers. A: This concept is called a power set in mathematics, and it refers to all subsets of a given set. Your question refers to the size of the power set which is 2^n where n is the size of your original set. This total includes the empty set, so as C4stor said, your total would be 2^n - 1. The above answer works if the input has all unique elements. If there are repeated elements then take the product of (count + 1) of every element, and again subtract one at the end to remove the empty set. E.g. [1,1,1,2,2,3]: our counts are 3, 2, 1, so our answer is 4 * 3 * 2 - 1 = 23. The idea is that for each element, you can have anywhere from 0 up to count(element) in your sublists. A: This specific sum is equal to 2^n -1 :-)
Python or math: How to count all possible combinations of a list's elements?
Say there is a list [1,2,3,4,5], I would need to get the count of all possible combinations of the elements (or 'sub-lists'), e.g. 1, 2, 3, 4, 5, 12, 13, 14, ..., 123, 124, ..., 12345. I know how to get nCr, the count of combinations of r elements of a list with total n elements. Python 3.8 or above: from math import comb p, r = 5, 2 print(comb(p, r)) Then I could do nC1 + nC2 +...+ nCn. But is there a better/faster way? p, result = 5, 0 for r in range(1, 6): result += comb(p, r) print(result) Would appreciate your answers.
[ "This concept is called a power set in mathematics, and it refers to all subsets of a given set. Your question refers to the size of the power set which is 2^n where n is the size of your original set. This total includes the empty set, so as C4stor said, your total would be 2^n - 1.\nThe above answer works if the input has all unique elements. If there are repeated elements then take the product of (count + 1) of every element, and again subtract one at the end to remove the empty set.\nE.g. [1,1,1,2,2,3]: our counts are 3, 2, 1, so our answer is 4 * 3 * 2 - 1 = 23.\nThe idea is that for each element, you can have anywhere from 0 up to count(element) in your sublists.\n", "This specific sum is equal to 2^n -1 :-)\n" ]
[ 3, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074549925_math_python.txt
Q: Converting Intersystems cache objectscript into a python function I am accessing an Intersystems cache 2017.1.xx instance through a python process to get various attributes about the database in able to monitor the database. One of the items I want to monitor is license usage. I wrote a objectscript script in a Terminal window to access license usage by user: s Rset=##class(%ResultSet).%New("%SYSTEM.License.UserListAll") s r=Rset.Execute() s ncol=Rset.GetColumnCount() While (Rset.Next()) {f i=1:1:ncol w !,Rset.GetData(i)} But, I have been unable to determine how to convert this script into a Python equivalent. I am using the intersys.pythonbind3 import for connecting and accessing the cache instance. I have been able to create python functions that accessing most everything else in the instance but this one piece of data I can not figure out how to translate it to Python (3.7). A: Following should work (based on the documentation): query = intersys.pythonbind.query(database) query.prepare_class("%SYSTEM.License","UserListAll") query.execute(); # Fetch each row in the result set, and print the # name and value of each column in a row: while 1: cols = query.fetch([None]) if len(cols) == 0: break print str(cols[0]) Also, notice that InterSystems IRIS -- successor to the Caché now has Python as an embedded language. See more in the docs A: Since the noted query "UserListAll" is not defined correctly in the library; not SqlProc. So to resolve this issue would require a ObjectScript with the query and the use of @Result set or similar in Python to get the results. So I am marking this as resolved. A: Not sure which Python interface you're using for Cache/IRIS, but this Open Source 3rd party one is worth investigating for the kind of things you're trying to do: https://github.com/chrisemunt/mg_python
Converting Intersystems cache objectscript into a python function
I am accessing an Intersystems cache 2017.1.xx instance through a python process to get various attributes about the database in able to monitor the database. One of the items I want to monitor is license usage. I wrote a objectscript script in a Terminal window to access license usage by user: s Rset=##class(%ResultSet).%New("%SYSTEM.License.UserListAll") s r=Rset.Execute() s ncol=Rset.GetColumnCount() While (Rset.Next()) {f i=1:1:ncol w !,Rset.GetData(i)} But, I have been unable to determine how to convert this script into a Python equivalent. I am using the intersys.pythonbind3 import for connecting and accessing the cache instance. I have been able to create python functions that accessing most everything else in the instance but this one piece of data I can not figure out how to translate it to Python (3.7).
[ "Following should work (based on the documentation):\nquery = intersys.pythonbind.query(database)\nquery.prepare_class(\"%SYSTEM.License\",\"UserListAll\")\nquery.execute();\n\n# Fetch each row in the result set, and print the\n# name and value of each column in a row: \nwhile 1:\n cols = query.fetch([None])\n if len(cols) == 0: break\n print str(cols[0])\n\nAlso, notice that InterSystems IRIS -- successor to the Caché now has Python as an embedded language. See more in the docs\n", "Since the noted query \"UserListAll\" is not defined correctly in the library; not SqlProc. So to resolve this issue would require a ObjectScript with the query and the use of @Result set or similar in Python to get the results. So I am marking this as resolved.\n", "Not sure which Python interface you're using for Cache/IRIS, but this Open Source 3rd party one is worth investigating for the kind of things you're trying to do:\nhttps://github.com/chrisemunt/mg_python\n" ]
[ 0, 0, 0 ]
[]
[]
[ "caching", "intersystems", "python" ]
stackoverflow_0071573937_caching_intersystems_python.txt
Q: Why is the apple not spawning? My Problem As a new programmer, I tried to make Snake in Python, the most straightforward programming language (besides Scratch) using Pygame. I didn't understand the problem until now, and the Food (And the snake's death point) are going out of bounds from the game's display. What should I do? My code # Importing libraries import pygame import random # Pygame initialization pygame.init() dis_width = 600 dis_height = 500 dis = pygame.display.set_mode((dis_width, dis_height)) clock = pygame.time.Clock() snake_block = 10 snake_speed = 10 font_style = pygame.font.SysFont("comicsansms", 25) score_font = pygame.font.SysFont("comicsansms", 35) pygame.display.set_caption('Snake REVAMPED') white = (255, 255, 255) blue = (50, 153, 213) red = (213, 50, 80) green = (0, 255, 102) yellow = (255, 255, 102) black = (0, 0, 0) # Defining functions def Your_score(score): Returning_value = score_font.render("Score: " + str(score), True, black) dis.blit(Returning_value, [0, 0]) def our_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(dis, green, [x[0], x[1], snake_block, snake_block]) def message(msg, color): m = font_style.render(msg, True, color) dis.blit(m, [dis_width / 6, dis_height / 3]) def Game_loop(): game_over = False game_close = False x1 = dis_width / 2 y1 = dis_height / 2 x1_change = 0 y1_change = 0 snake_list = [] Snake_length = 1 Food_x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 Food_y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 while not game_over: while game_close == True: dis.fill(black) message("Ouch! Press Enter to try again, or Shift to quit.", white) Your_score(Snake_length - 1) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: Game_loop() if event.key == pygame.K_LSHIFT: game_over = True game_close = False if event.key == pygame.K_RSHIFT: game_over = True game_close = False for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x1_change = -snake_block y1_change = 0 elif event.key == pygame.K_UP: x1_change = 0 y1_change = -snake_block elif event.key == pygame.K_RIGHT: x1_change = snake_block y1_change = 0 elif event.key == pygame.K_DOWN: x1_change = 0 y1_change = snake_block if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0: game_close = True x1 += x1_change y1 += y1_change dis.fill(white) pygame.draw.rect(dis, red, [Food_x, Food_y, snake_block, snake_block]) snake_Head = [] snake_Head.append(x1) snake_Head.append(y1) snake_list.append(snake_Head) if len(snake_list) > Snake_length: del snake_list[0] for x in snake_list[:-1]: if x == snake_Head: game_close = True our_snake(snake_block, snake_list) Your_score(Snake_length - 1) pygame.display.update() if x1 == Food_x and y1 == Food_y: Food_x = round( random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 Food_y = round( random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 Snake_length += 1 clock.tick(snake_speed) pygame.quit() quit() Game_loop() What I tried to do To fix the problem, I tried changing the variable "snake_block". But, it only made the sprites (If you could even call them sprites...) bigger, with the hitboxes messed up. I just can't seem to get what the problem is, and I have no idea how I'm supposed to add screen bounds to my game.
Why is the apple not spawning?
My Problem As a new programmer, I tried to make Snake in Python, the most straightforward programming language (besides Scratch) using Pygame. I didn't understand the problem until now, and the Food (And the snake's death point) are going out of bounds from the game's display. What should I do? My code # Importing libraries import pygame import random # Pygame initialization pygame.init() dis_width = 600 dis_height = 500 dis = pygame.display.set_mode((dis_width, dis_height)) clock = pygame.time.Clock() snake_block = 10 snake_speed = 10 font_style = pygame.font.SysFont("comicsansms", 25) score_font = pygame.font.SysFont("comicsansms", 35) pygame.display.set_caption('Snake REVAMPED') white = (255, 255, 255) blue = (50, 153, 213) red = (213, 50, 80) green = (0, 255, 102) yellow = (255, 255, 102) black = (0, 0, 0) # Defining functions def Your_score(score): Returning_value = score_font.render("Score: " + str(score), True, black) dis.blit(Returning_value, [0, 0]) def our_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(dis, green, [x[0], x[1], snake_block, snake_block]) def message(msg, color): m = font_style.render(msg, True, color) dis.blit(m, [dis_width / 6, dis_height / 3]) def Game_loop(): game_over = False game_close = False x1 = dis_width / 2 y1 = dis_height / 2 x1_change = 0 y1_change = 0 snake_list = [] Snake_length = 1 Food_x = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 Food_y = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 while not game_over: while game_close == True: dis.fill(black) message("Ouch! Press Enter to try again, or Shift to quit.", white) Your_score(Snake_length - 1) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: Game_loop() if event.key == pygame.K_LSHIFT: game_over = True game_close = False if event.key == pygame.K_RSHIFT: game_over = True game_close = False for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x1_change = -snake_block y1_change = 0 elif event.key == pygame.K_UP: x1_change = 0 y1_change = -snake_block elif event.key == pygame.K_RIGHT: x1_change = snake_block y1_change = 0 elif event.key == pygame.K_DOWN: x1_change = 0 y1_change = snake_block if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0: game_close = True x1 += x1_change y1 += y1_change dis.fill(white) pygame.draw.rect(dis, red, [Food_x, Food_y, snake_block, snake_block]) snake_Head = [] snake_Head.append(x1) snake_Head.append(y1) snake_list.append(snake_Head) if len(snake_list) > Snake_length: del snake_list[0] for x in snake_list[:-1]: if x == snake_Head: game_close = True our_snake(snake_block, snake_list) Your_score(Snake_length - 1) pygame.display.update() if x1 == Food_x and y1 == Food_y: Food_x = round( random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 Food_y = round( random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 Snake_length += 1 clock.tick(snake_speed) pygame.quit() quit() Game_loop() What I tried to do To fix the problem, I tried changing the variable "snake_block". But, it only made the sprites (If you could even call them sprites...) bigger, with the hitboxes messed up. I just can't seem to get what the problem is, and I have no idea how I'm supposed to add screen bounds to my game.
[]
[]
[ "As commented, the game works ok for me, however, I would swap the following lines:\n if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:\n game_close = True\n x1 += x1_change\n y1 += y1_change\n\nIt makes more sense like this:\n x1 += x1_change\n y1 += y1_change\n if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:\n game_close = True\n\nYou first want to update the position, only after that check whether the NEW position is out-of-bounds.\nI did not notice this issue while playing because, when you are out-of-bounds, it is impossible to get back in-bounds within the next move, but the wrong ordering let to the delay being twice the expected before the game over screen appeared.\n" ]
[ -1 ]
[ "pygame", "python" ]
stackoverflow_0074549810_pygame_python.txt
Q: Python folium - failed with extending functionality I would like to extend the functionality of my folium map I found a nice thread here: Python: How to extend Folium functionality (such as measuring distance) by using JS Leaflet inside python code? but it doesn't work when apply to my code export_js = [ ( "leaflet_bigimage_js", "js/Leaflet.BigImage.js", ) ] export_css = [ ( "leaflet_bigimage_css", "css/Leaflet.BigImage.css", ) ] exp = folium.MacroElement() exp.template = jinja2.Template(""" {% macro script(this, kwargs) %} L.control.bigImage({position: 'topright'}).addTo{map} {% endmacro %} """) map.get_root().add_child(exp) the map works, but the element doesn't appear at all. Moreover, JS console sees nothing. Is there any way how could I sort it out? UPDATE: I tried also: class exp(MacroElement): exp_template = Template(u""" {% macro script(this, kwargs) %} L.control.bigImage({position: 'topright'}).addTo({{ this._parent.get_name() }}) {% endmacro %} """) map.add_child(exp()) but with the same result A: If you have the css and js files on the computer, you can use the branca library, that gets installed with folium to include the js and css elements. import folium from branca.element import CssLink, JavascriptLink from pathlib import Path js_file = Path("/path/to/script.js") js_link = JavascriptLink(js_file.as_uri()) css_file = Path("/path/to/style.css") css_link = CssLink(css_file.as_uri()) map = folium.Map() html = map.get_root() header = html.header #Add links header.add_child(css_link) header.add_child(js_link)
Python folium - failed with extending functionality
I would like to extend the functionality of my folium map I found a nice thread here: Python: How to extend Folium functionality (such as measuring distance) by using JS Leaflet inside python code? but it doesn't work when apply to my code export_js = [ ( "leaflet_bigimage_js", "js/Leaflet.BigImage.js", ) ] export_css = [ ( "leaflet_bigimage_css", "css/Leaflet.BigImage.css", ) ] exp = folium.MacroElement() exp.template = jinja2.Template(""" {% macro script(this, kwargs) %} L.control.bigImage({position: 'topright'}).addTo{map} {% endmacro %} """) map.get_root().add_child(exp) the map works, but the element doesn't appear at all. Moreover, JS console sees nothing. Is there any way how could I sort it out? UPDATE: I tried also: class exp(MacroElement): exp_template = Template(u""" {% macro script(this, kwargs) %} L.control.bigImage({position: 'topright'}).addTo({{ this._parent.get_name() }}) {% endmacro %} """) map.add_child(exp()) but with the same result
[ "If you have the css and js files on the computer, you can use the branca library, that gets installed with folium to include the js and css elements.\nimport folium\nfrom branca.element import CssLink, JavascriptLink\nfrom pathlib import Path\n\njs_file = Path(\"/path/to/script.js\")\njs_link = JavascriptLink(js_file.as_uri())\n\ncss_file = Path(\"/path/to/style.css\")\ncss_link = CssLink(css_file.as_uri())\n\nmap = folium.Map()\nhtml = map.get_root()\nheader = html.header\n\n#Add links\nheader.add_child(css_link)\nheader.add_child(js_link)\n\n" ]
[ 0 ]
[]
[]
[ "folium", "python" ]
stackoverflow_0074545694_folium_python.txt
Q: create a python script in another python script and run it I have an python application which reads the python scripts and runs it and returns the values: main.py def Exec(id): try: connection = mysql.connector.connect(host='localhost', user='root', password='', database='mydb') # Fetch the python script from pythontbl table sql_select_Query = "SELECT python FROM mydb.pythontbl WHERE id={}".format(id) cursor = connection.cursor() cursor.execute(sql_select_Query) # get all records script = cursor.fetchall() # execute the python script with arguments ?? # return value should be saved in out out= ??? print("output",out) ?? except mysql.connector.Error as e: print("Error reading data from MySQL table", e) finally: if connection.is_connected(): connection.close() cursor.close() print("MySQL connection is closed") how can I execute the python script which I fetched from my main and sending the arguments to script and get back the result ? I can not use import script.py as I am fetching the script through my main.py A: create another file name fetchscript.py and in this file create the connection and fetch the script from your table , call fetchscript.py from main.py and then import pythonscript and call the desired function from pythonscript.py
create a python script in another python script and run it
I have an python application which reads the python scripts and runs it and returns the values: main.py def Exec(id): try: connection = mysql.connector.connect(host='localhost', user='root', password='', database='mydb') # Fetch the python script from pythontbl table sql_select_Query = "SELECT python FROM mydb.pythontbl WHERE id={}".format(id) cursor = connection.cursor() cursor.execute(sql_select_Query) # get all records script = cursor.fetchall() # execute the python script with arguments ?? # return value should be saved in out out= ??? print("output",out) ?? except mysql.connector.Error as e: print("Error reading data from MySQL table", e) finally: if connection.is_connected(): connection.close() cursor.close() print("MySQL connection is closed") how can I execute the python script which I fetched from my main and sending the arguments to script and get back the result ? I can not use import script.py as I am fetching the script through my main.py
[ "create another file name fetchscript.py and in this file create the connection and fetch the script from your table , call fetchscript.py from main.py and then import pythonscript and call the desired function from pythonscript.py\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074545730_python.txt
Q: Matplotlib animate fill_between shape I am trying to animate a fill_between shape inside matplotlib and I don't know how to update the data of the PolyCollection. Take this simple example: I have two lines and I am always filling between them. Of course, the lines change and are animated. Here is a dummy example: import matplotlib.pyplot as plt # Init plot: f_dummy = plt.figure(num=None, figsize=(6, 6)); axes_dummy = f_dummy.add_subplot(111); # Plotting: line1, = axes_dummy.plot(X, line1_data, color = 'k', linestyle = '--', linewidth=2.0, animated=True); line2, = axes_dummy.plot(X, line2_data, color = 'Grey', linestyle = '--', linewidth=2.0, animated=True); fill_lines = axes_dummy.fill_between(X, line1_data, line2_data, color = '0.2', alpha = 0.5, animated=True); f_dummy.show(); f_dummy.canvas.draw(); dummy_background = f_dummy.canvas.copy_from_bbox(axes_dummy.bbox); # [...] # Update plot data: def update_data(): line1_data = # Do something with data line2_data = # Do something with data f_dummy.canvas.restore_region( dummy_background ); line1.set_ydata(line1_data); line2.set_ydata(line2_data); # Update fill data too axes_dummy.draw_artist(line1); axes_dummy.draw_artist(line2); # Draw fill too f_dummy.canvas.blit( axes_dummy.bbox ); The question is how to update the fill_between Poly data based on line1_data and line2_data each time update_data() is called and draw them before blit ("# Update fill data too" & "# Draw fill too"). I tried fill_lines.set_verts() without success and could not find an example. A: Ok, as someone pointed out, we are dealing with a collection here, so we will have to delete and redraw. So somewhere in the update_data function, delete all collections associated with it: axes_dummy.collections.clear() and draw the new "fill_between" PolyCollection: axes_dummy.fill_between(x, y-sigma, y+sigma, facecolor='yellow', alpha=0.5) A similar trick is required to overlay an unfilled contour plot on top of a filled one, since an unfilled contour plot is a Collection as well (of lines I suppose?). A: this is not my answer, but I found it most useful: http://matplotlib.1069221.n5.nabble.com/animation-of-a-fill-between-region-td42814.html Hi Mauricio, Patch objects are a bit more difficult to work with than line objects, because unlike line objects are a step removed from the input data supplied by the user. There is an example similar to what you want to do here: http://matplotlib.org/examples/animation/histogram.html Basically, you need to modify the vertices of the path at each frame. It might look something like this: from matplotlib import animation import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.set_xlim([0,10000]) x = np.linspace(6000.,7000., 5) y = np.ones_like(x) collection = plt.fill_between(x, y) def animate(i): path = collection.get_paths()[0] path.vertices[:, 1] *= 0.9 animation.FuncAnimation(fig, animate, frames=25, interval=30) Take a look at path.vertices to see how they're laid out. Hope that helps, Jake A: If you don't want to use anitmation, or to remove everything from your figure to update only filling, you could use this way : call fill_lines.remove() and then call again axes_dummy.fill_between() to draw new ones. It worked in my case. A: initialize pyplot interactive mode import matplotlib.pyplot as plt plt.ion() use the optional label argument when plotting the fill: plt.fill_between( x, y1, y2, color="yellow", label="cone" ) plt.pause(0.001) # refresh the animation later in our script we can select by label to delete that specific fill or a list of fills, thus animating on a object by object basis. axis = plt.gca() fills = ["cone", "sideways", "market"] for collection in axis.collections: if str(collection.get_label()) in fills: collection.remove() del collection plt.pause(0.001) you can use the same label for groups of objects you would like to delete; or otherwise encode the labels with tags as needed to suit needs for example if we had fills labelled: "cone1" "cone2" "sideways1" if "cone" in str(collection.get_label()): would sort to delete both those prefixed with "cone". You can also animate lines in the same manner for line in axis.lines: A: another idiom which will work is too keep a list of your plotted objects; this method seems to work with any type of plotted object. # plot interactive mode on plt.ion() # create a dict to store "fills" # perhaps some other subclass of plots # "yellow lines" etc. plots = {"fills":[]} # begin the animation while 1: # cycle through previously plotted objects # attempt to kill them; else remember they exist fills = [] for fill in plots["fills"]: try: # remove and destroy reference fill.remove() del fill except: # and if not try again next time fills.append(fill) pass plots["fills"] = fills # transformation of data for next frame x, y1, y2 = your_function(x, y1, y2) # fill between plot is appended to stored fills list plots["fills"].append( plt.fill_between( x, y1, y2, color="red", ) ) # frame rate plt.pause(1) A: In contrast to what most answers here stated, it is not necessary to remove and redraw a PolyCollection returned by fill_between each time you want to update its data. Instead, you can modify the vertices and codes attribute of the underlying Path object. Let's assume you've created a PolyCollection via import numpy as np import matplotlib.pyplot as plt #dummy data x = np.arange(10) y0 = x-1 y1 = x+1 fig = plt.figure() ax = fig.add_subplot() p = ax.fill_between(x,y0,y1) and now you want to update p with new data xnew, y0new and y1new. Then what you could do is v_x = np.hstack([xnew[0],xnew,xnew[-1],xnew[::-1],xnew[0]]) v_y = np.hstack([y1new[0],y0new,y0new[-1],y1new[::-1],y1new[0]]) vertices = np.vstack([v_x,v_y]).T codes = np.array([1]+(2*len(xnew)+1)*[2]+[79]).astype('uint8') path = p.get_paths()[0] path.vertices = vertices path.codes = codes Explanation: path.vertices contains the vertices of the patch drawn by fill_between including additional start and end positions, path.codes contains instructions on how to use them (1=MOVE POINTER TO, 2=DRAW LINE TO, 79=CLOSE POLY).
Matplotlib animate fill_between shape
I am trying to animate a fill_between shape inside matplotlib and I don't know how to update the data of the PolyCollection. Take this simple example: I have two lines and I am always filling between them. Of course, the lines change and are animated. Here is a dummy example: import matplotlib.pyplot as plt # Init plot: f_dummy = plt.figure(num=None, figsize=(6, 6)); axes_dummy = f_dummy.add_subplot(111); # Plotting: line1, = axes_dummy.plot(X, line1_data, color = 'k', linestyle = '--', linewidth=2.0, animated=True); line2, = axes_dummy.plot(X, line2_data, color = 'Grey', linestyle = '--', linewidth=2.0, animated=True); fill_lines = axes_dummy.fill_between(X, line1_data, line2_data, color = '0.2', alpha = 0.5, animated=True); f_dummy.show(); f_dummy.canvas.draw(); dummy_background = f_dummy.canvas.copy_from_bbox(axes_dummy.bbox); # [...] # Update plot data: def update_data(): line1_data = # Do something with data line2_data = # Do something with data f_dummy.canvas.restore_region( dummy_background ); line1.set_ydata(line1_data); line2.set_ydata(line2_data); # Update fill data too axes_dummy.draw_artist(line1); axes_dummy.draw_artist(line2); # Draw fill too f_dummy.canvas.blit( axes_dummy.bbox ); The question is how to update the fill_between Poly data based on line1_data and line2_data each time update_data() is called and draw them before blit ("# Update fill data too" & "# Draw fill too"). I tried fill_lines.set_verts() without success and could not find an example.
[ "Ok, as someone pointed out, we are dealing with a collection here, so we will have to delete and redraw. So somewhere in the update_data function, delete all collections associated with it:\naxes_dummy.collections.clear()\n\nand draw the new \"fill_between\" PolyCollection:\naxes_dummy.fill_between(x, y-sigma, y+sigma, facecolor='yellow', alpha=0.5)\n\nA similar trick is required to overlay an unfilled contour plot on top of a filled one, since an unfilled contour plot is a Collection as well (of lines I suppose?).\n", "this is not my answer, but I found it most useful:\nhttp://matplotlib.1069221.n5.nabble.com/animation-of-a-fill-between-region-td42814.html\nHi Mauricio,\nPatch objects are a bit more difficult to work with than line objects, because unlike line objects are a step removed from the input data supplied by the user. There is an example similar to what you want to do here: http://matplotlib.org/examples/animation/histogram.html\nBasically, you need to modify the vertices of the path at each frame. It might look something like this:\nfrom matplotlib import animation\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.set_xlim([0,10000])\n\nx = np.linspace(6000.,7000., 5)\ny = np.ones_like(x)\n\ncollection = plt.fill_between(x, y)\n\ndef animate(i):\n path = collection.get_paths()[0]\n path.vertices[:, 1] *= 0.9\n\nanimation.FuncAnimation(fig, animate,\n frames=25, interval=30)\n\nTake a look at path.vertices to see how they're laid out.\nHope that helps,\n Jake\n", "If you don't want to use anitmation, or to remove everything from your figure to update only filling, you could use this way :\ncall fill_lines.remove() and then call again axes_dummy.fill_between() to draw new ones. It worked in my case.\n", "initialize pyplot interactive mode\nimport matplotlib.pyplot as plt\n\nplt.ion()\n\nuse the optional label argument when plotting the fill:\nplt.fill_between(\n x, \n y1, \n y2, \n color=\"yellow\", \n label=\"cone\"\n)\n\nplt.pause(0.001) # refresh the animation\n\nlater in our script we can select by label to delete that specific fill or a list of fills, thus animating on a object by object basis.\naxis = plt.gca()\n\nfills = [\"cone\", \"sideways\", \"market\"] \n\nfor collection in axis.collections:\n if str(collection.get_label()) in fills:\n collection.remove()\n del collection\n\nplt.pause(0.001)\n\nyou can use the same label for groups of objects you would like to delete; or otherwise encode the labels with tags as needed to suit needs\nfor example if we had fills labelled: \n\"cone1\" \"cone2\" \"sideways1\" \nif \"cone\" in str(collection.get_label()):\n\nwould sort to delete both those prefixed with \"cone\".\nYou can also animate lines in the same manner\nfor line in axis.lines:\n\n", "another idiom which will work is too keep a list of your plotted objects; this method seems to work with any type of plotted object.\n# plot interactive mode on\nplt.ion()\n\n# create a dict to store \"fills\" \n# perhaps some other subclass of plots \n# \"yellow lines\" etc. \nplots = {\"fills\":[]}\n\n# begin the animation\nwhile 1: \n\n # cycle through previously plotted objects\n # attempt to kill them; else remember they exist\n fills = []\n for fill in plots[\"fills\"]:\n try:\n # remove and destroy reference\n fill.remove()\n del fill\n except:\n # and if not try again next time\n fills.append(fill)\n pass\n plots[\"fills\"] = fills \n\n # transformation of data for next frame \n x, y1, y2 = your_function(x, y1, y2)\n\n # fill between plot is appended to stored fills list\n plots[\"fills\"].append(\n plt.fill_between(\n x,\n y1,\n y2,\n color=\"red\",\n )\n )\n\n # frame rate\n plt.pause(1)\n\n", "In contrast to what most answers here stated, it is not necessary to remove and redraw a PolyCollection returned by fill_between each time you want to update its data. Instead, you can modify the vertices and codes attribute of the underlying Path object. Let's assume you've created a PolyCollection via\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#dummy data\nx = np.arange(10)\ny0 = x-1\ny1 = x+1\n\nfig = plt.figure()\nax = fig.add_subplot()\np = ax.fill_between(x,y0,y1)\n\nand now you want to update p with new data xnew, y0new and y1new. Then what you could do is\nv_x = np.hstack([xnew[0],xnew,xnew[-1],xnew[::-1],xnew[0]])\nv_y = np.hstack([y1new[0],y0new,y0new[-1],y1new[::-1],y1new[0]])\nvertices = np.vstack([v_x,v_y]).T\ncodes = np.array([1]+(2*len(xnew)+1)*[2]+[79]).astype('uint8')\n\npath = p.get_paths()[0]\npath.vertices = vertices\npath.codes = codes\n\nExplanation: path.vertices contains the vertices of the patch drawn by fill_between including additional start and end positions, path.codes contains instructions on how to use them (1=MOVE POINTER TO, 2=DRAW LINE TO, 79=CLOSE POLY).\n" ]
[ 12, 5, 3, 0, 0, 0 ]
[]
[]
[ "animation", "matplotlib", "plot", "python" ]
stackoverflow_0016120801_animation_matplotlib_plot_python.txt
Q: ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects I'm trying to install discord.py , but I get this error out. pip updated immediately I say. I reinstalled python, pip and so on, I installed in pycharm both from PythonInterpreter and through the terminal please helpp \dfggfdgfdgfdgdf \fdggfddgfdgfgfd \fdgfdggfdgfdgfd \dfgdfgfdgdfg \fdgdfgfdgdfg \fdgfdgfdgfdg \dfgdfgdfgdf \gfdgfdgfdgdf \gfdgdfgdfg \dfgdfgfdgfdg × Building wheel for yarl (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [98 lines of output] C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\config\setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) ********************** * Accelerated build * ********************** running bdist_wheel running build running build_py running egg_info writing yarl.egg-info\PKG-INFO writing dependency_links to yarl.egg-info\dependency_links.txt writing requirements to yarl.egg-info\requires.txt writing top-level names to yarl.egg-info\top_level.txt reading manifest file 'yarl.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no previously-included files matching '*.pyc' found anywhere in distribution warning: no previously-included files matching '*.cache' found anywhere in distribution warning: no previously-included files found matching 'yarl\*.html' warning: no previously-included files found matching 'yarl\*.so' warning: no previously-included files found matching 'yarl\*.pyd' no previously-included directories found matching 'docs\_build' adding license file 'LICENSE' running build_ext building 'yarl._quoting_c' extension Traceback (most recent call last): File "C:\Users\User\PycharmProjects\pythonProject\venv\Lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 351, in <module> main() File "C:\Users\User\PycharmProjects\pythonProject\venv\Lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 333, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\PycharmProjects\pythonProject\venv\Lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 249, in build_wheel return _build_backend().build_wheel(wheel_directory, config_settings, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\build_meta.py", line 412, in build_wheel return self._build_with_temp_dir(['bdist_wheel'], '.whl', ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\build_meta.py", line 397, in _build_with_temp_dir self.run_setup() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\build_meta.py", line 484, in run_setup self).run_setup(setup_script=setup_script) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\build_meta.py", line 335, in run_setup exec(code, locals()) File "<string>", line 86, in <module> File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\__init__.py", line 87, in setup return distutils.core.setup(**attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 185, in setup return run_commands(dist) ^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 201, in run_commands dist.run_commands() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 968, in run_commands self.run_command(cmd) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\wheel\bdist_wheel.py", line 299, in run self.run_command('build') File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 319, in run_command self.distribution.run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build.py", line 132, in run self.run_command(cmd_name) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 319, in run_command self.distribution.run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\command\build_ext.py", line 84, in run _build_ext.run(self) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build_ext.py", line 346, in run self.build_extensions() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build_ext.py", line 466, in build_extensions self._build_extensions_serial() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build_ext.py", line 492, in _build_extensions_serial self.build_extension(ext) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\command\build_ext.py", line 246, in build_extension _build_ext.build_extension(self, ext) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build_ext.py", line 547, in build_extension objects = self.compiler.compile( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 344, in compile self.initialize() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 253, in initialize vc_env = _get_vc_env(plat_spec) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\msvc.py", line 214, in msvc14_get_vc_env return _msvc14_get_vc_env(plat_spec) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\msvc.py", line 168, in _msvc14_get_vc_env raise distutils.errors.DistutilsPlatformError( setuptools._distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for yarl Failed to build frozenlist multidict yarl ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects A: You probably have to investigate the error message in your log: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools" Here is related question: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools" Also the following may be helpful. I had the exact description of the error as in title of this question but for aiohttp, yarl and frozenlist modules. Just in case will leave here the description of encountered error and the solution. The error below I got while executing pip install -r requirements.txt for installation I made: socket.c -o build/temp.linux-armv8l-cpython-311/aiohttp/_websocket.o aiohttp/_websocket.c:198:12: fatal error: 'longintrepr.h' file not found #include "longintrepr.h" ^~~~~~~ 1 error generated. error: command '/data/data/com.termux/files/usr/bin/arm-linux-androideabi-clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for aiohttp Failed to build aiohttp ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects This error is specific to Python 3.11 version. On Python with 3.10.6 version installation went fine. To solve it I needed to update requirements.txt. Not working versions of modules with Python 3.11: aiohttp==3.8.1 yarl==1.4.2 frozenlist==1.3.0 Working versions: aiohttp==3.8.2 yarl==1.8.1 frozenlist==1.3.1 Links to the corresponding issues with fixes: https://github.com/aio-libs/aiohttp/issues/6600 https://github.com/aio-libs/yarl/issues/706 https://github.com/aio-libs/frozenlist/issues/305
ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects
I'm trying to install discord.py , but I get this error out. pip updated immediately I say. I reinstalled python, pip and so on, I installed in pycharm both from PythonInterpreter and through the terminal please helpp \dfggfdgfdgfdgdf \fdggfddgfdgfgfd \fdgfdggfdgfdgfd \dfgdfgfdgdfg \fdgdfgfdgdfg \fdgfdgfdgfdg \dfgdfgdfgdf \gfdgfdgfdgdf \gfdgdfgdfg \dfgdfgfdgfdg × Building wheel for yarl (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [98 lines of output] C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\config\setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) ********************** * Accelerated build * ********************** running bdist_wheel running build running build_py running egg_info writing yarl.egg-info\PKG-INFO writing dependency_links to yarl.egg-info\dependency_links.txt writing requirements to yarl.egg-info\requires.txt writing top-level names to yarl.egg-info\top_level.txt reading manifest file 'yarl.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no previously-included files matching '*.pyc' found anywhere in distribution warning: no previously-included files matching '*.cache' found anywhere in distribution warning: no previously-included files found matching 'yarl\*.html' warning: no previously-included files found matching 'yarl\*.so' warning: no previously-included files found matching 'yarl\*.pyd' no previously-included directories found matching 'docs\_build' adding license file 'LICENSE' running build_ext building 'yarl._quoting_c' extension Traceback (most recent call last): File "C:\Users\User\PycharmProjects\pythonProject\venv\Lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 351, in <module> main() File "C:\Users\User\PycharmProjects\pythonProject\venv\Lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 333, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\PycharmProjects\pythonProject\venv\Lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 249, in build_wheel return _build_backend().build_wheel(wheel_directory, config_settings, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\build_meta.py", line 412, in build_wheel return self._build_with_temp_dir(['bdist_wheel'], '.whl', ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\build_meta.py", line 397, in _build_with_temp_dir self.run_setup() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\build_meta.py", line 484, in run_setup self).run_setup(setup_script=setup_script) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\build_meta.py", line 335, in run_setup exec(code, locals()) File "<string>", line 86, in <module> File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\__init__.py", line 87, in setup return distutils.core.setup(**attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 185, in setup return run_commands(dist) ^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 201, in run_commands dist.run_commands() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 968, in run_commands self.run_command(cmd) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\wheel\bdist_wheel.py", line 299, in run self.run_command('build') File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 319, in run_command self.distribution.run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build.py", line 132, in run self.run_command(cmd_name) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 319, in run_command self.distribution.run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\dist.py", line 1217, in run_command super().run_command(command) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 987, in run_command cmd_obj.run() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\command\build_ext.py", line 84, in run _build_ext.run(self) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build_ext.py", line 346, in run self.build_extensions() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build_ext.py", line 466, in build_extensions self._build_extensions_serial() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build_ext.py", line 492, in _build_extensions_serial self.build_extension(ext) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\command\build_ext.py", line 246, in build_extension _build_ext.build_extension(self, ext) File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\command\build_ext.py", line 547, in build_extension objects = self.compiler.compile( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 344, in compile self.initialize() File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\_distutils\_msvccompiler.py", line 253, in initialize vc_env = _get_vc_env(plat_spec) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\msvc.py", line 214, in msvc14_get_vc_env return _msvc14_get_vc_env(plat_spec) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Temp\pip-build-env-0gyts2a3\overlay\Lib\site-packages\setuptools\msvc.py", line 168, in _msvc14_get_vc_env raise distutils.errors.DistutilsPlatformError( setuptools._distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for yarl Failed to build frozenlist multidict yarl ERROR: Could not build wheels for frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects
[ "You probably have to investigate the error message in your log:\nMicrosoft Visual C++ 14.0 or greater is required. Get it with \"Microsoft C++ Build Tools\"\nHere is related question: Microsoft Visual C++ 14.0 is required. Get it with \"Microsoft Visual C++ Build Tools\"\n\nAlso the following may be helpful. I had the exact description of the error as in title of this question but for aiohttp, yarl and frozenlist modules. Just in case will leave here the description of encountered error and the solution.\nThe error below I got while executing pip install -r requirements.txt for installation I made:\nsocket.c -o build/temp.linux-armv8l-cpython-311/aiohttp/_websocket.o\naiohttp/_websocket.c:198:12: fatal error: 'longintrepr.h' file not found\n#include \"longintrepr.h\" \n ^~~~~~~ 1 error generated.\nerror: command '/data/data/com.termux/files/usr/bin/arm-linux-androideabi-clang' \nfailed with exit code 1\n[end of output]\nnote: This error originates from a subprocess, and is likely not a problem with pip.\nERROR: Failed building wheel for aiohttp\nFailed to build aiohttp\nERROR: Could not build wheels for aiohttp, which is required to install\npyproject.toml-based projects\n\nThis error is specific to Python 3.11 version. On Python with 3.10.6 version installation went fine.\nTo solve it I needed to update requirements.txt.\nNot working versions of modules with Python 3.11:\naiohttp==3.8.1\nyarl==1.4.2\nfrozenlist==1.3.0\n\nWorking versions:\naiohttp==3.8.2\nyarl==1.8.1\nfrozenlist==1.3.1\n\nLinks to the corresponding issues with fixes:\n\nhttps://github.com/aio-libs/aiohttp/issues/6600\nhttps://github.com/aio-libs/yarl/issues/706\nhttps://github.com/aio-libs/frozenlist/issues/305\n\n" ]
[ 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074255709_discord_discord.py_python.txt
Q: Pandas Separate categorical and numeric features from multiple data frames and store in a new data frame I have a situation where I want to separate categorical and numeric features from multiple data frames as mentioned below (df1,df2,df3, and df4) and I want to store these in two different data frames with names "Cont" and "Cat". I am looking for a process that loops into these multiple data frames and gives the output that I am looking for as explained below. This should purely work using the dtypes functionality of pandas to identify if a col is categorical or numeric The input data frames look like: df1: Name1 Number1 ABC 123 DEF 234 XXX 456 df2: Name2 Number2 ABCD 1232 DEFG 2342 XXXY 4562 df3: Name3 Number3 AB 12 DE 23 XX 45 df4: Name4 Number4 A 1 D 3 X 5 The output should look like: Cat: Name1 Name2 Name3 Name4 ABC ABCD AB A DEF DEFG DE D XXX XXXY XX X and similarly: Cont: Number1 Number2 Number3 Number4 123 1232 12 1 234 2342 23 2 456 4562 45 5 How can this be achieved? A: You can use pandas.DataFrame.select_dtypes to create the two dataframes. Try this: out = pd.concat([df1, df2, df3, df4], axis=1) ​ cat= out.select_dtypes(include="object") #or include="category" cont= out.select_dtypes(include=np.number) # Output : print(cat) Name1 Name2 Name3 Name4 0 ABC ABCD AB A 1 DEF DEFG DE D 2 XXX XXXY XX X print(cont) Number1 Number2 Number3 Number4 0 123 1232 12 1 1 234 2342 23 3 2 456 4562 45 5
Pandas Separate categorical and numeric features from multiple data frames and store in a new data frame
I have a situation where I want to separate categorical and numeric features from multiple data frames as mentioned below (df1,df2,df3, and df4) and I want to store these in two different data frames with names "Cont" and "Cat". I am looking for a process that loops into these multiple data frames and gives the output that I am looking for as explained below. This should purely work using the dtypes functionality of pandas to identify if a col is categorical or numeric The input data frames look like: df1: Name1 Number1 ABC 123 DEF 234 XXX 456 df2: Name2 Number2 ABCD 1232 DEFG 2342 XXXY 4562 df3: Name3 Number3 AB 12 DE 23 XX 45 df4: Name4 Number4 A 1 D 3 X 5 The output should look like: Cat: Name1 Name2 Name3 Name4 ABC ABCD AB A DEF DEFG DE D XXX XXXY XX X and similarly: Cont: Number1 Number2 Number3 Number4 123 1232 12 1 234 2342 23 2 456 4562 45 5 How can this be achieved?
[ "You can use pandas.DataFrame.select_dtypes to create the two dataframes.\nTry this:\nout = pd.concat([df1, df2, df3, df4], axis=1)\n​\ncat= out.select_dtypes(include=\"object\") #or include=\"category\"\ncont= out.select_dtypes(include=np.number)\n\n# Output :\nprint(cat)\n Name1 Name2 Name3 Name4\n0 ABC ABCD AB A\n1 DEF DEFG DE D\n2 XXX XXXY XX X\n\nprint(cont)\n Number1 Number2 Number3 Number4\n0 123 1232 12 1\n1 234 2342 23 3\n2 456 4562 45 5\n\n" ]
[ 1 ]
[]
[]
[ "data_wrangling", "dataframe", "dtype", "pandas", "python" ]
stackoverflow_0074550006_data_wrangling_dataframe_dtype_pandas_python.txt
Q: Pasting .bin image files into excel using openpyxl I've been trying to write a script to fetch images and paste them all together into one file. For this I use ZipFile from zipfile to extract .bin image files from a collection of .xlsx files and I planned to use openpyxl to paste them all into one new .xlsx file. When I run this, I end up getting a KeyError: '.wmf'. I tried converting the image type to .png (or other raster image types). This did fix the issue, but the .bin image files seem to act a bit like a vector type of image and I would like to keep this attribute. I would love to know how to fix this, thank you! Here is my code: from zipfile import ZipFile from pathlib import Path import sys import os import xlsxwriter as xw "Function to find location of images" imgformats = ('bin') def is_image(filename): return any(filename.endswith(ext) for ext in imgformats) "Create folder" folders = ['imgsave'] for folder in folders: if not os.path.exists(folder): os.makedirs(folder) "Group the files" path = Path(".") try: files = path.glob('*.xlsx') except PermissionError as e: print(f'Permission Error: {str(e)}') sys.exit() "Set variables" file_count = 0 overall_size = 0 data = [] "Loop over files and extract the images" if not os.path.exists('xl'): for file in files: with ZipFile(file) as working_zip: image_list = [name for name in working_zip.namelist() if is_image(name)] for img in image_list: overall_size = overall_size + working_zip.getinfo(img).file_size file_count = len(image_list) working_zip.extractall("", image_list) for img in image_list: os.rename(img, f'xl/media/{file}.bin') data.append(file_count) data.append(overall_size) "Create list of pasting locations for in excel" cellcycletemp = ['A', 'H', 'O', 'V', 'AC'] rows = 4 cellcycle = [cellcycletemp[n%rows] + str(n//rows+1+12*(n//rows)+1) for n in range(120)] "Create excel file and paste .bin images into it" wb = openpyxl.Workbook() ws = wb.worksheets[0] imagelist = [img for img in os.listdir('xl/media/.') if '.bin' in img] for n, file in enumerate(imagelist): img = openpyxl.drawing.image.Image('xl/media/' + file) img.anchor = cellcycle[n] ws.add_image(img) wb.save('imgsave/combined images.xlsx') This is the error I end up getting: Traceback (most recent call last): File "C:\<path>\test_zipandpaste.py", line 67, in <module> wb.save('imgsave/combined images.xlsx') File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\workbook\workbook.py", line 407, in save save_workbook(self, filename) File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\writer\excel.py", line 293, in save_workbook writer.save() File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\writer\excel.py", line 275, in save self.write_data() File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\writer\excel.py", line 94, in write_data self.manifest._write(archive, self.workbook) File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\packaging\manifest.py", line 181, in _write self._register_mimetypes(filenames=archive.namelist()) File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\packaging\manifest.py", line 193, in _register_mimetypes mime = mimetypes.types_map[True][ext] KeyError: '.wmf' Process finished with exit code 1 edit: found a mistake in the code I posted originally and fixed it. A: I actually found a way to do it without openpyxl. Python has a build-in library xlsxwriter which can handle .wmf files and allows it to paste the .bin files as well. import xlsxwriter as xw wb = xw.Workbook('imgsave/combined images.xlsx') ws = wb.add_worksheet() imagelist = [img for img in os.listdir('xl/media/.') if '.bin' in img] for n, file in enumerate(imagelist): ws.insert_image(cellcycle[n], f'xl/media/{file}') wb.close()
Pasting .bin image files into excel using openpyxl
I've been trying to write a script to fetch images and paste them all together into one file. For this I use ZipFile from zipfile to extract .bin image files from a collection of .xlsx files and I planned to use openpyxl to paste them all into one new .xlsx file. When I run this, I end up getting a KeyError: '.wmf'. I tried converting the image type to .png (or other raster image types). This did fix the issue, but the .bin image files seem to act a bit like a vector type of image and I would like to keep this attribute. I would love to know how to fix this, thank you! Here is my code: from zipfile import ZipFile from pathlib import Path import sys import os import xlsxwriter as xw "Function to find location of images" imgformats = ('bin') def is_image(filename): return any(filename.endswith(ext) for ext in imgformats) "Create folder" folders = ['imgsave'] for folder in folders: if not os.path.exists(folder): os.makedirs(folder) "Group the files" path = Path(".") try: files = path.glob('*.xlsx') except PermissionError as e: print(f'Permission Error: {str(e)}') sys.exit() "Set variables" file_count = 0 overall_size = 0 data = [] "Loop over files and extract the images" if not os.path.exists('xl'): for file in files: with ZipFile(file) as working_zip: image_list = [name for name in working_zip.namelist() if is_image(name)] for img in image_list: overall_size = overall_size + working_zip.getinfo(img).file_size file_count = len(image_list) working_zip.extractall("", image_list) for img in image_list: os.rename(img, f'xl/media/{file}.bin') data.append(file_count) data.append(overall_size) "Create list of pasting locations for in excel" cellcycletemp = ['A', 'H', 'O', 'V', 'AC'] rows = 4 cellcycle = [cellcycletemp[n%rows] + str(n//rows+1+12*(n//rows)+1) for n in range(120)] "Create excel file and paste .bin images into it" wb = openpyxl.Workbook() ws = wb.worksheets[0] imagelist = [img for img in os.listdir('xl/media/.') if '.bin' in img] for n, file in enumerate(imagelist): img = openpyxl.drawing.image.Image('xl/media/' + file) img.anchor = cellcycle[n] ws.add_image(img) wb.save('imgsave/combined images.xlsx') This is the error I end up getting: Traceback (most recent call last): File "C:\<path>\test_zipandpaste.py", line 67, in <module> wb.save('imgsave/combined images.xlsx') File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\workbook\workbook.py", line 407, in save save_workbook(self, filename) File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\writer\excel.py", line 293, in save_workbook writer.save() File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\writer\excel.py", line 275, in save self.write_data() File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\writer\excel.py", line 94, in write_data self.manifest._write(archive, self.workbook) File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\packaging\manifest.py", line 181, in _write self._register_mimetypes(filenames=archive.namelist()) File "C:\<path>\Python\Python310\lib\site-packages\openpyxl\packaging\manifest.py", line 193, in _register_mimetypes mime = mimetypes.types_map[True][ext] KeyError: '.wmf' Process finished with exit code 1 edit: found a mistake in the code I posted originally and fixed it.
[ "I actually found a way to do it without openpyxl. Python has a build-in library xlsxwriter which can handle .wmf files and allows it to paste the .bin files as well.\nimport xlsxwriter as xw\n\nwb = xw.Workbook('imgsave/combined images.xlsx')\nws = wb.add_worksheet()\n\nimagelist = [img for img in os.listdir('xl/media/.') if '.bin' in img]\nfor n, file in enumerate(imagelist):\n ws.insert_image(cellcycle[n], f'xl/media/{file}')\nwb.close()\n\n" ]
[ 0 ]
[]
[]
[ "bin", "excel", "openpyxl", "python" ]
stackoverflow_0074547563_bin_excel_openpyxl_python.txt
Q: Kill all "workers" on "listener" error (multiprocessing, manager and queue set-up) I'm using multiprocessing to run workers on different files in parallel. Worker's results are put into queue. A listener gets the results from the queue and writes them to the file. Sometimes listener might run into errors (of various origins). In this case, the listener silently dies, but all other processes continue running (rather surprisingly, worker errors causes all processes to terminate). I would like to stop all processes (workers, listener, e.t.c.) when listener catches an error. How this can be done? The scheme of my code is as follows: def worker(file_path, q): ## do something q.put(1.) return True def listener(q): while True: m = q.get() if m == 'kill': break else: try: # do something and write to file except Exception as err: # raise error tb = sys.exc_info()[2] raise err.with_traceback(tb) def main(): manager = mp.Manager() q = manager.Queue(maxsize=3) with mp.Pool(5) as pool: watcher = pool.apply_async(listener, (q,)) files = ['path_1','path_2','path_3'] jobs = [ pool.apply_async(worker, (p,q,)) for p in files ] # fire off workers for job in jobs: job.get() # kill the listener when done q.put('kill') # run if __name__ == "__main__": main() I tried introducing event = manager.Event() and using it as a flag in main(): ## inside the pool, after starting workers while True: if event.is_set(): for job in jobs: job.terminate() No success. Calling os._exit(1) in listener exception block rises broken pipe error, but processes are not killed. I also tried setting daemon = True, for job in jobs: job.daemon = True Did not help. In fact, to handle listener exceptions, I'm using a callable, as required by apply_async (so that they are not entirely silenced). This complicates the situation, but not much. Thank you in advance. A: As always there are many ways to accomplish what you're after, but I would probably suggest using an Event to signal that the processes should quit. I also would not use a Pool in this instance, as it only really simplifies things for simple cases where you need something like map. More complicated use cases quickly make it easier to just build you own "pool" with the functionality you need. from multiprocessing import Process, Queue, Event from random import random def might_fail(a): assert(a > .001) def worker(args_q: Queue, result_q: Queue, do_quit: Event): try: while not do_quit.is_set(): args = args_q.get() if args is None: break else: # do something result_q.put(random()) finally: #signal that worker is exiting even if exception is raised result_q.put(None) #signal listener that worker is exiting def listener(result_q: Queue, do_quit: Event, n_workers: int): n_completed = 0 while n_workers > 0: res = result_q.get() if res is None: n_workers -= 1 else: n_completed += 1 try: might_fail(res) except: do_quit.set() #let main continue print(n_completed) raise #reraise error after we signal others to stop do_quit.set() #let main continue print(n_completed) if __name__ == "__main__": args_q = Queue() result_q = Queue() do_quit = Event() n_workers = 4 listener_p = Process(target=listener, args=(result_q, do_quit, n_workers)) listener_p.start() for _ in range(n_workers): worker_p = Process(target=worker, args=(args_q, result_q, do_quit)) worker_p.start() for _ in range(1000): args_q.put("some/file.txt") for _ in range(n_workers): args_q.put(None) do_quit.wait() print('done')
Kill all "workers" on "listener" error (multiprocessing, manager and queue set-up)
I'm using multiprocessing to run workers on different files in parallel. Worker's results are put into queue. A listener gets the results from the queue and writes them to the file. Sometimes listener might run into errors (of various origins). In this case, the listener silently dies, but all other processes continue running (rather surprisingly, worker errors causes all processes to terminate). I would like to stop all processes (workers, listener, e.t.c.) when listener catches an error. How this can be done? The scheme of my code is as follows: def worker(file_path, q): ## do something q.put(1.) return True def listener(q): while True: m = q.get() if m == 'kill': break else: try: # do something and write to file except Exception as err: # raise error tb = sys.exc_info()[2] raise err.with_traceback(tb) def main(): manager = mp.Manager() q = manager.Queue(maxsize=3) with mp.Pool(5) as pool: watcher = pool.apply_async(listener, (q,)) files = ['path_1','path_2','path_3'] jobs = [ pool.apply_async(worker, (p,q,)) for p in files ] # fire off workers for job in jobs: job.get() # kill the listener when done q.put('kill') # run if __name__ == "__main__": main() I tried introducing event = manager.Event() and using it as a flag in main(): ## inside the pool, after starting workers while True: if event.is_set(): for job in jobs: job.terminate() No success. Calling os._exit(1) in listener exception block rises broken pipe error, but processes are not killed. I also tried setting daemon = True, for job in jobs: job.daemon = True Did not help. In fact, to handle listener exceptions, I'm using a callable, as required by apply_async (so that they are not entirely silenced). This complicates the situation, but not much. Thank you in advance.
[ "As always there are many ways to accomplish what you're after, but I would probably suggest using an Event to signal that the processes should quit. I also would not use a Pool in this instance, as it only really simplifies things for simple cases where you need something like map. More complicated use cases quickly make it easier to just build you own \"pool\" with the functionality you need.\nfrom multiprocessing import Process, Queue, Event\nfrom random import random\n\n\ndef might_fail(a):\n assert(a > .001)\n\ndef worker(args_q: Queue, result_q: Queue, do_quit: Event):\n try:\n while not do_quit.is_set():\n args = args_q.get()\n if args is None:\n break\n else:\n # do something\n result_q.put(random())\n finally: #signal that worker is exiting even if exception is raised\n result_q.put(None) #signal listener that worker is exiting\n\ndef listener(result_q: Queue, do_quit: Event, n_workers: int):\n n_completed = 0\n while n_workers > 0:\n res = result_q.get()\n if res is None:\n n_workers -= 1\n else:\n n_completed += 1\n try:\n might_fail(res)\n except:\n do_quit.set() #let main continue\n print(n_completed)\n raise #reraise error after we signal others to stop\n do_quit.set() #let main continue\n print(n_completed)\n\nif __name__ == \"__main__\":\n args_q = Queue()\n result_q = Queue()\n do_quit = Event()\n n_workers = 4\n\n listener_p = Process(target=listener, args=(result_q, do_quit, n_workers))\n listener_p.start()\n\n for _ in range(n_workers):\n worker_p = Process(target=worker, args=(args_q, result_q, do_quit))\n worker_p.start()\n\n for _ in range(1000):\n args_q.put(\"some/file.txt\")\n\n for _ in range(n_workers):\n args_q.put(None)\n\n do_quit.wait()\n print('done')\n\n" ]
[ 1 ]
[]
[]
[ "error_handling", "multiprocessing", "python", "python_3.x", "queue" ]
stackoverflow_0074548611_error_handling_multiprocessing_python_python_3.x_queue.txt
Q: How to globally override a pythonPackage in nix I'm trying to override a python package (uvloop) globally, in nix, such that black sees the override. uvloop (python package) tests fail for me because I'm working behind a firewall. I can build things that use uvloop by editing the nixpkgs derivation directly (ugh) to set doCheck = false. I'm trying to encode this in an overlay, but without success - the overlay is read (e.g., syntax errors cause failure), but nothing I do in the overlay actually stop the tests from running. I've tried following tips from https://nixos.wiki/wiki/Overlays, https://nixos.org/manual/nixpkgs/stable/#how-to-override-a-python-package-using-overlays and How to use custom python with existing packages - nix derivation? (overlaying python using packageOverrides; with pythonOverrides; and with and without using overridePythonAttrs); both for python3 and python39; but with no success. E.g., self: super: { python3 = super.python3.override { packageOverrides = pyself: pysuper: { uvloop = pysuper.uvloop.overrideAttrs (_: { doCheck = false; }); }; }; } For bonus points, I'd like to achieve this for all instances of python package uvloop - not just the one in 3.9 - but I'll take any help I can get. Thanks, A: The following worked for me. It applies a patch to twitch-chat-downloader (Python app) and a patch to twitch-python (Python library used by twitch-chat-downloader). nix-env -iA nixpkgs.twitch-chat-downloader installed a patch copy of twitch-chat-downloader which uses a patched copy of twitch-python. { packageOverrides = pkgs: { python3 = pkgs.python3.override { packageOverrides = python-self: python-super: { twitch-python = python-super.twitch-python.overrideAttrs (attrs: { patches = (attrs.patches or []) ++ [ ./twitch-allow-no-token.patch ]; }); }; }; twitch-chat-downloader = pkgs.twitch-chat-downloader.overrideAttrs (attrs: { patches = (attrs.patches or []) ++ [ ./twitch-chat-downloader-no-oauth.patch ]; }); }; } A: Ran into the same issue with the same package. I wasn't able to source an answer from the Nix docs, but I think this is what's happening, and why your example doesn't work. python3 is just an alias of python39, in the same way that python3Packages is an alias of python39Packages (see this doc page.) When overriding python3, you're overriding the value of python39, but the result is then stored back in the python3 variable instead of the alias - so other Nix code which goes directly through python39 instead of the python3 alias still sees the non-overridden package set. A working way The way that worked for me was to override the value of python39 specifically, and leave python3 as an alias pointing to the new overridden package set: self: super: { python39 = super.python39.override { packageOverrides = pyself: pysuper: { uvloop = pysuper.uvloop.overrideAttrs (_: { doCheck = false; }); }; }; }
How to globally override a pythonPackage in nix
I'm trying to override a python package (uvloop) globally, in nix, such that black sees the override. uvloop (python package) tests fail for me because I'm working behind a firewall. I can build things that use uvloop by editing the nixpkgs derivation directly (ugh) to set doCheck = false. I'm trying to encode this in an overlay, but without success - the overlay is read (e.g., syntax errors cause failure), but nothing I do in the overlay actually stop the tests from running. I've tried following tips from https://nixos.wiki/wiki/Overlays, https://nixos.org/manual/nixpkgs/stable/#how-to-override-a-python-package-using-overlays and How to use custom python with existing packages - nix derivation? (overlaying python using packageOverrides; with pythonOverrides; and with and without using overridePythonAttrs); both for python3 and python39; but with no success. E.g., self: super: { python3 = super.python3.override { packageOverrides = pyself: pysuper: { uvloop = pysuper.uvloop.overrideAttrs (_: { doCheck = false; }); }; }; } For bonus points, I'd like to achieve this for all instances of python package uvloop - not just the one in 3.9 - but I'll take any help I can get. Thanks,
[ "The following worked for me. It applies a patch to twitch-chat-downloader (Python app) and a patch to twitch-python (Python library used by twitch-chat-downloader). nix-env -iA nixpkgs.twitch-chat-downloader installed a patch copy of twitch-chat-downloader which uses a patched copy of twitch-python.\n{\n packageOverrides = pkgs: {\n python3 = pkgs.python3.override {\n packageOverrides = python-self: python-super: {\n twitch-python = python-super.twitch-python.overrideAttrs (attrs: {\n patches = (attrs.patches or []) ++ [\n ./twitch-allow-no-token.patch\n ];\n });\n };\n };\n\n twitch-chat-downloader = pkgs.twitch-chat-downloader.overrideAttrs (attrs: {\n patches = (attrs.patches or []) ++ [\n ./twitch-chat-downloader-no-oauth.patch\n ];\n });\n };\n}\n\n", "Ran into the same issue with the same package. I wasn't able to source an answer from the Nix docs, but I think this is what's happening, and why your example doesn't work.\npython3 is just an alias of python39, in the same way that python3Packages is an alias of python39Packages (see this doc page.) When overriding python3, you're overriding the value of python39, but the result is then stored back in the python3 variable instead of the alias - so other Nix code which goes directly through python39 instead of the python3 alias still sees the non-overridden package set.\nA working way\nThe way that worked for me was to override the value of python39 specifically, and leave python3 as an alias pointing to the new overridden package set:\nself: super: {\n python39 = super.python39.override {\n packageOverrides = pyself: pysuper: {\n uvloop = pysuper.uvloop.overrideAttrs (_: {\n doCheck = false;\n });\n };\n };\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "nix", "python" ]
stackoverflow_0070395839_nix_python.txt
Q: Can someone help me with this simple calculator program in python? I am having problem in finding error Program got a Syntax error as follow: elif choice == "3": ^^^^ SyntaxError: invalid syntax print("1 Addition\n2 Subtraction\n3 Multiplication\n4 Division ") choice= input ("WHat is you choice? : ") num1 = float (input("Please enter a number: ")) num2 = float( input("please enter another number: ")) if choice == "1": print(Num1,"+", Num2, "=", (Num1 + Num2)) elif choice == "2": print(Num1,"-", Num2, "=", (Num1 - Num2)) elif choice == "3": print(Num1,"x", Num2, "=", (Num1 * Num2)) elif choice == "4": if Num2 == 0.0 print("0 error LOL") else: print(Num1, "/", Num2, "=", (Num1 / Num2) ) else: print("your choice is bad...") A: Variable names are case sensitive ("num1" cannot be referenced as "Num1") Indentation on elif should be inline with the original "if" Missing colon on if statement on line 13. Here is an altered version that worked for me: print("1 Addition\n2 Subtraction\n3 Multiplication\n4 Division ") choice= input ("WHat is you choice? : ") num1 = float (input("Please enter a number: ")) num2 = float( input("please enter another number: ")) if choice == "1": print(num1,"+", num2, "=", (num1 + num2)) elif choice == "2": print(num1,"-", num2, "=", (num1 - num2)) elif choice == "3": print(num1,"x", num2, "=", (num1 * num2)) elif choice == "4": if num2 == 0.0: print("0 error LOL") else: print(num1, "/", num2, "=", (num1 / num2) ) else: print("your choice is bad...")
Can someone help me with this simple calculator program in python? I am having problem in finding error
Program got a Syntax error as follow: elif choice == "3": ^^^^ SyntaxError: invalid syntax print("1 Addition\n2 Subtraction\n3 Multiplication\n4 Division ") choice= input ("WHat is you choice? : ") num1 = float (input("Please enter a number: ")) num2 = float( input("please enter another number: ")) if choice == "1": print(Num1,"+", Num2, "=", (Num1 + Num2)) elif choice == "2": print(Num1,"-", Num2, "=", (Num1 - Num2)) elif choice == "3": print(Num1,"x", Num2, "=", (Num1 * Num2)) elif choice == "4": if Num2 == 0.0 print("0 error LOL") else: print(Num1, "/", Num2, "=", (Num1 / Num2) ) else: print("your choice is bad...")
[ "Variable names are case sensitive (\"num1\" cannot be referenced as \"Num1\")\nIndentation on elif should be inline with the original \"if\"\nMissing colon on if statement on line 13.\nHere is an altered version that worked for me:\nprint(\"1 Addition\\n2 Subtraction\\n3 Multiplication\\n4 Division \")\nchoice= input (\"WHat is you choice? : \")\nnum1 = float (input(\"Please enter a number: \"))\nnum2 = float( input(\"please enter another number: \"))\n\nif choice == \"1\":\n print(num1,\"+\", num2, \"=\", (num1 + num2))\nelif choice == \"2\":\n print(num1,\"-\", num2, \"=\", (num1 - num2))\nelif choice == \"3\":\n print(num1,\"x\", num2, \"=\", (num1 * num2))\nelif choice == \"4\":\n if num2 == 0.0:\n print(\"0 error LOL\")\n else:\n print(num1, \"/\", num2, \"=\", (num1 / num2) )\nelse:\n print(\"your choice is bad...\")\n\n" ]
[ -1 ]
[ "You need to unindent the elif statements like:\nprint(\"1 Addition\\n2 Subtraction\\n3 Multiplication\\n4 Division \")\nchoice= input(\"What is you choice? : \")\nnum1 = float(input(\"Please enter a number: \"))\nnum2 = float(input(\"please enter another number: \"))\n\nif choice == \"1\":\n print(f\"{Num1}+{Num2}={Num1 + Num2}\")\nelif choice == \"2\":\n print(f\"{Num1}-{Num2}={Num1 - Num2}\")\nelif choice == \"3\":\n print(f\"{Num1}*{Num2}={Num1 * Num2}\")\nelif choice == \"4\":\n if Num2 == 0.0\n print(\"0 error LOL\")\n else:\n print(f\"{Num1}/{Num2}={Num1 / Num2}\")\nelse:\n print(\"your choice is bad...\")\n\nI changed your code slightly and used f-strings to make it slightly neater (in my opinion)\n" ]
[ -2 ]
[ "python", "syntax_error" ]
stackoverflow_0074549960_python_syntax_error.txt
Q: When to utilize pandas .filter() over other subsetting methods? I've been studying the different ways to filter and subset pandas DataFrames and came across the pandas.DataFrame.filter() method. However, I can't figure out why one would use this over another method of filtering (loc, iloc, logical operators, str.contains(), .query(), etc). Can anyone provide an example of when it makes sense to use .filter() over the alternatives? A: filter is applied to index or column labels, not the values. In contrast to query, contains etc. which are used to filter a DataFrame based on its contents. If you for example would like to only keep columns ending with 'address', you could use df.filter(regex='address$') A: Each function is used in particular circumstances. Filter() is useful for getting a large data down to a smaller size, based on the questions you want to ask. Query(), on the other hand, is useful for phrasing questions that use comparison operators (less than, equal to, greater than, etc.) The Pandas Query() method is a fantastic way to filter and query data. Unlike other Pandas methods, it uses a string argument that functions rather similar to SQL syntax. You should only use Query() when your question (query) can be posed as greater than, less than, equal to, or not equal to (or some combination of these). Use filter() when you want to get a quick sense of your dataset or, as we shall see, create a new dataframe based on the columns you want. It is particularly useful if your dataset has many columns. You can also use it to reorder your columns in a more desired way. for more read [http://pandas.pythonhumanities.com][1] [1]: http://pandas.pythonhumanities.com/03_02_advanced_querying.html#:~:text=Filter()%20is%20useful%20for,greater%20than%2C%20etc.).
When to utilize pandas .filter() over other subsetting methods?
I've been studying the different ways to filter and subset pandas DataFrames and came across the pandas.DataFrame.filter() method. However, I can't figure out why one would use this over another method of filtering (loc, iloc, logical operators, str.contains(), .query(), etc). Can anyone provide an example of when it makes sense to use .filter() over the alternatives?
[ "filter is applied to index or column labels, not the values.\nIn contrast to query, contains etc. which are used to filter a DataFrame based on its contents.\nIf you for example would like to only keep columns ending with 'address', you could use df.filter(regex='address$')\n", "\nEach function is used in particular circumstances. Filter() is useful for getting a large data down to a smaller size, based on the questions you want to ask. Query(), on the other hand, is useful for phrasing questions that use comparison operators (less than, equal to, greater than, etc.)\n\nThe Pandas Query() method is a fantastic way to filter and query data. Unlike other Pandas methods, it uses a string argument that functions rather similar to SQL syntax.\n\nYou should only use Query() when your question (query) can be posed as greater than, less than, equal to, or not equal to (or some combination of these).\n\nUse filter() when you want to get a quick sense of your dataset or, as we shall see, create a new dataframe based on the columns you want. It is particularly useful if your dataset has many columns. You can also use it to reorder your columns in a more desired way.\n\n\nfor more read [http://pandas.pythonhumanities.com][1]\n[1]: http://pandas.pythonhumanities.com/03_02_advanced_querying.html#:~:text=Filter()%20is%20useful%20for,greater%20than%2C%20etc.).\n" ]
[ 0, 0 ]
[]
[]
[ "dataframe", "filter", "pandas", "python" ]
stackoverflow_0069182663_dataframe_filter_pandas_python.txt
Q: Pygame not importing, tried all techniques I have read some of the Stack Overflow posts here about pygame not importing. I have tried moving pygame in the scripts folder of Python, making sure it is the right type, and installing it using anaconda prompt. Do you know why none of these are working? By the way, here's my code and error. I have Windows 10, 64 bit computer, and Python 2.7. import sys, os, random, pygame ImportError: No module named pygame A: make sure you installed the library in same python version where you are coding. if you don't know how to do that type this in python code and run it import pip pip.main(["install","pygame"]) if it does not work too you should probably upgrade python to 3.10
Pygame not importing, tried all techniques
I have read some of the Stack Overflow posts here about pygame not importing. I have tried moving pygame in the scripts folder of Python, making sure it is the right type, and installing it using anaconda prompt. Do you know why none of these are working? By the way, here's my code and error. I have Windows 10, 64 bit computer, and Python 2.7. import sys, os, random, pygame ImportError: No module named pygame
[ "make sure you installed the library in same python version where you are coding. if you don't know how to do that type this in python code and run it\nimport pip\npip.main([\"install\",\"pygame\"])\n\nif it does not work too you should probably upgrade python to 3.10\n" ]
[ 0 ]
[ "some users arent run pygame command.after showing requirement message.if you download pygame copy that 2 folder named as\"pygame\"and\"pygame-1.9.4.dist-info\"socopy this folder to your\"C:\\Program Files (x86)\\Python37-32\\Lib\" seriously after that u r DONE!!!!!!!!\n" ]
[ -2 ]
[ "import", "pygame", "python", "python_2.7", "python_import" ]
stackoverflow_0045224990_import_pygame_python_python_2.7_python_import.txt
Q: pyqt5: This application failed to start because no Qt platform plugin could be initialized - installation problem? I am working on Ubuntu 18.04 (as a Windows 10 subsystem for linux). When I try running code that uses pyqt5 it throws the error: " qt.qta.xcb: could not connect to display qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found. This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem. Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, xcb. Aborted " as in the image image of error message (the error is definitely connected to pyqt5). I have found many posts that suggest to: Go to => Python38>lib>site-packages>PyQt5>Qt>plugins In plugins copy platforms folder After that go to Python38>lib>site-packages>PyQt5_tools>Qt>bin paste folder here. Do copy and replace. but it seems like there is no Qt folder in pyqt5_tools on my computer. I have removed and installed back pyqt5, pyqt5-tools, pyqt5-plugins several times but it does not work. Can it be connected to the fact that I am using a subsystem? (I have downloaded pyqt5 both on Windows and on Ubuntu). Any suggestions to solve this problem? A: Someone suggested to run "xhost +local:" first. A: The error relates to a missing requirement for one or multiple XCB-related libraries, which needs to be fulfilled on X11 for Qt to function properly. For a full list of XCB libraries check here. I would suggest that, instead of copying files left and right, you first try reinstalling PyQt5 via pip. I've had a similar experience with conda, where PySided2 was not working due to a missing shiboken, which I had to install via pip. In addition you may want to try conda (e.g. Anaconda or Miniconda). Last but not least, if this is the only problem you have, you may attempt to install the required XCB libraries. This is however tricky, since the version your distro provides may be different from the rest that the pip installation has. A safe way for installing PyQt5 is simply using the package manager of your distro inside WSL. Since it's a virtualized system I'd assume that it's created solely for the purpose of working on a PyQt5 project and after that it will be deleted. Tainting the clean initial setup should therefor not be an issue. A: This error shows because you install PyQt on the base environment, so remove anaconda and reinstall it again then try to create a new environment and work in it. A: In my specific case the issue is caused by the WSL, that has no access to the graphic part of the computer. I performed a dual boot on my computer in order to proceed, because I could not find a way to solve the issue. A: I had the same issue, Ubuntu 18 on WSL as well. I solved following @rbaleksandar's suggestion. conda install -c anaconda pyqt
pyqt5: This application failed to start because no Qt platform plugin could be initialized - installation problem?
I am working on Ubuntu 18.04 (as a Windows 10 subsystem for linux). When I try running code that uses pyqt5 it throws the error: " qt.qta.xcb: could not connect to display qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found. This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem. Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, xcb. Aborted " as in the image image of error message (the error is definitely connected to pyqt5). I have found many posts that suggest to: Go to => Python38>lib>site-packages>PyQt5>Qt>plugins In plugins copy platforms folder After that go to Python38>lib>site-packages>PyQt5_tools>Qt>bin paste folder here. Do copy and replace. but it seems like there is no Qt folder in pyqt5_tools on my computer. I have removed and installed back pyqt5, pyqt5-tools, pyqt5-plugins several times but it does not work. Can it be connected to the fact that I am using a subsystem? (I have downloaded pyqt5 both on Windows and on Ubuntu). Any suggestions to solve this problem?
[ "Someone suggested to run \"xhost +local:\" first.\n", "The error relates to a missing requirement for one or multiple XCB-related libraries, which needs to be fulfilled on X11 for Qt to function properly. For a full list of XCB libraries check here.\nI would suggest that, instead of copying files left and right, you first try reinstalling PyQt5 via pip. I've had a similar experience with conda, where PySided2 was not working due to a missing shiboken, which I had to install via pip.\nIn addition you may want to try conda (e.g. Anaconda or Miniconda). Last but not least, if this is the only problem you have, you may attempt to install the required XCB libraries. This is however tricky, since the version your distro provides may be different from the rest that the pip installation has.\nA safe way for installing PyQt5 is simply using the package manager of your distro inside WSL. Since it's a virtualized system I'd assume that it's created solely for the purpose of working on a PyQt5 project and after that it will be deleted. Tainting the clean initial setup should therefor not be an issue.\n", "This error shows because you install PyQt on the base environment, so remove anaconda and reinstall it again then try to create a new environment and work in it.\n", "In my specific case the issue is caused by the WSL, that has no access to the graphic part of the computer. I performed a dual boot on my computer in order to proceed, because I could not find a way to solve the issue.\n", "I had the same issue, Ubuntu 18 on WSL as well.\nI solved following @rbaleksandar's suggestion.\nconda install -c anaconda pyqt\n\n" ]
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "pyqt", "pyqt5", "python", "qt", "user_interface" ]
stackoverflow_0072378976_pyqt_pyqt5_python_qt_user_interface.txt
Q: Using the same hotkey for two different purposes in Python Using pythons keyboard library, I have two function definitions: def start_tracking(): *code to start tracking time* def end_tracking(): *code to stop tracking time* I then want to use the same hotkey (e.g. F1) to invoke function 1 (start tracking time) on the first press and then function 2 (end tracking time) on the subsequent press. If I press the hotkey again after that, it should repeat the process. Basically I want to use the same hotkey to track time and stop tracking time. Here's what a working solution to start tracking time and stop tracking time using two different hotkeys looks like: keyboard.add_hotkey("F1", start_tracking) keyboard.add_hotkey("F2", end_tracking) How can I accomplish the same thing with only one key (F1)? I don't want to use a while loop because it slows down performance quite a bit. A: Consider using a class variable or global variable as a flag. Such that: class tracker(): def __init__(self): self.start_flag = True <- Init class variable def tracking(self): if self.start_flag: start_tracking() self.start_flag = False #<- class variable toggling else: stop_tracking() self.start_flag = True #<- class variable toggling if name == '__main__' x = tracker() x.tracking() # starts tracker time.sleep(5) x.tracking() # stops tracker Without more context on what your program is doing I can't say which is better. Typically globals should be avoided though. Simply put, you need a way to toggle which function is run. PS copypasting wont work. You will need to setup the class etc for proper usage. especially with where and how you defined start/stop. I would guess you are using globals but typically this should be avoided. A: Solution: def started(): start_tracking() keyboard.remove_hotkey("F1") keyboard.add_hotkey("F1", ended) def ended(): end_tracking() keyboard.remove_hotkey("F1") keyboard.add_hotkey("F1", started) #Hotkey keyboard.add_hotkey("F1", started) Basically I switch between the two events every time I press the hotkey by calling two functions in an alternating fashion.
Using the same hotkey for two different purposes in Python
Using pythons keyboard library, I have two function definitions: def start_tracking(): *code to start tracking time* def end_tracking(): *code to stop tracking time* I then want to use the same hotkey (e.g. F1) to invoke function 1 (start tracking time) on the first press and then function 2 (end tracking time) on the subsequent press. If I press the hotkey again after that, it should repeat the process. Basically I want to use the same hotkey to track time and stop tracking time. Here's what a working solution to start tracking time and stop tracking time using two different hotkeys looks like: keyboard.add_hotkey("F1", start_tracking) keyboard.add_hotkey("F2", end_tracking) How can I accomplish the same thing with only one key (F1)? I don't want to use a while loop because it slows down performance quite a bit.
[ "Consider using a class variable or global variable as a flag. Such that:\nclass tracker():\n\n def __init__(self):\n self.start_flag = True <- Init class variable\n\n def tracking(self):\n\n if self.start_flag:\n start_tracking()\n self.start_flag = False #<- class variable toggling\n else:\n stop_tracking()\n self.start_flag = True #<- class variable toggling\n\n\nif name == '__main__'\n x = tracker()\n x.tracking() # starts tracker \n time.sleep(5)\n x.tracking() # stops tracker \n\nWithout more context on what your program is doing I can't say which is better. Typically globals should be avoided though. Simply put, you need a way to toggle which function is run. PS copypasting wont work. You will need to setup the class etc for proper usage. especially with where and how you defined start/stop. I would guess you are using globals but typically this should be avoided.\n", "Solution:\ndef started():\n start_tracking()\n keyboard.remove_hotkey(\"F1\")\n keyboard.add_hotkey(\"F1\", ended)\n\ndef ended():\n end_tracking()\n keyboard.remove_hotkey(\"F1\")\n keyboard.add_hotkey(\"F1\", started)\n\n#Hotkey\n\nkeyboard.add_hotkey(\"F1\", started)\n\nBasically I switch between the two events every time I press the hotkey by calling two functions in an alternating fashion.\n" ]
[ 0, 0 ]
[]
[]
[ "keyboard", "python" ]
stackoverflow_0074549843_keyboard_python.txt
Q: The program should display ‘Out of range’ if credits entered are not in the range 0, 20, 40, 60, 80, 100 and 120 To try to solve the question above I tried by creating a list with the range and then a list with the variables in it. Then to check if the variables are in the list i used an if loop however it is not working and only printing out "out of range...". I have also tried a while loop and it would just repeat the total 7 times. I do not know how to fix it and would please like an answer. Thank you def main(): a = [0, 20, 40, 60, 80, 100, 120] try: userPass = int(input("Enter pass credits: ")) userDefer = int(input("Enter defer credits: ")) userFail = int(input("Enter fail credits: ")) except: print("Invalid number.") total = userFail + userPass + userDefer aValues = [ userPass, userFail, userDefer ] if aValues in a: print(total) else: print("Out of range. Try again") if total > 120: print("Total incorrect") repeat() else: if userPass >= 120: print("This student has progressed.") repeat() elif userPass >= 100 and total == 120: print("This student is trailing.") repeat() elif userFail <= 60 and total == 120: print("This student did not progress(module retreiver).") repeat() elif userPass <= userFail: print("This students program outcome is exclude.") repeat() else: print("incorrect. Try again.") repeat() def repeat(): choice = int(input("If you would like to quit type 1 or test another student write 2: ")) if choice != 1 and choice != 2: repeat() else: while choice == 2: main() while choice == 1: break print("Thank you.") main() A: Testing whether one set of numbers is in another is a set operation. So use set and subtract all of the valid values from your input. If any values remain, they are not valid. a = set([0, 20, 40, 60, 80, 100, 120]) if set([userPass, userFail, userDefer]) - a: print("Out of range. Try again") Interestingly, you can also use a range object. It is built to check for containment efficiently a = range(0, 121, 20) if any(val in a, for val not in (userPass, userFail, userDefer)): print("Out of range. Try again") A: You need to change the first if. if aValues[0] in a and aValues[1] in a and aValues[2] in a : print(total) if you need to put more values you can do this: total=0 for i in range(len(aValues)): if(aValues[i] in a): total=total+ aValues[i] else: print('Incorrect Value') print(total)
The program should display ‘Out of range’ if credits entered are not in the range 0, 20, 40, 60, 80, 100 and 120
To try to solve the question above I tried by creating a list with the range and then a list with the variables in it. Then to check if the variables are in the list i used an if loop however it is not working and only printing out "out of range...". I have also tried a while loop and it would just repeat the total 7 times. I do not know how to fix it and would please like an answer. Thank you def main(): a = [0, 20, 40, 60, 80, 100, 120] try: userPass = int(input("Enter pass credits: ")) userDefer = int(input("Enter defer credits: ")) userFail = int(input("Enter fail credits: ")) except: print("Invalid number.") total = userFail + userPass + userDefer aValues = [ userPass, userFail, userDefer ] if aValues in a: print(total) else: print("Out of range. Try again") if total > 120: print("Total incorrect") repeat() else: if userPass >= 120: print("This student has progressed.") repeat() elif userPass >= 100 and total == 120: print("This student is trailing.") repeat() elif userFail <= 60 and total == 120: print("This student did not progress(module retreiver).") repeat() elif userPass <= userFail: print("This students program outcome is exclude.") repeat() else: print("incorrect. Try again.") repeat() def repeat(): choice = int(input("If you would like to quit type 1 or test another student write 2: ")) if choice != 1 and choice != 2: repeat() else: while choice == 2: main() while choice == 1: break print("Thank you.") main()
[ "Testing whether one set of numbers is in another is a set operation. So use set and subtract all of the valid values from your input. If any values remain, they are not valid.\na = set([0, 20, 40, 60, 80, 100, 120])\nif set([userPass, userFail, userDefer]) - a:\n print(\"Out of range. Try again\")\n \n\nInterestingly, you can also use a range object. It is built to check for containment efficiently\na = range(0, 121, 20)\nif any(val in a, for val not in (userPass, userFail, userDefer)):\n print(\"Out of range. Try again\")\n\n", "You need to change the first if.\nif aValues[0] in a and aValues[1] in a and aValues[2] in a :\n print(total)\n\nif you need to put more values you can do this:\ntotal=0\nfor i in range(len(aValues)):\n if(aValues[i] in a):\n total=total+ aValues[i]\n else:\n print('Incorrect Value')\nprint(total)\n\n" ]
[ 0, 0 ]
[]
[]
[ "for_loop", "loops", "python" ]
stackoverflow_0074550104_for_loop_loops_python.txt
Q: How to solve TypeError: 'int' object is not iterable in Python while calculating sum of two numbers? I am trying to take two values as parameters and return True if its value is equal to 10 and false if it isn't. The values are strictly int. Here is the code class Solution: def twomakes10(self, no1, no2): if sum(no1, no2) == 10: return True else: return False if __name__ == "__main__": p = Solution() n1 = 9 n2 = 1 print(p.twomakes10(n1, n2)) A: sum function, gets an iterable value as input, you can try: sum([no1,no2]) A: sum is expecting iterable .. so make it happy. See below class Solution: def twomakes10(self, no1, no2): return sum([no1, no2]) if __name__ == "__main__": p = Solution() n1 = 9 n2 = 1 print(p.twomakes10(n1, n2))
How to solve TypeError: 'int' object is not iterable in Python while calculating sum of two numbers?
I am trying to take two values as parameters and return True if its value is equal to 10 and false if it isn't. The values are strictly int. Here is the code class Solution: def twomakes10(self, no1, no2): if sum(no1, no2) == 10: return True else: return False if __name__ == "__main__": p = Solution() n1 = 9 n2 = 1 print(p.twomakes10(n1, n2))
[ "sum function, gets an iterable value as input, you can try:\nsum([no1,no2])\n\n", "sum is expecting iterable .. so make it happy. See below\nclass Solution:\n\n def twomakes10(self, no1, no2):\n return sum([no1, no2])\n\n\nif __name__ == \"__main__\":\n p = Solution()\n n1 = 9\n n2 = 1\n print(p.twomakes10(n1, n2))\n\n" ]
[ 1, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074550268_list_python_tuples.txt
Q: Add comma between text I have a list of addresses in a text document and I want to add a comma after address line 1, and then save it all to a new text document. example my list of addresses are Address 1404 756 48 Stockholm Address 9 756 52 Stockholm Address 53 B lgh 1001 619 34 Stockholm Address 72 B lgh 1101 619 30 Stockholm Address 52 A 619 33 Stockholm What I want the output to be Address 1404, 756 48 Stockholm Address 9, 756 52 Stockholm Address 53 B lgh 1001, 619 34 Stockholm Address 72 B lgh 1101, 619 30 Stockholm Address 52 A, 619 33 Stockholm I can't figure out how to accurately place the comma at the right place (before the zip code) since the amount of whitespace isn't the same for all addresses. The zip code consists of 5 digits for instance (756 48). A: With regexp import re re.sub(r'\s(\d{3}\s\d{2}\s.*)$', ', \\1', 'Address 53 B lgh 1001 619 34 Stockholm') # 'Address 53 B lgh 1001, 619 34\xa0Stockholm' (the \xa0 is part of your strings. It will print as a space) A: You can use str.rstrip() to separate city and index from the first line: file_line = 'Address 72 B lgh 1101 619 30 Stockholm' # Use maxsplit=3 first_line, *second_line = address.rsplit(' ', 3) new_address = f'{first_line}, {' '.join(second_line)}' A: s='''Address 1404 756 48 Stockholm Address 9 756 52 Stockholm Address 53 B lgh 1001 619 34 Stockholm Address 72 B lgh 1101 619 30 Stockholm Address 52 A 619 33 Stockholm''' lis=s.split('\n') lis1=[i.split(' ') for i in lis] for i in lis1: for j in i: if i.index(j) == 1: lis1[lis1.index(i)][i.index(j)] = j +',' lis1=[' '.join(i) for i in lis1] lis1='\n'.join(lis1) print(lis1) A: If your postal code and city are limited to the format shown here (three digits, space, two digits, space, one word), then you can do this with a regular expression. It just needs to look for the postal code and city pattern, and capture both it and whatever comes before it, adding a comma in between: >>> import re >>> address_list = ['Address 1404 756 48 Stockholm', 'Address 9 756 52 Stockholm', 'Address 53 B lgh 1001 619 34 Stockholm', 'Address 72 B lgh 1101 619 30 Stockholm', 'Address 52 A 619 33 Stockholm'] # Define regex pattern as space+3digits+space+2digits+word. # Parens capture both that pattern and everything before it (.*) >>> p = re.compile(r"(.*)( \d{3} \d{2} \w+)") # Create a new list, replacing each item with group1+comma+group2 >>> new_addresses = [re.sub(p, r"\1,\2", a) for a in address_list] >>> for a in new_addresses: print(a) 'Address 1404, 756 48 Stockholm' 'Address 9, 756 52 Stockholm' 'Address 53 B lgh 1001, 619 34 Stockholm' 'Address 72 B lgh 1101, 619 30 Stockholm' 'Address 52 A, 619 33 Stockholm' If the patterns can be different than the examples you gave here (if a city can have two words, etc.) then you can still do this, you would just need to tweak the regex to match those patterns too. A: Try this: with open('sample.txt') as file: df = file.read() for line in df.split('\n'): split_line = line.split() split_line.insert(-3, ',') new_line = " ".join(elem for elem in split_line).strip() print(new_line) Output: Address 1404 , 756 48 Stockholm Address 9 , 756 52 Stockholm Address 53 B lgh 1001 , 619 34 Stockholm Address 72 B lgh 1101 , 619 30 Stockholm Address 52 A , 619 33 Stockholm The extra space before the commas can be adressed with a strip() further down.
Add comma between text
I have a list of addresses in a text document and I want to add a comma after address line 1, and then save it all to a new text document. example my list of addresses are Address 1404 756 48 Stockholm Address 9 756 52 Stockholm Address 53 B lgh 1001 619 34 Stockholm Address 72 B lgh 1101 619 30 Stockholm Address 52 A 619 33 Stockholm What I want the output to be Address 1404, 756 48 Stockholm Address 9, 756 52 Stockholm Address 53 B lgh 1001, 619 34 Stockholm Address 72 B lgh 1101, 619 30 Stockholm Address 52 A, 619 33 Stockholm I can't figure out how to accurately place the comma at the right place (before the zip code) since the amount of whitespace isn't the same for all addresses. The zip code consists of 5 digits for instance (756 48).
[ "With regexp\nimport re\nre.sub(r'\\s(\\d{3}\\s\\d{2}\\s.*)$', ', \\\\1', 'Address 53 B lgh 1001 619 34 Stockholm')\n# 'Address 53 B lgh 1001, 619 34\\xa0Stockholm'\n\n(the \\xa0 is part of your strings. It will print as a space)\n", "You can use str.rstrip() to separate city and index from the first line:\nfile_line = 'Address 72 B lgh 1101 619 30 Stockholm'\n\n# Use maxsplit=3\nfirst_line, *second_line = address.rsplit(' ', 3)\n\nnew_address = f'{first_line}, {' '.join(second_line)}'\n\n", "s='''Address 1404 756 48 Stockholm\nAddress 9 756 52 Stockholm\nAddress 53 B lgh 1001 619 34 Stockholm\nAddress 72 B lgh 1101 619 30 Stockholm\nAddress 52 A 619 33 Stockholm'''\nlis=s.split('\\n')\nlis1=[i.split(' ') for i in lis]\nfor i in lis1:\n for j in i:\n if i.index(j) == 1:\n lis1[lis1.index(i)][i.index(j)] = j +','\n\nlis1=[' '.join(i) for i in lis1]\nlis1='\\n'.join(lis1)\nprint(lis1)\n\n", "If your postal code and city are limited to the format shown here (three digits, space, two digits, space, one word), then you can do this with a regular expression. It just needs to look for the postal code and city pattern, and capture both it and whatever comes before it, adding a comma in between:\n>>> import re\n>>> address_list = ['Address 1404 756 48 Stockholm', 'Address 9 756 52 Stockholm', \n'Address 53 B lgh 1001 619 34 Stockholm', 'Address 72 B lgh 1101 619 30 Stockholm', \n'Address 52 A 619 33 Stockholm']\n\n# Define regex pattern as space+3digits+space+2digits+word.\n# Parens capture both that pattern and everything before it (.*)\n>>> p = re.compile(r\"(.*)( \\d{3} \\d{2} \\w+)\")\n\n# Create a new list, replacing each item with group1+comma+group2\n>>> new_addresses = [re.sub(p, r\"\\1,\\2\", a) for a in address_list]\n\n>>> for a in new_addresses: print(a) \n\n'Address 1404, 756 48 Stockholm'\n'Address 9, 756 52 Stockholm'\n'Address 53 B lgh 1001, 619 34 Stockholm'\n'Address 72 B lgh 1101, 619 30 Stockholm'\n'Address 52 A, 619 33 Stockholm'\n\nIf the patterns can be different than the examples you gave here (if a city can have two words, etc.) then you can still do this, you would just need to tweak the regex to match those patterns too.\n", "Try this:\nwith open('sample.txt') as file:\n df = file.read()\n for line in df.split('\\n'):\n split_line = line.split()\n split_line.insert(-3, ',')\n new_line = \" \".join(elem for elem in split_line).strip()\n print(new_line)\n\nOutput:\nAddress 1404 , 756 48 Stockholm\nAddress 9 , 756 52 Stockholm\nAddress 53 B lgh 1001 , 619 34 Stockholm\nAddress 72 B lgh 1101 , 619 30 Stockholm\nAddress 52 A , 619 33 Stockholm\n\nThe extra space before the commas can be adressed with a strip() further down.\n" ]
[ 2, 0, 0, 0, -1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074548921_python_python_3.x.txt
Q: How to check if key exists inside JSON file, if the key is inside an Array in JSON (ROBOT FRAMEWORK) So I am facing this problem, where I need to check if the key exists in my JSON file, and continue my actions based on that. So I am doing Add Item To JSON [Documentation] This keyword is designed to add an Item to JSON file [Arguments] ${json_file} ${item_ref} ${item_details} Create Dictionary something=${some_string} #Adding all my details here ${item_list} Create List ${item_details} #Check if there are any items already added to Add item To JSON ${is_item_key_exist} Run Keyword And Return Status Dictionary Should Contain Key ${json_file} Items # If Items key does not exists, then add the item to JSON IF ${is_item_key_exist} ${json_file}= Add Object To Json ${json_file} $..Items ${item_details} #Otherwise create Items key and add details into it ELSE ${items} Create Dictionary Items=${item_list} ${json_file}= Add Object To Json ${json_file} $.value.containers[0] ${items} END [Return] ${json_file} And this is what my json looks like "containers": [ { "Items": [ { "emptyFullIndicatorCode": "1/1", "emptyWeight": "0", "goods": "goods", "goodsWeight": "1", "numberOfPackages": "1", "packagingTypeCode": "PK", "packagingTypeName": "Colis (\"package\")", "reference": "YYYY1234567", "typeCode": "18R0" } ] } So in this scenario, when There is actual Key Items inside the JSON, my code returns false on the check if the key is actually there. I assume it's because the key Items is inside an array that is inside another key Containers, but I could not find a solution how to pinpoint to it. Tried accessing it via different keywords form Collections.py library but I never get it right. If I try to do same scenario with checking the Containers key - it works fine. A: @The Leviathan, I am not so familiar with robotframework but consider the following python recursion: def check_keys(search_key,data): return_value = False for key,value in data.items(): if search_key == key: return_value = True else: dict_test = check_list(search_key,value) #<-recursion if dict_test: return_value = True else: pass return return_value def check_list(search_key,x): #Checks that the 'value' is not a list containing a dict. return_value = False if isinstance(x,list): for item in x: if isinstance(item,dict): return_value = check_keys(search_key,item) return return_value Basically checks each value if there is another layer of dict inside. x = {"containers": [ { "Items": [ { "emptyFullIndicatorCode": "1/1", "emptyWeight": "0", "goods": "goods", "goodsWeight": "1", "numberOfPackages": "1", "packagingTypeCode": "PK", "packagingTypeName": "Colis (\"package\")", "reference": "YYYY1234567", "typeCode": "18R0" } ] }]} check_keys('containers',x) -> True check_keys('Items',x)->True check_keys('goodsWeight',x)->True check_keys('magic',x) -> False Not sure how to implement in robotframework but this is a recursive solution that does not modify the JSON, and probably not optimal as well.
How to check if key exists inside JSON file, if the key is inside an Array in JSON (ROBOT FRAMEWORK)
So I am facing this problem, where I need to check if the key exists in my JSON file, and continue my actions based on that. So I am doing Add Item To JSON [Documentation] This keyword is designed to add an Item to JSON file [Arguments] ${json_file} ${item_ref} ${item_details} Create Dictionary something=${some_string} #Adding all my details here ${item_list} Create List ${item_details} #Check if there are any items already added to Add item To JSON ${is_item_key_exist} Run Keyword And Return Status Dictionary Should Contain Key ${json_file} Items # If Items key does not exists, then add the item to JSON IF ${is_item_key_exist} ${json_file}= Add Object To Json ${json_file} $..Items ${item_details} #Otherwise create Items key and add details into it ELSE ${items} Create Dictionary Items=${item_list} ${json_file}= Add Object To Json ${json_file} $.value.containers[0] ${items} END [Return] ${json_file} And this is what my json looks like "containers": [ { "Items": [ { "emptyFullIndicatorCode": "1/1", "emptyWeight": "0", "goods": "goods", "goodsWeight": "1", "numberOfPackages": "1", "packagingTypeCode": "PK", "packagingTypeName": "Colis (\"package\")", "reference": "YYYY1234567", "typeCode": "18R0" } ] } So in this scenario, when There is actual Key Items inside the JSON, my code returns false on the check if the key is actually there. I assume it's because the key Items is inside an array that is inside another key Containers, but I could not find a solution how to pinpoint to it. Tried accessing it via different keywords form Collections.py library but I never get it right. If I try to do same scenario with checking the Containers key - it works fine.
[ "@The Leviathan, I am not so familiar with robotframework but consider the following python recursion:\ndef check_keys(search_key,data):\n return_value = False\n for key,value in data.items():\n if search_key == key:\n return_value = True\n else: \n dict_test = check_list(search_key,value) #<-recursion\n if dict_test:\n return_value = True\n else:\n pass\n return return_value\n \n\ndef check_list(search_key,x): #Checks that the 'value' is not a list containing a dict.\n return_value = False\n if isinstance(x,list):\n for item in x:\n if isinstance(item,dict):\n return_value = check_keys(search_key,item)\n return return_value\n\nBasically checks each value if there is another layer of dict inside.\nx = {\"containers\": [\n { \"Items\": [\n {\n \"emptyFullIndicatorCode\": \"1/1\",\n \"emptyWeight\": \"0\",\n \"goods\": \"goods\",\n \"goodsWeight\": \"1\",\n \"numberOfPackages\": \"1\",\n \"packagingTypeCode\": \"PK\",\n \"packagingTypeName\": \"Colis (\\\"package\\\")\",\n \"reference\": \"YYYY1234567\",\n \"typeCode\": \"18R0\"\n }\n ]\n }]}\n\ncheck_keys('containers',x) -> True\ncheck_keys('Items',x)->True\ncheck_keys('goodsWeight',x)->True\ncheck_keys('magic',x) -> False\n\nNot sure how to implement in robotframework but this is a recursive solution that does not modify the JSON, and probably not optimal as well.\n" ]
[ 0 ]
[]
[]
[ "arrays", "collections", "json", "python", "robotframework" ]
stackoverflow_0074478356_arrays_collections_json_python_robotframework.txt
Q: Creating nested list with different shapes with numpy I want to create a list of lists of random numbers, h[i,j,k], with axes of different lenghts. For that I have tried import numpy as np import random as rng NBR1 = 2 NBR2 = [2,3,1] list = np.array([np.array([np.array([rng.uniform(-1,1) for k in range(NBR2[i+1])]) for j in range(NBR2[i])]) for i in range(NBR1)]) Without the np.array, I can observe in the Variable Explorer that the list of lists is indeed of the shape I need. With the np.array, not only I cannot dig deep within the list layers (in the Variable Explorer) but I also get the warning: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray. In any case, when I try to extract a vector from this list of lists it comes out with the wrong shape. For instance testtt = list[0][:][0] Should have lenght 2, but it has 3 (I may be just getting this indexing wrong -- but the vector h[0,;;,0] should have length 2). What am I doing wrong? I'm an absolute begginer and appreciate any insigths. Edit: it appears numpy is not ideal for dealing with non-homogeneous lists, I believe that is the core of my problem. Edit2: The list of lists I want to obtain is of the following form: And writing testtt = list[0][:][0] I was hoping to get {h[0,0,0], h[0,1,0]}. A: Is the following what you are looking for (a list of np.arrays)? np.random.seed(0) # for reproducible example --remove when using lst = [np.random.uniform(-1, 1, size) for size in zip(NBR2, NBR2[1:])] >>> lst [array([[ 0.09762701, 0.43037873, 0.20552675], [ 0.08976637, -0.1526904 , 0.29178823]]), array([[-0.12482558], [ 0.783546 ], [ 0.92732552]])]
Creating nested list with different shapes with numpy
I want to create a list of lists of random numbers, h[i,j,k], with axes of different lenghts. For that I have tried import numpy as np import random as rng NBR1 = 2 NBR2 = [2,3,1] list = np.array([np.array([np.array([rng.uniform(-1,1) for k in range(NBR2[i+1])]) for j in range(NBR2[i])]) for i in range(NBR1)]) Without the np.array, I can observe in the Variable Explorer that the list of lists is indeed of the shape I need. With the np.array, not only I cannot dig deep within the list layers (in the Variable Explorer) but I also get the warning: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray. In any case, when I try to extract a vector from this list of lists it comes out with the wrong shape. For instance testtt = list[0][:][0] Should have lenght 2, but it has 3 (I may be just getting this indexing wrong -- but the vector h[0,;;,0] should have length 2). What am I doing wrong? I'm an absolute begginer and appreciate any insigths. Edit: it appears numpy is not ideal for dealing with non-homogeneous lists, I believe that is the core of my problem. Edit2: The list of lists I want to obtain is of the following form: And writing testtt = list[0][:][0] I was hoping to get {h[0,0,0], h[0,1,0]}.
[ "Is the following what you are looking for (a list of np.arrays)?\nnp.random.seed(0) # for reproducible example --remove when using\nlst = [np.random.uniform(-1, 1, size) for size in zip(NBR2, NBR2[1:])]\n\n>>> lst\n[array([[ 0.09762701, 0.43037873, 0.20552675],\n [ 0.08976637, -0.1526904 , 0.29178823]]),\n array([[-0.12482558],\n [ 0.783546 ],\n [ 0.92732552]])]\n\n" ]
[ 0 ]
[]
[]
[ "numpy_ndarray", "numpy_slicing", "python" ]
stackoverflow_0074548489_numpy_ndarray_numpy_slicing_python.txt
Q: Why does my Heroku app say my app is using Postgresql? Since Heroku is removing its free tier, I'm currently in the process of upgrading. However it says that my web app will be turned into an eco dyno, and my postgresql will be switched to "mini". I do not use any database in my app, and am not sure why it shows up. Will Heroku shut down my app if I don't pay an additional $5 a month for the database or can I just pay for the eco dyno? I tried to look at the Heroku knowledge articles and stack overflow but could not find the specific answer I'm looking for. A: You may have a Postgres instance that was automatically provisioned: Before you provision Heroku Postgres, confirm that it isn't already provisioned for your app. Heroku automatically provisions Postgres for apps that include certain libraries, such as the pg Ruby gem. I believe the psycopg2 Python module also triggers automatic provisioning. I suggest you inspect your existing database to see whether it contains any data. You can connect with the database client of your choice via your app's DATABASE_URL environment variable, but the easiest method might be to use Heroku Dataclips: Heroku Dataclips enable you to create SQL queries for your Heroku Postgres databases and share the results with colleagues, third-party tools, and the public. Recipients of a dataclip can view the data in their browser and also download it in JSON and CSV formats. There, you can use the schema explorer and / or run queries against your database. If you confirm that your database is not being used, feel free to destroy it. You are not required to use Heroku Postgres with your app.
Why does my Heroku app say my app is using Postgresql?
Since Heroku is removing its free tier, I'm currently in the process of upgrading. However it says that my web app will be turned into an eco dyno, and my postgresql will be switched to "mini". I do not use any database in my app, and am not sure why it shows up. Will Heroku shut down my app if I don't pay an additional $5 a month for the database or can I just pay for the eco dyno? I tried to look at the Heroku knowledge articles and stack overflow but could not find the specific answer I'm looking for.
[ "You may have a Postgres instance that was automatically provisioned:\n\nBefore you provision Heroku Postgres, confirm that it isn't already provisioned for your app. Heroku automatically provisions Postgres for apps that include certain libraries, such as the pg Ruby gem.\n\nI believe the psycopg2 Python module also triggers automatic provisioning.\nI suggest you inspect your existing database to see whether it contains any data. You can connect with the database client of your choice via your app's DATABASE_URL environment variable, but the easiest method might be to use Heroku Dataclips:\n\nHeroku Dataclips enable you to create SQL queries for your Heroku Postgres databases and share the results with colleagues, third-party tools, and the public. Recipients of a dataclip can view the data in their browser and also download it in JSON and CSV formats.\n\nThere, you can use the schema explorer and / or run queries against your database.\nIf you confirm that your database is not being used, feel free to destroy it. You are not required to use Heroku Postgres with your app.\n" ]
[ 0 ]
[]
[]
[ "django", "dyno", "heroku", "heroku_postgres", "python" ]
stackoverflow_0074549830_django_dyno_heroku_heroku_postgres_python.txt
Q: How to check if string of group in pandas is contained in another string of the same group in pandas I have this sample of dataframe | identifier | span | matched_string | | -------- | -------------- | ------ | | occupation | [0,12] | general manager| | occupation | [0,7] | manager | | time schedule | [13,14] | "0-5" | | occupation | [0,12]. | clerk | I want to group the df by identifier and then only keep the rows where a matched string is contained in another matched string of the same group and is the longer string. In this case manager is contained in general manager. Also I want to only keep the row if the matched string lays in the same span as the other matched string. In the end the df should look like this: | identifier | span | matched_string | | -------- | -------------- | ------ | | occupation | [0,12] | general manager| | time schedule| [13,14] | "0-5" | | occupation | [0,12] | clerk | In order to access the matches I have this code: ka = testa.groupby(["identifier"]) for name, group in ka: for index, row in group.iterrows(): for i in group['matched_string'].values: for j in group['matched_string'].values: for k in group['span_info'].values: for l in group['span_info'].values: if i != j and k != l: for m in list(range(k[0],k[1])): if m in list(range(l[0], l[1])) and i in j: max(i, j, key=len) Is there smarter way to do this? Also does someone have an idea on how I can keep rows where the strings dont contain one another as eg time schedule from the example table? Btw sorry for the bad format of the table but somehow I could not post the question unless it was formatted as code... Idk why A: I solved the problem by subdividing the for loops into functions and let them return True. Then I dropped those rows by index where both functions returned True. This is my solution: testa = df.groupby(["job_title_index", "identifier"]) #check if string matches are contained in the same span def same_span(row, row2): span_info = row['span_info'] span_info2 = row2['span_info'] if span_info != span_info2: #check if any number in range of span_info lays in another range(span_info[0], span_info[1]) for i in range(span_info[0], span_info[1]): if i in range(span_info2[0], span_info2[1]): return True #check if same matched_string def matched_string_check(row, row2): if row['matched_string'] in row2['matched_string'] and row['matched_string'] != row2['matched_string']: return True for name, group in testa: for index, row in group.iterrows(): for index2, row2 in group.iterrows(): if matched_string_check(row,row2) and same_span(row,row2): if max(row["matched_string"],row2["matched_string"],key=len) == row["matched_string"]: df.drop(index2, inplace=True) else: df.drop(index, inplace=True)
How to check if string of group in pandas is contained in another string of the same group in pandas
I have this sample of dataframe | identifier | span | matched_string | | -------- | -------------- | ------ | | occupation | [0,12] | general manager| | occupation | [0,7] | manager | | time schedule | [13,14] | "0-5" | | occupation | [0,12]. | clerk | I want to group the df by identifier and then only keep the rows where a matched string is contained in another matched string of the same group and is the longer string. In this case manager is contained in general manager. Also I want to only keep the row if the matched string lays in the same span as the other matched string. In the end the df should look like this: | identifier | span | matched_string | | -------- | -------------- | ------ | | occupation | [0,12] | general manager| | time schedule| [13,14] | "0-5" | | occupation | [0,12] | clerk | In order to access the matches I have this code: ka = testa.groupby(["identifier"]) for name, group in ka: for index, row in group.iterrows(): for i in group['matched_string'].values: for j in group['matched_string'].values: for k in group['span_info'].values: for l in group['span_info'].values: if i != j and k != l: for m in list(range(k[0],k[1])): if m in list(range(l[0], l[1])) and i in j: max(i, j, key=len) Is there smarter way to do this? Also does someone have an idea on how I can keep rows where the strings dont contain one another as eg time schedule from the example table? Btw sorry for the bad format of the table but somehow I could not post the question unless it was formatted as code... Idk why
[ "I solved the problem by subdividing the for loops into functions and let them return True. Then I dropped those rows by index where both functions returned True.\nThis is my solution:\ntesta = df.groupby([\"job_title_index\", \"identifier\"])\n\n#check if string matches are contained in the same span\ndef same_span(row, row2):\n span_info = row['span_info']\n span_info2 = row2['span_info']\n if span_info != span_info2:\n #check if any number in range of span_info lays in another range(span_info[0], span_info[1])\n for i in range(span_info[0], span_info[1]):\n if i in range(span_info2[0], span_info2[1]):\n return True\n\n#check if same matched_string\ndef matched_string_check(row, row2):\n if row['matched_string'] in row2['matched_string'] and row['matched_string'] != row2['matched_string']:\n return True\n\nfor name, group in testa:\n for index, row in group.iterrows():\n for index2, row2 in group.iterrows():\n if matched_string_check(row,row2) and same_span(row,row2):\n if max(row[\"matched_string\"],row2[\"matched_string\"],key=len) == row[\"matched_string\"]:\n df.drop(index2, inplace=True)\n else:\n df.drop(index, inplace=True)\n\n \n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074546016_dataframe_pandas_python.txt
Q: Xarray find lat/lon coordinates for maximum/minimum values for each timestep As the title says, supposing I have a ds with coords: [time lat lon], how can I obtain for each timestep in time the pair of ['lat','lon'] in which the maximum(or minimum) value for a given variable is located. A: Use xr.Dataset.idxmax to find the index label of the maximum along a dimension (one at a time). Same for xr.Dataset.idxmin. max_lons = ds.max(dim="lat").idxmax(dim="lon") max_lats = ds.max(dim="lon").idxmax(dim="lat") The results will be datasets, with each variable giving the lon or lat coresponding to the maximum in each time step for that variable.
Xarray find lat/lon coordinates for maximum/minimum values for each timestep
As the title says, supposing I have a ds with coords: [time lat lon], how can I obtain for each timestep in time the pair of ['lat','lon'] in which the maximum(or minimum) value for a given variable is located.
[ "Use xr.Dataset.idxmax to find the index label of the maximum along a dimension (one at a time). Same for xr.Dataset.idxmin.\nmax_lons = ds.max(dim=\"lat\").idxmax(dim=\"lon\")\nmax_lats = ds.max(dim=\"lon\").idxmax(dim=\"lat\")\n\nThe results will be datasets, with each variable giving the lon or lat coresponding to the maximum in each time step for that variable.\n" ]
[ 2 ]
[]
[]
[ "python", "python_xarray" ]
stackoverflow_0074547978_python_python_xarray.txt
Q: Create new columns using unique values in other columns in Python I'd like to create new columns in my dataframe using unique values from another column, for example Column 1 has the following values: Apple Apple Banana Strawberry Strawberry Strawberry When I check unique values in Column 1, the output would be : Apple Banana Strawberry Now I want to use these three values to create columns named "Apple","Banana","Strawberry" and I want to keep the code dynamic to adapt to however number of unique values are present in Column 1 I'm new to python, any help will be appreciated! So far, I've been doing getting that output by manually creating new columns in the dataset, I need this to happen automatically depending on the unique values in Column 1 A: extract unique values, iterate on them to create columns and fill in data. Here I inly put boolean values based on matching with the col1 value ... df = pd.DataFrame({"col1": ["apple", "apple", "banana", "pineapple", "banana", "apple"]}) data= col1 0 apple 1 apple 2 banana 3 pineapple 4 banana 5 apple transform: unique_col1_val = df["col1"].unique().tolist() for u in unique_col1_val: df[u] = df["col1"] == u # you need to determine how to fill these new columns # here we just put a bool indicating a match between new col name and col1 content ... # to put an int truth value use: # df[u] = (df["col1"] == u).astype(int) In [72]: df Out[72]: col1 apple banana pineapple 0 apple True False False 1 apple True False False 2 banana False True False 3 pineapple False False True 4 banana False True False 5 apple True False False using df[u] = (df["col1"] == u).astype(int): col1 apple banana pineapple 0 apple 1 0 0 1 apple 1 0 0 2 banana 0 1 0 3 pineapple 0 0 1 4 banana 0 1 0 5 apple 1 0 0
Create new columns using unique values in other columns in Python
I'd like to create new columns in my dataframe using unique values from another column, for example Column 1 has the following values: Apple Apple Banana Strawberry Strawberry Strawberry When I check unique values in Column 1, the output would be : Apple Banana Strawberry Now I want to use these three values to create columns named "Apple","Banana","Strawberry" and I want to keep the code dynamic to adapt to however number of unique values are present in Column 1 I'm new to python, any help will be appreciated! So far, I've been doing getting that output by manually creating new columns in the dataset, I need this to happen automatically depending on the unique values in Column 1
[ "extract unique values, iterate on them to create columns and fill in data.\nHere I inly put boolean values based on matching with the col1 value ...\ndf = pd.DataFrame({\"col1\": [\"apple\", \"apple\", \"banana\", \"pineapple\", \"banana\", \"apple\"]})\n\ndata=\n col1\n0 apple\n1 apple\n2 banana\n3 pineapple\n4 banana\n5 apple\n\ntransform:\nunique_col1_val = df[\"col1\"].unique().tolist()\nfor u in unique_col1_val:\n df[u] = df[\"col1\"] == u # you need to determine how to fill these new columns\n # here we just put a bool indicating a match between new col name and col1 content ...\n # to put an int truth value use:\n # df[u] = (df[\"col1\"] == u).astype(int)\n\nIn [72]: df\nOut[72]:\n col1 apple banana pineapple\n0 apple True False False\n1 apple True False False\n2 banana False True False\n3 pineapple False False True\n4 banana False True False\n5 apple True False False\n\n\nusing df[u] = (df[\"col1\"] == u).astype(int):\n col1 apple banana pineapple\n0 apple 1 0 0\n1 apple 1 0 0\n2 banana 0 1 0\n3 pineapple 0 0 1\n4 banana 0 1 0\n5 apple 1 0 0\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074550091_dataframe_pandas_python.txt
Q: can't fix weird characters when saving to .json file from python I'm trying to save a text from python but it generates strange characters "\u00f1" and I don't know how to eliminate this This is the code I'm using: with open("NoticiasHabboHotel.json", "w") as f: json.dump(test_versions, f, indent=0, separators=(',', ': ')) This is the text that generates me: Dise\u00f1adores de salas, \u00a1os necesitamos!27345 What I want is to convert it into normal letters I have tried different methods, such as encoding="utf8" and it doesn't work Could someone help me, thank you very much! A: See: https://docs.python.org/3/library/json.html#basic-usage You need to add ensure_ascii=False because ñ is a non-ASCII character with open("NoticiasHabboHotel.json", "w") as f: json.dump(test_versions, f, indent=0, separators=(',', ': '), ensure_ascii=False)
can't fix weird characters when saving to .json file from python
I'm trying to save a text from python but it generates strange characters "\u00f1" and I don't know how to eliminate this This is the code I'm using: with open("NoticiasHabboHotel.json", "w") as f: json.dump(test_versions, f, indent=0, separators=(',', ': ')) This is the text that generates me: Dise\u00f1adores de salas, \u00a1os necesitamos!27345 What I want is to convert it into normal letters I have tried different methods, such as encoding="utf8" and it doesn't work Could someone help me, thank you very much!
[ "See: https://docs.python.org/3/library/json.html#basic-usage\nYou need to add ensure_ascii=False because ñ is a non-ASCII character\nwith open(\"NoticiasHabboHotel.json\", \"w\") as f:\n json.dump(test_versions, f, indent=0, separators=(',', ': '), ensure_ascii=False)\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074549987_python.txt
Q: use OpenMaya to give particles specific translate and rotate values I'm struggling with OpenMaya here. I want to be able to take transform information from a list of locators and plug these values to particles shapes. The goal is to use this over 25000 locators, so I can't create a particle system for each instance. I really need to store position and rotation values to the particles themselves. To do that I started to dive into OpenMaya... (╯°□°)╯︵ ┻━┻ Anyway, the problem I'm facing now is that my scene crashes every time I launch this script and I can't figure out what I did wrong. I think I'm pretty close, but crashing Maya is not considered a victory. import pymel.core as pm import maya.OpenMaya as om import maya.OpenMayaFX as omfx import random ### A short script to create the scene with bunch of locators with random pos rot numOfLoc = 5 # this number will eventually be set 25000 when the script will work. # create locators with random position location(for test) def create_gazillion_locators(numOfLoc): for i in range(0, numOfLoc): # to create variation tx = random.uniform(-10, 10) ty = random.uniform(0, 5) tz = random.uniform(-10, 10) rx = random.uniform(0, 360) ry = random.uniform(0, 360) rz = random.uniform(0, 360) pm.spaceLocator() pm.move(tx, ty, tz) pm.rotate(rx, ry, rz, ws=True) # Select locators def select_locators(): pm.select(cl=True) loc_selection = pm.listRelatives(pm.ls(type = 'locator'), p=True) pm.select(loc_selection, r=True) return loc_selection # delete the locators def clean_the_scene(): #del locators (for testing purpiose) sel = select_locators() if sel is not None: pm.delete(sel) clean_the_scene() create_gazillion_locators(numOfLoc) ### Actual script # Found this on the internet. it seems to be more neat class Vector(om.MVector): def __str__(self): return '{0}, {1}, {2}'.format(self.x, self.y, self.z) def __repr__(self): return '{0}, {1}, {2}'.format(self.x, self.y, self.z) # OpenMaya treatment sel = select_locators() mSel = om.MSelectionList() om.MGlobal.getActiveSelectionList(mSel) mSel_iter = om.MItSelectionList(mSel) mSel_DagPath = om.MDagPath() # bvariables to store the transform in pos_array = om.MVectorArray() rot_array = om.MVectorArray() mLoc = om.MObject() # Main loop of selection iterator. while not mSel_iter.isDone(): # Get list of selected mSel_iter.getDagPath(mSel_DagPath) mSel_iter.getDependNode(mLoc) dep_node_name = om.MFnDependencyNode(mLoc).name() transl = pm.getAttr('{}.translate'.format(dep_node_name)) rotate = pm.getAttr('{}.rotate'.format(dep_node_name)) print(dep_node_name) print(Vector(transl[0], transl[1], transl[2])) print(Vector(rotate[0], rotate[1], rotate[2])) pos_array.append(Vector(transl[0], transl[1], transl[2])) rot_array.append(Vector(rotate[0], rotate[1], rotate[2])) mSel_iter.next() # Up untill there it seems to work ok. nparticles_transform, nparticles_shape = pm.nParticle(position = pos_array) pm.setAttr('nucleus1.gravity', 0.0) nparticles_shape.computeRotation.set(True) pm.addAttr(nparticles_shape, ln = 'rotationPP', dt = 'vectorArray') pm.addAttr(nparticles_shape, ln = 'rotationPP0', dt = 'vectorArray') pm.particleInstancer(nparticles_shape, name = p_instancer, edit = True, rotation = "rotationPP") particle_fn = omfx.MFnParticleSystem(nparticles_shape.__apimobject__()) particle_fn.setPerParticleAttribute('rotationPP', rot_array) particle_fn.setPerParticleAttribute('rotationPP0', rot_array) I read lots of things, went through the stack and google, I based my script on several other stuff I found/learnt (I listened to the OpenMaya course on Youtube by Chayan Vinayak)... But I've had a hard time understanding the OpenMaya documentation though. A: I've made a couple of changes to make it work. I didn't check the particle setup though. In fact, the main problem is mixing two different APIs. Either stick to OpenMaya (or even OpenMaya v2.0) or PyMEL. import pymel.core as pm import maya.OpenMaya as om import maya.OpenMayaFX as omfx import random ### A short script to create the scene with bunch of locators with random pos rot numOfLoc = 5 # this number will eventually be set 25000 when the script will work. # create locators with random position location(for test) def create_gazillion_locators(num_of_loc): for i in range(num_of_loc): # to create variation tx = random.uniform(-10, 10) ty = random.uniform(0, 5) tz = random.uniform(-10, 10) rx = random.uniform(0, 360) ry = random.uniform(0, 360) rz = random.uniform(0, 360) pm.spaceLocator() pm.move(tx, ty, tz) pm.rotate(rx, ry, rz, ws=True) # Select locators def select_locators(): pm.select(cl=True) loc_selection = pm.listRelatives(pm.ls(type="locator"), p=True) pm.select(loc_selection, r=True) return loc_selection # delete the locators def clean_the_scene(): # del locators (for testing purpiose) sel = select_locators() if sel is not None: pm.delete(sel) clean_the_scene() create_gazillion_locators(numOfLoc) ### Actual script # Found this on the internet. it seems to be more neat class Vector(om.MVector): def __str__(self): return "{0}, {1}, {2}".format(self.x, self.y, self.z) def __repr__(self): return "{0}, {1}, {2}".format(self.x, self.y, self.z) # OpenMaya treatment sel = select_locators() mSel = om.MSelectionList() om.MGlobal.getActiveSelectionList(mSel) mSel_iter = om.MItSelectionList(mSel) mSel_DagPath = om.MDagPath() # bvariables to store the transform in pos_array = [] rot_array = om.MVectorArray() mLoc = om.MObject() # Main loop of selection iterator. while not mSel_iter.isDone(): # Get list of selected mSel_iter.getDagPath(mSel_DagPath) mSel_iter.getDependNode(mLoc) dep_node_name = om.MFnDependencyNode(mLoc).name() transl = pm.getAttr("{}.translate".format(dep_node_name)) rotate = pm.getAttr("{}.rotate".format(dep_node_name)) print(dep_node_name) print(Vector(transl[0], transl[1], transl[2])) print(Vector(rotate[0], rotate[1], rotate[2])) pos_array.append((transl[0], transl[1], transl[2])) rot_array.append(Vector(rotate[0], rotate[1], rotate[2])) mSel_iter.next() # Up untill there it seems to work ok. nparticles_transform, nparticles_shape = pm.nParticle(position=pos_array) pm.setAttr("nucleus1.gravity", 0.0) nparticles_shape.computeRotation.set(True) pm.addAttr(nparticles_shape, ln="rotationPP", dt="vectorArray") pm.addAttr(nparticles_shape, ln="rotationPP0", dt="vectorArray") # Create an instancer before trying to edit instancer_node = pm.particleInstancer(nparticles_shape, name="p_instancer") pm.particleInstancer( nparticles_shape, name=instancer_node, edit=True, rotation="rotationPP" ) particle_fn = omfx.MFnParticleSystem(nparticles_shape.__apimobject__()) particle_fn.setPerParticleAttribute("rotationPP", rot_array) particle_fn.setPerParticleAttribute("rotationPP0", rot_array) A: I had a look and there is no need to use any openmaya in this case if you need pymel anyway. I used cmds for the creation of the locators because it is a bit faster, so if execution speed is a problem, try to switch everything to cmds. And I think there is no need to set the computeRotation because it's only used during simulation. import pymel.core as pm import maya.cmds as cmds import random numOfLoc = 5000 def c_create_gazillion_locators(num_of_loc): for i in range(num_of_loc): tx = random.uniform(-10, 10) ty = random.uniform(0, 5) tz = random.uniform(-10, 10) rx = random.uniform(0, 360) ry = random.uniform(0, 360) rz = random.uniform(0, 360) cmds.spaceLocator() cmds.move(tx, ty, tz) cmds.rotate(rx, ry, rz, ws=True) create_gazillion_locators(numOfLoc) locs = pm.ls(type="locator") locs = pm.listRelatives(locs, p=True) pos = [] rot = [] for loc in locs: pos.append(loc.translate.get()) rot.append(loc.rotate.get()) nparticles_transform, nparticles_shape = pm.nParticle(position=pos) pm.setAttr("nucleus1.gravity", 0.0) pm.addAttr(nparticles_shape, ln="rotationPP", dt="vectorArray") pm.addAttr(nparticles_shape, ln="rotationPP0", dt="vectorArray") rpp= pm.Attribute(nparticles_shape+".rotationPP") rpp0= pm.Attribute(nparticles_shape+".rotationPP0") rpp.set(rot) rpp0.set(rot)
use OpenMaya to give particles specific translate and rotate values
I'm struggling with OpenMaya here. I want to be able to take transform information from a list of locators and plug these values to particles shapes. The goal is to use this over 25000 locators, so I can't create a particle system for each instance. I really need to store position and rotation values to the particles themselves. To do that I started to dive into OpenMaya... (╯°□°)╯︵ ┻━┻ Anyway, the problem I'm facing now is that my scene crashes every time I launch this script and I can't figure out what I did wrong. I think I'm pretty close, but crashing Maya is not considered a victory. import pymel.core as pm import maya.OpenMaya as om import maya.OpenMayaFX as omfx import random ### A short script to create the scene with bunch of locators with random pos rot numOfLoc = 5 # this number will eventually be set 25000 when the script will work. # create locators with random position location(for test) def create_gazillion_locators(numOfLoc): for i in range(0, numOfLoc): # to create variation tx = random.uniform(-10, 10) ty = random.uniform(0, 5) tz = random.uniform(-10, 10) rx = random.uniform(0, 360) ry = random.uniform(0, 360) rz = random.uniform(0, 360) pm.spaceLocator() pm.move(tx, ty, tz) pm.rotate(rx, ry, rz, ws=True) # Select locators def select_locators(): pm.select(cl=True) loc_selection = pm.listRelatives(pm.ls(type = 'locator'), p=True) pm.select(loc_selection, r=True) return loc_selection # delete the locators def clean_the_scene(): #del locators (for testing purpiose) sel = select_locators() if sel is not None: pm.delete(sel) clean_the_scene() create_gazillion_locators(numOfLoc) ### Actual script # Found this on the internet. it seems to be more neat class Vector(om.MVector): def __str__(self): return '{0}, {1}, {2}'.format(self.x, self.y, self.z) def __repr__(self): return '{0}, {1}, {2}'.format(self.x, self.y, self.z) # OpenMaya treatment sel = select_locators() mSel = om.MSelectionList() om.MGlobal.getActiveSelectionList(mSel) mSel_iter = om.MItSelectionList(mSel) mSel_DagPath = om.MDagPath() # bvariables to store the transform in pos_array = om.MVectorArray() rot_array = om.MVectorArray() mLoc = om.MObject() # Main loop of selection iterator. while not mSel_iter.isDone(): # Get list of selected mSel_iter.getDagPath(mSel_DagPath) mSel_iter.getDependNode(mLoc) dep_node_name = om.MFnDependencyNode(mLoc).name() transl = pm.getAttr('{}.translate'.format(dep_node_name)) rotate = pm.getAttr('{}.rotate'.format(dep_node_name)) print(dep_node_name) print(Vector(transl[0], transl[1], transl[2])) print(Vector(rotate[0], rotate[1], rotate[2])) pos_array.append(Vector(transl[0], transl[1], transl[2])) rot_array.append(Vector(rotate[0], rotate[1], rotate[2])) mSel_iter.next() # Up untill there it seems to work ok. nparticles_transform, nparticles_shape = pm.nParticle(position = pos_array) pm.setAttr('nucleus1.gravity', 0.0) nparticles_shape.computeRotation.set(True) pm.addAttr(nparticles_shape, ln = 'rotationPP', dt = 'vectorArray') pm.addAttr(nparticles_shape, ln = 'rotationPP0', dt = 'vectorArray') pm.particleInstancer(nparticles_shape, name = p_instancer, edit = True, rotation = "rotationPP") particle_fn = omfx.MFnParticleSystem(nparticles_shape.__apimobject__()) particle_fn.setPerParticleAttribute('rotationPP', rot_array) particle_fn.setPerParticleAttribute('rotationPP0', rot_array) I read lots of things, went through the stack and google, I based my script on several other stuff I found/learnt (I listened to the OpenMaya course on Youtube by Chayan Vinayak)... But I've had a hard time understanding the OpenMaya documentation though.
[ "I've made a couple of changes to make it work. I didn't check the particle setup though. In fact, the main problem is mixing two different APIs. Either stick to OpenMaya (or even OpenMaya v2.0) or PyMEL.\nimport pymel.core as pm\nimport maya.OpenMaya as om\nimport maya.OpenMayaFX as omfx\n\nimport random\n\n### A short script to create the scene with bunch of locators with random pos rot\n\nnumOfLoc = 5 # this number will eventually be set 25000 when the script will work.\n\n# create locators with random position location(for test)\ndef create_gazillion_locators(num_of_loc):\n for i in range(num_of_loc):\n # to create variation\n tx = random.uniform(-10, 10)\n ty = random.uniform(0, 5)\n tz = random.uniform(-10, 10)\n rx = random.uniform(0, 360)\n ry = random.uniform(0, 360)\n rz = random.uniform(0, 360)\n\n pm.spaceLocator()\n pm.move(tx, ty, tz)\n pm.rotate(rx, ry, rz, ws=True)\n\n\n# Select locators\ndef select_locators():\n pm.select(cl=True)\n loc_selection = pm.listRelatives(pm.ls(type=\"locator\"), p=True)\n pm.select(loc_selection, r=True)\n\n return loc_selection\n\n\n# delete the locators\ndef clean_the_scene():\n # del locators (for testing purpiose)\n sel = select_locators()\n if sel is not None:\n pm.delete(sel)\n\n\nclean_the_scene()\ncreate_gazillion_locators(numOfLoc)\n\n\n### Actual script\n\n# Found this on the internet. it seems to be more neat\nclass Vector(om.MVector):\n def __str__(self):\n return \"{0}, {1}, {2}\".format(self.x, self.y, self.z)\n\n def __repr__(self):\n return \"{0}, {1}, {2}\".format(self.x, self.y, self.z)\n\n\n# OpenMaya treatment\nsel = select_locators()\n\nmSel = om.MSelectionList()\nom.MGlobal.getActiveSelectionList(mSel)\nmSel_iter = om.MItSelectionList(mSel)\nmSel_DagPath = om.MDagPath()\n\n# bvariables to store the transform in\npos_array = []\nrot_array = om.MVectorArray()\n\nmLoc = om.MObject()\n\n\n# Main loop of selection iterator.\nwhile not mSel_iter.isDone():\n\n # Get list of selected\n mSel_iter.getDagPath(mSel_DagPath)\n\n mSel_iter.getDependNode(mLoc)\n\n dep_node_name = om.MFnDependencyNode(mLoc).name()\n\n transl = pm.getAttr(\"{}.translate\".format(dep_node_name))\n rotate = pm.getAttr(\"{}.rotate\".format(dep_node_name))\n\n print(dep_node_name)\n\n print(Vector(transl[0], transl[1], transl[2]))\n print(Vector(rotate[0], rotate[1], rotate[2]))\n\n pos_array.append((transl[0], transl[1], transl[2]))\n rot_array.append(Vector(rotate[0], rotate[1], rotate[2]))\n\n mSel_iter.next()\n\n# Up untill there it seems to work ok.\n\nnparticles_transform, nparticles_shape = pm.nParticle(position=pos_array)\n\n\npm.setAttr(\"nucleus1.gravity\", 0.0)\n\n\nnparticles_shape.computeRotation.set(True)\n\n\npm.addAttr(nparticles_shape, ln=\"rotationPP\", dt=\"vectorArray\")\npm.addAttr(nparticles_shape, ln=\"rotationPP0\", dt=\"vectorArray\")\n# Create an instancer before trying to edit\ninstancer_node = pm.particleInstancer(nparticles_shape, name=\"p_instancer\")\npm.particleInstancer(\n nparticles_shape, name=instancer_node, edit=True, rotation=\"rotationPP\"\n)\n\nparticle_fn = omfx.MFnParticleSystem(nparticles_shape.__apimobject__())\nparticle_fn.setPerParticleAttribute(\"rotationPP\", rot_array)\nparticle_fn.setPerParticleAttribute(\"rotationPP0\", rot_array)\n\n", "I had a look and there is no need to use any openmaya in this case if you need pymel anyway. I used cmds for the creation of the locators because it is a bit faster, so if execution speed is a problem, try to switch everything to cmds.\nAnd I think there is no need to set the computeRotation because it's only used during simulation.\n import pymel.core as pm\n import maya.cmds as cmds\n import random\n numOfLoc = 5000\n \n def c_create_gazillion_locators(num_of_loc):\n for i in range(num_of_loc):\n tx = random.uniform(-10, 10)\n ty = random.uniform(0, 5)\n tz = random.uniform(-10, 10)\n rx = random.uniform(0, 360)\n ry = random.uniform(0, 360)\n rz = random.uniform(0, 360)\n \n cmds.spaceLocator()\n cmds.move(tx, ty, tz)\n cmds.rotate(rx, ry, rz, ws=True)\n \n create_gazillion_locators(numOfLoc)\n \n locs = pm.ls(type=\"locator\")\n locs = pm.listRelatives(locs, p=True)\n pos = []\n rot = []\n for loc in locs:\n pos.append(loc.translate.get())\n rot.append(loc.rotate.get())\n \n nparticles_transform, nparticles_shape = pm.nParticle(position=pos)\n pm.setAttr(\"nucleus1.gravity\", 0.0)\n pm.addAttr(nparticles_shape, ln=\"rotationPP\", dt=\"vectorArray\")\n pm.addAttr(nparticles_shape, ln=\"rotationPP0\", dt=\"vectorArray\")\n rpp= pm.Attribute(nparticles_shape+\".rotationPP\")\n rpp0= pm.Attribute(nparticles_shape+\".rotationPP0\")\n rpp.set(rot)\n rpp0.set(rot)\n\n" ]
[ 0, 0 ]
[]
[]
[ "maya", "maya_api", "python" ]
stackoverflow_0074539366_maya_maya_api_python.txt
Q: cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="No such configuration property: "bootstrap_servers""} I am trying to produce AVRO data to Kafka topic through python producer script, I already installed python dependencies avro-python3 and confluent_kafka, however when running this script i got below error: File "./kafka_producer_avro.py", line 24, in <module> kafka_producer_obj = Producer(kafka_config_obj) cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="No such configuration property: "bootstrap_servers""} After investigation i found that I should install (libsasl2-dev and libsasl2-modules) dependencies. (sudo yum install gcc libffi-devel python-devel python-pip python-wheel openssl-devel libsasl2-devel openldap-devel), but i got below Error: Unable to find a match: python-devel python-pip python-wheel libsasl2-devel A: Your shown error has nothing to do with OS packages. It's bootstrap.servers, not with an underscore. Also, the Kafka module is with hyphen, not underscore. Docs - https://docs.confluent.io/kafka-clients/python/current/overview.html You can additionally install fastavro with pip.
cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="No such configuration property: "bootstrap_servers""}
I am trying to produce AVRO data to Kafka topic through python producer script, I already installed python dependencies avro-python3 and confluent_kafka, however when running this script i got below error: File "./kafka_producer_avro.py", line 24, in <module> kafka_producer_obj = Producer(kafka_config_obj) cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="No such configuration property: "bootstrap_servers""} After investigation i found that I should install (libsasl2-dev and libsasl2-modules) dependencies. (sudo yum install gcc libffi-devel python-devel python-pip python-wheel openssl-devel libsasl2-devel openldap-devel), but i got below Error: Unable to find a match: python-devel python-pip python-wheel libsasl2-devel
[ "Your shown error has nothing to do with OS packages.\nIt's bootstrap.servers, not with an underscore. Also, the Kafka module is with hyphen, not underscore.\nDocs - https://docs.confluent.io/kafka-clients/python/current/overview.html\nYou can additionally install fastavro with pip.\n" ]
[ 0 ]
[]
[]
[ "apache_kafka", "confluent_kafka_python", "python" ]
stackoverflow_0074547844_apache_kafka_confluent_kafka_python_python.txt
Q: Pandas interpolate within a groupby for one column Similar to this question Pandas interpolate within a groupby but the answer to that question does the interpolate() for all columns. If I only want to limit the interpolate() to one column how do I do that? Input filename val1 val2 t 1 file1.csv 5 10 2 file1.csv NaN NaN 3 file1.csv 15 20 6 file2.csv NaN NaN 7 file2.csv 10 20 8 file2.csv 12 15 Expected Output filename val1 val2 t 1 file1.csv 5 10 2 file1.csv NaN 15 3 file1.csv 15 20 6 file2.csv NaN NaN 7 file2.csv 10 20 8 file2.csv 12 15 This attempt only returns val2 column but not the rest of the columns. df = df.groupby('filename').apply(lambda group: group['val2'].interpolate(method='index')) A: A direct approach: df = pd.read_clipboard() # clipboard contains OP sample data # interpolate only on col "val2" df["val2_interpolated"] = df[["filename","val2"]].groupby('filename') .apply(lambda x:x) # WTF .interpolate(method='linear')["val2"] returns: filename val1 val2 val2_interpolated t 1 file1.csv 5.0 10.0 10.0 2 file1.csv NaN NaN 15.0 3 file1.csv 15.0 20.0 20.0 6 file2.csv NaN NaN 20.0 7 file2.csv 10.0 20.0 20.0 8 file2.csv 12.0 15.0 15.0
Pandas interpolate within a groupby for one column
Similar to this question Pandas interpolate within a groupby but the answer to that question does the interpolate() for all columns. If I only want to limit the interpolate() to one column how do I do that? Input filename val1 val2 t 1 file1.csv 5 10 2 file1.csv NaN NaN 3 file1.csv 15 20 6 file2.csv NaN NaN 7 file2.csv 10 20 8 file2.csv 12 15 Expected Output filename val1 val2 t 1 file1.csv 5 10 2 file1.csv NaN 15 3 file1.csv 15 20 6 file2.csv NaN NaN 7 file2.csv 10 20 8 file2.csv 12 15 This attempt only returns val2 column but not the rest of the columns. df = df.groupby('filename').apply(lambda group: group['val2'].interpolate(method='index'))
[ "A direct approach:\ndf = pd.read_clipboard() # clipboard contains OP sample data\n# interpolate only on col \"val2\"\ndf[\"val2_interpolated\"] = df[[\"filename\",\"val2\"]].groupby('filename')\n.apply(lambda x:x) # WTF\n.interpolate(method='linear')[\"val2\"]\n\nreturns:\n filename val1 val2 val2_interpolated\nt\n1 file1.csv 5.0 10.0 10.0\n2 file1.csv NaN NaN 15.0\n3 file1.csv 15.0 20.0 20.0\n6 file2.csv NaN NaN 20.0\n7 file2.csv 10.0 20.0 20.0\n8 file2.csv 12.0 15.0 15.0\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "group_by", "interpolation", "pandas", "python" ]
stackoverflow_0074550482_dataframe_group_by_interpolation_pandas_python.txt
Q: How to retain attributes of inherited Spark DataFrame Class following a Spark operation on that class I create a new class called NewDataFrame with attribute a_string: import numpy as np import pandas as pd from pyspark.sql import DataFrame class NewDataFrame(DataFrame): def __init__(self, df): super().__init__(df._jdf,df.sql_ctx) self.a_string = "Hello, World." I use the class on some data and am able to print out a_string: data = { 'a': ['yellow', 'red'] ,'b': [1, 2] } df = pd.DataFrame(data) sdf = spark.createDataFrame(df) temp = NewDataFrame(sdf) temp.a_string Out[]: Hello, World. Now, I filter temp to a subset and try to output a_string and receive an error because the filter method returns a DataFrame, not NewDataFrame. temp = temp.filter("a='yellow'") temp.a_string Out[]: 'DataFrame' object has no attribute 'a_string' To keep the attribute in the result of a filter, I have tried creating a new method on the NewDataFrame class which performs the filter and then feeds the result back into a NewDataFrame class, which works, but I do not want to rewrite all the Spark functions in this manner. Is there a way for the class to have access to the full range of DataFrame methods while still retaining the attributes I define in NewDataFrame? A: I have tried the same inheritance in Python with no success. The PySpark dataframe has been implemented in a such way to return the Dataframe object after performing the operations. You can look at the source code and see how it has been done: https://github.com/apache/spark/blob/master/python/pyspark/sql/dataframe.py As mentioned in the question, without overriding each function in your subclass it will be difficult to build proper functional class. One another way is you can use initialize Parent object within the child class instead of inheriting from the Parent class.
How to retain attributes of inherited Spark DataFrame Class following a Spark operation on that class
I create a new class called NewDataFrame with attribute a_string: import numpy as np import pandas as pd from pyspark.sql import DataFrame class NewDataFrame(DataFrame): def __init__(self, df): super().__init__(df._jdf,df.sql_ctx) self.a_string = "Hello, World." I use the class on some data and am able to print out a_string: data = { 'a': ['yellow', 'red'] ,'b': [1, 2] } df = pd.DataFrame(data) sdf = spark.createDataFrame(df) temp = NewDataFrame(sdf) temp.a_string Out[]: Hello, World. Now, I filter temp to a subset and try to output a_string and receive an error because the filter method returns a DataFrame, not NewDataFrame. temp = temp.filter("a='yellow'") temp.a_string Out[]: 'DataFrame' object has no attribute 'a_string' To keep the attribute in the result of a filter, I have tried creating a new method on the NewDataFrame class which performs the filter and then feeds the result back into a NewDataFrame class, which works, but I do not want to rewrite all the Spark functions in this manner. Is there a way for the class to have access to the full range of DataFrame methods while still retaining the attributes I define in NewDataFrame?
[ "I have tried the same inheritance in Python with no success. The PySpark dataframe has been implemented in a such way to return the Dataframe object after performing the operations. You can look at the source code and see how it has been done:\nhttps://github.com/apache/spark/blob/master/python/pyspark/sql/dataframe.py\nAs mentioned in the question, without overriding each function in your subclass it will be difficult to build proper functional class. One another way is you can use initialize Parent object within the child class instead of inheriting from the Parent class.\n" ]
[ 0 ]
[]
[]
[ "class", "dataframe", "inheritance", "pyspark", "python" ]
stackoverflow_0071376315_class_dataframe_inheritance_pyspark_python.txt
Q: Python IPython Turning variables to strings I have a function that creates new Jupyter Notebook cells and I'm trying to use a loop to show value counts for each column and the specific difficulty I have is having them return with the column names in quotes. Here's what I have: def create_new_cell(contents): shell = get_ipython() payload = dict( source='set_next_input', text=contents, replace=False, ) shell.payload_manager.write_payload(payload, single=False) def show_vc(col): col = (f'(col)') content = "df[{col_name}].value_counts()"\ .format(col_name=col) create_new_cell(content) ^ This returns an actual 'col' instead of what I want, which is the series name. I've tried replacing col = (f'(col)') with things like col = str(col) or col = "(col)" but nothing has worked for me and I'm admittedly thinking about how to properly word this in a way so it will execute properly when I'm running my next cell, which is for x in df.columns: show_vc(x) Any help would be appreciated. A: You forgot curly brackets. You need to use them to replace the field with the variable. col = f'{col}' Test code col = 'column' col = f'{col}' print(col) A: So I just found the answer. I had to use Pretty Print. def show_vc(col): col = pformat(col) #col = f'({col})' content = "df[{col_name}].value_counts()"\ .format(col_name=col) create_new_cell(content) The output looked like this:
Python IPython Turning variables to strings
I have a function that creates new Jupyter Notebook cells and I'm trying to use a loop to show value counts for each column and the specific difficulty I have is having them return with the column names in quotes. Here's what I have: def create_new_cell(contents): shell = get_ipython() payload = dict( source='set_next_input', text=contents, replace=False, ) shell.payload_manager.write_payload(payload, single=False) def show_vc(col): col = (f'(col)') content = "df[{col_name}].value_counts()"\ .format(col_name=col) create_new_cell(content) ^ This returns an actual 'col' instead of what I want, which is the series name. I've tried replacing col = (f'(col)') with things like col = str(col) or col = "(col)" but nothing has worked for me and I'm admittedly thinking about how to properly word this in a way so it will execute properly when I'm running my next cell, which is for x in df.columns: show_vc(x) Any help would be appreciated.
[ "You forgot curly brackets.\nYou need to use them to replace the field with the variable.\ncol = f'{col}'\nTest code\ncol = 'column'\ncol = f'{col}'\nprint(col)\n\n", "So I just found the answer. I had to use Pretty Print.\ndef show_vc(col):\n col = pformat(col)\n #col = f'({col})'\n content = \"df[{col_name}].value_counts()\"\\\n .format(col_name=col)\n create_new_cell(content)\n\nThe output looked like this:\n\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074549942_python.txt
Q: How to return the sum for each string value in excel sheet? I try to return the sum for every fruit item. So I have a excel sheet with column E(5) and then for every row there is a value. So the row:ananas(6,7,8) has the values: 1596, 1309,1057 = total: 3962 So I have it like this: import openpyxl import tabula excelWorkbook = openpyxl.load_workbook(path, data_only=True) def calulate_total_fruit_NorthMidSouth(): sheet_factuur = excelWorkbook['Facturen '] fruit_name_rows = { 'ananas': [6, 7, 8], 'apple': [9, 10, 11], 'waspeen': [12, 13, 14], } total_fruit_counts = {k:sum([sheet_factuur.cell( row=row_num, column=5)).value for row_num, in fruit_name_rows.items()]} return total_fruit_counts the output has to look like this: ananas:3962 apple: 200 waspeen: 700 my excel sheet looks like this: Regio Noord Ananas 1,596.00 Regio Midden Ananas 1,309.00 Regio Zuid Ananas 1,057.00 Regio Noord Appel 1,333.80 Regio Midden Appel 1,090.44 Regio Zuid Appel 879.84 Regio Noord Waspeen 1,530.90 Regio Midden Waspeen 1,234.80 Regio Zuid Waspeen 1,001.70 ananas is colum 5 and row: 6,7,8 Appel is column 5 and row: 9,10,11 and Waspeen is column 5 and row: 12,13,14 A: You could use a dictionary to keep a running tally of sums while you iterate through the values. fruit_sums = { 'ananas': 0, 'apple': 0, 'waspeen': 0, } I would recommend converting all excel values to a python array. array = [row for row in sheet_factuur.values] Iterate through values and add them to your fruit_sums. for row_num, row_values in enumerate(array, 1): # excel does not have a row 0 for fruit in ['ananas', 'apple', 'waspeen']: # loop through specific fruits if row_num in fruit_name_rows[fruit]: fruit_sums[fruit] += row_values[4] # index 4 is column 5 in excel Then display or save the data however you wish. for fruit, s in fruit_sums.items(): print(f'{fruit.rjust(10)} {s}') >> ananas 3962 >> apple 200 >> waspeen 700
How to return the sum for each string value in excel sheet?
I try to return the sum for every fruit item. So I have a excel sheet with column E(5) and then for every row there is a value. So the row:ananas(6,7,8) has the values: 1596, 1309,1057 = total: 3962 So I have it like this: import openpyxl import tabula excelWorkbook = openpyxl.load_workbook(path, data_only=True) def calulate_total_fruit_NorthMidSouth(): sheet_factuur = excelWorkbook['Facturen '] fruit_name_rows = { 'ananas': [6, 7, 8], 'apple': [9, 10, 11], 'waspeen': [12, 13, 14], } total_fruit_counts = {k:sum([sheet_factuur.cell( row=row_num, column=5)).value for row_num, in fruit_name_rows.items()]} return total_fruit_counts the output has to look like this: ananas:3962 apple: 200 waspeen: 700 my excel sheet looks like this: Regio Noord Ananas 1,596.00 Regio Midden Ananas 1,309.00 Regio Zuid Ananas 1,057.00 Regio Noord Appel 1,333.80 Regio Midden Appel 1,090.44 Regio Zuid Appel 879.84 Regio Noord Waspeen 1,530.90 Regio Midden Waspeen 1,234.80 Regio Zuid Waspeen 1,001.70 ananas is colum 5 and row: 6,7,8 Appel is column 5 and row: 9,10,11 and Waspeen is column 5 and row: 12,13,14
[ "You could use a dictionary to keep a running tally of sums while you iterate through the values.\nfruit_sums = {\n 'ananas': 0,\n 'apple': 0,\n 'waspeen': 0,\n}\n\nI would recommend converting all excel values to a python array.\narray = [row for row in sheet_factuur.values]\n\nIterate through values and add them to your fruit_sums.\nfor row_num, row_values in enumerate(array, 1): # excel does not have a row 0\n for fruit in ['ananas', 'apple', 'waspeen']: # loop through specific fruits\n if row_num in fruit_name_rows[fruit]:\n fruit_sums[fruit] += row_values[4] # index 4 is column 5 in excel\n\nThen display or save the data however you wish.\nfor fruit, s in fruit_sums.items(): \n print(f'{fruit.rjust(10)} {s}')\n\n>> ananas 3962\n>> apple 200\n>> waspeen 700\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074549977_python.txt
Q: How to remove numbers from a string column that starts with 4 zeros? I have a column of names and informations of products, i need to remove the codes from the names and every code starts with four or more zeros, some names have four zeros or more in the weight and some are joined with the name as the example below: data = { 'Name' : ['ANOA 250g 00004689', 'ANOA 10000g 00000059884', '80%c asjw 150000001568 ', 'Shivangi000000478761'], } testdf = pd.DataFrame(data) The correct output would be: results = { 'Name' : ['ANOA 250g', 'ANOA 10000g', '80%c asjw 150000001568 ', 'Shivangi'], } results = pd.DataFrame(results) A: Use a regex with str.replace: testdf['Name'] = testdf['Name'].str.replace(r'(?:(?<=\D)|\s*\b)0{4}\d*', '', regex=True) Or, similar to @HaleemurAli, with a negative match testdf['Name'] = testdf['Name'].str.replace(r'(?<!\d)0{4,}0{4}\d*', '', regex=True) Output: Name 0 ANOA 250g 1 ANOA 10000g 2 80%c asjw 150000001568 3 Shivangi regex1 demo regex2 demo A: you can split the strings by the start of the code pattern, which is expressed by the regex (?<!\d)0{4,}. this pattern consumes four 0s that are not preceded by any digit. after splitting the string, take the first fragment, and the str.strip gets rid of possible trailing space testdf.Name.str.split('(?<!\d)0{4,}', regex=True, expand=True)[0].str.strip()[0].str.strip() # outputs: 0 ANOA 250g 1 ANOA 10000g 2 80%c asjw 150000001568 3 Shivangi note that this works for the case where the codes are always at the end of your string.
How to remove numbers from a string column that starts with 4 zeros?
I have a column of names and informations of products, i need to remove the codes from the names and every code starts with four or more zeros, some names have four zeros or more in the weight and some are joined with the name as the example below: data = { 'Name' : ['ANOA 250g 00004689', 'ANOA 10000g 00000059884', '80%c asjw 150000001568 ', 'Shivangi000000478761'], } testdf = pd.DataFrame(data) The correct output would be: results = { 'Name' : ['ANOA 250g', 'ANOA 10000g', '80%c asjw 150000001568 ', 'Shivangi'], } results = pd.DataFrame(results)
[ "Use a regex with str.replace:\ntestdf['Name'] = testdf['Name'].str.replace(r'(?:(?<=\\D)|\\s*\\b)0{4}\\d*',\n '', regex=True)\n\nOr, similar to @HaleemurAli, with a negative match\ntestdf['Name'] = testdf['Name'].str.replace(r'(?<!\\d)0{4,}0{4}\\d*',\n '', regex=True)\n\nOutput:\n Name\n0 ANOA 250g\n1 ANOA 10000g\n2 80%c asjw 150000001568 \n3 Shivangi\n\nregex1 demo\nregex2 demo\n", "you can split the strings by the start of the code pattern, which is expressed by the regex (?<!\\d)0{4,}. this pattern consumes four 0s that are not preceded by any digit. after splitting the string, take the first fragment, and the str.strip gets rid of possible trailing space\ntestdf.Name.str.split('(?<!\\d)0{4,}', regex=True, expand=True)[0].str.strip()[0].str.strip()\n# outputs:\n0 ANOA 250g\n1 ANOA 10000g\n2 80%c asjw 150000001568\n3 Shivangi\n\nnote that this works for the case where the codes are always at the end of your string.\n" ]
[ 3, 3 ]
[ "try splitting it at each space and checking if the each item has 0000 in it like:\nanswer=[]\nfor i in results[\"Name\"]:\n answer.append(\"\".join([j for j in i.split() if \"0000\" not in j]))\n\n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0074550291_pandas_python.txt
Q: Django CountryField, query by country I have a class similar to this: class Person(models.Model): name = CharField(max_length=255) citizenship = CountryField(multiple=True) In this example a Person can have more than one citizenship. Person.objects.create(name="Fred Flinstone", citizenship="US, CA") I want to query for everyone who has a US citizenship, which would return Fred from above. Is there a django-countries way to do this? I suppose I could treat it like a CharField. If I wanted to do something more complex like "is Person a citizen of US or GB", I was hoping there was a nicer way than a complex CharField query. A: Try this out: Person.objects.filter(citizenship__contains="US") Also check out the django-countries code, especially tests, if my suggestion is not exactly what you are searching for, I am sure you will find answer there: Link to tests
Django CountryField, query by country
I have a class similar to this: class Person(models.Model): name = CharField(max_length=255) citizenship = CountryField(multiple=True) In this example a Person can have more than one citizenship. Person.objects.create(name="Fred Flinstone", citizenship="US, CA") I want to query for everyone who has a US citizenship, which would return Fred from above. Is there a django-countries way to do this? I suppose I could treat it like a CharField. If I wanted to do something more complex like "is Person a citizen of US or GB", I was hoping there was a nicer way than a complex CharField query.
[ "Try this out:\n Person.objects.filter(citizenship__contains=\"US\")\n\nAlso check out the django-countries code, especially tests, if my suggestion is not exactly what you are searching for, I am sure you will find answer there:\nLink to tests\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074550230_django_django_models_python.txt
Q: Divide click commands into sections in cli documentation This code: #!/usr/bin env python3 import click def f(*a, **kw): print(a, kw) commands = [click.Command("cmd1", callback=f), click.Command("cmd2", callback=f)] cli = click.Group(commands={c.name: c for c in commands}) if __name__ == "__main__": cli() generates this help: # Usage: cli.py [OPTIONS] COMMAND [ARGS]... # Options: # --help Show this message and exit. # Commands: # cmd1 # cmd2 I have a lot of subcommands, so I want to divide them into sections in the help like this: # Usage: cli.py [OPTIONS] COMMAND [ARGS]... # Options: # --help Show this message and exit. # Commands: # cmd1 # cmd2 # # Extra other commands: # cmd3 # cmd4 How can I split the commands into sections in the help like that, without affecting the functionality? A: If you define your own group class you can overide the help generation like: Custom Class: class SectionedHelpGroup(click.Group): """Sections commands into help groups""" def __init__(self, *args, **kwargs): self.grouped_commands = kwargs.pop('grouped_commands', {}) commands = {} for group, command_list in self.grouped_commands.items(): for cmd in command_list: cmd.help_group = group commands[cmd.name] = cmd super(SectionedHelpGroup, self).__init__( *args, commands=commands, **kwargs) def command(self, *args, **kwargs): help_group = kwargs.pop('help_group') decorator = super(SectionedHelpGroup, self).command(*args, **kwargs) def new_decorator(f): cmd = decorator(f) cmd.help_group = help_group self.grouped_commands.setdefault(help_group, []).append(cmd) return cmd return new_decorator def format_commands(self, ctx, formatter): for group, cmds in self.grouped_commands.items(): rows = [] for subcommand in self.list_commands(ctx): cmd = self.get_command(ctx, subcommand) if cmd is None or cmd.help_group != group: continue rows.append((subcommand, cmd.short_help or '')) if rows: with formatter.section(group): formatter.write_dl(rows) Using the Custom Class: Pass the Custom Class to click.group() using cls parameter like: @click.group(cls=SectionedHelpGroup) def cli(): """""" when defining commands, pass the help group the command belongs to like: @cli.command(help_group='my help group') def a_command(*args, **kwargs): .... How does this work? This works because click is a well designed OO framework. The @click.group() decorator usually instantiates a click.Group object but allows this behavior to be over-ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Group in our own class and over ride the desired methods. In this case, we hook the command() decorator to allow the help_group to be identified. We also override the format_commands() method to print the commands help into the groups. Test Code: import click def f(*args, **kwargs): click.echo(args, kwargs) commands = { 'help group 1': [ click.Command("cmd1", callback=f), click.Command("cmd2", callback=f) ], 'help group 2': [ click.Command("cmd3", callback=f), click.Command("cmd4", callback=f) ] } cli = SectionedHelpGroup(grouped_commands=commands) @cli.command(help_group='help group 3') def a_command(*args, **kwargs): """My command""" click.echo(args, kwargs) if __name__ == "__main__": cli(['--help']) Results: Usage: test.py [OPTIONS] COMMAND [ARGS]... Options: --help Show this message and exit. help group 1: cmd1 cmd2 help group 2: cmd3 cmd4 help group 3: a_command My command A: Stephen's answer above gives the general principle. If you only add new commands to a group using add_command, it can be simplified slightly: import click import collections class SectionedHelpGroup(click.Group): """Organize commands as sections""" def __init__(self, *args, **kwargs): self.section_commands = collections.defaultdict(list) super().__init__(*args, **kwargs) def add_command(self, cmd, name=None, section=None): self.section_commands[section].append(cmd) super().add_command(cmd, name=name) def format_commands(self, ctx, formatter): for group, cmds in self.section_commands.items(): with formatter.section(group): formatter.write_dl( [(cmd.name, cmd.get_short_help_str() or "") for cmd in cmds] ) Example def f(*args, **kwargs): click.echo(args, kwargs) commands = { 'help group 1': [ click.Command("cmd1", callback=f), click.Command("cmd2", callback=f) ], 'help group 2': [ click.Command("cmd3", callback=f), click.Command("cmd4", callback=f) ] } @click.group( help=f"Sectioned Commands CLI", cls=SectionedHelpGroup ) def cli(): pass for (section, cmds) in commands.items(): for cmd in cmds: cli.add_command(cmd, section=section) if __name__ == "__main__": cli()
Divide click commands into sections in cli documentation
This code: #!/usr/bin env python3 import click def f(*a, **kw): print(a, kw) commands = [click.Command("cmd1", callback=f), click.Command("cmd2", callback=f)] cli = click.Group(commands={c.name: c for c in commands}) if __name__ == "__main__": cli() generates this help: # Usage: cli.py [OPTIONS] COMMAND [ARGS]... # Options: # --help Show this message and exit. # Commands: # cmd1 # cmd2 I have a lot of subcommands, so I want to divide them into sections in the help like this: # Usage: cli.py [OPTIONS] COMMAND [ARGS]... # Options: # --help Show this message and exit. # Commands: # cmd1 # cmd2 # # Extra other commands: # cmd3 # cmd4 How can I split the commands into sections in the help like that, without affecting the functionality?
[ "If you define your own group class you can overide the help generation like:\nCustom Class:\nclass SectionedHelpGroup(click.Group):\n \"\"\"Sections commands into help groups\"\"\"\n\n def __init__(self, *args, **kwargs):\n self.grouped_commands = kwargs.pop('grouped_commands', {})\n commands = {}\n for group, command_list in self.grouped_commands.items():\n for cmd in command_list:\n cmd.help_group = group\n commands[cmd.name] = cmd\n\n super(SectionedHelpGroup, self).__init__(\n *args, commands=commands, **kwargs)\n\n def command(self, *args, **kwargs):\n help_group = kwargs.pop('help_group')\n decorator = super(SectionedHelpGroup, self).command(*args, **kwargs)\n\n def new_decorator(f):\n cmd = decorator(f)\n cmd.help_group = help_group\n self.grouped_commands.setdefault(help_group, []).append(cmd)\n return cmd\n\n return new_decorator\n\n def format_commands(self, ctx, formatter):\n for group, cmds in self.grouped_commands.items():\n rows = []\n for subcommand in self.list_commands(ctx):\n cmd = self.get_command(ctx, subcommand)\n if cmd is None or cmd.help_group != group:\n continue\n rows.append((subcommand, cmd.short_help or ''))\n\n if rows:\n with formatter.section(group):\n formatter.write_dl(rows)\n\nUsing the Custom Class:\nPass the Custom Class to click.group() using cls parameter like:\n@click.group(cls=SectionedHelpGroup)\ndef cli():\n \"\"\"\"\"\"\n\nwhen defining commands, pass the help group the command belongs to like:\n@cli.command(help_group='my help group')\ndef a_command(*args, **kwargs):\n .... \n\nHow does this work?\nThis works because click is a well designed OO framework. The @click.group() decorator usually instantiates a click.Group object but allows this behavior to be over-ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Group in our own class and over ride the desired methods.\nIn this case, we hook the command() decorator to allow the help_group to be identified. We also override the format_commands() method to print the commands help into the groups.\nTest Code:\nimport click\n\ndef f(*args, **kwargs):\n click.echo(args, kwargs)\n\ncommands = {\n 'help group 1': [\n click.Command(\"cmd1\", callback=f),\n click.Command(\"cmd2\", callback=f)\n ],\n 'help group 2': [\n click.Command(\"cmd3\", callback=f),\n click.Command(\"cmd4\", callback=f)\n ]\n}\n\ncli = SectionedHelpGroup(grouped_commands=commands)\n\n@cli.command(help_group='help group 3')\ndef a_command(*args, **kwargs):\n \"\"\"My command\"\"\"\n click.echo(args, kwargs)\n\n\nif __name__ == \"__main__\":\n cli(['--help'])\n\nResults:\nUsage: test.py [OPTIONS] COMMAND [ARGS]...\n\nOptions:\n --help Show this message and exit.\n\nhelp group 1:\n cmd1\n cmd2\n\nhelp group 2:\n cmd3\n cmd4\n\nhelp group 3:\n a_command My command\n\n", "Stephen's answer above gives the general principle. If you only add new commands to a group using add_command, it can be simplified slightly:\nimport click\nimport collections\n\n\nclass SectionedHelpGroup(click.Group):\n \"\"\"Organize commands as sections\"\"\"\n\n def __init__(self, *args, **kwargs):\n self.section_commands = collections.defaultdict(list)\n super().__init__(*args, **kwargs)\n\n def add_command(self, cmd, name=None, section=None):\n self.section_commands[section].append(cmd)\n super().add_command(cmd, name=name)\n\n def format_commands(self, ctx, formatter):\n for group, cmds in self.section_commands.items():\n with formatter.section(group):\n formatter.write_dl(\n [(cmd.name, cmd.get_short_help_str() or \"\") for cmd in cmds]\n )\n\nExample\ndef f(*args, **kwargs):\n click.echo(args, kwargs)\n\ncommands = {\n 'help group 1': [\n click.Command(\"cmd1\", callback=f),\n click.Command(\"cmd2\", callback=f)\n ],\n 'help group 2': [\n click.Command(\"cmd3\", callback=f),\n click.Command(\"cmd4\", callback=f)\n ]\n}\n\n@click.group(\n help=f\"Sectioned Commands CLI\",\n cls=SectionedHelpGroup\n)\ndef cli():\n pass\n\nfor (section, cmds) in commands.items():\n for cmd in cmds:\n cli.add_command(cmd, section=section)\n\nif __name__ == \"__main__\":\n cli()\n\n" ]
[ 3, 0 ]
[]
[]
[ "command_line_interface", "python", "python_click" ]
stackoverflow_0057066951_command_line_interface_python_python_click.txt
Q: Test Google Cloud Function Im asked to test a Google Cloud Function triggered by http through cloud shell using the "curl -m 60 -X GET [url_of_your_function]" commnand. Does anyone know where to find the url of my function? Ive tried the main url of it and many other ideas but get not solution. I cannot find any documentation on Google Cloud as documentation for GCF its very scarse and disorganized. A: See Function URL on the documentation for Cloud Functions. The way to parse the describe result depends on whether you're using 1st or 2nd gen. Once you have the URL, assuming it requires auth, you can: ENDPOINT="$(gcloud functions describe ... )" TOKEN="$(gcloud auth print-identity-token)" curl \ --get \ --header "Authorization: Bearer ${TOKEN}" \ ${ENDPOINT} gcloud includes a command to invoke Cloud Functions directly too: gcloud functions call ...
Test Google Cloud Function
Im asked to test a Google Cloud Function triggered by http through cloud shell using the "curl -m 60 -X GET [url_of_your_function]" commnand. Does anyone know where to find the url of my function? Ive tried the main url of it and many other ideas but get not solution. I cannot find any documentation on Google Cloud as documentation for GCF its very scarse and disorganized.
[ "See Function URL on the documentation for Cloud Functions.\nThe way to parse the describe result depends on whether you're using 1st or 2nd gen.\nOnce you have the URL, assuming it requires auth, you can:\nENDPOINT=\"$(gcloud functions describe ... )\"\nTOKEN=\"$(gcloud auth print-identity-token)\"\n\ncurl \\\n--get \\\n--header \"Authorization: Bearer ${TOKEN}\" \\\n${ENDPOINT}\n\ngcloud includes a command to invoke Cloud Functions directly too:\ngcloud functions call ...\n\n" ]
[ 2 ]
[]
[]
[ "google_cloud_functions", "google_cloud_platform", "google_cloud_shell", "python" ]
stackoverflow_0074549234_google_cloud_functions_google_cloud_platform_google_cloud_shell_python.txt
Q: Popen from python to Cpp process I am trying to create a python script that will send lines into a cpp file running on a while loop and printing the lines received into the console. test.py #test.py import subprocess p = subprocess.Popen('./stdin.out',bufsize=1,stdin=subprocess.PIPE,stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, universal_newlines=True) p.stdin.write('hello world\n') p.stdin.write('hell world\n') p.stdin.write('hel world\n') p.terminate() stdin.cpp //stdin.cpp #include <iostream> int main(){ std::string line; std::cout << "Hello World! from C++" << std::endl; while (getline(std::cin, line)) { std::cout <<"Received from python:" << line << std::endl; } return 0; } Is this achievable? A: You have two problems. The first is that the python script terminates the subprocess before it has a chance to run. The second is that you pipe stdout and err to DEVNULL, so even if it did run, you wouldn't see anything. Normally, when you are done communicating with a subprocess, you close stdin. The subprocess can read stdin at its leasure and discover the close naturally at the end of input. Then wait for it to exit. #!/usr/bin/env python3 #test.py import subprocess p = subprocess.Popen('./wc',bufsize=1,stdin=subprocess.PIPE, universal_newlines=True) p.stdin.write('hello world\n') p.stdin.write('hell world\n') p.stdin.write('hel world\n') p.stdin.close() p.wait()
Popen from python to Cpp process
I am trying to create a python script that will send lines into a cpp file running on a while loop and printing the lines received into the console. test.py #test.py import subprocess p = subprocess.Popen('./stdin.out',bufsize=1,stdin=subprocess.PIPE,stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, universal_newlines=True) p.stdin.write('hello world\n') p.stdin.write('hell world\n') p.stdin.write('hel world\n') p.terminate() stdin.cpp //stdin.cpp #include <iostream> int main(){ std::string line; std::cout << "Hello World! from C++" << std::endl; while (getline(std::cin, line)) { std::cout <<"Received from python:" << line << std::endl; } return 0; } Is this achievable?
[ "You have two problems. The first is that the python script terminates the subprocess before it has a chance to run. The second is that you pipe stdout and err to DEVNULL, so even if it did run, you wouldn't see anything. Normally, when you are done communicating with a subprocess, you close stdin. The subprocess can read stdin at its leasure and discover the close naturally at the end of input. Then wait for it to exit.\n#!/usr/bin/env python3\n#test.py\nimport subprocess\n\np = subprocess.Popen('./wc',bufsize=1,stdin=subprocess.PIPE, universal_newlines=True)\n\np.stdin.write('hello world\\n')\np.stdin.write('hell world\\n')\np.stdin.write('hel world\\n')\np.stdin.close()\np.wait()\n\n" ]
[ 1 ]
[]
[]
[ "c++", "python", "subprocess" ]
stackoverflow_0074549489_c++_python_subprocess.txt
Q: ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects Python version: 3.11 Installing dependencies for an application by pip install -r requirements.txt gives the following error: socket.c -o build/temp.linux-armv8l-cpython-311/aiohttp/_websocket.o aiohttp/_websocket.c:198:12: fatal error: 'longintrepr.h' file not found #include "longintrepr.h" ^~~~~~~ 1 error generated. error: command '/data/data/com.termux/files/usr/bin/arm-linux-androideabi-clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for aiohttp Failed to build aiohttp ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects This error is specific to Python 3.11 version. On Python with 3.10.6 version installation goes fine. Related question: yarl/_quoting.c:196:12: fatal error: 'longintrepr.h' file not found - 1 error generated A: Solution for this error: need to update requirements.txt. Not working versions of modules with Python 3.11: aiohttp==3.8.1 yarl==1.4.2 frozenlist==1.3.0 Working versions: aiohttp==3.8.2 yarl==1.8.1 frozenlist==1.3.1 Links to the corresponding issues with fixes: https://github.com/aio-libs/aiohttp/issues/6600 https://github.com/aio-libs/yarl/issues/706 https://github.com/aio-libs/frozenlist/issues/305
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects
Python version: 3.11 Installing dependencies for an application by pip install -r requirements.txt gives the following error: socket.c -o build/temp.linux-armv8l-cpython-311/aiohttp/_websocket.o aiohttp/_websocket.c:198:12: fatal error: 'longintrepr.h' file not found #include "longintrepr.h" ^~~~~~~ 1 error generated. error: command '/data/data/com.termux/files/usr/bin/arm-linux-androideabi-clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for aiohttp Failed to build aiohttp ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects This error is specific to Python 3.11 version. On Python with 3.10.6 version installation goes fine. Related question: yarl/_quoting.c:196:12: fatal error: 'longintrepr.h' file not found - 1 error generated
[ "Solution for this error: need to update requirements.txt.\nNot working versions of modules with Python 3.11:\naiohttp==3.8.1\nyarl==1.4.2\nfrozenlist==1.3.0\n\nWorking versions:\naiohttp==3.8.2\nyarl==1.8.1\nfrozenlist==1.3.1\n\nLinks to the corresponding issues with fixes:\n\nhttps://github.com/aio-libs/aiohttp/issues/6600\nhttps://github.com/aio-libs/yarl/issues/706\nhttps://github.com/aio-libs/frozenlist/issues/305\n\n" ]
[ 0 ]
[]
[]
[ "aiohttp", "linux", "pip", "python", "termux" ]
stackoverflow_0074550830_aiohttp_linux_pip_python_termux.txt
Q: Django user is_authenticated vs. is_active: when should I use one or the other? After reading the documentation, I still don't fully grasp the difference between these two User methods: is_active and is_authenticated. Both are returning a boolean. While is_authenticated is read-only (and you get an error if you try to set it), is_active can be modified and for instance you can set it to False instead of deleting account. Running these commands, will de-activate a user: >>> from django.contrib.auth.models import User >>> u = User.objects.get(pk=10) # get an arbitrary user >>> u.is_active True >>> u.is_active = False # change the value >>> u.save() # save to make effective >>> u.is_authenticated True Now, this user is still authenticated but is not able to login anymore. The login view uses authenticate(). What is actually happening that the login for a de-activated user fails? if request.method == 'POST': username = request.POST['username'] password = request.POST['password1'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) To verify the credentials you use authenticate() which returns a User object in case of success or None otherwise. I guess it returns None in case the supplied credentials are correct but is_active is False. In addition, the Jinja block {% if user.is_authenticated %} evaluates as false if is_active is False, which is confusing when I think that user.is_authenticated is True and read-only. Question recap: When a user is de-activated, is_active is false and is_authenticated is (always) true. What is actually authenticate() checking if the user is not active but authenticated? Is it because is_authenticated is an alias for checking that the user exists? But then why is {% user.is_authenticated %} even false? A: is_active is an attribute on user accounts which can be flipped on and off. You can do that in the admin interface, or programmatically. Only active users are allowed to log in. I.e. you can use the is_active flag to prevent a user from logging in without needing to change their password, delete their account, or do anything else drastic. is_authenticated is an attribute of the specific user class being used. If you have actual User objects, their is_authenticated attribute is always true; it's a statically set attribute on the User class. The is_authenticated attribute is relevant only on user objects on requests: def view(request): if request.user.is_authenticated: ... If the user of the request was not authenticated, request.user would not be a User object, but an AnonymousUser object, whose is_authenticated attribute is always False. The idea here is that request.user always exists, regardless of whether a user is currently authenticated or not. This means you don't need to write code like if request.user is not None and request.user..... You can always expect a user object to exist, and you can distinguish between authenticated and unauthenticated (anonymous) users with the is_authenticated attribute.
Django user is_authenticated vs. is_active: when should I use one or the other?
After reading the documentation, I still don't fully grasp the difference between these two User methods: is_active and is_authenticated. Both are returning a boolean. While is_authenticated is read-only (and you get an error if you try to set it), is_active can be modified and for instance you can set it to False instead of deleting account. Running these commands, will de-activate a user: >>> from django.contrib.auth.models import User >>> u = User.objects.get(pk=10) # get an arbitrary user >>> u.is_active True >>> u.is_active = False # change the value >>> u.save() # save to make effective >>> u.is_authenticated True Now, this user is still authenticated but is not able to login anymore. The login view uses authenticate(). What is actually happening that the login for a de-activated user fails? if request.method == 'POST': username = request.POST['username'] password = request.POST['password1'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) To verify the credentials you use authenticate() which returns a User object in case of success or None otherwise. I guess it returns None in case the supplied credentials are correct but is_active is False. In addition, the Jinja block {% if user.is_authenticated %} evaluates as false if is_active is False, which is confusing when I think that user.is_authenticated is True and read-only. Question recap: When a user is de-activated, is_active is false and is_authenticated is (always) true. What is actually authenticate() checking if the user is not active but authenticated? Is it because is_authenticated is an alias for checking that the user exists? But then why is {% user.is_authenticated %} even false?
[ "is_active is an attribute on user accounts which can be flipped on and off. You can do that in the admin interface, or programmatically. Only active users are allowed to log in. I.e. you can use the is_active flag to prevent a user from logging in without needing to change their password, delete their account, or do anything else drastic.\nis_authenticated is an attribute of the specific user class being used. If you have actual User objects, their is_authenticated attribute is always true; it's a statically set attribute on the User class.\nThe is_authenticated attribute is relevant only on user objects on requests:\ndef view(request):\n if request.user.is_authenticated:\n ...\n\nIf the user of the request was not authenticated, request.user would not be a User object, but an AnonymousUser object, whose is_authenticated attribute is always False. The idea here is that request.user always exists, regardless of whether a user is currently authenticated or not. This means you don't need to write code like if request.user is not None and request.user..... You can always expect a user object to exist, and you can distinguish between authenticated and unauthenticated (anonymous) users with the is_authenticated attribute.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074550184_django_python.txt
Q: pygame surface isn't visible I'm currently trying to follow the Introduction to Pygame tutorial and I'm stuck on one step where the speaker makes the surface. His surface is bright red while my surface isn't visible at all. Here's the code: import pygame from sys import exit pygame.init() screen = pygame.display.set_mode((800, 400)) pygame.display.set_caption('Runner') clock = pygame.time.Clock() test_surface = pygame.Surface((100, 200)) test_surface.fill('Red') while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() screen.blit(test_surface, (0, 0)) pygame.display.update() clock.tick(60) I've already tried starting from the very beginning, my code and the steps I make are identical to his. I've also tried deleting python and pygame. I've installed Python version that the speaker has (3.9), but nothing helps. A: It is a matter of indentation. You have draw the scene and update the display in the application loop: import pygame from sys import exit pygame.init() screen = pygame.display.set_mode((800, 400)) pygame.display.set_caption('Runner') clock = pygame.time.Clock() test_surface = pygame.Surface((100, 200)) test_surface.fill('Red') while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() # INDENTATION #<------| screen.blit(test_surface, (0, 0)) pygame.display.update() clock.tick(60)
pygame surface isn't visible
I'm currently trying to follow the Introduction to Pygame tutorial and I'm stuck on one step where the speaker makes the surface. His surface is bright red while my surface isn't visible at all. Here's the code: import pygame from sys import exit pygame.init() screen = pygame.display.set_mode((800, 400)) pygame.display.set_caption('Runner') clock = pygame.time.Clock() test_surface = pygame.Surface((100, 200)) test_surface.fill('Red') while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() screen.blit(test_surface, (0, 0)) pygame.display.update() clock.tick(60) I've already tried starting from the very beginning, my code and the steps I make are identical to his. I've also tried deleting python and pygame. I've installed Python version that the speaker has (3.9), but nothing helps.
[ "It is a matter of indentation. You have draw the scene and update the display in the application loop:\nimport pygame\nfrom sys import exit\n\npygame.init()\nscreen = pygame.display.set_mode((800, 400))\npygame.display.set_caption('Runner')\nclock = pygame.time.Clock()\n\ntest_surface = pygame.Surface((100, 200))\ntest_surface.fill('Red')\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit()\n\n # INDENTATION\n #<------|\n\n screen.blit(test_surface, (0, 0))\n\n pygame.display.update()\n clock.tick(60)\n\n" ]
[ 0 ]
[]
[]
[ "pygame", "pygame_surface", "python" ]
stackoverflow_0074550877_pygame_pygame_surface_python.txt
Q: Not able to split the string properly using Regular Expression in python I'm using a regex pattern to split some strings based on pipe as the delimiter. Most of the strings were able to split correctly as per my requirement, but one type of string is not splitting correctly. Delimiter I'm considering is pipe and the rule is that if a pipe or other special character such as \ or " is present or enclosed in a double quotes inside the string, then split should not happen there. The regex pattern which I'm using is: pattern = r'"?\|(?!(?:(?<=[A-Za-z]\|)|(?<=[A-Za-z]\\\|))(?=[a-zA-Z]))"?' And some of the input string values are as follows for which it is working as expected: text = r'ced"|"ms|n"|4|98' print( re.split(pattern, text) ) # => ['ced', 'ms|n', '4', '98'] text = r'ced"|"ms\|n"|4|98' print( re.split(pattern, text) ) # => ['ced', 'ms\\|n', '4', '98'] text = r'2|dgx|3|abc' print( re.split(pattern, text) ) # => ['2', 'dgx', '3', 'ksfh'] However for the below input string, this regex is not splitting the string as expected. text = r'2|dgx|abc|3' print( re.split(pattern, text) ) # => ['2', 'dgx|abc', '3'] Instead of the above output , I'm expecting the output to be of ['2', 'dgx', 'abc', '3']. Is there any way by which I can achieve this by somehow modifying the same regex pattern that I'm currently using for rest of the above input strings? A: You can use an extracting approach using "\|"?(.*?)"(?=\|)|([^"|]+) See the regex demo. Details: "\|"? - a "| or "|" substring (.*?) - Group 1: any zero or more chars other than line break chars as few as possible " - a " char (?=\|) - a positive lookahead that requires a | char immediately on the right | - or ([^"|]+) - Group 2: any one or more chars other than " and |. See the Python demo: import re rx = re.compile(r'"\|"?(.*?)"(?=\|)|([^"|]+)') texts = [r'ced"|"ms|n"|4|98', r'ced"|"ms\|n"|4|98', r'2|dgx|3|abc', r'2|dgx|abc|3'] for text in texts: print([f'{x}{y}' for x, y in rx.findall(text)]) Output: ['ced', 'ms|n', '4', '98'] ['ced', 'ms\\|n', '4', '98'] ['2', 'dgx', '3', 'abc'] ['2', 'dgx', 'abc', '3']
Not able to split the string properly using Regular Expression in python
I'm using a regex pattern to split some strings based on pipe as the delimiter. Most of the strings were able to split correctly as per my requirement, but one type of string is not splitting correctly. Delimiter I'm considering is pipe and the rule is that if a pipe or other special character such as \ or " is present or enclosed in a double quotes inside the string, then split should not happen there. The regex pattern which I'm using is: pattern = r'"?\|(?!(?:(?<=[A-Za-z]\|)|(?<=[A-Za-z]\\\|))(?=[a-zA-Z]))"?' And some of the input string values are as follows for which it is working as expected: text = r'ced"|"ms|n"|4|98' print( re.split(pattern, text) ) # => ['ced', 'ms|n', '4', '98'] text = r'ced"|"ms\|n"|4|98' print( re.split(pattern, text) ) # => ['ced', 'ms\\|n', '4', '98'] text = r'2|dgx|3|abc' print( re.split(pattern, text) ) # => ['2', 'dgx', '3', 'ksfh'] However for the below input string, this regex is not splitting the string as expected. text = r'2|dgx|abc|3' print( re.split(pattern, text) ) # => ['2', 'dgx|abc', '3'] Instead of the above output , I'm expecting the output to be of ['2', 'dgx', 'abc', '3']. Is there any way by which I can achieve this by somehow modifying the same regex pattern that I'm currently using for rest of the above input strings?
[ "You can use an extracting approach using\n\"\\|\"?(.*?)\"(?=\\|)|([^\"|]+)\n\nSee the regex demo. Details:\n\n\"\\|\"? - a \"| or \"|\" substring\n(.*?) - Group 1: any zero or more chars other than line break chars as few as possible\n\" - a \" char\n(?=\\|) - a positive lookahead that requires a | char immediately on the right\n| - or\n([^\"|]+) - Group 2: any one or more chars other than \" and |.\n\nSee the Python demo:\nimport re\nrx = re.compile(r'\"\\|\"?(.*?)\"(?=\\|)|([^\"|]+)')\ntexts = [r'ced\"|\"ms|n\"|4|98',\n r'ced\"|\"ms\\|n\"|4|98',\n r'2|dgx|3|abc',\n r'2|dgx|abc|3']\nfor text in texts:\n print([f'{x}{y}' for x, y in rx.findall(text)])\n\nOutput:\n['ced', 'ms|n', '4', '98']\n['ced', 'ms\\\\|n', '4', '98']\n['2', 'dgx', '3', 'abc']\n['2', 'dgx', 'abc', '3']\n\n" ]
[ 0 ]
[]
[]
[ "list", "python", "regex", "split", "string" ]
stackoverflow_0074550840_list_python_regex_split_string.txt
Q: turn function add(1, 4) into (add, 1, 4) I have been experimenting with using functions to make a mini programming language, but can't find out how to turn the function add(1, 4) into (add, 1, 4) So far I have this: mem = {} def inp(text): return(input(text)) def store(name, value): mem[str(name)] = value def get(name): return(mem[str(name)]) def ifel(con, exp1, exp2): if con == True: return(exp1) else: return(exp2) def add(*args): return(sum(args)) def sub(*args): last = 0 for each in args: last = last - each return(last) def dev(*args): last = 0 for index, each in enumerate(args): if index == 0: last = each else: last = last / each return(last) def mul(*args): last = 0 for index, each in enumerate(args): if index == 0: last = each else: last = last * each return(last) def power(*args): last = 0 for index, each in enumerate(args): if index == 0: last = each else: last = pow(last, each) return(last) def root(*args): last = 0 for index, each in enumerate(args): if index == 0: last = each else: last = pow(last, (1 / each)) return(last) def say(t): print(t) print((5 * (9 ** 4)) / 3) say(dev(mul(5, power(9, 4)), 3)) I would like to be able to write this as: (say, (dev, (mul, 5, (power, 9, 5)), 3)) or (say (dev (mul 5 (power 9 5)) 3)) How could I call a function with the first place in the parentheses? I got inspiration from Lisp syntax, and am trying to recreate my own version. A: You're either making a fairly basic mistake or attempting something very nuanced and difficult. :) Assuming the former: You need to be clear about the difference between python syntax and your syntax. Functions in your syntax are generally not going to be python functions (there's some nuance there) - they'll be values, and you'll have something like an interp(...) function that actually interprets them. Because python functions are values, there can be some overlap here - (add, 3, 4) could be treated as a tuple whose first value is a function. Pretending all your functions were binary operations, you could have something like: def interp(someFunction, arg1, arg2): someFunction(interp(arg1), interp(arg2)) with some other code to handle the base case of literal values. (Or do varargs and have literals as 0-argument functions that return the literal.) More commonly you'd just have add, etc, by something more akin to an enum, and interp would match on each case: def interp(term): match term: case(ADD, arg1, arg2): return interp(arg1) + interp(arg2) Generally speaking, this will be easier to serialize and inspect than having actual lambdas. The Advanced Thing: You're almost certainly not doing this, but there is such a thing as a "quoted DSL" which is a domain-specific language written as an extension of the host language. Implementing them is much more involved, but they have the advantage of benefiting from the development environment and features of the host language. (For instance, you can use them to get syntax completion and error highlighting in your DSL without taking on the very difficult task of writing such yourself.)
turn function add(1, 4) into (add, 1, 4)
I have been experimenting with using functions to make a mini programming language, but can't find out how to turn the function add(1, 4) into (add, 1, 4) So far I have this: mem = {} def inp(text): return(input(text)) def store(name, value): mem[str(name)] = value def get(name): return(mem[str(name)]) def ifel(con, exp1, exp2): if con == True: return(exp1) else: return(exp2) def add(*args): return(sum(args)) def sub(*args): last = 0 for each in args: last = last - each return(last) def dev(*args): last = 0 for index, each in enumerate(args): if index == 0: last = each else: last = last / each return(last) def mul(*args): last = 0 for index, each in enumerate(args): if index == 0: last = each else: last = last * each return(last) def power(*args): last = 0 for index, each in enumerate(args): if index == 0: last = each else: last = pow(last, each) return(last) def root(*args): last = 0 for index, each in enumerate(args): if index == 0: last = each else: last = pow(last, (1 / each)) return(last) def say(t): print(t) print((5 * (9 ** 4)) / 3) say(dev(mul(5, power(9, 4)), 3)) I would like to be able to write this as: (say, (dev, (mul, 5, (power, 9, 5)), 3)) or (say (dev (mul 5 (power 9 5)) 3)) How could I call a function with the first place in the parentheses? I got inspiration from Lisp syntax, and am trying to recreate my own version.
[ "You're either making a fairly basic mistake or attempting something very nuanced and difficult. :)\nAssuming the former: You need to be clear about the difference between python syntax and your syntax. Functions in your syntax are generally not going to be python functions (there's some nuance there) - they'll be values, and you'll have something like an interp(...) function that actually interprets them.\nBecause python functions are values, there can be some overlap here - (add, 3, 4) could be treated as a tuple whose first value is a function. Pretending all your functions were binary operations, you could have something like:\ndef interp(someFunction, arg1, arg2):\n someFunction(interp(arg1), interp(arg2))\n\nwith some other code to handle the base case of literal values. (Or do varargs and have literals as 0-argument functions that return the literal.)\nMore commonly you'd just have add, etc, by something more akin to an enum, and interp would match on each case:\ndef interp(term):\n match term:\n case(ADD, arg1, arg2): return interp(arg1) + interp(arg2)\n\nGenerally speaking, this will be easier to serialize and inspect than having actual lambdas.\nThe Advanced Thing:\nYou're almost certainly not doing this, but there is such a thing as a \"quoted DSL\" which is a domain-specific language written as an extension of the host language. Implementing them is much more involved, but they have the advantage of benefiting from the development environment and features of the host language. (For instance, you can use them to get syntax completion and error highlighting in your DSL without taking on the very difficult task of writing such yourself.)\n" ]
[ 0 ]
[]
[]
[ "for_loop", "function", "math", "notation", "python" ]
stackoverflow_0074550781_for_loop_function_math_notation_python.txt
Q: How can I mock patch a class used in an isinstance test? I want to test the function is_myclass. Please help me understand how to write a successful test. def is_myclass(obj): """This absurd stub is a simplified version of the production code.""" isinstance(obj, MyClass) MyClass() Docs The Python Docs for unittest.mock illustrate three ways of addressing the isinstance problem: Set the spec parameter to the real class. Assign the real class to the __class__ attribute. Use spec in the patch of the real class. __class__ Normally the __class__ attribute of an object will return its type. For a mock object with a spec, __class__ returns the spec class instead. This allows mock objects to pass isinstance() tests for the object they are replacing / masquerading as: >>> mock = Mock(spec=3) >>> isinstance(mock, int) True __class__ is assignable to, this allows a mock to pass an isinstance() check without forcing you to use a spec: >>> mock = Mock() >>> mock.__class__ = dict >>> isinstance(mock, dict) True [...] If you use spec or spec_set and patch() is replacing a class, then the return value of the created mock will have the same spec. >>> Original = Class >>> patcher = patch('__main__.Class', spec=True) >>> MockClass = patcher.start() >>> instance = MockClass() >>> assert isinstance(instance, Original) >>> patcher.stop() Tests I have written five tests each of which attempts firstly to reproduce each of the three solutions and secondly to carry out a realistic test of the target code. The typical pattern is assert isinstance followed by a call to is_myclass. All tests fail. Test 1 This is a close copy of the example provided in the docs for the use of spec. It differs from the docs by using spec=<class> instead of spec=<instance>. It passes a local assert test but the call to is_myclass fails because MyClass is not mocked. This is equivalent to Michele d’Amico’s answer to the similar question in isinstance and Mocking . Test 2 This is the patched equivalent of test 1. The spec argument fails to set the __class__ of the mocked MyClass and the test fails the local assert isinstance. Test 3 This is a close copy of the example provided in the docs for the use of __class__. It passes a local assert test but the call to is_myclass fails because MyClass is not mocked. Test 4 This is the patched equivalent of test 3. The assignment to __class__ does set the __class__ of the mocked MyClass but this does not change its type and so the test fails the local assert isinstance. Test 5 This is a close copy of the use of spec in a call to patch. It passes the local assert test but only by virtue of accessing a local copy of MyClass. Since this local variable is not used within is_myclass the call fails. Code This code was written as a stand alone test module intended to be run in the PyCharm IDE. You may need to modify it to run in other test environments. module temp2.py import unittest import unittest.mock as mock class WrongCodeTested(Exception): pass class MyClass: def __init__(self): """This is a simplified version of a production class which must be mocked for unittesting.""" raise WrongCodeTested('Testing code in MyClass.__init__') def is_myclass(obj): """This absurd stub is a simplified version of the production code.""" isinstance(obj, MyClass) MyClass() class ExamplesFromDocs(unittest.TestCase): def test_1_spec(self): obj = mock.Mock(spec=MyClass) print(type(MyClass)) # <class 'type'> assert isinstance(obj, MyClass) # Local assert test passes is_myclass(obj) # Fail: MyClass instantiated def test_2_spec_patch(self): with mock.patch('temp2.MyClass', spec=True) as mock_myclass: obj = mock_myclass() print(type(mock_myclass)) # <class 'unittest.mock.MagicMock'> print(type(MyClass)) # <class 'unittest.mock.MagicMock'> assert isinstance(obj, MyClass) # Local assert test fails def test_3__class__(self): obj = mock.Mock() obj.__class__ = MyClass print(type(MyClass)) # <class 'type'> isinstance(obj, MyClass) # Local assert test passes is_myclass(obj) # Fail: MyClass instantiated def test_4__class__patch(self): Original = MyClass with mock.patch('temp2.MyClass') as mock_myclass: mock_myclass.__class__ = Original obj = mock_myclass() obj.__class__ = Original print(MyClass.__class__) # <class 'temp2.MyClass'> print(type(MyClass)) # <class 'unittest.mock.MagicMock'> assert isinstance(obj, MyClass) # Local assert test fails def test_5_patch_with_spec(self): Original = MyClass p = mock.patch('temp2.MyClass', spec=True) MockMyClass = p.start() obj = MockMyClass() print(type(Original)) # <class 'type'> print(type(MyClass)) # <class 'unittest.mock.MagicMock'> print(type(MockMyClass)) # <class 'unittest.mock.MagicMock'> assert isinstance(obj, Original) # Local assert test passes is_myclass(obj) # Fail: Bad type for MyClass A: You can't mock the second argument of isinstance(), no. The documentation you found concerns making a mock as the first argument pass the test. If you want to produce something that is acceptable as the second argument to isinstance(), you actually have to have a type, not an instance (and mocks are always instances). You could use a subclass instead of MyClass instead, that'll definitely pass, and giving it a __new__ method lets you alter what is returned when you try to call it to create an instance: class MockedSubClass(MyClass): def __new__(cls, *args, **kwargs): return mock.Mock(spec=cls) # produce a mocked instance when called and patch that in: mock.patch('temp2.MyClass', new=MockedSubClass) and use an instance of that class as the mock: instance = mock.Mock(spec=MockedSubClass) Or, and this is much simpler, just use Mock as the class, and have obj be an Mock instance: with mock.patch('temp2.MyClass', new=mock.Mock) as mocked_class: is_myclass(mocked_class()) Either way, your test then passes: >>> with mock.patch('temp2.MyClass', new=MockedSubClass) as mocked_class: ... instance = mock.Mock(spec=MockedSubClass) ... assert isinstance(instance, mocked_class) ... is_myclass(instance) ... >>> # no exceptions raised! ... >>> with mock.patch('temp2.MyClass', new=mock.Mock) as mocked_class: ... is_myclass(mocked_class()) ... >>> # no exceptions raised! ... For your specific tests, here is why they fail: You never mocked MyClass, it still references the original class. The first line of is_myclass() succeeds, but the second line uses the original MyClass and it is booby trapped. MyClass is replaced with a mock.Mock instance, not an actual type, so isinstance() raises a TypeError: isinstance() arg 2 must be a type or tuple of types exception. Fails exactly the same way 1 failed, MyClass is left in-tact and is booby trapped. Fails the same way as 2 does. __class__ is an attribute only useful on instances. A class object doesn't use the __class__ attribute, you still have an instance instead of a class and isinstance() raises a type error. is essentially exactly the same as 4, only you started the patcher manually instead of having the context manager take care of it, and you used isinstance(obj, Original) to check the instance, so you never got the type error there. The type error is instead triggered in is_myclass(). A: @Martijn Pieters has an excellent answer, I just thought I'd add how I accomplished this with decoraters: import temp2 class MockedMyClass: pass class MockedMySubClass(MockedMyClass): pass @patch("temp2.MyClass", new=MockedMyClass) def test_is_subclass(self): assert issubclass(MockedMySubClass, temp2.MyClass) NOTE: Even though a decorator is used, the test does not require any additional arguments. A: Here is a way you can use auto_spec on a mocked class and still be able to call isinstance. def get_mock_ability_class(): class MockAbility(Ability): def __new__(cls, *args, **kwargs): return mock.create_autospec(MockAbility, *args, **kwargs) return MockAbility MockAbility = get_mock_ability_class() AnotherMockAbility = get_mock_ability_class() m = MockAbility() a = AnotherMockAbility() isinstance(m, MockAbility) # True isinstance(a, MockAbility) # False # Ability has a forget method m.forget() m.forget.assert_called_once() credit to Perry Goy for coming up with this
How can I mock patch a class used in an isinstance test?
I want to test the function is_myclass. Please help me understand how to write a successful test. def is_myclass(obj): """This absurd stub is a simplified version of the production code.""" isinstance(obj, MyClass) MyClass() Docs The Python Docs for unittest.mock illustrate three ways of addressing the isinstance problem: Set the spec parameter to the real class. Assign the real class to the __class__ attribute. Use spec in the patch of the real class. __class__ Normally the __class__ attribute of an object will return its type. For a mock object with a spec, __class__ returns the spec class instead. This allows mock objects to pass isinstance() tests for the object they are replacing / masquerading as: >>> mock = Mock(spec=3) >>> isinstance(mock, int) True __class__ is assignable to, this allows a mock to pass an isinstance() check without forcing you to use a spec: >>> mock = Mock() >>> mock.__class__ = dict >>> isinstance(mock, dict) True [...] If you use spec or spec_set and patch() is replacing a class, then the return value of the created mock will have the same spec. >>> Original = Class >>> patcher = patch('__main__.Class', spec=True) >>> MockClass = patcher.start() >>> instance = MockClass() >>> assert isinstance(instance, Original) >>> patcher.stop() Tests I have written five tests each of which attempts firstly to reproduce each of the three solutions and secondly to carry out a realistic test of the target code. The typical pattern is assert isinstance followed by a call to is_myclass. All tests fail. Test 1 This is a close copy of the example provided in the docs for the use of spec. It differs from the docs by using spec=<class> instead of spec=<instance>. It passes a local assert test but the call to is_myclass fails because MyClass is not mocked. This is equivalent to Michele d’Amico’s answer to the similar question in isinstance and Mocking . Test 2 This is the patched equivalent of test 1. The spec argument fails to set the __class__ of the mocked MyClass and the test fails the local assert isinstance. Test 3 This is a close copy of the example provided in the docs for the use of __class__. It passes a local assert test but the call to is_myclass fails because MyClass is not mocked. Test 4 This is the patched equivalent of test 3. The assignment to __class__ does set the __class__ of the mocked MyClass but this does not change its type and so the test fails the local assert isinstance. Test 5 This is a close copy of the use of spec in a call to patch. It passes the local assert test but only by virtue of accessing a local copy of MyClass. Since this local variable is not used within is_myclass the call fails. Code This code was written as a stand alone test module intended to be run in the PyCharm IDE. You may need to modify it to run in other test environments. module temp2.py import unittest import unittest.mock as mock class WrongCodeTested(Exception): pass class MyClass: def __init__(self): """This is a simplified version of a production class which must be mocked for unittesting.""" raise WrongCodeTested('Testing code in MyClass.__init__') def is_myclass(obj): """This absurd stub is a simplified version of the production code.""" isinstance(obj, MyClass) MyClass() class ExamplesFromDocs(unittest.TestCase): def test_1_spec(self): obj = mock.Mock(spec=MyClass) print(type(MyClass)) # <class 'type'> assert isinstance(obj, MyClass) # Local assert test passes is_myclass(obj) # Fail: MyClass instantiated def test_2_spec_patch(self): with mock.patch('temp2.MyClass', spec=True) as mock_myclass: obj = mock_myclass() print(type(mock_myclass)) # <class 'unittest.mock.MagicMock'> print(type(MyClass)) # <class 'unittest.mock.MagicMock'> assert isinstance(obj, MyClass) # Local assert test fails def test_3__class__(self): obj = mock.Mock() obj.__class__ = MyClass print(type(MyClass)) # <class 'type'> isinstance(obj, MyClass) # Local assert test passes is_myclass(obj) # Fail: MyClass instantiated def test_4__class__patch(self): Original = MyClass with mock.patch('temp2.MyClass') as mock_myclass: mock_myclass.__class__ = Original obj = mock_myclass() obj.__class__ = Original print(MyClass.__class__) # <class 'temp2.MyClass'> print(type(MyClass)) # <class 'unittest.mock.MagicMock'> assert isinstance(obj, MyClass) # Local assert test fails def test_5_patch_with_spec(self): Original = MyClass p = mock.patch('temp2.MyClass', spec=True) MockMyClass = p.start() obj = MockMyClass() print(type(Original)) # <class 'type'> print(type(MyClass)) # <class 'unittest.mock.MagicMock'> print(type(MockMyClass)) # <class 'unittest.mock.MagicMock'> assert isinstance(obj, Original) # Local assert test passes is_myclass(obj) # Fail: Bad type for MyClass
[ "You can't mock the second argument of isinstance(), no. The documentation you found concerns making a mock as the first argument pass the test. If you want to produce something that is acceptable as the second argument to isinstance(), you actually have to have a type, not an instance (and mocks are always instances).\nYou could use a subclass instead of MyClass instead, that'll definitely pass, and giving it a __new__ method lets you alter what is returned when you try to call it to create an instance:\nclass MockedSubClass(MyClass):\n def __new__(cls, *args, **kwargs):\n return mock.Mock(spec=cls) # produce a mocked instance when called\n\nand patch that in:\nmock.patch('temp2.MyClass', new=MockedSubClass)\n\nand use an instance of that class as the mock:\ninstance = mock.Mock(spec=MockedSubClass)\n\nOr, and this is much simpler, just use Mock as the class, and have obj be an Mock instance:\nwith mock.patch('temp2.MyClass', new=mock.Mock) as mocked_class:\n is_myclass(mocked_class())\n\nEither way, your test then passes:\n>>> with mock.patch('temp2.MyClass', new=MockedSubClass) as mocked_class:\n... instance = mock.Mock(spec=MockedSubClass)\n... assert isinstance(instance, mocked_class)\n... is_myclass(instance)\n...\n>>> # no exceptions raised!\n...\n>>> with mock.patch('temp2.MyClass', new=mock.Mock) as mocked_class:\n... is_myclass(mocked_class())\n...\n>>> # no exceptions raised!\n...\n\n\nFor your specific tests, here is why they fail:\n\nYou never mocked MyClass, it still references the original class. The first line of is_myclass() succeeds, but the second line uses the original MyClass and it is booby trapped.\nMyClass is replaced with a mock.Mock instance, not an actual type, so isinstance() raises a TypeError: isinstance() arg 2 must be a type or tuple of types exception.\nFails exactly the same way 1 failed, MyClass is left in-tact and is booby trapped.\nFails the same way as 2 does. __class__ is an attribute only useful on instances. A class object doesn't use the __class__ attribute, you still have an instance instead of a class and isinstance() raises a type error.\nis essentially exactly the same as 4, only you started the patcher manually instead of having the context manager take care of it, and you used isinstance(obj, Original) to check the instance, so you never got the type error there. The type error is instead triggered in is_myclass().\n\n", "@Martijn Pieters has an excellent answer, I just thought I'd add how I accomplished this with decoraters:\nimport temp2\n\nclass MockedMyClass:\n pass\n\nclass MockedMySubClass(MockedMyClass):\n pass\n\n@patch(\"temp2.MyClass\", new=MockedMyClass)\ndef test_is_subclass(self):\n assert issubclass(MockedMySubClass, temp2.MyClass)\n\nNOTE: Even though a decorator is used, the test does not require any additional arguments.\n", "Here is a way you can use auto_spec on a mocked class and still be able to call isinstance.\ndef get_mock_ability_class():\n\n class MockAbility(Ability):\n def __new__(cls, *args, **kwargs):\n return mock.create_autospec(MockAbility, *args, **kwargs)\n return MockAbility\n\nMockAbility = get_mock_ability_class()\nAnotherMockAbility = get_mock_ability_class()\n\nm = MockAbility()\na = AnotherMockAbility()\nisinstance(m, MockAbility) # True\nisinstance(a, MockAbility) # False\n\n# Ability has a forget method\nm.forget()\nm.forget.assert_called_once()\n\n\ncredit to Perry Goy for coming up with this\n" ]
[ 6, 0, 0 ]
[]
[]
[ "mocking", "python", "python_unittest", "unit_testing" ]
stackoverflow_0049718428_mocking_python_python_unittest_unit_testing.txt
Q: Why url_for generates URL with localhost as the hostname instead of the domain name? I have a FastAPI web application using Jinja2 templates, which is working fine on localhost, but not in production. The problem is that is not generating URLs for JavaScript and other static files correctly. I have deployed it on EC2 instance using gunicorn and nginx. I have this line of code in my HTML file: <script src="{{ url_for('static', path='js/login_signup.js') }}"></script> The problem is that it is generating the URL like this: <script src="http://127.0.0.1:8000/static/js/login_signup.js"></script> What I want is to generate something like this: <script src="http://my_domain.com/static/js/login_signup.js"></script> A: Serve on 0.0.0.0 instead of 127.0.0.1. If you're using uvicorn which is the default web server for FastAPI, you need to pass --host 0.0.0.0 when starting the server. For other servers, look up the equivalent flag. A: Since you mentioned that you are using gunicorn, you need to make sure you are binding gunicorn to 0.0.0.0. For example: gunicorn --bind 0.0.0.0:80 Additionally, since you are using Nginx, make sure to configure your "server" config section, as described here: server { server_name example.com location / { proxy_redirect off; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $server_name; ... } listen 443 ssl; If the above does not solve the issue for you, see other options below. Option 1 You can use realtive paths instead, as described here and here. Example: <link href="static/styles.css'" rel="stylesheet"> Option 2 You can create a custom function where you replace the hostname in the URL, and use that function instead inside your Jinja2 templates. If you would also like to include query parameters in the URL, rather than just path parameters, have a look at this answer and this answer. Example: Backend from fastapi import FastAPI, Request from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from typing import Any import urllib app = FastAPI() def my_url_for(request: Request, name: str, **path_params: Any) -> str: url = request.url_for(name, **path_params) parsed = list(urllib.parse.urlparse(url)) parsed[1] = 'my_domain.com' return urllib.parse.urlunparse(parsed) app.mount('/static', StaticFiles(directory='static'), name='static') templates = Jinja2Templates(directory='templates') templates.env.globals['my_url_for'] = my_url_for Frontend <link href="{{ my_url_for(request, 'static', path='/styles.css') }}" rel="stylesheet">
Why url_for generates URL with localhost as the hostname instead of the domain name?
I have a FastAPI web application using Jinja2 templates, which is working fine on localhost, but not in production. The problem is that is not generating URLs for JavaScript and other static files correctly. I have deployed it on EC2 instance using gunicorn and nginx. I have this line of code in my HTML file: <script src="{{ url_for('static', path='js/login_signup.js') }}"></script> The problem is that it is generating the URL like this: <script src="http://127.0.0.1:8000/static/js/login_signup.js"></script> What I want is to generate something like this: <script src="http://my_domain.com/static/js/login_signup.js"></script>
[ "Serve on 0.0.0.0 instead of 127.0.0.1. If you're using uvicorn which is the default web server for FastAPI, you need to pass --host 0.0.0.0 when starting the server. For other servers, look up the equivalent flag.\n", "Since you mentioned that you are using gunicorn, you need to make sure you are binding gunicorn to 0.0.0.0. For example:\ngunicorn --bind 0.0.0.0:80 \n\nAdditionally, since you are using Nginx, make sure to configure your \"server\" config section, as described here:\n server {\n server_name example.com\n location / {\n proxy_redirect off;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-Host $server_name;\n\n ...\n }\n\n\n listen 443 ssl; \n\nIf the above does not solve the issue for you, see other options below.\nOption 1\nYou can use realtive paths instead, as described here and here. Example:\n<link href=\"static/styles.css'\" rel=\"stylesheet\">\n\nOption 2\nYou can create a custom function where you replace the hostname in the URL, and use that function instead inside your Jinja2 templates. If you would also like to include query parameters in the URL, rather than just path parameters, have a look at this answer and this answer. Example:\nBackend\nfrom fastapi import FastAPI, Request\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\nfrom typing import Any\nimport urllib\n\napp = FastAPI()\n\ndef my_url_for(request: Request, name: str, **path_params: Any) -> str:\n url = request.url_for(name, **path_params)\n parsed = list(urllib.parse.urlparse(url))\n parsed[1] = 'my_domain.com'\n return urllib.parse.urlunparse(parsed)\n \n\napp.mount('/static', StaticFiles(directory='static'), name='static')\ntemplates = Jinja2Templates(directory='templates')\ntemplates.env.globals['my_url_for'] = my_url_for\n\nFrontend\n<link href=\"{{ my_url_for(request, 'static', path='/styles.css') }}\" rel=\"stylesheet\">\n\n" ]
[ 0, 0 ]
[]
[]
[ "fastapi", "jinja2", "python", "starlette", "templating" ]
stackoverflow_0074549045_fastapi_jinja2_python_starlette_templating.txt
Q: Else or elif condition executed every time in python code in the nested dictionary I am trying to execute below code wherein I want to insert a key in the dictionary with a particular value on a condition where tos is greater than or less than the value of position key in the dictionary. But in the output I see the else or elif condition executed every time. def convert_csv_to_dataframe_and_then_convert_csv_data_to_dictionary(tos): recs = {0: {'POSITION': 650886123, 'is_valid': False}, 1: {'POSITION': 650886121, 'is_valid': False}} for i in recs: if int(recs[i]['POSITION'])>tos: recs[i]['is_valid']=True elif int(recs[i]['POSITION'])<tos: recs[i]['is_valid'] = False print(recs) convert_csv_to_dataframe_and_then_convert_csv_data_to_dictionary(6508861232) Below is the output. { 0: { 'POSITION': 650886123, 'is_valid': False}, 1: { 'POSITION': 650886121, 'is_valid': False} } I have passed tos as 6508861232 which is greater than 650886123 and the other position key value in the dictionary but the is_valid is not added as True in the dictionary. Am I missing something in the code? A: Your code is working fine: if int(recs[i]['POSITION'])>tos: recs[i]['is_valid']=True elif int(recs[i]['POSITION'])<tos: recs[i]['is_valid'] = False In both the cases int(recs[i]['POSITION'])<tos, thus recs[i]['is_valid'] = False You might want to change the positions of True and False to get desired behavior as: if int(recs[i]['POSITION'])>tos: recs[i]['is_valid'] = False elif int(recs[i]['POSITION'])<tos: recs[i]['is_valid'] = True A: Both the numbers (values of 'POSITION') in your dataframe have 9 digits. The tos has 10 digits. So the output you got is correct.
Else or elif condition executed every time in python code in the nested dictionary
I am trying to execute below code wherein I want to insert a key in the dictionary with a particular value on a condition where tos is greater than or less than the value of position key in the dictionary. But in the output I see the else or elif condition executed every time. def convert_csv_to_dataframe_and_then_convert_csv_data_to_dictionary(tos): recs = {0: {'POSITION': 650886123, 'is_valid': False}, 1: {'POSITION': 650886121, 'is_valid': False}} for i in recs: if int(recs[i]['POSITION'])>tos: recs[i]['is_valid']=True elif int(recs[i]['POSITION'])<tos: recs[i]['is_valid'] = False print(recs) convert_csv_to_dataframe_and_then_convert_csv_data_to_dictionary(6508861232) Below is the output. { 0: { 'POSITION': 650886123, 'is_valid': False}, 1: { 'POSITION': 650886121, 'is_valid': False} } I have passed tos as 6508861232 which is greater than 650886123 and the other position key value in the dictionary but the is_valid is not added as True in the dictionary. Am I missing something in the code?
[ "Your code is working fine:\nif int(recs[i]['POSITION'])>tos:\n recs[i]['is_valid']=True \nelif int(recs[i]['POSITION'])<tos:\n recs[i]['is_valid'] = False\n\nIn both the cases int(recs[i]['POSITION'])<tos, thus\nrecs[i]['is_valid'] = False\nYou might want to change the positions of True and False to get desired behavior as:\nif int(recs[i]['POSITION'])>tos:\n recs[i]['is_valid'] = False \nelif int(recs[i]['POSITION'])<tos:\n recs[i]['is_valid'] = True\n\n", "Both the numbers (values of 'POSITION') in your dataframe have 9 digits. The tos has 10 digits.\nSo the output you got is correct.\n" ]
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074550814_pandas_python.txt
Q: Replacing character in a list with keys from a dictionary of lists I have a dictionary containing lists like char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']} I have another list containing characters word_list = ['r', 'v', 'p', 'c'] I want to replace the letters in word_list with keys in the dictionary so that it should become ['6', '1', '1', '2'] I tried some thing like word_list[:]=[char_code.get(e,'') for e in word_list] A: First, invert the dictionary, so that you can easily look up the digit symbol for a given letter: num_code = { letter: digit for digit, letters in char_code.items() for letter in letters } Then simply use that lookup to do the mapping: word_list[:] = [num_code[letter] for letter in word_list] Which gives us the expected result. A: One way to do it with for looping on word_list and using list comprehension to find each list element inside char_codedictionary and finallyappend` the keys like this- char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']} word_list = ['r', 'v', 'p', 'c'] expected_list = [] for word in word_list: expected_list.append([k for k, v in char_code.items() if word in v][0]) print(expected_list) Output: ['6', '1', '1', '2'] A: Your dictionary isn't structured efficiently to do the kind of lookup you're asking for - it's "inside out". You can do it, but it's clumsy. You want the key to be a letter and it's value to be the code, but you have the other way around. Transform your dictionary and it will simplify your list creation: >>> letter_to_code = {letter: code for code, lst in char_code.items() for letter in lst} >>> [letter_to_code[letter] for letter in word_list] ['6', '1', '1', '2']
Replacing character in a list with keys from a dictionary of lists
I have a dictionary containing lists like char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']} I have another list containing characters word_list = ['r', 'v', 'p', 'c'] I want to replace the letters in word_list with keys in the dictionary so that it should become ['6', '1', '1', '2'] I tried some thing like word_list[:]=[char_code.get(e,'') for e in word_list]
[ "First, invert the dictionary, so that you can easily look up the digit symbol for a given letter:\nnum_code = {\n letter: digit\n for digit, letters in char_code.items()\n for letter in letters\n}\n\nThen simply use that lookup to do the mapping:\nword_list[:] = [num_code[letter] for letter in word_list]\n\nWhich gives us the expected result.\n", "One way to do it with for looping on word_list and using list comprehension to find each list element inside char_codedictionary and finallyappend` the keys like this-\nchar_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']}\n\nword_list = ['r', 'v', 'p', 'c']\nexpected_list = []\nfor word in word_list:\n expected_list.append([k for k, v in char_code.items() if word in v][0])\nprint(expected_list)\n\nOutput:\n['6', '1', '1', '2']\n\n", "Your dictionary isn't structured efficiently to do the kind of lookup you're asking for - it's \"inside out\". You can do it, but it's clumsy. You want the key to be a letter and it's value to be the code, but you have the other way around.\nTransform your dictionary and it will simplify your list creation:\n>>> letter_to_code = {letter: code for code, lst in char_code.items() for letter in lst}\n>>> [letter_to_code[letter] for letter in word_list]\n['6', '1', '1', '2']\n\n" ]
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074550763_python.txt
Q: Python: Incorrect UTC Offset The following code prints: -1 day, 19:00:00 when New York is actually 5 hours behind UTC. What is wrong and how to fix it? import pytz from datetime import datetime date = datetime(2022, 11, 23, 22, 30) tz = pytz.timezone('America/New_York') print(tz.utcoffset(date)) A: tz.utcoffset(date) returns a datetime.timedelta that should be added to a UTC datetime to get local time. Its a negative number for negative UTC offsets so that the addition works. >>> import pytz >>> from datetime import datetime >>> >>> date = datetime(2022, 11, 23, 22, 30) >>> tz = pytz.timezone('America/New_York') >>> offset = tz.utcoffset(date) >>> offset datetime.timedelta(days=-1, seconds=68400) >>> date + offset datetime.datetime(2022, 11, 23, 17, 30) timedelta displays oddly. days=-1, seconds=68400 means to go backwards 1 day and then forward 68400 seconds, giving you that -5 hours. A: If you just want the offset as a string, you can use date = datetime(2022, 11, 23, 22, 30, tzinfo = zoneinfo.ZoneInfo('America/New_York')) print(date.strftime('%z')) This prints: -0500 I'm using Python 3.9 - not sure if the syntax is the same in your version.
Python: Incorrect UTC Offset
The following code prints: -1 day, 19:00:00 when New York is actually 5 hours behind UTC. What is wrong and how to fix it? import pytz from datetime import datetime date = datetime(2022, 11, 23, 22, 30) tz = pytz.timezone('America/New_York') print(tz.utcoffset(date))
[ "tz.utcoffset(date) returns a datetime.timedelta that should be added to a UTC datetime to get local time. Its a negative number for negative UTC offsets so that the addition works.\n>>> import pytz\n>>> from datetime import datetime\n>>> \n>>> date = datetime(2022, 11, 23, 22, 30)\n>>> tz = pytz.timezone('America/New_York')\n>>> offset = tz.utcoffset(date)\n>>> offset\ndatetime.timedelta(days=-1, seconds=68400)\n>>> date + offset\ndatetime.datetime(2022, 11, 23, 17, 30)\n\ntimedelta displays oddly. days=-1, seconds=68400 means to go backwards 1 day and then forward 68400 seconds, giving you that -5 hours.\n", "If you just want the offset as a string, you can use\ndate = datetime(2022, 11, 23, 22, 30, tzinfo = zoneinfo.ZoneInfo('America/New_York'))\nprint(date.strftime('%z'))\n\nThis prints: -0500\nI'm using Python 3.9 - not sure if the syntax is the same in your version.\n" ]
[ 0, 0 ]
[]
[]
[ "datetime", "python", "python_3.x", "pytz", "timezone_offset" ]
stackoverflow_0074550378_datetime_python_python_3.x_pytz_timezone_offset.txt
Q: Python Sequential parallel loop gets stuck in the middle I'm making a sequential parallel loop. It runs for the first time, but ends without running the loop. I don't know which part is wrong. Running the code the value is [2, 3, 3] [2, 2, 3] [2, 2, 2] If I replace it with while statement, I can't get the value I want. [2, 3, 3] [1, 3, 3] [0, 3, 3] [0, 2, 3] [0, 1, 3] [0, 0, 3] [0, 0, 2] [0, 0, 1] [0, 0, 0] This is an invalid value. the value i want is [2, 3, 3] [2, 2, 3] [2, 2, 2] [1, 2, 2] [1, 1, 2] [1, 1, 1] [0, 1, 1] [0, 0, 1] [0, 0, 0] is the value. import time list_a = ['AA','BB','CC'] list_b = ['AAdata','BBdata','CCdata'] dd = 'state' retry_cnt = [3] * len(list_a) for i, symbol in enumerate(list_b): if retry_cnt[i] > 0: dd = 'state' time.sleep(0.2) if 'state' in dd: retry_cnt[i] -= 1 time.sleep(0.2) print(retry_cnt) continue A: Your loop is only executing 3 times because list_b only has 3 elements in it. If you want the whole loop to run 3 times, you could wrap it in another for loop, like so: for x in range(3): for i, symbol in enumerate(list_b): if retry_cnt[i] > 0: dd = 'state' time.sleep(0.2) if 'state' in dd: retry_cnt[i] -= 1 time.sleep(0.2) print(retry_cnt) Also, the continue is probably unnecessary because it is the last instruction in the loop, so it happens automatically.
Python Sequential parallel loop gets stuck in the middle
I'm making a sequential parallel loop. It runs for the first time, but ends without running the loop. I don't know which part is wrong. Running the code the value is [2, 3, 3] [2, 2, 3] [2, 2, 2] If I replace it with while statement, I can't get the value I want. [2, 3, 3] [1, 3, 3] [0, 3, 3] [0, 2, 3] [0, 1, 3] [0, 0, 3] [0, 0, 2] [0, 0, 1] [0, 0, 0] This is an invalid value. the value i want is [2, 3, 3] [2, 2, 3] [2, 2, 2] [1, 2, 2] [1, 1, 2] [1, 1, 1] [0, 1, 1] [0, 0, 1] [0, 0, 0] is the value. import time list_a = ['AA','BB','CC'] list_b = ['AAdata','BBdata','CCdata'] dd = 'state' retry_cnt = [3] * len(list_a) for i, symbol in enumerate(list_b): if retry_cnt[i] > 0: dd = 'state' time.sleep(0.2) if 'state' in dd: retry_cnt[i] -= 1 time.sleep(0.2) print(retry_cnt) continue
[ "Your loop is only executing 3 times because list_b only has 3 elements in it.\nIf you want the whole loop to run 3 times, you could wrap it in another for loop, like so:\nfor x in range(3):\n for i, symbol in enumerate(list_b):\n if retry_cnt[i] > 0:\n dd = 'state'\n time.sleep(0.2)\n if 'state' in dd:\n retry_cnt[i] -= 1\n time.sleep(0.2)\n print(retry_cnt) \n\nAlso, the continue is probably unnecessary because it is the last instruction in the loop, so it happens automatically.\n" ]
[ 0 ]
[]
[]
[ "enumerate", "for_loop", "python" ]
stackoverflow_0074550883_enumerate_for_loop_python.txt
Q: How to calculate my encoding sha256 maximum int lenght? I use this little code in a function to generate immutable hash of strings and store it. My problem is i don't know how to find the max possible value with sha256 :7 'little' ??? int.from_bytes(hashlib.sha256(value.encode('utf-8')).digest()[:7], 'little') A: Well, if you have seven bytes, and you turn that into an integer, the maximum value is the same as the maximum value of a (7*8) bit integer, because there are 8 bits in a byte. The largest value of a 56-bit unsigned integer is 2**56 - 1, and the smallest value is 0. >>> 2**56 - 1 72057594037927935 What about negative values? int.from_bytes() interprets its value as unsigned by default, so you won't have negative values.
How to calculate my encoding sha256 maximum int lenght?
I use this little code in a function to generate immutable hash of strings and store it. My problem is i don't know how to find the max possible value with sha256 :7 'little' ??? int.from_bytes(hashlib.sha256(value.encode('utf-8')).digest()[:7], 'little')
[ "Well, if you have seven bytes, and you turn that into an integer, the maximum value is the same as the maximum value of a (7*8) bit integer, because there are 8 bits in a byte. The largest value of a 56-bit unsigned integer is 2**56 - 1, and the smallest value is 0.\n>>> 2**56 - 1\n72057594037927935\n\nWhat about negative values? int.from_bytes() interprets its value as unsigned by default, so you won't have negative values.\n" ]
[ 1 ]
[]
[]
[ "calculation", "python" ]
stackoverflow_0074550960_calculation_python.txt
Q: Keras call model.fit where x is two-tuple of np.ndarray I have a regression tf.keras.Model that takes in: x: tuple[np.ndarray, np.ndarray], where the two items have different shapes Shapes are (128, 1152) and (1, 256) y: float I have my model and training codified like so: class MyModel(tf.keras.Model): def __init__(self): ... # Omitted for brevity def call(self, inputs: tuple[tf.Tensor, tf.Tensor], training=None, mask=None): # Unpacks the two-tuple weights_1, weights_2 = inputs ... # Omitted for brevity # NOTE: item 0's shape is (128, 1152), item 1's shape is (1, 256) datapoint_x: tuple[np.ndarray, np.ndarray] datapoint_y: float model = MyModel() model(inputs=datapoint_x) # Works fine However, when I go to fit the model, I get an Exception: >>> model.fit(x=datapoint_x, y=np.array(datapoint_y)) Traceback (most recent call last): File "/path/to/python3.10/site-packages/IPython/core/interactiveshell.py", line 3433, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-5-a5dfb3dd4846>", line 1, in <module> model.fit(x=datapoint_x, y=np.array(datapoint_y)) File "/path/to/python3.10/site-packages/keras/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "/path/to/python3.10/site-packages/tensorflow/python/framework/tensor_shape.py", line 910, in __getitem__ return self._dims[key] IndexError: tuple index out of range I investigated this, and self._dims is () and key is 0. What is the proper way to call Model.fit on a dataset with two-tuple x's? A: The answer is Model.fit is iterating over the x's and y's, so I had to add a batch dimension up-front to my x[0] and y. This could be easily done using np.newaxis or np.expand_dims. import numpy as np # NOTE: item 0's shape is (128, 1152), item 1's shape is (1, 256) datapoint_x: tuple[np.ndarray, np.ndarray] datapoint_y: float # NOTE: now item 0's shape is (1, 128, 1152), and item 1's shape remains (1, 256) batch_x = (datapoint_x[0][np.newaxis, :], datapoint_x[1]) # NOTE: now y's shape is (1,) batch_y = np.array([datapoint_y]) model.fit(x=batch_x, y=batch_y)
Keras call model.fit where x is two-tuple of np.ndarray
I have a regression tf.keras.Model that takes in: x: tuple[np.ndarray, np.ndarray], where the two items have different shapes Shapes are (128, 1152) and (1, 256) y: float I have my model and training codified like so: class MyModel(tf.keras.Model): def __init__(self): ... # Omitted for brevity def call(self, inputs: tuple[tf.Tensor, tf.Tensor], training=None, mask=None): # Unpacks the two-tuple weights_1, weights_2 = inputs ... # Omitted for brevity # NOTE: item 0's shape is (128, 1152), item 1's shape is (1, 256) datapoint_x: tuple[np.ndarray, np.ndarray] datapoint_y: float model = MyModel() model(inputs=datapoint_x) # Works fine However, when I go to fit the model, I get an Exception: >>> model.fit(x=datapoint_x, y=np.array(datapoint_y)) Traceback (most recent call last): File "/path/to/python3.10/site-packages/IPython/core/interactiveshell.py", line 3433, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-5-a5dfb3dd4846>", line 1, in <module> model.fit(x=datapoint_x, y=np.array(datapoint_y)) File "/path/to/python3.10/site-packages/keras/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "/path/to/python3.10/site-packages/tensorflow/python/framework/tensor_shape.py", line 910, in __getitem__ return self._dims[key] IndexError: tuple index out of range I investigated this, and self._dims is () and key is 0. What is the proper way to call Model.fit on a dataset with two-tuple x's?
[ "The answer is Model.fit is iterating over the x's and y's, so I had to add a batch dimension up-front to my x[0] and y.\nThis could be easily done using np.newaxis or np.expand_dims.\nimport numpy as np\n\n# NOTE: item 0's shape is (128, 1152), item 1's shape is (1, 256)\ndatapoint_x: tuple[np.ndarray, np.ndarray]\ndatapoint_y: float\n\n# NOTE: now item 0's shape is (1, 128, 1152), and item 1's shape remains (1, 256)\nbatch_x = (datapoint_x[0][np.newaxis, :], datapoint_x[1])\n# NOTE: now y's shape is (1,)\nbatch_y = np.array([datapoint_y])\n\nmodel.fit(x=batch_x, y=batch_y)\n\n" ]
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow", "tf.keras" ]
stackoverflow_0074542125_keras_python_tensorflow_tf.keras.txt
Q: How do you plot on a premade matplotlib plot with IPyWidgets? I have a scenario where I would like to initialize the plot and plot a bunch of stuff on it before I run a widget on it. However, the jupyter widget refuses to plot on my already made plot. Instead, nothing shows up. A simplified example of this is below. import matplotlib.pyplot as plt import ipywidgets as widgets from IPython import display fig=plt.figure(1,(2,2)) axs=fig.gca() def testAnimate(x): axs.text(0.5,0.5,x) xs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10 gui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument display.display(gui) #display it I would expect the value of x to show up on axs, but it does not. I realize that in this case I could just do plt.text, however in my actual project that is not viable. So, how do I get the value of x to show up on my plot? Thanks! A: Assuming that you are using Jupyter Notebook, you first have to initialize the interactive matplotlib. You can do that by running either one of the following magic commands: %matplotlib notebook %matplotlib widget. This one requires ipympl to be installed. Then, execute: import matplotlib.pyplot as plt import ipywidgets as widgets from IPython import display fig, ax = plt.subplots() text = ax.text(0.5, 0.5, "0") def testAnimate(x): text.set_text(x) xs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10 gui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument display.display(gui) #display it A: You were close. I had seen to put the plot creating in the function you call with the interactive wrapper. See here. Translating that to your code by moving the two lines inside the function would have your notebook cell be: import matplotlib.pyplot as plt import ipywidgets as widgets from IPython import display def testAnimate(x): fig=plt.figure(1,(2,2)) axs=fig.gca() axs.text(0.5,0.5,x) xs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10 gui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument gui Note that this works with %matplolib inline or actually without it at all as detailed in the comment at the top of the code there. I don't want the extra cruft and stuff that %matplotlib widget or %matplotlib notebook makes and makes the interactivity limited to the slider, like you seem to prefer as well. And because the interactive ability of ipywidgets will make the widget automatically, you can simplify further to: import matplotlib.pyplot as plt import ipywidgets as widgets from IPython import display def testAnimate(x): fig=plt.figure(1,(2,2)) axs=fig.gca() axs.text(0.5,0.5,x) gui = widgets.interactive(testAnimate, x=(0,3,1)) gui
How do you plot on a premade matplotlib plot with IPyWidgets?
I have a scenario where I would like to initialize the plot and plot a bunch of stuff on it before I run a widget on it. However, the jupyter widget refuses to plot on my already made plot. Instead, nothing shows up. A simplified example of this is below. import matplotlib.pyplot as plt import ipywidgets as widgets from IPython import display fig=plt.figure(1,(2,2)) axs=fig.gca() def testAnimate(x): axs.text(0.5,0.5,x) xs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10 gui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument display.display(gui) #display it I would expect the value of x to show up on axs, but it does not. I realize that in this case I could just do plt.text, however in my actual project that is not viable. So, how do I get the value of x to show up on my plot? Thanks!
[ "Assuming that you are using Jupyter Notebook, you first have to initialize the interactive matplotlib. You can do that by running either one of the following magic commands:\n\n%matplotlib notebook\n%matplotlib widget. This one requires ipympl to be installed.\n\nThen, execute:\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\nfrom IPython import display \n\nfig, ax = plt.subplots()\ntext = ax.text(0.5, 0.5, \"0\")\n\ndef testAnimate(x):\n text.set_text(x)\n\nxs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10\n\ngui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument\ndisplay.display(gui) #display it\n\n", "You were close. I had seen to put the plot creating in the function you call with the interactive wrapper. See here.\nTranslating that to your code by moving the two lines inside the function would have your notebook cell be:\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\nfrom IPython import display \n\ndef testAnimate(x):\n fig=plt.figure(1,(2,2))\n axs=fig.gca()\n axs.text(0.5,0.5,x)\n\nxs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10\n\ngui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument\ngui\n\nNote that this works with %matplolib inline or actually without it at all as detailed in the comment at the top of the code there.\nI don't want the extra cruft and stuff that %matplotlib widget or %matplotlib notebook makes and makes the interactivity limited to the slider, like you seem to prefer as well.\n\nAnd because the interactive ability of ipywidgets will make the widget automatically, you can simplify further to:\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\nfrom IPython import display \n\ndef testAnimate(x):\n fig=plt.figure(1,(2,2))\n axs=fig.gca()\n axs.text(0.5,0.5,x)\n\ngui = widgets.interactive(testAnimate, x=(0,3,1))\ngui\n\n" ]
[ 0, 0 ]
[]
[]
[ "ipywidgets", "jupyter_lab", "matplotlib", "python" ]
stackoverflow_0074539146_ipywidgets_jupyter_lab_matplotlib_python.txt
Q: Not able to install node@10 on mac M1 chip device System I have a project which requires node@10 to run. I used https://brew.sh to install node@10. I used the below command to install node@10 brew install --build-from-source node@10 It was not able to install and i got the following error. ./configure: line 3: exec: python: not found I installed python using brew. brew install python The above command installed python3, so i created alias for python alias python=python3 So, python is working. I again tried brew install --build-from-source node@10 and still getting A: I don't have enough rep to comment so I'll try to phrase this as an answer: Chances are there is a messed up symlink somewhere Usually you can use brew info python to troubleshoot your python install with homebrew installs. Also use which python at the terminal to see the actual path to the python executable. A: I had the same issue on MacOS 13.0.1. The only solution worked for me is, downloading node 10.x.x package from https://nodejs.org/en/download/
Not able to install node@10 on mac M1 chip device
System I have a project which requires node@10 to run. I used https://brew.sh to install node@10. I used the below command to install node@10 brew install --build-from-source node@10 It was not able to install and i got the following error. ./configure: line 3: exec: python: not found I installed python using brew. brew install python The above command installed python3, so i created alias for python alias python=python3 So, python is working. I again tried brew install --build-from-source node@10 and still getting
[ "I don't have enough rep to comment so I'll try to phrase this as an answer:\nChances are there is a messed up symlink somewhere\n\nUsually you can use brew info python to troubleshoot your python install with homebrew installs.\nAlso use which python at the terminal to see the actual path to the python executable.\n\n", "I had the same issue on MacOS 13.0.1. The only solution worked for me is, downloading node 10.x.x package from https://nodejs.org/en/download/\n" ]
[ 0, 0 ]
[]
[]
[ "apple_m1", "macos", "node.js", "python" ]
stackoverflow_0072036779_apple_m1_macos_node.js_python.txt
Q: Python Telethon - Send messages at timed intervals I'm trying to send a message to my group at defined time intervals, but I get a warning in the output the first time I try to send the message. Next times no warning, but nothing is posted in the group. I'm the owner of the group so in theory there shouldn't be any permissions issues. Code from telethon import TelegramClient import schedule def sendImage(): apiId = 1111111 apiHash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" phone = "+111111111111" client = TelegramClient(phone, apiId, apiHash) toChat = 1641242898 client.start() print("Sending...") client.send_file(toChat, "./image.jpg", caption="Write text here") client.disconnect() return def main(): schedule.every(10).seconds.do(sendImage) while True: schedule.run_pending() if __name__ == "__main__": main() Output Sending... RuntimeWarning: coroutine 'UploadMethods.send_file' was never awaited client.send_file(toChat, "./image.jpg", caption="Write text here") RuntimeWarning: Enable tracemalloc to get the object allocation traceback Sending... Sending... Sending... A: Telethon uses asyncio, but schedule wasn't designed with asyncio in mind. You should consider using an asyncio-based alternative to schedule, or just use Python's builtin functions in the asyncio module to "schedule" things: import asyncio from telethon import TelegramClient def send_image(): ... client = TelegramClient(phone, apiId, apiHash) await client.start() await client.send_file(toChat, "./image.jpg", caption="Write text here") await client.disconnect() async def main(): while True: # forever await send_image() # send image, then await asyncio.sleep(10) # sleep 10 seconds # this is essentially "every 10 seconds call send_image" if __name__ == "__main__": asyncio.run(main()) You should also consider creating and start()ing the client inside main to avoid recreating it every time.
Python Telethon - Send messages at timed intervals
I'm trying to send a message to my group at defined time intervals, but I get a warning in the output the first time I try to send the message. Next times no warning, but nothing is posted in the group. I'm the owner of the group so in theory there shouldn't be any permissions issues. Code from telethon import TelegramClient import schedule def sendImage(): apiId = 1111111 apiHash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" phone = "+111111111111" client = TelegramClient(phone, apiId, apiHash) toChat = 1641242898 client.start() print("Sending...") client.send_file(toChat, "./image.jpg", caption="Write text here") client.disconnect() return def main(): schedule.every(10).seconds.do(sendImage) while True: schedule.run_pending() if __name__ == "__main__": main() Output Sending... RuntimeWarning: coroutine 'UploadMethods.send_file' was never awaited client.send_file(toChat, "./image.jpg", caption="Write text here") RuntimeWarning: Enable tracemalloc to get the object allocation traceback Sending... Sending... Sending...
[ "Telethon uses asyncio, but schedule wasn't designed with asyncio in mind. You should consider using an asyncio-based alternative to schedule, or just use Python's builtin functions in the asyncio module to \"schedule\" things:\nimport asyncio\nfrom telethon import TelegramClient\n\ndef send_image():\n ...\n client = TelegramClient(phone, apiId, apiHash)\n\n await client.start()\n await client.send_file(toChat, \"./image.jpg\", caption=\"Write text here\")\n await client.disconnect()\n\nasync def main():\n while True: # forever\n await send_image() # send image, then\n await asyncio.sleep(10) # sleep 10 seconds\n\n # this is essentially \"every 10 seconds call send_image\"\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n\nYou should also consider creating and start()ing the client inside main to avoid recreating it every time.\n" ]
[ 0 ]
[ "As the output says you need to await the response of the coroutine. The code may trigger exceptions which should be handled.\ntry:\n client = TelegramClient(...)\n client.start()\nexcept Exception as e:\n print(f\"Exception while starting the client - {e}\")\nelse:\n try:\n ret_value = await client.send_file(...)\n except Exception as e:\n print(f\"Exception while sending the message - {e}\")\n else:\n print(f\"Message sent. Return Value {ret_value}\")\n\n" ]
[ -1 ]
[ "python", "python_3.x", "telegram", "telegram_bot", "telethon" ]
stackoverflow_0074546581_python_python_3.x_telegram_telegram_bot_telethon.txt
Q: filter dataset in Pandas based on a specific datetime column condition I have a dataframe with recorded dates and event dates, I use the following script to create a new dataframe with only rows where record and event dates match. New_df =df1.loc[(df1['record_date'] == df1['event_date'])] However I want to include rows from dataset where record dates are +- 1 day, 2 day, 3 days from event date including above code. How can do that? A: can you try this: New_df =df1.loc[abs((df1['record_date'] - df1['event_date'])).dt.days <= 3] #get +- 3 days A: new_df = df.loc[df.record_date.sub(df.event_date).abs().le('3d')]
filter dataset in Pandas based on a specific datetime column condition
I have a dataframe with recorded dates and event dates, I use the following script to create a new dataframe with only rows where record and event dates match. New_df =df1.loc[(df1['record_date'] == df1['event_date'])] However I want to include rows from dataset where record dates are +- 1 day, 2 day, 3 days from event date including above code. How can do that?
[ "can you try this:\nNew_df =df1.loc[abs((df1['record_date'] - df1['event_date'])).dt.days <= 3] #get +- 3 days\n\n", "new_df = df.loc[df.record_date.sub(df.event_date).abs().le('3d')]\n\n" ]
[ 1, 1 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074550793_datetime_pandas_python.txt
Q: RE-ORDER VALUES OF COLUMNS PARAMETERS I'm using this code valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS']) to pivot this dataframe on python withe pandas. MARCA MES_C CMC CMV VL_VENDAS 3F 01/2022 0,00 33,85 147,70 3M 01/2022 57.130,75 77.457,69 182.964,37 3M 02/2022 87.177,66 75.491,39 169.560,01 but the columns='MES_C' is out of order. CMC CMV VL_VENDAS CMC CMV VL_VENDAS MES_C 01/2022 01/2022 01/2022 02/2022 02/2022 02/2022 MARCA 3F 0,00 NaN 33,85 NaN 147,70 NaN 3M 5.130,75 7.177,66 7.457,69 5.491,39 2.964,37 9.560,01 how to change to get the result like this? CMC CMV VL_VENDAS MES_C 01/2022 02/2022 01/2022 02/2022 01/2022 02/2022 MARCA 3F 0,00 NaN 33,85 NaN 147,70 NaN 3M 57.130,75 87.177,66 77.457,69 75.491,39 182.964,37 169.560,01 I want to show the results groped by the values ['CMC','CMV','VL_VENDAS'] I'ved tried with valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS']) and pd.pivot_table(valores, values=['CMC','CMV','VL_VENDAS'], index='MARCA', columns='MES_C', aggfunc='first') A: pivot = pd.pivot_table(valores, index=['MARCA'], columns='MES_C', aggfunc={'CMC':'sum','CMV':'sum','VL_VENDAS':'sum'}, fill_value=0, margins=True) .swaplevel(axis=1) .sort_index(level=0, axis=1) .reindex(['CMC','CMV','VL_VENDAS'], level=1, axis=1) .rename_axis(columns=[None, None]) pivot.to_excel('relatorio.xlsx', sheet_name='cmcxcmv') with this code, works to change the column order and fix the problem.
RE-ORDER VALUES OF COLUMNS PARAMETERS
I'm using this code valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS']) to pivot this dataframe on python withe pandas. MARCA MES_C CMC CMV VL_VENDAS 3F 01/2022 0,00 33,85 147,70 3M 01/2022 57.130,75 77.457,69 182.964,37 3M 02/2022 87.177,66 75.491,39 169.560,01 but the columns='MES_C' is out of order. CMC CMV VL_VENDAS CMC CMV VL_VENDAS MES_C 01/2022 01/2022 01/2022 02/2022 02/2022 02/2022 MARCA 3F 0,00 NaN 33,85 NaN 147,70 NaN 3M 5.130,75 7.177,66 7.457,69 5.491,39 2.964,37 9.560,01 how to change to get the result like this? CMC CMV VL_VENDAS MES_C 01/2022 02/2022 01/2022 02/2022 01/2022 02/2022 MARCA 3F 0,00 NaN 33,85 NaN 147,70 NaN 3M 57.130,75 87.177,66 77.457,69 75.491,39 182.964,37 169.560,01 I want to show the results groped by the values ['CMC','CMV','VL_VENDAS'] I'ved tried with valores.pivot(index='MARCA', columns='MES_C', values=['CMC','CMV','VL_VENDAS']) and pd.pivot_table(valores, values=['CMC','CMV','VL_VENDAS'], index='MARCA', columns='MES_C', aggfunc='first')
[ "pivot = pd.pivot_table(valores, index=['MARCA'], columns='MES_C', aggfunc={'CMC':'sum','CMV':'sum','VL_VENDAS':'sum'}, fill_value=0, margins=True)\n.swaplevel(axis=1)\n.sort_index(level=0, axis=1)\n.reindex(['CMC','CMV','VL_VENDAS'], level=1, axis=1)\n.rename_axis(columns=[None, None])\n\npivot.to_excel('relatorio.xlsx', sheet_name='cmcxcmv')\n\nwith this code, works to change the column order and fix the problem.\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074539380_pandas_python_python_3.x.txt
Q: Multiply / divide dataframe columns by list / series along axis 1 I have a dataframe with N columns, where N may be 0. And I have a list of scalar values, the same length than the list of columns in the dataframe. I want to multiply or divide the columns of the dataframe by the corresponding value in the list. E.g. Dataframe 1 2 3 1 1 2 3 2 4 5 6 3 7 8 9 Multipliers 0 1 2 Expected 1 2 3 1 0 2 6 2 0 5 12 3 0 8 18 Let's create data # Empty df_1 = pd.DataFrame({}, index=idx) list_1 = [] series_1 = pd.Series(list_1, dtype=float) # Not empty (1 element to shorten example) df_2 = pd.DataFrame({1: [1]}, index=idx) list_2 = [12] series_2 = pd.Series(list_2, dtype=float) It works as expected when I pass the multipliers as a list df_2.mul(list_2) 1 1 12 However, I get a warning if the list is empty df_1.mul(list_1, axis=1) <stdin>:1: FutureWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning. Empty DataFrame Columns: [] Index: [1] So I tried to pass the list as a series. I don't get any warning when the series is empty df_1.mul(series_1, axis=1) Empty DataFrame Columns: [] Index: [1] But this is obviously not the right thing to do because when passing a series, the series index is matched with the column names. df_2.mul(series_2) 0 1 1 NaN NaN I would like to rely on the columns order, like with the list. How may I achieve this? I'm fine with the list. I just want to be future-proof, so I'd like to get rid of the warning. A: Here is one (hacky) way to do it: import pandas as pd def helper(df, other, *args, **kwargs): if isinstance(other, list) and not other: return pd.DataFrame() return mul(df, other, **kwargs) mul = pd.DataFrame.mul pd.DataFrame.mul = helper df_1 = pd.DataFrame({}) list_1 = [] df_2 = pd.DataFrame({1: [1]}) list_2 = [12] Then: print(df_2.mul(list_2)) 1 0 12 print(df_1.mul(list_1, axis=1)) # No warning Empty DataFrame Columns: [] Index: []
Multiply / divide dataframe columns by list / series along axis 1
I have a dataframe with N columns, where N may be 0. And I have a list of scalar values, the same length than the list of columns in the dataframe. I want to multiply or divide the columns of the dataframe by the corresponding value in the list. E.g. Dataframe 1 2 3 1 1 2 3 2 4 5 6 3 7 8 9 Multipliers 0 1 2 Expected 1 2 3 1 0 2 6 2 0 5 12 3 0 8 18 Let's create data # Empty df_1 = pd.DataFrame({}, index=idx) list_1 = [] series_1 = pd.Series(list_1, dtype=float) # Not empty (1 element to shorten example) df_2 = pd.DataFrame({1: [1]}, index=idx) list_2 = [12] series_2 = pd.Series(list_2, dtype=float) It works as expected when I pass the multipliers as a list df_2.mul(list_2) 1 1 12 However, I get a warning if the list is empty df_1.mul(list_1, axis=1) <stdin>:1: FutureWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning. Empty DataFrame Columns: [] Index: [1] So I tried to pass the list as a series. I don't get any warning when the series is empty df_1.mul(series_1, axis=1) Empty DataFrame Columns: [] Index: [1] But this is obviously not the right thing to do because when passing a series, the series index is matched with the column names. df_2.mul(series_2) 0 1 1 NaN NaN I would like to rely on the columns order, like with the list. How may I achieve this? I'm fine with the list. I just want to be future-proof, so I'd like to get rid of the warning.
[ "Here is one (hacky) way to do it:\nimport pandas as pd\n\ndef helper(df, other, *args, **kwargs):\n if isinstance(other, list) and not other:\n return pd.DataFrame()\n return mul(df, other, **kwargs)\n\n\nmul = pd.DataFrame.mul\npd.DataFrame.mul = helper\n\n\ndf_1 = pd.DataFrame({})\nlist_1 = []\n\ndf_2 = pd.DataFrame({1: [1]})\nlist_2 = [12]\n\nThen:\nprint(df_2.mul(list_2))\n\n 1\n0 12\n\nprint(df_1.mul(list_1, axis=1))\n\n# No warning\nEmpty DataFrame\nColumns: []\nIndex: []\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074448601_pandas_python.txt
Q: Add a role to a user with the selection menu discord.py I just have a question, I make a bot with discord and the users on the guild add their roles themself with a drop-down menu, for this, in my code, i have this module (with many others options): class selectmenu(discord.ui.View): def __init__(self): super().__init__(timeout=None) options=[ discord.SelectOption(label="Happy", value=1), discord.SelectOption(label="Sad", value=2), discord.SelectOption(label="In love", value=3), ] @discord.ui.select(placeholder="Emotion", min_values=1, max_values=1, options=options, custom_id="selectmenu") async def select(self, interaction: discord.Interaction, select): user = interaction.user guild = interaction.guild select.disabled=True if select.values[0] == "1": role = discord.utils.get(guild.roles, name="Happy") await user.add_roles(role) await interaction.response.send_message("Emotion Happy added!", ephemeral=True) elif select.values[0] == "2": role = discord.utils.get(guild.roles, name="Sad") await user.add_roles(role) await interaction.response.send_message("Emotion Sad added", ephemeral=True) elif select.values[0] == "3": role = discord.utils.get(guild.roles, name="In love") await user.add_roles(role) await interaction.response.send_message("Emotion In love added", ephemeral=True) This code is functional, but it is no efficient, let me explain: there is is one condition per role but if we have 20 roles, we have 20 conditions, that takes too many lines of code! If someone has a solution, even if it allows me to remove a dozen lines, it is good to take! thanks to anyone who tries to help me A: To improve efficiency, you may want to consider using a dictionary to store your roles, with the menu selection as keys and the role names as values. For example: roleDict = {'1': 'Happy', '2': 'Sad', '3': 'In Love'} From this point, the dictionary can be implemented as follows: role = discord.utils.get(guild.roles, name = roleDict[<USER_SELECTION>]) await user.add_roles(role) await interaction.response.send_message("Emotion " + roleDict[<USER_SELECTION>] + " added!", ephemeral=True)
Add a role to a user with the selection menu discord.py
I just have a question, I make a bot with discord and the users on the guild add their roles themself with a drop-down menu, for this, in my code, i have this module (with many others options): class selectmenu(discord.ui.View): def __init__(self): super().__init__(timeout=None) options=[ discord.SelectOption(label="Happy", value=1), discord.SelectOption(label="Sad", value=2), discord.SelectOption(label="In love", value=3), ] @discord.ui.select(placeholder="Emotion", min_values=1, max_values=1, options=options, custom_id="selectmenu") async def select(self, interaction: discord.Interaction, select): user = interaction.user guild = interaction.guild select.disabled=True if select.values[0] == "1": role = discord.utils.get(guild.roles, name="Happy") await user.add_roles(role) await interaction.response.send_message("Emotion Happy added!", ephemeral=True) elif select.values[0] == "2": role = discord.utils.get(guild.roles, name="Sad") await user.add_roles(role) await interaction.response.send_message("Emotion Sad added", ephemeral=True) elif select.values[0] == "3": role = discord.utils.get(guild.roles, name="In love") await user.add_roles(role) await interaction.response.send_message("Emotion In love added", ephemeral=True) This code is functional, but it is no efficient, let me explain: there is is one condition per role but if we have 20 roles, we have 20 conditions, that takes too many lines of code! If someone has a solution, even if it allows me to remove a dozen lines, it is good to take! thanks to anyone who tries to help me
[ "To improve efficiency, you may want to consider using a dictionary to store your roles, with the menu selection as keys and the role names as values. For example:\nroleDict = {'1': 'Happy', '2': 'Sad', '3': 'In Love'}\n\nFrom this point, the dictionary can be implemented as follows:\nrole = discord.utils.get(guild.roles, name = roleDict[<USER_SELECTION>])\nawait user.add_roles(role)\nawait interaction.response.send_message(\"Emotion \" + roleDict[<USER_SELECTION>] + \" added!\", ephemeral=True)\n\n" ]
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074551165_discord.py_python.txt
Q: Not able to download a file through request in python When I try to download a file online it doesn't work for a particular site while it works for others. Why is this happening and what should I do about it? I write the content of the dl request in my case https://drivers.amd.com/drivers/amd-software-adrenalin-edition-22.11.1-win10-win11-nov15.exe (warning: 500+ MB file) from this page: https://www.amd.com/fr/support/graphics/amd-radeon-6000-series/amd-radeon-6900-series/amd-radeon-rx-6900-xt 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'} web = Session() web.headers.update(headers) def dl_btn(self): try: dl = web.get(self.link) #I use an old session that allowed me to retrieve a download link. file = dl.headers['Content-Disposition'].split('=')[1] file = filedialog.askdirectory() + '/' + file #Open file explorer to choose the download destination. open(file, "wb").write(dl.content) except: popen(f'start {self.link}') #It open a page that indicate me a wrong request... A: If you read the error page, it tells you exactly what the problem is: they don't allow downloads without a referer from their website. Therefore, your headers will need to include a Referer key/value, and I assume a proper User-Agent as well: import requests from tkinter import filedialog referer = "https://www.amd.com/fr/support/graphics/amd-radeon-6000-series/amd-radeon-6900-series/amd-radeon-rx-6900-xt" file_to_dl = "https://drivers.amd.com/drivers/amd-software-adrenalin-edition-22.11.1-win10-win11-nov15.exe" 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" headers = {"User-Agent": user_agent, "Referer": referer} r = requests.get(file_to_dl, headers=headers) # wait a while... file = file_to_dl.split("/")[-1] file_location = filedialog.askdirectory() + '/' + file open(file_location, "wb").write(r.content)
Not able to download a file through request in python
When I try to download a file online it doesn't work for a particular site while it works for others. Why is this happening and what should I do about it? I write the content of the dl request in my case https://drivers.amd.com/drivers/amd-software-adrenalin-edition-22.11.1-win10-win11-nov15.exe (warning: 500+ MB file) from this page: https://www.amd.com/fr/support/graphics/amd-radeon-6000-series/amd-radeon-6900-series/amd-radeon-rx-6900-xt 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'} web = Session() web.headers.update(headers) def dl_btn(self): try: dl = web.get(self.link) #I use an old session that allowed me to retrieve a download link. file = dl.headers['Content-Disposition'].split('=')[1] file = filedialog.askdirectory() + '/' + file #Open file explorer to choose the download destination. open(file, "wb").write(dl.content) except: popen(f'start {self.link}') #It open a page that indicate me a wrong request...
[ "If you read the error page, it tells you exactly what the problem is: they don't allow downloads without a referer from their website. Therefore, your headers will need to include a Referer key/value, and I assume a proper User-Agent as well:\nimport requests\nfrom tkinter import filedialog\n\nreferer = \"https://www.amd.com/fr/support/graphics/amd-radeon-6000-series/amd-radeon-6900-series/amd-radeon-rx-6900-xt\"\nfile_to_dl = \"https://drivers.amd.com/drivers/amd-software-adrenalin-edition-22.11.1-win10-win11-nov15.exe\"\nuser_agent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36\"\nheaders = {\"User-Agent\": user_agent,\n \"Referer\": referer}\n\nr = requests.get(file_to_dl, headers=headers)\n# wait a while...\nfile = file_to_dl.split(\"/\")[-1]\nfile_location = filedialog.askdirectory() + '/' + file\nopen(file_location, \"wb\").write(r.content)\n\n" ]
[ 1 ]
[]
[]
[ "download", "python", "request" ]
stackoverflow_0074551098_download_python_request.txt
Q: Pandas - Update Column Values If Values in Rows Are Partially Matching I have a dataframe similar to below-given dataframe. I need to add a value in Validated column that matches the below condition: If there are multiple rows with the same values in State, ColorName, and Code columns then at least one row should contain a positive value in the Value column. If there is no row with a positive value in Value column, I need to add "Invalid" in the Validated column for all the matching rows.Is there a way I can do it without iterating over each row? State ColorName Code Value Validated Arizona Yellow A 50 Alabama Orange A 150 Arkansas Red B -500 Kentuky Green M -40 Ohio Blue X 100 Alabama Orange A -30 Arizona Yellow A 100 California Blue C 100 California Blue C -100 Arkansas Red B 500 Ohio Yellow X 100 California Blue C 100 A: df = pd.DataFrame({'State': ['Arizona', 'Alabama', 'Arkansas', 'Kentuky', 'Ohio', 'Alabama', 'Arizona', 'California', 'California', 'Arkansas', 'Ohio', 'California'], 'ColorName': ['Yellow', 'Orange', 'Red', 'Green', 'Blue', 'Orange', 'Yellow', 'Blue', 'Blue', 'Red', 'Yellow', 'Blue'], 'Code': ['A', 'A', 'B', 'M', 'X', 'A', 'A', 'C', 'C', 'B', 'X', 'C'], 'Value': [50, 150, -500, -40, 100, -30, 100, 100, -100, 500, 100, 100]}) df['Validated'] = df.groupby(['State', 'ColorName', 'Code'])['Value'].transform(lambda x: 'Valid' if x.shape[0] > 1 and x.max() > 0 else 'Invalid') print(df) State ColorName Code Value Validated 0 Arizona Yellow A 50 Valid 1 Alabama Orange A 150 Valid 2 Arkansas Red B -500 Valid 3 Kentuky Green M -40 Invalid 4 Ohio Blue X 100 Invalid 5 Alabama Orange A -30 Valid 6 Arizona Yellow A 100 Valid 7 California Blue C 100 Valid 8 California Blue C -100 Valid 9 Arkansas Red B 500 Valid 10 Ohio Yellow X 100 Invalid 11 California Blue C 100 Valid A: Assuming you want more than one value and at least one positive: g = (df.assign(flag=df['Value'].gt(0)) .groupby(['State', 'ColorName', 'Code']) ) m1 = g.transform('size').gt(1) m2 = g['flag'].transform('any') df['Validated'] = np.where(m1&m2, 'Valid', 'Invalid') Output: State ColorName Code Value Validated 0 Arizona Yellow A 50 Valid 1 Alabama Orange A 150 Valid 2 Arkansas Red B -500 Valid 3 Kentuky Green M -40 Invalid 4 Ohio Blue X 100 Invalid 5 Alabama Orange A -30 Valid 6 Arizona Yellow A 100 Valid 7 California Blue C 100 Valid 8 California Blue C -100 Valid 9 Arkansas Red B 500 Valid 10 Ohio Yellow X 100 Invalid 11 California Blue C 100 Valid If you just want at least one positive value: df['Validated'] = np.where(m2, 'Valid', 'Invalid') Output: State ColorName Code Value Validated 0 Arizona Yellow A 50 Valid 1 Alabama Orange A 150 Valid 2 Arkansas Red B -500 Valid 3 Kentuky Green M -40 Invalid 4 Ohio Blue X 100 Valid 5 Alabama Orange A -30 Valid 6 Arizona Yellow A 100 Valid 7 California Blue C 100 Valid 8 California Blue C -100 Valid 9 Arkansas Red B 500 Valid 10 Ohio Yellow X 100 Valid 11 California Blue C 100 Valid
Pandas - Update Column Values If Values in Rows Are Partially Matching
I have a dataframe similar to below-given dataframe. I need to add a value in Validated column that matches the below condition: If there are multiple rows with the same values in State, ColorName, and Code columns then at least one row should contain a positive value in the Value column. If there is no row with a positive value in Value column, I need to add "Invalid" in the Validated column for all the matching rows.Is there a way I can do it without iterating over each row? State ColorName Code Value Validated Arizona Yellow A 50 Alabama Orange A 150 Arkansas Red B -500 Kentuky Green M -40 Ohio Blue X 100 Alabama Orange A -30 Arizona Yellow A 100 California Blue C 100 California Blue C -100 Arkansas Red B 500 Ohio Yellow X 100 California Blue C 100
[ "df = pd.DataFrame({'State': ['Arizona', 'Alabama', 'Arkansas', 'Kentuky', 'Ohio', 'Alabama', 'Arizona', 'California',\n 'California', 'Arkansas', 'Ohio', 'California'],\n 'ColorName': ['Yellow', 'Orange', 'Red', 'Green', 'Blue', 'Orange', 'Yellow', 'Blue', 'Blue', 'Red',\n 'Yellow', 'Blue'],\n 'Code': ['A', 'A', 'B', 'M', 'X', 'A', 'A', 'C', 'C', 'B', 'X', 'C'],\n 'Value': [50, 150, -500, -40, 100, -30, 100, 100, -100, 500, 100, 100]})\n\ndf['Validated'] = df.groupby(['State', 'ColorName', 'Code'])['Value'].transform(lambda x: 'Valid' if x.shape[0] > 1 and x.max() > 0 else 'Invalid')\nprint(df)\n\n State ColorName Code Value Validated\n0 Arizona Yellow A 50 Valid\n1 Alabama Orange A 150 Valid\n2 Arkansas Red B -500 Valid\n3 Kentuky Green M -40 Invalid\n4 Ohio Blue X 100 Invalid\n5 Alabama Orange A -30 Valid\n6 Arizona Yellow A 100 Valid\n7 California Blue C 100 Valid\n8 California Blue C -100 Valid\n9 Arkansas Red B 500 Valid\n10 Ohio Yellow X 100 Invalid\n11 California Blue C 100 Valid\n\n", "Assuming you want more than one value and at least one positive:\ng = (df.assign(flag=df['Value'].gt(0))\n .groupby(['State', 'ColorName', 'Code'])\n )\n\nm1 = g.transform('size').gt(1)\nm2 = g['flag'].transform('any')\n\ndf['Validated'] = np.where(m1&m2, 'Valid', 'Invalid')\n\nOutput:\n State ColorName Code Value Validated\n0 Arizona Yellow A 50 Valid\n1 Alabama Orange A 150 Valid\n2 Arkansas Red B -500 Valid\n3 Kentuky Green M -40 Invalid\n4 Ohio Blue X 100 Invalid\n5 Alabama Orange A -30 Valid\n6 Arizona Yellow A 100 Valid\n7 California Blue C 100 Valid\n8 California Blue C -100 Valid\n9 Arkansas Red B 500 Valid\n10 Ohio Yellow X 100 Invalid\n11 California Blue C 100 Valid\n\nIf you just want at least one positive value:\ndf['Validated'] = np.where(m2, 'Valid', 'Invalid')\n\nOutput:\n State ColorName Code Value Validated\n0 Arizona Yellow A 50 Valid\n1 Alabama Orange A 150 Valid\n2 Arkansas Red B -500 Valid\n3 Kentuky Green M -40 Invalid\n4 Ohio Blue X 100 Valid\n5 Alabama Orange A -30 Valid\n6 Arizona Yellow A 100 Valid\n7 California Blue C 100 Valid\n8 California Blue C -100 Valid\n9 Arkansas Red B 500 Valid\n10 Ohio Yellow X 100 Valid\n11 California Blue C 100 Valid\n\n" ]
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074551122_dataframe_pandas_python.txt
Q: getting AttributeError: 'numpy.ndarray' object has no attribute 'dim' when converting tensorflow code to pytorch I was translating my TensorFlow code to PyTorch and suddenly faced this error. What am I doing wrong here? AttributeError Traceback (most recent call last) <ipython-input-36-058644576709> in <module> 3 batch_size = 1024 4 Xtrain = torch.concat( ----> 5 [transforms(Xtrain[batch_size*batch:batch_size*(batch +1)]) for batch in range(len(Xtrain)//batch_size+1)], 6 axis=0 7 ) <ipython-input-36-058644576709> in <listcomp>(.0) 3 batch_size = 1024 4 Xtrain = torch.concat( ----> 5 [transforms(Xtrain[batch_size*batch:batch_size*(batch +1)]) for batch in range(len(Xtrain)//batch_size+1)], 6 axis=0 7 ) <ipython-input-22-9fc8aa48e3e2> in transforms(x) 1 def transforms(x: torch.Tensor) -> torch.Tensor: 2 """Return Fourrier spectrogram.""" ----> 3 spectrograms = torch.stft(x, win_length=32, n_fft=4, hop_length=64) 4 spectrograms = torch.abs(spectrograms) 5 return torch.einsum("...ijk->...jki", spectrograms) ~\anaconda3\lib\site-packages\torch\functional.py in stft(input, n_fft, hop_length, win_length, window, center, pad_mode, normalized, onesided, return_complex) 565 # this and F.pad to ATen. 566 if center: --> 567 signal_dim = input.dim() 568 extended_shape = [1] * (3 - signal_dim) + list(input.size()) 569 pad = int(n_fft // 2) AttributeError: 'numpy.ndarray' object has no attribute 'dim' The following is the approach I have tried already: #!/usr/bin/env python # coding: utf-8 # # Import library # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') #%matplotlib qt # # Load pooled data # In[2]: from nu_smrutils import loaddat import pandas as pd # In[26]: import pickle import mne import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Seaborn is a Python # data visualization library built on top of Matplotlib. import datetime # module supplies classes for manipulating dates and times. import nu_smrutils # utils for SMR import nu_MIdata_loader # MI data loader import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers # In[3]: dname = dict(BNCI2014004 = 'aBNCI2014004R.pickle', BNCI2014001 = 'aBNCI2014001R.pickle', Weibo2014 = 'aWeibo2014R.pickle', Physionet = 'aPhysionetRR.pickle') # In[4]: # itemname is one of : ['BNCI2014004', 'BNCI2014001', 'Weibo2014', 'Physionet'] itemname = 'BNCI2014004' filename = dname[itemname] iname = itemname + '__' # In[5]: data = loaddat(filename) # In[6]: data[0]['right_hand'].plot(); # In[7]: from nu_smrutils import load_pooled, augment_dataset, crop_data # In[8]: subjectIndex = list(range(108)) class_name = ['left_hand', 'right_hand'] dat = load_pooled(data, subjectIndex, class_name, normalize = True, test_size = 0.15) # # Data augmentation # In[9]: print(dat.keys()) dat['xtrain'].shape # In[10]: get_ipython().run_line_magic('pinfo', 'augment_dataset') # In[11]: augdata = dict(std_dev = 0.01, multiple = 2) # In[12]: xtrain, ytrain = augment_dataset(dat['xtrain'], dat['ytrain'], augdata['std_dev'], augdata['multiple']) print("Shape after data augmentation :", xtrain.shape) dat['xtrain'], dat['ytrain'] = xtrain, ytrain # # Data Cropping # In[14]: fs = 80 # sampling frequency crop_len = 1.5 #or None crop = dict(fs = fs, crop_len = crop_len) #if crop['crop_len']: X_train,y_train = crop_data(crop['fs'],crop['crop_len'], dat['xtrain'], dat['ytrain'], xpercent = 50) X_valid,y_valid = crop_data(crop['fs'],crop['crop_len'], dat['xvalid'], dat['yvalid'], xpercent = 50) X_test, y_test = crop_data(crop['fs'],crop['crop_len'], dat['xtest'], dat['ytest'], xpercent = 50) dat = dict(xtrain = X_train, xvalid = X_valid, xtest = X_test, ytrain = y_train, yvalid = y_valid, ytest = y_test) # In[16]: print('data shape after cropping :',dat['xtrain'].shape) # # Pytorch dataloaders # In[18]: import torch from torch.utils.data import TensorDataset, DataLoader def get_data_loaders(dat, batch_size, EEGNET = None): # convert data dimensions to into to gray scale image format if EEGNET: ### EEGNet model requires the last dimension to be 1 ff = lambda dat: torch.unsqueeze(dat, dim = -1) else: ff = lambda dat: torch.unsqueeze(dat, dim = 1) x_train, x_valid, x_test = map(ff,(dat['xtrain'], dat['xvalid'],dat['xtest'])) y_train, y_valid, y_test = dat['ytrain'], dat['yvalid'], dat['ytest'] print('Input data shape', x_train.shape) # TensorDataset & Dataloader train_dat = TensorDataset(x_train, y_train) val_dat = TensorDataset(x_valid, y_valid) train_loader = DataLoader(train_dat, batch_size = batch_size, shuffle = True) val_loader = DataLoader(val_dat, batch_size = batch_size, shuffle = False) output = dict(dset_loaders = {'train': train_loader, 'val': val_loader}, dset_sizes = {'train': len(x_train), 'val': len(x_valid)}, test_data = {'x_test' : x_test, 'y_test' : y_test}) return output # In[19]: dat = get_data_loaders(dat, batch_size = 64) dat.keys() # In[20]: # Sanity check begin dset_loaders = dat['dset_loaders'] dset_sizes = dat['dset_sizes'] dset_sizes dtrain = dset_loaders['train'] dval = dset_loaders['val'] dtr = iter(dtrain) dv = iter(dval) # In[21]: inputs, labels = next(dtr) print(inputs.shape, labels.shape) # Sanity check end # In[29]: augmentdata = dict(std_dev = 0.01, multiple = 1) # to augment data fs = 80 crop_length = 1.5 #seconds crop = dict(fs = fs, crop_length = crop_length) # crop length class1, class2 = 'left_hand', 'right_hand' s = list(range(108)) # In[31]: def convertY(Y): return np.concatenate([Y[:, None], np.where(Y == 0, 1, 0)[:, None]], axis=-1) # In[33]: def convert(d): # converting tran method Xtrain = d['xtrain'].numpy() Xval = d['xvalid'].numpy() Xtest = d['xtest'].numpy() Ytrain = convertY(d['ytrain'].numpy()) Yval = convertY(d['yvalid'].numpy()) Ytest = convertY(d['ytest'].numpy()) return Xtrain, Xval, Xtest, Ytrain, Yval, Ytest # In[34]: files = ['aBNCI2014004R.pickle', ] # In data we storage sample from different files Data = [] for file in files: d = nu_MIdata_loader.EEGDataLoader(file, class_name = [class1, class2]) d1 = d.load_pooled(s, normalize = True, crop = crop, test_size = 0.01, augmentdata = augmentdata) Data.append(convert(d1)) # In[35]: # concatenate all data if there more then one file Xtrain = np.concatenate([d[0] for d in Data]) Xval = np.concatenate([d[1] for d in Data]) Xtest = np.concatenate([d[2] for d in Data]) Xtrain = np.concatenate([Xtrain, Xval], axis=0) Ytrain = np.concatenate([d[3] for d in Data]) Yval = np.concatenate([d[4] for d in Data]) Ytest = np.concatenate([d[5] for d in Data]) Ytrain = np.concatenate([Ytrain, Yval], axis=0) # In[22]: def transforms(x: torch.Tensor) -> torch.Tensor: """Return Fourrier spectrogram.""" spectrograms = torch.stft(x, win_length=32, n_fft=4, hop_length=64) spectrograms = torch.abs(spectrograms) return torch.einsum("...ijk->...jki", spectrograms) # In[36]: # Convert data in batchs # Cause outofmemort or python crash batch_size = 1024 Xtrain = torch.concat( [transforms(Xtrain[batch_size*batch:batch_size*(batch +1)]) for batch in range(len(Xtrain)//batch_size+1)], axis=0 ) Xtest = torch.concat( [transforms(Xtest[batch_size*batch:batch_size*(batch +1)]) for batch in range(len(Xtest)//batch_size+1)], axis=0 ) # Convert to tensorflow tensors Ytrain = torch.cast(Ytrain, dtype='float32') Ytest = torch.cast(Ytest, dtype='float32') A: torch.stft is a pytorch function and expects a Tensor as the input. You must convert your numpy array into a tensor and then pass that as the input. you can use torch.from_numpy to do this.
getting AttributeError: 'numpy.ndarray' object has no attribute 'dim' when converting tensorflow code to pytorch
I was translating my TensorFlow code to PyTorch and suddenly faced this error. What am I doing wrong here? AttributeError Traceback (most recent call last) <ipython-input-36-058644576709> in <module> 3 batch_size = 1024 4 Xtrain = torch.concat( ----> 5 [transforms(Xtrain[batch_size*batch:batch_size*(batch +1)]) for batch in range(len(Xtrain)//batch_size+1)], 6 axis=0 7 ) <ipython-input-36-058644576709> in <listcomp>(.0) 3 batch_size = 1024 4 Xtrain = torch.concat( ----> 5 [transforms(Xtrain[batch_size*batch:batch_size*(batch +1)]) for batch in range(len(Xtrain)//batch_size+1)], 6 axis=0 7 ) <ipython-input-22-9fc8aa48e3e2> in transforms(x) 1 def transforms(x: torch.Tensor) -> torch.Tensor: 2 """Return Fourrier spectrogram.""" ----> 3 spectrograms = torch.stft(x, win_length=32, n_fft=4, hop_length=64) 4 spectrograms = torch.abs(spectrograms) 5 return torch.einsum("...ijk->...jki", spectrograms) ~\anaconda3\lib\site-packages\torch\functional.py in stft(input, n_fft, hop_length, win_length, window, center, pad_mode, normalized, onesided, return_complex) 565 # this and F.pad to ATen. 566 if center: --> 567 signal_dim = input.dim() 568 extended_shape = [1] * (3 - signal_dim) + list(input.size()) 569 pad = int(n_fft // 2) AttributeError: 'numpy.ndarray' object has no attribute 'dim' The following is the approach I have tried already: #!/usr/bin/env python # coding: utf-8 # # Import library # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') #%matplotlib qt # # Load pooled data # In[2]: from nu_smrutils import loaddat import pandas as pd # In[26]: import pickle import mne import numpy as np import matplotlib.pyplot as plt import seaborn as sns # Seaborn is a Python # data visualization library built on top of Matplotlib. import datetime # module supplies classes for manipulating dates and times. import nu_smrutils # utils for SMR import nu_MIdata_loader # MI data loader import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers # In[3]: dname = dict(BNCI2014004 = 'aBNCI2014004R.pickle', BNCI2014001 = 'aBNCI2014001R.pickle', Weibo2014 = 'aWeibo2014R.pickle', Physionet = 'aPhysionetRR.pickle') # In[4]: # itemname is one of : ['BNCI2014004', 'BNCI2014001', 'Weibo2014', 'Physionet'] itemname = 'BNCI2014004' filename = dname[itemname] iname = itemname + '__' # In[5]: data = loaddat(filename) # In[6]: data[0]['right_hand'].plot(); # In[7]: from nu_smrutils import load_pooled, augment_dataset, crop_data # In[8]: subjectIndex = list(range(108)) class_name = ['left_hand', 'right_hand'] dat = load_pooled(data, subjectIndex, class_name, normalize = True, test_size = 0.15) # # Data augmentation # In[9]: print(dat.keys()) dat['xtrain'].shape # In[10]: get_ipython().run_line_magic('pinfo', 'augment_dataset') # In[11]: augdata = dict(std_dev = 0.01, multiple = 2) # In[12]: xtrain, ytrain = augment_dataset(dat['xtrain'], dat['ytrain'], augdata['std_dev'], augdata['multiple']) print("Shape after data augmentation :", xtrain.shape) dat['xtrain'], dat['ytrain'] = xtrain, ytrain # # Data Cropping # In[14]: fs = 80 # sampling frequency crop_len = 1.5 #or None crop = dict(fs = fs, crop_len = crop_len) #if crop['crop_len']: X_train,y_train = crop_data(crop['fs'],crop['crop_len'], dat['xtrain'], dat['ytrain'], xpercent = 50) X_valid,y_valid = crop_data(crop['fs'],crop['crop_len'], dat['xvalid'], dat['yvalid'], xpercent = 50) X_test, y_test = crop_data(crop['fs'],crop['crop_len'], dat['xtest'], dat['ytest'], xpercent = 50) dat = dict(xtrain = X_train, xvalid = X_valid, xtest = X_test, ytrain = y_train, yvalid = y_valid, ytest = y_test) # In[16]: print('data shape after cropping :',dat['xtrain'].shape) # # Pytorch dataloaders # In[18]: import torch from torch.utils.data import TensorDataset, DataLoader def get_data_loaders(dat, batch_size, EEGNET = None): # convert data dimensions to into to gray scale image format if EEGNET: ### EEGNet model requires the last dimension to be 1 ff = lambda dat: torch.unsqueeze(dat, dim = -1) else: ff = lambda dat: torch.unsqueeze(dat, dim = 1) x_train, x_valid, x_test = map(ff,(dat['xtrain'], dat['xvalid'],dat['xtest'])) y_train, y_valid, y_test = dat['ytrain'], dat['yvalid'], dat['ytest'] print('Input data shape', x_train.shape) # TensorDataset & Dataloader train_dat = TensorDataset(x_train, y_train) val_dat = TensorDataset(x_valid, y_valid) train_loader = DataLoader(train_dat, batch_size = batch_size, shuffle = True) val_loader = DataLoader(val_dat, batch_size = batch_size, shuffle = False) output = dict(dset_loaders = {'train': train_loader, 'val': val_loader}, dset_sizes = {'train': len(x_train), 'val': len(x_valid)}, test_data = {'x_test' : x_test, 'y_test' : y_test}) return output # In[19]: dat = get_data_loaders(dat, batch_size = 64) dat.keys() # In[20]: # Sanity check begin dset_loaders = dat['dset_loaders'] dset_sizes = dat['dset_sizes'] dset_sizes dtrain = dset_loaders['train'] dval = dset_loaders['val'] dtr = iter(dtrain) dv = iter(dval) # In[21]: inputs, labels = next(dtr) print(inputs.shape, labels.shape) # Sanity check end # In[29]: augmentdata = dict(std_dev = 0.01, multiple = 1) # to augment data fs = 80 crop_length = 1.5 #seconds crop = dict(fs = fs, crop_length = crop_length) # crop length class1, class2 = 'left_hand', 'right_hand' s = list(range(108)) # In[31]: def convertY(Y): return np.concatenate([Y[:, None], np.where(Y == 0, 1, 0)[:, None]], axis=-1) # In[33]: def convert(d): # converting tran method Xtrain = d['xtrain'].numpy() Xval = d['xvalid'].numpy() Xtest = d['xtest'].numpy() Ytrain = convertY(d['ytrain'].numpy()) Yval = convertY(d['yvalid'].numpy()) Ytest = convertY(d['ytest'].numpy()) return Xtrain, Xval, Xtest, Ytrain, Yval, Ytest # In[34]: files = ['aBNCI2014004R.pickle', ] # In data we storage sample from different files Data = [] for file in files: d = nu_MIdata_loader.EEGDataLoader(file, class_name = [class1, class2]) d1 = d.load_pooled(s, normalize = True, crop = crop, test_size = 0.01, augmentdata = augmentdata) Data.append(convert(d1)) # In[35]: # concatenate all data if there more then one file Xtrain = np.concatenate([d[0] for d in Data]) Xval = np.concatenate([d[1] for d in Data]) Xtest = np.concatenate([d[2] for d in Data]) Xtrain = np.concatenate([Xtrain, Xval], axis=0) Ytrain = np.concatenate([d[3] for d in Data]) Yval = np.concatenate([d[4] for d in Data]) Ytest = np.concatenate([d[5] for d in Data]) Ytrain = np.concatenate([Ytrain, Yval], axis=0) # In[22]: def transforms(x: torch.Tensor) -> torch.Tensor: """Return Fourrier spectrogram.""" spectrograms = torch.stft(x, win_length=32, n_fft=4, hop_length=64) spectrograms = torch.abs(spectrograms) return torch.einsum("...ijk->...jki", spectrograms) # In[36]: # Convert data in batchs # Cause outofmemort or python crash batch_size = 1024 Xtrain = torch.concat( [transforms(Xtrain[batch_size*batch:batch_size*(batch +1)]) for batch in range(len(Xtrain)//batch_size+1)], axis=0 ) Xtest = torch.concat( [transforms(Xtest[batch_size*batch:batch_size*(batch +1)]) for batch in range(len(Xtest)//batch_size+1)], axis=0 ) # Convert to tensorflow tensors Ytrain = torch.cast(Ytrain, dtype='float32') Ytest = torch.cast(Ytest, dtype='float32')
[ "torch.stft is a pytorch function and expects a Tensor as the input. You must convert your numpy array into a tensor and then pass that as the input.\nyou can use torch.from_numpy to do this.\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "python_3.x", "pytorch", "tensorflow" ]
stackoverflow_0074551169_numpy_python_python_3.x_pytorch_tensorflow.txt
Q: Counting all the odd numbers in a nested list and printing the result in the output I'm new to Python and we received an assignment wherein we must arbitrarily define a nested list, and then implement code that counts up all the odd numbers in the list and prints the result out to the user. Our lecturer instructed us to use the modulo (%) operator, as well as nested for loops. However that is as far as he has explained to us how to do, and I'm completely stuck even whilst looking up online guides. m = [[12, 7, 23, 32], [18, 9, 6, 30], [4, 21, 98, 72], [62, 38, 15, 2]] oddCount = 0 for x in m: if x % 2 != 0: That is the current state of my code. I am painfully aware of how wrong it might be, but with the little information I have on hand that is all I could come up with. It spits out an error, saying that the modulo operator doesn't work if the object is a list or an integer, and for some reason x is of type list despite me not having it defined as a list. A: You're on the right track, but since the arrays are nested you need to use a nested for loop to access the array elements and not just the arrays themselves. for array in m: for x in array: if x % 2 != 0: And from there just sum up the odd elements.
Counting all the odd numbers in a nested list and printing the result in the output
I'm new to Python and we received an assignment wherein we must arbitrarily define a nested list, and then implement code that counts up all the odd numbers in the list and prints the result out to the user. Our lecturer instructed us to use the modulo (%) operator, as well as nested for loops. However that is as far as he has explained to us how to do, and I'm completely stuck even whilst looking up online guides. m = [[12, 7, 23, 32], [18, 9, 6, 30], [4, 21, 98, 72], [62, 38, 15, 2]] oddCount = 0 for x in m: if x % 2 != 0: That is the current state of my code. I am painfully aware of how wrong it might be, but with the little information I have on hand that is all I could come up with. It spits out an error, saying that the modulo operator doesn't work if the object is a list or an integer, and for some reason x is of type list despite me not having it defined as a list.
[ "You're on the right track, but since the arrays are nested you need to use a nested for loop to access the array elements and not just the arrays themselves.\nfor array in m:\n for x in array:\n if x % 2 != 0:\n\nAnd from there just sum up the odd elements.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074551380_python.txt
Q: ModuleNotFoundError but module is installed I have pip installed colorgram.py but I am still getting an error: ModuleNotFoundError: No module named 'colorgram' I have also created a path to the python location: C:\Users\me\AppData\Local\Programs\Python\Python39 C:\Users\me\AppData\Local\Programs\Python\Python39/scripts any idea how to fix this? A: I guess you've installed the module with a different python version than you have run it. To fix this you can run python -m pip install <the-name-of-the-module> and than run the script with python <path-to-your-script>. If you want to use python3 just replace all python with python3. A: I ran into this same issue which brought me here. I found a solution in my case. The package was installed, attempts to re-install said requirement already satisfied. In my case the tool I was trying to use (pytest) was not installed in the venv but was installed in the path. Installing pytest into the same venv solved the issue. A: same problem. Try to create a new project, it's probably you install colorgram.py after creating the project and the module is not contained in venv, installing colorgram.py from pycharm directly might help too. A: I solved this issue recently by updating my $PYTHONPATH to match my site-packages. I couldn't use a module command from the commandline (e.g. ModuleNotFoundError: No module named 'onelogin_aws_cli') When you pip install the Module, note where it's already installed (e.g. Requirement already satisfied: onelogin-aws-cli==0.1.6 in ./venv/lib/python3.9/site-packages (0.1.6)) Set your Python path to the location of the site packages (e.g. export $PYTHONPATH=./venv/lib/python3.9/site-packages) I was then able to use the onelogin_aws_cli command from the commandline.
ModuleNotFoundError but module is installed
I have pip installed colorgram.py but I am still getting an error: ModuleNotFoundError: No module named 'colorgram' I have also created a path to the python location: C:\Users\me\AppData\Local\Programs\Python\Python39 C:\Users\me\AppData\Local\Programs\Python\Python39/scripts any idea how to fix this?
[ "I guess you've installed the module with a different python version than you have run it. To fix this you can run python -m pip install <the-name-of-the-module> and than run the script with python <path-to-your-script>. If you want to use python3 just replace all python with python3.\n", "I ran into this same issue which brought me here.\nI found a solution in my case. The package was installed, attempts to re-install said requirement already satisfied.\nIn my case the tool I was trying to use (pytest) was not installed in the venv but was installed in the path. Installing pytest into the same venv solved the issue.\n", "same problem. Try to create a new project, it's probably you install colorgram.py after creating the project and the module is not contained in venv, installing colorgram.py from pycharm directly might help too.\n", "I solved this issue recently by updating my $PYTHONPATH to match my site-packages. I couldn't use a module command from the commandline (e.g. ModuleNotFoundError: No module named 'onelogin_aws_cli')\n\nWhen you pip install the Module, note where it's already installed (e.g. Requirement already satisfied: onelogin-aws-cli==0.1.6 in ./venv/lib/python3.9/site-packages (0.1.6))\nSet your Python path to the location of the site packages (e.g. export $PYTHONPATH=./venv/lib/python3.9/site-packages)\n\nI was then able to use the onelogin_aws_cli command from the commandline.\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0065458461_python.txt
Q: How to properly Install mediapipe on Raspberry Pi I tried to Install mediapipe for Python on Raspberry Pi 4 Model B with Raspbian OS 11 (Bullseye). I have followed the expected Steps like "sudo pip3 install mediapipe-rpi4". Its successfully installed referring to the terminal, but when i try to import it in a Python file it returns a module not found Error. Is it because of the 64 bit OS? A: Did you ever find a solution to this? The solution posted at github here: https://github.com/superuser789/MediaPipe-on-RaspberryPi/issues/10 Worked for me, and could get mediapipe working on the Raspberry Pi running either 64 bit or 32 bit bullseye. Be aware that this method results in the mediapipe install upgrading openCV to 4.6.0 which is not enabled for gstreamer so you will not be able to run the raspberry pi camera under opencv. It does allow running a webcam, in opencv, with mediapipe. Getting mediapipe on the Raspberry Pi running Bullseye with the pi cam is proving to be quiet illusive.
How to properly Install mediapipe on Raspberry Pi
I tried to Install mediapipe for Python on Raspberry Pi 4 Model B with Raspbian OS 11 (Bullseye). I have followed the expected Steps like "sudo pip3 install mediapipe-rpi4". Its successfully installed referring to the terminal, but when i try to import it in a Python file it returns a module not found Error. Is it because of the 64 bit OS?
[ "Did you ever find a solution to this?\nThe solution posted at github here:\nhttps://github.com/superuser789/MediaPipe-on-RaspberryPi/issues/10\nWorked for me, and could get mediapipe working on the Raspberry Pi running either 64 bit or 32 bit bullseye. Be aware that this method results in the mediapipe install upgrading openCV to 4.6.0 which is not enabled for gstreamer so you will not be able to run the raspberry pi camera under opencv. It does allow running a webcam, in opencv, with mediapipe.\nGetting mediapipe on the Raspberry Pi running Bullseye with the pi cam is proving to be quiet illusive.\n" ]
[ 0 ]
[]
[]
[ "computer_vision", "mediapipe", "python", "raspberry_pi", "raspberry_pi4" ]
stackoverflow_0073635109_computer_vision_mediapipe_python_raspberry_pi_raspberry_pi4.txt
Q: Select pytorch tensor elements by list of indices I guess I have a pretty simple problem. Let's take the following tensor of length 6 t = torch.tensor([10., 20., 30., 40., 50., 60.]) Now I would like to to access only the elements at specific indices, lets say at [0, 3, 4]. So I would like to return # exptected output tensor([10., 40., 50.]) I found torch.index_select which worked great for a tensor of two dimensions, e.g. dimension (2, 4), but not for the given t for example. How can access a set of elements based on a given list of indices in a 1-d tensor without using a for loop? A: You can in fact use index_select for this: t = torch.tensor([10., 20., 30., 40., 50., 60.]) output = torch.index_select(t, 0, torch.LongTensor([0, 3, 4])) # output: tensor([10., 40., 50.]) You just need to specify the dimension (0) as the second parameter. This is the only valid dimension to specify for a 1-d input tensor.
Select pytorch tensor elements by list of indices
I guess I have a pretty simple problem. Let's take the following tensor of length 6 t = torch.tensor([10., 20., 30., 40., 50., 60.]) Now I would like to to access only the elements at specific indices, lets say at [0, 3, 4]. So I would like to return # exptected output tensor([10., 40., 50.]) I found torch.index_select which worked great for a tensor of two dimensions, e.g. dimension (2, 4), but not for the given t for example. How can access a set of elements based on a given list of indices in a 1-d tensor without using a for loop?
[ "You can in fact use index_select for this:\nt = torch.tensor([10., 20., 30., 40., 50., 60.])\noutput = torch.index_select(t, 0, torch.LongTensor([0, 3, 4]))\n# output: tensor([10., 40., 50.])\n\nYou just need to specify the dimension (0) as the second parameter. This is the only valid dimension to specify for a 1-d input tensor.\n" ]
[ 1 ]
[]
[]
[ "python", "pytorch", "tensor" ]
stackoverflow_0074551428_python_pytorch_tensor.txt
Q: How do I assign a split list into different variable names? listA = [11, 18, 19, 21, 29, 46] length = len(listA) splits = np.array_split(listA, length) i = 0 for array in splits: print("test" + str([i])) print(list(array)) i += 1 Output: test[0] [11] test[1] [18] test[2] [19] test[3] [21] test[4] [29] test[5] [46] What I am trying to accomplish here in this example is instead of printing out test[0] through test[5] and the items below (each in a new list), I want to do an assignment to a variable. To clarify what I mean I would basically like to name each list test[0] through 5 as variables so that I could work with them in my code later on. A: Are you just looking to make a dictionary? If you're looking to make the actual variables test0 test1 test2 etc... that's a TERRIBLE idea unless done explicitly like in Paul M.'s comment: a, b, c, d, e, f = splits Given: listA = [11, 18, 19, 21, 29, 46] Doing: dictA = {f'test{i}':v for i, v in enumerate(listA)} print(dictA) print(dictA['test4']) Output: {'test0': 11, 'test1': 18, 'test2': 19, 'test3': 21, 'test4': 29, 'test5': 46} 29
How do I assign a split list into different variable names?
listA = [11, 18, 19, 21, 29, 46] length = len(listA) splits = np.array_split(listA, length) i = 0 for array in splits: print("test" + str([i])) print(list(array)) i += 1 Output: test[0] [11] test[1] [18] test[2] [19] test[3] [21] test[4] [29] test[5] [46] What I am trying to accomplish here in this example is instead of printing out test[0] through test[5] and the items below (each in a new list), I want to do an assignment to a variable. To clarify what I mean I would basically like to name each list test[0] through 5 as variables so that I could work with them in my code later on.
[ "Are you just looking to make a dictionary?\n\nIf you're looking to make the actual variables test0 test1 test2 etc... that's a TERRIBLE idea unless done explicitly like in Paul M.'s comment: a, b, c, d, e, f = splits\n\nGiven:\nlistA = [11, 18, 19, 21, 29, 46]\n\nDoing:\ndictA = {f'test{i}':v for i, v in enumerate(listA)}\n\nprint(dictA)\nprint(dictA['test4'])\n\nOutput:\n{'test0': 11, 'test1': 18, 'test2': 19, 'test3': 21, 'test4': 29, 'test5': 46}\n29\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074551265_python_python_3.x.txt
Q: how to keep history of all outputs a user receives when inputting in a program I need to keep track of inputs in my program and store the outputs in a list so they can be replayed(printed out in the end to keep track of the program. history=[] def get_input(): global history answer=input("enter:") history.append(answer) if answer=="off": print("hi") else: if answer=="forward": print("moved forward") elif answer=="back": print("moved back") answer=get_input() #history.append(answer) return history print(get_input()) I tried doing this but it only returned the actual inputs and not the outputs they led to. A: def get_input(history): answer = input("enter:") history.append(answer) if answer == "off": print("hi") return history else: if answer == "forward": print("moved forward") elif answer == "back": print("moved back") return get_input(history) print(get_input([])) enter:forward moved forward enter:back moved back enter:off hi ['forward', 'back', 'off']
how to keep history of all outputs a user receives when inputting in a program
I need to keep track of inputs in my program and store the outputs in a list so they can be replayed(printed out in the end to keep track of the program. history=[] def get_input(): global history answer=input("enter:") history.append(answer) if answer=="off": print("hi") else: if answer=="forward": print("moved forward") elif answer=="back": print("moved back") answer=get_input() #history.append(answer) return history print(get_input()) I tried doing this but it only returned the actual inputs and not the outputs they led to.
[ "def get_input(history):\n answer = input(\"enter:\")\n history.append(answer)\n if answer == \"off\":\n print(\"hi\")\n return history\n else:\n if answer == \"forward\":\n print(\"moved forward\")\n elif answer == \"back\":\n print(\"moved back\")\n return get_input(history)\n\nprint(get_input([]))\n\nenter:forward\nmoved forward\nenter:back\nmoved back\nenter:off\nhi\n['forward', 'back', 'off']\n\n" ]
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074551479_list_python.txt
Q: Python __float__() magic method not converting my custom class object I am trying to use 2 classes to calculate the perimeter of a triangle. Whatever I do I cannot convert the 3 triangle legs' lengths from data type "Point" (vertice1, vertice2, vertice3) into floats. The following error is displayed when I sum them to get the perimeter of the triangle : File "main.py", line 37, in perimeter self.__total += float(self.__mylist[element]) TypeError: float() argument must be a string or a number, not 'Point' Here is the code : import math class Point: def __init__(self, x=0.0, y=0.0): self.__x = float(x) self.__y = float(y) def getx(self, x2): return x2 - self.__x def gety(self, y2): return y2 - self.__y def distance_from_xy(self, x2, y2): return math.hypot(self.getx(x2), self.gety(y2)) def distance_from_point(self, point): return math.hypot(self.getx(point.__dict__['_Point__x']), self.gety(point.__dict__['_Point__y'])) class Triangle: def __init__(self, vertice1, vertice2, vertice3): self.__vertice1 = vertice1 self.__vertice2 = vertice2 self.__vertice3 = vertice3 self.__mylist = [self.__vertice1, self.__vertice2, self.__vertice3] self.__total = 0 def __float__(self): return self.__mylist[self.__vertice1], self.__mylist[self.__vertice2], self.__mylist[self.__vertice3] def perimeter(self): for element in range(0, len(self.__mylist)): self.__total += float(self.__mylist[element]) return self.__total triangle = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) print(triangle.perimeter()) Following my research, I understand that I need to convert my custom class object into a float before to be able to use the "+" operator but I am obviously wrong somewhere. Thank you! A: I understand that I need to convert my custom class object into a float before to be able to use the "+" operator but I am obviously wrong somewhere. At the part where you're never telling Python how to convert your custom type to a float: float will work out of the box on "built-in" types, but for a custom type (such as the Point you're using it on) it just calls the __float__ magic method. Since there is no Point.__float__, it raises an error instead, your Point is not convertible to a float. Your code also makes no sense, as you're apparently trying to convert the individual points to floats, and... that doesn't really make sense? I guess you could express a point as the decimal value x.y but then the addition of these makes no sense. Why don't you just compute the distances between your three points and add that? You even have helper functions for that... Other issues. your use of __ is incorrect, the purpose of the double-underscore prefix is not to emulate private variables in other languages (that is not a thing in Python), it's to avoid innocent conflicts during inheritance why are you accessing __dict__ and mangled attribute names? why are you storing both individual vertices and a list of all vertices? getx and gety are very strange names for what are apparently the x and y distances between points why are you storing the perimeter on the Triangle, and not even using that as a cache? Suggestion: something along the lines of class Point: def __init__(self, x=0.0, y=0.0): self.x = float(x) self.y = float(y) def distance(self, other): return abs(math.hypot(other.x - self.x, other.y - self.y)) class Triangle: def __init__(self, vertice1, vertice2, vertice3): self.v1 = vertice1 self.v2 = vertice2 self.v3 = vertice3 def perimeter(self): return self.v1.distance(self.v2)\ + self.v2.distance(self.v3)\ + self.v3.distance(self.v1) triangle = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) print(triangle.perimeter()) or slightly more modern: @dataclass class Point: x: float y: float def distance(self, other): return math.dist(astuple(self), astuple(other)) @dataclass class Triangle: v1: Point v2: Point v3: Point def perimeter(self): return self.v1.distance(self.v2)\ + self.v2.distance(self.v3)\ + self.v3.distance(self.v1) triangle = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) print(triangle.perimeter()) For perimeter we could go wild with weird functional code and it'd definitely be fun, but it'd also be less readable and less efficient: def perimeter(self): return sum(map( Point.distance, attrgetter('v1', 'v2', 'v3')(self), attrgetter('v2', 'v3', 'v1')(self), )) alternatively leaning more on the dataclass features: def perimeter(self): points = astuple(self) points2 = points[1:] + points[:1] return sum(map(math.dist, points, points2)) (at which point Point.distance is a bit obsolete)
Python __float__() magic method not converting my custom class object
I am trying to use 2 classes to calculate the perimeter of a triangle. Whatever I do I cannot convert the 3 triangle legs' lengths from data type "Point" (vertice1, vertice2, vertice3) into floats. The following error is displayed when I sum them to get the perimeter of the triangle : File "main.py", line 37, in perimeter self.__total += float(self.__mylist[element]) TypeError: float() argument must be a string or a number, not 'Point' Here is the code : import math class Point: def __init__(self, x=0.0, y=0.0): self.__x = float(x) self.__y = float(y) def getx(self, x2): return x2 - self.__x def gety(self, y2): return y2 - self.__y def distance_from_xy(self, x2, y2): return math.hypot(self.getx(x2), self.gety(y2)) def distance_from_point(self, point): return math.hypot(self.getx(point.__dict__['_Point__x']), self.gety(point.__dict__['_Point__y'])) class Triangle: def __init__(self, vertice1, vertice2, vertice3): self.__vertice1 = vertice1 self.__vertice2 = vertice2 self.__vertice3 = vertice3 self.__mylist = [self.__vertice1, self.__vertice2, self.__vertice3] self.__total = 0 def __float__(self): return self.__mylist[self.__vertice1], self.__mylist[self.__vertice2], self.__mylist[self.__vertice3] def perimeter(self): for element in range(0, len(self.__mylist)): self.__total += float(self.__mylist[element]) return self.__total triangle = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) print(triangle.perimeter()) Following my research, I understand that I need to convert my custom class object into a float before to be able to use the "+" operator but I am obviously wrong somewhere. Thank you!
[ "\nI understand that I need to convert my custom class object into a float before to be able to use the \"+\" operator but I am obviously wrong somewhere.\n\nAt the part where you're never telling Python how to convert your custom type to a float: float will work out of the box on \"built-in\" types, but for a custom type (such as the Point you're using it on) it just calls the __float__ magic method. Since there is no Point.__float__, it raises an error instead, your Point is not convertible to a float.\nYour code also makes no sense, as you're apparently trying to convert the individual points to floats, and... that doesn't really make sense? I guess you could express a point as the decimal value x.y but then the addition of these makes no sense.\nWhy don't you just compute the distances between your three points and add that? You even have helper functions for that...\nOther issues.\n\nyour use of __ is incorrect, the purpose of the double-underscore prefix is not to emulate private variables in other languages (that is not a thing in Python), it's to avoid innocent conflicts during inheritance\nwhy are you accessing __dict__ and mangled attribute names?\nwhy are you storing both individual vertices and a list of all vertices?\ngetx and gety are very strange names for what are apparently the x and y distances between points\nwhy are you storing the perimeter on the Triangle, and not even using that as a cache?\n\nSuggestion: something along the lines of\nclass Point:\n def __init__(self, x=0.0, y=0.0):\n self.x = float(x)\n self.y = float(y)\n\n def distance(self, other):\n return abs(math.hypot(other.x - self.x, other.y - self.y))\n\nclass Triangle:\n def __init__(self, vertice1, vertice2, vertice3):\n self.v1 = vertice1\n self.v2 = vertice2\n self.v3 = vertice3\n\n def perimeter(self):\n return self.v1.distance(self.v2)\\\n + self.v2.distance(self.v3)\\\n + self.v3.distance(self.v1)\n\ntriangle = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))\nprint(triangle.perimeter())\n\nor slightly more modern:\n@dataclass\nclass Point:\n x: float\n y: float\n\n def distance(self, other):\n return math.dist(astuple(self), astuple(other))\n\n@dataclass\nclass Triangle:\n v1: Point\n v2: Point\n v3: Point\n\n def perimeter(self):\n return self.v1.distance(self.v2)\\\n + self.v2.distance(self.v3)\\\n + self.v3.distance(self.v1)\n\ntriangle = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))\nprint(triangle.perimeter())\n\nFor perimeter we could go wild with weird functional code and it'd definitely be fun, but it'd also be less readable and less efficient:\n def perimeter(self):\n return sum(map(\n Point.distance,\n attrgetter('v1', 'v2', 'v3')(self),\n attrgetter('v2', 'v3', 'v1')(self),\n ))\n\nalternatively leaning more on the dataclass features:\n def perimeter(self):\n points = astuple(self)\n points2 = points[1:] + points[:1]\n return sum(map(math.dist, points, points2))\n\n(at which point Point.distance is a bit obsolete)\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074532096_python.txt
Q: I can't figure out pip tensorrt line 17 error I couldn't install it in any way, I wonder what could be the cause of the error. I installed C++ and other necessary stuff I am using windows 11 I installed pip install nvidia-pyindex with no problem. Same as tensorrt I can't install pycuda library and I get same error \` (base) PS C:\\Users\\byara\> pip install nvidia-tensorrt Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com Collecting nvidia-tensorrt Downloading nvidia-tensorrt-0.0.1.dev5.tar.gz (7.9 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─\> \[17 lines of output\] Traceback (most recent call last): File "\<string\>", line 2, in \<module\> File "\<pip-setuptools-caller\>", line 34, in \<module\> File "C:\\Users\\byara\\AppData\\Local\\Temp\\pip-install-ak3sxwfw\\nvidia-tensorrt_a7512906bd3241728853c0e6a10bf9d4\\setup.py", line 150, in \<module\> raise RuntimeError(open("ERROR.txt", "r").read()) RuntimeError: \########################################################################################### The package you are trying to install is only a placeholder project on PyPI.org repository. This package is hosted on NVIDIA Python Package Index. This package can be installed as: ` $ pip install nvidia-pyindex $ pip install nvidia-tensorrt `your text` ########################################################################################### [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─\> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. \` A: TensorRT is not available for Windows via pip. You can verify that by looking at the wheel files in PyPI, link. All the wheel files for the latest version are for Linux. Thus, trying to install on Windows will pick the previous releases, which were place-holder packages. Those releases just print the message you are seeing, on all OSes. According to the documentation The zip file is the only option currently for Windows. You can find instructions on how to install at Zip File Installation.
I can't figure out pip tensorrt line 17 error
I couldn't install it in any way, I wonder what could be the cause of the error. I installed C++ and other necessary stuff I am using windows 11 I installed pip install nvidia-pyindex with no problem. Same as tensorrt I can't install pycuda library and I get same error \` (base) PS C:\\Users\\byara\> pip install nvidia-tensorrt Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com Collecting nvidia-tensorrt Downloading nvidia-tensorrt-0.0.1.dev5.tar.gz (7.9 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─\> \[17 lines of output\] Traceback (most recent call last): File "\<string\>", line 2, in \<module\> File "\<pip-setuptools-caller\>", line 34, in \<module\> File "C:\\Users\\byara\\AppData\\Local\\Temp\\pip-install-ak3sxwfw\\nvidia-tensorrt_a7512906bd3241728853c0e6a10bf9d4\\setup.py", line 150, in \<module\> raise RuntimeError(open("ERROR.txt", "r").read()) RuntimeError: \########################################################################################### The package you are trying to install is only a placeholder project on PyPI.org repository. This package is hosted on NVIDIA Python Package Index. This package can be installed as: ` $ pip install nvidia-pyindex $ pip install nvidia-tensorrt `your text` ########################################################################################### [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─\> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. \`
[ "TensorRT is not available for Windows via pip. You can verify that by looking at the wheel files in PyPI, link. All the wheel files for the latest version are for Linux. Thus, trying to install on Windows will pick the previous releases, which were place-holder packages. Those releases just print the message you are seeing, on all OSes.\nAccording to the documentation\n\nThe zip file is the only option currently for Windows.\n\nYou can find instructions on how to install at Zip File Installation.\n" ]
[ 0 ]
[]
[]
[ "nvidia", "pip", "python", "tensorrt", "windows" ]
stackoverflow_0074520032_nvidia_pip_python_tensorrt_windows.txt
Q: BeautifulSoup - search by text inside a tag Observe the following problem: import re from bs4 import BeautifulSoup as BS soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> Edit </a> """) # This returns the <a> element soup.find( 'a', href="/customer-menu/1/accounts/1/update", text=re.compile(".*Edit.*") ) soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> <i class="fa fa-edit"></i> Edit </a> """) # This returns None soup.find( 'a', href="/customer-menu/1/accounts/1/update", text=re.compile(".*Edit.*") ) For some reason, BeautifulSoup will not match the text, when the <i> tag is there as well. Finding the tag and showing its text produces >>> a2 = soup.find( 'a', href="/customer-menu/1/accounts/1/update" ) >>> print(repr(a2.text)) '\n Edit\n' Right. According to the Docs, soup uses the match function of the regular expression, not the search function. So I need to provide the DOTALL flag: pattern = re.compile('.*Edit.*') pattern.match('\n Edit\n') # Returns None pattern = re.compile('.*Edit.*', flags=re.DOTALL) pattern.match('\n Edit\n') # Returns MatchObject Alright. Looks good. Let's try it with soup soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> <i class="fa fa-edit"></i> Edit </a> """) soup.find( 'a', href="/customer-menu/1/accounts/1/update", text=re.compile(".*Edit.*", flags=re.DOTALL) ) # Still return None... Why?! Edit My solution based on geckons answer: I implemented these helpers: import re MATCH_ALL = r'.*' def like(string): """ Return a compiled regular expression that matches the given string with any prefix and postfix, e.g. if string = "hello", the returned regex matches r".*hello.*" """ string_ = string if not isinstance(string_, str): string_ = str(string_) regex = MATCH_ALL + re.escape(string_) + MATCH_ALL return re.compile(regex, flags=re.DOTALL) def find_by_text(soup, text, tag, **kwargs): """ Find the tag in soup that matches all provided kwargs, and contains the text. If no match is found, return None. If more than one match is found, raise ValueError. """ elements = soup.find_all(tag, **kwargs) matches = [] for element in elements: if element.find(text=like(text)): matches.append(element) if len(matches) > 1: raise ValueError("Too many matches:\n" + "\n".join(matches)) elif len(matches) == 0: return None else: return matches[0] Now, when I want to find the element above, I just run find_by_text(soup, 'Edit', 'a', href='/customer-menu/1/accounts/1/update') A: The problem is that your <a> tag with the <i> tag inside, doesn't have the string attribute you expect it to have. First let's take a look at what text="" argument for find() does. NOTE: The text argument is an old name, since BeautifulSoup 4.4.0 it's called string. From the docs: Although string is for finding strings, you can combine it with arguments that find tags: Beautiful Soup will find all tags whose .string matches your value for string. This code finds the tags whose .string is “Elsie”: soup.find_all("a", string="Elsie") # [<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>] Now let's take a look what Tag's string attribute is (from the docs again): If a tag has only one child, and that child is a NavigableString, the child is made available as .string: title_tag.string # u'The Dormouse's story' (...) If a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to be None: print(soup.html.string) # None This is exactly your case. Your <a> tag contains a text and <i> tag. Therefore, the find gets None when trying to search for a string and thus it can't match. How to solve this? Maybe there is a better solution but I would probably go with something like this: import re from bs4 import BeautifulSoup as BS soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> <i class="fa fa-edit"></i> Edit </a> """) links = soup.find_all('a', href="/customer-menu/1/accounts/1/update") for link in links: if link.find(text=re.compile("Edit")): thelink = link break print(thelink) I think there are not too many links pointing to /customer-menu/1/accounts/1/update so it should be fast enough. A: in one line using lambda soup.find(lambda tag:tag.name=="a" and "Edit" in tag.text) A: You can pass a function that return True if a text contains "Edit" to .find In [51]: def Edit_in_text(tag): ....: return tag.name == 'a' and 'Edit' in tag.text ....: In [52]: soup.find(Edit_in_text, href="/customer-menu/1/accounts/1/update") Out[52]: <a href="/customer-menu/1/accounts/1/update"> <i class="fa fa-edit"></i> Edit </a> EDIT: You can use the .get_text() method instead of the text in your function which gives the same result: def Edit_in_text(tag): return tag.name == 'a' and 'Edit' in tag.get_text() A: With soupsieve 2.1.0 you can use :-soup-contains css pseudo class selector to target a node's text. This replaces the deprecated form of :contains(). from bs4 import BeautifulSoup as BS soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> Edit </a> """) single = soup.select_one('a:-soup-contains("Edit")').text.strip() multiple = [i.text.strip() for i in soup.select('a:-soup-contains("Edit")')] print(single, '\n', multiple) A: Method - 1: Checking text property pattern = 'Edit' a2 = soup.find_all('a', string = pattern)[0] Method - 2: Using lambda iterate through all elements a2 = soup.find(lambda tag:tag.name=="a" and "Edit" in tag.text) Good Luck
BeautifulSoup - search by text inside a tag
Observe the following problem: import re from bs4 import BeautifulSoup as BS soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> Edit </a> """) # This returns the <a> element soup.find( 'a', href="/customer-menu/1/accounts/1/update", text=re.compile(".*Edit.*") ) soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> <i class="fa fa-edit"></i> Edit </a> """) # This returns None soup.find( 'a', href="/customer-menu/1/accounts/1/update", text=re.compile(".*Edit.*") ) For some reason, BeautifulSoup will not match the text, when the <i> tag is there as well. Finding the tag and showing its text produces >>> a2 = soup.find( 'a', href="/customer-menu/1/accounts/1/update" ) >>> print(repr(a2.text)) '\n Edit\n' Right. According to the Docs, soup uses the match function of the regular expression, not the search function. So I need to provide the DOTALL flag: pattern = re.compile('.*Edit.*') pattern.match('\n Edit\n') # Returns None pattern = re.compile('.*Edit.*', flags=re.DOTALL) pattern.match('\n Edit\n') # Returns MatchObject Alright. Looks good. Let's try it with soup soup = BS(""" <a href="/customer-menu/1/accounts/1/update"> <i class="fa fa-edit"></i> Edit </a> """) soup.find( 'a', href="/customer-menu/1/accounts/1/update", text=re.compile(".*Edit.*", flags=re.DOTALL) ) # Still return None... Why?! Edit My solution based on geckons answer: I implemented these helpers: import re MATCH_ALL = r'.*' def like(string): """ Return a compiled regular expression that matches the given string with any prefix and postfix, e.g. if string = "hello", the returned regex matches r".*hello.*" """ string_ = string if not isinstance(string_, str): string_ = str(string_) regex = MATCH_ALL + re.escape(string_) + MATCH_ALL return re.compile(regex, flags=re.DOTALL) def find_by_text(soup, text, tag, **kwargs): """ Find the tag in soup that matches all provided kwargs, and contains the text. If no match is found, return None. If more than one match is found, raise ValueError. """ elements = soup.find_all(tag, **kwargs) matches = [] for element in elements: if element.find(text=like(text)): matches.append(element) if len(matches) > 1: raise ValueError("Too many matches:\n" + "\n".join(matches)) elif len(matches) == 0: return None else: return matches[0] Now, when I want to find the element above, I just run find_by_text(soup, 'Edit', 'a', href='/customer-menu/1/accounts/1/update')
[ "The problem is that your <a> tag with the <i> tag inside, doesn't have the string attribute you expect it to have. First let's take a look at what text=\"\" argument for find() does.\nNOTE: The text argument is an old name, since BeautifulSoup 4.4.0 it's called string.\nFrom the docs:\n\nAlthough string is for finding strings, you can combine it with\n arguments that find tags: Beautiful Soup will find all tags whose\n .string matches your value for string. This code finds the tags\n whose .string is “Elsie”:\nsoup.find_all(\"a\", string=\"Elsie\")\n# [<a href=\"http://example.com/elsie\" class=\"sister\" id=\"link1\">Elsie</a>]\n\n\nNow let's take a look what Tag's string attribute is (from the docs again):\n\nIf a tag has only one child, and that child is a NavigableString, the\n child is made available as .string:\ntitle_tag.string\n# u'The Dormouse's story'\n\n\n(...)\n\nIf a tag contains more than one thing, then it’s not clear what\n .string should refer to, so .string is defined to be None:\nprint(soup.html.string)\n# None\n\n\nThis is exactly your case. Your <a> tag contains a text and <i> tag. Therefore, the find gets None when trying to search for a string and thus it can't match.\nHow to solve this?\nMaybe there is a better solution but I would probably go with something like this:\nimport re\nfrom bs4 import BeautifulSoup as BS\n\nsoup = BS(\"\"\"\n<a href=\"/customer-menu/1/accounts/1/update\">\n <i class=\"fa fa-edit\"></i> Edit\n</a>\n\"\"\")\n\nlinks = soup.find_all('a', href=\"/customer-menu/1/accounts/1/update\")\n\nfor link in links:\n if link.find(text=re.compile(\"Edit\")):\n thelink = link\n break\n\nprint(thelink)\n\nI think there are not too many links pointing to /customer-menu/1/accounts/1/update so it should be fast enough.\n", "in one line using lambda\nsoup.find(lambda tag:tag.name==\"a\" and \"Edit\" in tag.text)\n\n", "You can pass a function that return True if a text contains \"Edit\" to .find\nIn [51]: def Edit_in_text(tag):\n ....: return tag.name == 'a' and 'Edit' in tag.text\n ....: \n\nIn [52]: soup.find(Edit_in_text, href=\"/customer-menu/1/accounts/1/update\")\nOut[52]: \n<a href=\"/customer-menu/1/accounts/1/update\">\n<i class=\"fa fa-edit\"></i> Edit\n</a>\n\n\nEDIT:\nYou can use the .get_text() method instead of the text in your function which gives the same result:\ndef Edit_in_text(tag):\n return tag.name == 'a' and 'Edit' in tag.get_text()\n\n", "With soupsieve 2.1.0 you can use :-soup-contains css pseudo class selector to target a node's text. This replaces the deprecated form of :contains().\nfrom bs4 import BeautifulSoup as BS\n\nsoup = BS(\"\"\"\n<a href=\"/customer-menu/1/accounts/1/update\">\n Edit\n</a>\n\"\"\")\nsingle = soup.select_one('a:-soup-contains(\"Edit\")').text.strip()\nmultiple = [i.text.strip() for i in soup.select('a:-soup-contains(\"Edit\")')]\nprint(single, '\\n', multiple)\n\n", "\nMethod - 1: Checking text property\n\n pattern = 'Edit'\n a2 = soup.find_all('a', string = pattern)[0]\n\n\nMethod - 2: Using lambda iterate through all elements\n\n a2 = soup.find(lambda tag:tag.name==\"a\" and \"Edit\" in tag.text)\n\nGood Luck\n" ]
[ 91, 79, 17, 6, 1 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0031958637_beautifulsoup_python_regex.txt
Q: How to find the number of unordered pairs of 2D coordinate points, whose joining line passes through origin? (Original problem description) Pair of points You are given the following An integer N A 2D array of length N denoting the points in the 2D coordinate system, that is (x, y) Task Determine the number of unordered pairs (i, j) or (j, i) and i != j such that The straight line connecting the points (A[i][1], A[i][2]) and (A[j][1], A[j][2]) passes through (0, 0) (Context, this was a coding problem on hacker earth site and I did solve it (bruteforce) method) My code: def find_pairs(array, size): li = [] for i in range(size): for j in range(size): if (i, j) not in li and (j, i) not in li: if ((array[i][1] * (array[j][0] - array[i][0])) == ((array[i][0] * (array[j][1] - array[i][1]))): li.append((i,j)) return len(li) The math the code uses is, given two points (x1, y1) and (x2, y2), their line passes through the origin if they satisfy the equation (x1 * (y2 - y1)) = (y1 * (x2 - x1)) This code passed half the test cases (which were testing for correct answer) but failed the remaining which had time constraint. I tried to use itertools.combinations but it exceeded the memory limit Is there any way to write a program with less than N2 time complexity? A: One optimization we can make in your code is not to check previously traversed co-ordinates: def find_pairs(array, size): count = 0 for i in range(size - 1): for j in range(i + 1, size): if ((array[i][1] * (array[j][0] - array[i][0])) == ((array[i][0] * (array[j][1] - array[i][1]))): count += 1 return count A: Put tangent (slope) of line origin-to-point into Counter (in general - dictionary with value as counter for old Python without this class). Make separate counter for points with x=0 (vertical line). After putting all slopes into the map, retieve number of pairs for every slope - n points with the same slope give n*(n-1)/2 pairs Linear complexity. from collections import Counter pts = [[1,0],[2,2],[-1,-1],[4,4],[0,2],[-2,0]] vert = 0 cntr = Counter() for p in pts: if p[0]: cntr[p[1]/p[0]] += 1 else: vert += 1 res = vert * (vert - 1) // 2 for v in cntr.values(): res += v*(v-1) // 2 print(res) # 4 pairs Update: accounts for (0,0): from collections import Counter pts = [[1,0],[2,2],[-1,-1],[4,4],[0,2],[-2,0],[0,0],[0,0]] vert = 0 zeros = 0 cntr = Counter() for p in pts: if p[0]: cntr[p[1]/p[0]] += 1 else: if p[1]: vert += 1 else: zeros += 1 res = vert * (vert - 1) // 2 for v in cntr.values(): res += v*(v-1) // 2 res += (len(pts) - zeros) * zeros + zeros*(zeros-1)//2 print(res) //17 pairs Potential pitfall - float number comparison might give wrong results for some pairs. If points are integers, it is possible to use integer tuple ( sign(x)*y/gcd(y,x), abs(x)/gcd(x,y) ) as key A: If using itertools.combinations exceeded your memory limit then you used it incorrectly. The functions in the itertools library are generally quite memory efficient because they work with iterators rather than creating complete lists in memory. num_pairs = 0 for i, j in itertools.combinations(array, 2): if i_j_are_valid_points(): # your formula here num_pairs += 2 # (i, j) and (j, i) are both valid Note that this is still O(N^2) - you can't find all combinations of pairs in less time. But it will run over twice as fast as your solution since: 1) it doesn't check both (i, j) and (j, i) redundantly; 2) it doesn't need to traverse the list of already found solutions. A: I suspect you can do this in O(NlogN) (merge sort) time, at least in theory. If you convert to polar coordinates, then you're looking for two points (r_1, theta) and (r_2, theta + pi) so you can just sort them and then process from theta in [0, pi), and compare with those from theta in [pi, 2pi). If you use floating point numbers though, you'll need to be careful how you compare the two values because floating point values are only stored approximately.
How to find the number of unordered pairs of 2D coordinate points, whose joining line passes through origin?
(Original problem description) Pair of points You are given the following An integer N A 2D array of length N denoting the points in the 2D coordinate system, that is (x, y) Task Determine the number of unordered pairs (i, j) or (j, i) and i != j such that The straight line connecting the points (A[i][1], A[i][2]) and (A[j][1], A[j][2]) passes through (0, 0) (Context, this was a coding problem on hacker earth site and I did solve it (bruteforce) method) My code: def find_pairs(array, size): li = [] for i in range(size): for j in range(size): if (i, j) not in li and (j, i) not in li: if ((array[i][1] * (array[j][0] - array[i][0])) == ((array[i][0] * (array[j][1] - array[i][1]))): li.append((i,j)) return len(li) The math the code uses is, given two points (x1, y1) and (x2, y2), their line passes through the origin if they satisfy the equation (x1 * (y2 - y1)) = (y1 * (x2 - x1)) This code passed half the test cases (which were testing for correct answer) but failed the remaining which had time constraint. I tried to use itertools.combinations but it exceeded the memory limit Is there any way to write a program with less than N2 time complexity?
[ "One optimization we can make in your code is not to check previously traversed co-ordinates:\ndef find_pairs(array, size):\n count = 0\n for i in range(size - 1):\n for j in range(i + 1, size):\n if ((array[i][1] * (array[j][0] - array[i][0])) == ((array[i][0] * (array[j][1] - array[i][1]))):\n count += 1\n return count\n\n", "Put tangent (slope) of line origin-to-point into Counter (in general - dictionary with value as counter for old Python without this class). Make separate counter for points with x=0 (vertical line).\nAfter putting all slopes into the map, retieve number of pairs for every slope - n points with the same slope give n*(n-1)/2 pairs\nLinear complexity.\nfrom collections import Counter\npts = [[1,0],[2,2],[-1,-1],[4,4],[0,2],[-2,0]]\nvert = 0\ncntr = Counter()\nfor p in pts:\n if p[0]:\n cntr[p[1]/p[0]] += 1\n else:\n vert += 1\nres = vert * (vert - 1) // 2\nfor v in cntr.values():\n res += v*(v-1) // 2\nprint(res) # 4 pairs\n\nUpdate: accounts for (0,0):\nfrom collections import Counter\npts = [[1,0],[2,2],[-1,-1],[4,4],[0,2],[-2,0],[0,0],[0,0]]\nvert = 0\nzeros = 0\ncntr = Counter()\nfor p in pts:\n if p[0]:\n cntr[p[1]/p[0]] += 1\n else:\n if p[1]:\n vert += 1\n else:\n zeros += 1\nres = vert * (vert - 1) // 2\nfor v in cntr.values():\n res += v*(v-1) // 2\nres += (len(pts) - zeros) * zeros + zeros*(zeros-1)//2\nprint(res) //17 pairs\n \n\nPotential pitfall - float number comparison might give wrong results for some pairs.\nIf points are integers, it is possible to use integer tuple ( sign(x)*y/gcd(y,x), abs(x)/gcd(x,y) ) as key\n", "If using itertools.combinations exceeded your memory limit then you used it incorrectly. The functions in the itertools library are generally quite memory efficient because they work with iterators rather than creating complete lists in memory.\nnum_pairs = 0\nfor i, j in itertools.combinations(array, 2):\n if i_j_are_valid_points(): # your formula here\n num_pairs += 2 # (i, j) and (j, i) are both valid\n\nNote that this is still O(N^2) - you can't find all combinations of pairs in less time. But it will run over twice as fast as your solution since: 1) it doesn't check both (i, j) and (j, i) redundantly; 2) it doesn't need to traverse the list of already found solutions.\n", "I suspect you can do this in O(NlogN) (merge sort) time, at least in theory. If you convert to polar coordinates, then you're looking for two points (r_1, theta) and (r_2, theta + pi) so you can just sort them and then process from theta in [0, pi), and compare with those from theta in [pi, 2pi). If you use floating point numbers though, you'll need to be careful how you compare the two values because floating point values are only stored approximately.\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "math", "performance", "python" ]
stackoverflow_0074551043_math_performance_python.txt
Q: Conditionally match two dataframes of unequal size I have two dataframes of unequal size with examples below. We will refer to the first dataframe as df1: Miles AB Param1 Param2 Param3 Param4 1.5 A 0.12345 0.12345 0.12345 0.12345 1.7 B 0.12345 0.12345 0.12345 0.12345 1.9 A 0.12345 0.12345 0.12345 0.12345 2.6 A 0.12345 0.12345 0.12345 0.12345 2.7 B 0.12345 0.12345 0.12345 0.12345 3.5 B 0.12345 0.12345 0.12345 0.12345 5.6 A 0.12345 0.12345 0.12345 0.12345 7.8 B 0.12345 0.12345 0.12345 0.12345 9.9 B 0.12345 0.12345 0.12345 0.12345 Then a similar dataframe that has some similar information, but has a different column parameter AND is smaller than the dataframe above, for example as below, which we will refer to as df2: Miles AB Param5 1.9 A 56 2.5 A 69 3.4 B 42 5.6 A 41 What I am trying to do is add Param5 where applicable to the first table, with the conditions that the values in AB are the same AND the mile difference between the two files is no more than 0.1 (ideally the miles are equal, but based on the original sources of these files, sometimes they can be off by 0.1). Miles AB Param1 Param2 Param3 Param4 Param5 1.5 A 0.12345 0.12345 0.12345 0.12345 1.7 B 0.12345 0.12345 0.12345 0.12345 1.9 A 0.12345 0.12345 0.12345 0.12345 56 2.6 A 0.12345 0.12345 0.12345 0.12345 69 2.7 B 0.12345 0.12345 0.12345 0.12345 3.5 B 0.12345 0.12345 0.12345 0.12345 42 5.6 A 0.12345 0.12345 0.12345 0.12345 41 7.8 B 0.12345 0.12345 0.12345 0.12345 9.9 B 0.12345 0.12345 0.12345 0.12345 I am trying to use an np.where function like below but it obviously doesn't work in its current state given that the two dataframes have unequal numbers of rows: df1['Param5'] = np.where(((df2['AB']==df1['AB']) & (abs(df2['Miles']-df1['Miles'])<=0.1)), df2['Param5'],'') This then returns ValueError: Can only compare identically-labeled Series objects Any assistance would be much appreciated how I could get the two dataframes indexed together with the condition that the AB values are the same and the mile difference is no more than 0.1. Thank you in advance! A: Use a merge_asof: (pd.merge_asof(df1.reset_index().sort_values(by='Miles'), df2.sort_values(by='Miles'), by='AB', on='Miles', direction='nearest', tolerance=0.1) .set_index('index').sort_index() ) Output: Miles AB Param1 Param2 Param3 Param4 Param5 0 1.5 A 0.12345 0.12345 0.12345 0.12345 NaN 1 1.7 B 0.12345 0.12345 0.12345 0.12345 NaN 2 1.9 A 0.12345 0.12345 0.12345 0.12345 56.0 3 2.6 A 0.12345 0.12345 0.12345 0.12345 NaN 4 2.7 B 0.12345 0.12345 0.12345 0.12345 NaN 5 3.5 B 0.12345 0.12345 0.12345 0.12345 NaN 6 5.6 A 0.12345 0.12345 0.12345 0.12345 41.0 7 7.8 B 0.12345 0.12345 0.12345 0.12345 NaN 8 9.9 B 0.12345 0.12345 0.12345 0.12345 NaN Output with tolerance=0.10001: Miles AB Param1 Param2 Param3 Param4 Param5 0 1.5 A 0.12345 0.12345 0.12345 0.12345 NaN 1 1.7 B 0.12345 0.12345 0.12345 0.12345 NaN 2 1.9 A 0.12345 0.12345 0.12345 0.12345 56.0 3 2.6 A 0.12345 0.12345 0.12345 0.12345 69.0 4 2.7 B 0.12345 0.12345 0.12345 0.12345 NaN 5 3.5 B 0.12345 0.12345 0.12345 0.12345 42.0 6 5.6 A 0.12345 0.12345 0.12345 0.12345 41.0 7 7.8 B 0.12345 0.12345 0.12345 0.12345 NaN 8 9.9 B 0.12345 0.12345 0.12345 0.12345 NaN
Conditionally match two dataframes of unequal size
I have two dataframes of unequal size with examples below. We will refer to the first dataframe as df1: Miles AB Param1 Param2 Param3 Param4 1.5 A 0.12345 0.12345 0.12345 0.12345 1.7 B 0.12345 0.12345 0.12345 0.12345 1.9 A 0.12345 0.12345 0.12345 0.12345 2.6 A 0.12345 0.12345 0.12345 0.12345 2.7 B 0.12345 0.12345 0.12345 0.12345 3.5 B 0.12345 0.12345 0.12345 0.12345 5.6 A 0.12345 0.12345 0.12345 0.12345 7.8 B 0.12345 0.12345 0.12345 0.12345 9.9 B 0.12345 0.12345 0.12345 0.12345 Then a similar dataframe that has some similar information, but has a different column parameter AND is smaller than the dataframe above, for example as below, which we will refer to as df2: Miles AB Param5 1.9 A 56 2.5 A 69 3.4 B 42 5.6 A 41 What I am trying to do is add Param5 where applicable to the first table, with the conditions that the values in AB are the same AND the mile difference between the two files is no more than 0.1 (ideally the miles are equal, but based on the original sources of these files, sometimes they can be off by 0.1). Miles AB Param1 Param2 Param3 Param4 Param5 1.5 A 0.12345 0.12345 0.12345 0.12345 1.7 B 0.12345 0.12345 0.12345 0.12345 1.9 A 0.12345 0.12345 0.12345 0.12345 56 2.6 A 0.12345 0.12345 0.12345 0.12345 69 2.7 B 0.12345 0.12345 0.12345 0.12345 3.5 B 0.12345 0.12345 0.12345 0.12345 42 5.6 A 0.12345 0.12345 0.12345 0.12345 41 7.8 B 0.12345 0.12345 0.12345 0.12345 9.9 B 0.12345 0.12345 0.12345 0.12345 I am trying to use an np.where function like below but it obviously doesn't work in its current state given that the two dataframes have unequal numbers of rows: df1['Param5'] = np.where(((df2['AB']==df1['AB']) & (abs(df2['Miles']-df1['Miles'])<=0.1)), df2['Param5'],'') This then returns ValueError: Can only compare identically-labeled Series objects Any assistance would be much appreciated how I could get the two dataframes indexed together with the condition that the AB values are the same and the mile difference is no more than 0.1. Thank you in advance!
[ "Use a merge_asof:\n(pd.merge_asof(df1.reset_index().sort_values(by='Miles'),\n df2.sort_values(by='Miles'),\n by='AB', on='Miles',\n direction='nearest', tolerance=0.1)\n .set_index('index').sort_index()\n)\n\nOutput:\n Miles AB Param1 Param2 Param3 Param4 Param5\n0 1.5 A 0.12345 0.12345 0.12345 0.12345 NaN\n1 1.7 B 0.12345 0.12345 0.12345 0.12345 NaN\n2 1.9 A 0.12345 0.12345 0.12345 0.12345 56.0\n3 2.6 A 0.12345 0.12345 0.12345 0.12345 NaN\n4 2.7 B 0.12345 0.12345 0.12345 0.12345 NaN\n5 3.5 B 0.12345 0.12345 0.12345 0.12345 NaN\n6 5.6 A 0.12345 0.12345 0.12345 0.12345 41.0\n7 7.8 B 0.12345 0.12345 0.12345 0.12345 NaN\n8 9.9 B 0.12345 0.12345 0.12345 0.12345 NaN\n\nOutput with tolerance=0.10001:\n Miles AB Param1 Param2 Param3 Param4 Param5\n0 1.5 A 0.12345 0.12345 0.12345 0.12345 NaN\n1 1.7 B 0.12345 0.12345 0.12345 0.12345 NaN\n2 1.9 A 0.12345 0.12345 0.12345 0.12345 56.0\n3 2.6 A 0.12345 0.12345 0.12345 0.12345 69.0\n4 2.7 B 0.12345 0.12345 0.12345 0.12345 NaN\n5 3.5 B 0.12345 0.12345 0.12345 0.12345 42.0\n6 5.6 A 0.12345 0.12345 0.12345 0.12345 41.0\n7 7.8 B 0.12345 0.12345 0.12345 0.12345 NaN\n8 9.9 B 0.12345 0.12345 0.12345 0.12345 NaN\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "numpy", "python" ]
stackoverflow_0074551555_dataframe_numpy_python.txt
Q: How do I print a .txt file line-by-line? I am making my first game and want to create a score board within a .txt file, however when I try and print the score board it doesn't work. with open("Scores.txt", "r") as scores: for i in range(len(score.readlines())): print(score.readlines(i + 1)) Instead of printing each line of the .txt file as I expected it to instead it just prints [] The contents of the .txt file are: NAME: AGE: GENDER: SCORE: I know it's only one line but it should still work shouldn't it? *Note there are spaces between each word in the .txt file, though Stack Overflow formatting doesn't allow me to show that. A: Assign the result of score.readlines() to a variable. Then you can loop through it and index it. with open("Scores.txt", "r") as scores: scorelines = scores.readlines() for line in scorelines: print(line) A: .readlines() reads everything until it reaches the end of the file. Calling it repeatedly will return [] as the file seeker is already at the end. Try iterating over the file like so: with open("Scores.txt", "r") as scores: for line in scores: print(line.rstrip())
How do I print a .txt file line-by-line?
I am making my first game and want to create a score board within a .txt file, however when I try and print the score board it doesn't work. with open("Scores.txt", "r") as scores: for i in range(len(score.readlines())): print(score.readlines(i + 1)) Instead of printing each line of the .txt file as I expected it to instead it just prints [] The contents of the .txt file are: NAME: AGE: GENDER: SCORE: I know it's only one line but it should still work shouldn't it? *Note there are spaces between each word in the .txt file, though Stack Overflow formatting doesn't allow me to show that.
[ "Assign the result of score.readlines() to a variable. Then you can loop through it and index it.\nwith open(\"Scores.txt\", \"r\") as scores:\n scorelines = scores.readlines()\n\nfor line in scorelines:\n print(line)\n\n", ".readlines() reads everything until it reaches the end of the file. Calling it repeatedly will return [] as the file seeker is already at the end.\nTry iterating over the file like so:\nwith open(\"Scores.txt\", \"r\") as scores:\n for line in scores:\n print(line.rstrip())\n\n" ]
[ 1, 0 ]
[]
[]
[ "python", "txt" ]
stackoverflow_0074551613_python_txt.txt
Q: What is a faster method to calculate hourly totals from a pandas DataFrame thatn a for loop? I have a pandas DataFrame with about 200,000 rows of raw data. Each row has start and stop times that can span an hour to years. I am using a for loop to calculate a total for each hour of a year; each hourly total sums records that span that hour. I am calculating hourly totals for a full year, or about 24 * 365 = 8760 hours. Even running this for only 1,000 rows of raw data takes about 40 seconds on my laptop. I'm looking for a much faster alternative. I extracted the logic to create this standalone code, which runs successfully in Python 3.10. import numpy as np import pandas as pd from datetime import datetime, timedelta import random def make_test_data(records: int = 1000) -> pd.DataFrame: """ :param records: int: the number of records to create for tthe est data set. :return: pd.DataFrame with columns ['INTERFACE', 'CLASS', 'START_TIME', 'STOP_TIME', 'CAPACITY'] """ random.seed(0) # Random data will be in these bounds. valid_interfaces = ('A', 'B', 'C', 'D', 'E', 'F') valid_classes = ('FIRM', 'NON-FIRM', 'SECONDARY') min_date = datetime(2022, 1, 1) max_date = datetime(2023, 1, 1) # Random date genertor def rand_date(min_date, max_date): days = (max_date - min_date).days return min_date + timedelta(days=random.randrange(days)) records = records or 100 interfaces = random.choices(valid_interfaces, k=records) classes = random.choices(valid_classes, k=records) starts = [rand_date(min_date, max_date) for _ in range(records)] stops = [rand_date(_, max_date) for _ in starts] capacities = [random.randint(-10000, 10000) for _ in range(records)] data = {'INTERFACE': interfaces, 'CLASS': classes, 'START_TIME': starts, 'STOP_TIME': stops, 'CAPACITY': capacities } return pd.DataFrame(data) def calc_hourly_totals(data: pd.DataFrame) -> pd.DataFrame: """ Create a dataframe with net capacity by hour, interface and class. :param data: pd.DataFrame with columns ['INTERFACE', 'CLASS', 'START_TIME', 'STOP_TIME', 'CAPACITY'] :return: pd.DataFrame with columns ['INTERFACE', 'CLASS', 'HOUR_BEGINNING', 'CAPACITY'] """ min_date = data.START_TIME.min() max_date = data.START_TIME.max() hourly_dates = [min_date + timedelta(hours=_) for _ in range((max_date - min_date).days * 24 + int((max_date - min_date).seconds / 3600) ) ] # print('hourly_dates:', hourly_dates) result = pd.DataFrame(columns=['INTERFACE', 'CLASS', 'HOUR_BEGINNING', 'CAPACITY']) loop = 0 for hour_start in hourly_dates: hour_stop = hour_start + timedelta(hours=1) # Filter data. Keep only the ones that overlap within this day/hour. df = data[(data.START_TIME < np.datetime64(hour_stop)) & (data.STOP_TIME > np.datetime64(hour_start))] df = df.groupby(['INTERFACE', 'CLASS']).sum('CAPACITY') df['HOUR_BEGINNING'] = hour_start df.reset_index(inplace=True) # Move INTERFACE from index to a column. df = df[['INTERFACE', 'CLASS', 'HOUR_BEGINNING', 'CAPACITY']] result = pd.concat([result, df]) # loop += 1 # if loop % 1000 == 0: # print(f' completed {loop} of {len(hourly_dates)} loops.') result.rename(columns={'CAPACITY': 'NET_CAPACITY'}, inplace=True) result.reset_index(inplace=True) return result if __name__ == '__main__': from time import perf_counter test_data = make_test_data(1_000) # test_data = pd.read_excel(r'C:\Personal\projects\tsd_python\data\net_tsr_data_2021_04_01-2022_04_01.xlsx', # sheet_name='Raw TSR Data') print('test data rows:', len(test_data)) t_start = perf_counter() result = calc_hourly_totals(test_data) t_finish = perf_counter() print('computation time:', t_finish - t_start) print(result.head()) My results look like this: test data rows: 1000 computation time: 38.52079169999888 index INTERFACE CLASS HOUR_BEGINNING NET_CAPACITY 0 0 A FIRM 2022-01-01 00:00:00 -8646 1 1 B SECONDARY 2022-01-01 00:00:00 -2296 2 2 E SECONDARY 2022-01-01 00:00:00 7927 3 0 A FIRM 2022-01-01 01:00:00 -8646 4 1 B SECONDARY 2022-01-01 01:00:00 -2296 Process finished with exit code 0 A: If you are willing to trade off speed for memory and you have enough of the latter, the following could work: # Calculate all possible time-points - similar to hourly_dates but with an additional time-point at the end hour_beginning = pd.Series(pd.date_range(test_data['START_TIME'].min(), test_data['STOP_TIME'].max(), freq='H')) # Remove this additional -last- time-point hour_beginning = hour_beginning.drop(hour_beginning.index[-1]) You then calculate the cartesian product of the possible INTERFACE, CLASS and hour_beginning values: interfaces = test_data['INTERFACE'].unique() classes = test_data['CLASS'].unique() # Import itertools comb = pd.DataFrame( itertools.product(interfaces, classes, hour_beginning), columns=['INTERFACE', 'CLASS', 'HOUR_BEGINNING'], ) Then you merge the test_data with the product df, but select only the time-points between START_TIME and END_TIME: df_mrg = test_data.merge(comb, on = ['INTERFACE', 'CLASS']).query('START_TIME <= HOUR_BEGINNING < STOP_TIME') Finally you groupby and sum: result2 = df_mrg.groupby(['INTERFACE', 'CLASS', 'HOUR_BEGINNING']).sum(numeric_only=True) result2 = result2.reset_index().sort_values(['INTERFACE', 'CLASS', 'HOUR_BEGINNING']).rename(columns={'CAPACITY': 'NET_CAPACITY'}) result2 is equal to "your" result sorted: result1 = result.drop('index', axis = 1).sort_values(['INTERFACE', 'CLASS', 'HOUR_BEGINNING']) result1.reset_index(drop=True).compare(result2.reset_index(drop=True)) # Raises no error On Colab the new aggregation takes 1.7 sec, the old 1 min 27 sec.
What is a faster method to calculate hourly totals from a pandas DataFrame thatn a for loop?
I have a pandas DataFrame with about 200,000 rows of raw data. Each row has start and stop times that can span an hour to years. I am using a for loop to calculate a total for each hour of a year; each hourly total sums records that span that hour. I am calculating hourly totals for a full year, or about 24 * 365 = 8760 hours. Even running this for only 1,000 rows of raw data takes about 40 seconds on my laptop. I'm looking for a much faster alternative. I extracted the logic to create this standalone code, which runs successfully in Python 3.10. import numpy as np import pandas as pd from datetime import datetime, timedelta import random def make_test_data(records: int = 1000) -> pd.DataFrame: """ :param records: int: the number of records to create for tthe est data set. :return: pd.DataFrame with columns ['INTERFACE', 'CLASS', 'START_TIME', 'STOP_TIME', 'CAPACITY'] """ random.seed(0) # Random data will be in these bounds. valid_interfaces = ('A', 'B', 'C', 'D', 'E', 'F') valid_classes = ('FIRM', 'NON-FIRM', 'SECONDARY') min_date = datetime(2022, 1, 1) max_date = datetime(2023, 1, 1) # Random date genertor def rand_date(min_date, max_date): days = (max_date - min_date).days return min_date + timedelta(days=random.randrange(days)) records = records or 100 interfaces = random.choices(valid_interfaces, k=records) classes = random.choices(valid_classes, k=records) starts = [rand_date(min_date, max_date) for _ in range(records)] stops = [rand_date(_, max_date) for _ in starts] capacities = [random.randint(-10000, 10000) for _ in range(records)] data = {'INTERFACE': interfaces, 'CLASS': classes, 'START_TIME': starts, 'STOP_TIME': stops, 'CAPACITY': capacities } return pd.DataFrame(data) def calc_hourly_totals(data: pd.DataFrame) -> pd.DataFrame: """ Create a dataframe with net capacity by hour, interface and class. :param data: pd.DataFrame with columns ['INTERFACE', 'CLASS', 'START_TIME', 'STOP_TIME', 'CAPACITY'] :return: pd.DataFrame with columns ['INTERFACE', 'CLASS', 'HOUR_BEGINNING', 'CAPACITY'] """ min_date = data.START_TIME.min() max_date = data.START_TIME.max() hourly_dates = [min_date + timedelta(hours=_) for _ in range((max_date - min_date).days * 24 + int((max_date - min_date).seconds / 3600) ) ] # print('hourly_dates:', hourly_dates) result = pd.DataFrame(columns=['INTERFACE', 'CLASS', 'HOUR_BEGINNING', 'CAPACITY']) loop = 0 for hour_start in hourly_dates: hour_stop = hour_start + timedelta(hours=1) # Filter data. Keep only the ones that overlap within this day/hour. df = data[(data.START_TIME < np.datetime64(hour_stop)) & (data.STOP_TIME > np.datetime64(hour_start))] df = df.groupby(['INTERFACE', 'CLASS']).sum('CAPACITY') df['HOUR_BEGINNING'] = hour_start df.reset_index(inplace=True) # Move INTERFACE from index to a column. df = df[['INTERFACE', 'CLASS', 'HOUR_BEGINNING', 'CAPACITY']] result = pd.concat([result, df]) # loop += 1 # if loop % 1000 == 0: # print(f' completed {loop} of {len(hourly_dates)} loops.') result.rename(columns={'CAPACITY': 'NET_CAPACITY'}, inplace=True) result.reset_index(inplace=True) return result if __name__ == '__main__': from time import perf_counter test_data = make_test_data(1_000) # test_data = pd.read_excel(r'C:\Personal\projects\tsd_python\data\net_tsr_data_2021_04_01-2022_04_01.xlsx', # sheet_name='Raw TSR Data') print('test data rows:', len(test_data)) t_start = perf_counter() result = calc_hourly_totals(test_data) t_finish = perf_counter() print('computation time:', t_finish - t_start) print(result.head()) My results look like this: test data rows: 1000 computation time: 38.52079169999888 index INTERFACE CLASS HOUR_BEGINNING NET_CAPACITY 0 0 A FIRM 2022-01-01 00:00:00 -8646 1 1 B SECONDARY 2022-01-01 00:00:00 -2296 2 2 E SECONDARY 2022-01-01 00:00:00 7927 3 0 A FIRM 2022-01-01 01:00:00 -8646 4 1 B SECONDARY 2022-01-01 01:00:00 -2296 Process finished with exit code 0
[ "If you are willing to trade off speed for memory and you have enough of the latter, the following could work:\n# Calculate all possible time-points - similar to hourly_dates but with an additional time-point at the end \nhour_beginning = pd.Series(pd.date_range(test_data['START_TIME'].min(), test_data['STOP_TIME'].max(), freq='H'))\n\n# Remove this additional -last- time-point\nhour_beginning = hour_beginning.drop(hour_beginning.index[-1])\n\nYou then calculate the cartesian product of the possible INTERFACE, CLASS and hour_beginning values:\ninterfaces = test_data['INTERFACE'].unique()\nclasses = test_data['CLASS'].unique()\n\n# Import itertools\ncomb = pd.DataFrame(\n itertools.product(interfaces, classes, hour_beginning),\n columns=['INTERFACE', 'CLASS', 'HOUR_BEGINNING'],\n)\n\nThen you merge the test_data with the product df, but select only the time-points between START_TIME and END_TIME:\ndf_mrg = test_data.merge(comb, on = ['INTERFACE', 'CLASS']).query('START_TIME <= HOUR_BEGINNING < STOP_TIME')\n\nFinally you groupby and sum:\nresult2 = df_mrg.groupby(['INTERFACE', 'CLASS', 'HOUR_BEGINNING']).sum(numeric_only=True)\nresult2 = result2.reset_index().sort_values(['INTERFACE', 'CLASS', 'HOUR_BEGINNING']).rename(columns={'CAPACITY': 'NET_CAPACITY'})\n\nresult2 is equal to \"your\" result sorted:\nresult1 = result.drop('index', axis = 1).sort_values(['INTERFACE', 'CLASS', 'HOUR_BEGINNING'])\nresult1.reset_index(drop=True).compare(result2.reset_index(drop=True)) # Raises no error\n\nOn Colab the new aggregation takes 1.7 sec, the old 1 min 27 sec.\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074547954_dataframe_pandas_python_python_3.x.txt
Q: How can I use min() without getting "0" or "" for an answer? I'm trying to use min in a list that came from a .csv and some of the values are '' how can I ignore those and also "0"? I tried index1 = (life_expectancy.index(min(life_expectancy,))) print(life_expectancy[index1]) and got nothing, when i tried: index1 = (life_expectancy.index(min(life_expectancy, key=int))) I got: ValueError: invalid literal for int() with base 10: '' Because this is the value that the function treats at the min A: I don't think there is a simple way to do this in a single line of code using min. One way to avoid 0-values is to call filter before min. Then, to avoid invalid values, you can write a wrapper around int that returns 0 on invalid values. def int_or_zero(s): try: return int(s) except ValueError: return 0 def nonzero_min(seq): return min(filter(None, map(int_or_zero, seq))) print( nonzero_min(['hello', '0', '12', '3', '0', '5', '']) ) # 3 Another way is to write the whole function "manually" with a for-loop. def nonzero_min2(seq): m = 9999999 for x in seq: try: x = int(x) if x < m and x != 0: m = x except ValueError: pass return m print( nonzero_min2(['hello', '0', '12', '3', '0', '5', '']) ) # 3 A: The problem statement is incomplete, so we cannot conclude. Is it a list of strings ? integers ? floats ? with None ? with float("NaN") ? a mix of all ? With a list of mixed numbers and strings, you would have: life_expectancy= [2,3,5,7,11,13, "", 0, "", 3.14, 1.414, "", 1.712, "", 1.618, 0] index1 = (life_expectancy.index(min(life_expectancy,))) TypeError: '<' not supported between instances of 'str' and 'int' index1 = (life_expectancy.index(min(life_expectancy,key=int))) ValueError: invalid literal for int() with base 10: '' With a list of mixed numbers, None, and strings, you would have: life_expectancy= [2,3,5,7,11,13, None, 0, None, 3.14, 1.414, None, 1.712, None, 1.618, 0] index1 = (life_expectancy.index(min(life_expectancy,))) TypeError: '<' not supported between instances of 'NoneType' and 'int' index1 = (life_expectancy.index(min(life_expectancy,key=int))) TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType' So, yeah ... it all depends on your actual inputs... Stef's answer should do the trick. otherwise: manual filtering using a list comprehension (https://stackoverflow.com/a/74549587/7237062 but a bit more pythonic) life_expectancy= [2,3,5,7,11,13, "", "0", "", "3.14", 1.414, "", 1.712, "", 1.618, 0] new_list = [e for e in life_expectancy if e and type(e) != str] new_list >>> [2, 3, 5, 7, 11, 13, 1.414, 1.712, 1.618] revise your CSV loading. you may consider using pandas and its read_csv() function, quopting: Read a comma-separated values (csv) file into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Give a special look to all the doc/parameters, because there are a lot of default values and inferences, especially: sepstr, default ‘,’ Delimiter to use. and: decimalstr, default ‘.’ Character to recognize as decimal point (e.g. use ‘,’ for European data). (and a lot more) A: you can try something like : df_temp = df.loc[df["column_name"]!=""] df_temp = df_temp.loc[df_temp["column_name"]>0] Im not sure if you could just do != "" | 0, not sure if loc supports double condition. Then you can just do a min on that df_temp A: Try this: new_life_expectancy = [value for value in life_expectancy if value != '' and value != '0'] This removes all instances of '' and 0
How can I use min() without getting "0" or "" for an answer?
I'm trying to use min in a list that came from a .csv and some of the values are '' how can I ignore those and also "0"? I tried index1 = (life_expectancy.index(min(life_expectancy,))) print(life_expectancy[index1]) and got nothing, when i tried: index1 = (life_expectancy.index(min(life_expectancy, key=int))) I got: ValueError: invalid literal for int() with base 10: '' Because this is the value that the function treats at the min
[ "I don't think there is a simple way to do this in a single line of code using min.\nOne way to avoid 0-values is to call filter before min. Then, to avoid invalid values, you can write a wrapper around int that returns 0 on invalid values.\ndef int_or_zero(s):\n try:\n return int(s)\n except ValueError:\n return 0\n\ndef nonzero_min(seq):\n return min(filter(None, map(int_or_zero, seq)))\n\nprint( nonzero_min(['hello', '0', '12', '3', '0', '5', '']) )\n# 3\n\nAnother way is to write the whole function \"manually\" with a for-loop.\ndef nonzero_min2(seq):\n m = 9999999\n for x in seq:\n try:\n x = int(x)\n if x < m and x != 0:\n m = x\n except ValueError:\n pass\n return m\n\nprint( nonzero_min2(['hello', '0', '12', '3', '0', '5', '']) )\n# 3\n\n", "The problem statement is incomplete, so we cannot conclude.\nIs it a list of strings ? integers ? floats ? with None ? with float(\"NaN\") ? a mix of all ?\n\nWith a list of mixed numbers and strings, you would have:\nlife_expectancy= [2,3,5,7,11,13, \"\", 0, \"\", 3.14, 1.414, \"\", 1.712, \"\", 1.618, 0]\nindex1 = (life_expectancy.index(min(life_expectancy,)))\nTypeError: '<' not supported between instances of 'str' and 'int'\n\nindex1 = (life_expectancy.index(min(life_expectancy,key=int)))\nValueError: invalid literal for int() with base 10: ''\n\n\nWith a list of mixed numbers, None, and strings, you would have:\nlife_expectancy= [2,3,5,7,11,13, None, 0, None, 3.14, 1.414, None, 1.712, None, 1.618, 0]\nindex1 = (life_expectancy.index(min(life_expectancy,)))\nTypeError: '<' not supported between instances of 'NoneType' and 'int'\n\nindex1 = (life_expectancy.index(min(life_expectancy,key=int)))\nTypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'\n\n\nSo, yeah ... it all depends on your actual inputs...\nStef's answer should do the trick.\notherwise:\n\nmanual filtering using a list comprehension (https://stackoverflow.com/a/74549587/7237062 but a bit more pythonic)\n\nlife_expectancy= [2,3,5,7,11,13, \"\", \"0\", \"\", \"3.14\", 1.414, \"\", 1.712, \"\", 1.618, 0]\nnew_list = [e for e in life_expectancy if e and type(e) != str]\nnew_list\n>>> [2, 3, 5, 7, 11, 13, 1.414, 1.712, 1.618]\n\n\nrevise your CSV loading.\n\nyou may consider using pandas and its read_csv() function, quopting:\n\nRead a comma-separated values (csv) file into DataFrame.\nAlso supports optionally iterating or breaking of the file into chunks.\n\nGive a special look to all the doc/parameters, because there are a lot of default values and inferences, especially:\n\nsepstr, default ‘,’\nDelimiter to use.\n\nand:\n\ndecimalstr, default ‘.’\nCharacter to recognize as decimal point (e.g. use ‘,’ for European data).\n\n(and a lot more)\n", "you can try something like :\ndf_temp = df.loc[df[\"column_name\"]!=\"\"]\n\ndf_temp = df_temp.loc[df_temp[\"column_name\"]>0]\n\nIm not sure if you could just do != \"\" | 0, not sure if loc supports double condition.\nThen you can just do a min on that df_temp\n", "Try this:\nnew_life_expectancy = [value for value in life_expectancy if value != '' and value != '0']\n\nThis removes all instances of '' and 0\n" ]
[ 2, 1, 0, -1 ]
[ "#You can simply remove all 0 terms and string terms from your list and then use min\nl=[1,34,6,4,1,4,0]\nl1=l\nwhile True:\n try:\n l1.remove(0)\n except ValueError:\n break \nprint(min(l1)) \n\n" ]
[ -2 ]
[ "list", "minimum", "python", "python_3.x" ]
stackoverflow_0074549273_list_minimum_python_python_3.x.txt
Q: First argument to get_object_or_404() must be a Model. How can I get an user's id to the User model? I'm trying to make a favorite functionality where an user can add other users as their favorites. In the View where the profile of an user is shown I have a button that adds an user or removes it if it was already added. The problem is that I can't pass to the views the user that will be added as a favorite. models.py class User(AbstractUser): is_type1 = models.BooleanField(default=False) ... class Type1(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) favorite = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name='favorite') views.py def FavoriteView(request, pk): current_user = request.user Type1.user = current_user.id buser = Type1.user Type1.favorite = get_object_or_404(User, id=request.POST.get('username')) # The of the error where I try to add the user being added as a favorite fuser = Type1.favorite if Type1.favorite.filter(id=request.user.id).exists(): Type1.favorite.remove(request.user) else: Type1.favorite.add(request.user) return HttpResponseRedirect(reverse('profile-details', kwargs={'username': Type1.favorite})) class UserView(DetailView): model = User ... template_name = 'users/profile-details.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) favorite_connected = get_object_or_404(Type1.favorite, id=self.kwargs['username']) # The of the error where I try to add the user being added as a favorite favorite = False if favorite_connected.favorite.filter(id=self.request.user.id).exists(): liked = True data['user_is_favorite'] = favorite return data profile-details.html ... {% if user.is_authenticated %} <form action="{% url 'favorite' object.id %}" method="POST"> {% csrf_token %} {% if user_is_favorite %} <button type="submit" name="favorite" value="{{object.id}}">Not favorite</button> {% else %} <button type="submit" name="favorite" value="{{object.id}}">Favorite</button> {% endif %} </form> {% else %} <a href="{% url 'login' %}?next={{request.path}}">Log in to add user to favorites.</a><br> {% endif %} urls.py path('profile/<str:username>/', UserView.as_view(), name='profile-details'), path('favorite/<str:username>/', FavoriteView, name="favorite"), A: One immediate problem I see is that your URL path wants a string for the username, but your URL for the form gives it the ID of the user, so that'll be an int. In terms of your error, you're trying to pass a username, but I don't think that'll be in the POST data. However if it was, you should be able to do; get_object_or_404(User, username=request.POST.get('username')) However, based on my initial comment, you should probably just get the user by ID like you are doing, but use the PK of the user which is comes with your view; get_object_or_404(User, id=pk) You may also come across more errors, because you're assigning an object, if it exists to Type1.favorite and then attempting to do Type1.favorite.filter( which will fail. You can only .filter() on a queryset, not a model instance.
First argument to get_object_or_404() must be a Model. How can I get an user's id to the User model?
I'm trying to make a favorite functionality where an user can add other users as their favorites. In the View where the profile of an user is shown I have a button that adds an user or removes it if it was already added. The problem is that I can't pass to the views the user that will be added as a favorite. models.py class User(AbstractUser): is_type1 = models.BooleanField(default=False) ... class Type1(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) favorite = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, related_name='favorite') views.py def FavoriteView(request, pk): current_user = request.user Type1.user = current_user.id buser = Type1.user Type1.favorite = get_object_or_404(User, id=request.POST.get('username')) # The of the error where I try to add the user being added as a favorite fuser = Type1.favorite if Type1.favorite.filter(id=request.user.id).exists(): Type1.favorite.remove(request.user) else: Type1.favorite.add(request.user) return HttpResponseRedirect(reverse('profile-details', kwargs={'username': Type1.favorite})) class UserView(DetailView): model = User ... template_name = 'users/profile-details.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) favorite_connected = get_object_or_404(Type1.favorite, id=self.kwargs['username']) # The of the error where I try to add the user being added as a favorite favorite = False if favorite_connected.favorite.filter(id=self.request.user.id).exists(): liked = True data['user_is_favorite'] = favorite return data profile-details.html ... {% if user.is_authenticated %} <form action="{% url 'favorite' object.id %}" method="POST"> {% csrf_token %} {% if user_is_favorite %} <button type="submit" name="favorite" value="{{object.id}}">Not favorite</button> {% else %} <button type="submit" name="favorite" value="{{object.id}}">Favorite</button> {% endif %} </form> {% else %} <a href="{% url 'login' %}?next={{request.path}}">Log in to add user to favorites.</a><br> {% endif %} urls.py path('profile/<str:username>/', UserView.as_view(), name='profile-details'), path('favorite/<str:username>/', FavoriteView, name="favorite"),
[ "One immediate problem I see is that your URL path wants a string for the username, but your URL for the form gives it the ID of the user, so that'll be an int.\nIn terms of your error, you're trying to pass a username, but I don't think that'll be in the POST data. However if it was, you should be able to do;\nget_object_or_404(User, username=request.POST.get('username'))\nHowever, based on my initial comment, you should probably just get the user by ID like you are doing, but use the PK of the user which is comes with your view;\nget_object_or_404(User, id=pk)\nYou may also come across more errors, because you're assigning an object, if it exists to Type1.favorite and then attempting to do Type1.favorite.filter( which will fail. You can only .filter() on a queryset, not a model instance.\n" ]
[ 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074551597_django_django_views_python.txt
Q: Filter with a computed field is not working [Odoo 8] I have to display in a tree view the number of attachments an invoice has. This is OK, I'm doing it with a compute. I also have to be able to filter the invoices that have attached files and here is the problem. I can't use this field in searching because it doesn't have store=True attribute, and if I add it, the compute attribute stops working I was investigating and there is a search=" " attribute that can be put on the field I have it this way right now, but for some reason it's not working for me. attachment_count = fields.Integer(string="QAF", compute='count_attachments', search='_search_att_count') @api.one def count_attachments(self): # code def _search_att_count(self, operator, value): field_id = self.search([]) if operator == '=': field_id = [x.id for x in field_id if x.attachment_count == value] return [('id', 'in', field_id)] I'm getting this error: Traceback (most recent call last): File "/opt/odoo/odoo/openerp/http.py", line 546, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/opt/odoo/odoo/openerp/http.py", line 583, in dispatch result = self._call_function(**self.params) File "/opt/odoo/odoo/openerp/http.py", line 319, in _call_function return checked_call(self.db, *args, **kwargs) File "/opt/odoo/odoo/openerp/service/model.py", line 118, in wrapper return f(dbname, *args, **kwargs) File "/opt/odoo/odoo/openerp/http.py", line 316, in checked_call return self.endpoint(*a, **kw) File "/opt/odoo/odoo/openerp/http.py", line 812, in __call__ return self.method(*args, **kw) File "/opt/odoo/odoo/openerp/http.py", line 412, in response_wrap response = f(*args, **kw) File "/opt/odoo/odoo/addons/web/controllers/main.py", line 884, in search_read return self.do_search_read(model, fields, offset, limit, domain, sort) File "/opt/odoo/odoo/addons/web/controllers/main.py", line 905, in do_search_read request.context) File "/opt/odoo/odoo/openerp/http.py", line 917, in proxy result = meth(cr, request.uid, *args, **kw) File "/opt/odoo/odoo/openerp/api.py", line 268, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/odoo/openerp/models.py", line 5184, in search_read record_ids = self.search(cr, uid, domain or [], offset=offset, limit=limit, order=order, context=context) File "/opt/odoo/odoo/openerp/api.py", line 268, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/odoo/openerp/models.py", line 1650, in search return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count) File "/opt/odoo/odoo/openerp/api.py", line 268, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/odoo/openerp/models.py", line 4687, in _search query = self._where_calc(cr, user, args, context=context) File "/opt/odoo/odoo/openerp/api.py", line 268, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/odoo/openerp/models.py", line 4500, in _where_calc where_clause, where_params = e.to_sql() File "/opt/odoo/odoo/openerp/osv/expression.py", line 1287, in to_sql q, p = self.__leaf_to_sql(leaf) File "/opt/odoo/odoo/openerp/osv/expression.py", line 1154, in __leaf_to_sql Blockquote "Invalid value %r in domain term %r" % (right, leaf) AssertionError: Invalid value account.invoice(29521, 24984, 16542, 23652, 23651, 28875, 36436, 9637, 24800 And the number continous A: self.search([]) returns a list of recordsets. So when your code doesn't match the "if" condition, it will throw an error. You need to add an "else" condition to get a list of record ids. For example: def _search_att_count(self, operator, value): field_id = self.search([]) if operator == '=': field_id = [x.id for x in field_id if x.attachment_count == value] else: field_id = field_id.ids return [('id', 'in', field_id)]
Filter with a computed field is not working [Odoo 8]
I have to display in a tree view the number of attachments an invoice has. This is OK, I'm doing it with a compute. I also have to be able to filter the invoices that have attached files and here is the problem. I can't use this field in searching because it doesn't have store=True attribute, and if I add it, the compute attribute stops working I was investigating and there is a search=" " attribute that can be put on the field I have it this way right now, but for some reason it's not working for me. attachment_count = fields.Integer(string="QAF", compute='count_attachments', search='_search_att_count') @api.one def count_attachments(self): # code def _search_att_count(self, operator, value): field_id = self.search([]) if operator == '=': field_id = [x.id for x in field_id if x.attachment_count == value] return [('id', 'in', field_id)] I'm getting this error: Traceback (most recent call last): File "/opt/odoo/odoo/openerp/http.py", line 546, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/opt/odoo/odoo/openerp/http.py", line 583, in dispatch result = self._call_function(**self.params) File "/opt/odoo/odoo/openerp/http.py", line 319, in _call_function return checked_call(self.db, *args, **kwargs) File "/opt/odoo/odoo/openerp/service/model.py", line 118, in wrapper return f(dbname, *args, **kwargs) File "/opt/odoo/odoo/openerp/http.py", line 316, in checked_call return self.endpoint(*a, **kw) File "/opt/odoo/odoo/openerp/http.py", line 812, in __call__ return self.method(*args, **kw) File "/opt/odoo/odoo/openerp/http.py", line 412, in response_wrap response = f(*args, **kw) File "/opt/odoo/odoo/addons/web/controllers/main.py", line 884, in search_read return self.do_search_read(model, fields, offset, limit, domain, sort) File "/opt/odoo/odoo/addons/web/controllers/main.py", line 905, in do_search_read request.context) File "/opt/odoo/odoo/openerp/http.py", line 917, in proxy result = meth(cr, request.uid, *args, **kw) File "/opt/odoo/odoo/openerp/api.py", line 268, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/odoo/openerp/models.py", line 5184, in search_read record_ids = self.search(cr, uid, domain or [], offset=offset, limit=limit, order=order, context=context) File "/opt/odoo/odoo/openerp/api.py", line 268, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/odoo/openerp/models.py", line 1650, in search return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count) File "/opt/odoo/odoo/openerp/api.py", line 268, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/odoo/openerp/models.py", line 4687, in _search query = self._where_calc(cr, user, args, context=context) File "/opt/odoo/odoo/openerp/api.py", line 268, in wrapper return old_api(self, *args, **kwargs) File "/opt/odoo/odoo/openerp/models.py", line 4500, in _where_calc where_clause, where_params = e.to_sql() File "/opt/odoo/odoo/openerp/osv/expression.py", line 1287, in to_sql q, p = self.__leaf_to_sql(leaf) File "/opt/odoo/odoo/openerp/osv/expression.py", line 1154, in __leaf_to_sql Blockquote "Invalid value %r in domain term %r" % (right, leaf) AssertionError: Invalid value account.invoice(29521, 24984, 16542, 23652, 23651, 28875, 36436, 9637, 24800 And the number continous
[ "self.search([]) returns a list of recordsets. So when your code doesn't match the \"if\" condition, it will throw an error.\nYou need to add an \"else\" condition to get a list of record ids. For example:\ndef _search_att_count(self, operator, value):\n field_id = self.search([])\n if operator == '=':\n field_id = [x.id for x in field_id if x.attachment_count == value]\n else:\n field_id = field_id.ids\n return [('id', 'in', field_id)]\n\n" ]
[ 1 ]
[]
[]
[ "odoo", "odoo_8", "python" ]
stackoverflow_0074551614_odoo_odoo_8_python.txt
Q: Lark: How to ignore whitespace after parsing? I am creating a REPL for Linux commands. Since my grammar for command is call: WS? (redirection WS)* argument (WS atom)* WS?, once the parsing is done, I always find whitespace is included as one of the nodes in the parse tree. I understand including WS in the grammar to catch the command line correctly, but I want to filter out them after parsing. I tried adding %ignore WS at the end of the file, but it didn't work. A: You can use a Transformer and have the method for the WS token return Discard. Transformers make it much easier to convert the result of the parsing into the format that you need for the rest of your program. Since you didn't include your grammar, and your specific use case is too complex to replicate quickly, I'll show an example using the following basic grammar: GRAMMAR = r""" ?start: ints ints: (INT WS*)+ %import common (INT, WS) """ Before defining a transformer, we can see that all ints and spaces are present in the parsed tree: >>> Lark(GRAMMAR).parse('12 34 56') Tree(Token('RULE', 'ints'), [Token('INT', '12'), Token('WS', ' '), Token('INT', '34'), Token('WS', ' '), Token('INT', '56')]) We can define a simple transformer that only transforms WS: from lark import Lark, Token, Transformer, Discard class SpaceTransformer(Transformer): def WS(self, tok: Token): return Discard Which results in the same tree as before, but now the WS tokens have been removed: >>> tree = Lark(GRAMMAR).parse('12 34 56') >>> SpaceTransformer().transform(tree) Tree(Token('RULE', 'ints'), [Token('INT', '12'), Token('INT', '34'), Token('INT', '56')]) The transformer can be expanded further to handle more of the defined tokens: class SpaceTransformer(Transformer): def WS(self, tok: Token): return Discard def INT(self, tok: Token) -> int: return int(tok.value) That results in the values being proper integers, but they are still in the tree: >>> tree = Lark(GRAMMAR).parse('12 34 56') >>> SpaceTransformer().transform(tree) Tree(Token('RULE', 'ints'), [12, 34, 56]) We can take it one step further and define a method for the rule as well - each method in a Transformer that matches a token or rule will automatically be called for each matching parsed value: class SpaceTransformer(Transformer): def WS(self, tok: Token): return Discard def INT(self, tok: Token) -> int: return int(tok.value) def ints(self, integers): return integers Now when we transform the tree, we get a list of ints instead of a tree: >>> tree = Lark(GRAMMAR).parse('12 34 56') >>> SpaceTransformer().transform(tree) [12, 34, 56] While my example used very simple types, you could define a method for your command rule that returns a Command object, or whatever you have defined to represent it. For rules that contain other rules, the outer rules will receive the already transformed objects, just like ints received int objects. There are also some customizations you can apply to how the transformer methods receive arguments by using the v_args decorator.
Lark: How to ignore whitespace after parsing?
I am creating a REPL for Linux commands. Since my grammar for command is call: WS? (redirection WS)* argument (WS atom)* WS?, once the parsing is done, I always find whitespace is included as one of the nodes in the parse tree. I understand including WS in the grammar to catch the command line correctly, but I want to filter out them after parsing. I tried adding %ignore WS at the end of the file, but it didn't work.
[ "You can use a Transformer and have the method for the WS token return Discard.\nTransformers make it much easier to convert the result of the parsing into the format that you need for the rest of your program. Since you didn't include your grammar, and your specific use case is too complex to replicate quickly, I'll show an example using the following basic grammar:\nGRAMMAR = r\"\"\"\n?start: ints\nints: (INT WS*)+\n%import common (INT, WS)\n\"\"\"\n\nBefore defining a transformer, we can see that all ints and spaces are present in the parsed tree:\n>>> Lark(GRAMMAR).parse('12 34 56')\nTree(Token('RULE', 'ints'), [Token('INT', '12'), Token('WS', ' '), Token('INT', '34'), Token('WS', ' '), Token('INT', '56')])\n\nWe can define a simple transformer that only transforms WS:\nfrom lark import Lark, Token, Transformer, Discard\n\nclass SpaceTransformer(Transformer):\n def WS(self, tok: Token):\n return Discard\n\nWhich results in the same tree as before, but now the WS tokens have been removed:\n>>> tree = Lark(GRAMMAR).parse('12 34 56')\n\n>>> SpaceTransformer().transform(tree)\nTree(Token('RULE', 'ints'), [Token('INT', '12'), Token('INT', '34'), Token('INT', '56')])\n\n\nThe transformer can be expanded further to handle more of the defined tokens:\nclass SpaceTransformer(Transformer):\n def WS(self, tok: Token):\n return Discard\n\n def INT(self, tok: Token) -> int:\n return int(tok.value)\n\nThat results in the values being proper integers, but they are still in the tree:\n>>> tree = Lark(GRAMMAR).parse('12 34 56')\n\n>>> SpaceTransformer().transform(tree)\nTree(Token('RULE', 'ints'), [12, 34, 56])\n\n\nWe can take it one step further and define a method for the rule as well - each method in a Transformer that matches a token or rule will automatically be called for each matching parsed value:\nclass SpaceTransformer(Transformer):\n def WS(self, tok: Token):\n return Discard\n\n def INT(self, tok: Token) -> int:\n return int(tok.value)\n\n def ints(self, integers):\n return integers\n\nNow when we transform the tree, we get a list of ints instead of a tree:\n>>> tree = Lark(GRAMMAR).parse('12 34 56')\n\n>>> SpaceTransformer().transform(tree)\n[12, 34, 56]\n\nWhile my example used very simple types, you could define a method for your command rule that returns a Command object, or whatever you have defined to represent it. For rules that contain other rules, the outer rules will receive the already transformed objects, just like ints received int objects.\nThere are also some customizations you can apply to how the transformer methods receive arguments by using the v_args decorator.\n" ]
[ 0 ]
[]
[]
[ "lark_parser", "parsing", "python", "read_eval_print_loop" ]
stackoverflow_0074550878_lark_parser_parsing_python_read_eval_print_loop.txt
Q: Python - How to properly fill a multiline text field in PDF form using pdfrw? I'm filling a PDF form using python with pdfrw. I have no problem with any single line text field in the form. But when I try to fill a multi-line textfield it doesn`t render properly, it ignores break lines. This is part of my code: pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject('true'))) for x in range(0, len(pdf.Root.AcroForm.Fields)): try: if pdf.Root.AcroForm.Fields[x].T in ['(Observaciones)']: pdf.Root.AcroForm.Fields[x].update(PdfDict(V='This\nis\nmultiline', Ff=1)) continue This is the output. This is the settings in the form field using Adobe Acrobat. I have selected the options: Multiline, Scroll Long Text, Allow Rich Text Formatting. I have tried using \r and the <br> tag too. How should I set the value to render properly? A: I cannot read Spanish setting, but if you make sure these 2 fields are checked, then you probably will be OK. Setting A: I've had this issue too. I haven't delved into the implementation of the multi-line feature by pdfrw, but I do know that when I flatten the form field (Ff=1, which you also have in your code), it no longer supports multi-line. Try taking that off and see if multi-line is supported again. A: After struggling with flattening my fields (setting to read-only) while keeping the multiline intact I finally found the solution. I came across this rushed solution to just turn the ‘/Ff’ value to 1 but in doing so you run the chance of removing some of the formatting for the form, and here is a better explanation on how to manipulate this field. In the ‘PDF Reference: third edition’ page:532 it states “The value of the field dictionary’s Ff entry is an unsigned 32-bit integer containing flags specifying various characteristics of the field. Bit positions within the flag word are numbered from 1 (low-order) to 32 (high-order).“ So, when I looked into the Ff field I got 4096 (in binary = 0001-0000-0000-0000) for allot of the forms I was struggling with. Turns out that the 13th bit controls the multiline setting and just setting the Ff to 1 therefor erases the rest of the settings and only dictates that the specific form should be read-only. You could just do it the lazy way and give Ff the value 4097 (or whatever your Ff value is +1) or flip the bit you want in the byte string that you want to manipulate. Here is a simple way to do it, that is modifiable to your needs. bitPosition = 0 #First position being value 0 bitValue = 1 mask = 1 << bitPosition oldFfValue = pdf.Root.AcroForm.Fields[x].Ff newFfValue = (int(oldFfValue) & ~mask) | ((1 << 0) & mask) pdf.Root.AcroForm.Fields[x].Ff.update(PdfDict(Ff=newFfValue)) ps. Not 100% sure if accessing the Ff value works this way for you since my approach was based on this persons example code since it fit my needs better. All in all I recommend giving the PDF reference document a look if you want to mess with the rest of the bits to see the interesting characteristics they control. Other usefull bits are for example: 14th bit is for password star typing. 23rd bit is for disabling spell-check. 24th bit is for disabling scrolling of the field. A: I set the the ff to 4097 and it seems to be working but need to check if it has impact on other things.
Python - How to properly fill a multiline text field in PDF form using pdfrw?
I'm filling a PDF form using python with pdfrw. I have no problem with any single line text field in the form. But when I try to fill a multi-line textfield it doesn`t render properly, it ignores break lines. This is part of my code: pdf.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject('true'))) for x in range(0, len(pdf.Root.AcroForm.Fields)): try: if pdf.Root.AcroForm.Fields[x].T in ['(Observaciones)']: pdf.Root.AcroForm.Fields[x].update(PdfDict(V='This\nis\nmultiline', Ff=1)) continue This is the output. This is the settings in the form field using Adobe Acrobat. I have selected the options: Multiline, Scroll Long Text, Allow Rich Text Formatting. I have tried using \r and the <br> tag too. How should I set the value to render properly?
[ "I cannot read Spanish setting, but if you make sure these 2 fields are checked, then you probably will be OK.\nSetting\n", "I've had this issue too. I haven't delved into the implementation of the multi-line feature by pdfrw, but I do know that when I flatten the form field (Ff=1, which you also have in your code), it no longer supports multi-line. Try taking that off and see if multi-line is supported again.\n", "After struggling with flattening my fields (setting to read-only) while keeping the multiline intact I finally found the solution.\nI came across this rushed solution to just turn the ‘/Ff’ value to 1 but in doing so you run the chance of removing some of the formatting for the form, and here is a better explanation on how to manipulate this field.\nIn the ‘PDF Reference: third edition’ page:532 it states\n\n“The value of the field dictionary’s Ff entry is an unsigned 32-bit\ninteger containing flags specifying various characteristics of the\nfield. Bit positions within the flag word are numbered from 1\n(low-order) to 32 (high-order).“\n\nSo, when I looked into the Ff field I got 4096 (in binary = 0001-0000-0000-0000) for allot of the forms I was struggling with. Turns out that the 13th bit controls the multiline setting and just setting the Ff to 1 therefor erases the rest of the settings and only dictates that the specific form should be read-only.\nYou could just do it the lazy way and give Ff the value 4097 (or whatever your Ff value is +1) or flip the bit you want in the byte string that you want to manipulate.\nHere is a simple way to do it, that is modifiable to your needs.\nbitPosition = 0 #First position being value 0\nbitValue = 1\nmask = 1 << bitPosition\noldFfValue = pdf.Root.AcroForm.Fields[x].Ff\nnewFfValue = (int(oldFfValue) & ~mask) | ((1 << 0) & mask)\npdf.Root.AcroForm.Fields[x].Ff.update(PdfDict(Ff=newFfValue))\n\nps. Not 100% sure if accessing the Ff value works this way for you since my approach was based on this persons example code since it fit my needs better.\nAll in all I recommend giving the PDF reference document a look if you want to mess with the rest of the bits to see the interesting characteristics they control.\nOther usefull bits are for example:\n\n14th bit is for password star typing.\n23rd bit is for disabling spell-check.\n24th bit is for disabling scrolling of the field.\n\n", "I set the the ff to 4097 and it seems to be working but need to check if it has impact on other things.\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "acrobat", "pdf", "pdf_form", "pdfrw", "python" ]
stackoverflow_0068119744_acrobat_pdf_pdf_form_pdfrw_python.txt
Q: How can I send an embed via my Discord bot, w/python? I've been working a new Discord bot. I've learnt a few stuff,and, now, I'd like to make the things a little more custom. I've been trying to make the bot send embeds, instead, of a common message. embed=discord.Embed(title="Tile", description="Desc", color=0x00ff00) embed.add_field(name="Fiel1", value="hi", inline=False) embed.add_field(name="Field2", value="hi2", inline=False) await self.bot.say(embed=embed) When executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed. A: To get it to work I changed your send_message line to await message.channel.send(embed=embed) Here is a full example bit of code to show how it all fits: @client.event async def on_message(message): if message.content.startswith('!hello'): embedVar = discord.Embed(title="Title", description="Desc", color=0x00ff00) embedVar.add_field(name="Field1", value="hi", inline=False) embedVar.add_field(name="Field2", value="hi2", inline=False) await message.channel.send(embed=embedVar) I used the discord.py docs to help find this. https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.send for the layout of the send method. https://discordpy.readthedocs.io/en/latest/api.html#embed for the Embed class. Before version 1.0: If you're using a version before 1.0, use the method await client.send_message(message.channel, embed=embed) instead. A: When executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed. This means you're out of date. Use pip to update your version of the library. pip install --upgrade discord.py A: @bot.command() async def displayembed(ctx): embed = discord.Embed(title="Your title here", description="Your desc here") #,color=Hex code embed.add_field(name="Name", value="you can make as much as fields you like to") embed.set_footer(name="footer") #if you like to await ctx.send(embed=embed) A: how about put @client.event instead of the @bot.command() it fixed everything when I put @client.event... @bot.command() does not work you can type @client.event async def displayembed(ctx): embed = discord.Embed(title="Your title here", description="Your desc here") #,color=Hex code embed.add_field(name="Name", value="you can make as much as fields you like to") embed.set_footer(name="footer") #if you like to await ctx.send(embed=embed) A: For anyone coming across this in 2022: how about put @client.event instead of the @bot.command() it fixed everything when I put @client.event... @bot.command() does not work you can type To this ^, I don't recommend using @client.event / @bot.event as you'd want to register your commands as a command. If you want to simply make a command with an embed in your main.py file, make sure you have something like: import discord from discord.ext import commands intents = discord.Itents.default() bot = commands.Bot(command_prefix='YOURPREFIX', description='description', intents=intents) @bot.command(name="embed") async def embed(ctx): embed = discord.Embed(title='Title', description='Desc', color=discord.Color.random()) embed.add_field(name="Name", value="Value", inline=False) await ctx.send(embed=embed) However, I personally like separating my commands into a /commands folder and with separate files for all of them as it's good practice for neater code. For that, I use cogs. /commands/embed.py from discord.ext import commands import discord class EmbedCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="embed") async def embed(self, ctx): embed = discord.Embed(title='Title', description='Desc', color=discord.Color.random()) embed.add_field(name="Name", value="Value", inline=False) await ctx.send(embed=embed) Then import it all into your main.py file: from commands.embed import EmbedCog bot.add_cog(EmbedCog(bot)) A: Before using embed embed (Embed) – The rich embed for the content to send. This cannot be mixed with embeds parameter. embeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed TypeError – You specified both embed and embeds or file and files or thread and thread_name. @client.event async def on_message(message): if message.content.startswith('!hi'): embed = discord.Embed(title="This is title of embedded element", description="Desc", color=0x00ff00) embed.add_field(name="Like header in HTML", value="Text of field 1", inline=False) embed.add_field(name="Like header in html", value="text of field 2", inline=False) await message.channel.send(embed=embed) Reference
How can I send an embed via my Discord bot, w/python?
I've been working a new Discord bot. I've learnt a few stuff,and, now, I'd like to make the things a little more custom. I've been trying to make the bot send embeds, instead, of a common message. embed=discord.Embed(title="Tile", description="Desc", color=0x00ff00) embed.add_field(name="Fiel1", value="hi", inline=False) embed.add_field(name="Field2", value="hi2", inline=False) await self.bot.say(embed=embed) When executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed.
[ "To get it to work I changed your send_message line to\nawait message.channel.send(embed=embed)\nHere is a full example bit of code to show how it all fits:\n@client.event\nasync def on_message(message):\n if message.content.startswith('!hello'):\n embedVar = discord.Embed(title=\"Title\", description=\"Desc\", color=0x00ff00)\n embedVar.add_field(name=\"Field1\", value=\"hi\", inline=False)\n embedVar.add_field(name=\"Field2\", value=\"hi2\", inline=False)\n await message.channel.send(embed=embedVar)\n\nI used the discord.py docs to help find this.\nhttps://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.send for the layout of the send method.\nhttps://discordpy.readthedocs.io/en/latest/api.html#embed for the Embed class.\nBefore version 1.0: If you're using a version before 1.0, use the method await client.send_message(message.channel, embed=embed) instead.\n", "\nWhen executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed.\n\nThis means you're out of date. Use pip to update your version of the library.\npip install --upgrade discord.py\n\n", "@bot.command()\nasync def displayembed(ctx):\n embed = discord.Embed(title=\"Your title here\", description=\"Your desc here\") #,color=Hex code\n embed.add_field(name=\"Name\", value=\"you can make as much as fields you like to\")\n embed.set_footer(name=\"footer\") #if you like to\n await ctx.send(embed=embed)\n\n", "how about put @client.event instead of the @bot.command() it fixed everything when I put @client.event... @bot.command() does not work you can type\n@client.event\nasync def displayembed(ctx):\n embed = discord.Embed(title=\"Your title here\", description=\"Your desc here\") #,color=Hex code\n embed.add_field(name=\"Name\", value=\"you can make as much as fields you like to\")\n embed.set_footer(name=\"footer\") #if you like to\n await ctx.send(embed=embed)\n\n", "For anyone coming across this in 2022:\n\nhow about put @client.event instead of the @bot.command() it fixed everything when I put @client.event... @bot.command() does not work you can type\n\nTo this ^, I don't recommend using @client.event / @bot.event as you'd want to register your commands as a command.\nIf you want to simply make a command with an embed in your main.py file, make sure you have something like:\nimport discord\nfrom discord.ext import commands\n\nintents = discord.Itents.default()\n\nbot = commands.Bot(command_prefix='YOURPREFIX', description='description', intents=intents)\n\n@bot.command(name=\"embed\")\nasync def embed(ctx):\n embed = discord.Embed(title='Title', description='Desc', color=discord.Color.random())\n embed.add_field(name=\"Name\", value=\"Value\", inline=False)\n await ctx.send(embed=embed)\n\nHowever, I personally like separating my commands into a /commands folder and with separate files for all of them as it's good practice for neater code.\nFor that, I use cogs.\n/commands/embed.py\nfrom discord.ext import commands\nimport discord\n\nclass EmbedCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n \n @commands.command(name=\"embed\")\n async def embed(self, ctx):\n embed = discord.Embed(title='Title', description='Desc', color=discord.Color.random())\n embed.add_field(name=\"Name\", value=\"Value\", inline=False)\n await ctx.send(embed=embed)\n\nThen import it all into your main.py file:\nfrom commands.embed import EmbedCog\n\nbot.add_cog(EmbedCog(bot))\n\n", "Before using embed\nembed (Embed) – The rich embed for the content to send. This cannot be mixed with embeds parameter.\nembeds (List[Embed]) – A list of embeds to send with the content. Maximum of 10. This cannot be mixed with the embed\nTypeError – You specified both embed and embeds or file and files or thread and thread_name.\n@client.event\nasync def on_message(message):\n if message.content.startswith('!hi'):\n embed = discord.Embed(title=\"This is title of embedded element\", description=\"Desc\", color=0x00ff00)\n embed.add_field(name=\"Like header in HTML\", value=\"Text of field 1\", inline=False)\n embed.add_field(name=\"Like header in html\", value=\"text of field 2\", inline=False)\n await message.channel.send(embed=embed)\n\nReference\n" ]
[ 42, 7, 2, 2, 1, 0 ]
[]
[]
[ "discord", "discord.py", "embed", "python" ]
stackoverflow_0044862112_discord_discord.py_embed_python.txt
Q: Getting Annotations of a class and all parent classes in python Suppose you have a class structure like this: class parent(object): parent_annotation:str class child(parent): child_annotation:int Right now inspect.get_annotations(child) returns only {'child_annotation': <class:'int'>} I want a general-purpose way to get the union of annotations on all classes in the inheritance tree: {'child_annotation':<class:'int'>, 'parent_annotation':<class:'str'>} Is this possible? A: Thanks @juanpa.arrivillaga, and thanks @chepner Here's a solution: class parent(object): parent_annotation:str def all_annotations(self): all_annotations = {} for cls in type(self).mro(): all_annotations.update(inspect.get_annotations(cls)) return all_annotations class child(parent): child_annotation:int example_child = child() print(example_child.all_annotations()) >>> {'child_annotation':<class:'int'>, 'parent_annotation':<class:'str'>}
Getting Annotations of a class and all parent classes in python
Suppose you have a class structure like this: class parent(object): parent_annotation:str class child(parent): child_annotation:int Right now inspect.get_annotations(child) returns only {'child_annotation': <class:'int'>} I want a general-purpose way to get the union of annotations on all classes in the inheritance tree: {'child_annotation':<class:'int'>, 'parent_annotation':<class:'str'>} Is this possible?
[ "Thanks @juanpa.arrivillaga, and thanks @chepner\nHere's a solution:\n\nclass parent(object):\n parent_annotation:str\n\n def all_annotations(self):\n all_annotations = {}\n for cls in type(self).mro():\n all_annotations.update(inspect.get_annotations(cls))\n return all_annotations\n\nclass child(parent):\n child_annotation:int\n\nexample_child = child()\n\nprint(example_child.all_annotations())\n>>> {'child_annotation':<class:'int'>, 'parent_annotation':<class:'str'>}\n\n\n\n" ]
[ 0 ]
[]
[]
[ "oop", "python", "python_3.x" ]
stackoverflow_0074551257_oop_python_python_3.x.txt
Q: Create Nothing from falsey values using Returns library Using the Returns library, I have a function that filters a list. I want it to return Nothing if the list is empty (i.e. falsey) or Some([...]) if the list has values. Maybe seems to be mostly focused on "true" nothing, being None. But I'm wondering if there's a way to get Nothing from a falsey value without doing something like data = [] result = Some(data) if len(data) > 0 else Nothing A: It looks like you have at least a few options. (1) You can create a new class that inherits from Maybe, and then override any methods you like, (2) create a simple function that returns Nothing is data is false, else returns Maybe.from_optional(data) {or whatever other method of Maybe you prefer), or (3) create your own container as per the returns documentation at https://returns.readthedocs.io/en/latest/pages/create-your-own-container.html. Here is a class called Possibly, that inherits from Maybe and overrides the from_optional class method. You can add similar overrides for other methods following this pattern. from typing import Optional from returns.maybe import Maybe, _NewValueType, _Nothing, Some class Possibly(Maybe): def __init__(self): super().__init__() @classmethod def from_optional( cls, inner_value: Optional[_NewValueType], ) -> 'Maybe[_NewValueType]': """ Creates new instance of ``Maybe`` container based on an optional value. """ if not inner_value or inner_value is None: return _Nothing(inner_value) return Some(inner_value) data = [1,2,3] empty_data = [] print(Possibly.from_optional(data)) print(Possibly.from_optional(empty_data)) Here are two equivalent functions: from returns.maybe import Maybe, _Nothing data = [1,2,3] empty_data = [] def my_from_optional(anything): if not anything: return _Nothing(anything) else: return Maybe.from_optional(anything) def my_from_optional(anything): return Maybe.from_optional(anything) if anything else _Nothing(anything) print(my_from_optional(data)) print(my_from_optional(empty_data))
Create Nothing from falsey values using Returns library
Using the Returns library, I have a function that filters a list. I want it to return Nothing if the list is empty (i.e. falsey) or Some([...]) if the list has values. Maybe seems to be mostly focused on "true" nothing, being None. But I'm wondering if there's a way to get Nothing from a falsey value without doing something like data = [] result = Some(data) if len(data) > 0 else Nothing
[ "It looks like you have at least a few options. (1) You can create a new class that inherits from Maybe, and then override any methods you like, (2) create a simple function that returns Nothing is data is false, else returns Maybe.from_optional(data) {or whatever other method of Maybe you prefer), or (3) create your own container as per the returns documentation at https://returns.readthedocs.io/en/latest/pages/create-your-own-container.html.\nHere is a class called Possibly, that inherits from Maybe and overrides the from_optional class method. You can add similar overrides for other methods following this pattern.\nfrom typing import Optional\nfrom returns.maybe import Maybe, _NewValueType, _Nothing, Some\n\nclass Possibly(Maybe):\n def __init__(self):\n super().__init__()\n\n @classmethod\n def from_optional(\n cls, inner_value: Optional[_NewValueType],\n ) -> 'Maybe[_NewValueType]':\n \"\"\"\n Creates new instance of ``Maybe`` container based on an optional value.\n\n \"\"\"\n if not inner_value or inner_value is None:\n return _Nothing(inner_value)\n return Some(inner_value)\n\n\n\ndata = [1,2,3]\nempty_data = []\n\n\nprint(Possibly.from_optional(data))\nprint(Possibly.from_optional(empty_data))\n\nHere are two equivalent functions:\nfrom returns.maybe import Maybe, _Nothing\n\ndata = [1,2,3]\nempty_data = []\n\ndef my_from_optional(anything):\n if not anything:\n return _Nothing(anything)\n else:\n return Maybe.from_optional(anything)\n\ndef my_from_optional(anything):\n return Maybe.from_optional(anything) if anything else _Nothing(anything)\n\nprint(my_from_optional(data))\nprint(my_from_optional(empty_data))\n\n" ]
[ 0 ]
[]
[]
[ "option_type", "python" ]
stackoverflow_0074549388_option_type_python.txt
Q: What is a beautiful soup bound method? I'm experimenting with http://robobrowser.readthedocs.org/en/latest/readme.html, a new python library based on the beautiful soup library. I'm trying to test it out by opening an html page and returning it within a django app, but I can't figure out to do this most simple task. My django app contains : def index(request): p=str(request.POST.get('p', False)) # p='https://www.yahoo.com/' browser = RoboBrowser(history=True) browser.open(p) html = browser.find_all return HttpResponse(html) when I look at the outputted html I see: <bound method BeautifulSoup.find_all of <!DOCTYPE html> <html> ...................... <head> ............... </body> </html> > What is a beautiful soup bound method? How can I get the straight html? A: It's a method object, bound to the BeautifulSoup object. You didn't call it. It's representation is a little confusing because the repr() of the BeautifulSoup parse tree is included, which is simply the tree rendered as a HTML source string. To get to the underlying BeautifulSoup parse tree, you can use; use str() to turn that back into a source string: html = str(browser.state.parsed) Alternatively, you can still access the original requests response object with: browser.state.response which means that the original downloaded HTML is found as: html = browser.state.response.content A: BeautifulSoup is a Python package used for parsing HTML and XML documents, it creates a parse tree for parsed paged which can be used for web scraping. There are many Beautifulsoup methods, which allows us to search a parse tree. If we search out of that tree it will be out of bound. .next_sibling and .previous_sibling are the tags that are used for navigating between page elements that are on same level of the parse tree. Reference
What is a beautiful soup bound method?
I'm experimenting with http://robobrowser.readthedocs.org/en/latest/readme.html, a new python library based on the beautiful soup library. I'm trying to test it out by opening an html page and returning it within a django app, but I can't figure out to do this most simple task. My django app contains : def index(request): p=str(request.POST.get('p', False)) # p='https://www.yahoo.com/' browser = RoboBrowser(history=True) browser.open(p) html = browser.find_all return HttpResponse(html) when I look at the outputted html I see: <bound method BeautifulSoup.find_all of <!DOCTYPE html> <html> ...................... <head> ............... </body> </html> > What is a beautiful soup bound method? How can I get the straight html?
[ "It's a method object, bound to the BeautifulSoup object. You didn't call it.\nIt's representation is a little confusing because the repr() of the BeautifulSoup parse tree is included, which is simply the tree rendered as a HTML source string.\nTo get to the underlying BeautifulSoup parse tree, you can use; use str() to turn that back into a source string:\nhtml = str(browser.state.parsed)\n\nAlternatively, you can still access the original requests response object with:\nbrowser.state.response\n\nwhich means that the original downloaded HTML is found as:\nhtml = browser.state.response.content\n\n", "BeautifulSoup is a Python package used for parsing HTML and XML documents, it creates a parse tree for parsed paged which can be used for web scraping.\nThere are many Beautifulsoup methods, which allows us to search a parse tree. If we search out of that tree it will be out of bound.\n.next_sibling and .previous_sibling are the tags that are used for navigating between page elements that are on same level of the parse tree.\nReference\n" ]
[ 3, 0 ]
[]
[]
[ "beautifulsoup", "django", "python", "robobrowser" ]
stackoverflow_0023414369_beautifulsoup_django_python_robobrowser.txt
Q: Unable to install orjson 3.3.0 on macOS 12.2.1 with Apple M1 chip I am trying to install orjson==3.3.0 on my MacBook Pro with Apple M1 Pro chip running macOS Monterey 12.2.1. Python version: 3.8.9 Command used: pip install orjson==3.3.0 Error: Collecting orjson==3.3.0 Downloading orjson-3.3.0.tar.gz (654 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 654.9/654.9 KB 2.9 MB/s eta 0:00:00 Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> [468 lines of output] Collecting maturin<0.9,>=0.8.1 Downloading maturin-0.8.3.tar.gz (82 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 82.2/82.2 KB 1.5 MB/s eta 0:00:00 Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing metadata (pyproject.toml): started Preparing metadata (pyproject.toml): finished with status 'done' Collecting toml~=0.10.0 Using cached toml-0.10.2-py2.py3-none-any.whl (16 kB) Building wheels for collected packages: maturin Building wheel for maturin (pyproject.toml): started Building wheel for maturin (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for maturin (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [443 lines of output] running bdist_wheel running build installing to build/bdist.macosx-10.14-arm64/wheel running install Updating crates.io index Downloading crates ... Downloaded mime_guess v2.0.3 Downloaded net2 v0.2.34 Downloaded num_cpus v1.13.0 Downloaded once_cell v1.4.0 Downloaded shlex v0.1.1 Downloaded regex v1.3.9 Downloaded socket2 v0.3.12 Downloaded termcolor v1.1.0 Downloaded podio v0.1.7 Downloaded ppv-lite86 v0.2.8 Downloaded proc-macro-nested v0.1.6 Downloaded proc-macro-error-attr v1.0.4 Downloaded semver v0.10.0 Downloaded rand_chacha v0.2.2 Downloaded serde_json v1.0.57 Downloaded platform-info v0.0.1 Downloaded quote v1.0.7 Downloaded rand_core v0.5.1 Downloaded ansi_term v0.11.0 Downloaded tempfile v3.1.0 Downloaded cc v1.0.58 Downloaded scroll_derive v0.10.2 Downloaded proc-macro-hack v0.5.18 Downloaded textwrap v0.11.0 Downloaded time v0.1.43 Downloaded clap v2.33.3 Downloaded unicode-width v0.1.8 Downloaded httparse v1.3.4 Downloaded crc32fast v1.2.0 Downloaded try-lock v0.2.3 Downloaded http-body v0.3.1 Downloaded futures-sink v0.3.5 Downloaded dtoa v0.4.6 Downloaded hyper v0.13.7 Downloaded serde v1.0.115 Downloaded vec_map v0.8.2 Downloaded matches v0.1.8 Downloaded idna v0.2.0 Downloaded strsim v0.8.0 Downloaded proc-macro-error v1.0.4 Downloaded digest v0.9.0 Downloaded pin-project v0.4.23 Downloaded rustc-demangle v0.1.16 Downloaded slab v0.4.2 Downloaded thiserror v1.0.20 Downloaded thread_local v1.0.1 Downloaded thiserror-impl v1.0.20 Downloaded sha2 v0.9.1 Downloaded want v0.3.0 Downloaded untrusted v0.7.1 Downloaded spin v0.5.2 Downloaded scroll v0.10.1 Downloaded percent-encoding v2.1.0 Downloaded toml v0.5.6 Downloaded tinyvec v0.3.3 Downloaded tower-service v0.3.0 Downloaded serde_urlencoded v0.6.1 Downloaded same-file v1.0.6 Downloaded structopt-derive v0.4.9 Downloaded serde_derive v1.0.115 Downloaded platforms v0.2.1 Downloaded pin-project-lite v0.1.7 Downloaded mime v0.3.16 Downloaded glob v0.3.0 Downloaded typenum v1.12.0 Downloaded block-buffer v0.9.0 Downloaded tar v0.4.29 Downloaded unicode-bidi v0.3.4 Downloaded unicode-segmentation v1.6.0 Downloaded url v2.1.1 Downloaded version_check v0.9.2 Downloaded tokio-rustls v0.14.0 Downloaded walkdir v2.3.1 Downloaded xattr v0.2.2 Downloaded tracing v0.1.19 Downloaded pretty_env_logger v0.4.0 Downloaded unicase v2.6.0 Downloaded rand v0.7.3 Downloaded unicode-xid v0.2.1 Downloaded tracing-core v0.1.14 Downloaded uuid v0.8.1 Downloaded zip v0.5.6 Downloaded webpki v0.21.3 Downloaded sct v0.6.0 Downloaded unicode-normalization v0.1.13 Downloaded adler v0.2.3 Downloaded anyhow v1.0.32 Downloaded futures-io v0.3.5 Downloaded futures-core v0.3.5 Downloaded futures-task v0.3.5 Downloaded tokio-util v0.3.1 Downloaded semver-parser v0.7.0 Downloaded hashbrown v0.8.2 Downloaded rpassword v4.0.5 Downloaded getrandom v0.1.14 Downloaded heck v0.3.1 Downloaded futures-macro v0.3.5 Downloaded http v0.2.1 Downloaded ipnet v2.3.0 Downloaded itoa v0.4.6 Downloaded human-panic v1.0.3 Downloaded plain v0.2.3 Downloaded log v0.4.11 Downloaded memchr v2.3.3 Downloaded miniz_oxide v0.4.0 Downloaded mio v0.6.22 Downloaded indexmap v1.5.1 Downloaded futures-util v0.3.5 Downloaded bzip2 v0.3.3 Downloaded iovec v0.1.4 Downloaded atty v0.2.14 Downloaded cargo_metadata v0.11.1 Downloaded cbindgen v0.14.3 Downloaded winapi v0.3.9 Downloaded webpki-roots v0.19.0 Downloaded pin-project-internal v0.4.23 Downloaded h2 v0.2.6 Downloaded hyper-rustls v0.21.0 Downloaded humantime v1.3.0 Downloaded env_logger v0.7.1 Downloaded structopt v0.3.16 Downloaded goblin v0.2.3 Downloaded pkg-config v0.3.18 Downloaded autocfg v1.0.0 Downloaded syn v1.0.38 Downloaded rustls v0.18.1 Downloaded object v0.20.0 Downloaded pin-utils v0.1.0 Downloaded opaque-debug v0.3.0 Downloaded proc-macro2 v1.0.19 Downloaded quick-error v1.2.3 Downloaded bytesize v1.0.1 Downloaded futures-channel v0.3.5 Downloaded tokio v0.2.22 Downloaded cfg-if v0.1.10 Downloaded lazy_static v1.4.0 Downloaded fnv v1.0.7 Downloaded base64 v0.12.3 Downloaded generic-array v0.14.4 Downloaded filetime v0.2.12 Downloaded remove_dir_all v0.5.3 Downloaded backtrace v0.3.50 Downloaded reqwest v0.10.7 Downloaded bytes v0.5.6 Downloaded bitflags v1.2.1 Downloaded aho-corasick v0.7.13 Downloaded os_type v2.2.0 Downloaded flate2 v1.0.16 Downloaded libc v0.2.74 Downloaded bzip2-sys v0.1.9+1.0.8 Downloaded addr2line v0.13.0 Downloaded regex-syntax v0.6.18 Downloaded gimli v0.22.0 Downloaded ryu v1.0.5 Downloaded encoding_rs v0.8.23 Downloaded ring v0.16.15 Compiling libc v0.2.74 Compiling cfg-if v0.1.10 Compiling proc-macro2 v1.0.19 Compiling unicode-xid v0.2.1 Compiling syn v1.0.38 Compiling version_check v0.9.2 Compiling log v0.4.11 Compiling memchr v2.3.3 Compiling lazy_static v1.4.0 Compiling cc v1.0.58 Compiling serde_derive v1.0.115 Compiling serde v1.0.115 Compiling itoa v0.4.6 Compiling autocfg v1.0.0 Compiling fnv v1.0.7 Compiling getrandom v0.1.14 Compiling bytes v0.5.6 Compiling slab v0.4.2 Compiling futures-core v0.3.5 Compiling untrusted v0.7.1 Compiling pin-project-internal v0.4.23 Compiling spin v0.5.2 Compiling pin-project-lite v0.1.7 Compiling proc-macro-nested v0.1.6 Compiling proc-macro-hack v0.5.18 Compiling typenum v1.12.0 Compiling once_cell v1.4.0 Compiling ppv-lite86 v0.2.8 Compiling pin-utils v0.1.0 Compiling matches v0.1.8 Compiling futures-sink v0.3.5 Compiling ryu v1.0.5 Compiling regex-syntax v0.6.18 Compiling pkg-config v0.3.18 Compiling tinyvec v0.3.3 Compiling adler v0.2.3 Compiling futures-io v0.3.5 Compiling httparse v1.3.4 Compiling base64 v0.12.3 Compiling unicode-segmentation v1.6.0 Compiling serde_json v1.0.57 Compiling bitflags v1.2.1 Compiling crc32fast v1.2.0 Compiling try-lock v0.2.3 Compiling termcolor v1.1.0 Compiling quick-error v1.2.3 Compiling gimli v0.22.0 Compiling winapi v0.3.9 Compiling tower-service v0.3.0 Compiling percent-encoding v2.1.0 Compiling unicode-width v0.1.8 Compiling encoding_rs v0.8.23 Compiling semver-parser v0.7.0 Compiling vec_map v0.8.2 Compiling remove_dir_all v0.5.3 Compiling ansi_term v0.11.0 Compiling object v0.20.0 Compiling mime v0.3.16 Compiling cbindgen v0.14.3 Compiling anyhow v1.0.32 Compiling strsim v0.8.0 Compiling rustc-demangle v0.1.16 Compiling dtoa v0.4.6 Compiling same-file v1.0.6 Compiling plain v0.2.3 Compiling podio v0.1.7 Compiling ipnet v2.3.0 Compiling opaque-debug v0.3.0 Compiling bytesize v1.0.1 Compiling glob v0.3.0 Compiling shlex v0.1.1 Compiling platforms v0.2.1 Compiling thread_local v1.0.1 Compiling tracing-core v0.1.14 Compiling unicase v2.6.0 Compiling proc-macro-error-attr v1.0.4 Compiling generic-array v0.14.4 Compiling proc-macro-error v1.0.4 Compiling hashbrown v0.8.2 Compiling indexmap v1.5.1 Compiling http v0.2.1 Compiling ring v0.16.15 Compiling futures-channel v0.3.5 Compiling futures-task v0.3.5 Compiling unicode-bidi v0.3.4 Compiling miniz_oxide v0.4.0 Compiling unicode-normalization v0.1.13 Compiling heck v0.3.1 Compiling humantime v1.3.0 Compiling bzip2-sys v0.1.9+1.0.8 Compiling textwrap v0.11.0 Compiling walkdir v2.3.1 Compiling addr2line v0.13.0 Compiling http-body v0.3.1 Compiling idna v0.2.0 Compiling tracing v0.1.19 Compiling want v0.3.0 Compiling aho-corasick v0.7.13 Compiling net2 v0.2.34 Compiling iovec v0.1.4 Compiling num_cpus v1.13.0 Compiling time v0.1.43 Compiling atty v0.2.14 Compiling socket2 v0.3.12 Compiling backtrace v0.3.50 Compiling xattr v0.2.2 Compiling filetime v0.2.12 Compiling rpassword v4.0.5 error: failed to run custom build command for `ring v0.16.15` Caused by: process didn't exit successfully: `/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug/build/ring-e433715426729417/build-script-build` (exit status: 101) --- stdout OPT_LEVEL = Some("0") TARGET = Some("aarch64-apple-darwin") HOST = Some("aarch64-apple-darwin") CC_aarch64-apple-darwin = None CC_aarch64_apple_darwin = None HOST_CC = None CC = None CFLAGS_aarch64-apple-darwin = None CFLAGS_aarch64_apple_darwin = None HOST_CFLAGS = None CFLAGS = None CRATE_CC_NO_DEFAULTS = None DEBUG = Some("true") CARGO_CFG_TARGET_FEATURE = None --- stderr ENV CARGO=/Users/admin/.rustup/toolchains/stable-aarch64-apple-darwin/bin/cargo ENV CARGO_CFG_TARGET_ARCH=aarch64 ENV CARGO_CFG_TARGET_ENDIAN=little ENV CARGO_CFG_TARGET_ENV= ENV CARGO_CFG_TARGET_FAMILY=unix ENV CARGO_CFG_TARGET_OS=macos ENV CARGO_CFG_TARGET_POINTER_WIDTH=64 ENV CARGO_CFG_TARGET_VENDOR=apple ENV CARGO_CFG_UNIX= ENV CARGO_ENCODED_RUSTFLAGS= ENV CARGO_FEATURE_ALLOC=1 ENV CARGO_FEATURE_DEFAULT=1 ENV CARGO_FEATURE_DEV_URANDOM_FALLBACK=1 ENV CARGO_FEATURE_ONCE_CELL=1 ENV CARGO_HOME=/Users/admin/.cargo ENV CARGO_MAKEFLAGS=-j --jobserver-fds=8,10 --jobserver-auth=8,10 ENV CARGO_MANIFEST_DIR=/Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15 ENV CARGO_MANIFEST_LINKS=ring-asm ENV CARGO_PKG_AUTHORS=Brian Smith <brian@briansmith.org> ENV CARGO_PKG_DESCRIPTION=Safe, fast, small crypto using Rust. ENV CARGO_PKG_HOMEPAGE= ENV CARGO_PKG_LICENSE= ENV CARGO_PKG_LICENSE_FILE=LICENSE ENV CARGO_PKG_NAME=ring ENV CARGO_PKG_REPOSITORY=https://github.com/briansmith/ring ENV CARGO_PKG_VERSION=0.16.15 ENV CARGO_PKG_VERSION_MAJOR=0 ENV CARGO_PKG_VERSION_MINOR=16 ENV CARGO_PKG_VERSION_PATCH=15 ENV CARGO_PKG_VERSION_PRE= ENV DEBUG=true ENV DYLD_FALLBACK_LIBRARY_PATH=/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug/deps:/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug:/Users/admin/.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/aarch64-apple-darwin/lib:/Users/admin/.rustup/toolchains/stable-aarch64-apple-darwin/lib:/Users/admin/lib:/usr/local/lib:/usr/lib ENV HOME=/Users/admin ENV HOST=aarch64-apple-darwin ENV LC_CTYPE=UTF-8 ENV LOGNAME=admin ENV NUM_JOBS=10 ENV OLDPWD=/Users/admin ENV OPT_LEVEL=0 ENV OUT_DIR=/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug/build/ring-74dfb65fdc90ab2c/out ENV PATH=/Users/admin/.cargo/bin:/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/bin:/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/normal/bin:/Users/admin/.cargo/bin:/Users/admin/venv/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin ENV PEP517_BUILD_BACKEND=setuptools.build_meta ENV PIP_REQ_TRACKER=/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-req-tracker-179wcdnq ENV PLAT=macosx-10.14-arm64 ENV PROFILE=debug ENV PS1=(venv) %n@%m %1~ %# ENV PWD=/Users/admin ENV PYTHONNOUSERSITE=1 ENV PYTHONPATH=/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/site ENV RUSTC=rustc ENV RUSTDOC=rustdoc ENV RUSTUP_HOME=/Users/admin/.rustup ENV RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin ENV RUST_RECURSION_COUNT=1 ENV SHELL=/bin/zsh ENV SHLVL=1 ENV SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.WMzJWaFIA5/Listeners ENV TARGET=aarch64-apple-darwin ENV TERM=xterm-256color ENV TERM_PROGRAM=Apple_Terminal ENV TERM_PROGRAM_VERSION=443 ENV TERM_SESSION_ID=B8FDBA53-2516-4197-B600-445E738CFDEF ENV TMPDIR=/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/ ENV USER=admin ENV VIRTUAL_ENV=/Users/admin/venv ENV XPC_FLAGS=0x0 ENV XPC_SERVICE_NAME=0 ENV _=/Users/admin/venv/bin/pip ENV _PIP_STANDALONE_CERT=/Users/admin/venv/lib/python3.8/site-packages/pip/_vendor/certifi/cacert.pem ENV __CFBundleIdentifier=com.apple.Terminal ENV __CF_USER_TEXT_ENCODING=0x1F7:0x0:0x0 running "cc" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-fno-omit-frame-pointer" "-arch" "arm64" "-I" "include" "-Wall" "-Wextra" "-pedantic" "-pedantic-errors" "-Wall" "-Wextra" "-Wcast-align" "-Wcast-qual" "-Wconversion" "-Wenum-compare" "-Wfloat-equal" "-Wformat=2" "-Winline" "-Winvalid-pch" "-Wmissing-field-initializers" "-Wmissing-include-dirs" "-Wredundant-decls" "-Wshadow" "-Wsign-compare" "-Wsign-conversion" "-Wundef" "-Wuninitialized" "-Wwrite-strings" "-fno-strict-aliasing" "-fvisibility=hidden" "-fstack-protector" "-gfull" "-DNDEBUG" "-c" "-o/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug/build/ring-74dfb65fdc90ab2c/out/aesv8-armx-linux64.o" "/Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S" /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:18:17: error: unexpected token in '.section' directive .section .rodata ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:28:1: error: unknown directive .hidden GFp_aes_hw_set_encrypt_key ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:29:1: error: unknown directive .type GFp_aes_hw_set_encrypt_key,%function ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:161:1: error: unknown directive .size GFp_aes_hw_set_encrypt_key,.-GFp_aes_hw_set_encrypt_key ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:163:1: error: unknown directive .hidden GFp_aes_hw_encrypt ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:164:1: error: unknown directive .type GFp_aes_hw_encrypt,%function ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:191:1: error: unknown directive .size GFp_aes_hw_encrypt,.-GFp_aes_hw_encrypt ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:193:1: error: unknown directive .hidden GFp_aes_hw_decrypt ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:194:1: error: unknown directive .type GFp_aes_hw_decrypt,%function ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:221:1: error: unknown directive .size GFp_aes_hw_decrypt,.-GFp_aes_hw_decrypt ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:223:1: error: unknown directive .hidden GFp_aes_hw_ctr32_encrypt_blocks ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:224:1: error: unknown directive .type GFp_aes_hw_ctr32_encrypt_blocks,%function ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:403:1: error: unknown directive .size GFp_aes_hw_ctr32_encrypt_blocks,.-GFp_aes_hw_ctr32_encrypt_blocks ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:407:19: error: unexpected token in '.section' directive .section .note.GNU-stack,"",%progbits ^ thread 'main' panicked at 'execution failed', /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/build.rs:664:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace warning: build failed, waiting for other jobs to finish... error: build failed Traceback (most recent call last): File "/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/tmpwhciv39r", line 363, in <module> main() File "/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/tmpwhciv39r", line 345, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/tmpwhciv39r", line 261, in build_wheel return _build_backend().build_wheel(wheel_directory, config_settings, File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 208, in build_wheel return self._build_with_temp_dir(['bdist_wheel'], '.whl', File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 194, in _build_with_temp_dir self.run_setup() File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 142, in run_setup exec(compile(code, __file__, 'exec'), locals()) File "setup.py", line 81, in <module> setup( File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/setuptools/__init__.py", line 145, in setup return distutils.core.setup(**attrs) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/core.py", line 148, in setup dist.run_commands() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/dist.py", line 966, in run_commands self.run_command(cmd) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/dist.py", line 985, in run_command cmd_obj.run() File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/wheel/bdist_wheel.py", line 228, in run self.run_command('install') File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/cmd.py", line 313, in run_command self.distribution.run_command(command) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/dist.py", line 985, in run_command cmd_obj.run() File "setup.py", line 58, in run subprocess.check_call( File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['cargo', 'rustc', '--bin', 'maturin', '--', '-C', 'link-arg=-s']' returned non-zero exit status 101. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for maturin Failed to build maturin ERROR: Could not build wheels for maturin, which is required to install pyproject.toml-based projects [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I have tried looking around and stumbled upon the following posts: Does Poetry install --no-dev need Rust to be installed? requirement.txt installation is failing while building "orjson" on 64 bit python interpreter on 64 bit Mac OSX However, it did not really help. Any help would be highly appreciated. A: I don't know if that helps you but I had a similar Problem with 3.6.2, so I ran pip install orjson and it installed orjson==3.8.1 without a Problem.
Unable to install orjson 3.3.0 on macOS 12.2.1 with Apple M1 chip
I am trying to install orjson==3.3.0 on my MacBook Pro with Apple M1 Pro chip running macOS Monterey 12.2.1. Python version: 3.8.9 Command used: pip install orjson==3.3.0 Error: Collecting orjson==3.3.0 Downloading orjson-3.3.0.tar.gz (654 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 654.9/654.9 KB 2.9 MB/s eta 0:00:00 Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> [468 lines of output] Collecting maturin<0.9,>=0.8.1 Downloading maturin-0.8.3.tar.gz (82 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 82.2/82.2 KB 1.5 MB/s eta 0:00:00 Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing metadata (pyproject.toml): started Preparing metadata (pyproject.toml): finished with status 'done' Collecting toml~=0.10.0 Using cached toml-0.10.2-py2.py3-none-any.whl (16 kB) Building wheels for collected packages: maturin Building wheel for maturin (pyproject.toml): started Building wheel for maturin (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for maturin (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [443 lines of output] running bdist_wheel running build installing to build/bdist.macosx-10.14-arm64/wheel running install Updating crates.io index Downloading crates ... Downloaded mime_guess v2.0.3 Downloaded net2 v0.2.34 Downloaded num_cpus v1.13.0 Downloaded once_cell v1.4.0 Downloaded shlex v0.1.1 Downloaded regex v1.3.9 Downloaded socket2 v0.3.12 Downloaded termcolor v1.1.0 Downloaded podio v0.1.7 Downloaded ppv-lite86 v0.2.8 Downloaded proc-macro-nested v0.1.6 Downloaded proc-macro-error-attr v1.0.4 Downloaded semver v0.10.0 Downloaded rand_chacha v0.2.2 Downloaded serde_json v1.0.57 Downloaded platform-info v0.0.1 Downloaded quote v1.0.7 Downloaded rand_core v0.5.1 Downloaded ansi_term v0.11.0 Downloaded tempfile v3.1.0 Downloaded cc v1.0.58 Downloaded scroll_derive v0.10.2 Downloaded proc-macro-hack v0.5.18 Downloaded textwrap v0.11.0 Downloaded time v0.1.43 Downloaded clap v2.33.3 Downloaded unicode-width v0.1.8 Downloaded httparse v1.3.4 Downloaded crc32fast v1.2.0 Downloaded try-lock v0.2.3 Downloaded http-body v0.3.1 Downloaded futures-sink v0.3.5 Downloaded dtoa v0.4.6 Downloaded hyper v0.13.7 Downloaded serde v1.0.115 Downloaded vec_map v0.8.2 Downloaded matches v0.1.8 Downloaded idna v0.2.0 Downloaded strsim v0.8.0 Downloaded proc-macro-error v1.0.4 Downloaded digest v0.9.0 Downloaded pin-project v0.4.23 Downloaded rustc-demangle v0.1.16 Downloaded slab v0.4.2 Downloaded thiserror v1.0.20 Downloaded thread_local v1.0.1 Downloaded thiserror-impl v1.0.20 Downloaded sha2 v0.9.1 Downloaded want v0.3.0 Downloaded untrusted v0.7.1 Downloaded spin v0.5.2 Downloaded scroll v0.10.1 Downloaded percent-encoding v2.1.0 Downloaded toml v0.5.6 Downloaded tinyvec v0.3.3 Downloaded tower-service v0.3.0 Downloaded serde_urlencoded v0.6.1 Downloaded same-file v1.0.6 Downloaded structopt-derive v0.4.9 Downloaded serde_derive v1.0.115 Downloaded platforms v0.2.1 Downloaded pin-project-lite v0.1.7 Downloaded mime v0.3.16 Downloaded glob v0.3.0 Downloaded typenum v1.12.0 Downloaded block-buffer v0.9.0 Downloaded tar v0.4.29 Downloaded unicode-bidi v0.3.4 Downloaded unicode-segmentation v1.6.0 Downloaded url v2.1.1 Downloaded version_check v0.9.2 Downloaded tokio-rustls v0.14.0 Downloaded walkdir v2.3.1 Downloaded xattr v0.2.2 Downloaded tracing v0.1.19 Downloaded pretty_env_logger v0.4.0 Downloaded unicase v2.6.0 Downloaded rand v0.7.3 Downloaded unicode-xid v0.2.1 Downloaded tracing-core v0.1.14 Downloaded uuid v0.8.1 Downloaded zip v0.5.6 Downloaded webpki v0.21.3 Downloaded sct v0.6.0 Downloaded unicode-normalization v0.1.13 Downloaded adler v0.2.3 Downloaded anyhow v1.0.32 Downloaded futures-io v0.3.5 Downloaded futures-core v0.3.5 Downloaded futures-task v0.3.5 Downloaded tokio-util v0.3.1 Downloaded semver-parser v0.7.0 Downloaded hashbrown v0.8.2 Downloaded rpassword v4.0.5 Downloaded getrandom v0.1.14 Downloaded heck v0.3.1 Downloaded futures-macro v0.3.5 Downloaded http v0.2.1 Downloaded ipnet v2.3.0 Downloaded itoa v0.4.6 Downloaded human-panic v1.0.3 Downloaded plain v0.2.3 Downloaded log v0.4.11 Downloaded memchr v2.3.3 Downloaded miniz_oxide v0.4.0 Downloaded mio v0.6.22 Downloaded indexmap v1.5.1 Downloaded futures-util v0.3.5 Downloaded bzip2 v0.3.3 Downloaded iovec v0.1.4 Downloaded atty v0.2.14 Downloaded cargo_metadata v0.11.1 Downloaded cbindgen v0.14.3 Downloaded winapi v0.3.9 Downloaded webpki-roots v0.19.0 Downloaded pin-project-internal v0.4.23 Downloaded h2 v0.2.6 Downloaded hyper-rustls v0.21.0 Downloaded humantime v1.3.0 Downloaded env_logger v0.7.1 Downloaded structopt v0.3.16 Downloaded goblin v0.2.3 Downloaded pkg-config v0.3.18 Downloaded autocfg v1.0.0 Downloaded syn v1.0.38 Downloaded rustls v0.18.1 Downloaded object v0.20.0 Downloaded pin-utils v0.1.0 Downloaded opaque-debug v0.3.0 Downloaded proc-macro2 v1.0.19 Downloaded quick-error v1.2.3 Downloaded bytesize v1.0.1 Downloaded futures-channel v0.3.5 Downloaded tokio v0.2.22 Downloaded cfg-if v0.1.10 Downloaded lazy_static v1.4.0 Downloaded fnv v1.0.7 Downloaded base64 v0.12.3 Downloaded generic-array v0.14.4 Downloaded filetime v0.2.12 Downloaded remove_dir_all v0.5.3 Downloaded backtrace v0.3.50 Downloaded reqwest v0.10.7 Downloaded bytes v0.5.6 Downloaded bitflags v1.2.1 Downloaded aho-corasick v0.7.13 Downloaded os_type v2.2.0 Downloaded flate2 v1.0.16 Downloaded libc v0.2.74 Downloaded bzip2-sys v0.1.9+1.0.8 Downloaded addr2line v0.13.0 Downloaded regex-syntax v0.6.18 Downloaded gimli v0.22.0 Downloaded ryu v1.0.5 Downloaded encoding_rs v0.8.23 Downloaded ring v0.16.15 Compiling libc v0.2.74 Compiling cfg-if v0.1.10 Compiling proc-macro2 v1.0.19 Compiling unicode-xid v0.2.1 Compiling syn v1.0.38 Compiling version_check v0.9.2 Compiling log v0.4.11 Compiling memchr v2.3.3 Compiling lazy_static v1.4.0 Compiling cc v1.0.58 Compiling serde_derive v1.0.115 Compiling serde v1.0.115 Compiling itoa v0.4.6 Compiling autocfg v1.0.0 Compiling fnv v1.0.7 Compiling getrandom v0.1.14 Compiling bytes v0.5.6 Compiling slab v0.4.2 Compiling futures-core v0.3.5 Compiling untrusted v0.7.1 Compiling pin-project-internal v0.4.23 Compiling spin v0.5.2 Compiling pin-project-lite v0.1.7 Compiling proc-macro-nested v0.1.6 Compiling proc-macro-hack v0.5.18 Compiling typenum v1.12.0 Compiling once_cell v1.4.0 Compiling ppv-lite86 v0.2.8 Compiling pin-utils v0.1.0 Compiling matches v0.1.8 Compiling futures-sink v0.3.5 Compiling ryu v1.0.5 Compiling regex-syntax v0.6.18 Compiling pkg-config v0.3.18 Compiling tinyvec v0.3.3 Compiling adler v0.2.3 Compiling futures-io v0.3.5 Compiling httparse v1.3.4 Compiling base64 v0.12.3 Compiling unicode-segmentation v1.6.0 Compiling serde_json v1.0.57 Compiling bitflags v1.2.1 Compiling crc32fast v1.2.0 Compiling try-lock v0.2.3 Compiling termcolor v1.1.0 Compiling quick-error v1.2.3 Compiling gimli v0.22.0 Compiling winapi v0.3.9 Compiling tower-service v0.3.0 Compiling percent-encoding v2.1.0 Compiling unicode-width v0.1.8 Compiling encoding_rs v0.8.23 Compiling semver-parser v0.7.0 Compiling vec_map v0.8.2 Compiling remove_dir_all v0.5.3 Compiling ansi_term v0.11.0 Compiling object v0.20.0 Compiling mime v0.3.16 Compiling cbindgen v0.14.3 Compiling anyhow v1.0.32 Compiling strsim v0.8.0 Compiling rustc-demangle v0.1.16 Compiling dtoa v0.4.6 Compiling same-file v1.0.6 Compiling plain v0.2.3 Compiling podio v0.1.7 Compiling ipnet v2.3.0 Compiling opaque-debug v0.3.0 Compiling bytesize v1.0.1 Compiling glob v0.3.0 Compiling shlex v0.1.1 Compiling platforms v0.2.1 Compiling thread_local v1.0.1 Compiling tracing-core v0.1.14 Compiling unicase v2.6.0 Compiling proc-macro-error-attr v1.0.4 Compiling generic-array v0.14.4 Compiling proc-macro-error v1.0.4 Compiling hashbrown v0.8.2 Compiling indexmap v1.5.1 Compiling http v0.2.1 Compiling ring v0.16.15 Compiling futures-channel v0.3.5 Compiling futures-task v0.3.5 Compiling unicode-bidi v0.3.4 Compiling miniz_oxide v0.4.0 Compiling unicode-normalization v0.1.13 Compiling heck v0.3.1 Compiling humantime v1.3.0 Compiling bzip2-sys v0.1.9+1.0.8 Compiling textwrap v0.11.0 Compiling walkdir v2.3.1 Compiling addr2line v0.13.0 Compiling http-body v0.3.1 Compiling idna v0.2.0 Compiling tracing v0.1.19 Compiling want v0.3.0 Compiling aho-corasick v0.7.13 Compiling net2 v0.2.34 Compiling iovec v0.1.4 Compiling num_cpus v1.13.0 Compiling time v0.1.43 Compiling atty v0.2.14 Compiling socket2 v0.3.12 Compiling backtrace v0.3.50 Compiling xattr v0.2.2 Compiling filetime v0.2.12 Compiling rpassword v4.0.5 error: failed to run custom build command for `ring v0.16.15` Caused by: process didn't exit successfully: `/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug/build/ring-e433715426729417/build-script-build` (exit status: 101) --- stdout OPT_LEVEL = Some("0") TARGET = Some("aarch64-apple-darwin") HOST = Some("aarch64-apple-darwin") CC_aarch64-apple-darwin = None CC_aarch64_apple_darwin = None HOST_CC = None CC = None CFLAGS_aarch64-apple-darwin = None CFLAGS_aarch64_apple_darwin = None HOST_CFLAGS = None CFLAGS = None CRATE_CC_NO_DEFAULTS = None DEBUG = Some("true") CARGO_CFG_TARGET_FEATURE = None --- stderr ENV CARGO=/Users/admin/.rustup/toolchains/stable-aarch64-apple-darwin/bin/cargo ENV CARGO_CFG_TARGET_ARCH=aarch64 ENV CARGO_CFG_TARGET_ENDIAN=little ENV CARGO_CFG_TARGET_ENV= ENV CARGO_CFG_TARGET_FAMILY=unix ENV CARGO_CFG_TARGET_OS=macos ENV CARGO_CFG_TARGET_POINTER_WIDTH=64 ENV CARGO_CFG_TARGET_VENDOR=apple ENV CARGO_CFG_UNIX= ENV CARGO_ENCODED_RUSTFLAGS= ENV CARGO_FEATURE_ALLOC=1 ENV CARGO_FEATURE_DEFAULT=1 ENV CARGO_FEATURE_DEV_URANDOM_FALLBACK=1 ENV CARGO_FEATURE_ONCE_CELL=1 ENV CARGO_HOME=/Users/admin/.cargo ENV CARGO_MAKEFLAGS=-j --jobserver-fds=8,10 --jobserver-auth=8,10 ENV CARGO_MANIFEST_DIR=/Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15 ENV CARGO_MANIFEST_LINKS=ring-asm ENV CARGO_PKG_AUTHORS=Brian Smith <brian@briansmith.org> ENV CARGO_PKG_DESCRIPTION=Safe, fast, small crypto using Rust. ENV CARGO_PKG_HOMEPAGE= ENV CARGO_PKG_LICENSE= ENV CARGO_PKG_LICENSE_FILE=LICENSE ENV CARGO_PKG_NAME=ring ENV CARGO_PKG_REPOSITORY=https://github.com/briansmith/ring ENV CARGO_PKG_VERSION=0.16.15 ENV CARGO_PKG_VERSION_MAJOR=0 ENV CARGO_PKG_VERSION_MINOR=16 ENV CARGO_PKG_VERSION_PATCH=15 ENV CARGO_PKG_VERSION_PRE= ENV DEBUG=true ENV DYLD_FALLBACK_LIBRARY_PATH=/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug/deps:/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug:/Users/admin/.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/aarch64-apple-darwin/lib:/Users/admin/.rustup/toolchains/stable-aarch64-apple-darwin/lib:/Users/admin/lib:/usr/local/lib:/usr/lib ENV HOME=/Users/admin ENV HOST=aarch64-apple-darwin ENV LC_CTYPE=UTF-8 ENV LOGNAME=admin ENV NUM_JOBS=10 ENV OLDPWD=/Users/admin ENV OPT_LEVEL=0 ENV OUT_DIR=/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug/build/ring-74dfb65fdc90ab2c/out ENV PATH=/Users/admin/.cargo/bin:/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/bin:/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/normal/bin:/Users/admin/.cargo/bin:/Users/admin/venv/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin ENV PEP517_BUILD_BACKEND=setuptools.build_meta ENV PIP_REQ_TRACKER=/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-req-tracker-179wcdnq ENV PLAT=macosx-10.14-arm64 ENV PROFILE=debug ENV PS1=(venv) %n@%m %1~ %# ENV PWD=/Users/admin ENV PYTHONNOUSERSITE=1 ENV PYTHONPATH=/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/site ENV RUSTC=rustc ENV RUSTDOC=rustdoc ENV RUSTUP_HOME=/Users/admin/.rustup ENV RUSTUP_TOOLCHAIN=stable-aarch64-apple-darwin ENV RUST_RECURSION_COUNT=1 ENV SHELL=/bin/zsh ENV SHLVL=1 ENV SSH_AUTH_SOCK=/private/tmp/com.apple.launchd.WMzJWaFIA5/Listeners ENV TARGET=aarch64-apple-darwin ENV TERM=xterm-256color ENV TERM_PROGRAM=Apple_Terminal ENV TERM_PROGRAM_VERSION=443 ENV TERM_SESSION_ID=B8FDBA53-2516-4197-B600-445E738CFDEF ENV TMPDIR=/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/ ENV USER=admin ENV VIRTUAL_ENV=/Users/admin/venv ENV XPC_FLAGS=0x0 ENV XPC_SERVICE_NAME=0 ENV _=/Users/admin/venv/bin/pip ENV _PIP_STANDALONE_CERT=/Users/admin/venv/lib/python3.8/site-packages/pip/_vendor/certifi/cacert.pem ENV __CFBundleIdentifier=com.apple.Terminal ENV __CF_USER_TEXT_ENCODING=0x1F7:0x0:0x0 running "cc" "-O0" "-ffunction-sections" "-fdata-sections" "-fPIC" "-g" "-fno-omit-frame-pointer" "-arch" "arm64" "-I" "include" "-Wall" "-Wextra" "-pedantic" "-pedantic-errors" "-Wall" "-Wextra" "-Wcast-align" "-Wcast-qual" "-Wconversion" "-Wenum-compare" "-Wfloat-equal" "-Wformat=2" "-Winline" "-Winvalid-pch" "-Wmissing-field-initializers" "-Wmissing-include-dirs" "-Wredundant-decls" "-Wshadow" "-Wsign-compare" "-Wsign-conversion" "-Wundef" "-Wuninitialized" "-Wwrite-strings" "-fno-strict-aliasing" "-fvisibility=hidden" "-fstack-protector" "-gfull" "-DNDEBUG" "-c" "-o/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-install-ll07r0xs/maturin_0e5f2f37c0de4d1c8658d72a11487de2/target/debug/build/ring-74dfb65fdc90ab2c/out/aesv8-armx-linux64.o" "/Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S" /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:18:17: error: unexpected token in '.section' directive .section .rodata ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:28:1: error: unknown directive .hidden GFp_aes_hw_set_encrypt_key ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:29:1: error: unknown directive .type GFp_aes_hw_set_encrypt_key,%function ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:161:1: error: unknown directive .size GFp_aes_hw_set_encrypt_key,.-GFp_aes_hw_set_encrypt_key ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:163:1: error: unknown directive .hidden GFp_aes_hw_encrypt ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:164:1: error: unknown directive .type GFp_aes_hw_encrypt,%function ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:191:1: error: unknown directive .size GFp_aes_hw_encrypt,.-GFp_aes_hw_encrypt ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:193:1: error: unknown directive .hidden GFp_aes_hw_decrypt ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:194:1: error: unknown directive .type GFp_aes_hw_decrypt,%function ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:221:1: error: unknown directive .size GFp_aes_hw_decrypt,.-GFp_aes_hw_decrypt ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:223:1: error: unknown directive .hidden GFp_aes_hw_ctr32_encrypt_blocks ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:224:1: error: unknown directive .type GFp_aes_hw_ctr32_encrypt_blocks,%function ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:403:1: error: unknown directive .size GFp_aes_hw_ctr32_encrypt_blocks,.-GFp_aes_hw_ctr32_encrypt_blocks ^ /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/pregenerated/aesv8-armx-linux64.S:407:19: error: unexpected token in '.section' directive .section .note.GNU-stack,"",%progbits ^ thread 'main' panicked at 'execution failed', /Users/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/ring-0.16.15/build.rs:664:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace warning: build failed, waiting for other jobs to finish... error: build failed Traceback (most recent call last): File "/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/tmpwhciv39r", line 363, in <module> main() File "/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/tmpwhciv39r", line 345, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/tmpwhciv39r", line 261, in build_wheel return _build_backend().build_wheel(wheel_directory, config_settings, File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 208, in build_wheel return self._build_with_temp_dir(['bdist_wheel'], '.whl', File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 194, in _build_with_temp_dir self.run_setup() File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 142, in run_setup exec(compile(code, __file__, 'exec'), locals()) File "setup.py", line 81, in <module> setup( File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/setuptools/__init__.py", line 145, in setup return distutils.core.setup(**attrs) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/core.py", line 148, in setup dist.run_commands() File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/dist.py", line 966, in run_commands self.run_command(cmd) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/dist.py", line 985, in run_command cmd_obj.run() File "/private/var/folders/jl/9g_fqrr101g_s9y5jjns3rvc0000gq/T/pip-build-env-w4ta8kth/overlay/lib/python3.8/site-packages/wheel/bdist_wheel.py", line 228, in run self.run_command('install') File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/cmd.py", line 313, in run_command self.distribution.run_command(command) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/distutils/dist.py", line 985, in run_command cmd_obj.run() File "setup.py", line 58, in run subprocess.check_call( File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['cargo', 'rustc', '--bin', 'maturin', '--', '-C', 'link-arg=-s']' returned non-zero exit status 101. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for maturin Failed to build maturin ERROR: Could not build wheels for maturin, which is required to install pyproject.toml-based projects [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. I have tried looking around and stumbled upon the following posts: Does Poetry install --no-dev need Rust to be installed? requirement.txt installation is failing while building "orjson" on 64 bit python interpreter on 64 bit Mac OSX However, it did not really help. Any help would be highly appreciated.
[ "I don't know if that helps you but I had a similar Problem with 3.6.2, so I ran pip install orjson and it installed orjson==3.8.1 without a Problem.\n" ]
[ 0 ]
[]
[]
[ "apple_m1", "macos", "orjson", "python", "rust" ]
stackoverflow_0071349322_apple_m1_macos_orjson_python_rust.txt
Q: Unable to convert datetime string with timezone to datetime in UTC using datetime python module I am having issues converting a datetime string of this format "%d %b %Y %X %Z" to "%Y-%m-%dT%X%z". The timezone information is stripped out. For example: >> import datetime >> datetime_string_raw = "18 Nov 2022 08:57:04 EST" >> datetime_utc = datetime.datetime.strptime(datetime_string_raw, "%d %b %Y %X %Z").strftime("%Y-%m-%dT%X%z") >> print(datetime_utc) 2022-11-18T08:57:04 How can I get it to print the UTC offset? Why doesn't the %Z and %z have any effect? Thanks! A: Using dateutil's parser and a definition which abbreviated names should resemble which time zone: import datetime import dateutil # pip install python-dateutil tzinfos = {"EST": dateutil.tz.gettz("America/New_York"), "EDT": dateutil.tz.gettz("America/New_York")} datetime_string_raw = "18 Nov 2022 08:57:04 EST" datetime_ny = dateutil.parser.parse(datetime_string_raw, tzinfos=tzinfos) print(datetime_ny) # 2022-11-18 08:57:04-05:00 datetime_utc = datetime_ny.astimezone(datetime.timezone.utc) print(datetime_utc) # 2022-11-18 13:57:04+00:00 You can do basically the same using only the standard library, but it requires some pre-processing of the date/time string. Ex: import datetime import zoneinfo # Python >= 3.9 def parse_dt_with_tz(dt_string: str, fmt: str, tzinfos: dict) -> datetime.datetime: """Parse date/time string with abbreviated time zone name to aware datetime.""" parts = dt_string.split(" ") tz = tzinfos.get(parts[-1]) # last element is the tz name if not tz: raise ValueError(f"no entry found for {parts[-1]} in tzinfos") return datetime.datetime.strptime(" ".join(parts[:-1]), fmt).replace(tzinfo=tz) # usage tzinfos = {"EST": zoneinfo.ZoneInfo("America/New_York"), "EDT": zoneinfo.ZoneInfo("America/New_York")} s = "18 Nov 2022 08:57:04 EST" dt = parse_dt_with_tz(s, "%d %b %Y %H:%M:%S", tzinfos) print(dt, repr(dt)) # 2022-11-18 08:57:04-05:00 datetime.datetime(2022, 11, 18, 8, 57, 4, tzinfo=zoneinfo.ZoneInfo(key='America/New_York'))
Unable to convert datetime string with timezone to datetime in UTC using datetime python module
I am having issues converting a datetime string of this format "%d %b %Y %X %Z" to "%Y-%m-%dT%X%z". The timezone information is stripped out. For example: >> import datetime >> datetime_string_raw = "18 Nov 2022 08:57:04 EST" >> datetime_utc = datetime.datetime.strptime(datetime_string_raw, "%d %b %Y %X %Z").strftime("%Y-%m-%dT%X%z") >> print(datetime_utc) 2022-11-18T08:57:04 How can I get it to print the UTC offset? Why doesn't the %Z and %z have any effect? Thanks!
[ "Using dateutil's parser and a definition which abbreviated names should resemble which time zone:\nimport datetime\nimport dateutil # pip install python-dateutil\n\ntzinfos = {\"EST\": dateutil.tz.gettz(\"America/New_York\"),\n \"EDT\": dateutil.tz.gettz(\"America/New_York\")}\n\ndatetime_string_raw = \"18 Nov 2022 08:57:04 EST\" \n\ndatetime_ny = dateutil.parser.parse(datetime_string_raw, tzinfos=tzinfos)\nprint(datetime_ny)\n# 2022-11-18 08:57:04-05:00\n\ndatetime_utc = datetime_ny.astimezone(datetime.timezone.utc)\nprint(datetime_utc)\n# 2022-11-18 13:57:04+00:00\n\n\nYou can do basically the same using only the standard library, but it requires some pre-processing of the date/time string. Ex:\nimport datetime\nimport zoneinfo # Python >= 3.9\n\ndef parse_dt_with_tz(dt_string: str, fmt: str, tzinfos: dict) -> datetime.datetime:\n \"\"\"Parse date/time string with abbreviated time zone name to aware datetime.\"\"\"\n parts = dt_string.split(\" \")\n tz = tzinfos.get(parts[-1]) # last element is the tz name\n if not tz:\n raise ValueError(f\"no entry found for {parts[-1]} in tzinfos\")\n return datetime.datetime.strptime(\" \".join(parts[:-1]), fmt).replace(tzinfo=tz)\n\n# usage\ntzinfos = {\"EST\": zoneinfo.ZoneInfo(\"America/New_York\"),\n \"EDT\": zoneinfo.ZoneInfo(\"America/New_York\")}\n\ns = \"18 Nov 2022 08:57:04 EST\"\ndt = parse_dt_with_tz(s, \"%d %b %Y %H:%M:%S\", tzinfos)\nprint(dt, repr(dt))\n# 2022-11-18 08:57:04-05:00 datetime.datetime(2022, 11, 18, 8, 57, 4, tzinfo=zoneinfo.ZoneInfo(key='America/New_York'))\n\n" ]
[ 1 ]
[]
[]
[ "datetime", "python", "python_3.x", "python_datetime", "timezone" ]
stackoverflow_0074551570_datetime_python_python_3.x_python_datetime_timezone.txt
Q: What matplotlib rc parameter controls legend title size? Is there an rc parameter to control the size of a legend title in matplotlib? It's possible to set with ax.legend().set_title(prop={"size": title_size}) But it does not seem to correspond to the rc parameters legend.fontsize or axes.titlesize. What parameter controls the size of this element? A: Inspecting the source code and trying around a little bit it seems to me that there is no such rc parameter. The default font size is used. It is a bit surprising to me - probably it's because legend titles are not used very often. Update 2017/18/09: Still not possible. If anybody of you would need it, please open an issue for this on github. Github Link A: rcParams["legend.title_fontsize"] will be available in matplotlib v3.0. A: This should work: plt.rc('font', size=20) in Matplotlib 3.3.0. A: params = { 'legend.title_fontsize' : 'x-large' } pylab.rcParams.update(params) A: plt.rc('legend',fontsize=25, title_fontsize= 25)
What matplotlib rc parameter controls legend title size?
Is there an rc parameter to control the size of a legend title in matplotlib? It's possible to set with ax.legend().set_title(prop={"size": title_size}) But it does not seem to correspond to the rc parameters legend.fontsize or axes.titlesize. What parameter controls the size of this element?
[ "Inspecting the source code and trying around a little bit it seems to me that there is no such rc parameter. The default font size is used.\nIt is a bit surprising to me - probably it's because legend titles are not used very often.\nUpdate 2017/18/09: Still not possible. If anybody of you would need it, please open an issue for this on github. Github Link\n", "rcParams[\"legend.title_fontsize\"] will be available in matplotlib v3.0.\n", "This should work:\nplt.rc('font', size=20) \n\nin Matplotlib 3.3.0.\n", "params = {\n 'legend.title_fontsize' : 'x-large'\n }\npylab.rcParams.update(params)\n\n", "plt.rc('legend',fontsize=25, title_fontsize= 25)\n" ]
[ 3, 3, 0, 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0021130576_matplotlib_python.txt
Q: Is it possible to get GridSpec from Figure before adding Axes? Consider the following code from matplotlib import pyplot as plt fig = plt.figure() grid = fig.add_gridspec(2,2) We have that grid is a GridSpec instance. Consider now the following code from matplotlib import pyplot as plt fig = plt.figure() fig.add_gridspec(2,2) The only way to retrieve the GridSpec associated to fig that I found is either to use the first code snippet I posted or to add a Subplot first and then get the GridSpec from such a Subplot: axes = fig.add_subplot(grid[0]) grid = axes.get_gridspec() But what if I want to get the GridSpec from fig directly and before adding any Subplot? Is it possible? A: This is the code defining the add_gridspec method: def add_gridspec(self, nrows=1, ncols=1, **kwargs): """ ... """ _ = kwargs.pop('figure', None) # pop in case user has added this... gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs) self._gridspecs.append(gs) return gs Figure._gridspecs is a list of gridspecs, e.g., >>> import matplotlib.pyplot as plt ... fig = plt.figure() ... fig.add_gridspec(2, 2) ... fig.add_gridspec(4, 4) ... fig._gridspecs [GridSpec(2, 2), GridSpec(4, 4)] >>>
Is it possible to get GridSpec from Figure before adding Axes?
Consider the following code from matplotlib import pyplot as plt fig = plt.figure() grid = fig.add_gridspec(2,2) We have that grid is a GridSpec instance. Consider now the following code from matplotlib import pyplot as plt fig = plt.figure() fig.add_gridspec(2,2) The only way to retrieve the GridSpec associated to fig that I found is either to use the first code snippet I posted or to add a Subplot first and then get the GridSpec from such a Subplot: axes = fig.add_subplot(grid[0]) grid = axes.get_gridspec() But what if I want to get the GridSpec from fig directly and before adding any Subplot? Is it possible?
[ "This is the code defining the add_gridspec method:\n def add_gridspec(self, nrows=1, ncols=1, **kwargs):\n \"\"\"\n ...\n \"\"\"\n _ = kwargs.pop('figure', None) # pop in case user has added this...\n gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs)\n self._gridspecs.append(gs)\n return gs\n\nFigure._gridspecs is a list of gridspecs, e.g.,\n>>> import matplotlib.pyplot as plt\n... fig = plt.figure()\n... fig.add_gridspec(2, 2)\n... fig.add_gridspec(4, 4)\n... fig._gridspecs\n[GridSpec(2, 2), GridSpec(4, 4)]\n>>>\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074550664_matplotlib_python.txt
Q: DAG not visible in Web-UI I am new to Airflow. I am following a tutorial and written following code. from airflow import DAG from airflow.operators.python_operator import PythonOperator from datetime import datetime, timedelta from models.correctness_prediction import CorrectnessPrediction default_args = { 'owner': 'abc', 'depends_on_past': False, 'start_date': datetime.now(), 'email': ['abc@xyz.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5) } def correctness_prediction(arg): CorrectnessPrediction.train() dag = DAG('daily_processing', default_args=default_args) task_1 = PythonOperator( task_id='print_the_context', provide_context=True, python_callable=correctness_prediction, dag=dag) On running the script, it doesn't show any errors but when I check for dags in Web-UI it doesn't show under Menu->DAGs But I can see the scheduled job under Menu->Browse->Jobs I also cannot see anything in $AIRFLOW_HOME/dags. Is it supposed to be like this only? Can someone explain why? A: Run airflow list_dags to check, whether the dag file is located correctly. For some reason, I didn't see my dag in the browser UI before I executed this. Must be issue with browser cache or something. If that doesn't work, you should just restart the webserver with airflow webserver -p 8080 -D A: I have the same issue. To resolve I need to run scheduler airflow scheduler Without this command, I don't see my new DAGs BTW: the UI show me warning related to that problem: The scheduler does not appear to be running. Last heartbeat was received 9 seconds ago. The DAGs list may not update, and new tasks will not be scheduled. A: We need to clarify several things: By no means you need to run the DAG file yourself (unless you're testing it for syntax errors). This is the job of Scheduler/Executor. For DAG file to be visible by Scheduler (and consequently, Webserver), you need to add it to dags_folder (specified in airflow.cfg. By default it's $AIRFLOW_HOME/dags subfolder). Airflow Scheduler checks dags_folder for new DAG files every 5 minutes by default (governed by dag_dir_list_interval in airflow.cfg). So if you just added a new file, you have two options: Restart Scheduler Wait until current Scheduler process picks up new DAGs. A: The ScheduleJob that you see on the jobs page is an entry for the Scheduler. Thats not the dag being scheduled. Its weird that your $AIRFLOW_HOME/dags is empty. All dags must live within the $AIRFLOW_HOME/dags directory (specifically in the dags directory configured in your airflow.cfg file). Looks like you are not storing the actual dag in the right directory (the dags directory). Alternatively, sometimes you also need to restart the webserver for the dag to show up (though that doesn't seem to be the issue here). A: Check the dags_folder variable in airflow.cfg. If you have a virtual environment then run the command export AIRFLOW_HOME=$(pwd) from the main project directory. Note that running export AIRFLOW_HOME=$(pwd) expects your dags to be in a dags subdirectory in the project directory. A: I had the same issue. I had put the downloaded Airflow twice, once without sudo and once with sudo. I was using with the sudo version, where the directories where under my user path. I simply ran the airflow command: export AIRFLOW_HOME=~/airflow A: In my case, the DAG was exactly one of the default ones that I copy-pasted to check the correct volume mappings throughout the docker-compose installation. It turns out that while the web UI shows no errors, the command line airflow dag list return with the error Error: Failed to load all files. For details, run airflow dags list-import-errors. Which is the key to the solution: the DAG was not added since it was a duplicate of an already loaded dag A: Check the Paused dags. Your DAG might have ended there. If you are sure that you have added .py file correctly then manually type the url of the dag using dag_id. For e.g. http://AIRFLOW_URL/graph?dag_id=dag_id. Then you can see if Airflow has accepted your dag or not. A: I experienced the same issue. In my case, the permissions of the new DAG were incorrect. Run ls -l to see the permissions of the new DAG. For me, the owner was listed as myself, instead of default airflow user (which in my case should have been root). Once I changed permissions (chown root:root <file_name>), the file showed up in the Web UI immediately. A: listing the dag or restarting the webserver didn't help me. but resetting db did. airflow db reset A: After reading previous answers, for me this worked: Restart the webserver, e.g. pkill -f "airflow webserver" and then airflow webserver -D. Also restart the scheduler with pkill -f "airflow scheduler" and airflow scheduler -D. Besides that, make sure that your DAG is contained in the DAGS folder specified in airflow.cfg, located in $AIRFLOW_HOME. This worked for me, after I could see the DAG with airflow dags list, but not in the UI, and also not trigger it. A: I just ran into the same problem. Airflow suggested me to use the following command to evaluate my dag: Error: Failed to load all files. For details, run `airflow dags list-import-errors` It was just a comma in my way :).
DAG not visible in Web-UI
I am new to Airflow. I am following a tutorial and written following code. from airflow import DAG from airflow.operators.python_operator import PythonOperator from datetime import datetime, timedelta from models.correctness_prediction import CorrectnessPrediction default_args = { 'owner': 'abc', 'depends_on_past': False, 'start_date': datetime.now(), 'email': ['abc@xyz.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5) } def correctness_prediction(arg): CorrectnessPrediction.train() dag = DAG('daily_processing', default_args=default_args) task_1 = PythonOperator( task_id='print_the_context', provide_context=True, python_callable=correctness_prediction, dag=dag) On running the script, it doesn't show any errors but when I check for dags in Web-UI it doesn't show under Menu->DAGs But I can see the scheduled job under Menu->Browse->Jobs I also cannot see anything in $AIRFLOW_HOME/dags. Is it supposed to be like this only? Can someone explain why?
[ "Run airflow list_dags\nto check, whether the dag file is located correctly. \nFor some reason, I didn't see my dag in the browser UI before I executed this. Must be issue with browser cache or something.\nIf that doesn't work, you should just restart the webserver with airflow webserver -p 8080 -D\n", "I have the same issue. To resolve I need to run scheduler\nairflow scheduler\n\nWithout this command, I don't see my new DAGs\nBTW: the UI show me warning related to that problem:\n\nThe scheduler does not appear to be running. Last heartbeat was received 9 seconds ago. The DAGs list may not update, and new tasks will not be scheduled.\n\n", "We need to clarify several things:\n\nBy no means you need to run the DAG file yourself (unless you're testing it for syntax errors). This is the job of Scheduler/Executor.\nFor DAG file to be visible by Scheduler (and consequently, Webserver), you need to add it to dags_folder (specified in airflow.cfg. By default it's $AIRFLOW_HOME/dags subfolder).\n\nAirflow Scheduler checks dags_folder for new DAG files every 5 minutes by default (governed by dag_dir_list_interval in airflow.cfg). So if you just added a new file, you have two options:\n\nRestart Scheduler\nWait until current Scheduler process picks up new DAGs.\n\n", "The ScheduleJob that you see on the jobs page is an entry for the Scheduler. Thats not the dag being scheduled. \nIts weird that your $AIRFLOW_HOME/dags is empty. All dags must live within the $AIRFLOW_HOME/dags directory (specifically in the dags directory configured in your airflow.cfg file). Looks like you are not storing the actual dag in the right directory (the dags directory).\nAlternatively, sometimes you also need to restart the webserver for the dag to show up (though that doesn't seem to be the issue here).\n", "Check the dags_folder variable in airflow.cfg. If you have a virtual environment then run the command export AIRFLOW_HOME=$(pwd) from the main project directory. Note that running export AIRFLOW_HOME=$(pwd) expects your dags to be in a dags subdirectory in the project directory. \n", "I had the same issue. I had put the downloaded Airflow twice, once without sudo and once with sudo. I was using with the sudo version, where the directories where under my user path. I simply ran the airflow command:\nexport AIRFLOW_HOME=~/airflow\n", "In my case, the DAG was exactly one of the default ones that I copy-pasted to check the correct volume mappings throughout the docker-compose installation.\nIt turns out that while the web UI shows no errors, the command line airflow dag list return with the error\nError: Failed to load all files. For details, run airflow dags list-import-errors.\nWhich is the key to the solution:\n\nthe DAG was not added since it was a duplicate of an already loaded dag\n\n", "Check the Paused dags. Your DAG might have ended there. If you are sure that you have added .py file correctly then manually type the url of the dag using dag_id. For e.g. http://AIRFLOW_URL/graph?dag_id=dag_id. Then you can see if Airflow has accepted your dag or not.\n", "I experienced the same issue. In my case, the permissions of the new DAG were incorrect.\nRun ls -l to see the permissions of the new DAG. For me, the owner was listed as myself, instead of default airflow user (which in my case should have been root).\nOnce I changed permissions (chown root:root <file_name>), the file showed up in the Web UI immediately.\n", "listing the dag or restarting the webserver didn't help me. but resetting db did.\nairflow db reset\n\n", "After reading previous answers, for me this worked:\n\nRestart the webserver, e.g. pkill -f \"airflow webserver\" and then airflow webserver -D.\nAlso restart the scheduler with pkill -f \"airflow scheduler\" and airflow scheduler -D.\n\nBesides that, make sure that your DAG is contained in the DAGS folder specified in airflow.cfg, located in $AIRFLOW_HOME.\nThis worked for me, after I could see the DAG with airflow dags list, but not in the UI, and also not trigger it.\n", "I just ran into the same problem. Airflow suggested me to use the following command to evaluate my dag:\nError: Failed to load all files. For details, run `airflow dags list-import-errors`\n\nIt was just a comma in my way :).\n" ]
[ 26, 23, 20, 12, 7, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "airflow", "directed_acyclic_graphs", "python", "python_3.x" ]
stackoverflow_0038992997_airflow_directed_acyclic_graphs_python_python_3.x.txt
Q: Not able to copy file in docker file which is downloaded in github actions I can able to see the .pkl which is downloaded using actions/download-artifact@v3 action in work directory along with Dockerfile as shown below, When I try to COPY file inside Dockefile, I get a file not found error. How to copy the files inside docker image that are downloaded(through github actions) before building docker image? Here is doc from github on docker support, but I didn't get exactly how to solve my issue. Any help would be really appreciated!! Dockerfile: name: Docker - GitHub workflow env: CONTAINER_NAME: xxx-xxx on: workflow_dispatch: push: branches: ["main"] pull_request: branches: ["main"] permissions: id-token: write contents: read jobs: load-artifacts: runs-on: ubuntu-latest environment: dev env: output_path: ./xxx/xxx_model.pkl steps: - uses: actions/checkout@v3 - name: Download PPE model file run: | az storage blob download --container-name ppe-container --name xxx_model.pkl -f "${{ env.output_path }}" - name: View output - after run: | ls -lhR - name: 'Upload Artifact' uses: actions/upload-artifact@v3 with: name: ppe_model path: ${{ env.output_path }} build: needs: load-artifacts runs-on: ubuntu-latest env: ACR: xxxx steps: - uses: actions/checkout@v3 - uses: actions/download-artifact@v3 id: download with: name: ppe_model # path: ${{ env.model_path }} - name: Echo download path run: echo ${{steps.download.outputs.download-path}} - name: View directory files run: | ls -lhR -a - name: Build container image uses: docker/build-push-action@v2 with: push: false tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }} file: ./Dockerfile A: In your workflow file, you're not specifying the context: - name: Build container image uses: docker/build-push-action@v2 with: push: false tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }} file: ./Dockerfile By default, that means that docker/build-push-action choose a git context. That will re-clone your repository... without your model. The fix, then, is to specify a path context, like this: - name: Build container image uses: docker/build-push-action@v2 with: context: . push: false tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }} file: ./Dockerfile
Not able to copy file in docker file which is downloaded in github actions
I can able to see the .pkl which is downloaded using actions/download-artifact@v3 action in work directory along with Dockerfile as shown below, When I try to COPY file inside Dockefile, I get a file not found error. How to copy the files inside docker image that are downloaded(through github actions) before building docker image? Here is doc from github on docker support, but I didn't get exactly how to solve my issue. Any help would be really appreciated!! Dockerfile: name: Docker - GitHub workflow env: CONTAINER_NAME: xxx-xxx on: workflow_dispatch: push: branches: ["main"] pull_request: branches: ["main"] permissions: id-token: write contents: read jobs: load-artifacts: runs-on: ubuntu-latest environment: dev env: output_path: ./xxx/xxx_model.pkl steps: - uses: actions/checkout@v3 - name: Download PPE model file run: | az storage blob download --container-name ppe-container --name xxx_model.pkl -f "${{ env.output_path }}" - name: View output - after run: | ls -lhR - name: 'Upload Artifact' uses: actions/upload-artifact@v3 with: name: ppe_model path: ${{ env.output_path }} build: needs: load-artifacts runs-on: ubuntu-latest env: ACR: xxxx steps: - uses: actions/checkout@v3 - uses: actions/download-artifact@v3 id: download with: name: ppe_model # path: ${{ env.model_path }} - name: Echo download path run: echo ${{steps.download.outputs.download-path}} - name: View directory files run: | ls -lhR -a - name: Build container image uses: docker/build-push-action@v2 with: push: false tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }} file: ./Dockerfile
[ "In your workflow file, you're not specifying the context:\n - name: Build container image\n uses: docker/build-push-action@v2\n with:\n push: false\n tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }}\n file: ./Dockerfile\n\nBy default, that means that docker/build-push-action choose a git context. That will re-clone your repository... without your model.\nThe fix, then, is to specify a path context, like this:\n - name: Build container image\n uses: docker/build-push-action@v2\n with:\n context: .\n push: false\n tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }}\n file: ./Dockerfile\n\n" ]
[ 2 ]
[]
[]
[ "docker", "fastapi", "github_actions", "python" ]
stackoverflow_0074551520_docker_fastapi_github_actions_python.txt
Q: change after purchase not giving the right breakdown def main(): money1 = input("Purchase price: ") money2 = input("Paid amount of money: ") price = int(money1) paid = int(money2) change = paid - price ten_euro = change // 10 five_euro = change % 10 // 5 two_euro = change % 5 // 2 one_euro = (change % 2) if price < paid: print("Offer change:") if change >= 10: print(ten_euro, "ten-euro notes") if (change % 10) >= 5: print(five_euro, "five-euro notes") if (change % 5) >= 2: print(two_euro, "two-euro coins") if (change % 2) >= 2: print(one_euro, "one-euro coins") else: print("No change") if __name__ == "__main__": main() Create a program that asks how much purchases cost and the amount of paid money and then prints the amount of change. Simplify the program by only allowing the use of sums of 1, 2, 5, and 10 euros. Ensure that the total price is always in full euros. My problem is with the one-euro coins, as it is not showing as expected. Examples of how the program should work: Purchase price: 12 Paid amount of money: 50 Offer change: 3 ten-euro notes 1 five-euro notes 1 two-euro coins 1 one-euro coins Purchase price: 9 Paid amount of money: 20 Offer change: 1 ten-euro notes 1 one-euro coins A: This line is incorrect: if (change % 2) >= 2. This can never be true. You probably meant: if (change % 2) >= 1. Apart from that I think you could simplify the program by decrementing the change variable as you calculate the different denominations. You can use the builtin method divmod for this. You can also check if the ten_euro, five_euro, etc are greater than zero in the printout rather than re-calculating their amount. ten_euro, change = divmod(change, 10) five_euro, change = divmod(change, 5) two_euro, change = divmod(change, 2) one_euro = change if price < paid: print("Offer change:") if ten_euro: print(ten_euro, "ten-euro notes") if five_euro: print(five_euro, "five-euro notes") if two_euro: print(two_euro, "two-euro coins") if one_euro: print(one_euro, "one-euro coins") else: print("No change") A: We got to calculate # one_euro count better and you are there. Here is a working solution, included a check on the total change aswell. def main(): money1 = input("Purchase price: ") money2 = input("Paid amount of money: ") price = int(money1) paid = int(money2) change = paid - price ten_euro_count = change // 10 five_euro_count = change % 10 // 5 two_euro_count = change % 5 // 2 sum_of_change = 0 if price < paid: print("Offer change:") if change >= 10: print(ten_euro_count, "ten-euro notes") sum_of_change = sum_of_change + ten_euro_count * 10 if (change % 10) >= 5: print(five_euro_count, "five-euro notes") sum_of_change = sum_of_change + five_euro_count * 5 if (change % 5) >= 2: print(two_euro_count, "two-euro coins") sum_of_change = sum_of_change + two_euro_count * 2 if change - sum_of_change != 0: one_euro_count = 1 print(one_euro_count, "one-euro coins") else: print("No change") if __name__ == "__main__": main() A: Faulty decision structure; if (change % 2) >= 2 Code change; def main(): money1 = int(input("Purchase price: ")) money2 = int(input("Paid amount of money: ")) change = money2 - money1 ten_euro = change // 10 five_euro = (change % 10) // 5 two_euro = (change % 5) // 2 total = 0 if money1 < money2: print("Offer change:") if change >= 10: print(ten_euro, "ten-euro notes") total += ten_euro*10 if (change % 10) >= 5: print(five_euro, "five-euro notes") total += five_euro*5 if (change % 5) >= 2: print(two_euro, "two-euro coins") total += two_euro*2 if change - total > 0: print(change-total, "one-euro coins") else: print("No change") if __name__ == "__main__": main()
change after purchase not giving the right breakdown
def main(): money1 = input("Purchase price: ") money2 = input("Paid amount of money: ") price = int(money1) paid = int(money2) change = paid - price ten_euro = change // 10 five_euro = change % 10 // 5 two_euro = change % 5 // 2 one_euro = (change % 2) if price < paid: print("Offer change:") if change >= 10: print(ten_euro, "ten-euro notes") if (change % 10) >= 5: print(five_euro, "five-euro notes") if (change % 5) >= 2: print(two_euro, "two-euro coins") if (change % 2) >= 2: print(one_euro, "one-euro coins") else: print("No change") if __name__ == "__main__": main() Create a program that asks how much purchases cost and the amount of paid money and then prints the amount of change. Simplify the program by only allowing the use of sums of 1, 2, 5, and 10 euros. Ensure that the total price is always in full euros. My problem is with the one-euro coins, as it is not showing as expected. Examples of how the program should work: Purchase price: 12 Paid amount of money: 50 Offer change: 3 ten-euro notes 1 five-euro notes 1 two-euro coins 1 one-euro coins Purchase price: 9 Paid amount of money: 20 Offer change: 1 ten-euro notes 1 one-euro coins
[ "This line is incorrect: if (change % 2) >= 2.\nThis can never be true. You probably meant: if (change % 2) >= 1.\nApart from that I think you could simplify the program by decrementing the change variable as you calculate the different denominations. You can use the builtin method divmod for this.\nYou can also check if the ten_euro, five_euro, etc are greater than zero in the printout rather than re-calculating their amount.\nten_euro, change = divmod(change, 10)\nfive_euro, change = divmod(change, 5)\ntwo_euro, change = divmod(change, 2)\none_euro = change\n\nif price < paid:\n print(\"Offer change:\")\n if ten_euro:\n print(ten_euro, \"ten-euro notes\")\n if five_euro:\n print(five_euro, \"five-euro notes\")\n if two_euro:\n print(two_euro, \"two-euro coins\")\n if one_euro:\n print(one_euro, \"one-euro coins\")\nelse:\n print(\"No change\")\n\n", "We got to calculate # one_euro count better and you are there.\nHere is a working solution, included a check on the total change aswell.\ndef main():\n money1 = input(\"Purchase price: \")\n money2 = input(\"Paid amount of money: \")\n price = int(money1)\n paid = int(money2)\n change = paid - price\n\n ten_euro_count = change // 10\n five_euro_count = change % 10 // 5\n two_euro_count = change % 5 // 2\n\n sum_of_change = 0\n\n if price < paid:\n print(\"Offer change:\")\n if change >= 10:\n print(ten_euro_count, \"ten-euro notes\")\n sum_of_change = sum_of_change + ten_euro_count * 10\n if (change % 10) >= 5:\n print(five_euro_count, \"five-euro notes\")\n sum_of_change = sum_of_change + five_euro_count * 5\n if (change % 5) >= 2:\n print(two_euro_count, \"two-euro coins\")\n sum_of_change = sum_of_change + two_euro_count * 2\n if change - sum_of_change != 0:\n one_euro_count = 1\n print(one_euro_count, \"one-euro coins\")\n else:\n print(\"No change\")\n\nif __name__ == \"__main__\":\n main()\n\n", "Faulty decision structure;\nif (change % 2) >= 2\n\nCode change;\ndef main():\n money1 = int(input(\"Purchase price: \"))\n money2 = int(input(\"Paid amount of money: \"))\n change = money2 - money1\n\n ten_euro = change // 10\n five_euro = (change % 10) // 5\n two_euro = (change % 5) // 2\n total = 0\n\n if money1 < money2:\n print(\"Offer change:\")\n if change >= 10:\n print(ten_euro, \"ten-euro notes\")\n total += ten_euro*10\n if (change % 10) >= 5:\n print(five_euro, \"five-euro notes\")\n total += five_euro*5\n if (change % 5) >= 2:\n print(two_euro, \"two-euro coins\")\n total += two_euro*2\n if change - total > 0:\n print(change-total, \"one-euro coins\")\n else:\n print(\"No change\")\n\nif __name__ == \"__main__\":\n main()\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074551585_python.txt
Q: "detail": "Method \"GET\" not allowed" in django-rest-framework (for permission_classes = IsAuthenticated and more where it allowed GET method) Help please! I have installed for view class permission_class which allow GET-requests, but when i send GET-request i get messege: GET method is not allowed i have views.py file: class WomenAPIList(generics.ListCreateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAuthenticatedOrReadOnly, ) class WomenAPIUpdate(generics.UpdateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAuthenticated, ) # authentication_classes = (TokenAuthentication, ) class WomenAPIDestroy(generics.RetrieveDestroyAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAdminOrReadOnly, ) In views.py file i use basic integrated IsAuthenticated class for WomenAPIUpdate: class WomenAPIUpdate(generics.UpdateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAuthenticated, ) # authentication_classes = (TokenAuthentication, ) My urls.py file looks like: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/drf-auth/', include('rest_framework.urls')), path('api/v1/women/', WomenAPIList.as_view()), path('api/v1/women/<int:pk>/', WomenAPIUpdate.as_view()), path('api/v1/womendelete/<int:pk>/', WomenAPIDestroy.as_view()), path('api/v1/auth/', include('djoser.urls')), re_path(r'^auth/', include('djoser.urls.authtoken')), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] And for WomenAPIUpdate class i have installed next url: path('api/v1/women/<int:pk>/', WomenAPIUpdate.as_view()), But when i make GET-request to this url i get messege: "GET method is not allowed" (i get same messege during using Postaman and Browser). Here is my models.py file: class Women(models.Model): title = models.CharField(max_length=255) content = models.TextField(blank=True) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=True) cat_id = models.ForeignKey('Category', on_delete=models.PROTECT, null=True) car_id = models.BooleanField(default=True) user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) def __str__(self): return self.title class Category(models.Model): name = models.CharField(max_length=100, db_index=True) def __str__(self): return self.name I tried create own permission classes where i allowed GET method during using integrated tuple SAFE_METHODS and installed them to WomenAPIUpdate class, but it did'nt work: class IsAdminOrReadOnly(BasePermission): def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return True return bool(request.user and request.user.is_staff) class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.user == request.user SAFE_METHOD tuple: SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') It worrked until i created Authentication settings and instelled them in settings.py file: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } A: You need to apply Both cases like this .... With Browser (Session and Basic Both worked with Browser but at time you can apply only one) (Handle Session) REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', # -------------- OR ------------------------- 'rest_framework.authentication.SessionAuthentication', ] } With Postmen (Handle JWT Token) REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } A: For the view WomenAPIUpdate use are inheriting generics.UpdateAPIView which will only allow PUT or PATCH methods, which means it will only allow you to UPDATE an object, not to FETCH/GET data. If you are trying to use GET method in postman, it will throw error. For getting one object, either inherit from generics.RetrieveAPIView or change this class WomenAPIUpdate(generics.UpdateAPIView): to class WomenAPIUpdate(generics.RetrieveUpdateAPIView):
"detail": "Method \"GET\" not allowed" in django-rest-framework (for permission_classes = IsAuthenticated and more where it allowed GET method)
Help please! I have installed for view class permission_class which allow GET-requests, but when i send GET-request i get messege: GET method is not allowed i have views.py file: class WomenAPIList(generics.ListCreateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAuthenticatedOrReadOnly, ) class WomenAPIUpdate(generics.UpdateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAuthenticated, ) # authentication_classes = (TokenAuthentication, ) class WomenAPIDestroy(generics.RetrieveDestroyAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAdminOrReadOnly, ) In views.py file i use basic integrated IsAuthenticated class for WomenAPIUpdate: class WomenAPIUpdate(generics.UpdateAPIView): queryset = Women.objects.all() serializer_class = WomenSerializer permission_classes = (IsAuthenticated, ) # authentication_classes = (TokenAuthentication, ) My urls.py file looks like: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/drf-auth/', include('rest_framework.urls')), path('api/v1/women/', WomenAPIList.as_view()), path('api/v1/women/<int:pk>/', WomenAPIUpdate.as_view()), path('api/v1/womendelete/<int:pk>/', WomenAPIDestroy.as_view()), path('api/v1/auth/', include('djoser.urls')), re_path(r'^auth/', include('djoser.urls.authtoken')), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] And for WomenAPIUpdate class i have installed next url: path('api/v1/women/<int:pk>/', WomenAPIUpdate.as_view()), But when i make GET-request to this url i get messege: "GET method is not allowed" (i get same messege during using Postaman and Browser). Here is my models.py file: class Women(models.Model): title = models.CharField(max_length=255) content = models.TextField(blank=True) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=True) cat_id = models.ForeignKey('Category', on_delete=models.PROTECT, null=True) car_id = models.BooleanField(default=True) user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) def __str__(self): return self.title class Category(models.Model): name = models.CharField(max_length=100, db_index=True) def __str__(self): return self.name I tried create own permission classes where i allowed GET method during using integrated tuple SAFE_METHODS and installed them to WomenAPIUpdate class, but it did'nt work: class IsAdminOrReadOnly(BasePermission): def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return True return bool(request.user and request.user.is_staff) class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.user == request.user SAFE_METHOD tuple: SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') It worrked until i created Authentication settings and instelled them in settings.py file: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] }
[ "You need to apply Both cases like this ....\nWith Browser (Session and Basic Both worked with Browser but at time you can apply only one) (Handle Session)\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n ],\n\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.AllowAny',\n ],\n\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n \n 'rest_framework.authentication.BasicAuthentication',\n # -------------- OR -------------------------\n 'rest_framework.authentication.SessionAuthentication',\n ]\n}\n\nWith Postmen (Handle JWT Token)\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': [\n 'rest_framework.renderers.JSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n ],\n\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.AllowAny',\n ],\n\n 'DEFAULT_AUTHENTICATION_CLASSES': [\n 'rest_framework_simplejwt.authentication.JWTAuthentication',\n \n ]\n}\n\n", "For the view WomenAPIUpdate use are inheriting generics.UpdateAPIView which will only allow PUT or PATCH methods, which means it will only allow you to UPDATE an object, not to FETCH/GET data.\nIf you are trying to use GET method in postman, it will throw error.\nFor getting one object, either inherit from generics.RetrieveAPIView or\nchange this\nclass WomenAPIUpdate(generics.UpdateAPIView):\nto\nclass WomenAPIUpdate(generics.RetrieveUpdateAPIView):\n" ]
[ 0, 0 ]
[]
[]
[ "django_rest_framework", "get", "permissions", "python" ]
stackoverflow_0074535625_django_rest_framework_get_permissions_python.txt
Q: Counting number of strings in a List with Python I have a list in my hand and I want to create vocabulary from this list. Then, I want to show each word and count the same strings in this list. The sample list as below. new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus'] First, I created a vocabulary with below. vocabulary = [] for i in range (0, len(new_list)): if new_list[i] not in vocabulary: vocabulary.append(new_list[i])` print vocabulary The output of above code is: "count, once, one, this, thus." I want to show the number of each words in the list as below. [count][1], [once][2], [one][2], [this][1], [thus][2]. In order to get above result; I try below code. matris = [] for i in range(0,len(new_list)): temp = [] temp.insert(0,new_list.count(new_list[i])) matris.append(temp) for x in matris: print x Above code only gives the number of words. Can someone advise me how can I print the word name and number of the words together such as in [once][2] format. A: Use a Counter dict to get the word count then just iterate over the .items: from collections import Counter new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus'] cn = Counter(new_list) for k,v in cn.items(): print("{} appears {} time(s)".format(k,v)) If you want that particular output you can wrap the elements in the str.format: for k,v in cn.items(): print("[{}][{}]".format(k,v)) [thus][2] [count][1] [one][2] [once][2] [this][1] To get the output from highest count to lowest use .most_common: cn = Counter(new_list) for k,v in cn.most_common(): print("[{}][{}]".format(k,v)) Output: [once][2] [thus][2] [one][2] [count][1] [this][1] If you want the data alphabetically from lowest to highest and from highest to lowest for the count you need to pass a key -x[1] to sorted to negate the count sorting the count from highest to lowest: for k, v in sorted(cn.items(), key=lambda x: (-x[1],x[0])): print("[{}][{}]".format(k, v)) Output: [once][2] [one][2] [thus][2] [count][1] [this][1] A: new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus'] vocabulary = list(dict.fromkeys(new_list)) print(*vocabulary, sep = "\n") OUTPUT: one thus once count this ####################### matris= ["["+str(item)+"]"+"["+str(new_list.count(item))+"]" for item in new_list] print(*list(dict.fromkeys(matris)), sep = "\n") OUTPUT: [one][2] [thus][2] [once][2] [count][1] [this][1]
Counting number of strings in a List with Python
I have a list in my hand and I want to create vocabulary from this list. Then, I want to show each word and count the same strings in this list. The sample list as below. new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus'] First, I created a vocabulary with below. vocabulary = [] for i in range (0, len(new_list)): if new_list[i] not in vocabulary: vocabulary.append(new_list[i])` print vocabulary The output of above code is: "count, once, one, this, thus." I want to show the number of each words in the list as below. [count][1], [once][2], [one][2], [this][1], [thus][2]. In order to get above result; I try below code. matris = [] for i in range(0,len(new_list)): temp = [] temp.insert(0,new_list.count(new_list[i])) matris.append(temp) for x in matris: print x Above code only gives the number of words. Can someone advise me how can I print the word name and number of the words together such as in [once][2] format.
[ "Use a Counter dict to get the word count then just iterate over the .items:\nfrom collections import Counter\n\nnew_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus']\n\ncn = Counter(new_list)\nfor k,v in cn.items():\n print(\"{} appears {} time(s)\".format(k,v))\n\nIf you want that particular output you can wrap the elements in the str.format:\nfor k,v in cn.items():\n print(\"[{}][{}]\".format(k,v))\n\n[thus][2]\n[count][1]\n[one][2]\n[once][2]\n[this][1]\n\nTo get the output from highest count to lowest use .most_common:\ncn = Counter(new_list)\nfor k,v in cn.most_common():\n print(\"[{}][{}]\".format(k,v))\n\nOutput:\n[once][2]\n[thus][2]\n[one][2]\n[count][1]\n[this][1]\n\nIf you want the data alphabetically from lowest to highest and from highest to lowest for the count you need to pass a key -x[1] to sorted to negate the count sorting the count from highest to lowest:\nfor k, v in sorted(cn.items(), key=lambda x: (-x[1],x[0])):\n print(\"[{}][{}]\".format(k, v))\n\nOutput:\n[once][2]\n[one][2]\n[thus][2]\n[count][1]\n[this][1]\n\n", "new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus']\nvocabulary = list(dict.fromkeys(new_list))\nprint(*vocabulary, sep = \"\\n\")\n\nOUTPUT:\none\nthus\nonce\ncount\nthis\n\n#######################\nmatris= [\"[\"+str(item)+\"]\"+\"[\"+str(new_list.count(item))+\"]\" for item in \nnew_list]\nprint(*list(dict.fromkeys(matris)), sep = \"\\n\")\n\nOUTPUT:\n[one][2]\n[thus][2]\n[once][2]\n[count][1]\n[this][1]\n\n" ]
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0030692655_python.txt
Q: Getting an infinite loop in pandas when creating a CSV I am trying to create a function that receives two separate CSV files, finds differences between them and create a third CSV file which is populated with the rows that fall into a certain category (if the value of CSV A in row #1 is present in any row in CSV B) but this is creating me an infinite loop. It should return about 20-25 rows but it's caught in a loop and creating over 200 million before VSCode gives up and shuts off def valorPivoteo(ftth_osp, pivote, dataLoader): # for a, sig in array_sig.iterrows(): # for b, sig in array_osp.iterrows(): fila = pd.DataFrame({"FTTH": [ftth_osp], "ID": pivote}) dataLoader = pd.concat([dataLoader, fila]) return dataLoader ## Main which calls the previous def for i, sig in array_sig.iterrows(): for j, osp in array_osp.iterrows(): if(etc): etc elif(etc): etc else: buscarIDOSP = buscarID(valor_sig, array_osp) if(buscarIDOSP == False): x = valorReemplazo(ftth_osp, ftth_sig, valor_sig, valor_osp, dataLoader) dataLoader = pd.concat([dataLoader, x], ignore_index=True) break elif(buscarIDOSP == True): y = valorPivoteo(ftth_osp, pivote, dataLoader) dataLoader = pd.concat([dataLoader, y], ignore_index=True) pivote+=1 break Tried condensing the code so it's not so tiresome to read, tried creating an if so it breaks after certain value in i or j is achieved, or putting a break here and there, but to no avail A: Figured it out, in the def I shouldn't be doing a concat between dataLoader and fila. I should just create fila, add them the values and then return it. That just fixes it. So in summary: def valorPivoteo(ftth_osp, valor_osp, pivote, dataLoader): fila = pd.DataFrame({"FTTH": [ftth_osp], "ID": pivote}) return fila Hope this helps someone in the future!
Getting an infinite loop in pandas when creating a CSV
I am trying to create a function that receives two separate CSV files, finds differences between them and create a third CSV file which is populated with the rows that fall into a certain category (if the value of CSV A in row #1 is present in any row in CSV B) but this is creating me an infinite loop. It should return about 20-25 rows but it's caught in a loop and creating over 200 million before VSCode gives up and shuts off def valorPivoteo(ftth_osp, pivote, dataLoader): # for a, sig in array_sig.iterrows(): # for b, sig in array_osp.iterrows(): fila = pd.DataFrame({"FTTH": [ftth_osp], "ID": pivote}) dataLoader = pd.concat([dataLoader, fila]) return dataLoader ## Main which calls the previous def for i, sig in array_sig.iterrows(): for j, osp in array_osp.iterrows(): if(etc): etc elif(etc): etc else: buscarIDOSP = buscarID(valor_sig, array_osp) if(buscarIDOSP == False): x = valorReemplazo(ftth_osp, ftth_sig, valor_sig, valor_osp, dataLoader) dataLoader = pd.concat([dataLoader, x], ignore_index=True) break elif(buscarIDOSP == True): y = valorPivoteo(ftth_osp, pivote, dataLoader) dataLoader = pd.concat([dataLoader, y], ignore_index=True) pivote+=1 break Tried condensing the code so it's not so tiresome to read, tried creating an if so it breaks after certain value in i or j is achieved, or putting a break here and there, but to no avail
[ "Figured it out, in the def I shouldn't be doing a concat between dataLoader and fila. I should just create fila, add them the values and then return it. That just fixes it.\nSo in summary:\ndef valorPivoteo(ftth_osp, valor_osp, pivote, dataLoader):\n fila = pd.DataFrame({\"FTTH\": [ftth_osp], \"ID\": pivote})\n return fila\n\nHope this helps someone in the future!\n" ]
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074549452_csv_dataframe_pandas_python.txt
Q: How to pass generated data from a Auth Middleware to a Blueprint function in Flask 2? (Solved) I have a function foo() defined from a Blueprint and from it I need to be able to read to a variable that is only created a moment before when the Middleware is executed. I have something like this: app.py def create_app(): app = Flask(__name__) with app.app_context(): app.register_blueprint(my_blueprint) app.wsgi_app = MiddlewareExample(app.wsgi_app) return app my_middleware.py from werkzeug.wrappers import Request, Response class MiddlewareExample: def __init__(self, app): self.app = app def __call__(self, environ, start_response): request = Request(environ) headers = request.headers ... result_validation = some_validations(headers) my_data = result_validation['some_result'] if my_data['some_error']: ... # return error response # If the validation is success i'll need `my_data` later on foo() # somehow pass `my_data` to the Blueprint ... return self.app(environ, start_response) my_custom_blueprint.py demo_routes = Blueprint('demo', __name__, url_prefix='/demo') @demo_routes.route('/', methods=['GET']) def foo(): # do something with the previously generated `my_data` variable I could use current_app.config['my_data'] from the blueprint side having used self.app.config from the middleware, but the data I need to pass to the blueprint will be generated from a validation that I need to always apply to almost every route in my app, the content of my_data will be different with each request and using "app.config" might not seem like such a good idea if I will have hundreds of requests. I even tried to pass it somehow through the header but if it is possible I did not discover it :( In some places I saw data being added to environ['my_data'] = 'hello', I didn't figure out how to read environ from the Blueprint, however I think it would be something similar to using app.config. It is possible to do something like this by going through the middleware without using a session or storing the information in database? If there is an answer that can bring me closer to this result that I need, thank you very much! A: If anyone needs to do something similar to what I needed, Here's an example of how I ended up solving it using a decorator. def my_custom_validator(f): @wraps(f) def decorated_function(*args, **kwargs): headers = request.headers result_validation = some_validations(headers) my_data = result_validation['some_result'] return f(*args, **kwargs, my_data=my_data) # <-- from here I can attach it to the blueprint return decorated_function On the blueprint.. demo_routes = Blueprint('demo', __name__, url_prefix='/demo') @demo_routes.route('/', methods=['GET']) @my_custom_validator def foo(my_data): # Now I can manipulate my data from here
How to pass generated data from a Auth Middleware to a Blueprint function in Flask 2? (Solved)
I have a function foo() defined from a Blueprint and from it I need to be able to read to a variable that is only created a moment before when the Middleware is executed. I have something like this: app.py def create_app(): app = Flask(__name__) with app.app_context(): app.register_blueprint(my_blueprint) app.wsgi_app = MiddlewareExample(app.wsgi_app) return app my_middleware.py from werkzeug.wrappers import Request, Response class MiddlewareExample: def __init__(self, app): self.app = app def __call__(self, environ, start_response): request = Request(environ) headers = request.headers ... result_validation = some_validations(headers) my_data = result_validation['some_result'] if my_data['some_error']: ... # return error response # If the validation is success i'll need `my_data` later on foo() # somehow pass `my_data` to the Blueprint ... return self.app(environ, start_response) my_custom_blueprint.py demo_routes = Blueprint('demo', __name__, url_prefix='/demo') @demo_routes.route('/', methods=['GET']) def foo(): # do something with the previously generated `my_data` variable I could use current_app.config['my_data'] from the blueprint side having used self.app.config from the middleware, but the data I need to pass to the blueprint will be generated from a validation that I need to always apply to almost every route in my app, the content of my_data will be different with each request and using "app.config" might not seem like such a good idea if I will have hundreds of requests. I even tried to pass it somehow through the header but if it is possible I did not discover it :( In some places I saw data being added to environ['my_data'] = 'hello', I didn't figure out how to read environ from the Blueprint, however I think it would be something similar to using app.config. It is possible to do something like this by going through the middleware without using a session or storing the information in database? If there is an answer that can bring me closer to this result that I need, thank you very much!
[ "If anyone needs to do something similar to what I needed,\nHere's an example of how I ended up solving it using a decorator.\ndef my_custom_validator(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n headers = request.headers\n\n result_validation = some_validations(headers)\n my_data = result_validation['some_result']\n\n return f(*args, **kwargs, my_data=my_data) # <-- from here I can attach it to the blueprint\n return decorated_function\n\nOn the blueprint..\ndemo_routes = Blueprint('demo', __name__, url_prefix='/demo')\n\n\n@demo_routes.route('/', methods=['GET'])\n@my_custom_validator\ndef foo(my_data):\n # Now I can manipulate my data from here\n\n" ]
[ 1 ]
[]
[]
[ "blueprint", "flask", "middleware", "python" ]
stackoverflow_0074481991_blueprint_flask_middleware_python.txt
Q: Plot multiples values in the same Column graph I need to plot these graphs in the same plot, but i cant put it together, how can i make this? import pandas as pd import matplotlib.pyplot as plt import random import seaborn as sns plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame(dict( year=range(2010,2021), qtd=[int(random.random() * 20) for x in range(2010,2021)], monetary=[int(random.random() * int(random.random() * 10000)) for x in range(2010,2021)]) ) # fig, ax = plt.subplots() df.plot(x="year", y=['qtd',"monetary"], kind='bar', figsize=(3, 3)) df.plot(x="year", y=['monetary','qtd'], kind='bar', figsize=(3, 3)) plt.show() A: See pandas.DataFrame.plot for a description of all parameters. Plot grouped bars and set the y-axis to a log scale because the range of 'monetary' is much larger than 'qtd'. See the logy= parameter. Tested in python 3.11, pandas 1.5.2, matplotlib 3.6.2 These options do not explicitly require importing matplotlib, but matplotlib is imported by pandas, and is the default plotting backend. ax = df.plot(x="year", kind='bar', figsize=(6, 6), logy=True, rot=0) Plot in subplots and do not share the y-axis. Adjust the layout= parameter as needed. See the sharey= and sharex= parameters. ax = df.plot(x="year", kind='bar', subplots=True, layout=(1, 2), figsize=(14, 6), sharey=False, rot=0, legend=False) ax = df.plot(x="year", kind='bar', subplots=True, layout=(2, 1), figsize=(6, 12), sharey=False, sharex=False, rot=0, legend=False)
Plot multiples values in the same Column graph
I need to plot these graphs in the same plot, but i cant put it together, how can i make this? import pandas as pd import matplotlib.pyplot as plt import random import seaborn as sns plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame(dict( year=range(2010,2021), qtd=[int(random.random() * 20) for x in range(2010,2021)], monetary=[int(random.random() * int(random.random() * 10000)) for x in range(2010,2021)]) ) # fig, ax = plt.subplots() df.plot(x="year", y=['qtd',"monetary"], kind='bar', figsize=(3, 3)) df.plot(x="year", y=['monetary','qtd'], kind='bar', figsize=(3, 3)) plt.show()
[ "\nSee pandas.DataFrame.plot for a description of all parameters.\nPlot grouped bars and set the y-axis to a log scale because the range of 'monetary' is much larger than 'qtd'. See the logy= parameter.\nTested in python 3.11, pandas 1.5.2, matplotlib 3.6.2\n\nThese options do not explicitly require importing matplotlib, but matplotlib is imported by pandas, and is the default plotting backend.\n\n\n\nax = df.plot(x=\"year\", kind='bar', figsize=(6, 6), logy=True, rot=0)\n\n\n\nPlot in subplots and do not share the y-axis. Adjust the layout= parameter as needed. See the sharey= and sharex= parameters.\n\nax = df.plot(x=\"year\", kind='bar', subplots=True, layout=(1, 2), figsize=(14, 6), sharey=False, rot=0, legend=False)\n\n\nax = df.plot(x=\"year\", kind='bar', subplots=True, layout=(2, 1), figsize=(6, 12), sharey=False, sharex=False, rot=0, legend=False)\n\n\n" ]
[ 2 ]
[]
[]
[ "bar_chart", "grouped_bar_chart", "pandas", "python" ]
stackoverflow_0074551033_bar_chart_grouped_bar_chart_pandas_python.txt
Q: Python equivalent of Golang's select on channels Go has a select statement that works on channels. From the documentation: The select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready. Is there a Python equivalent of the following code: package main import "fmt" func main() { c1 := make(chan int) c2 := make(chan int) quit := make(chan int) go func() { for i := 0; i < 10; i++ { c1 <- i } quit <- 0 }() go func() { for i := 0; i < 2; i++ { c2 <- i } }() for { select { case <-c1: fmt.Println("Received value from c1") case <-c2: fmt.Println("Received value from c2") case <-quit: fmt.Println("quit") return } } } Output of this program: Received value from c1 Received value from c1 Received value from c2 Received value from c1 Received value from c2 Received value from c1 Received value from c1 Received value from c1 Received value from c1 Received value from c1 Received value from c1 Received value from c1 quit A: Here's a pretty direct translation, but the "choosing which if multiple are ready" part works differently - it's just taking what came in first. Also this is like running your code with gomaxprocs(1). import threading import Queue def main(): c1 = Queue.Queue(maxsize=0) c2 = Queue.Queue(maxsize=0) quit = Queue.Queue(maxsize=0) def func1(): for i in range(10): c1.put(i) quit.put(0) threading.Thread(target=func1).start() def func2(): for i in range(2): c2.put(i) threading.Thread(target=func2).start() combined = Queue.Queue(maxsize=0) def listen_and_forward(queue): while True: combined.put((queue, queue.get())) t = threading.Thread(target=listen_and_forward, args=(c1,)) t.daemon = True t.start() t = threading.Thread(target=listen_and_forward, args=(c2,)) t.daemon = True t.start() t = threading.Thread(target=listen_and_forward, args=(quit,)) t.daemon = True t.start() while True: which, message = combined.get() if which is c1: print 'Received value from c1' elif which is c2: print 'Received value from c2' elif which is quit: print 'Received value from quit' return main() The basic change is simulating the select with threads that combine messages. If you were going to use this pattern much, you might write some select code: import threading import Queue def select(*queues): combined = Queue.Queue(maxsize=0) def listen_and_forward(queue): while True: combined.put((queue, queue.get())) for queue in queues: t = threading.Thread(target=listen_and_forward, args=(queue,)) t.daemon = True t.start() while True: yield combined.get() def main(): c1 = Queue.Queue(maxsize=0) c2 = Queue.Queue(maxsize=0) quit = Queue.Queue(maxsize=0) def func1(): for i in range(10): c1.put(i) quit.put(0) threading.Thread(target=func1).start() def func2(): for i in range(2): c2.put(i) threading.Thread(target=func2).start() for which, msg in select(c1, c2, quit): if which is c1: print 'Received value from c1' elif which is c2: print 'Received value from c2' elif which is quit: print 'Received value from quit' return main() But... Note that this select isn't quite the go one, though it doesn't matter for your program - a goroutine could send a result on a channel that would be queued up in the select and lost if we didn't always iterate over the select to completion! A: Also consider the offset library by Benoit Chesneau. It is a port of the Go concurrency model to Python, using fibers under the covers. He gave a presentation about this at PyCon APAC 2013: Slides Video A: You can use multiprocessing.Pipe instead of chan, threading.Thread instead of go and select.select instead of select. Here's a reimplementation of your go example in Python using this approach: import random from multiprocessing import Pipe from select import select from threading import Thread def main(): c1_r, c1_w = Pipe(duplex=False) c2_r, c2_w = Pipe(duplex=False) quit_r, quit_w = Pipe(duplex=False) def func1(): for i in range(10): c1_w.send(i) quit_w.send(0) Thread(target=func1).start() def func2(): for i in range(2): c2_w.send(i) Thread(target=func2).start() while True: ready, _, _ = select([c1_r, c2_r, quit_r], [], []) which = random.choice(ready) if which == c1_r: c1_r.recv() print 'Received value from c1' elif which == c2_r: c2_r.recv() print 'Received value from c2' elif which == quit_r and len(ready) == 1: quit_r.recv() print 'Received value from quit' return if __name__ == '__main__': main() This implementation is based upon @Thomas's implementation, but unlike @Thomas's it doesn't spawn extra threads to perform the select. Tested on Linux with Python 2.7.13. Windows may behave differently as select is a Unixy thing. Edit: I added the len(ready) == 1 condition so quit is only handled after the other pipes are drained. This isn't required in Go as the channels are zero sized, so func1 can't send a message to quit_w until after the message sent to c1_w has been received. Thanks to the comment by @Sean Perry. A: With Python 3.5 there are the keywords async and await which make it possible to have functions which can be suspended in execution and thus are able to run on an evenloop instead of threads. The asyncio std lib is offering one. To more directly map the behaviour of Go blocking channels and select you might make use of this small library and then your example code would look very similar in Python. A: Yes, all are possible with goless. You can try it. Have Fun ;-) Here is an example: c1 = goless.chan() c2 = goless.chan() def func1(): time.sleep(1) c1.send('one') goless.go(func1) def func2(): time.sleep(2) c2.send('two') goless.go(func2) for i in range(2): case, val = goless.select([goless.rcase(c1), goless.rcase(c2)]) print(val) A: Here's another, an attempt at imitating the go syntax: from threading import Thread from Queue import Queue def main(): c1 = Queue.Queue(maxsize=0) c2 = Queue.Queue(maxsize=0) quit = Queue.Queue(maxsize=0) Thread(target=lambda: [c1.put(i) for i in range(10)] or quit.put(0)).start() Thread(target=lambda: [c2.put(i) for i in range(2)]).start() for which, msg in select(c1, c2, quit): if which is c1: print 'Received value from c1' elif which is c2: print 'Received value from c2' elif which is quit: print 'Received value from quit' return def select(*queues): combined = Queue.Queue(maxsize=0) def listen_and_forward(queue): while True: combined.put((queue, queue.get())) for queue in queues: t = Thread(target=listen_and_forward, args=(queue,)) t.daemon = True t.start() while True: yield combined.get() main() A: For completeness: Go-style channels, including working select are available as part of pygolang: ch1 = chan() # synchronous channel ch2 = chan(3) # channel with buffer of size 3 def _(): ch1.send('a') ch2.send('b') go(_) ch1.recv() # will give 'a' ch2.recv_() # will give ('b', True) _, _rx = select( ch1.recv, # 0 ch2.recv_, # 1 (ch2.send, obj2), # 2 default, # 3 ) if _ == 0: # _rx is what was received from ch1 ... if _ == 1: # _rx is (rx, ok) of what was received from ch2 ... if _ == 2: # we know obj2 was sent to ch2 ... if _ == 3: # default case ... offset (see https://stackoverflow.com/a/19143696/9456786) also seems interesting. goless (see https://stackoverflow.com/a/39269599/9456786), unfortunately, has weak select implementation, which by design does not work properly on synchronous channels. A: There are several answers here that use queue.Queue and threading.Thread to simulate the select behaviour but it's not necessary. You can extend queue.Queue like this: import queue import os import select class EQueue(queue.Queue): def __init__(self, *args, **kwargs) self._fd = os.eventfd(flags=0x00004001) super().__init__(*args, **kwargs) def put(self, *args, **kwargs): super().put(*args, **kwargs) eventfd_write(self._fd, 1) def get(self, *args, **kwargs): os.eventfd_read(self._fd) super().get(*args, **kwargs) def fileno(self): return self._fd def __del__(self): os.close(self._fd) This adds an extra semaphore around the queue and, crucially, one that is accessible through a file descriptor. This means you can now wait on this queue with select.select(). So the above examples that use queues and threads can be rewritten without the extra threads: def main(): c1 = EQueue(maxsize=0) c2 = EQueue(maxsize=0) quit = EQueue(maxsize=0) def func1(): for i in range(10): c1.put(i) quit.put(0) threading.Thread(target=func1).start() def func2(): for i in range(2): c2.put(i) threading.Thread(target=func2).start() rx, _, _ = select.select([c1, c2, quit], [], []): if c1 in rx: msg = c1.get() print 'Received value from c1' elif c2 in rx: msg = c2.get() print 'Received value from c2' elif quit in rx: print 'Received value from quit' return main() The main function here is fairly similar to that given by @alkasm above but there is no custom implementation of select and no thread-per-queue to collect all the separate queues into one; it relies on the operating system to tell you when a queue has items available. Note that os.eventfd was only added in Python 3.10 but implementing it in ctypes is fairly trivial or there is the eventfd package on PyPI. The latter also supports Windows, unlike the other options, simulating eventfds with pipes. The python doco claims that eventfds are only available on Linux systems running glibc >= 2.8 but muslc also supports them.
Python equivalent of Golang's select on channels
Go has a select statement that works on channels. From the documentation: The select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready. Is there a Python equivalent of the following code: package main import "fmt" func main() { c1 := make(chan int) c2 := make(chan int) quit := make(chan int) go func() { for i := 0; i < 10; i++ { c1 <- i } quit <- 0 }() go func() { for i := 0; i < 2; i++ { c2 <- i } }() for { select { case <-c1: fmt.Println("Received value from c1") case <-c2: fmt.Println("Received value from c2") case <-quit: fmt.Println("quit") return } } } Output of this program: Received value from c1 Received value from c1 Received value from c2 Received value from c1 Received value from c2 Received value from c1 Received value from c1 Received value from c1 Received value from c1 Received value from c1 Received value from c1 Received value from c1 quit
[ "Here's a pretty direct translation, but the \"choosing which if multiple are ready\" part works differently - it's just taking what came in first. Also this is like running your code with gomaxprocs(1).\nimport threading\nimport Queue\n\ndef main():\n c1 = Queue.Queue(maxsize=0)\n c2 = Queue.Queue(maxsize=0)\n quit = Queue.Queue(maxsize=0)\n\n def func1():\n for i in range(10):\n c1.put(i)\n quit.put(0)\n\n threading.Thread(target=func1).start()\n\n def func2():\n for i in range(2):\n c2.put(i)\n\n threading.Thread(target=func2).start()\n\n combined = Queue.Queue(maxsize=0)\n\n def listen_and_forward(queue):\n while True:\n combined.put((queue, queue.get()))\n\n t = threading.Thread(target=listen_and_forward, args=(c1,))\n t.daemon = True\n t.start()\n t = threading.Thread(target=listen_and_forward, args=(c2,))\n t.daemon = True\n t.start()\n t = threading.Thread(target=listen_and_forward, args=(quit,))\n t.daemon = True\n t.start()\n\n while True:\n which, message = combined.get()\n if which is c1:\n print 'Received value from c1'\n elif which is c2:\n print 'Received value from c2'\n elif which is quit:\n print 'Received value from quit'\n return\nmain()\n\nThe basic change is simulating the select with threads that combine messages. If you were going to use this pattern much, you might write some select code:\nimport threading\nimport Queue\n\ndef select(*queues):\n combined = Queue.Queue(maxsize=0)\n def listen_and_forward(queue):\n while True:\n combined.put((queue, queue.get()))\n for queue in queues:\n t = threading.Thread(target=listen_and_forward, args=(queue,))\n t.daemon = True\n t.start()\n while True:\n yield combined.get()\n\ndef main():\n\n c1 = Queue.Queue(maxsize=0)\n c2 = Queue.Queue(maxsize=0)\n quit = Queue.Queue(maxsize=0)\n\n def func1():\n for i in range(10):\n c1.put(i)\n quit.put(0)\n\n threading.Thread(target=func1).start()\n\n def func2():\n for i in range(2):\n c2.put(i)\n\n threading.Thread(target=func2).start()\n\n for which, msg in select(c1, c2, quit):\n if which is c1:\n print 'Received value from c1'\n elif which is c2:\n print 'Received value from c2'\n elif which is quit:\n print 'Received value from quit'\n return\nmain()\n\nBut...\nNote that this select isn't quite the go one, though it doesn't matter for your program - a goroutine could send a result on a channel that would be queued up in the select and lost if we didn't always iterate over the select to completion!\n", "Also consider the offset library by Benoit Chesneau. It is a port of the Go concurrency model to Python, using fibers under the covers.\nHe gave a presentation about this at PyCon APAC 2013:\n\nSlides\nVideo\n\n", "You can use multiprocessing.Pipe instead of chan, threading.Thread instead of go and select.select instead of select.\nHere's a reimplementation of your go example in Python using this approach:\nimport random\nfrom multiprocessing import Pipe\nfrom select import select\nfrom threading import Thread\n\n\ndef main():\n c1_r, c1_w = Pipe(duplex=False)\n c2_r, c2_w = Pipe(duplex=False)\n quit_r, quit_w = Pipe(duplex=False)\n\n def func1():\n for i in range(10):\n c1_w.send(i)\n quit_w.send(0)\n\n Thread(target=func1).start()\n\n def func2():\n for i in range(2):\n c2_w.send(i)\n\n Thread(target=func2).start()\n\n while True:\n ready, _, _ = select([c1_r, c2_r, quit_r], [], [])\n which = random.choice(ready)\n if which == c1_r:\n c1_r.recv()\n print 'Received value from c1'\n elif which == c2_r:\n c2_r.recv()\n print 'Received value from c2'\n elif which == quit_r and len(ready) == 1:\n quit_r.recv()\n print 'Received value from quit'\n return\n\nif __name__ == '__main__':\n main()\n\nThis implementation is based upon @Thomas's implementation, but unlike @Thomas's it doesn't spawn extra threads to perform the select.\nTested on Linux with Python 2.7.13. Windows may behave differently as select is a Unixy thing.\nEdit: I added the len(ready) == 1 condition so quit is only handled after the other pipes are drained. This isn't required in Go as the channels are zero sized, so func1 can't send a message to quit_w until after the message sent to c1_w has been received. Thanks to the comment by @Sean Perry.\n", "With Python 3.5 there are the keywords async and await which make it possible to have functions which can be suspended in execution and thus are able to run on an evenloop instead of threads. The asyncio std lib is offering one.\nTo more directly map the behaviour of Go blocking channels and select you might make use of this small library and then your example code would look very similar in Python.\n", "Yes, all are possible with goless. You can try it. \nHave Fun ;-)\nHere is an example:\nc1 = goless.chan()\nc2 = goless.chan()\n\ndef func1():\n time.sleep(1)\n c1.send('one')\ngoless.go(func1)\n\ndef func2():\n time.sleep(2)\n c2.send('two')\ngoless.go(func2)\n\nfor i in range(2):\n case, val = goless.select([goless.rcase(c1), goless.rcase(c2)])\n print(val)\n\n", "Here's another, an attempt at imitating the go syntax:\nfrom threading import Thread\nfrom Queue import Queue\n\ndef main():\n\n c1 = Queue.Queue(maxsize=0)\n c2 = Queue.Queue(maxsize=0)\n quit = Queue.Queue(maxsize=0)\n\n Thread(target=lambda: [c1.put(i) for i in range(10)] or quit.put(0)).start()\n Thread(target=lambda: [c2.put(i) for i in range(2)]).start()\n\n for which, msg in select(c1, c2, quit):\n if which is c1:\n print 'Received value from c1'\n elif which is c2:\n print 'Received value from c2'\n elif which is quit:\n print 'Received value from quit'\n return\n\ndef select(*queues):\n combined = Queue.Queue(maxsize=0)\n def listen_and_forward(queue):\n while True:\n combined.put((queue, queue.get()))\n for queue in queues:\n t = Thread(target=listen_and_forward, args=(queue,))\n t.daemon = True\n t.start()\n while True:\n yield combined.get()\n\nmain()\n\n", "For completeness: Go-style channels, including working select are available as part of pygolang:\nch1 = chan() # synchronous channel\nch2 = chan(3) # channel with buffer of size 3\n\ndef _():\n ch1.send('a')\n ch2.send('b')\ngo(_)\n\nch1.recv() # will give 'a'\nch2.recv_() # will give ('b', True)\n\n_, _rx = select(\n ch1.recv, # 0\n ch2.recv_, # 1\n (ch2.send, obj2), # 2\n default, # 3\n)\nif _ == 0:\n # _rx is what was received from ch1\n ...\nif _ == 1:\n # _rx is (rx, ok) of what was received from ch2\n ...\nif _ == 2:\n # we know obj2 was sent to ch2\n ...\nif _ == 3:\n # default case\n ...\n\noffset (see https://stackoverflow.com/a/19143696/9456786) also seems interesting.\ngoless (see https://stackoverflow.com/a/39269599/9456786), unfortunately, has weak select implementation, which by design does not work properly on synchronous channels.\n", "There are several answers here that use queue.Queue and threading.Thread to simulate the select behaviour but it's not necessary. You can extend queue.Queue like this:\nimport queue\nimport os\nimport select\n\nclass EQueue(queue.Queue):\n def __init__(self, *args, **kwargs)\n self._fd = os.eventfd(flags=0x00004001)\n super().__init__(*args, **kwargs)\n\n def put(self, *args, **kwargs):\n super().put(*args, **kwargs)\n eventfd_write(self._fd, 1)\n\n def get(self, *args, **kwargs):\n os.eventfd_read(self._fd)\n super().get(*args, **kwargs)\n\n def fileno(self):\n return self._fd\n\n def __del__(self):\n os.close(self._fd)\n\nThis adds an extra semaphore around the queue and, crucially, one that is accessible through a file descriptor. This means you can now wait on this queue with select.select(). So the above examples that use queues and threads can be rewritten without the extra threads:\ndef main():\n\n c1 = EQueue(maxsize=0)\n c2 = EQueue(maxsize=0)\n quit = EQueue(maxsize=0)\n\n def func1():\n for i in range(10):\n c1.put(i)\n quit.put(0)\n\n threading.Thread(target=func1).start()\n\n def func2():\n for i in range(2):\n c2.put(i)\n\n threading.Thread(target=func2).start()\n\n rx, _, _ = select.select([c1, c2, quit], [], []):\n if c1 in rx:\n msg = c1.get()\n print 'Received value from c1'\n elif c2 in rx:\n msg = c2.get()\n print 'Received value from c2'\n elif quit in rx:\n print 'Received value from quit'\n return\nmain()\n\nThe main function here is fairly similar to that given by @alkasm above but there is no custom implementation of select and no thread-per-queue to collect all the separate queues into one; it relies on the operating system to tell you when a queue has items available.\nNote that os.eventfd was only added in Python 3.10 but implementing it in ctypes is fairly trivial or there is the eventfd package on PyPI. The latter also supports Windows, unlike the other options, simulating eventfds with pipes. The python doco claims that eventfds are only available on Linux systems running glibc >= 2.8 but muslc also supports them.\n" ]
[ 19, 12, 9, 4, 4, 3, 2, 1 ]
[]
[]
[ "go", "python" ]
stackoverflow_0019130986_go_python.txt
Q: Draw a Rectangle over an image and get the coordinates in python I'm trying to develop a code that open an image where you can select a point quit the mouse and drag to form a rectangle until you don't release the left button. Then from python I should receive the starting coordinates and the height and width in pixel of the rectangle, how can I do it? I saw that the packages argparse and cv2 can be used, but I don't really know how to approach it. A: I won't do the job for you but I'm willing to help. You will need 2 blocks of code: an image displayer a mouse-event listener To start, you may forget about the image displayer. You may concentrate on the mouse listener while you draw your rectangle anywhere on the screen. Select a mouse listener library. There are many on pypi.org. I propose pynput because it is easy to work with and is well documented. read documentation (focus on "on_click") write your code to implement your mouse listener. It's simple (less than 10 lines). At the end of your program, add a statement: input(">") run your program. Click anywhere on the screen and drag to another point. Release. your on_click() function will be called twice (once for button press and once for button release). Record the two sets of X-Y coordinates (unit is pixels). once the button is released, compute the size of the rectangle (in pixels). press any key on the keyboard to end the program. Once your program is working you may work on the imager. If the image is large, you may have to use a scaling factor to reduce it. You will have to introduce the scaling factor in your sizing equations. When a program skeleton will exist, do not hesitate to ask questions. Asking for help when there is no visible sweat will not bring you many answers.
Draw a Rectangle over an image and get the coordinates in python
I'm trying to develop a code that open an image where you can select a point quit the mouse and drag to form a rectangle until you don't release the left button. Then from python I should receive the starting coordinates and the height and width in pixel of the rectangle, how can I do it? I saw that the packages argparse and cv2 can be used, but I don't really know how to approach it.
[ "I won't do the job for you but I'm willing to help.\nYou will need 2 blocks of code:\n\nan image displayer\na mouse-event listener\n\nTo start, you may forget about the image displayer. You may concentrate on the mouse listener while you draw your rectangle anywhere on the screen.\nSelect a mouse listener library. There are many on pypi.org.\nI propose pynput because it is easy to work with and is well documented.\n\nread documentation (focus on \"on_click\")\nwrite your code to implement your mouse listener. It's simple (less than 10 lines). At the end of your program, add a statement:\ninput(\">\")\nrun your program. Click anywhere on the screen and drag to another point. Release.\nyour on_click() function will be called twice (once for button press and once for button release). Record the two sets of X-Y coordinates (unit is pixels).\nonce the button is released, compute the size of the rectangle (in pixels).\npress any key on the keyboard to end the program.\n\nOnce your program is working you may work on the imager. If the image is large, you may have to use a scaling factor to reduce it. You will have to introduce the scaling factor in your sizing equations.\nWhen a program skeleton will exist, do not hesitate to ask questions.\nAsking for help when there is no visible sweat will not bring you many answers.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074549601_python.txt
Q: How to place the buttons side to side in tkinter using place method? I am new to tkinter and learning to create simple widgets. I have encountered on issue, when I was creating many buttons to click, I found that the spacing between the buttons is not uniform and it becomes more congested as it goes left to right. MWE How to make spacing between buttons uniform? %%writefile a.py import sys import tkinter as tk from tkinter import ttk,messagebox win = tk.Tk() def countdown(win): child = tk.Toplevel(win) child.geometry('400x300') child.resizable(0, 0) # label: current time title tk.Label(child, font='arial 15 bold', text='current time :').place(x=40, y=70) tk.Label(child, font='arial 15 bold', text='set the time').place(x=40, y=150) tk.Label(child,text='',fg='gray25').place(x=190, y=70) frame_top = tk.Frame(child) frame_top.pack(expand=False, fill=tk.X) frame_bottom = tk.Frame(child) frame_bottom.pack(expand=False, fill=tk.X) mins = [1,2,5,10,15,20,25,30,35,40] for i,minn in enumerate(mins): tk.Button(frame_top,text=str(minn)+'m',bd='5',).pack(expand=True, side=tk.LEFT) for i,minn in enumerate([45,50,55,60,90,120,150,180]): tk.Button(frame_bottom,text=str(minn)+'m',bd='5',).pack(expand=True, side=tk.LEFT) menubar = tk.Menu(win) menu = tk.Menu(menubar, tearoff=0) menubar.add_cascade(label="Scripts", menu=menu) menu.add_command(label='Countdown',command=lambda : countdown(win)) menu.add_command(label='Exit',command=sys.exit) win.config(menu=menubar) win.mainloop() Suggestion A: You'll have a much easier time using a different geometry manager like pack() or, better yet, grid() Using pack: import tkinter as tk child = tk.Tk() child.geometry('400x300') x,w = 0,40 mins = [1,2,5,10,15,20,25,30,35,40] mins2 = [45,50,55,60,90,120,150,180] # create some frames to contain each row of buttons frame_top = tk.Frame(child) frame_top.pack(expand=False, fill=tk.X) frame_bottom = tk.Frame(child) frame_bottom.pack(expand=False, fill=tk.X) for minn in (mins): button = tk.Button(frame_top, text=str(minn)+'m', bd='5') button.pack(expand=True, side=tk.LEFT) for minn in (mins2): button = tk.Button(frame_bottom, text=str(minn)+'m', bd='5') button.pack(expand=True, side=tk.LEFT) child.mainloop() Using grid: import tkinter as tk child = tk.Tk() child.geometry('400x300') x,w = 0,40 mins = [1,2,5,10,15,20,25,30,35,40] mins2 = [45,50,55,60,90,120,150,180] for i, min in enumerate(mins): button = tk.Button(child, text=str(minn)+'m', bd='5') button.grid(row=0, column=i) for i, minn in enumerate(mins2): button = Button(child, text=str(minn)+'m', bd='5') button.grid(row=1, column=i) child.mainloop() Admittedly, I am the most familiar with pack() - if anyone sees an issue with my grid() implementation, by all means let me know! Addendum It's usually prudent to instantiate your widgets separately from adding them to a geometry manager like pack, place, or grid # DON'T: button = ttk.Button(parent).pack() # button = None # DO: button = ttk.Button(parent) # instantiate widget button.pack() # pack separately # button = .!button The reason is explained here, but the gist is that the geometry manager methods return None and that can cause problems if you're not paying attention.
How to place the buttons side to side in tkinter using place method?
I am new to tkinter and learning to create simple widgets. I have encountered on issue, when I was creating many buttons to click, I found that the spacing between the buttons is not uniform and it becomes more congested as it goes left to right. MWE How to make spacing between buttons uniform? %%writefile a.py import sys import tkinter as tk from tkinter import ttk,messagebox win = tk.Tk() def countdown(win): child = tk.Toplevel(win) child.geometry('400x300') child.resizable(0, 0) # label: current time title tk.Label(child, font='arial 15 bold', text='current time :').place(x=40, y=70) tk.Label(child, font='arial 15 bold', text='set the time').place(x=40, y=150) tk.Label(child,text='',fg='gray25').place(x=190, y=70) frame_top = tk.Frame(child) frame_top.pack(expand=False, fill=tk.X) frame_bottom = tk.Frame(child) frame_bottom.pack(expand=False, fill=tk.X) mins = [1,2,5,10,15,20,25,30,35,40] for i,minn in enumerate(mins): tk.Button(frame_top,text=str(minn)+'m',bd='5',).pack(expand=True, side=tk.LEFT) for i,minn in enumerate([45,50,55,60,90,120,150,180]): tk.Button(frame_bottom,text=str(minn)+'m',bd='5',).pack(expand=True, side=tk.LEFT) menubar = tk.Menu(win) menu = tk.Menu(menubar, tearoff=0) menubar.add_cascade(label="Scripts", menu=menu) menu.add_command(label='Countdown',command=lambda : countdown(win)) menu.add_command(label='Exit',command=sys.exit) win.config(menu=menubar) win.mainloop() Suggestion
[ "You'll have a much easier time using a different geometry manager like pack() or, better yet, grid()\nUsing pack:\nimport tkinter as tk\n\nchild = tk.Tk()\nchild.geometry('400x300')\n\nx,w = 0,40\nmins = [1,2,5,10,15,20,25,30,35,40]\nmins2 = [45,50,55,60,90,120,150,180]\n# create some frames to contain each row of buttons\nframe_top = tk.Frame(child)\nframe_top.pack(expand=False, fill=tk.X)\nframe_bottom = tk.Frame(child)\nframe_bottom.pack(expand=False, fill=tk.X)\n\nfor minn in (mins):\n button = tk.Button(frame_top, text=str(minn)+'m', bd='5')\n button.pack(expand=True, side=tk.LEFT)\n\nfor minn in (mins2):\n button = tk.Button(frame_bottom, text=str(minn)+'m', bd='5')\n button.pack(expand=True, side=tk.LEFT)\n\nchild.mainloop()\n\nUsing grid:\nimport tkinter as tk\n\nchild = tk.Tk()\nchild.geometry('400x300')\n\nx,w = 0,40\nmins = [1,2,5,10,15,20,25,30,35,40]\nmins2 = [45,50,55,60,90,120,150,180]\n\nfor i, min in enumerate(mins):\n button = tk.Button(child, text=str(minn)+'m', bd='5')\n button.grid(row=0, column=i)\n\nfor i, minn in enumerate(mins2):\n button = Button(child, text=str(minn)+'m', bd='5')\n button.grid(row=1, column=i)\n\nchild.mainloop()\n\nAdmittedly, I am the most familiar with pack() - if anyone sees an issue with my grid() implementation, by all means let me know!\n\nAddendum\nIt's usually prudent to instantiate your widgets separately from adding them to a geometry manager like pack, place, or grid\n# DON'T:\nbutton = ttk.Button(parent).pack()\n# button = None\n\n# DO:\nbutton = ttk.Button(parent) # instantiate widget\nbutton.pack() # pack separately\n# button = .!button\n\nThe reason is explained here, but the gist is that the geometry manager methods return None and that can cause problems if you're not paying attention.\n" ]
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074551930_python_tkinter.txt
Q: Expand json data in a column inside dataframe I know there is a way to expand the columns without extracting and joining/concatenating/appending data. I have this json data which I've already normalized but I have a column that has a nested json: Image of issue So what I want to do is to expand this json data in a way that adds columns automatically in the dataframe without indexing since the data inside that column doesn´t have any key to pair, so it should be by position/row only. What could I do to unnest it? Thanks! Update: In a previous step I've already normalized it: response1 = requests.get(url1, params=params1, headers=headertoken) textresponse1 = response1.text if "El contrato enviado no tiene envios registrados." in textresponse1: continue textresponse1 = json.loads(response1.text) response1_df = pd.json_normalize(textresponse1['envios']) enviosdf = pd.concat([enviosdf,response1_df]) Problem is that, after this, the column 'bultos' is another json. Which when you try to normalize it, this happens: 0 {'kilos': 0.0025, 'IdDeProducto': 'ysyHhBHttHd... 1 {'kilos': 0.0025, 'IdDeProducto': 'QNEOqaNXtsi... 2 {'kilos': 0.0025, 'IdDeProducto': 'V7b3D7xaSur... The normalization doesn't normalize it nor expands it. A: you should use explode before json_normalize because they are lists: enviosdf=enviosdf.explode('bultos').reset_index(drop=True) enviosdf=enviosdf.join(pd.json_normalize(enviosdf.pop('bultos')))
Expand json data in a column inside dataframe
I know there is a way to expand the columns without extracting and joining/concatenating/appending data. I have this json data which I've already normalized but I have a column that has a nested json: Image of issue So what I want to do is to expand this json data in a way that adds columns automatically in the dataframe without indexing since the data inside that column doesn´t have any key to pair, so it should be by position/row only. What could I do to unnest it? Thanks! Update: In a previous step I've already normalized it: response1 = requests.get(url1, params=params1, headers=headertoken) textresponse1 = response1.text if "El contrato enviado no tiene envios registrados." in textresponse1: continue textresponse1 = json.loads(response1.text) response1_df = pd.json_normalize(textresponse1['envios']) enviosdf = pd.concat([enviosdf,response1_df]) Problem is that, after this, the column 'bultos' is another json. Which when you try to normalize it, this happens: 0 {'kilos': 0.0025, 'IdDeProducto': 'ysyHhBHttHd... 1 {'kilos': 0.0025, 'IdDeProducto': 'QNEOqaNXtsi... 2 {'kilos': 0.0025, 'IdDeProducto': 'V7b3D7xaSur... The normalization doesn't normalize it nor expands it.
[ "you should use explode before json_normalize because they are lists:\nenviosdf=enviosdf.explode('bultos').reset_index(drop=True)\nenviosdf=enviosdf.join(pd.json_normalize(enviosdf.pop('bultos')))\n\n" ]
[ -1 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074551061_json_pandas_python.txt
Q: How to get the difference of two querysets in Django? I have to querysets. alllists and subscriptionlists alllists = List.objects.filter(datamode = 'A') subscriptionlists = Membership.objects.filter(member__id=memberid, datamode='A') I need a queryset called unsubscriptionlist, which possess all records in alllists except the records in subscription lists. How to achieve this? A: Since Django 1.11, QuerySets have a difference() method amongst other new methods: # Capture elements that are in qs_all but not in qs_part qs_diff = qs_all.difference(qs_part) Also see: https://stackoverflow.com/a/45651267/5497962 A: You should be able to use the set operation difference to help: set(alllists).difference(set(subscriptionlists)) A: Well I see two options here. 1. Filter things manually (quite ugly) diff = [] for all in alllists: found = False for sub in subscriptionlists: if sub.id == all.id: found = True break if not found: diff.append(all) 2. Just make another query diff = List.objects.filter(datamode = 'A').exclude(member__id=memberid, datamode='A') A: How about: subscriptionlists = Membership.objects.filter(member__id=memberid, datamode='A') unsubscriptionlists = Membership.objects.exclude(member__id=memberid, datamode='A') The unsubscriptionlists should be the inverse of subscription lists. Brian's answer will work as well, though set() will most likely evaluate the query and will take a performance hit in evaluating both sets into memory. This method will keep the lazy initialization until you need the data. A: In case anyone's searching for a way to do symmetric difference, such operator is not available in Django. That said, it's not that hard to implement it using difference and union, and it'll all be done in a single query: q1.difference(q2).union(q2.difference(q1))
How to get the difference of two querysets in Django?
I have to querysets. alllists and subscriptionlists alllists = List.objects.filter(datamode = 'A') subscriptionlists = Membership.objects.filter(member__id=memberid, datamode='A') I need a queryset called unsubscriptionlist, which possess all records in alllists except the records in subscription lists. How to achieve this?
[ "Since Django 1.11, QuerySets have a difference() method amongst other new methods:\n# Capture elements that are in qs_all but not in qs_part\nqs_diff = qs_all.difference(qs_part) \n\nAlso see: https://stackoverflow.com/a/45651267/5497962\n", "You should be able to use the set operation difference to help:\nset(alllists).difference(set(subscriptionlists))\n\n", "Well I see two options here.\n1. Filter things manually (quite ugly)\ndiff = []\nfor all in alllists:\n found = False\n for sub in subscriptionlists:\n if sub.id == all.id:\n found = True \n break\n if not found:\n diff.append(all)\n\n2. Just make another query\ndiff = List.objects.filter(datamode = 'A').exclude(member__id=memberid, datamode='A')\n\n", "How about:\nsubscriptionlists = Membership.objects.filter(member__id=memberid, datamode='A')\nunsubscriptionlists = Membership.objects.exclude(member__id=memberid, datamode='A')\n\nThe unsubscriptionlists should be the inverse of subscription lists. \nBrian's answer will work as well, though set() will most likely evaluate the query and will take a performance hit in evaluating both sets into memory. This method will keep the lazy initialization until you need the data.\n", "In case anyone's searching for a way to do symmetric difference, such operator is not available in Django.\nThat said, it's not that hard to implement it using difference and union, and it'll all be done in a single query:\nq1.difference(q2).union(q2.difference(q1))\n\n" ]
[ 32, 21, 11, 4, 0 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0005945912_django_django_queryset_python.txt