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: getting data from the backend django models I am working on a project pastly the i used sql querys, but change in the django models the models i used are for the members table class Members(models.Model): name = models.CharField(max_length = 50) address = models.CharField(max_length = 50) phoneNo = models.CharField(unique=True, max_length = 50) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def __str__(self): return self.name for the bills table salesPerson = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) purchasedPerson = models.ForeignKey(Members, on_delete = models.SET_NULL, null=True) cash = models.BooleanField(default=True) totalAmount = models.IntegerField() advance = models.IntegerField(null=True, blank=True) remarks = models.CharField(max_length = 200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] i am having a query that is credits = Bills.objects.all().filter(cash = False).values ('purchasedPerson').annotate( cnt = Count('purchasedPerson'), debit = Sum( 'totalAmount' ), credit = Sum( 'advance' ), balance = Sum( 'totalAmount' ) - Sum( 'advance' ) ).order_by ('purchasedPerson') getting the output as [{'purchasedPerson': 1, 'cnt': 2, 'debit': 23392, 'credit': 100, 'balance': 23292}, {'purchasedPerson': 2, 'cnt': 1, 'debit': 1280, 'credit': 0, 'balance': 1280}] but i need in the out put name, address and phone number also how can i get those A: Pass all fields you need in .values() like: Bills.objects.filter(cash = False).values('purchasedPerson', 'name', 'address', 'phoneNo').annotate(...) Another choice is skipping the .values() part: Bills.objects.filter(cash = False).annotate(...) Note: all() is not required in your case.
getting data from the backend django models
I am working on a project pastly the i used sql querys, but change in the django models the models i used are for the members table class Members(models.Model): name = models.CharField(max_length = 50) address = models.CharField(max_length = 50) phoneNo = models.CharField(unique=True, max_length = 50) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def __str__(self): return self.name for the bills table salesPerson = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) purchasedPerson = models.ForeignKey(Members, on_delete = models.SET_NULL, null=True) cash = models.BooleanField(default=True) totalAmount = models.IntegerField() advance = models.IntegerField(null=True, blank=True) remarks = models.CharField(max_length = 200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] i am having a query that is credits = Bills.objects.all().filter(cash = False).values ('purchasedPerson').annotate( cnt = Count('purchasedPerson'), debit = Sum( 'totalAmount' ), credit = Sum( 'advance' ), balance = Sum( 'totalAmount' ) - Sum( 'advance' ) ).order_by ('purchasedPerson') getting the output as [{'purchasedPerson': 1, 'cnt': 2, 'debit': 23392, 'credit': 100, 'balance': 23292}, {'purchasedPerson': 2, 'cnt': 1, 'debit': 1280, 'credit': 0, 'balance': 1280}] but i need in the out put name, address and phone number also how can i get those
[ "Pass all fields you need in .values() like:\nBills.objects.filter(cash = False).values('purchasedPerson', 'name', 'address', 'phoneNo').annotate(...)\n\nAnother choice is skipping the .values() part:\nBills.objects.filter(cash = False).annotate(...)\n\n\nNote: all() is not required in your case.\n\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074590177_django_python.txt
Q: Execute function specifically on CPU in Jax I have a function that will basically instantiate a huge array and do other things. I am running my code on TPUs so basically my memory is limited. How can I execute my function specifically on the CPU? If I do: y = jax.device_put(my_function(), device=jax.devices("cpu")[0]) I guess that my_function() is first executed on TPU and the result is put on CPU, which gives me memory error. and using jax.config.update('jax_platform_name', 'cpu') at the beginning of my code seems to have no effect. Also please note that I can't modify my_function() Thanks! A: I'm going to make a guess here. I can't run it either so you may have to fiddle with it with jax.default_device(jax.devices("cpu")[0]): y = my_function() See the docs here and here. A: To directly specify the device on which a function should be executed, use the device argument of jax.jit. For example (using a GPU runtime because it's the accelerator I have access to at the moment): import jax gpu_device = jax.devices('gpu')[0] cpu_device = jax.devices('cpu')[0] def my_function(x): return x.sum() x = jax.numpy.arange(10) x_gpu = jax.jit(my_function, device=gpu_device)(x) print(x_tpu.device()) # gpu:0 x_cpu = jax.jit(my_function, device=cpu_device)(x) print(x_cpu.device()) # TFRT_CPU_0 This can also be controlled with the jax.default_device decorator around the call-site: with jax.default_device(cpu_device): print(jax.jit(my_function)(x).device()) # TFRT_CPU_0 with jax.default_device(gpu_device): print(jax.jit(my_function)(x).device()) # gpu:0
Execute function specifically on CPU in Jax
I have a function that will basically instantiate a huge array and do other things. I am running my code on TPUs so basically my memory is limited. How can I execute my function specifically on the CPU? If I do: y = jax.device_put(my_function(), device=jax.devices("cpu")[0]) I guess that my_function() is first executed on TPU and the result is put on CPU, which gives me memory error. and using jax.config.update('jax_platform_name', 'cpu') at the beginning of my code seems to have no effect. Also please note that I can't modify my_function() Thanks!
[ "I'm going to make a guess here. I can't run it either so you may have to fiddle with it\nwith jax.default_device(jax.devices(\"cpu\")[0]):\n y = my_function()\n\nSee the docs here and here.\n", "To directly specify the device on which a function should be executed, use the device argument of jax.jit. For example (using a GPU runtime because it's the accelerator I have access to at the moment):\nimport jax\n\ngpu_device = jax.devices('gpu')[0]\ncpu_device = jax.devices('cpu')[0]\n\ndef my_function(x):\n return x.sum()\n\nx = jax.numpy.arange(10)\n\nx_gpu = jax.jit(my_function, device=gpu_device)(x)\nprint(x_tpu.device())\n# gpu:0\n\nx_cpu = jax.jit(my_function, device=cpu_device)(x)\nprint(x_cpu.device())\n# TFRT_CPU_0\n\nThis can also be controlled with the jax.default_device decorator around the call-site:\nwith jax.default_device(cpu_device):\n print(jax.jit(my_function)(x).device())\n # TFRT_CPU_0\n\nwith jax.default_device(gpu_device):\n print(jax.jit(my_function)(x).device())\n # gpu:0\n\n" ]
[ 0, 0 ]
[]
[]
[ "cpu", "jax", "memory", "python", "tpu" ]
stackoverflow_0074537026_cpu_jax_memory_python_tpu.txt
Q: Unable to Login Django Admin after Update : Giving Error Forbidden (403) CSRF verification failed I am encountering the error Forbidden (403) CSRF verification failed when trying to login into the Django Admin after updating the version of Django. Also, there were no changes in the settings of Django. The error can be seen in the below image: A: I Already posted it on https://shriekdj.hashnode.dev/unable-to-login-django-admin-after-update-giving-error-forbidden-403-csrf-verification-failed-request-aborted. This Issue can happen suddenly after updating to the newer version Of Django. Details Django Project Foundation team made some changes in security requirements for all Django Versions 4.0 and Above. They made it mandatory to create a list of URLs getting any type of form upload or POST request in project settings named as CSRF_TRUSTED_ORIGINS. They did not update the details in the latest tutorial documentation, but they published the Changes Notes at https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes-4-0. First Solution For localhost or 127.0.0.1. Goto settings.py of your Django project and create a new list of URLs at last like given below CSRF_TRUSTED_ORIGINS = ['http://*', 'https://*'] if You're running a project in localhost, then you should open all URLs here * symbol means all URLs. Also, http:// is mandatory. Second Solution This is also for Localhost and DEBUG=True. Copy the list of ALLOWED_ORIGINS into CSRF_TRUSTED_ORIGINS as given below. ALLOWED_ORIGINS = ['http://*', 'https://*'] CSRF_TRUSTED_ORIGINS = ALLOWED_ORIGINS.copy() Third Solution When deploying, you have to add URLs to allow form uploading ( making any POST request ). I know this may be tricky and time-consuming but it's now mandatory. Also, this is mandatory for Online IDEs also like Replit and Glitch. A: Open the config file (most likely settings.py) and set the CSRF_TRUSTED_ORIGINS key as a shallow copy of the ALLOWED_HOSTS key which, in turn, should be set as recommended in the documentation.1 For example: # -*- coding: utf-8 -*- # For security consideration, please set to match the host/domain of your site, e.g., ALLOWED_HOSTS = ['.example.com']. # Please refer https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts for details. ALLOWED_HOSTS = ['.yourdomain.com', '.localhost', '127.0.0.1', '[::1]'] # Whether to use a secure cookie for the CSRF cookie # https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-cookie-secure CSRF_COOKIE_SECURE = True # The value of the SameSite flag on the CSRF cookie # https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-cookie-samesite CSRF_COOKIE_SAMESITE = 'Strict' CSRF_TRUSTED_ORIGINS = ALLOWED_HOSTS.copy() (...) 1 The config file contains a link to the documentation of the ALLOWED_HOSTS key — right above that key. Surprise, surprise.
Unable to Login Django Admin after Update : Giving Error Forbidden (403) CSRF verification failed
I am encountering the error Forbidden (403) CSRF verification failed when trying to login into the Django Admin after updating the version of Django. Also, there were no changes in the settings of Django. The error can be seen in the below image:
[ "I Already posted it on https://shriekdj.hashnode.dev/unable-to-login-django-admin-after-update-giving-error-forbidden-403-csrf-verification-failed-request-aborted.\nThis Issue can happen suddenly after updating to the newer version Of Django.\nDetails\n\nDjango Project Foundation team made some changes in security requirements for all Django Versions 4.0 and Above. They made it mandatory to create a list of URLs getting any type of form upload or POST request in project settings named as CSRF_TRUSTED_ORIGINS.\n\n\n\nThey did not update the details in the latest tutorial documentation, but they published the Changes Notes at https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes-4-0.\n\n\n\nFirst Solution\n\nFor localhost or 127.0.0.1.\n\n\n\nGoto settings.py of your Django project and create a new list of URLs at last like given below\n\n\nCSRF_TRUSTED_ORIGINS = ['http://*', 'https://*']\n\n\nif You're running a project in localhost, then you should open all URLs here * symbol means all URLs. Also, http:// is mandatory.\n\n\nSecond Solution\n\nThis is also for Localhost and DEBUG=True.\n\n\n\nCopy the list of ALLOWED_ORIGINS into CSRF_TRUSTED_ORIGINS as given below.\n\n\nALLOWED_ORIGINS = ['http://*', 'https://*']\nCSRF_TRUSTED_ORIGINS = ALLOWED_ORIGINS.copy()\n\n\nThird Solution\nWhen deploying, you have to add URLs to allow form uploading ( making any POST request ).\nI know this may be tricky and time-consuming but it's now mandatory.\nAlso, this is mandatory for Online IDEs also like Replit and Glitch.\n", "Open the config file (most likely settings.py) and set the CSRF_TRUSTED_ORIGINS key as a shallow copy of the ALLOWED_HOSTS key which, in turn, should be set as recommended in the documentation.1\nFor example:\n# -*- coding: utf-8 -*-\n# For security consideration, please set to match the host/domain of your site, e.g., ALLOWED_HOSTS = ['.example.com'].\n# Please refer https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts for details.\nALLOWED_HOSTS = ['.yourdomain.com', '.localhost', '127.0.0.1', '[::1]']\n\n# Whether to use a secure cookie for the CSRF cookie\n# https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-cookie-secure\nCSRF_COOKIE_SECURE = True\n\n# The value of the SameSite flag on the CSRF cookie\n# https://docs.djangoproject.com/en/3.2/ref/settings/#csrf-cookie-samesite\nCSRF_COOKIE_SAMESITE = 'Strict'\n\nCSRF_TRUSTED_ORIGINS = ALLOWED_HOSTS.copy()\n\n(...)\n\n\n1 The config file contains a link to the documentation of the ALLOWED_HOSTS key — right above that key. Surprise, surprise.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_admin", "django_forms", "python", "python_3.x" ]
stackoverflow_0071857585_django_django_admin_django_forms_python_python_3.x.txt
Q: How to update marker positions in a scatter mapbox? I'm trying to display live location data on a mapbox scatter plot. In order to mimic new data received from the server the callback moves all points every 3 seconds: import plotly.express as px from dash import Dash, html, dcc from dash.dependencies import Input, Output px.set_mapbox_access_token(open(".mapbox_token").read()) df = px.data.carshare() app = Dash(__name__) app.layout = html.Div([ dcc.Graph(id='map', animate=True), dcc.Interval( id='interval-component', interval=3000, ) ]) @app.callback(Output('map', 'figure'), [Input('interval-component', 'n_intervals')]) def update_map(n): df['centroid_lon'] += 0.01 fig = px.scatter_mapbox(df, lat="centroid_lat", lon="centroid_lon") return fig if __name__ == '__main__': app.run_server(debug=True) While the labels are correctly changing their location, the markers are stuck at their original positions. result A: I found a work around by having two callbacks. my html looks like this dbc.Col > dcc.Graph(figure = fig) @app.callback( Output('graph-id','figure'), Input('control-id', 'n_clicks') ) def update_func(scatter_map_fig): return go.Figure The second callback returns a new graph component with the updated information of the figure @app.callback( Output('col-id','children'), Input('graph-id', 'figure'), State('date_range','start_date'), State('date_range','end_date'), ) def update_func_2(scatter_map_fig): scatter_fig = go.Figure() scatter_fig.update_layout(...) ... (put your figure logic here) return dcc.Graph(figure=fig) It is a bit janky but it works until there's a better solution. Hope it helps.
How to update marker positions in a scatter mapbox?
I'm trying to display live location data on a mapbox scatter plot. In order to mimic new data received from the server the callback moves all points every 3 seconds: import plotly.express as px from dash import Dash, html, dcc from dash.dependencies import Input, Output px.set_mapbox_access_token(open(".mapbox_token").read()) df = px.data.carshare() app = Dash(__name__) app.layout = html.Div([ dcc.Graph(id='map', animate=True), dcc.Interval( id='interval-component', interval=3000, ) ]) @app.callback(Output('map', 'figure'), [Input('interval-component', 'n_intervals')]) def update_map(n): df['centroid_lon'] += 0.01 fig = px.scatter_mapbox(df, lat="centroid_lat", lon="centroid_lon") return fig if __name__ == '__main__': app.run_server(debug=True) While the labels are correctly changing their location, the markers are stuck at their original positions. result
[ "I found a work around by having two callbacks.\nmy html looks like this dbc.Col > dcc.Graph(figure = fig)\n@app.callback(\n Output('graph-id','figure'),\n\n Input('control-id', 'n_clicks')\n)\ndef update_func(scatter_map_fig):\n return go.Figure\n\nThe second callback returns a new graph component with the updated information of the figure\n@app.callback(\n Output('col-id','children'),\n\n Input('graph-id', 'figure'),\n\n State('date_range','start_date'),\n State('date_range','end_date'),\n)\ndef update_func_2(scatter_map_fig):\n scatter_fig = go.Figure()\n scatter_fig.update_layout(...)\n ... (put your figure logic here)\n return dcc.Graph(figure=fig)\n\nIt is a bit janky but it works until there's a better solution. Hope it helps.\n" ]
[ 0 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074567159_plotly_dash_python.txt
Q: Flask change the server header I've made a simple flask application: Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. GET / HTTP/1.1 host:google.be HTTP/1.0 404 NOT FOUND Content-Type: text/html Content-Length: 233 Server: Werkzeug/0.9.6 Python/2.7.6 Date: Mon, 08 Dec 2014 19:15:43 GMT <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>404 Not Found</title> <h1>Not Found</h1> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p> Connection closed by foreign host. One of the things I would like the change is the server header which at the moment is set as Werkzeug/0.9.6 Python/2.7.6 to something my own chosing. But I can't seem to find anything in the documentation on how to do this. A: You can use Flask's make_response method to add or modify headers. from flask import make_response @app.route('/index') def index(): resp = make_response("Hello, World!") resp.headers['server'] = 'ASD' return resp A: @bcarroll's answer works but it will bypass other processes defined in original process_response method such as set session cookie. To avoid the above: class localFlask(Flask): def process_response(self, response): #Every response will be processed here first response.headers['server'] = SERVER_NAME super(localFlask, self).process_response(response) return(response) A: You can change the Server header for every response by overriding the Flask.process_response() method. from flask import Flask from flask import Response SERVER_NAME = 'Custom Flask Web Server v0.1.0' class localFlask(Flask): def process_response(self, response): #Every response will be processed here first response.headers['server'] = SERVER_NAME return(response) app = localFlask(__name__) @app.route('/') def index(): return('<h2>INDEX</h2>') @app.route('/test') def test(): return('<h2>This is a test</h2>') http://flask.pocoo.org/docs/0.12/api/#flask.Flask.process_response A: Overriding Server header in code does not work if You use production server like gunicorn. The better way is to use proxy server behind gunicorn and there change Server header. A: TL;DR - overwrite /python3.8/http/server.py send_response method. Comment the server header addition line. Why? Adding/Manipulating headers in flask (in any way that mentioned above) will fire the response with the configured headers from flask to the web server but the WSGI logic (which happens independently, after & before flask logic) will be the last one to modify those values if any. In your case(Werkzeug) some headers are hard-coded in python http module which werkzeug depending on. The server header is one of them. A: Easy way: @app.after_request def changeserver(response): response.headers['server'] = SERVER_NAME return response
Flask change the server header
I've made a simple flask application: Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. GET / HTTP/1.1 host:google.be HTTP/1.0 404 NOT FOUND Content-Type: text/html Content-Length: 233 Server: Werkzeug/0.9.6 Python/2.7.6 Date: Mon, 08 Dec 2014 19:15:43 GMT <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>404 Not Found</title> <h1>Not Found</h1> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p> Connection closed by foreign host. One of the things I would like the change is the server header which at the moment is set as Werkzeug/0.9.6 Python/2.7.6 to something my own chosing. But I can't seem to find anything in the documentation on how to do this.
[ "You can use Flask's make_response method to add or modify headers.\nfrom flask import make_response\n\n@app.route('/index')\ndef index():\n resp = make_response(\"Hello, World!\")\n resp.headers['server'] = 'ASD'\n return resp\n\n", "@bcarroll's answer works but it will bypass other processes defined in original process_response method such as set session cookie.\nTo avoid the above:\nclass localFlask(Flask):\n def process_response(self, response):\n #Every response will be processed here first\n response.headers['server'] = SERVER_NAME\n super(localFlask, self).process_response(response)\n return(response)\n\n", "You can change the Server header for every response by overriding the Flask.process_response() method.\n from flask import Flask\n from flask import Response\n\n SERVER_NAME = 'Custom Flask Web Server v0.1.0'\n\n class localFlask(Flask):\n def process_response(self, response):\n #Every response will be processed here first\n response.headers['server'] = SERVER_NAME\n return(response)\n\n app = localFlask(__name__)\n\n\n @app.route('/')\n def index():\n return('<h2>INDEX</h2>')\n\n @app.route('/test')\n def test():\n return('<h2>This is a test</h2>')\n\nhttp://flask.pocoo.org/docs/0.12/api/#flask.Flask.process_response\n", "Overriding Server header in code does not work if You use production server like gunicorn. The better way is to use proxy server behind gunicorn and there change Server header.\n", "TL;DR - overwrite /python3.8/http/server.py send_response method. Comment the server header addition line.\nWhy?\nAdding/Manipulating headers in flask (in any way that mentioned above) will fire the response with the configured headers from flask to the web server but the WSGI logic (which happens independently, after & before flask logic) will be the last one to modify those values if any.\nIn your case(Werkzeug) some headers are hard-coded in python http module which werkzeug depending on. The server header is one of them.\n", "Easy way:\n@app.after_request\ndef changeserver(response):\n response.headers['server'] = SERVER_NAME\n return response\n\n" ]
[ 13, 8, 5, 3, 0, 0 ]
[]
[]
[ "flask", "python", "werkzeug" ]
stackoverflow_0027365298_flask_python_werkzeug.txt
Q: Remove elements from a list based on a condition in Python, problem: loop removes only the first instance For each element in my list I'd like to check: if it includes 'strategies available for player', or is it equal to '\n' If yes, the element should be removed. I've written a loop to iterate over the list. It removes the first instance of 'strategies availbale for player' just fine but totally ignores the second one. I have no idea why. What am I missing? I can handle it some other way but I would like to understand what is happening here. a_list = ['-2 strategies available for player-\n', 'd1 = c(0.0216,0.0519,0.0714,0.0942,0.1050);\n', 'd2 = c(0.0382,0.0475,0.0526,0.0768,0.1173);\n', 'd3 = c(0.0297,0.0561,0.0822,0.0834,0.1321);\n', 'd4 = c(0.1179,0.1233,0.1351,0.1369,0.1669);\n', 'd5 = c(0.0143,0.0256,0.0294,0.0366,0.0461);\n', 'd6 = c(0.03300,0.0535,0.0832,0.0867,0.1014);\n', 'd7 = c(0.0661,0.0921,0.1205,0.1398,0.1650);\n', 'd8 = c(0.0629,0.08316,0.1210,0.1467,0.1642);\n', '\n', '-3 strategies available for player-\n', 'd1 = c(0.0594,0.0691,0.0797,0.1020,0.1134);\n', 'd2 = c(0.0613,0.0737,0.1075,0.1160,0.1299);\n', 'd3 = c(0.1082,0.1216,0.1343,0.1410,0.1495);\n', 'd4 = c(0.0949,0.1086,0.1288,0.1506,0.1583);\n', 'd5 = c(0.0371,0.0498,0.0571,0.0688,0.0961);\n', 'd6 = c(0.0752,0.0962,0.1056,0.1218,0.1465);\n', 'd7 = c(0.0849,0.1209,0.1321,0.1574,0.1663);\n', 'd8 = c(0.0737,0.1216,0.1498,0.1793,0.1923);'] for el in a_list: if 'strategies available for' in el or el == '\n': a_list.remove(el) for el in a_list: print(el) A: I would suggest to create another list using list comprehension and applying conditions accordingly: el = [x for x in a_list if not 'strategies available for' in x or x != '\n'] But, if you wish to remove the elements from the current list and without creating a new one, you SHOULD iterate from the end whenever you are trying to remove elements while in a loop. This does not mess up the indexing. for el in a_list[::-1]: if 'strategies available for' in el or el == '\n': a_list.remove(el)
Remove elements from a list based on a condition in Python, problem: loop removes only the first instance
For each element in my list I'd like to check: if it includes 'strategies available for player', or is it equal to '\n' If yes, the element should be removed. I've written a loop to iterate over the list. It removes the first instance of 'strategies availbale for player' just fine but totally ignores the second one. I have no idea why. What am I missing? I can handle it some other way but I would like to understand what is happening here. a_list = ['-2 strategies available for player-\n', 'd1 = c(0.0216,0.0519,0.0714,0.0942,0.1050);\n', 'd2 = c(0.0382,0.0475,0.0526,0.0768,0.1173);\n', 'd3 = c(0.0297,0.0561,0.0822,0.0834,0.1321);\n', 'd4 = c(0.1179,0.1233,0.1351,0.1369,0.1669);\n', 'd5 = c(0.0143,0.0256,0.0294,0.0366,0.0461);\n', 'd6 = c(0.03300,0.0535,0.0832,0.0867,0.1014);\n', 'd7 = c(0.0661,0.0921,0.1205,0.1398,0.1650);\n', 'd8 = c(0.0629,0.08316,0.1210,0.1467,0.1642);\n', '\n', '-3 strategies available for player-\n', 'd1 = c(0.0594,0.0691,0.0797,0.1020,0.1134);\n', 'd2 = c(0.0613,0.0737,0.1075,0.1160,0.1299);\n', 'd3 = c(0.1082,0.1216,0.1343,0.1410,0.1495);\n', 'd4 = c(0.0949,0.1086,0.1288,0.1506,0.1583);\n', 'd5 = c(0.0371,0.0498,0.0571,0.0688,0.0961);\n', 'd6 = c(0.0752,0.0962,0.1056,0.1218,0.1465);\n', 'd7 = c(0.0849,0.1209,0.1321,0.1574,0.1663);\n', 'd8 = c(0.0737,0.1216,0.1498,0.1793,0.1923);'] for el in a_list: if 'strategies available for' in el or el == '\n': a_list.remove(el) for el in a_list: print(el)
[ "I would suggest to create another list using list comprehension and applying conditions accordingly:\nel = [x for x in a_list if not 'strategies available for' in x or x != '\\n']\n\nBut, if you wish to remove the elements from the current list and without creating a new one, you SHOULD iterate from the end whenever you are trying to remove elements while in a loop. This does not mess up the indexing.\nfor el in a_list[::-1]:\n if 'strategies available for' in el or el == '\\n':\n a_list.remove(el)\n\n" ]
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074590287_list_python.txt
Q: Update table in SQLite based on other table I have two tables, A and B. Due to wrongly specified loop I need to delete some rows from table A (25k rows). The tables looks as follows: CREATE TABLE "A" ( "tournament" INTEGER, "year" INTEGER, "course" INTEGER, "round" INTEGER, "hole" INTEGER, "front" INTEGER, "side" INTEGER, "region" INTEGER ); and CREATE TABLE "B" ( "tournament" INTEGER, "year" INTEGER, "R1" INTEGER, "R2" INTEGER, "R3" INTEGER, "R4" INTEGER, ); The columns R1, R2, R3 and R4 specify which course (from table A) was used in that round (from table A). To show whats going wrong in Table A 33 2016 895 1 1 12 5 L 33 2016 895 1 2 18 10 R 33 2016 895 1 3 15 7 R 33 2016 895 1 4 11 7 R 33 2016 895 1 5 18 7 L 33 2016 895 1 6 28 5 L 33 2016 895 1 7 21 12 R 33 2016 895 1 8 14 4 L 33 2016 895 1 9 10 5 R 33 2016 895 1 10 11 4 R 33 2016 880 1 1 12 5 L 33 2016 880 1 2 18 10 R 33 2016 880 1 3 15 7 R 33 2016 880 1 4 11 7 R 33 2016 880 1 5 18 7 L 33 2016 880 1 6 28 5 L 33 2016 880 1 7 21 12 R 33 2016 880 1 8 14 4 L 33 2016 880 1 9 10 5 R 33 2016 880 1 10 11 4 R 33 2016 715 1 1 12 5 L 33 2016 715 1 2 18 10 R 33 2016 715 1 3 15 7 R 33 2016 715 1 4 11 7 R 33 2016 715 1 5 18 7 L 33 2016 715 1 6 28 5 L 33 2016 715 1 7 21 12 R 33 2016 715 1 8 14 4 L 33 2016 715 1 9 10 5 R 33 2016 715 1 10 11 4 R Table B looks for this particular example like 33 2016 715 715 715 715 So, the data should only have been inserted for course 715. I think I need to loop over B and get the course-codes for each tournament-year-round combination and only keep these data buckets in A. How can I do this? Thanks A: The simplest way to get all the Rx values from table B is with UNION in a CTE. Then use NOT IN in the DELETE statement to delete all rows of table A with a course that does not exist in the CTE: WITH cte AS ( SELECT R1 FROM B UNION SELECT R2 FROM B UNION SELECT R3 FROM B UNION SELECT R4 FROM B ) DELETE FROM A WHERE course NOT IN cte; See the demo. or, with NOT EXISTS: DELETE FROM A WHERE NOT EXISTS ( SELECT * FROM B WHERE A.course IN (B.R1, B.R2, B.R3, B.R4) ); See the demo. If you need the columns tournament and year in the conditions also, change to: WITH cte AS ( SELECT tournament, year, R1 FROM B UNION SELECT tournament, year, R2 FROM B UNION SELECT tournament, year, R3 FROM B UNION SELECT tournament, year, R4 FROM B ) DELETE FROM A WHERE (tournament, year, course) NOT IN cte; See the demo. or: DELETE FROM A WHERE NOT EXISTS ( SELECT * FROM B WHERE B.tournament = A.tournament AND B.year = A.year AND A.course IN (B.R1, B.R2, B.R3, B.R4) ); See the demo.
Update table in SQLite based on other table
I have two tables, A and B. Due to wrongly specified loop I need to delete some rows from table A (25k rows). The tables looks as follows: CREATE TABLE "A" ( "tournament" INTEGER, "year" INTEGER, "course" INTEGER, "round" INTEGER, "hole" INTEGER, "front" INTEGER, "side" INTEGER, "region" INTEGER ); and CREATE TABLE "B" ( "tournament" INTEGER, "year" INTEGER, "R1" INTEGER, "R2" INTEGER, "R3" INTEGER, "R4" INTEGER, ); The columns R1, R2, R3 and R4 specify which course (from table A) was used in that round (from table A). To show whats going wrong in Table A 33 2016 895 1 1 12 5 L 33 2016 895 1 2 18 10 R 33 2016 895 1 3 15 7 R 33 2016 895 1 4 11 7 R 33 2016 895 1 5 18 7 L 33 2016 895 1 6 28 5 L 33 2016 895 1 7 21 12 R 33 2016 895 1 8 14 4 L 33 2016 895 1 9 10 5 R 33 2016 895 1 10 11 4 R 33 2016 880 1 1 12 5 L 33 2016 880 1 2 18 10 R 33 2016 880 1 3 15 7 R 33 2016 880 1 4 11 7 R 33 2016 880 1 5 18 7 L 33 2016 880 1 6 28 5 L 33 2016 880 1 7 21 12 R 33 2016 880 1 8 14 4 L 33 2016 880 1 9 10 5 R 33 2016 880 1 10 11 4 R 33 2016 715 1 1 12 5 L 33 2016 715 1 2 18 10 R 33 2016 715 1 3 15 7 R 33 2016 715 1 4 11 7 R 33 2016 715 1 5 18 7 L 33 2016 715 1 6 28 5 L 33 2016 715 1 7 21 12 R 33 2016 715 1 8 14 4 L 33 2016 715 1 9 10 5 R 33 2016 715 1 10 11 4 R Table B looks for this particular example like 33 2016 715 715 715 715 So, the data should only have been inserted for course 715. I think I need to loop over B and get the course-codes for each tournament-year-round combination and only keep these data buckets in A. How can I do this? Thanks
[ "The simplest way to get all the Rx values from table B is with UNION in a CTE.\nThen use NOT IN in the DELETE statement to delete all rows of table A with a course that does not exist in the CTE:\nWITH cte AS (\n SELECT R1 FROM B \n UNION \n SELECT R2 FROM B \n UNION \n SELECT R3 FROM B \n UNION \n SELECT R4 FROM B\n)\nDELETE FROM A\nWHERE course NOT IN cte;\n\nSee the demo.\nor, with NOT EXISTS:\nDELETE FROM A\nWHERE NOT EXISTS (\n SELECT *\n FROM B\n WHERE A.course IN (B.R1, B.R2, B.R3, B.R4)\n);\n\nSee the demo.\nIf you need the columns tournament and year in the conditions also, change to:\nWITH cte AS (\n SELECT tournament, year, R1 FROM B \n UNION \n SELECT tournament, year, R2 FROM B \n UNION \n SELECT tournament, year, R3 FROM B \n UNION \n SELECT tournament, year, R4 FROM B\n)\nDELETE FROM A\nWHERE (tournament, year, course) NOT IN cte;\n\nSee the demo.\nor:\nDELETE FROM A\nWHERE NOT EXISTS (\n SELECT *\n FROM B\n WHERE B.tournament = A.tournament\n AND B.year = A.year \n AND A.course IN (B.R1, B.R2, B.R3, B.R4)\n);\n\nSee the demo.\n" ]
[ 1 ]
[]
[]
[ "common_table_expression", "python", "sql", "sql_delete", "sqlite" ]
stackoverflow_0074590084_common_table_expression_python_sql_sql_delete_sqlite.txt
Q: Given rows and cols, print a list of all seats in a theater Sample input: 2 3 Expected output: 1A 1B 1C 2A 2B 2C Current code: num_rows = int(input()) num_cols = int(input()) k='A' for i in range(num_rows): for j in range(num_cols): print(f'{i+1}{k}',end=' ') k = chr(ord(k)+1) Current output: 1A 1B 1C 2D 2E 2F The letter does not start again at "A" for each row. How can I fix this? A: It looks like you have misplaced the k='A' line. The rest seems to be correct. num_rows = int(input()) num_cols = int(input()) for i in range(num_rows): k='A' for j in range(num_cols): print(f'{i+1}{k}',end=' ') k = chr(ord(k)+1) For your input this would output 1A 1B 1C 2A 2B 2C
Given rows and cols, print a list of all seats in a theater
Sample input: 2 3 Expected output: 1A 1B 1C 2A 2B 2C Current code: num_rows = int(input()) num_cols = int(input()) k='A' for i in range(num_rows): for j in range(num_cols): print(f'{i+1}{k}',end=' ') k = chr(ord(k)+1) Current output: 1A 1B 1C 2D 2E 2F The letter does not start again at "A" for each row. How can I fix this?
[ "It looks like you have misplaced the k='A' line. The rest seems to be correct.\nnum_rows = int(input())\nnum_cols = int(input())\n\nfor i in range(num_rows):\n k='A'\n for j in range(num_cols):\n print(f'{i+1}{k}',end=' ')\n k = chr(ord(k)+1)\n\nFor your input this would output\n1A 1B 1C 2A 2B 2C \n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074590316_python.txt
Q: GROUP By in Django ORM for page in Django Admin I'm not very long in Django, sorry for the probably stupid question. But after many hours of trying to solve and a huge number of searches on the Internet, I did not find a solution. My Models: class Offer(models.Model): seller = models.ForeignKey()<..> # other fields class OfferViewCount(models.Model): offer = models.ForeignKey(Offer, verbose_name=_('Offer'), on_delete=models.CASCADE) user_agent = models.CharField(verbose_name=_('User Agent'), max_length=200) ip_address = models.CharField(verbose_name=_('IP Address'), max_length=32) created_date = models.DateTimeField(auto_now_add=True) The database of the OfferViewCount model has the following data: id;user_agent;ip_address;created_date;offer_id 24;insomnia/2022.6.0f;127.0.0.1;2022-11-18 14:14:52.501008+00;192 25;insomnia/2022.6.0z;127.0.0.1;2022-11-18 15:03:31.471366+00;192 23;insomnia/2022.6.0;127.0.0.1;2022-11-18 14:14:49.840141+00;193 28;insomnia/2022.6.0;127.0.0.1;2022-11-18 15:04:18.867051+00;195 29;insomnia/2022.6.0;127.0.0.1;2022-11-21 11:33:15.719524+00;195 30;test;127.0.1.1;2022-11-22 19:34:39+00;195 If I use the default output in Django Admin like this: class OfferViewCountAdmin(admin.ModelAdmin): list_display = ('offer',) I get this: Offer offer #192 offer #192 offer #193 offer #195 offer #195 offer #195 I want to get a result like this: Offer;Views offer #192;2 offer #193;1 offer #195;3 Simply put, I want to display one instance of each duplicate post in the admin, and display the total number of them in a custom field. In SQL it would look something like this: SELECT offer_id, COUNT(*) AS count FROM offer_offerviewcount GROUP BY offer_id ORDER BY COUNT DESC; I've tried many options, including overwriting get_queryset. In general, I managed to achieve the desired result like this: class OfferViewCountAdmin(admin.ModelAdmin): list_display = ('offer', 'get_views') list_filter = ['created_date', 'offer'] list_per_page = 20 def get_views(self, obj): return OfferViewCount.objects.filter(offer=obj.offer).count() def get_queryset(self, request): qs = OfferViewCount.objects.filter( ~Exists(OfferViewCount.objects.filter( Q(offer__lt=OuterRef('offer')) | Q(offer=OuterRef('offer'), pk__lt=OuterRef('pk')), offer=OuterRef('offer') )) ) return qs get_views.short_description = _('Views') But in this case, sorting by Views does not work. If I add it explicitly via admin_order_field for get_views, I get an error because there is no such field in the database. To avoid such an error, it is necessary to fasten the overwritten annotate queriset, something like this: qs = OfferViewCount.objects.filter( ~Exists(OfferViewCount.objects.filter( Q(offer__lt=OuterRef('offer')) | Q(offer=OuterRef('offer'), pk__lt=OuterRef('pk')), offer=OuterRef('offer') )) ).annotate(_views_count=Count('offer')) And change get_views to: def get_views(self, obj): return obj._views_count But in this case, Count('offer') always returns 1, probably because not the entire base is analyzed there. Actually, tell me, please, how to add a working sorting? If there is some much simpler way (without ~Exists and constructions with Q()|Q()). A: you should use the Django group by like below def get_queryset(self, request): qs = OfferViewCount.objects.values("offer") .annotate(count=Count("offer")).distinct().order_by("count") return qs A: You can use below queryset for group by query from django.db.models import Count def get_queryset(self, request): qs = OfferViewCount.objects.values( 'offer' ).annotate( offer_count=Count('id') ).order_by("-offer_count") return qs In mysql raw query like, SELECT `offer_offerviewcount`.`offer_id`, COUNT(`offer_offerviewcount`.`id`) AS `offer_count` FROM `offer_offerviewcount` GROUP BY `offer_offerviewcount`.`offer_id` ORDER BY `offer_count` DESC But if you use admin default change_list template then this query gives you an error. Because django admin when render values in template expect list of objects in queryset and group_by query return in queryset as list of dict. If you want to use above query, then you override change_list template and rendered data itself.
GROUP By in Django ORM for page in Django Admin
I'm not very long in Django, sorry for the probably stupid question. But after many hours of trying to solve and a huge number of searches on the Internet, I did not find a solution. My Models: class Offer(models.Model): seller = models.ForeignKey()<..> # other fields class OfferViewCount(models.Model): offer = models.ForeignKey(Offer, verbose_name=_('Offer'), on_delete=models.CASCADE) user_agent = models.CharField(verbose_name=_('User Agent'), max_length=200) ip_address = models.CharField(verbose_name=_('IP Address'), max_length=32) created_date = models.DateTimeField(auto_now_add=True) The database of the OfferViewCount model has the following data: id;user_agent;ip_address;created_date;offer_id 24;insomnia/2022.6.0f;127.0.0.1;2022-11-18 14:14:52.501008+00;192 25;insomnia/2022.6.0z;127.0.0.1;2022-11-18 15:03:31.471366+00;192 23;insomnia/2022.6.0;127.0.0.1;2022-11-18 14:14:49.840141+00;193 28;insomnia/2022.6.0;127.0.0.1;2022-11-18 15:04:18.867051+00;195 29;insomnia/2022.6.0;127.0.0.1;2022-11-21 11:33:15.719524+00;195 30;test;127.0.1.1;2022-11-22 19:34:39+00;195 If I use the default output in Django Admin like this: class OfferViewCountAdmin(admin.ModelAdmin): list_display = ('offer',) I get this: Offer offer #192 offer #192 offer #193 offer #195 offer #195 offer #195 I want to get a result like this: Offer;Views offer #192;2 offer #193;1 offer #195;3 Simply put, I want to display one instance of each duplicate post in the admin, and display the total number of them in a custom field. In SQL it would look something like this: SELECT offer_id, COUNT(*) AS count FROM offer_offerviewcount GROUP BY offer_id ORDER BY COUNT DESC; I've tried many options, including overwriting get_queryset. In general, I managed to achieve the desired result like this: class OfferViewCountAdmin(admin.ModelAdmin): list_display = ('offer', 'get_views') list_filter = ['created_date', 'offer'] list_per_page = 20 def get_views(self, obj): return OfferViewCount.objects.filter(offer=obj.offer).count() def get_queryset(self, request): qs = OfferViewCount.objects.filter( ~Exists(OfferViewCount.objects.filter( Q(offer__lt=OuterRef('offer')) | Q(offer=OuterRef('offer'), pk__lt=OuterRef('pk')), offer=OuterRef('offer') )) ) return qs get_views.short_description = _('Views') But in this case, sorting by Views does not work. If I add it explicitly via admin_order_field for get_views, I get an error because there is no such field in the database. To avoid such an error, it is necessary to fasten the overwritten annotate queriset, something like this: qs = OfferViewCount.objects.filter( ~Exists(OfferViewCount.objects.filter( Q(offer__lt=OuterRef('offer')) | Q(offer=OuterRef('offer'), pk__lt=OuterRef('pk')), offer=OuterRef('offer') )) ).annotate(_views_count=Count('offer')) And change get_views to: def get_views(self, obj): return obj._views_count But in this case, Count('offer') always returns 1, probably because not the entire base is analyzed there. Actually, tell me, please, how to add a working sorting? If there is some much simpler way (without ~Exists and constructions with Q()|Q()).
[ "you should use the Django group by like below\ndef get_queryset(self, request):\n qs = OfferViewCount.objects.values(\"offer\")\n .annotate(count=Count(\"offer\")).distinct().order_by(\"count\")\n return qs\n\n", "You can use below queryset for group by query\nfrom django.db.models import Count\n\ndef get_queryset(self, request):\n qs = OfferViewCount.objects.values(\n 'offer'\n ).annotate(\n offer_count=Count('id')\n ).order_by(\"-offer_count\")\n return qs\n\nIn mysql raw query like,\nSELECT \n`offer_offerviewcount`.`offer_id`, \nCOUNT(`offer_offerviewcount`.`id`) AS `offer_count` \nFROM `offer_offerviewcount` \nGROUP BY `offer_offerviewcount`.`offer_id` \nORDER BY `offer_count` DESC\n\nBut if you use admin default change_list template then this query gives you an error. Because django admin when render values in template expect list of objects in queryset and group_by query return in queryset as list of dict.\nIf you want to use above query, then you override change_list template and rendered data itself.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "django_queryset", "python" ]
stackoverflow_0074575988_django_django_admin_django_models_django_queryset_python.txt
Q: How to measure objects in different planes with OpenCv and a single camera I'm working on a project where I need to track markers placed in a person. The person will be walking on a treadmill. I will use a single camera for each side. I already calibrated the cameras, but now I'm trying to understand how to solve a problem. The problem is: the person will be walking and consequently the plane of the marker will change a bit, e.g, the marker on the shoulder can get closer to the camera sometimes if the person moves a bit to the side. I can't measure distances using depth because I'm only using one camera for each side. So, I discovered that Aruco markers could keep the same scale even if the plane changes (the distance between the camera and the object). But to use these markers I'll need to attach an Aruco marker to each marker that will be placed on the person's body. It doesn't seem to be a very "simple" solution. However, at this moment, this is the best solution that I'm thinking about. Does anyone have another idea to overcome this problem? A: If the treadmill is always the same, you might use it as a "calibration object" to fix scale. Build (or find online) a 3d model for it, position it on the image in a 3d modeling tool (e.g. Blender), then work out, e.g., the position of its "walk plane" w.r.t. the camera.
How to measure objects in different planes with OpenCv and a single camera
I'm working on a project where I need to track markers placed in a person. The person will be walking on a treadmill. I will use a single camera for each side. I already calibrated the cameras, but now I'm trying to understand how to solve a problem. The problem is: the person will be walking and consequently the plane of the marker will change a bit, e.g, the marker on the shoulder can get closer to the camera sometimes if the person moves a bit to the side. I can't measure distances using depth because I'm only using one camera for each side. So, I discovered that Aruco markers could keep the same scale even if the plane changes (the distance between the camera and the object). But to use these markers I'll need to attach an Aruco marker to each marker that will be placed on the person's body. It doesn't seem to be a very "simple" solution. However, at this moment, this is the best solution that I'm thinking about. Does anyone have another idea to overcome this problem?
[ "If the treadmill is always the same, you might use it as a \"calibration object\" to fix scale. Build (or find online) a 3d model for it, position it on the image in a 3d modeling tool (e.g. Blender), then work out, e.g., the position of its \"walk plane\" w.r.t. the camera.\n" ]
[ 0 ]
[]
[]
[ "computer_vision", "opencv", "python" ]
stackoverflow_0074563856_computer_vision_opencv_python.txt
Q: Is there a way in Django where the superadmin can create normal users and the users gets an email with the credentials that was created for them? I am having troubles about how to implement a scenario I am working on. I'm new to web dev so please pardon my naivety. I am using the default Django admin panel, where I have logged in with a super admin I created. The app doesn't have a sign up view so only the admin will be able to create new users. The normal users will them receive an email with their credential. So that they can login with through the LoginAPIView. views.py class LoginView(APIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255) password = serializers.CharField(min_length=8, write_only=True) class Meta: model = User fields = ["email", "password"] def validate(self, attrs): email = attrs.get("email") password = attrs.get("password") user = auth.authenticate(username=email, password=password) if not user: raise AuthenticationFailed("Invalid credentials") if not user.is_active: raise AuthenticationFailed("Account is not active, please contain admin") return {"email": user.email} models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email or not password: raise ValueError("Users must have both email and password") email = self.normalize_email(email).lower() user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): if not password: raise ValueError("Password is required") user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): # user data email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) # status is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) # timestamps created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return self.email admin.py from django.contrib import admin from authentication.models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display = ("email", "first_name","last_name") How do I go about implementing the logic where the admin creates a user from the admin panel and the user receives the credentials to login. I also have a SignUpView below incase I it is needed. views.py class SignUpView(APIView): serializer_class = RegisterSerializer def post(self, request, *args): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data return Response(user_data, status=status.HTTP_201_CREATED) Thanks in advance.! A: You can use create Admin actions that sends emails utilizing the send_email function when an account is created. Admin Actions - https://docs.djangoproject.com/en/3.2/ref/contrib/admin/actions/ send_email - https://docs.djangoproject.com/en/4.1/topics/email/
Is there a way in Django where the superadmin can create normal users and the users gets an email with the credentials that was created for them?
I am having troubles about how to implement a scenario I am working on. I'm new to web dev so please pardon my naivety. I am using the default Django admin panel, where I have logged in with a super admin I created. The app doesn't have a sign up view so only the admin will be able to create new users. The normal users will them receive an email with their credential. So that they can login with through the LoginAPIView. views.py class LoginView(APIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255) password = serializers.CharField(min_length=8, write_only=True) class Meta: model = User fields = ["email", "password"] def validate(self, attrs): email = attrs.get("email") password = attrs.get("password") user = auth.authenticate(username=email, password=password) if not user: raise AuthenticationFailed("Invalid credentials") if not user.is_active: raise AuthenticationFailed("Account is not active, please contain admin") return {"email": user.email} models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email or not password: raise ValueError("Users must have both email and password") email = self.normalize_email(email).lower() user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): if not password: raise ValueError("Password is required") user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): # user data email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) # status is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) # timestamps created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return self.email admin.py from django.contrib import admin from authentication.models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): list_display = ("email", "first_name","last_name") How do I go about implementing the logic where the admin creates a user from the admin panel and the user receives the credentials to login. I also have a SignUpView below incase I it is needed. views.py class SignUpView(APIView): serializer_class = RegisterSerializer def post(self, request, *args): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data return Response(user_data, status=status.HTTP_201_CREATED) Thanks in advance.!
[ "You can use create Admin actions that sends emails utilizing the send_email function when an account is created.\nAdmin Actions - https://docs.djangoproject.com/en/3.2/ref/contrib/admin/actions/\nsend_email - https://docs.djangoproject.com/en/4.1/topics/email/\n" ]
[ 1 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074586852_django_django_rest_framework_python.txt
Q: How to add date stamps on the images using Python library to create noise in the image How to add date stamps on the image frames using Python library to create noise in the image I tried the below but would like to know how to add it as part of the image frame from datetime import datetime datetime.now().strftime('%Y-%m-%d %H:%M:%S') import pandas as pd print(pd.datetime.now()) A: From this article, you can understand how add watermark on image. I modified code from that website to add timestamp as watermark using python Pillow library. from datetime import datetime from PIL import Image, ImageDraw, ImageFont im = Image.open('image.jpg') width, height = im.size draw = ImageDraw.Draw(im) text = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) font = ImageFont.truetype('arial.ttf', 36) textwidth, textheight = draw.textsize(text, font) margin = 10 x = width - textwidth - margin y = height - textheight - margin draw.text((x, y), text, font=font) im.show() im.save('watermark.jpg')
How to add date stamps on the images using Python library to create noise in the image
How to add date stamps on the image frames using Python library to create noise in the image I tried the below but would like to know how to add it as part of the image frame from datetime import datetime datetime.now().strftime('%Y-%m-%d %H:%M:%S') import pandas as pd print(pd.datetime.now())
[ "From this article, you can understand how add watermark on image.\nI modified code from that website to add timestamp as watermark using python Pillow library.\n\n\nfrom datetime import datetime\nfrom PIL import Image, ImageDraw, ImageFont\nim = Image.open('image.jpg')\nwidth, height = im.size\ndraw = ImageDraw.Draw(im)\ntext = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\nfont = ImageFont.truetype('arial.ttf', 36)\ntextwidth, textheight = draw.textsize(text, font)\nmargin = 10\nx = width - textwidth - margin\ny = height - textheight - margin\ndraw.text((x, y), text, font=font)\nim.show()\nim.save('watermark.jpg')\n\n\n\n" ]
[ 0 ]
[]
[]
[ "autoencoder", "deep_learning", "python" ]
stackoverflow_0074590071_autoencoder_deep_learning_python.txt
Q: Is there any good command to get pixel's gray value (in this case I'm working on a gray image) I found img.getpixel((i,j))[0] that works well, but I want to pick the gray value of pixels that have less gray value than T (T go grom 0 to 255). I tried the code below but it didn't work as I expected. #create a list to store results for each loop: J={} #picking gray value of pixels: totalgrayvalue=0 for i in range (width): for j in range (height): for T in range (255): if totalgrayvalue == (im_grey.getpixel((i,j)))[0] and in range (0,T): J[T] = totalgrayvalue A: Giving the complete answer would be no fun for you, so here are some thoughts and a little animation. Using Python for loops with images is really not very advisable, they are slow and error-prone. Try to favour vectorised code like Numpy or OpenCV in general. import cv2 import numpy as np # Load image im = cv2.imread('Mushroom1.jpg', cv2.IMREAD_GRAYSCALE) # Calculate total number of pixels in image nPixels = im.size # Iterate over the possible threshold values, skipping 10 at a time for speed of development/checking for T in range(1,255,10): # Make all pixels under threshold black, leaving those above threshold unchanged thresholded = (im < T) * im # Save the image for debug and animation cv2.imwrite(f'DEBUG-T{T:03}.png', thresholded) # Count the non-zero and deduce the zero pixels nonZero = cv2.countNonZero(thresholded) Zero = nPixels - nonZero # Sum the non-zero pixels sum = np.sum(thresholded) # Print some statistics print(f'T={T}, zero={Zero}, nonZero={nonZero}, sum={sum}') Sample Output T=1, zero=272640, nonZero=0, sum=0 T=11, zero=241004, nonZero=31636, sum=155929 T=21, zero=225472, nonZero=47168, sum=387872 T=31, zero=217889, nonZero=54751, sum=576313 T=41, zero=214256, nonZero=58384, sum=703371 T=51, zero=212088, nonZero=60552, sum=801384 T=61, zero=210347, nonZero=62293, sum=897791 T=71, zero=208741, nonZero=63899, sum=1002737 T=81, zero=206957, nonZero=65683, sum=1137514 T=91, zero=205196, nonZero=67444, sum=1288089 T=101, zero=203262, nonZero=69378, sum=1472991 T=111, zero=200945, nonZero=71695, sum=1717630 T=121, zero=198389, nonZero=74251, sum=2012972 T=131, zero=195386, nonZero=77254, sum=2390555 T=141, zero=191845, nonZero=80795, sum=2870781 T=151, zero=187409, nonZero=85231, sum=3517150 T=161, zero=181320, nonZero=91320, sum=4465922 T=171, zero=171610, nonZero=101030, sum=6076646 T=181, zero=156768, nonZero=115872, sum=8686503 T=191, zero=134692, nonZero=137948, sum=12787198 T=201, zero=105763, nonZero=166877, sum=18447591 T=211, zero=73061, nonZero=199579, sum=25171467 T=221, zero=42168, nonZero=230472, sum=31826825 T=231, zero=15384, nonZero=257256, sum=37855551 T=241, zero=5364, nonZero=267276, sum=40200454 T=251, zero=4926, nonZero=267714, sum=40306547 You might like to have a look at this code - just ignore the line numbers preceding the colon if you are unaccustomed to IPython, and be aware that it prints variables if you type their name: In [2]: import numpy as np In [3]: im = np.arange(7) In [4]: im Out[4]: array([0, 1, 2, 3, 4, 5, 6]) In [5]: mask = im < 3 In [6]: mask Out[6]: array([ True, True, True, False, False, False, False]) In [7]: im[mask].sum() # sum of values < 3 Out[7]: 3 In [8]: im[~mask].sum() # sum of values >= 3 Out[8]: 18
Is there any good command to get pixel's gray value (in this case I'm working on a gray image)
I found img.getpixel((i,j))[0] that works well, but I want to pick the gray value of pixels that have less gray value than T (T go grom 0 to 255). I tried the code below but it didn't work as I expected. #create a list to store results for each loop: J={} #picking gray value of pixels: totalgrayvalue=0 for i in range (width): for j in range (height): for T in range (255): if totalgrayvalue == (im_grey.getpixel((i,j)))[0] and in range (0,T): J[T] = totalgrayvalue
[ "Giving the complete answer would be no fun for you, so here are some thoughts and a little animation.\nUsing Python for loops with images is really not very advisable, they are slow and error-prone. Try to favour vectorised code like Numpy or OpenCV in general.\nimport cv2\nimport numpy as np\n\n# Load image\nim = cv2.imread('Mushroom1.jpg', cv2.IMREAD_GRAYSCALE)\n\n# Calculate total number of pixels in image\nnPixels = im.size\n\n# Iterate over the possible threshold values, skipping 10 at a time for speed of development/checking\nfor T in range(1,255,10):\n # Make all pixels under threshold black, leaving those above threshold unchanged\n thresholded = (im < T) * im\n # Save the image for debug and animation\n cv2.imwrite(f'DEBUG-T{T:03}.png', thresholded)\n\n # Count the non-zero and deduce the zero pixels\n nonZero = cv2.countNonZero(thresholded)\n Zero = nPixels - nonZero\n\n # Sum the non-zero pixels\n sum = np.sum(thresholded)\n\n # Print some statistics\n print(f'T={T}, zero={Zero}, nonZero={nonZero}, sum={sum}')\n\n\n\nSample Output\nT=1, zero=272640, nonZero=0, sum=0\nT=11, zero=241004, nonZero=31636, sum=155929\nT=21, zero=225472, nonZero=47168, sum=387872\nT=31, zero=217889, nonZero=54751, sum=576313\nT=41, zero=214256, nonZero=58384, sum=703371\nT=51, zero=212088, nonZero=60552, sum=801384\nT=61, zero=210347, nonZero=62293, sum=897791\nT=71, zero=208741, nonZero=63899, sum=1002737\nT=81, zero=206957, nonZero=65683, sum=1137514\nT=91, zero=205196, nonZero=67444, sum=1288089\nT=101, zero=203262, nonZero=69378, sum=1472991\nT=111, zero=200945, nonZero=71695, sum=1717630\nT=121, zero=198389, nonZero=74251, sum=2012972\nT=131, zero=195386, nonZero=77254, sum=2390555\nT=141, zero=191845, nonZero=80795, sum=2870781\nT=151, zero=187409, nonZero=85231, sum=3517150\nT=161, zero=181320, nonZero=91320, sum=4465922\nT=171, zero=171610, nonZero=101030, sum=6076646\nT=181, zero=156768, nonZero=115872, sum=8686503\nT=191, zero=134692, nonZero=137948, sum=12787198\nT=201, zero=105763, nonZero=166877, sum=18447591\nT=211, zero=73061, nonZero=199579, sum=25171467\nT=221, zero=42168, nonZero=230472, sum=31826825\nT=231, zero=15384, nonZero=257256, sum=37855551\nT=241, zero=5364, nonZero=267276, sum=40200454\nT=251, zero=4926, nonZero=267714, sum=40306547\n\n\nYou might like to have a look at this code - just ignore the line numbers preceding the colon if you are unaccustomed to IPython, and be aware that it prints variables if you type their name:\nIn [2]: import numpy as np\nIn [3]: im = np.arange(7)\nIn [4]: im\nOut[4]: array([0, 1, 2, 3, 4, 5, 6])\nIn [5]: mask = im < 3\nIn [6]: mask\nOut[6]: array([ True, True, True, False, False, False, False])\nIn [7]: im[mask].sum() # sum of values < 3\nOut[7]: 3\nIn [8]: im[~mask].sum() # sum of values >= 3\nOut[8]: 18\n\n" ]
[ 2 ]
[]
[]
[ "image_processing", "image_segmentation", "python", "python_imaging_library", "variance" ]
stackoverflow_0074582777_image_processing_image_segmentation_python_python_imaging_library_variance.txt
Q: Change values in a kivy storage Can someone tell me how to change a value in a kivy storage (JsonStore) ? Here is an example of what I have : from kivy.storage.jsonstore import JsonStore store = JsonStore("Test.json") store["MyDict"] = {"0":"H", "1":"A", "2":"Y"} print(store["MyDict"]) store["MyDict"]["1"] = "E" print(store["MyDict"]) This code work but when I look in the Test.json file, there is this dictionnary {"0":"H", "1":"A", "2":"Y"} instead of this one {"0":"H", "1":"E", "2":"Y"} I would like to use this as a normal dictionary. A: you cannot directly do this because that store object is not a dictionary. however, you can store your whole dictionary as one item in the store. In this example, entry is a Python dict. According to the kivy.storage documentation, the storage objects have put(), get(), exists(), delete() and find() methods. This code shows a printout of protected memeber _data of the object which is a dict but it should not be modified directly. from kivy.storage.jsonstore import JsonStore store = JsonStore("Test.json") MyDict = {"0": "H", "1": "A", "2": "Y"} store.put("settings", MyDict=MyDict) entry = store.get('settings')['MyDict'] entry["1"] = "E" store.put("settings", MyDict=MyDict) entry = store.get('settings')['MyDict'] print(f"protected member {store._data}") print(entry["1"])
Change values in a kivy storage
Can someone tell me how to change a value in a kivy storage (JsonStore) ? Here is an example of what I have : from kivy.storage.jsonstore import JsonStore store = JsonStore("Test.json") store["MyDict"] = {"0":"H", "1":"A", "2":"Y"} print(store["MyDict"]) store["MyDict"]["1"] = "E" print(store["MyDict"]) This code work but when I look in the Test.json file, there is this dictionnary {"0":"H", "1":"A", "2":"Y"} instead of this one {"0":"H", "1":"E", "2":"Y"} I would like to use this as a normal dictionary.
[ "you cannot directly do this because that store object is not a dictionary.\nhowever, you can store your whole dictionary as one item in the store.\nIn this example, entry is a Python dict. According to the kivy.storage documentation, the storage objects have put(), get(), exists(), delete() and find() methods. This code shows a printout of protected memeber _data of the object which is a dict but it should not be modified directly.\nfrom kivy.storage.jsonstore import JsonStore\n\nstore = JsonStore(\"Test.json\")\n\nMyDict = {\"0\": \"H\", \"1\": \"A\", \"2\": \"Y\"}\nstore.put(\"settings\", MyDict=MyDict)\n\nentry = store.get('settings')['MyDict']\nentry[\"1\"] = \"E\"\nstore.put(\"settings\", MyDict=MyDict)\nentry = store.get('settings')['MyDict']\nprint(f\"protected member {store._data}\")\nprint(entry[\"1\"])\n\n" ]
[ 1 ]
[]
[]
[ "kivy", "python", "storage" ]
stackoverflow_0074589758_kivy_python_storage.txt
Q: TypeError: translation() got an unexpected keyword argument 'codeset' I'm following a Python tutorial on youtube and need to create a django website, however I am unable to start, because when I enter "python manage.py runserver" I get the "TypeError: translation() got an unexpected keyword argument 'codeset'" message. I've run back the video like 20 times to see if I've missed anything, but no, because it's just the beginning of the django website tutorial. I've also tried typing python3 instead of python and some other options I saw on Stack Overflow, but none are really exactly relevant to the error message I'm getting. Perhaps someone knows how to fix this? I tried to start a development server by typing in "python manage.py runserver" which was supposed to start a django webserver at 127.0.0.1:8000 or something, but instead I got the error message specified in the title code: PS C:\Users\kaspa\PycharmProjects\PyShop> python manage.py runserver Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x00000145784C1F80> Traceback (most recent call last): File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\models.py", line 94, in <module> class Group(models.Model): File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\base.py", line 139, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\base.py", line 304, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\fields\related.py", line 1583, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\fields\related.py", line 1051, in create_many_to_many_intermediary_model 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 149, in __mod__ return str(self) % rhs ^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 113, in __text_cast return func(*self.__args, **self.__kw) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\__init__.py", line 75, in gettext return _trans.gettext(message) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 286, in gettext _default = _default or translation(settings.LANGUAGE_CODE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 199, in translation _translations[language] = DjangoTranslation(language) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 90, in __init__ self._init_translation_catalog() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 131, in _init_translation_catalog translation = self._new_gnu_trans(localedir) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 119, in _new_gnu_trans return gettext_module.translation( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: translation() got an unexpected keyword argument 'codeset ' A: I've also been following Mosh's Python course, ran into the same problem, came here for answers and then did some more research on my own. I'm a total beginner, I might me wrong, but in the tutorial, Mosh makes us install django 2.1 instead of the current version of django. The error "translation() got an unexpected keyword argument 'codeset'" basically means that python thinks there shouldn't be an argument called 'codeset' after the gettext_module.translation( that is in the code created with/(used in?) django 2.1. Turns out, in the python gettext documentation, "Changed in version 3.11: codeset parameter is removed.". So django 2.1 has some code that isn't reconized by python 3.11, which pops an error. Solution: 1- Deleted my python "PyShop" project. 2- Closed PyCharm. 3- Created a new "PyShop" project. 4- In the terminal, typed "pip uninstall django". 5- Then installed the current version of django by typing "pip install django" in the terminal (not pip install django==2.1 as shown in the tutorial). 6- Created the "pyshop" folder by typing "django-admin startproject pyshop ." in the terminal. 7- Typed "python manage.py runserver" in the terminal. And voila! No more error, because the current version of django doesn't create stuff with code that the current version of python doesn't recognize in it. New to python and stack overflow, sorry for some things I maybe wrote wrong or something :) A: RE: William Laflamme's solution: Your solution worked for me thank you. Just solution point 4, this was not necessary in my case as Django was not installed in the new virtual environment. Cheers!
TypeError: translation() got an unexpected keyword argument 'codeset'
I'm following a Python tutorial on youtube and need to create a django website, however I am unable to start, because when I enter "python manage.py runserver" I get the "TypeError: translation() got an unexpected keyword argument 'codeset'" message. I've run back the video like 20 times to see if I've missed anything, but no, because it's just the beginning of the django website tutorial. I've also tried typing python3 instead of python and some other options I saw on Stack Overflow, but none are really exactly relevant to the error message I'm getting. Perhaps someone knows how to fix this? I tried to start a development server by typing in "python manage.py runserver" which was supposed to start a django webserver at 127.0.0.1:8000 or something, but instead I got the error message specified in the title code: PS C:\Users\kaspa\PycharmProjects\PyShop> python manage.py runserver Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x00000145784C1F80> Traceback (most recent call last): File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\models.py", line 94, in <module> class Group(models.Model): File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\base.py", line 139, in __new__ new_class.add_to_class(obj_name, obj) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\base.py", line 304, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\fields\related.py", line 1583, in contribute_to_class self.remote_field.through = create_many_to_many_intermediary_model(self, cls) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\fields\related.py", line 1051, in create_many_to_many_intermediary_model 'verbose_name': _('%(from)s-%(to)s relationship') % {'from': from_, 'to': to}, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 149, in __mod__ return str(self) % rhs ^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 113, in __text_cast return func(*self.__args, **self.__kw) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\__init__.py", line 75, in gettext return _trans.gettext(message) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 286, in gettext _default = _default or translation(settings.LANGUAGE_CODE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 199, in translation _translations[language] = DjangoTranslation(language) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 90, in __init__ self._init_translation_catalog() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 131, in _init_translation_catalog translation = self._new_gnu_trans(localedir) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation\trans_real.py", line 119, in _new_gnu_trans return gettext_module.translation( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: translation() got an unexpected keyword argument 'codeset '
[ "I've also been following Mosh's Python course, ran into the same problem, came here for answers and then did some more research on my own.\nI'm a total beginner, I might me wrong, but in the tutorial, Mosh makes us install django 2.1 instead of the current version of django. The error \"translation() got an unexpected keyword argument 'codeset'\" basically means that python thinks there shouldn't be an argument called 'codeset' after the gettext_module.translation( that is in the code created with/(used in?) django 2.1.\nTurns out, in the python gettext documentation, \"Changed in version 3.11: codeset parameter is removed.\". So django 2.1 has some code that isn't reconized by python 3.11, which pops an error.\nSolution:\n1- Deleted my python \"PyShop\" project.\n2- Closed PyCharm.\n3- Created a new \"PyShop\" project.\n4- In the terminal, typed \"pip uninstall django\".\n5- Then installed the current version of django by typing \"pip install django\" in the terminal (not pip install django==2.1 as shown in the tutorial).\n6- Created the \"pyshop\" folder by typing \"django-admin startproject pyshop .\" in the terminal.\n7- Typed \"python manage.py runserver\" in the terminal.\nAnd voila! No more error, because the current version of django doesn't create stuff with code that the current version of python doesn't recognize in it.\nNew to python and stack overflow, sorry for some things I maybe wrote wrong or something :)\n", "RE: William Laflamme's solution:\nYour solution worked for me thank you. Just solution point 4, this was not necessary in my case as Django was not installed in the new virtual environment. Cheers!\n" ]
[ 0, 0 ]
[]
[]
[ "django", "manage.py", "python" ]
stackoverflow_0074406706_django_manage.py_python.txt
Q: How to merge 2 dataframe rows in a new dataframe row with pandas? I have 2 variables (dataframes) one is 47 colums wide and the other is 87, they are DF2 and DF2. Then I have a variable (dataframe) called full_data. Df1 and DF2 are two different subset of data I want to merge together once I find 2 rows are equal. I am doing everything I want so far besides appending the right value to the new dataframe. below is the line of code I have been playing around with: full_data = full_data.append(pd.concat([df1[i:i+1].copy(),df2[j:j+1]].copy(), axis=1), ignore_index = True) once I find the rows in both Df1 and DF2 are equal I am trying to read both those rows and put them one after the other as a single row in the variable full_data. What is happening right now is that the line of code is writting 2 rows and no one as I want. what I want is full_data.append(Df1 DF2) and right now I am getting full_data(i)=DF1 full_data(i+1)=DF2 Any help would be apreciated. EM full_data = full_data.append(pd.concat([df1[i:i+1].copy(),df2[j:j+1]].copy(), axis=1), ignore_index = True) A: In the end I solved my problem. Probably I was not clear enough but my question but what was happening when concatenating is that I was getting duplicated or multiple rows when the expected result was getting a single row concatenation. The issues was found to be with the indexing. Indexing had to be reset because of the way pandas works. I found an example and explanation here My solution here: df3 = df2[j:j+1].copy() df4 = df1[i:i+1].copy() full_data = full_data.append( pd.concat([df4.reset_index(drop=True), df3.reset_index(drop=True)], axis=1), ignore_index = True ) I first created a copy of my variables and then reset the indexes.
How to merge 2 dataframe rows in a new dataframe row with pandas?
I have 2 variables (dataframes) one is 47 colums wide and the other is 87, they are DF2 and DF2. Then I have a variable (dataframe) called full_data. Df1 and DF2 are two different subset of data I want to merge together once I find 2 rows are equal. I am doing everything I want so far besides appending the right value to the new dataframe. below is the line of code I have been playing around with: full_data = full_data.append(pd.concat([df1[i:i+1].copy(),df2[j:j+1]].copy(), axis=1), ignore_index = True) once I find the rows in both Df1 and DF2 are equal I am trying to read both those rows and put them one after the other as a single row in the variable full_data. What is happening right now is that the line of code is writting 2 rows and no one as I want. what I want is full_data.append(Df1 DF2) and right now I am getting full_data(i)=DF1 full_data(i+1)=DF2 Any help would be apreciated. EM full_data = full_data.append(pd.concat([df1[i:i+1].copy(),df2[j:j+1]].copy(), axis=1), ignore_index = True)
[ "In the end I solved my problem. Probably I was not clear enough but my question but what was happening when concatenating is that I was getting duplicated or multiple rows when the expected result was getting a single row concatenation.\nThe issues was found to be with the indexing. Indexing had to be reset because of the way pandas works.\nI found an example and explanation here\nMy solution here:\ndf3 = df2[j:j+1].copy()\ndf4 = df1[i:i+1].copy()\n\nfull_data = full_data.append(\n pd.concat([df4.reset_index(drop=True), df3.reset_index(drop=True)], axis=1),\n ignore_index = True\n)\n\nI first created a copy of my variables and then reset the indexes.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074586298_dataframe_pandas_python.txt
Q: Local file upload progress bar in console using Python I need to upload a file and show its stats to the user (as it shows on the console). Didn't find any library for this, the function can be as simple as showing the uploaded percentage (uploaded/filesize*100) and showing the uploaded size (20/50MB) with the upload speed and ETA. There's a nice library named alive-progress on printing out the progress bar. but I just don't have any idea on how to do this, like the simpler version of what is done on youtube-dl. A: You could use the sys lib. Using stdout & flush (more details here). import sys, time lenght_bar = 50 sys.stdout.write("Loading : |%s|" % (" " * lenght_bar)) sys.stdout.write("\b" * (lenght_bar+1)) #use backspace for i in range(lenght_bar): sys.stdout.write("▒") sys.stdout.flush() time.sleep(0.1) #process sys.stdout.write("| 100%") sys.stdout.write("\nDone") time.sleep(10) A: There is another way. Combining \r with print(text, end=''). I don't know how you're getting your uploaded_size so there is a sample code that should work anyway. import time #Progress bar def updateProgressBar(size_uploaded, size_file, size_bar=50): perc_uploaded = round(size_uploaded / size_file * 100) progress = round(perc_uploaded / 100 * size_bar) status_bar = f"-{'▒' * progress}{' ' * (size_bar - progress)}-" status_count = f"[{size_uploaded}/{size_file}MB]" #add your status_eta #add your status_speed print(f"\r{status_bar} | {status_count} | {perc_uploaded}%", end='') #using the carriage-return (\r) to "overwrite" the previous line #For the demo file_size = 2**16 #fake file size uploaded_size = 0 while uploaded_size < file_size: uploaded_size += 1 updateProgressBar(uploaded_size, file_size) print("\nDone!") time.sleep(10) I suggest that each time you're getting an update about your uploaded_size/ETA/upload_speed you call the updateProgressBar method. A: The following code should run on Python 3.7 or later. Just edit SRC_FILE and DEST_URL before copy and paste. import aiohttp import asyncio import os import aiofiles import math from tqdm import tqdm async def file_sender(file_name=None, chunk_size=65536): file_size = os.path.getsize(file_name) chunks = max(1, int(math.ceil(file_size / chunk_size))) progress = tqdm(desc=f"Uploading", total=file_size, unit="B", unit_scale=True, unit_divisor=1024) async with aiofiles.open(file_name, 'rb') as f: for _ in range(chunks): chunk = await f.read(chunk_size) progress.update(len(chunk)) yield chunk async def async_http_upload_from_file(src, dst): async with aiohttp.ClientSession() as session: await session.post(dst, data=file_sender(file_name=src)) SRC_FILE = 'path/to/your/file' DEST_URL = 'path/to/your/url' asyncio.run(async_http_upload_from_file(SRC_FILE, DEST_URL)) I think you can try using this URL for testing: DEST_URL = 'http://httpbin.org/post' A: The tqdm lib can do this. file_size = os.path.getsize(file_path) with open(file_path, 'rb') as f: with tqdm(desc=f"[INFO] Uploading", total=file_size, unit="B", unit_scale=True, unit_divisor=1024) as t: reader_wrapper = CallbackIOWrapper(t.update, f, "read") resp = httpx.post(url, files={'apk_file': reader_wrapper}) it looks like: [INFO] Uploading: 100%|██████████| 9.60M/9.60M [00:02<00:00, 3.85MB/s]
Local file upload progress bar in console using Python
I need to upload a file and show its stats to the user (as it shows on the console). Didn't find any library for this, the function can be as simple as showing the uploaded percentage (uploaded/filesize*100) and showing the uploaded size (20/50MB) with the upload speed and ETA. There's a nice library named alive-progress on printing out the progress bar. but I just don't have any idea on how to do this, like the simpler version of what is done on youtube-dl.
[ "You could use the sys lib.\nUsing stdout & flush (more details here).\nimport sys, time\n\nlenght_bar = 50\n\nsys.stdout.write(\"Loading : |%s|\" % (\" \" * lenght_bar))\nsys.stdout.write(\"\\b\" * (lenght_bar+1)) #use backspace\n\nfor i in range(lenght_bar):\n sys.stdout.write(\"▒\")\n sys.stdout.flush()\n time.sleep(0.1) #process\n\nsys.stdout.write(\"| 100%\")\nsys.stdout.write(\"\\nDone\")\n\ntime.sleep(10)\n\n", "There is another way. Combining \\r with print(text, end='').\nI don't know how you're getting your uploaded_size so there is a sample code that should work anyway.\nimport time\n\n#Progress bar\ndef updateProgressBar(size_uploaded, size_file, size_bar=50):\n perc_uploaded = round(size_uploaded / size_file * 100)\n progress = round(perc_uploaded / 100 * size_bar)\n\n status_bar = f\"-{'▒' * progress}{' ' * (size_bar - progress)}-\"\n status_count = f\"[{size_uploaded}/{size_file}MB]\"\n #add your status_eta\n #add your status_speed\n\n print(f\"\\r{status_bar} | {status_count} | {perc_uploaded}%\", end='')\n #using the carriage-return (\\r) to \"overwrite\" the previous line\n\n\n\n#For the demo\nfile_size = 2**16 #fake file size\nuploaded_size = 0\nwhile uploaded_size < file_size:\n uploaded_size += 1\n\n updateProgressBar(uploaded_size, file_size)\n\nprint(\"\\nDone!\")\n\ntime.sleep(10)\n\nI suggest that each time you're getting an update about your uploaded_size/ETA/upload_speed you call the updateProgressBar method.\n", "The following code should run on Python 3.7 or later.\nJust edit SRC_FILE and DEST_URL before copy and paste.\nimport aiohttp\nimport asyncio\nimport os\nimport aiofiles\nimport math\nfrom tqdm import tqdm\n\nasync def file_sender(file_name=None, chunk_size=65536):\n file_size = os.path.getsize(file_name)\n chunks = max(1, int(math.ceil(file_size / chunk_size)))\n progress = tqdm(desc=f\"Uploading\", total=file_size, unit=\"B\", unit_scale=True, unit_divisor=1024)\n async with aiofiles.open(file_name, 'rb') as f:\n for _ in range(chunks):\n chunk = await f.read(chunk_size)\n progress.update(len(chunk))\n yield chunk\n\nasync def async_http_upload_from_file(src, dst):\n async with aiohttp.ClientSession() as session:\n await session.post(dst, data=file_sender(file_name=src))\n\nSRC_FILE = 'path/to/your/file'\nDEST_URL = 'path/to/your/url'\n\nasyncio.run(async_http_upload_from_file(SRC_FILE, DEST_URL))\n\nI think you can try using this URL for testing:\nDEST_URL = 'http://httpbin.org/post'\n\n", "The tqdm lib can do this.\nfile_size = os.path.getsize(file_path)\nwith open(file_path, 'rb') as f:\n with tqdm(desc=f\"[INFO] Uploading\", total=file_size, unit=\"B\", unit_scale=True, unit_divisor=1024) as t:\n reader_wrapper = CallbackIOWrapper(t.update, f, \"read\")\n resp = httpx.post(url, files={'apk_file': reader_wrapper})\n\nit looks like:\n[INFO] Uploading: 100%|██████████| 9.60M/9.60M [00:02<00:00, 3.85MB/s]\n\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "pathlib", "progress_bar", "python", "python_3.x", "sys" ]
stackoverflow_0071160646_pathlib_progress_bar_python_python_3.x_sys.txt
Q: How to remove all balise in text python I want to extract data from a tag to simply retrieve the text. Unfortunately I can't extract just the text, I always have links in this one. Is it possible to remove all of the <img> and <a href> tags from my text? <div class="xxx" data-handler="xxx">its a good day <a class="link" href="https://" title="text">https:// link</a></div> I just want to recover this : its a good day and ignore the content of the <a href> tag in my <div> tag Currently I perform the extraction via a beautifulsoup.find('div) A: Try to do this import requests from bs4 import BeautifulSoup #response = requests.get('your url') html = BeautifulSoup('''<div class="xxx" data-handler="xxx">its a good day <a class="link" href="https://" title="text">https:// link</a> </div>''', 'html.parser') soup = html.find_all(class_='xxx') print(soup[0].text.split('\n')[0]) A: EDIT Based on your comment, that all text before <a> should be captured and not only the first one in element, select all previous_siblings and check for NavigableString: ' '.join( [s for s in soup.select_one('.xxx a').previous_siblings if isinstance(s, NavigableString)] ) Example from bs4 import Tag, NavigableString, BeautifulSoup html=''' <div class="xxx" data-handler="xxx"><br>New wallpaper <br>Find over 100+ of <a class="link" href="https://" title="text">https:// link</a></div> ''' soup = BeautifulSoup(html) ' '.join( [s for s in soup.select_one('.xxx a').previous_siblings if isinstance(s, NavigableString)] ) To focus just on the text and not the children tags of an element, you could use : .find(text=True) In case the pattern is always the same and text the first part of content in the element: .contents[0] Example from bs4 import BeautifulSoup html=''' <div class="xxx" data-handler="xxx">its a good day <a class="link" href="https://" title="text">https:// link</a></div> ''' soup = BeautifulSoup(html) soup.div.find(text=True).strip() Output its a good day A: Let's import re and use re.sub: import re s1 = '<div class="xxx" data-handler="xxx">its a good day' s2 = '<a class="link" href="https://" title="text">https:// link</a></div>' s1 = re.sub(r'\<[^()]*\>', '', s1) s2 = re.sub(r'\<[^()]*\>', '', s2) Output >>> print(s1) ... 'its a good day' >>> print(s2) ... '' A: So basically you don't want any text inside the <a> tags and everything within all tags. from bs4 import BeautifulSoup html1=''' <div class="xxx" data-handler="xxx"><br>New wallpaper <br>Find over 100+ of <a class="link" href="https://" title="text">https:// link </a></div> ''' html2 = ''' <div class="xxx" data-handler="xxx">its a good day <a class="link" href="https://" title="text">https:// link</a></div> ''' html3 = ''' <div class="xxx" data-handler="xxx"><br>New wallpaper <br>Find over 100+ of <a class="link" href="https://" title="text">https:// link </a><div class="xxx" data-handler="xxx">its a good day <a class="link" href="https://" title="text">https:// link</a></div></div> ''' soup = BeautifulSoup(html3,'html.parser') for t in soup.find_all('a', href=True): t.decompose() test = soup.find('div',class_='xxx').getText().strip() print(test) output: #for html1: New wallpaper Find over 100+ of #for html2: its a good day #for html3: New wallpaper Find over 100+ of its a good day
How to remove all balise in text python
I want to extract data from a tag to simply retrieve the text. Unfortunately I can't extract just the text, I always have links in this one. Is it possible to remove all of the <img> and <a href> tags from my text? <div class="xxx" data-handler="xxx">its a good day <a class="link" href="https://" title="text">https:// link</a></div> I just want to recover this : its a good day and ignore the content of the <a href> tag in my <div> tag Currently I perform the extraction via a beautifulsoup.find('div)
[ "Try to do this\nimport requests\nfrom bs4 import BeautifulSoup\n\n#response = requests.get('your url')\n\nhtml = BeautifulSoup('''<div class=\"xxx\" data-handler=\"xxx\">its a good day\n<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a> \n</div>''', 'html.parser')\n\nsoup = html.find_all(class_='xxx')\n\nprint(soup[0].text.split('\\n')[0])\n\n", "EDIT\nBased on your comment, that all text before <a> should be captured and not only the first one in element, select all previous_siblings and check for NavigableString:\n' '.join(\n [s for s in soup.select_one('.xxx a').previous_siblings if isinstance(s, NavigableString)]\n)\n\nExample\nfrom bs4 import Tag, NavigableString, BeautifulSoup\n\nhtml='''\n<div class=\"xxx\" data-handler=\"xxx\"><br>New wallpaper <br>Find over 100+ of <a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div>\n'''\nsoup = BeautifulSoup(html)\n\n' '.join(\n [s for s in soup.select_one('.xxx a').previous_siblings if isinstance(s, NavigableString)]\n)\n\n\nTo focus just on the text and not the children tags of an element, you could use :\n.find(text=True)\n\nIn case the pattern is always the same and text the first part of content in the element:\n.contents[0]\n\nExample\nfrom bs4 import BeautifulSoup\nhtml='''\n<div class=\"xxx\" data-handler=\"xxx\">its a good day\n<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div>\n'''\n\nsoup = BeautifulSoup(html)\n\nsoup.div.find(text=True).strip()\n\nOutput\nits a good day\n\n", "Let's import re and use re.sub:\nimport re \n\ns1 = '<div class=\"xxx\" data-handler=\"xxx\">its a good day'\ns2 = '<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div>'\n \n \ns1 = re.sub(r'\\<[^()]*\\>', '', s1)\ns2 = re.sub(r'\\<[^()]*\\>', '', s2)\n\nOutput\n>>> print(s1)\n... 'its a good day'\n>>> print(s2)\n... ''\n\n", "So basically you don't want any text inside the <a> tags and everything within all tags.\nfrom bs4 import BeautifulSoup\n\nhtml1='''\n<div class=\"xxx\" data-handler=\"xxx\"><br>New wallpaper <br>Find over 100+ of <a class=\"link\" href=\"https://\" title=\"text\">https:// link </a></div>\n'''\nhtml2 = ''' <div class=\"xxx\" data-handler=\"xxx\">its a good day\n<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div> '''\n\nhtml3 = ''' <div class=\"xxx\" data-handler=\"xxx\"><br>New wallpaper <br>Find over 100+ of <a class=\"link\" href=\"https://\" title=\"text\">https:// link </a><div class=\"xxx\" data-handler=\"xxx\">its a good day\n<a class=\"link\" href=\"https://\" title=\"text\">https:// link</a></div></div> '''\n\nsoup = BeautifulSoup(html3,'html.parser')\n\n\nfor t in soup.find_all('a', href=True):\n t.decompose()\ntest = soup.find('div',class_='xxx').getText().strip()\n\nprint(test)\n\noutput:\n#for html1: New wallpaper Find over 100+ of\n#for html2: its a good day\n#for html3: New wallpaper Find over 100+ of its a good day\n\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x", "web_scraping" ]
stackoverflow_0074589261_beautifulsoup_python_python_3.x_web_scraping.txt
Q: pyrogram.errors.exceptions.bad_request_400.PhoneCodeInvalid: Telegram says: [400 PHONE_CODE_INVALID] - The confirmation code is invalid pyrogram.errors.exceptions.bad_request_400.PhoneCodeInvalid: Telegram says: [400 PHONE_CODE_INVALID] - The confirmation code is invalid (caused by "auth.SignUp") When I want to sign up it says confirmation code is invalid but I didn't even input the confirmation code. I've been searching for a long time and I asked everywhere except stackowerflow. Can somebody help ? :/ I got the confirmation code btw but I can't input it. It gives this error and after that it sends the confirmation code. app = Client(name=number, api_id=api_id, api_hash=api_pass, phone_number=number) app.connect() sent_code = app.send_code(phone_number=number) app.sign_up(phone_number=number, phone_code_hash=sent_code.phone_code_hash, first_name = "dsadadsad", last_name = "asdadsa") A: Take confirmation code as input, then pass it in code. client = Client(f"sessions/{phone}", api_id, api_hash) client.connect() sent_code = client.send_code(phone) code = input("Enter the code : ") signed_in = client.sign_in(phone, sent_code.phone_code_hash, code)
pyrogram.errors.exceptions.bad_request_400.PhoneCodeInvalid: Telegram says: [400 PHONE_CODE_INVALID] - The confirmation code is invalid
pyrogram.errors.exceptions.bad_request_400.PhoneCodeInvalid: Telegram says: [400 PHONE_CODE_INVALID] - The confirmation code is invalid (caused by "auth.SignUp") When I want to sign up it says confirmation code is invalid but I didn't even input the confirmation code. I've been searching for a long time and I asked everywhere except stackowerflow. Can somebody help ? :/ I got the confirmation code btw but I can't input it. It gives this error and after that it sends the confirmation code. app = Client(name=number, api_id=api_id, api_hash=api_pass, phone_number=number) app.connect() sent_code = app.send_code(phone_number=number) app.sign_up(phone_number=number, phone_code_hash=sent_code.phone_code_hash, first_name = "dsadadsad", last_name = "asdadsa")
[ "Take confirmation code as input, then pass it in code.\nclient = Client(f\"sessions/{phone}\", api_id, api_hash)\n\nclient.connect()\n\nsent_code = client.send_code(phone)\n\ncode = input(\"Enter the code : \")\n\nsigned_in = client.sign_in(phone, sent_code.phone_code_hash, code)\n\n" ]
[ 0 ]
[]
[]
[ "pyrogram", "python", "telegram" ]
stackoverflow_0073910395_pyrogram_python_telegram.txt
Q: Selenium python driver doesn't click or press the key for the button all the times I'm using selenium to get to YouTube and write something on the search bar and then press the button or press the enter key. Both clicking or pressing a key does sometimes work, but sometimes it does not. I tried to wait with WebDriverWait, and I even changed the waiting time from 10 to 20 seconds, but it didn't make any difference. And if I add anything (like printing the new page title), it only shows me the first page title and not the title after the search. Here is my code and what I tried: from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def get_driver(): firefox_options = Options() # firefox_options.add_argument("--headless") driver = webdriver.Firefox(executable_path=r"C:\Program Files\Mozilla Firefox\geckodriver.exe", options=firefox_options) driver.implicitly_wait(9) return driver driver = get_driver() driver.get('https://www.youtube.com/') search = driver.find_element(By.XPATH, '//input[@id="search"]') search.send_keys("python") # search.send_keys(Keys.ENTER) #using the enter key # If I add nothing after this line it work # searchbutton = driver.find_element(By.XPATH,'//*[@id="search-icon-legacy"]') # This also dose doesn't work # searchbutton.click() # using the click method() #also dose not work WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="search-icon-legacy"]'))).click() # Sometimes work # driver.implicitly_wait(10) # print(driver.title) # This show me only the title of the first page not the one after the search Is it because I use the Firefox webdriver (should I change to Chrome)? Or is it because of my internet connection? A: To make this working you need to click the search field input first, then add a short delay and then send the Keys.ENTER or click search-icon-legacy element. So, this is not your fault, this is how YouTube webpage works. You may even call it a kind of bug. But since this webpage it built for human users it works good since human will never click on the input field and insert the search value there within zero time. Anyway, the 2 following codes are working: First. import time from selenium import webdriver from selenium.webdriver import Keys from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC options = Options() options.add_argument("start-maximized") options.add_argument('--disable-notifications') webdriver_service = Service('C:\webdrivers\chromedriver.exe') driver = webdriver.Chrome(options=options, service=webdriver_service) wait = WebDriverWait(driver, 10) url = "https://www.youtube.com/" driver.get(url) search = wait.until(EC.element_to_be_clickable((By.XPATH, '//input[@id="search"]'))) search.click() time.sleep(0.2) search.send_keys("python") wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="search-icon-legacy"]'))).click() Second. import time from selenium import webdriver from selenium.webdriver import Keys from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC options = Options() options.add_argument("start-maximized") options.add_argument('--disable-notifications') webdriver_service = Service('C:\webdrivers\chromedriver.exe') driver = webdriver.Chrome(options=options, service=webdriver_service) wait = WebDriverWait(driver, 10) url = "https://www.youtube.com/" driver.get(url) search = wait.until(EC.element_to_be_clickable((By.XPATH, '//input[@id="search"]'))) search.click() time.sleep(0.2) search.send_keys("python" + Keys.ENTER)
Selenium python driver doesn't click or press the key for the button all the times
I'm using selenium to get to YouTube and write something on the search bar and then press the button or press the enter key. Both clicking or pressing a key does sometimes work, but sometimes it does not. I tried to wait with WebDriverWait, and I even changed the waiting time from 10 to 20 seconds, but it didn't make any difference. And if I add anything (like printing the new page title), it only shows me the first page title and not the title after the search. Here is my code and what I tried: from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def get_driver(): firefox_options = Options() # firefox_options.add_argument("--headless") driver = webdriver.Firefox(executable_path=r"C:\Program Files\Mozilla Firefox\geckodriver.exe", options=firefox_options) driver.implicitly_wait(9) return driver driver = get_driver() driver.get('https://www.youtube.com/') search = driver.find_element(By.XPATH, '//input[@id="search"]') search.send_keys("python") # search.send_keys(Keys.ENTER) #using the enter key # If I add nothing after this line it work # searchbutton = driver.find_element(By.XPATH,'//*[@id="search-icon-legacy"]') # This also dose doesn't work # searchbutton.click() # using the click method() #also dose not work WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="search-icon-legacy"]'))).click() # Sometimes work # driver.implicitly_wait(10) # print(driver.title) # This show me only the title of the first page not the one after the search Is it because I use the Firefox webdriver (should I change to Chrome)? Or is it because of my internet connection?
[ "To make this working you need to click the search field input first, then add a short delay and then send the Keys.ENTER or click search-icon-legacy element.\nSo, this is not your fault, this is how YouTube webpage works. You may even call it a kind of bug. But since this webpage it built for human users it works good since human will never click on the input field and insert the search value there within zero time.\nAnyway, the 2 following codes are working:\nFirst.\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver import Keys\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\noptions = Options()\noptions.add_argument(\"start-maximized\")\noptions.add_argument('--disable-notifications')\n\nwebdriver_service = Service('C:\\webdrivers\\chromedriver.exe')\ndriver = webdriver.Chrome(options=options, service=webdriver_service)\nwait = WebDriverWait(driver, 10)\n\nurl = \"https://www.youtube.com/\"\ndriver.get(url)\n\nsearch = wait.until(EC.element_to_be_clickable((By.XPATH, '//input[@id=\"search\"]')))\nsearch.click()\ntime.sleep(0.2)\nsearch.send_keys(\"python\")\nwait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"search-icon-legacy\"]'))).click()\n\nSecond.\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver import Keys\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\noptions = Options()\noptions.add_argument(\"start-maximized\")\noptions.add_argument('--disable-notifications')\n\nwebdriver_service = Service('C:\\webdrivers\\chromedriver.exe')\ndriver = webdriver.Chrome(options=options, service=webdriver_service)\nwait = WebDriverWait(driver, 10)\n\nurl = \"https://www.youtube.com/\"\ndriver.get(url)\n\nsearch = wait.until(EC.element_to_be_clickable((By.XPATH, '//input[@id=\"search\"]')))\nsearch.click()\ntime.sleep(0.2)\nsearch.send_keys(\"python\" + Keys.ENTER)\n\n" ]
[ 2 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_testing", "webdriverwait" ]
stackoverflow_0074590398_python_selenium_selenium_webdriver_web_testing_webdriverwait.txt
Q: Comparing dictionary of list of dictionary/nested dictionary There are two dict main and input, I want to validate the "input" such that all the keys in the list of dictionary and nested dictionary (if present/all keys are optional) matches that of the main if not the wrong/different key should be returned as the output. main = "app":[{ "name": str, "info": [ { "role": str, "scope": {"groups": list} } ] },{ "name": str, "info": [ {"role": str} ] }] input_data = "app":[{ 'name': 'nms', 'info': [ { 'role': 'user', 'scope': {'groups': ['xyz'] } }] },{ 'name': 'abc', 'info': [ {'rol': 'user'} ] }] when compared input with main the wrong/different key should be given as output, in this case ['rol'] A: The schema module does exactly this. You can catch SchemaUnexpectedTypeError to see which data doesn't match your pattern. Also, make sure you don't use the word input as a variable name, as it's the name of a built-in function. A: keys = [] def print_dict(d): if type(d) == dict: for val in d.keys(): df = d[val] try: if type(df) == list: for i in range(0,len(df)): if type(df[i]) == dict: print_dict(df[i]) except AttributeError: pass keys.append(val) else: try: x = d[0] if type(x) == dict: print_dict(d[0]) except: pass return keys keys_input = print_dict(input) keys = [] keys_main = print_dict(main) print(keys_input) print(keys_main) for i in keys_input[:]: if i in keys_main: keys_input.remove(i) print(keys_input) This has worked for me. you can check above code snippet and if any changes provide more information so any chances if required. A: Dictionary and lists compare theire content nested by default. input_data == main should result in the right output if you format your dicts correctly. Try adding curly brackets "{"/"}" arround your dicts. It should probably look like something like this: main = {"app": [{ "name": str, "info": [ { "role": str, "scope": {"groups": list} } ] },{ "name": str, "info": [ {"role": str} ] }]} input_data = {"app":[{ 'name': 'nms', 'info': [ { 'role': 'user', 'scope': {'groups': ['xyz'] } }] },{ 'name': 'abc', 'info': [ {'rol': 'user'} ] }]} input_data2 = {"app": [{ 'name': 'nms', 'info': [ { 'role': 'user', 'scope': {'groups': ['xyz'] } }] }, { 'name': 'abc', 'info': [ {'rol': 'user'} ] }]} Comparision results should look like this: input_data2 == input_data # True main == input_data # False
Comparing dictionary of list of dictionary/nested dictionary
There are two dict main and input, I want to validate the "input" such that all the keys in the list of dictionary and nested dictionary (if present/all keys are optional) matches that of the main if not the wrong/different key should be returned as the output. main = "app":[{ "name": str, "info": [ { "role": str, "scope": {"groups": list} } ] },{ "name": str, "info": [ {"role": str} ] }] input_data = "app":[{ 'name': 'nms', 'info': [ { 'role': 'user', 'scope': {'groups': ['xyz'] } }] },{ 'name': 'abc', 'info': [ {'rol': 'user'} ] }] when compared input with main the wrong/different key should be given as output, in this case ['rol']
[ "The schema module does exactly this.\nYou can catch SchemaUnexpectedTypeError to see which data doesn't match your pattern.\nAlso, make sure you don't use the word input as a variable name, as it's the name of a built-in function.\n", "keys = []\ndef print_dict(d):\n if type(d) == dict:\n for val in d.keys():\n df = d[val]\n try:\n if type(df) == list:\n for i in range(0,len(df)):\n if type(df[i]) == dict:\n print_dict(df[i])\n except AttributeError:\n pass\n keys.append(val)\n else:\n try:\n x = d[0]\n if type(x) == dict:\n print_dict(d[0])\n except:\n pass\n return keys\nkeys_input = print_dict(input)\nkeys = []\nkeys_main = print_dict(main)\nprint(keys_input)\n\nprint(keys_main)\n\nfor i in keys_input[:]:\n if i in keys_main:\n keys_input.remove(i)\nprint(keys_input)\n\nThis has worked for me. you can check above code snippet and if any changes provide more information so any chances if required.\n", "Dictionary and lists compare theire content nested by default.\ninput_data == main should result in the right output if you format your dicts correctly. Try adding curly brackets \"{\"/\"}\" arround your dicts. It should probably look like something like this:\nmain = {\"app\": [{\n \"name\": str,\n \"info\": [\n {\n \"role\": str,\n \"scope\": {\"groups\": list}\n }\n ]\n },{\n \"name\": str,\n \"info\": [\n {\"role\": str}\n ]\n}]}\n\ninput_data = {\"app\":[{\n 'name': 'nms',\n 'info': [\n {\n 'role': 'user',\n 'scope': {'groups': ['xyz']\n }\n }]\n},{\n 'name': 'abc',\n 'info': [\n {'rol': 'user'}\n ]\n}]}\n\ninput_data2 = {\"app\": [{\n 'name': 'nms',\n 'info': [\n {\n 'role': 'user',\n 'scope': {'groups': ['xyz']\n }\n }]\n}, {\n 'name': 'abc',\n 'info': [\n {'rol': 'user'}\n ]\n}]}\n\nComparision results should look like this:\ninput_data2 == input_data # True\nmain == input_data # False\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "comparison", "dictionary", "list", "python", "recursion" ]
stackoverflow_0074531927_comparison_dictionary_list_python_recursion.txt
Q: How to make an application from two python programs? I have two python programs which one of them connects to a bluetooth device(socket package), it receives and saves data from device, and another one read the stored data and draw a real time plot. I should make one application from these two programs. I tried to mix these two python programs, but since bluetooth should wait to receive data (through a while loop), the other parts of program does not work. I tried to solve this problem using Clock.schedule_interval, but the program will hang after a period of time. So I decided to run these two programs simultaneously. I read, we can run some python programs at a same time using a python script. Is there any trick to join these two programs and build one application? Any help would be greatly appreciated. A: Install threaded: pip install threaded Create a new python file: from threading import Thread def runFile1(): import file1 def runFile2(): import file2 Thread(target=runFile1).start() runFile2() Run the new python file. A: It can be done with threading. To do communication between the threaded function and your main function, use objects such as queue.Queue and threading.Event. the bluetooth functions can be placed into a function that is the target of the thread import time from threading import Thread from queue import Queue class BlueToothFunctions(Thread): def __init__(self, my_queue): super().__init__() self.my_queue = my_queue # optional: causes this thread to end immediately if the main program is terminated self.daemon = True def run(self) -> None: while True: # do all the bluetooth stuff foreverer g = self.my_queue.get() if g == (None, None): break print(g) time.sleep(1.0) print("bluetooth closed") if __name__ == '__main__': _queue = Queue() # just one way to communicate to a thread # pass an object reference so both main and thread have a way to communicate on this common queue my_bluetooth = BlueToothFunctions(_queue) my_bluetooth.start() # creates the thread and executes run() method for i in range(5): # communicate to the threaded functions _queue.put(i) _queue.put((None, None)) # optional, a way to cause the thread to end my_bluetooth.join(timeout=5.0) # optional, pause here until thread ends print('program complete')
How to make an application from two python programs?
I have two python programs which one of them connects to a bluetooth device(socket package), it receives and saves data from device, and another one read the stored data and draw a real time plot. I should make one application from these two programs. I tried to mix these two python programs, but since bluetooth should wait to receive data (through a while loop), the other parts of program does not work. I tried to solve this problem using Clock.schedule_interval, but the program will hang after a period of time. So I decided to run these two programs simultaneously. I read, we can run some python programs at a same time using a python script. Is there any trick to join these two programs and build one application? Any help would be greatly appreciated.
[ "Install threaded:\npip install threaded\n\nCreate a new python file:\nfrom threading import Thread\n\ndef runFile1(): import file1\ndef runFile2(): import file2\n\nThread(target=runFile1).start()\nrunFile2()\n\nRun the new python file.\n", "It can be done with threading. To do communication between the threaded function and your main function, use objects such as queue.Queue and threading.Event.\nthe bluetooth functions can be placed into a function that is the target of the thread\nimport time\nfrom threading import Thread\nfrom queue import Queue\n\n\nclass BlueToothFunctions(Thread):\n def __init__(self, my_queue):\n super().__init__()\n self.my_queue = my_queue\n # optional: causes this thread to end immediately if the main program is terminated\n self.daemon = True\n\n def run(self) -> None:\n while True:\n # do all the bluetooth stuff foreverer\n g = self.my_queue.get()\n if g == (None, None):\n break\n print(g)\n time.sleep(1.0)\n print(\"bluetooth closed\")\n\n\nif __name__ == '__main__':\n _queue = Queue() # just one way to communicate to a thread\n # pass an object reference so both main and thread have a way to communicate on this common queue\n my_bluetooth = BlueToothFunctions(_queue)\n my_bluetooth.start() # creates the thread and executes run() method\n\n for i in range(5):\n # communicate to the threaded functions\n _queue.put(i)\n _queue.put((None, None)) # optional, a way to cause the thread to end\n my_bluetooth.join(timeout=5.0) # optional, pause here until thread ends\n print('program complete')\n\n" ]
[ 0, 0 ]
[]
[]
[ "kivy", "multithreading", "python", "sockets" ]
stackoverflow_0074588784_kivy_multithreading_python_sockets.txt
Q: mini-batch gradient descent, loss doesn't improve and accuracy very low I’m trying to implement mini-batch gradient descent on the popular iris dataset, but somehow I don’t manage to get the accuracy of the model above 75-80%. Also the loss does not decrease and is rather stuck at around 0.45, even when I set the number of iterations to 10000. Something im missing here ? class NeuralNetwork(nn.Module): def __init__(self): super().__init__() self.linear_stack = nn.Sequential( nn.Linear(4,128), nn.ReLU(), nn.Linear(128,64), nn.ReLU(), nn.Linear(64,3), ) def forward(self, x): logits = self.linear_stack(x) return logits training loop, batchsize per epoch = 10. transform_label maps [0,1,2] to the labels. lr = 0.01 model = NeuralNetwork() optim = torch.optim.Adam(model.parameters(), lr=lr) loss = torch.nn.CrossEntropyLoss() n_iters = 1000 steps = n_iters/10 LOSS = [] for epochs in range(n_iters): for i,(inputs, labels) in enumerate(train_loader): out = model(inputs) train_labels = transform_label(labels) l = loss(out, train_labels) l.backward() #update weights optim.step() optim.zero_grad() LOSS.append(l.item()) if epochs%steps == 0: print(f"\n epoch: {int(epochs+steps)}/{n_iters}, loss: {sum(LOSS)/len(LOSS)}") #if i % 1 == 0: #print(f" steps: {i+1}, loss : {l.item()}") output: epoch: 100/1000, loss: 1.0636296272277832 epoch: 400/1000, loss: 0.5142968013338076 epoch: 500/1000, loss: 0.49906910391073867 epoch: 900/1000, loss: 0.4586030915751588 epoch: 1000/1000, loss: 0.4543738731996598 Is it possible to calculate the loss like that or should I use torch.max()? If I do so I get this Error: Expected floating point type for target with class probabilities, got Long A: you didn't provide enough data and code to reproduce the problem. I wrote a complete and working code to train your model on the IRIS dataset. Imports and Classes. import torch from torch import nn import pandas as pd from torch.utils.data import Dataset, DataLoader from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, LabelEncoder from sklearn.metrics import classification_report class MyDataset(Dataset): def __init__(self, X, Y): assert len(X) == len(Y) self.X = X self.Y = Y def __len__(self): return len(self.X) def __getitem__(self, item): x = self.X[item] y = self.Y[item] return x, y class NeuralNetwork(nn.Module): def __init__(self): super().__init__() self.linear_stack = nn.Sequential( nn.Linear(4,128), nn.ReLU(), nn.Linear(128,64), nn.ReLU(), nn.Linear(64,3), ) def forward(self, x): logits = self.linear_stack(x) return logits Read and Preprocess the data. # Dataset was downloaded from https://archive.ics.uci.edu/ml/machine-learning-databases/iris/ df = pd.read_csv("iris.data", names=["x1", "x2", "x3", "x4", "label"]) X, Y = df[['x1', "x2", "x3", "x4"]], df['label'] # First, we transform the labels to numbers 0,1,2 encoder = LabelEncoder() Y = encoder.fit_transform(Y) # We split the dataset to train and test X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=123) # Due to the nature of Neural Networks, we standardize the inputs to get better results scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) train_dataset = MyDataset(X_train, Y_train) test_dataset = MyDataset(X_test, Y_test) train_loader = DataLoader(train_dataset, batch_size=8) test_loader = DataLoader(test_dataset, batch_size=8) Train the model. lr = 0.01 model = NeuralNetwork() optim = torch.optim.Adam(model.parameters(), lr=lr) loss = torch.nn.CrossEntropyLoss() n_iters = 1000 steps = n_iters/10 LOSS = [] for epochs in range(n_iters): for i,(inputs, labels) in enumerate(train_loader): optim.zero_grad() out = model(inputs.float()) l = loss(out, labels) l.backward() optim.step() LOSS.append(l.item()) if epochs%steps == 0: print(f"\n epoch: {int(epochs+steps)}/{n_iters}, loss: {sum(LOSS)/len(LOSS)}") output: Then, we need to run the model on test data to calculate the metrics. preds = [] with torch.no_grad(): for i,(inputs, labels) in enumerate(test_loader): out = model(inputs.float()) preds.extend(list(torch.argmax(out, axis=1).cpu().numpy())) To get the metrics, you can use "classification_report". print(classification_report(y_true=Y_test, y_pred=preds)) output: I hope my answer helps you.
mini-batch gradient descent, loss doesn't improve and accuracy very low
I’m trying to implement mini-batch gradient descent on the popular iris dataset, but somehow I don’t manage to get the accuracy of the model above 75-80%. Also the loss does not decrease and is rather stuck at around 0.45, even when I set the number of iterations to 10000. Something im missing here ? class NeuralNetwork(nn.Module): def __init__(self): super().__init__() self.linear_stack = nn.Sequential( nn.Linear(4,128), nn.ReLU(), nn.Linear(128,64), nn.ReLU(), nn.Linear(64,3), ) def forward(self, x): logits = self.linear_stack(x) return logits training loop, batchsize per epoch = 10. transform_label maps [0,1,2] to the labels. lr = 0.01 model = NeuralNetwork() optim = torch.optim.Adam(model.parameters(), lr=lr) loss = torch.nn.CrossEntropyLoss() n_iters = 1000 steps = n_iters/10 LOSS = [] for epochs in range(n_iters): for i,(inputs, labels) in enumerate(train_loader): out = model(inputs) train_labels = transform_label(labels) l = loss(out, train_labels) l.backward() #update weights optim.step() optim.zero_grad() LOSS.append(l.item()) if epochs%steps == 0: print(f"\n epoch: {int(epochs+steps)}/{n_iters}, loss: {sum(LOSS)/len(LOSS)}") #if i % 1 == 0: #print(f" steps: {i+1}, loss : {l.item()}") output: epoch: 100/1000, loss: 1.0636296272277832 epoch: 400/1000, loss: 0.5142968013338076 epoch: 500/1000, loss: 0.49906910391073867 epoch: 900/1000, loss: 0.4586030915751588 epoch: 1000/1000, loss: 0.4543738731996598 Is it possible to calculate the loss like that or should I use torch.max()? If I do so I get this Error: Expected floating point type for target with class probabilities, got Long
[ "you didn't provide enough data and code to reproduce the problem. I wrote a complete and working code to train your model on the IRIS dataset.\nImports and Classes.\nimport torch\nfrom torch import nn\nimport pandas as pd\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.metrics import classification_report\n\nclass MyDataset(Dataset):\n def __init__(self, X, Y):\n assert len(X) == len(Y)\n self.X = X\n self.Y = Y\n \n def __len__(self):\n return len(self.X)\n \n def __getitem__(self, item):\n x = self.X[item]\n y = self.Y[item]\n return x, y\n\nclass NeuralNetwork(nn.Module):\n def __init__(self):\n super().__init__()\n self.linear_stack = nn.Sequential(\n nn.Linear(4,128),\n nn.ReLU(),\n nn.Linear(128,64),\n nn.ReLU(),\n nn.Linear(64,3),\n )\n def forward(self, x):\n logits = self.linear_stack(x)\n return logits\n\nRead and Preprocess the data.\n# Dataset was downloaded from https://archive.ics.uci.edu/ml/machine-learning-databases/iris/\ndf = pd.read_csv(\"iris.data\", names=[\"x1\", \"x2\", \"x3\", \"x4\", \"label\"])\nX, Y = df[['x1', \"x2\", \"x3\", \"x4\"]], df['label']\n\n# First, we transform the labels to numbers 0,1,2\nencoder = LabelEncoder()\nY = encoder.fit_transform(Y)\n\n# We split the dataset to train and test\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=123)\n\n# Due to the nature of Neural Networks, we standardize the inputs to get better results\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\ntrain_dataset = MyDataset(X_train, Y_train)\ntest_dataset = MyDataset(X_test, Y_test)\n\ntrain_loader = DataLoader(train_dataset, batch_size=8)\ntest_loader = DataLoader(test_dataset, batch_size=8) \n\nTrain the model.\nlr = 0.01\nmodel = NeuralNetwork()\noptim = torch.optim.Adam(model.parameters(), lr=lr)\nloss = torch.nn.CrossEntropyLoss()\n\nn_iters = 1000\nsteps = n_iters/10\nLOSS = []\n\nfor epochs in range(n_iters): \n for i,(inputs, labels) in enumerate(train_loader):\n optim.zero_grad()\n out = model(inputs.float())\n l = loss(out, labels)\n l.backward()\n optim.step()\n LOSS.append(l.item())\n if epochs%steps == 0:\n print(f\"\\n epoch: {int(epochs+steps)}/{n_iters}, loss: {sum(LOSS)/len(LOSS)}\")\n \n\noutput:\n\nThen, we need to run the model on test data to calculate the metrics.\npreds = []\nwith torch.no_grad():\n for i,(inputs, labels) in enumerate(test_loader):\n out = model(inputs.float())\n preds.extend(list(torch.argmax(out, axis=1).cpu().numpy()))\n\nTo get the metrics, you can use \"classification_report\".\nprint(classification_report(y_true=Y_test, y_pred=preds))\n\noutput:\n\nI hope my answer helps you.\n" ]
[ 1 ]
[]
[]
[ "gradient", "iris_dataset", "mini_batch", "python", "pytorch" ]
stackoverflow_0074589556_gradient_iris_dataset_mini_batch_python_pytorch.txt
Q: transpose function of numpy I am new to numpy and python and I am trying to understand the usage of transpose function of numpy. The code below works fine but I am still not be able to understand the effect of transpose function and also the use of the arguments inside it. It would be great help if someone can explain the usage and effect of transpose function in below code. import numpy as np my_list = [[[[[[1,2],[3,4]],[[1,2],[3,4]]], [[[1,2],[3,4]],[[1,2],[3,4]]]],[[[[1,2],[3,4]],[[1,2],[3,4]]], [[[1,2],[3,4]],[[1,2],[3,4]]]]], [[[[[1,2],[3,4]],[[1,2],[3,4]]], [[[1,0],[1,1]],[[1,0],[1,1]]]],[[[[1,0],[1,1]],[[1,0],[1,1]]], [[[1,0],[1,1]],[[1,0],[1,1]]]]]] arr = np.array(my_list) perm_testing = [0,1,2,3,4,5] testing = arr.transpose(perm_testing) print(testing) Edit import numpy as np my_list = [[1,2],[3,4]] arr = np.array(my_list) perm_testing = [1,0] testing = arr.transpose(perm_testing) print(testing) [[1 3] [2 4]] A: Here's an attempt to visually explain for a 3d-array. I hope it'll help you better understand what's happening: a=np.arange(24).reshape(2,4,3) # array([[[ 0, 1, 2], # [ 3, 4, 5], # [ 6, 7, 8], # [ 9, 10, 11]], # # [[12, 13, 14], # [15, 16, 17], # [18, 19, 20], # [21, 22, 23]]]) And a visual 3d representation of a (axis 0 corresponds to the first bracket level and to the first size in the shape, and so on for axis 1 and 2): a.transpose(1,0,2) # swapping axis 0 and 1 # array([[[ 0, 1, 2], # [12, 13, 14]], # # [[ 3, 4, 5], # [15, 16, 17]], # # [[ 6, 7, 8], # [18, 19, 20]], # # [[ 9, 10, 11], # [21, 22, 23]]]) Visual 3d representation of the new array (sorry, my drawing skills are quite limited):
transpose function of numpy
I am new to numpy and python and I am trying to understand the usage of transpose function of numpy. The code below works fine but I am still not be able to understand the effect of transpose function and also the use of the arguments inside it. It would be great help if someone can explain the usage and effect of transpose function in below code. import numpy as np my_list = [[[[[[1,2],[3,4]],[[1,2],[3,4]]], [[[1,2],[3,4]],[[1,2],[3,4]]]],[[[[1,2],[3,4]],[[1,2],[3,4]]], [[[1,2],[3,4]],[[1,2],[3,4]]]]], [[[[[1,2],[3,4]],[[1,2],[3,4]]], [[[1,0],[1,1]],[[1,0],[1,1]]]],[[[[1,0],[1,1]],[[1,0],[1,1]]], [[[1,0],[1,1]],[[1,0],[1,1]]]]]] arr = np.array(my_list) perm_testing = [0,1,2,3,4,5] testing = arr.transpose(perm_testing) print(testing) Edit import numpy as np my_list = [[1,2],[3,4]] arr = np.array(my_list) perm_testing = [1,0] testing = arr.transpose(perm_testing) print(testing) [[1 3] [2 4]]
[ "Here's an attempt to visually explain for a 3d-array. I hope it'll help you better understand what's happening:\na=np.arange(24).reshape(2,4,3)\n\n# array([[[ 0, 1, 2],\n# [ 3, 4, 5],\n# [ 6, 7, 8],\n# [ 9, 10, 11]],\n#\n# [[12, 13, 14],\n# [15, 16, 17],\n# [18, 19, 20],\n# [21, 22, 23]]])\n\nAnd a visual 3d representation of a (axis 0 corresponds to the first bracket level and to the first size in the shape, and so on for axis 1 and 2):\n\na.transpose(1,0,2) # swapping axis 0 and 1\n\n# array([[[ 0, 1, 2],\n# [12, 13, 14]],\n# \n# [[ 3, 4, 5],\n# [15, 16, 17]],\n# \n# [[ 6, 7, 8],\n# [18, 19, 20]],\n#\n# [[ 9, 10, 11],\n# [21, 22, 23]]])\n\nVisual 3d representation of the new array (sorry, my drawing skills are quite limited):\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074586389_numpy_python.txt
Q: Match by "," ",[" or "]," second alternative is not working I have the regex: (?:,)(?![^[]*\])|(?:,\[)(?![^[]*\])|(?:\],)(?![^[]*\]) which is supposed to find all of the , ,[ or ], in a string however the second or statement (?:,\[)(?![^[]*\]) does not work but the other two do. input : file,[test],10,10,[something],[something else] desired output: file test 10 10 something something else actual output : file [test 10 10 [something [something else A: It depends on the order in your pattern. You noticed correctly that the expressions consume the part of the strings that they match and that there exist special expressions to hold them from consuming parts of the string. However, if you use such expression, you might end up with some remaining characters: import re patterns = [r"[,\[\]]", #1 r"[,(\],\[)(,\[)(\],)]", #2 r"(\],\[)|(,\[)|(\],)|,", #3 r",\[?|\],", #4 r"(\],\[)|(,\[?)|\]," #5 r"(\](?=,))|((?<=,)\[)|," #6 ] for pat in patterns: print(re.sub(pat, " ", input)) file test 10 10 something something else file test 10 10 something something else file test 10 10 something something else file test 10 10 something [something else file test 10 10 something something else file test 10 10 something something else The first two patterns replace every character separately and thus yield to double or even triple spaces if the characters are followed by each other. #3 does a good job, the key is that we first look for the most complex pattern \],\[ and afterwards for the less complex patterns \],, ,\[ and ,. This becomes clear if you check out #4 in comparison. The last pattern (#5) is just a fancy rewriting of #5. Pattern #6 is perhaps what you intended to do in the first place. It looks for brackets with a preceding/following coma but consumes neither of the comas. Only afterwards it replaces all comas again. However this cascaded checking results in multiple spaces again.
Match by "," ",[" or "]," second alternative is not working
I have the regex: (?:,)(?![^[]*\])|(?:,\[)(?![^[]*\])|(?:\],)(?![^[]*\]) which is supposed to find all of the , ,[ or ], in a string however the second or statement (?:,\[)(?![^[]*\]) does not work but the other two do. input : file,[test],10,10,[something],[something else] desired output: file test 10 10 something something else actual output : file [test 10 10 [something [something else
[ "It depends on the order in your pattern. You noticed correctly that the expressions consume the part of the strings that they match and that there exist special expressions to hold them from consuming parts of the string. However, if you use such expression, you might end up with some remaining characters:\nimport re\n\npatterns = [r\"[,\\[\\]]\", #1\n r\"[,(\\],\\[)(,\\[)(\\],)]\", #2\n r\"(\\],\\[)|(,\\[)|(\\],)|,\", #3\n r\",\\[?|\\],\", #4\n r\"(\\],\\[)|(,\\[?)|\\],\" #5\n r\"(\\](?=,))|((?<=,)\\[)|,\" #6\n ]\nfor pat in patterns:\n print(re.sub(pat, \" \", input))\n\n\nfile test 10 10 something something else\nfile test 10 10 something something else\nfile test 10 10 something something else\nfile test 10 10 something [something else\nfile test 10 10 something something else\nfile test 10 10 something something else\n\nThe first two patterns replace every character separately and thus yield to double or even triple spaces if the characters are followed by each other. #3 does a good job, the key is that we first look for the most complex pattern \\],\\[ and afterwards for the less complex patterns \\],, ,\\[ and ,. This becomes clear if you check out #4 in comparison. The last pattern (#5) is just a fancy rewriting of #5. Pattern #6 is perhaps what you intended to do in the first place. It looks for brackets with a preceding/following coma but consumes neither of the comas. Only afterwards it replaces all comas again. However this cascaded checking results in multiple spaces again.\n" ]
[ 0 ]
[]
[]
[ "python", "python_re", "regex" ]
stackoverflow_0074366543_python_python_re_regex.txt
Q: How to hide/show password with Custom Tkinter? Can't find any info about how to make password visible or hide with Custom Tkinter. import tkinter as tk import customtkinter def toggle_password(): if txt.cget('show') == '': txt.config(show='*') else: txt.config(show='') root = tk.Tk() root.geometry("200x200") txt = customtkinter.CTkEntry(root, width=20) txt.pack() toggle_btn = customtkinter.CTkButton(root, text='Show Password', width=15, command=toggle_password) toggle_btn.pack() root.mainloop() A: The show method isn't directly supported by the CtkEntry widget. You will need to configure the Entry widget that is internal to the CtkEntry widget. def toggle_password(): if txt.entry.cget('show') == '': txt.entry.config(show='*') else: txt.entry.config(show='')
How to hide/show password with Custom Tkinter?
Can't find any info about how to make password visible or hide with Custom Tkinter. import tkinter as tk import customtkinter def toggle_password(): if txt.cget('show') == '': txt.config(show='*') else: txt.config(show='') root = tk.Tk() root.geometry("200x200") txt = customtkinter.CTkEntry(root, width=20) txt.pack() toggle_btn = customtkinter.CTkButton(root, text='Show Password', width=15, command=toggle_password) toggle_btn.pack() root.mainloop()
[ "The show method isn't directly supported by the CtkEntry widget. You will need to configure the Entry widget that is internal to the CtkEntry widget.\ndef toggle_password():\n if txt.entry.cget('show') == '':\n txt.entry.config(show='*')\n else:\n txt.entry.config(show='')\n\n" ]
[ 0 ]
[]
[]
[ "customtkinter", "passwords", "python", "tkinter" ]
stackoverflow_0074590427_customtkinter_passwords_python_tkinter.txt
Q: python - the scope of variables inside "main" function This is my first post here, so please give me some constructive criticism (not too much). My initial intent was to receive inputs from the user, and save them into variables to later user in other functions (in other modules). This is a simplified version of what i am trying to do: i tried both with and without the "global inputfile" line, unsuccessfully. I also tried sending the variable as an argument to a function outside, it didnt work. I also tried importing the main module to the other module, it didnt work. The code: def main(argv): inputfile = "a" if __name__ == "__main__": global inputfile print(inputfile) gives me the following error: NameError: name 'inputfile' is not defined Thank you for your time. A: You need to call the function in order to acces the function value. def main(): global inputfile inputfile = "a" if __name__ == "__main__": main() print(inputfile) Gives # a
python - the scope of variables inside "main" function
This is my first post here, so please give me some constructive criticism (not too much). My initial intent was to receive inputs from the user, and save them into variables to later user in other functions (in other modules). This is a simplified version of what i am trying to do: i tried both with and without the "global inputfile" line, unsuccessfully. I also tried sending the variable as an argument to a function outside, it didnt work. I also tried importing the main module to the other module, it didnt work. The code: def main(argv): inputfile = "a" if __name__ == "__main__": global inputfile print(inputfile) gives me the following error: NameError: name 'inputfile' is not defined Thank you for your time.
[ "You need to call the function in order to acces the function value.\ndef main():\n global inputfile\n\n inputfile = \"a\"\n\nif __name__ == \"__main__\":\n main()\n print(inputfile)\n\nGives #\na\n\n" ]
[ 2 ]
[]
[]
[ "defined", "global", "program_entry_point", "python", "scope" ]
stackoverflow_0074590613_defined_global_program_entry_point_python_scope.txt
Q: Parse every element in a Dataframe I have a Dataframe of some 3700 rows. I used if loop and gave my conditions. The code got executed but i'm only getting one element. I want the to check whole Dataframe and print all elements within my conditions. for i in df: i=0 div = "Divergence spotted at " if (df.High[i] < df.High[i+1]) and (df.RSI[i] > df.RSI[i+1]) : print(f'{div}{i}') i=i+1 break if (df.High[i] > df.High[i+1]) and (df.RSI[i] < df.RSI[i+1]) : print(f'{div}{i}') i=i+1 break else: print("no divergence spotted") My Output My code exited after printing first element. I want it to check the whole Dataframe and print multiple elements that satisfy my condition. A: You are using break, this stops at the first divergence. You would rather need: out = [] for i in range(len(df)-1): div = "Divergence spotted at " if (df.High[i] < df.High[i+1]) and (df.RSI[i] > df.RSI[i+1]) : out.append(f'{div}{i}') if (df.High[i] > df.High[i+1]) and (df.RSI[i] < df.RSI[i+1]) : out.append(f'{div}{i}') else: out.append('') out.append('') Output: ['Divergence spotted at 0', '', '', '', '', 'Divergence spotted at 4', ''] But using a loop is inefficient, a vectorial solution would be: m = (np.sign(df['High'].diff(-1).fillna(0)) .ne(np.sign(df['RSI'].diff(-1).fillna(0))) ) df['divergence'] = np.where(m, 'divergence spotted', '') Output: High RSI divergence 0 1 2 divergence spotted 1 2 1 2 3 2 3 2 1 4 3 2 divergence spotted 5 1 3
Parse every element in a Dataframe
I have a Dataframe of some 3700 rows. I used if loop and gave my conditions. The code got executed but i'm only getting one element. I want the to check whole Dataframe and print all elements within my conditions. for i in df: i=0 div = "Divergence spotted at " if (df.High[i] < df.High[i+1]) and (df.RSI[i] > df.RSI[i+1]) : print(f'{div}{i}') i=i+1 break if (df.High[i] > df.High[i+1]) and (df.RSI[i] < df.RSI[i+1]) : print(f'{div}{i}') i=i+1 break else: print("no divergence spotted") My Output My code exited after printing first element. I want it to check the whole Dataframe and print multiple elements that satisfy my condition.
[ "You are using break, this stops at the first divergence.\nYou would rather need:\nout = []\nfor i in range(len(df)-1):\n div = \"Divergence spotted at \"\n \n if (df.High[i] < df.High[i+1]) and (df.RSI[i] > df.RSI[i+1]) :\n \n out.append(f'{div}{i}')\n if (df.High[i] > df.High[i+1]) and (df.RSI[i] < df.RSI[i+1]) :\n \n out.append(f'{div}{i}')\n else:\n out.append('')\nout.append('')\n\nOutput: ['Divergence spotted at 0', '', '', '', '', 'Divergence spotted at 4', '']\nBut using a loop is inefficient, a vectorial solution would be:\nm = (np.sign(df['High'].diff(-1).fillna(0))\n .ne(np.sign(df['RSI'].diff(-1).fillna(0)))\n )\ndf['divergence'] = np.where(m, 'divergence spotted', '')\n\nOutput:\n High RSI divergence\n0 1 2 divergence spotted\n1 2 1 \n2 3 2 \n3 2 1 \n4 3 2 divergence spotted\n5 1 3 \n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "if_statement", "loops", "python" ]
stackoverflow_0074590622_dataframe_for_loop_if_statement_loops_python.txt
Q: Storing parquet file in redis I want to know how I would store a parquet file as it is binary data in redis via python? Background is, that I want check the fastest way of serving a parquet file of small size over the network. I believe object storage like s3 or any file system is slower. So it comes down to the fastest way of serving binary data over the network, but still have some database like structure as storage layer. Probably the data needs to live in the memory on the server side to send it over network directly into the clients side memory. (remember it is about small size files compressed with parquet around 30-50 Mb, so to big for simple file system reads and to small for big data technology, hdfs etc. ) A: Okay found it myself: Use python Pandas to write as bytes into memory bytes_data = df.to_parquet() Now having the compressed parquet format as bytes in memory one can send it to redis set("key", bytes_data)
Storing parquet file in redis
I want to know how I would store a parquet file as it is binary data in redis via python? Background is, that I want check the fastest way of serving a parquet file of small size over the network. I believe object storage like s3 or any file system is slower. So it comes down to the fastest way of serving binary data over the network, but still have some database like structure as storage layer. Probably the data needs to live in the memory on the server side to send it over network directly into the clients side memory. (remember it is about small size files compressed with parquet around 30-50 Mb, so to big for simple file system reads and to small for big data technology, hdfs etc. )
[ "Okay found it myself:\n\nUse python Pandas to write as bytes into memory\nbytes_data = df.to_parquet()\n\nNow having the compressed parquet format as bytes in memory one can send it to redis\nset(\"key\", bytes_data)\n\n\n" ]
[ 0 ]
[]
[]
[ "parquet", "pyarrow", "python", "redis" ]
stackoverflow_0074584407_parquet_pyarrow_python_redis.txt
Q: MultiIndex pandas dataframe and writing to Google Sheets using gspread-pandas Starting with the following dictionary: test_dict = {'header1_1': {'header2_1': {'header3_1': {'header4_1': ['322.5', 330.0, -0.28], 'header4_2': ['322.5', 332.5, -0.26]}, 'header3_2': {'header4_1': ['285.0', 277.5, -0.09], 'header4_2': ['287.5', 277.5, -0.12]}}, 'header2_2': {'header3_1': {'header4_1': ['345.0', 357.5, -0.14], 'header4_2': ['345.0', 362.5, -0.14]}, 'header3_2': {'header4_1': ['257.5', 245.0, -0.1], 'header4_2': ['257.5', 240.0, -0.08]}}}} I want the headers in the index, so I reform the dictionary: reformed_dict = {} for outerKey, innerDict in test_dict.items(): for innerKey, innerDict2 in innerDict.items(): for innerKey2, innerDict3 in innerDict2.items(): for innerKey3, values in innerDict3.items(): reformed_dict[(outerKey, innerKey, innerKey2, innerKey3)] = values And assign column names to the headers: keys = reformed_dict.keys() values = reformed_dict.values() index = pd.MultiIndex.from_tuples(keys, names=["H1", "H2", "H3", "H4"]) df = pd.DataFrame(data=values, index=index) That gets to a dataframe that looks like this: Issue #1 [*** this has been answered by @AzharKhan, so feel free to skip ahead to Issue #2 ***]: To assign names to the data columns, I tried: df.columns = ['col 1', 'col 2' 'col 3'] and got error: "ValueError: Length mismatch: Expected axis has 3 elements, new values have 2 elements" Then per a suggestion, I tried: df = df.rename(columns={'0': 'Col1', '1': 'Col2', '2': 'Col3'}) This does not generate an error, but the dataframe looks exactly the same as before, with 0, 1, 2 as the data column headers. How can I assign names to these data columns? I assume 0, 1, 2 are column indices, not column names. Issue #2: When I write this dataframe to Google Sheets using gspread-pandas: s.open_sheet('test') Spread.df_to_sheet(s, df, index=True, headers=True, start='A8', replace=False) The result is this: What I would like is this: This is how the dataframe appears in Jupyter notebook screenshot earlier, so it seems the process of writing to spreadsheet is filling in the empty row headers, which makes the table harder to read at a glance. How can I get the output to spreadsheet to omit the row headers until they have changed, and thus get the second spreadsheet output? A: Issue #1 Your columns are numbers (not strings). You can see it by: print(df.columns) [Out]: RangeIndex(start=0, stop=3, step=1) Use numbers in df.rename() as follows: df = df.rename(columns={0: 'Col1', 1: 'Col2', 2: 'Col3'}) print(df.columns) print(df) [Out]: Index(['Col1', 'Col2', 'Col3'], dtype='object') Col1 Col2 Col3 H1 H2 H3 H4 header1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28 header4_2 322.5 332.5 -0.26 header3_2 header4_1 285.0 277.5 -0.09 header4_2 287.5 277.5 -0.12 header2_2 header3_1 header4_1 345.0 357.5 -0.14 header4_2 345.0 362.5 -0.14 header3_2 header4_1 257.5 245.0 -0.10 header4_2 257.5 240.0 -0.08 Or if you want to generalise it rather than hard coding then use: df = df.rename(columns={i:f"Col{i+1}" for i in df.columns}) I am not sure about your issue #2. You may want to carve it out into a separate question to get attention. A: Here is a way to handle issue #1 by using pd.json_normalize() df = pd.json_normalize(test_dict,max_level=3).stack().droplevel(0) idx = df.index.map(lambda x: tuple(x.split('.'))).rename(['H1','H2','H3','H4']) df = pd.DataFrame(df.tolist(),index = idx,columns = ['col1','col2','col3']) Output: col1 col2 col3 H1 H2 H3 H4 header1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28 header4_2 322.5 332.5 -0.26 header3_2 header4_1 285.0 277.5 -0.09 header4_2 287.5 277.5 -0.12 header2_2 header3_1 header4_1 345.0 357.5 -0.14 header4_2 345.0 362.5 -0.14 header3_2 header4_1 257.5 245.0 -0.10 header4_2 257.5 240.0 -0.08 Issue #2 is tricky because Jupyter notebook displays the index with the "blank" values, but if you were to do df.index, it would show that all the data is actually there. Its just a visual choice used by Jupyter notebooks. In order to achieve this, you can check for value changes and join newly created df. idx_df = df.index.to_frame().reset_index(drop=True) df = idx_df.where(idx_df.ne(idx_df.shift())).join(df.reset_index(drop=True))
MultiIndex pandas dataframe and writing to Google Sheets using gspread-pandas
Starting with the following dictionary: test_dict = {'header1_1': {'header2_1': {'header3_1': {'header4_1': ['322.5', 330.0, -0.28], 'header4_2': ['322.5', 332.5, -0.26]}, 'header3_2': {'header4_1': ['285.0', 277.5, -0.09], 'header4_2': ['287.5', 277.5, -0.12]}}, 'header2_2': {'header3_1': {'header4_1': ['345.0', 357.5, -0.14], 'header4_2': ['345.0', 362.5, -0.14]}, 'header3_2': {'header4_1': ['257.5', 245.0, -0.1], 'header4_2': ['257.5', 240.0, -0.08]}}}} I want the headers in the index, so I reform the dictionary: reformed_dict = {} for outerKey, innerDict in test_dict.items(): for innerKey, innerDict2 in innerDict.items(): for innerKey2, innerDict3 in innerDict2.items(): for innerKey3, values in innerDict3.items(): reformed_dict[(outerKey, innerKey, innerKey2, innerKey3)] = values And assign column names to the headers: keys = reformed_dict.keys() values = reformed_dict.values() index = pd.MultiIndex.from_tuples(keys, names=["H1", "H2", "H3", "H4"]) df = pd.DataFrame(data=values, index=index) That gets to a dataframe that looks like this: Issue #1 [*** this has been answered by @AzharKhan, so feel free to skip ahead to Issue #2 ***]: To assign names to the data columns, I tried: df.columns = ['col 1', 'col 2' 'col 3'] and got error: "ValueError: Length mismatch: Expected axis has 3 elements, new values have 2 elements" Then per a suggestion, I tried: df = df.rename(columns={'0': 'Col1', '1': 'Col2', '2': 'Col3'}) This does not generate an error, but the dataframe looks exactly the same as before, with 0, 1, 2 as the data column headers. How can I assign names to these data columns? I assume 0, 1, 2 are column indices, not column names. Issue #2: When I write this dataframe to Google Sheets using gspread-pandas: s.open_sheet('test') Spread.df_to_sheet(s, df, index=True, headers=True, start='A8', replace=False) The result is this: What I would like is this: This is how the dataframe appears in Jupyter notebook screenshot earlier, so it seems the process of writing to spreadsheet is filling in the empty row headers, which makes the table harder to read at a glance. How can I get the output to spreadsheet to omit the row headers until they have changed, and thus get the second spreadsheet output?
[ "Issue #1\nYour columns are numbers (not strings). You can see it by:\nprint(df.columns)\n\n[Out]:\nRangeIndex(start=0, stop=3, step=1)\n\nUse numbers in df.rename() as follows:\ndf = df.rename(columns={0: 'Col1', 1: 'Col2', 2: 'Col3'})\nprint(df.columns)\nprint(df)\n\n[Out]:\nIndex(['Col1', 'Col2', 'Col3'], dtype='object')\n\n Col1 Col2 Col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n\nOr if you want to generalise it rather than hard coding then use:\ndf = df.rename(columns={i:f\"Col{i+1}\" for i in df.columns})\n\nI am not sure about your issue #2. You may want to carve it out into a separate question to get attention.\n", "Here is a way to handle issue #1 by using pd.json_normalize()\ndf = pd.json_normalize(test_dict,max_level=3).stack().droplevel(0)\nidx = df.index.map(lambda x: tuple(x.split('.'))).rename(['H1','H2','H3','H4'])\ndf = pd.DataFrame(df.tolist(),index = idx,columns = ['col1','col2','col3'])\n\nOutput:\n col1 col2 col3\nH1 H2 H3 H4 \nheader1_1 header2_1 header3_1 header4_1 322.5 330.0 -0.28\n header4_2 322.5 332.5 -0.26\n header3_2 header4_1 285.0 277.5 -0.09\n header4_2 287.5 277.5 -0.12\n header2_2 header3_1 header4_1 345.0 357.5 -0.14\n header4_2 345.0 362.5 -0.14\n header3_2 header4_1 257.5 245.0 -0.10\n header4_2 257.5 240.0 -0.08\n\nIssue #2 is tricky because Jupyter notebook displays the index with the \"blank\" values, but if you were to do df.index, it would show that all the data is actually there. Its just a visual choice used by Jupyter notebooks.\nIn order to achieve this, you can check for value changes and join newly created df.\nidx_df = df.index.to_frame().reset_index(drop=True)\n\ndf = idx_df.where(idx_df.ne(idx_df.shift())).join(df.reset_index(drop=True))\n\n" ]
[ 1, 0 ]
[]
[]
[ "gspread", "pandas", "python" ]
stackoverflow_0074564252_gspread_pandas_python.txt
Q: How to get partial cumulative sums (of positive and negative numbers) in an array? I have an array with positive and negative numbers and want to do a cumulative sum of numbers of the same sign until the next number carries an opposite sign. It starts again at 0. Maybe better explained with a sample. Here is the original array: np.array([0.2, 0.5, 1.3, 0.6, -0.3, -1.1, 0.2, -2.0, 0.7, 1.1, 0.0, -1.2]) And the output I expect without using a loop, of course: np.array([0.0, 0.0, 0.0, 2.6, 0.0, -1.4, 0.2, -2.0, 0.0, 0.0, 1.8, -1.2]) Any efficient idea would help a lot... A: One vectorial option: a = np.array([0.2, 0.5, 1.3, 0.6, -0.3, -1.1, 0.2, -2.0, 0.7, 1.1, 0.0, -1.2]) cs = np.cumsum(a) idx = np.nonzero(np.r_[np.diff(a>0), True]) out = np.zeros_like(a) out[idx] = np.diff(np.r_[0, cs[idx]]) Output: array([ 0. , 0. , 0. , 2.6, 0. , -1.4, 0.2, -2. , 0. , 1.8, 0. , -1.2])
How to get partial cumulative sums (of positive and negative numbers) in an array?
I have an array with positive and negative numbers and want to do a cumulative sum of numbers of the same sign until the next number carries an opposite sign. It starts again at 0. Maybe better explained with a sample. Here is the original array: np.array([0.2, 0.5, 1.3, 0.6, -0.3, -1.1, 0.2, -2.0, 0.7, 1.1, 0.0, -1.2]) And the output I expect without using a loop, of course: np.array([0.0, 0.0, 0.0, 2.6, 0.0, -1.4, 0.2, -2.0, 0.0, 0.0, 1.8, -1.2]) Any efficient idea would help a lot...
[ "One vectorial option:\na = np.array([0.2, 0.5, 1.3, 0.6, -0.3, -1.1, 0.2, -2.0, 0.7, 1.1, 0.0, -1.2])\n\ncs = np.cumsum(a)\nidx = np.nonzero(np.r_[np.diff(a>0), True])\nout = np.zeros_like(a)\n\nout[idx] = np.diff(np.r_[0, cs[idx]])\n\nOutput:\narray([ 0. , 0. , 0. , 2.6, 0. , -1.4, 0.2, -2. , 0. , 1.8, 0. , -1.2])\n\n" ]
[ 2 ]
[]
[]
[ "arrays", "cumulative_sum", "numpy", "python", "sum" ]
stackoverflow_0074590529_arrays_cumulative_sum_numpy_python_sum.txt
Q: How can I insert the numbers of the 3D matrix into 2D matrix? Suppose that A is a three-dimensional matrix like the following: A = [np.zeros((3, 8)) for _ in range(20)] and B is a two-dimensional matrix that has 60 rows and 8 columns containing numbers. What should I do if I want to put numbers from matrix B into matrix A and use a loop to write code? A[0][0] = B[0] A[0][1] = B[1] A[0][2] = B[2] A[1][0] = B[3] A[1][1] = B[4] A[1][2] = B[5] ... A[20][0] = B[58] A[20][1] = B[59] A[20][2] = B[60] Thanks A: I hope I've understood your question right. You can use .flat + indexing: A = [np.zeros((3, 8)) for _ in range(20)] B = np.arange(60 * 8).reshape(60, 8) for i, subl in enumerate(A): subl.flat[:] = B.flat[i * 3 * 8 :] print(*A, sep="\n\n") Prints: [[ 0. 1. 2. 3. 4. 5. 6. 7.] [ 8. 9. 10. 11. 12. 13. 14. 15.] [16. 17. 18. 19. 20. 21. 22. 23.]] [[24. 25. 26. 27. 28. 29. 30. 31.] [32. 33. 34. 35. 36. 37. 38. 39.] [40. 41. 42. 43. 44. 45. 46. 47.]] ...
How can I insert the numbers of the 3D matrix into 2D matrix?
Suppose that A is a three-dimensional matrix like the following: A = [np.zeros((3, 8)) for _ in range(20)] and B is a two-dimensional matrix that has 60 rows and 8 columns containing numbers. What should I do if I want to put numbers from matrix B into matrix A and use a loop to write code? A[0][0] = B[0] A[0][1] = B[1] A[0][2] = B[2] A[1][0] = B[3] A[1][1] = B[4] A[1][2] = B[5] ... A[20][0] = B[58] A[20][1] = B[59] A[20][2] = B[60] Thanks
[ "I hope I've understood your question right. You can use .flat + indexing:\nA = [np.zeros((3, 8)) for _ in range(20)]\nB = np.arange(60 * 8).reshape(60, 8)\n\nfor i, subl in enumerate(A):\n subl.flat[:] = B.flat[i * 3 * 8 :]\n\nprint(*A, sep=\"\\n\\n\")\n\nPrints:\n[[ 0. 1. 2. 3. 4. 5. 6. 7.]\n [ 8. 9. 10. 11. 12. 13. 14. 15.]\n [16. 17. 18. 19. 20. 21. 22. 23.]]\n\n[[24. 25. 26. 27. 28. 29. 30. 31.]\n [32. 33. 34. 35. 36. 37. 38. 39.]\n [40. 41. 42. 43. 44. 45. 46. 47.]]\n\n...\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "for_loop", "loops", "matrix", "python" ]
stackoverflow_0074588839_arrays_for_loop_loops_matrix_python.txt
Q: Grid from left to right I am having troubles putting a grid of images starting from the top right corner. I am trying to do the Python Crash Course Sideway shooter project, so I tried creating a grid from the top right corner. I can create one column in the top right corner, but when I try to write a code to create multiple columns going towards the left side of the screen, it fails to work, and no images are created at all. This is the code I have for this: def _create_fleet(self): """Create the fleet of aliens.""" alien = Alien(self) alien_width, alien_height = alien.rect.size current_x, current_y = alien_width, alien_height while current_x > (3 * alien_width): while current_y < (self.settings.height - alien_height): new_alien = Alien(self) new_alien.y = current_y new_alien.rect.y = current_y self.aliens.add(new_alien) current_y += 2 * alien_height current_y = alien_height current_x -= 3 * alien_width If I only have this part of the code, the one column works fine: def _create_fleet(self): """Create the fleet of aliens.""" alien = Alien(self) alien_width, alien_height = alien.rect.size current_x, current_y = alien_width, alien_height while current_y < (self.settings.height - alien_height): new_alien = Alien(self) new_alien.y = current_y new_alien.rect.y = current_y self.aliens.add(new_alien) current_y += 2 * alien_height Would anyone have an idea where it is going sideways? I have tried the above code, and I expect to have multiple columns of aliens filling the screen from right to left. A: current_x starts at alien_width. So you need to step the current_x coordinate from left to right. And you have to current_x to new_alien.x and new_alien.rect.x: alien_width, alien_height = alien.rect.size # from left to right while current_x < self.settings.width - alien_width: # from top to bottom while current_y < self.settings.height - alien_height: # create new alien at current_x, current_y new_alien = Alien(self) new_alien.rect.topleft = current_x, current_y new_alien.x, new_alien.y = new_alien.rect.topleft # step current_y current_y += 2 * alien_height # reset current_y current_y = alien_height # step current_x current_x += 2 * alien_width
Grid from left to right
I am having troubles putting a grid of images starting from the top right corner. I am trying to do the Python Crash Course Sideway shooter project, so I tried creating a grid from the top right corner. I can create one column in the top right corner, but when I try to write a code to create multiple columns going towards the left side of the screen, it fails to work, and no images are created at all. This is the code I have for this: def _create_fleet(self): """Create the fleet of aliens.""" alien = Alien(self) alien_width, alien_height = alien.rect.size current_x, current_y = alien_width, alien_height while current_x > (3 * alien_width): while current_y < (self.settings.height - alien_height): new_alien = Alien(self) new_alien.y = current_y new_alien.rect.y = current_y self.aliens.add(new_alien) current_y += 2 * alien_height current_y = alien_height current_x -= 3 * alien_width If I only have this part of the code, the one column works fine: def _create_fleet(self): """Create the fleet of aliens.""" alien = Alien(self) alien_width, alien_height = alien.rect.size current_x, current_y = alien_width, alien_height while current_y < (self.settings.height - alien_height): new_alien = Alien(self) new_alien.y = current_y new_alien.rect.y = current_y self.aliens.add(new_alien) current_y += 2 * alien_height Would anyone have an idea where it is going sideways? I have tried the above code, and I expect to have multiple columns of aliens filling the screen from right to left.
[ "current_x starts at alien_width. So you need to step the current_x coordinate from left to right. And you have to current_x to new_alien.x and new_alien.rect.x:\nalien_width, alien_height = alien.rect.size\n\n# from left to right\nwhile current_x < self.settings.width - alien_width:\n \n # from top to bottom\n while current_y < self.settings.height - alien_height:\n\n # create new alien at current_x, current_y \n new_alien = Alien(self)\n new_alien.rect.topleft = current_x, current_y\n new_alien.x, new_alien.y = new_alien.rect.topleft\n \n # step current_y \n current_y += 2 * alien_height\n\n # reset current_y \n current_y = alien_height\n # step current_x\n current_x += 2 * alien_width\n\n" ]
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074590634_pygame_python.txt
Q: ImportError: cannot import name 'WatermarkEncoder' from 'imWatermark' I'm trying to run stable diffusion on my local pc. It's a macbook pro m1. Even though I did follow every single step, I keep getting an import error. What might possibly be the reason and how may I fix it? ImportError: cannot import name 'WatermarkEncoder' from 'imWatermark' I was referring an online tutorial so I did end up searching through the comments. Found nothing so far. A: If you look in the txt2img.py script it references https://github.com/ShieldMnt/invisible-watermark Install with pip install invisible-watermark A: It seems they forgot to add it into requirements.txt or smt like that. If you continue getting the error after invisible-watermark installation, change the line from imWatermark import WatermarkEncoder in txt2img.py to from imwatermark import WatermarkEncoder (lowercase)
ImportError: cannot import name 'WatermarkEncoder' from 'imWatermark'
I'm trying to run stable diffusion on my local pc. It's a macbook pro m1. Even though I did follow every single step, I keep getting an import error. What might possibly be the reason and how may I fix it? ImportError: cannot import name 'WatermarkEncoder' from 'imWatermark' I was referring an online tutorial so I did end up searching through the comments. Found nothing so far.
[ "If you look in the txt2img.py script it references https://github.com/ShieldMnt/invisible-watermark\nInstall with pip install invisible-watermark\n", "It seems they forgot to add it into requirements.txt or smt like that.\nIf you continue getting the error after invisible-watermark installation, change the line from imWatermark import WatermarkEncoder in txt2img.py to from imwatermark import WatermarkEncoder (lowercase)\n" ]
[ 1, 0 ]
[]
[]
[ "importerror", "python", "python_import", "stable_diffusion", "watermark" ]
stackoverflow_0074524544_importerror_python_python_import_stable_diffusion_watermark.txt
Q: Scipy linear programming doesn't give the correct answer I am trying to solve the following problem using Scipy. However, it doesn't produce the correct result. r is the only decision variable that we have. Since the equation (2) doesn't follow the Scipy's required format of Ab <= ub I modified to the following form. Following is my implemented code: # Objective function def objective(): return [time[e] for e in edge] # setting the bounds for the decision variables def bounds(): return [(0, V[e[0]]) for e in edge] # generating the constraints def constraints(): b = [] A = [] const = [] const_2 = [] for i in region: for e in edge: if e[0] != e[1] and (e[0]==i or e[1]==i): if (e[0]==i): const.append(1) const_2.append(1) else: const.append(-1) const_2.append(0) else: const.append(0) const_2.append(0) # const 1 \sum (r_{ij} - r_{ji}) \leq V_i - D_i A.append(const) b.append(V[i] - D[i]) # const 2 \sum r_{ij} <= V_i A.append(const_2) b.append(V[i]) const = [] const_2 = [] return A, b obj_fn = objective() a_up, b_up = constraints() res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds()) When I run the code it prodeces the following result for each edge i.e., r_e: {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0} However, it is not equal to the result produced by CPLEX (The cplex result is the correct one which I use to compare my results to): {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0} I am not sure, but I think the problem is with the constraints. Can someone help me to find out what my mistake is here please? The minimum required data to run the code: V = {0: 1, 1: 71, 2: 6, 3: 0, 4: 34, 5: 51, 6: 88, 7: 61, 8: 0, 9: 0, 10: 43, 11: 62, 12: 144, 13: 36, 14: 0, 15: 12} D = {0: 94, 1: 16, 2: 38, 3: 6, 4: 66, 5: 22, 6: 134, 7: 8, 8: 46, 9: 6, 10: 3, 11: 36, 12: 39, 13: 26, 14: 40, 15: 22} edge = [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (0, 10), (0, 11), (0, 12), (0, 13), (0, 14), (0, 15), (1, 0), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (2, 0), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13), (2, 14), (2, 15), (3, 0), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (3, 12), (3, 13), (3, 14), (3, 15), (4, 0), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (4, 12), (4, 13), (4, 14), (4, 15), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10), (5, 11), (5, 12), (5, 13), (5, 14), (5, 15), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (6, 12), (6, 13), (6, 14), (6, 15), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 8), (7, 9), (7, 10), (7, 11), (7, 12), (7, 13), (7, 14), (7, 15), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 9), (8, 10), (8, 11), (8, 12), (8, 13), (8, 14), (8, 15), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8), (9, 10), (9, 11), (9, 12), (9, 13), (9, 14), (9, 15), (10, 0), (10, 1), (10, 2), (10, 3), (10, 4), (10, 5), (10, 6), (10, 7), (10, 8), (10, 9), (10, 11), (10, 12), (10, 13), (10, 14), (10, 15), (11, 0), (11, 1), (11, 2), (11, 3), (11, 4), (11, 5), (11, 6), (11, 7), (11, 8), (11, 9), (11, 10), (11, 12), (11, 13), (11, 14), (11, 15), (12, 0), (12, 1), (12, 2), (12, 3), (12, 4), (12, 5), (12, 6), (12, 7), (12, 8), (12, 9), (12, 10), (12, 11), (12, 13), (12, 14), (12, 15), (13, 0), (13, 1), (13, 2), (13, 3), (13, 4), (13, 5), (13, 6), (13, 7), (13, 8), (13, 9), (13, 10), (13, 11), (13, 12), (13, 14), (13, 15), (14, 0), (14, 1), (14, 2), (14, 3), (14, 4), (14, 5), (14, 6), (14, 7), (14, 8), (14, 9), (14, 10), (14, 11), (14, 12), (14, 13), (14, 15), (15, 0), (15, 1), (15, 2), (15, 3), (15, 4), (15, 5), (15, 6), (15, 7), (15, 8), (15, 9), (15, 10), (15, 11), (15, 12), (15, 13), (15, 14)] region = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] time = {(0, 1): 1, (0, 2): 1, (0, 3): 2, (0, 4): 2, (0, 5): 2, (0, 6): 2, (0, 7): 3, (0, 8): 3, (0, 9): 3, (0, 10): 3, (0, 11): 4, (0, 12): 4, (0, 13): 3, (0, 14): 4, (0, 15): 5, (1, 0): 1, (1, 2): 1, (1, 3): 1, (1, 4): 2, (1, 5): 2, (1, 6): 2, (1, 7): 3, (1, 8): 3, (1, 9): 3, (1, 10): 3, (1, 11): 4, (1, 12): 4, (1, 13): 3, (1, 14): 4, (1, 15): 4, (2, 0): 2, (2, 1): 1, (2, 3): 1, (2, 4): 3, (2, 5): 2, (2, 6): 2, (2, 7): 2, (2, 8): 4, (2, 9): 3, (2, 10): 3, (2, 11): 3, (2, 12): 5, (2, 13): 4, (2, 14): 4, (2, 15): 4, (3, 0): 2, (3, 1): 2, (3, 2): 1, (3, 4): 3, (3, 5): 3, (3, 6): 2, (3, 7): 2, (3, 8): 4, (3, 9): 4, (3, 10): 3, (3, 11): 3, (3, 12): 5, (3, 13): 5, (3, 14): 5, (3, 15): 4, (4, 0): 2, (4, 1): 2, (4, 2): 2, (4, 3): 3, (4, 5): 1, (4, 6): 2, (4, 7): 2, (4, 8): 2, (4, 9): 2, (4, 10): 2, (4, 11): 3, (4, 12): 2, (4, 13): 3, (4, 14): 3, (4, 15): 4, (5, 0): 2, (5, 1): 2, (5, 2): 2, (5, 3): 2, (5, 4): 1, (5, 6): 2, (5, 7): 2, (5, 8): 2, (5, 9): 2, (5, 10): 2, (5, 11): 3, (5, 12): 3, (5, 13): 2, (5, 14): 3, (5, 15): 3, (6, 0): 2, (6, 1): 2, (6, 2): 2, (6, 3): 2, (6, 4): 2, (6, 5): 1, (6, 7): 1, (6, 8): 3, (6, 9): 2, (6, 10): 2, (6, 11): 2, (6, 12): 3, (6, 13): 3, (6, 14): 3, (6, 15): 3, (7, 0): 3, (7, 1): 3, (7, 2): 2, (7, 3): 2, (7, 4): 2, (7, 5): 2, (7, 6): 2, (7, 8): 3, (7, 9): 3, (7, 10): 2, (7, 11): 2, (7, 12): 4, (7, 13): 4, (7, 14): 3, (7, 15): 3, (8, 0): 3, (8, 1): 3, (8, 2): 3, (8, 3): 3, (8, 4): 1, (8, 5): 2, (8, 6): 3, (8, 7): 3, (8, 9): 2, (8, 10): 2, (8, 11): 2, (8, 12): 1, (8, 13): 2, (8, 14): 2, (8, 15): 3, (9, 0): 3, (9, 1): 3, (9, 2): 3, (9, 3): 4, (9, 4): 2, (9, 5): 2, (9, 6): 2, (9, 7): 3, (9, 8): 2, (9, 10): 2, (9, 11): 2, (9, 12): 2, (9, 13): 1, (9, 14): 2, (9, 15): 2, (10, 0): 4, (10, 1): 3, (10, 2): 3, (10, 3): 3, (10, 4): 3, (10, 5): 2, (10, 6): 2, (10, 7): 2, (10, 8): 2, (10, 9): 2, (10, 11): 2, (10, 12): 2, (10, 13): 2, (10, 14): 2, (10, 15): 2, (11, 0): 4, (11, 1): 4, (11, 2): 3, (11, 3): 2, (11, 4): 3, (11, 5): 3, (11, 6): 2, (11, 7): 2, (11, 8): 2, (11, 9): 2, (11, 10): 2, (11, 12): 2, (11, 13): 3, (11, 14): 2, (11, 15): 1, (12, 0): 3, (12, 1): 4, (12, 2): 4, (12, 3): 4, (12, 4): 2, (12, 5): 3, (12, 6): 3, (12, 7): 4, (12, 8): 1, (12, 9): 2, (12, 10): 2, (12, 11): 3, (12, 13): 1, (12, 14): 2, (12, 15): 2, (13, 0): 5, (13, 1): 3, (13, 2): 4, (13, 3): 5, (13, 4): 3, (13, 5): 3, (13, 6): 3, (13, 7): 3, (13, 8): 2, (13, 9): 2, (13, 10): 2, (13, 11): 2, (13, 12): 2, (13, 14): 1, (13, 15): 2, (14, 0): 5, (14, 1): 4, (14, 2): 4, (14, 3): 4, (14, 4): 3, (14, 5): 3, (14, 6): 3, (14, 7): 3, (14, 8): 2, (14, 9): 2, (14, 10): 2, (14, 11): 2, (14, 12): 2, (14, 13): 1, (14, 15): 1, (15, 0): 5, (15, 1): 5, (15, 2): 4, (15, 3): 4, (15, 4): 4, (15, 5): 3, (15, 6): 3, (15, 7): 3, (15, 8): 3, (15, 9): 2, (15, 10): 2, (15, 11): 2, (15, 12): 2, (15, 13): 2, (15, 14): 2} A: Your problem does not have a unique solution. Both the Scipy and CPLEX solutions are equivalent in that they have the same OF value. Here's a verification: S_scipy = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0} S_cplex = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0} sum([S_scipy[s]*time[s] for s in S_scipy]) == sum([S_cplex[s]*time[s] for s in S_cplex]) > True A: res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds()) are you callling obj_fn or Objetc()?
Scipy linear programming doesn't give the correct answer
I am trying to solve the following problem using Scipy. However, it doesn't produce the correct result. r is the only decision variable that we have. Since the equation (2) doesn't follow the Scipy's required format of Ab <= ub I modified to the following form. Following is my implemented code: # Objective function def objective(): return [time[e] for e in edge] # setting the bounds for the decision variables def bounds(): return [(0, V[e[0]]) for e in edge] # generating the constraints def constraints(): b = [] A = [] const = [] const_2 = [] for i in region: for e in edge: if e[0] != e[1] and (e[0]==i or e[1]==i): if (e[0]==i): const.append(1) const_2.append(1) else: const.append(-1) const_2.append(0) else: const.append(0) const_2.append(0) # const 1 \sum (r_{ij} - r_{ji}) \leq V_i - D_i A.append(const) b.append(V[i] - D[i]) # const 2 \sum r_{ij} <= V_i A.append(const_2) b.append(V[i]) const = [] const_2 = [] return A, b obj_fn = objective() a_up, b_up = constraints() res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds()) When I run the code it prodeces the following result for each edge i.e., r_e: {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0} However, it is not equal to the result produced by CPLEX (The cplex result is the correct one which I use to compare my results to): {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0} I am not sure, but I think the problem is with the constraints. Can someone help me to find out what my mistake is here please? The minimum required data to run the code: V = {0: 1, 1: 71, 2: 6, 3: 0, 4: 34, 5: 51, 6: 88, 7: 61, 8: 0, 9: 0, 10: 43, 11: 62, 12: 144, 13: 36, 14: 0, 15: 12} D = {0: 94, 1: 16, 2: 38, 3: 6, 4: 66, 5: 22, 6: 134, 7: 8, 8: 46, 9: 6, 10: 3, 11: 36, 12: 39, 13: 26, 14: 40, 15: 22} edge = [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (0, 10), (0, 11), (0, 12), (0, 13), (0, 14), (0, 15), (1, 0), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (2, 0), (2, 1), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13), (2, 14), (2, 15), (3, 0), (3, 1), (3, 2), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (3, 10), (3, 11), (3, 12), (3, 13), (3, 14), (3, 15), (4, 0), (4, 1), (4, 2), (4, 3), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (4, 10), (4, 11), (4, 12), (4, 13), (4, 14), (4, 15), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 6), (5, 7), (5, 8), (5, 9), (5, 10), (5, 11), (5, 12), (5, 13), (5, 14), (5, 15), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (6, 12), (6, 13), (6, 14), (6, 15), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 8), (7, 9), (7, 10), (7, 11), (7, 12), (7, 13), (7, 14), (7, 15), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 9), (8, 10), (8, 11), (8, 12), (8, 13), (8, 14), (8, 15), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8), (9, 10), (9, 11), (9, 12), (9, 13), (9, 14), (9, 15), (10, 0), (10, 1), (10, 2), (10, 3), (10, 4), (10, 5), (10, 6), (10, 7), (10, 8), (10, 9), (10, 11), (10, 12), (10, 13), (10, 14), (10, 15), (11, 0), (11, 1), (11, 2), (11, 3), (11, 4), (11, 5), (11, 6), (11, 7), (11, 8), (11, 9), (11, 10), (11, 12), (11, 13), (11, 14), (11, 15), (12, 0), (12, 1), (12, 2), (12, 3), (12, 4), (12, 5), (12, 6), (12, 7), (12, 8), (12, 9), (12, 10), (12, 11), (12, 13), (12, 14), (12, 15), (13, 0), (13, 1), (13, 2), (13, 3), (13, 4), (13, 5), (13, 6), (13, 7), (13, 8), (13, 9), (13, 10), (13, 11), (13, 12), (13, 14), (13, 15), (14, 0), (14, 1), (14, 2), (14, 3), (14, 4), (14, 5), (14, 6), (14, 7), (14, 8), (14, 9), (14, 10), (14, 11), (14, 12), (14, 13), (14, 15), (15, 0), (15, 1), (15, 2), (15, 3), (15, 4), (15, 5), (15, 6), (15, 7), (15, 8), (15, 9), (15, 10), (15, 11), (15, 12), (15, 13), (15, 14)] region = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] time = {(0, 1): 1, (0, 2): 1, (0, 3): 2, (0, 4): 2, (0, 5): 2, (0, 6): 2, (0, 7): 3, (0, 8): 3, (0, 9): 3, (0, 10): 3, (0, 11): 4, (0, 12): 4, (0, 13): 3, (0, 14): 4, (0, 15): 5, (1, 0): 1, (1, 2): 1, (1, 3): 1, (1, 4): 2, (1, 5): 2, (1, 6): 2, (1, 7): 3, (1, 8): 3, (1, 9): 3, (1, 10): 3, (1, 11): 4, (1, 12): 4, (1, 13): 3, (1, 14): 4, (1, 15): 4, (2, 0): 2, (2, 1): 1, (2, 3): 1, (2, 4): 3, (2, 5): 2, (2, 6): 2, (2, 7): 2, (2, 8): 4, (2, 9): 3, (2, 10): 3, (2, 11): 3, (2, 12): 5, (2, 13): 4, (2, 14): 4, (2, 15): 4, (3, 0): 2, (3, 1): 2, (3, 2): 1, (3, 4): 3, (3, 5): 3, (3, 6): 2, (3, 7): 2, (3, 8): 4, (3, 9): 4, (3, 10): 3, (3, 11): 3, (3, 12): 5, (3, 13): 5, (3, 14): 5, (3, 15): 4, (4, 0): 2, (4, 1): 2, (4, 2): 2, (4, 3): 3, (4, 5): 1, (4, 6): 2, (4, 7): 2, (4, 8): 2, (4, 9): 2, (4, 10): 2, (4, 11): 3, (4, 12): 2, (4, 13): 3, (4, 14): 3, (4, 15): 4, (5, 0): 2, (5, 1): 2, (5, 2): 2, (5, 3): 2, (5, 4): 1, (5, 6): 2, (5, 7): 2, (5, 8): 2, (5, 9): 2, (5, 10): 2, (5, 11): 3, (5, 12): 3, (5, 13): 2, (5, 14): 3, (5, 15): 3, (6, 0): 2, (6, 1): 2, (6, 2): 2, (6, 3): 2, (6, 4): 2, (6, 5): 1, (6, 7): 1, (6, 8): 3, (6, 9): 2, (6, 10): 2, (6, 11): 2, (6, 12): 3, (6, 13): 3, (6, 14): 3, (6, 15): 3, (7, 0): 3, (7, 1): 3, (7, 2): 2, (7, 3): 2, (7, 4): 2, (7, 5): 2, (7, 6): 2, (7, 8): 3, (7, 9): 3, (7, 10): 2, (7, 11): 2, (7, 12): 4, (7, 13): 4, (7, 14): 3, (7, 15): 3, (8, 0): 3, (8, 1): 3, (8, 2): 3, (8, 3): 3, (8, 4): 1, (8, 5): 2, (8, 6): 3, (8, 7): 3, (8, 9): 2, (8, 10): 2, (8, 11): 2, (8, 12): 1, (8, 13): 2, (8, 14): 2, (8, 15): 3, (9, 0): 3, (9, 1): 3, (9, 2): 3, (9, 3): 4, (9, 4): 2, (9, 5): 2, (9, 6): 2, (9, 7): 3, (9, 8): 2, (9, 10): 2, (9, 11): 2, (9, 12): 2, (9, 13): 1, (9, 14): 2, (9, 15): 2, (10, 0): 4, (10, 1): 3, (10, 2): 3, (10, 3): 3, (10, 4): 3, (10, 5): 2, (10, 6): 2, (10, 7): 2, (10, 8): 2, (10, 9): 2, (10, 11): 2, (10, 12): 2, (10, 13): 2, (10, 14): 2, (10, 15): 2, (11, 0): 4, (11, 1): 4, (11, 2): 3, (11, 3): 2, (11, 4): 3, (11, 5): 3, (11, 6): 2, (11, 7): 2, (11, 8): 2, (11, 9): 2, (11, 10): 2, (11, 12): 2, (11, 13): 3, (11, 14): 2, (11, 15): 1, (12, 0): 3, (12, 1): 4, (12, 2): 4, (12, 3): 4, (12, 4): 2, (12, 5): 3, (12, 6): 3, (12, 7): 4, (12, 8): 1, (12, 9): 2, (12, 10): 2, (12, 11): 3, (12, 13): 1, (12, 14): 2, (12, 15): 2, (13, 0): 5, (13, 1): 3, (13, 2): 4, (13, 3): 5, (13, 4): 3, (13, 5): 3, (13, 6): 3, (13, 7): 3, (13, 8): 2, (13, 9): 2, (13, 10): 2, (13, 11): 2, (13, 12): 2, (13, 14): 1, (13, 15): 2, (14, 0): 5, (14, 1): 4, (14, 2): 4, (14, 3): 4, (14, 4): 3, (14, 5): 3, (14, 6): 3, (14, 7): 3, (14, 8): 2, (14, 9): 2, (14, 10): 2, (14, 11): 2, (14, 12): 2, (14, 13): 1, (14, 15): 1, (15, 0): 5, (15, 1): 5, (15, 2): 4, (15, 3): 4, (15, 4): 4, (15, 5): 3, (15, 6): 3, (15, 7): 3, (15, 8): 3, (15, 9): 2, (15, 10): 2, (15, 11): 2, (15, 12): 2, (15, 13): 2, (15, 14): 2}
[ "Your problem does not have a unique solution. Both the Scipy and CPLEX solutions are equivalent in that they have the same OF value. Here's a verification:\nS_scipy = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 0, (7, 1): 0, (7, 2): 32, (7, 3): 0, (7, 4): 0, (7, 5): 0, (7, 6): 21, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 25, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 15, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 6, (11, 4): 0, (11, 5): 0, (11, 6): 0, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 10, (11, 15): 10, (12, 0): 38, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 3, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 5, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 15, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nS_cplex = {(0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0, (0, 10): 0, (0, 11): 0, (0, 12): 0, (0, 13): 0, (0, 14): 0, (0, 15): 0, (1, 0): 55, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0, (1, 10): 0, (1, 11): 0, (1, 12): 0, (1, 13): 0, (1, 14): 0, (1, 15): 0, (2, 0): 0, (2, 1): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0, (2, 10): 0, (2, 11): 0, (2, 12): 0, (2, 13): 0, (2, 14): 0, (2, 15): 0, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0, (3, 10): 0, (3, 11): 0, (3, 12): 0, (3, 13): 0, (3, 14): 0, (3, 15): 0, (4, 0): 0, (4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 5): 0, (4, 6): 0, (4, 7): 0, (4, 8): 0, (4, 9): 0, (4, 10): 0, (4, 11): 0, (4, 12): 0, (4, 13): 0, (4, 14): 0, (4, 15): 0, (5, 0): 0, (5, 1): 0, (5, 2): 0, (5, 3): 0, (5, 4): 29, (5, 6): 0, (5, 7): 0, (5, 8): 0, (5, 9): 0, (5, 10): 0, (5, 11): 0, (5, 12): 0, (5, 13): 0, (5, 14): 0, (5, 15): 0, (6, 0): 0, (6, 1): 0, (6, 2): 0, (6, 3): 0, (6, 4): 0, (6, 5): 0, (6, 7): 0, (6, 8): 0, (6, 9): 0, (6, 10): 0, (6, 11): 0, (6, 12): 0, (6, 13): 0, (6, 14): 0, (6, 15): 0, (7, 0): 12, (7, 1): 0, (7, 2): 32, (7, 3): 6, (7, 4): 3, (7, 5): 0, (7, 6): 0, (7, 8): 0, (7, 9): 0, (7, 10): 0, (7, 11): 0, (7, 12): 0, (7, 13): 0, (7, 14): 0, (7, 15): 0, (8, 0): 0, (8, 1): 0, (8, 2): 0, (8, 3): 0, (8, 4): 0, (8, 5): 0, (8, 6): 0, (8, 7): 0, (8, 9): 0, (8, 10): 0, (8, 11): 0, (8, 12): 0, (8, 13): 0, (8, 14): 0, (8, 15): 0, (9, 0): 0, (9, 1): 0, (9, 2): 0, (9, 3): 0, (9, 4): 0, (9, 5): 0, (9, 6): 0, (9, 7): 0, (9, 8): 0, (9, 10): 0, (9, 11): 0, (9, 12): 0, (9, 13): 0, (9, 14): 0, (9, 15): 0, (10, 0): 0, (10, 1): 0, (10, 2): 0, (10, 3): 0, (10, 4): 0, (10, 5): 0, (10, 6): 40, (10, 7): 0, (10, 8): 0, (10, 9): 0, (10, 11): 0, (10, 12): 0, (10, 13): 0, (10, 14): 0, (10, 15): 0, (11, 0): 0, (11, 1): 0, (11, 2): 0, (11, 3): 0, (11, 4): 0, (11, 5): 0, (11, 6): 6, (11, 7): 0, (11, 8): 0, (11, 9): 0, (11, 10): 0, (11, 12): 0, (11, 13): 0, (11, 14): 4, (11, 15): 10, (12, 0): 26, (12, 1): 0, (12, 2): 0, (12, 3): 0, (12, 4): 0, (12, 5): 0, (12, 6): 0, (12, 7): 0, (12, 8): 46, (12, 9): 6, (12, 10): 0, (12, 11): 0, (12, 13): 26, (12, 14): 0, (12, 15): 0, (13, 0): 0, (13, 1): 0, (13, 2): 0, (13, 3): 0, (13, 4): 0, (13, 5): 0, (13, 6): 0, (13, 7): 0, (13, 8): 0, (13, 9): 0, (13, 10): 0, (13, 11): 0, (13, 12): 0, (13, 14): 36, (13, 15): 0, (14, 0): 0, (14, 1): 0, (14, 2): 0, (14, 3): 0, (14, 4): 0, (14, 5): 0, (14, 6): 0, (14, 7): 0, (14, 8): 0, (14, 9): 0, (14, 10): 0, (14, 11): 0, (14, 12): 0, (14, 13): 0, (14, 15): 0, (15, 0): 0, (15, 1): 0, (15, 2): 0, (15, 3): 0, (15, 4): 0, (15, 5): 0, (15, 6): 0, (15, 7): 0, (15, 8): 0, (15, 9): 0, (15, 10): 0, (15, 11): 0, (15, 12): 0, (15, 13): 0, (15, 14): 0}\n\nsum([S_scipy[s]*time[s] for s in S_scipy]) == sum([S_cplex[s]*time[s] for s in S_cplex])\n\n> True\n\n", "res = linprog(obj_fn, A_ub=a_up, b_ub=b_up, bounds=bounds())\n\nare you callling obj_fn or Objetc()?\n" ]
[ 1, 0 ]
[]
[]
[ "linear_programming", "python", "scipy" ]
stackoverflow_0074585512_linear_programming_python_scipy.txt
Q: Trying to add a progress bar as my python program runs I am a beginner writing a Python code, where the computer generates a random number between 1 and 10, 1 and 100, 1 and 1000, 1 and 10000, 1 and 100000 and so on. The computer itself will guess the random number a number of times (a user input number), and every time there is a count of how many times the computer took to guess the random number. A mean of the count over the number of times will be calculated and put in an array, where matplotlib will generate a graph of x=log10(the upper bounds of the random number range, i.e. 10, 100, 1000,...) At the moment, I print the log10 of each bound as it is processed, and that has been acting as my progress tracker. But I am thinking of adding my progress bar, and I don't know where to put it so that I can see how much of the overall program has run. I have added tqdm.tqdm in all sorts of different places to no avail. I am expecting a progress bar increasing as the program runs. My program is as shown. # Importing the modules needed import random import time import timeit import numpy as np import matplotlib.pyplot as plt import tqdm # Function for making the computer guess the number it itself has generated and seeing how many times it takes for it to guess the number def computer_guess(x): # Telling program that value "low" exists and it's 0 low = 0 # Telling program that value "high" exists and it's the arbitrary parameter x high = x # Storing random number with lower limit "low" and upper limit "high" as "ranno" for the while-loop later ranno = random.randint(low, high) # Setting initial value of "guess" for iteration guess = -1 # Setting initial value of "count" for iteration count = 1 # While-loop for all guessing conditions while guess != ranno: # Condition: As long as values of "low" and "high" aren't the same, keep guessing until the values are the same, in which case "guess" is same as "low" (or "high" becuase they are the same anyway) if low != high: guess = random.randint(low, high) else: guess = low # Condition: If the guess if bigger than the random number, lower the "high" value to one less than 1, and add 1 to the guess count if guess > ranno: high = guess - 1 count += 1 # Condition: If the guess if smaller than the random number, increase the "low" value to one more than 1, and add 1 to the guess count elif guess < ranno: low = guess + 1 count += 1 # Condition: If it's not either of the above, i.e. the computer has guessed the number, return the guess count for this function else: return count # Setting up a global array "upper_bounds" of the range of range of random numbers as a log array from 10^1 to 10^50 upper_bounds = np.logspace(1, 50, 50, 10) def guess_avg(no_of_guesses): # Empty array for all averages list_of_averages = [] # For every value in the "upper_bounds" array, for bound in upper_bounds: # choose random number, "ranx", between 0 and the bound in the array ranx = random.randint(0, bound) # make an empty Numpy array, "guess_array", to insert the guesses into guess_array = np.array([]) # For every value in whatever the no_of_guesses is when function called, for i in np.arange(no_of_guesses): # assign value, "guess", as calling function with value "ranx" guess = computer_guess(ranx) # stuff each resultant guess into the "guess_array" array guess_array = np.append(guess_array, guess) # Print log10 of each value in "upper_bound" print(int(np.log10(bound))) # Finding the mean of each value of the array of all guesses for the order of magnitude average_of_guesses = np.mean(guess_array) # Stuff the averages of guesses into the array the empty array made before list_of_averages.append(average_of_guesses) # Save the average of all averages in the list of averages into a single variable average_of_averages = np.mean(list_of_averages) # Print the list of averages print(f"Your list of averages: {list_of_averages}") # Print the average of averages print(f"Average of averages: {average_of_averages}") return list_of_averages # Repeat the "guess_avg" function as long as the program is running while True: # Ask user to input a number for how many guesses they want the computer to make for each order of magnitude, and use that number for calling the function "guess_avg()" resultant_average_numbers = guess_avg( int(input("Input the number of guesses you want the computer to make: "))) # Plot a graph with log10 of the order of magnitudes on the horizontal and the returned number of average of guesses plt.plot(np.log10(upper_bounds), resultant_average_numbers) # Show plot plt.show() I apologise if this is badly explained, it's my first time using Stackoverflow. A: You can define the following progress_bar function, which you will call from wherever you want to monitor the advancement in you code: import colorama def progress_bar(progress, total, color=colorama.Fore.YELLOW): percent = 100 * (progress / float(total)) bar = '█' * int(percent) + '-' * (100 - int(percent)) print(color + f'\r|{bar}| {percent:.2f}%', end='\r') if progress == total: print(colorama.Fore.GREEN + f'\r|{bar}| {percent:.2f}%', end='\r') Hope this helps A: You can also call tqdm by hand and then update it manually. progress_bar = tqdm.tqdm(total=100) progress_bar.update() When you are finished, you can call progress_bar.clear() to start again. A: You probably want two progress bars in the guess_avg() function. One to track the ranges and another to track the guesses. In this example I've used the Enlighten progress bar library, but you can accomplish similar behavior with other libraries that support nested progress bars. One advantage Enlighten is going to have over others is you can print whatever you want while the progress bar is running, good for debugging. You can make this simpler by using context managers and auto-updating counters, but I didn't do that here to make it clearer what's happening. You can also customize the template used for the progress bar. import enlighten def guess_avg(no_of_guesses): # Empty array for all averages list_of_averages = [] # For every value in the "upper_bounds" array, # Create a progress bar manager manager manager = enlighten.get_manager(leave=False) # Create main progress bar for ranges pbar_bounds = manager.counter(total=len(upper_bounds), desc='Bound ranges', unit='ranges') for bound in upper_bounds: # choose random number, "ranx", between 0 and the bound in the array ranx = random.randint(0, bound) # make an empty Numpy array, "guess_array", to insert the guesses into guess_array = np.array([]) # For every value in whatever the no_of_guesses is when function called, # Create nested progress bar for guesses, leave removes progress bar on close pbar_guesses = manager.counter(total=no_of_guesses, desc='Guessing', unit='guesses', leave=False) for i in np.arange(no_of_guesses): # assign value, "guess", as calling function with value "ranx" guess = computer_guess(ranx) # stuff each resultant guess into the "guess_array" array guess_array = np.append(guess_array, guess) pbar_guesses.update() # Update nested progress bar pbar_guesses.close() # Close nested progress bar # Print log10 of each value in "upper_bound" print(int(np.log10(bound))) # You can remove this now if you want pbar_bounds.update() # Update main progress bar # Finding the mean of each value of the array of all guesses for the order of magnitude average_of_guesses = np.mean(guess_array) # Stuff the averages of guesses into the array the empty array made before list_of_averages.append(average_of_guesses) manager.stop() # Stop the progress bar manager # Save the average of all averages in the list of averages into a single variable average_of_averages = np.mean(list_of_averages) # Print the list of averages print(f"Your list of averages: {list_of_averages}") # Print the average of averages print(f"Average of averages: {average_of_averages}") return list_of_averages
Trying to add a progress bar as my python program runs
I am a beginner writing a Python code, where the computer generates a random number between 1 and 10, 1 and 100, 1 and 1000, 1 and 10000, 1 and 100000 and so on. The computer itself will guess the random number a number of times (a user input number), and every time there is a count of how many times the computer took to guess the random number. A mean of the count over the number of times will be calculated and put in an array, where matplotlib will generate a graph of x=log10(the upper bounds of the random number range, i.e. 10, 100, 1000,...) At the moment, I print the log10 of each bound as it is processed, and that has been acting as my progress tracker. But I am thinking of adding my progress bar, and I don't know where to put it so that I can see how much of the overall program has run. I have added tqdm.tqdm in all sorts of different places to no avail. I am expecting a progress bar increasing as the program runs. My program is as shown. # Importing the modules needed import random import time import timeit import numpy as np import matplotlib.pyplot as plt import tqdm # Function for making the computer guess the number it itself has generated and seeing how many times it takes for it to guess the number def computer_guess(x): # Telling program that value "low" exists and it's 0 low = 0 # Telling program that value "high" exists and it's the arbitrary parameter x high = x # Storing random number with lower limit "low" and upper limit "high" as "ranno" for the while-loop later ranno = random.randint(low, high) # Setting initial value of "guess" for iteration guess = -1 # Setting initial value of "count" for iteration count = 1 # While-loop for all guessing conditions while guess != ranno: # Condition: As long as values of "low" and "high" aren't the same, keep guessing until the values are the same, in which case "guess" is same as "low" (or "high" becuase they are the same anyway) if low != high: guess = random.randint(low, high) else: guess = low # Condition: If the guess if bigger than the random number, lower the "high" value to one less than 1, and add 1 to the guess count if guess > ranno: high = guess - 1 count += 1 # Condition: If the guess if smaller than the random number, increase the "low" value to one more than 1, and add 1 to the guess count elif guess < ranno: low = guess + 1 count += 1 # Condition: If it's not either of the above, i.e. the computer has guessed the number, return the guess count for this function else: return count # Setting up a global array "upper_bounds" of the range of range of random numbers as a log array from 10^1 to 10^50 upper_bounds = np.logspace(1, 50, 50, 10) def guess_avg(no_of_guesses): # Empty array for all averages list_of_averages = [] # For every value in the "upper_bounds" array, for bound in upper_bounds: # choose random number, "ranx", between 0 and the bound in the array ranx = random.randint(0, bound) # make an empty Numpy array, "guess_array", to insert the guesses into guess_array = np.array([]) # For every value in whatever the no_of_guesses is when function called, for i in np.arange(no_of_guesses): # assign value, "guess", as calling function with value "ranx" guess = computer_guess(ranx) # stuff each resultant guess into the "guess_array" array guess_array = np.append(guess_array, guess) # Print log10 of each value in "upper_bound" print(int(np.log10(bound))) # Finding the mean of each value of the array of all guesses for the order of magnitude average_of_guesses = np.mean(guess_array) # Stuff the averages of guesses into the array the empty array made before list_of_averages.append(average_of_guesses) # Save the average of all averages in the list of averages into a single variable average_of_averages = np.mean(list_of_averages) # Print the list of averages print(f"Your list of averages: {list_of_averages}") # Print the average of averages print(f"Average of averages: {average_of_averages}") return list_of_averages # Repeat the "guess_avg" function as long as the program is running while True: # Ask user to input a number for how many guesses they want the computer to make for each order of magnitude, and use that number for calling the function "guess_avg()" resultant_average_numbers = guess_avg( int(input("Input the number of guesses you want the computer to make: "))) # Plot a graph with log10 of the order of magnitudes on the horizontal and the returned number of average of guesses plt.plot(np.log10(upper_bounds), resultant_average_numbers) # Show plot plt.show() I apologise if this is badly explained, it's my first time using Stackoverflow.
[ "You can define the following progress_bar function, which you will call from wherever you want to monitor the advancement in you code:\nimport colorama\ndef progress_bar(progress, total, color=colorama.Fore.YELLOW):\n percent = 100 * (progress / float(total))\n bar = '█' * int(percent) + '-' * (100 - int(percent))\n print(color + f'\\r|{bar}| {percent:.2f}%', end='\\r')\n if progress == total:\n print(colorama.Fore.GREEN + f'\\r|{bar}| {percent:.2f}%', end='\\r')\n\nHope this helps\n", "You can also call tqdm by hand and then update it manually.\nprogress_bar = tqdm.tqdm(total=100)\nprogress_bar.update()\n\nWhen you are finished, you can call progress_bar.clear() to start again.\n", "You probably want two progress bars in the guess_avg() function. One to track the ranges and another to track the guesses.\nIn this example I've used the Enlighten progress bar library, but you can accomplish similar behavior with other libraries that support nested progress bars. One advantage Enlighten is going to have over others is you can print whatever you want while the progress bar is running, good for debugging.\nYou can make this simpler by using context managers and auto-updating counters, but I didn't do that here to make it clearer what's happening. You can also customize the template used for the progress bar.\nimport enlighten\n\ndef guess_avg(no_of_guesses):\n # Empty array for all averages\n list_of_averages = []\n\n # For every value in the \"upper_bounds\" array,\n\n # Create a progress bar manager manager\n manager = enlighten.get_manager(leave=False)\n # Create main progress bar for ranges\n pbar_bounds = manager.counter(total=len(upper_bounds), desc='Bound ranges', unit='ranges')\n for bound in upper_bounds:\n # choose random number, \"ranx\", between 0 and the bound in the array\n ranx = random.randint(0, bound)\n # make an empty Numpy array, \"guess_array\", to insert the guesses into\n guess_array = np.array([])\n # For every value in whatever the no_of_guesses is when function called,\n # Create nested progress bar for guesses, leave removes progress bar on close\n pbar_guesses = manager.counter(total=no_of_guesses, desc='Guessing', unit='guesses', leave=False)\n for i in np.arange(no_of_guesses):\n # assign value, \"guess\", as calling function with value \"ranx\"\n guess = computer_guess(ranx)\n # stuff each resultant guess into the \"guess_array\" array\n guess_array = np.append(guess_array, guess)\n pbar_guesses.update() # Update nested progress bar\n pbar_guesses.close() # Close nested progress bar\n\n # Print log10 of each value in \"upper_bound\"\n print(int(np.log10(bound))) # You can remove this now if you want\n pbar_bounds.update() # Update main progress bar\n\n # Finding the mean of each value of the array of all guesses for the order of magnitude\n\n average_of_guesses = np.mean(guess_array)\n # Stuff the averages of guesses into the array the empty array made before\n list_of_averages.append(average_of_guesses)\n manager.stop() # Stop the progress bar manager\n\n # Save the average of all averages in the list of averages into a single variable\n average_of_averages = np.mean(list_of_averages)\n # Print the list of averages\n print(f\"Your list of averages: {list_of_averages}\")\n # Print the average of averages\n print(f\"Average of averages: {average_of_averages}\")\n return list_of_averages\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "for_loop", "progress_bar", "python" ]
stackoverflow_0074536225_for_loop_progress_bar_python.txt
Q: How do I use nested lists properly in that context I need to create a memory game in Python. I need to print a 5x4 (4 rows, 5 elements in a line) field in the console and the fields should have names like a1, b1, c1... in the next row a2, b2, c2 etc. We've already got a list of symbols, which should be used in the game (list1). One of the instructions we have is to create nested lists here, which gives me a hard time. If you see below, I created a nested list, which shuffles the cards and puts them in a list. When I print those, I get the 5x4 row as needed. If an user writes a1 and b2 in the console, I have to print the exact symbols that are placed in that row. However, I have no idea how I should proceed at this point. I had some thoughts, but they seem to be unprofessional... My idea: Create new list with fields a1, b1, etc. and print those. If an user writes a1 and b1, I get the index in the list and find the symbol at the same index in my cards list. --> Nested lists seem to be useless with that idea + creating a new list with fields is probably not wanted in that task cards = ["✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀", "✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀"] My solution so far: def create_grid(cards): random.shuffle(cards) cards2 = [cards[i:i+5] for i in range(0, len(cards), 5)] return cards2 A: Instead of using fields, translate the reference to two indices; one for the row, the other the column. Your nested list appears to use a list of rows, and each nested list is a list of cards at each column. It could be that your nested list actually encodes columns and that each nested list holds cards at each row, but then you only have to swap the row and col variables in one place. Once you have separate row and col variables you can then use those two values to index the nested list: col, row = interpret_reference(reference) card = grid[row][col] where reference is the user's input. Note that grid[row] gives you the inner list of columns, and grid[row][col] then picks the right column. Python lists are indexed with non-negative integers, so numbers from 0 and up. So you need a way to translate the letter (a, b, c, d, e) to an integer column index starting at 0, and the number (1, 2, 3, 4) to an integer value one lower, so "1" becomes 0, etc., an operation defined as a function named interpret_reference(). There are lots of ways of doing that. One simple way would be to use a dictionary for both column letters and row numbers: col_letters = {"a": 0, "b": 1, "c": 2, "d": 3, "e": 4} row_numbers = {"1", 0, "2": 1, "3": 2, "4": 3} def interpret_reference(userinput): col, row = userinput return col_letters[col], row_numbers[row] Note that this returns col, row, the same order as the user input. In my first example code snippet, the variables are then used in the swapped order to index the nested list. If your actual nested list structure is swapped, simply swap the order to grid[col][row]. The interpret_reference() function ignores error handling (where a user enters something that's not a valid reference). The function will raise an exception in that case, either ValueError when the input is not exactly 2 characters, or KeyError when they used a character that's not a valid row or column reference. See Asking the user for input until they give a valid response for methods of handling user input with error handling. There are, as mentioned, other techniques to map the user input to integer numbers. Computers encode text as numbers. What numbers exactly doesn't really matter, but you can rely on the numbers for lower-case ASCII letters (a, b, c, d, etc.) to be consecutive. The ord() function gives you the integer number that the Unicode standard has assigned to a character, and if you then subtract the Unicode number (a codepoint) for the character "a" from that value you get an number starting at 0, provided you started with a lowercase letter: col = ord(col_reference) - ord("a") This sets col to 0 if col_reference is the character "a", 1, if given "b", etc. You could use the same trick for the number input, when entered on the keyboard in response to a input() call, Python receives the number part as a string. Subtract such ASCII digits (characters representing the Arabic numerals used in English) from ord("1") and you get the right row index. The int() type can take a string and interpret it as an integer number. Given the string "1", it returns the integer value 1. Subtract 1 and you are done: row = int(row_reference) - 1 This changes how you handle errors, however; using dictionaries makes it easier to detect incorrect input because only valid input characters are keys in the dictionaries. When using ord() and int(), however, you also have to do extra work to validate that the resulting integers are not negative numbers and not too large (so larger than 3 or 4). E.g. if the user gave you z9 as input, you'd get col = 25 and row = 8 and then you'd get an IndexError when you tried to use those references. And "99" would also work as input, giving you col = -40 because the ASCII character "9" comes before the lowercase letter "a" in the Unicode table (they have integer codepoint numbers 57 and 97, respectively). Side note: your create_grid function changes the cards list in-place. It is probably fine, as long as your other code doesn't expect the card symbols to stay in their original order. You can replace random.shuffle(cards) with shuffled = random.sample(cards, len(cards)) to get a new list that is shuffled without affecting the original cards list. A: As the names are fixed to a1 to d5, you can use the ASCII code using ord for the first letter to get the row index. import random cards = ["✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀", "✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀"] def create_grid(cards): shuffled_cards = cards.copy() random.shuffle(shuffled_cards) cards2 = [shuffled_cards[i:i + 5] for i in range(0, len(shuffled_cards), 5)] return cards2 grid = create_grid(cards) print("Grid:") for line in grid: print(" ".join(line)) print("") while True: field = input("Enter a name of the field (0 to exit): ") if field[0] == '0': break field = field.lower() row = ord(field[0]) - ord('a') column = int(field[1]) - 1 if row >= len(grid) or column >= len(grid[0]): print("The field is out of grid size. Try again.\n") continue print(f"{field}: {grid[row][column]}\n") Output: Grid: ✂ ✂ ❄ ☀ ✉ ✿ ✖ ✈ ★ ♫ ✖ ✉ ♥ ✿ ❄ ♫ ★ ✈ ♥ ☀ Enter a name of the field (0 to exit): a2 a2: ✂ Enter a name of the field (0 to exit): b1 b1: ✿ Enter a name of the field (0 to exit): d4 d4: ♥ Enter a name of the field (0 to exit): e2 The field is out of grid size. Try again. Enter a name of the field (0 to exit): 0 Explanation: I did not modify the original cards list. Rather I copied the content and shuffled them on the copy: shuffled_cards = cards.copy() The program takes field name from the user from range a1 to d4 and then print the value of that index from the grid. I parsed the input from the user and calculated the row and column. Row is calculated by using the ASCII code of the first character and column is calculated by subtracting 1 from the second character of user input as the list is 0 indexed. The grid has a size of 4 x 5. Thus, if user enters some large input, it will tell the user that the input field is our of the grid size. It takes field name from user until user enters 0. You can change it as your need.
How do I use nested lists properly in that context
I need to create a memory game in Python. I need to print a 5x4 (4 rows, 5 elements in a line) field in the console and the fields should have names like a1, b1, c1... in the next row a2, b2, c2 etc. We've already got a list of symbols, which should be used in the game (list1). One of the instructions we have is to create nested lists here, which gives me a hard time. If you see below, I created a nested list, which shuffles the cards and puts them in a list. When I print those, I get the 5x4 row as needed. If an user writes a1 and b2 in the console, I have to print the exact symbols that are placed in that row. However, I have no idea how I should proceed at this point. I had some thoughts, but they seem to be unprofessional... My idea: Create new list with fields a1, b1, etc. and print those. If an user writes a1 and b1, I get the index in the list and find the symbol at the same index in my cards list. --> Nested lists seem to be useless with that idea + creating a new list with fields is probably not wanted in that task cards = ["✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀", "✿", "❄", "★", "♥", "✉", "✂", "✖", "✈", "♫", "☀"] My solution so far: def create_grid(cards): random.shuffle(cards) cards2 = [cards[i:i+5] for i in range(0, len(cards), 5)] return cards2
[ "Instead of using fields, translate the reference to two indices; one for the row, the other the column. Your nested list appears to use a list of rows, and each nested list is a list of cards at each column. It could be that your nested list actually encodes columns and that each nested list holds cards at each row, but then you only have to swap the row and col variables in one place.\nOnce you have separate row and col variables you can then use those two values to index the nested list:\ncol, row = interpret_reference(reference)\ncard = grid[row][col]\n\nwhere reference is the user's input. Note that grid[row] gives you the inner list of columns, and grid[row][col] then picks the right column.\nPython lists are indexed with non-negative integers, so numbers from 0 and up.\nSo you need a way to translate the letter (a, b, c, d, e) to an integer column index starting at 0, and the number (1, 2, 3, 4) to an integer value one lower, so \"1\" becomes 0, etc., an operation defined as a function named interpret_reference().\nThere are lots of ways of doing that. One simple way would be to use a dictionary for both column letters and row numbers:\ncol_letters = {\"a\": 0, \"b\": 1, \"c\": 2, \"d\": 3, \"e\": 4}\nrow_numbers = {\"1\", 0, \"2\": 1, \"3\": 2, \"4\": 3}\n\ndef interpret_reference(userinput):\n col, row = userinput\n return col_letters[col], row_numbers[row]\n\nNote that this returns col, row, the same order as the user input. In my first example code snippet, the variables are then used in the swapped order to index the nested list. If your actual nested list structure is swapped, simply swap the order to grid[col][row].\nThe interpret_reference() function ignores error handling (where a user enters something that's not a valid reference). The function will raise an exception in that case, either ValueError when the input is not exactly 2 characters, or KeyError when they used a character that's not a valid row or column reference. See Asking the user for input until they give a valid response for methods of handling user input with error handling.\nThere are, as mentioned, other techniques to map the user input to integer numbers.\n\nComputers encode text as numbers. What numbers exactly doesn't really matter, but you can rely on the numbers for lower-case ASCII letters (a, b, c, d, etc.) to be consecutive. The ord() function gives you the integer number that the Unicode standard has assigned to a character, and if you then subtract the Unicode number (a codepoint) for the character \"a\" from that value you get an number starting at 0, provided you started with a lowercase letter:\ncol = ord(col_reference) - ord(\"a\")\n\nThis sets col to 0 if col_reference is the character \"a\", 1, if given \"b\", etc.\nYou could use the same trick for the number input, when entered on the keyboard in response to a input() call, Python receives the number part as a string. Subtract such ASCII digits (characters representing the Arabic numerals used in English) from ord(\"1\") and you get the right row index.\n\n\n\nThe int() type can take a string and interpret it as an integer number. Given the string \"1\", it returns the integer value 1. Subtract 1 and you are done:\nrow = int(row_reference) - 1\n\n\n\nThis changes how you handle errors, however; using dictionaries makes it easier to detect incorrect input because only valid input characters are keys in the dictionaries. When using ord() and int(), however, you also have to do extra work to validate that the resulting integers are not negative numbers and not too large (so larger than 3 or 4).\nE.g. if the user gave you z9 as input, you'd get col = 25 and row = 8 and then you'd get an IndexError when you tried to use those references. And \"99\" would also work as input, giving you col = -40 because the ASCII character \"9\" comes before the lowercase letter \"a\" in the Unicode table (they have integer codepoint numbers 57 and 97, respectively).\nSide note: your create_grid function changes the cards list in-place. It is probably fine, as long as your other code doesn't expect the card symbols to stay in their original order. You can replace random.shuffle(cards) with shuffled = random.sample(cards, len(cards)) to get a new list that is shuffled without affecting the original cards list.\n", "As the names are fixed to a1 to d5, you can use the ASCII code using ord for the first letter to get the row index.\nimport random\n\ncards = [\"✿\", \"❄\", \"★\", \"♥\", \"✉\", \"✂\", \"✖\", \"✈\", \"♫\", \"☀\",\n \"✿\", \"❄\", \"★\", \"♥\", \"✉\", \"✂\", \"✖\", \"✈\", \"♫\", \"☀\"]\n\n\ndef create_grid(cards):\n shuffled_cards = cards.copy()\n random.shuffle(shuffled_cards)\n cards2 = [shuffled_cards[i:i + 5] for i in\n range(0, len(shuffled_cards), 5)]\n return cards2\n\n\ngrid = create_grid(cards)\nprint(\"Grid:\")\nfor line in grid:\n print(\" \".join(line))\n\nprint(\"\")\n\nwhile True:\n field = input(\"Enter a name of the field (0 to exit): \")\n if field[0] == '0':\n break\n field = field.lower()\n row = ord(field[0]) - ord('a')\n column = int(field[1]) - 1\n if row >= len(grid) or column >= len(grid[0]):\n print(\"The field is out of grid size. Try again.\\n\")\n continue\n print(f\"{field}: {grid[row][column]}\\n\")\n\nOutput:\nGrid:\n✂ ✂ ❄ ☀ ✉\n✿ ✖ ✈ ★ ♫\n✖ ✉ ♥ ✿ ❄\n♫ ★ ✈ ♥ ☀\n\nEnter a name of the field (0 to exit): a2\na2: ✂\n\nEnter a name of the field (0 to exit): b1\nb1: ✿\n\nEnter a name of the field (0 to exit): d4\nd4: ♥\n\nEnter a name of the field (0 to exit): e2\nThe field is out of grid size. Try again.\n\nEnter a name of the field (0 to exit): 0\n\nExplanation:\n\nI did not modify the original cards list. Rather I copied the content and shuffled them on the copy: shuffled_cards = cards.copy()\nThe program takes field name from the user from range a1 to d4 and then print the value of that index from the grid.\nI parsed the input from the user and calculated the row and column. Row is calculated by using the ASCII code of the first character and column is calculated by subtracting 1 from the second character of user input as the list is 0 indexed.\nThe grid has a size of 4 x 5. Thus, if user enters some large input, it will tell the user that the input field is our of the grid size.\nIt takes field name from user until user enters 0. You can change it as your need.\n\n" ]
[ 2, 1 ]
[]
[]
[ "function", "nested_lists", "printing", "python" ]
stackoverflow_0074590616_function_nested_lists_printing_python.txt
Q: how to enter elements using "input" EDIT: Command lista = [int(i) for i in input("Podaj Liczby: ").split(",")] still doesn't sort. When I try to enter numbers, it does not sort them for me Even if i use "," still doesn't sort. Here's code: lista = [int(i) for i in input("Podaj Liczby: ").split(",")] def sortowaniebabelkowe(): n = len(lista) zmiana = False while n > 1: for l in range(0, n-1): if lista[l]>lista[l+1]: lista[l],lista[l+1]==lista[l+1],lista[l] zamien = True n -= 1 print(lista) if zmiana == False: break sortowaniebabelkowe() A: i think you have to use lista[l],lista[l+1]=lista[l+1],lista[l] insead of lista[l],lista[l+1]==lista[l+1],lista[l] to swap the values. A: I modified above code in to this form lista = [int(i) for i in input("Podaj Liczby: ").split(",")] def sortowaniebabelkowe(): n = len(lista) while n >0: for l in range(0, n-1): if lista[l]>lista[l+1]: lista[l],lista[l+1]=lista[l+1],lista[l] n -= 1 print(lista) sortowaniebabelkowe() Now it works. A: You have several problems in your sorting function. == is a conditional operator and not an assignment operator. The name of your variable zmiana is not same. This implies, that zmiana is never True so the while loop only runs once. The updated code: lista = [int(i) for i in input("Podaj Liczby: ").split(",")] def sortowaniebabelkowe(): n = len(lista) zmiana = False while n > 1: for l in range(0, n-1): if lista[l]>lista[l+1]: lista[l],lista[l+1]=lista[l+1],lista[l] # == is replaced with = zmiana = True #The name of the variable is changed to zmiana n -= 1 print(lista) if zmiana == False: break sortowaniebabelkowe()
how to enter elements using "input"
EDIT: Command lista = [int(i) for i in input("Podaj Liczby: ").split(",")] still doesn't sort. When I try to enter numbers, it does not sort them for me Even if i use "," still doesn't sort. Here's code: lista = [int(i) for i in input("Podaj Liczby: ").split(",")] def sortowaniebabelkowe(): n = len(lista) zmiana = False while n > 1: for l in range(0, n-1): if lista[l]>lista[l+1]: lista[l],lista[l+1]==lista[l+1],lista[l] zamien = True n -= 1 print(lista) if zmiana == False: break sortowaniebabelkowe()
[ "i think you have to use\nlista[l],lista[l+1]=lista[l+1],lista[l]\n\ninsead of\nlista[l],lista[l+1]==lista[l+1],lista[l]\n\nto swap the values.\n", "I modified above code in to this form\nlista = [int(i) for i in input(\"Podaj Liczby: \").split(\",\")]\ndef sortowaniebabelkowe():\n n = len(lista)\n while n >0:\n for l in range(0, n-1): \n if lista[l]>lista[l+1]:\n lista[l],lista[l+1]=lista[l+1],lista[l]\n n -= 1\n print(lista) \nsortowaniebabelkowe()\n\nNow it works.\n", "You have several problems in your sorting function.\n\n== is a conditional operator and not an assignment operator.\nThe name of your variable zmiana is not same. This implies, that zmiana is never True so the while loop only runs once.\n\nThe updated code:\nlista = [int(i) for i in input(\"Podaj Liczby: \").split(\",\")]\ndef sortowaniebabelkowe():\n n = len(lista)\n zmiana = False\n while n > 1:\n for l in range(0, n-1):\n if lista[l]>lista[l+1]:\n lista[l],lista[l+1]=lista[l+1],lista[l] # == is replaced with =\n zmiana = True #The name of the variable is changed to zmiana\n n -= 1\n print(lista)\n if zmiana == False: break\nsortowaniebabelkowe()\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.11" ]
stackoverflow_0074590255_python_python_3.11.txt
Q: Recursively generate LaTeX expression for continued fractions for a given python list I am trying to generate LaTeX string expression for continued fractions in Jupyter Notebook. for example, a given Python list x=[1,2,3,4,5] can be written as continued fraction: Structure expression to generate this LaTeX fraction is \\frac{Numerator}{Denominator} With Non-recursive code : from IPython.display import display, Markdown # Non-recursive: def nest_frac(previous_expr, numerator_expr1, denominator_expr2): return previous_expr + " + \\frac{"+ numerator_expr1 + "}{" + denominator_expr2 + "}" # Cumbersome, error-prone display(Markdown("$"+ \ nest_frac("1","1", \ nest_frac("2","1", \ nest_frac("3","1", \ nest_frac("4","1", "5") \ ) \ ) \ ) \ + "$") \ ) x = [1,2,3,4,5] How to recursively generate expression provided a python list. A: We can define the function nest_frac_N taking x as an additional argument: def nest_frac_N(previous_expr, numerator_expr1, denominator_expr2, x): temp_frac=str(x[len(x)-1]-1) +"+ \\frac{"+str(numerator_expr1)+"}{"+str(x[len(x)-1])+"}" for i in reversed(x[:len(x)-2]): temp_frac = str(i) +"+ \\frac{1}{"+temp_frac+"}" return temp_frac If we need an output for x=[1,2,3,4,5] we do: >>> x = [1,2,3,4,5] >>> nest_frac_N(1, 1, 1, x) ... '1+ \\frac{1}{2+ \\frac{1}{3+ \\frac{1}{4+ \\frac{1}{5}}}}' To get the markdown format we use : display(Markdown("$"+nest_frac_N(1, 1, 1, x)+"$")) Let's the x size to 10 to ensure that function is flexible : Output >>> x = [1,2,3,4,5,6,7,8,9,10] >>> nest_frac_N(1, 1, 1, x) ... '1+ \\frac{1}{2+ \\frac{1}{3+ \\frac{1}{4+ \\frac{1}{5+ \\frac{1}{6+ \\frac{1}{7+ \\frac{1}{8+ \\frac{1}{9+ \\frac{1}{10}}}}}}}}}' And to get the markdown : display(Markdown("$"+nest_frac_N(1, 1, 1, x)+"$")) And we can easily re-set the function in a way to display directly the markdown format.
Recursively generate LaTeX expression for continued fractions for a given python list
I am trying to generate LaTeX string expression for continued fractions in Jupyter Notebook. for example, a given Python list x=[1,2,3,4,5] can be written as continued fraction: Structure expression to generate this LaTeX fraction is \\frac{Numerator}{Denominator} With Non-recursive code : from IPython.display import display, Markdown # Non-recursive: def nest_frac(previous_expr, numerator_expr1, denominator_expr2): return previous_expr + " + \\frac{"+ numerator_expr1 + "}{" + denominator_expr2 + "}" # Cumbersome, error-prone display(Markdown("$"+ \ nest_frac("1","1", \ nest_frac("2","1", \ nest_frac("3","1", \ nest_frac("4","1", "5") \ ) \ ) \ ) \ + "$") \ ) x = [1,2,3,4,5] How to recursively generate expression provided a python list.
[ "We can define the function nest_frac_N taking x as an additional argument:\ndef nest_frac_N(previous_expr, numerator_expr1, denominator_expr2, x):\n \n temp_frac=str(x[len(x)-1]-1) +\"+ \\\\frac{\"+str(numerator_expr1)+\"}{\"+str(x[len(x)-1])+\"}\"\n \n for i in reversed(x[:len(x)-2]):\n \n temp_frac = str(i) +\"+ \\\\frac{1}{\"+temp_frac+\"}\"\n \n return temp_frac\n\nIf we need an output for x=[1,2,3,4,5] we do:\n>>> x = [1,2,3,4,5]\n>>> nest_frac_N(1, 1, 1, x)\n... '1+ \\\\frac{1}{2+ \\\\frac{1}{3+ \\\\frac{1}{4+ \\\\frac{1}{5}}}}'\n\nTo get the markdown format we use :\ndisplay(Markdown(\"$\"+nest_frac_N(1, 1, 1, x)+\"$\"))\n\nLet's the x size to 10 to ensure that function is flexible :\nOutput\n>>> x = [1,2,3,4,5,6,7,8,9,10]\n>>> nest_frac_N(1, 1, 1, x)\n... '1+ \\\\frac{1}{2+ \\\\frac{1}{3+ \\\\frac{1}{4+ \\\\frac{1}{5+ \\\\frac{1}{6+ \\\\frac{1}{7+ \\\\frac{1}{8+ \\\\frac{1}{9+ \\\\frac{1}{10}}}}}}}}}'\n\nAnd to get the markdown :\ndisplay(Markdown(\"$\"+nest_frac_N(1, 1, 1, x)+\"$\"))\n\nAnd we can easily re-set the function in a way to display directly the markdown format.\n" ]
[ 0 ]
[]
[]
[ "continued_fractions", "jupyter_notebook", "latex", "mathjax", "python" ]
stackoverflow_0074590234_continued_fractions_jupyter_notebook_latex_mathjax_python.txt
Q: how to return value inside a dictionary which is changed by a radio button I created a dictionary with two keys, when selecting one of the keys, the dictionary items are updated, the problem is that I am not returning the selected value within the updated list. for example, when selecting 'male', and then 'Executed', I would like to receive 'Executed' as a value import PySimpleGUI as sg genero = { 'male': ['Required','Executed'], 'female': ['Required', 'Performed'] } layout = [ [sg.Radio('male', "RADIO1", default=False, key="-IN1-")], [sg.Radio('female', "RADIO1", default=False, key="-IN2-")], [sg.Listbox(genero.keys(), size=(30, 3), enable_events=True, key='-PART-')], [sg.Push(),sg.Button('GENERATE'), sg.Exit("Exit")] ] window = sg.Window("GENERATE PETITION", layout) while True: event, values = window.read() if event == sg.WIN_CLOSED or event == "Exit": break elif values["-IN1-"] == True: window['-PART-'].update(genero['male']) elif values["-IN2-"] == True: window['-PART-'].update(genero['female']) elif event == 'GENERATE': print('-PART-') window.close() print(event,values) atualmente está retornando assim: Exit {'-IN1-': True, '-IN2-': False, '-PART-': []} A: There's programming logic issue in the event loop, it will be better for all the cases starts with the event decision, not the value(s) decision. In your code, the case for the event GENERATE will be never executed after any one of the Radio element clicked. import PySimpleGUI as sg genero = { 'male': ['Required','Executed'], 'female': ['Required', 'Performed'] } layout = [ [sg.Radio('male', "RADIO1", default=False, enable_events=True, key="-IN1-")], [sg.Radio('female', "RADIO1", default=False, enable_events=True, key="-IN2-")], [sg.Listbox(genero.keys(), size=(30, 3), enable_events=True, key='-PART-')], [sg.Push(),sg.Button('GENERATE'), sg.Exit("Exit")] ] window = sg.Window("GENERATE PETITION", layout) while True: event, values = window.read() if event == sg.WIN_CLOSED or event == "Exit": break elif event in ('-IN1-', '-IN2-'): if values["-IN1-"] == True: window['-PART-'].update(genero['male']) else: window['-PART-'].update(genero['female']) elif event == 'GENERATE': selections = values['-PART-'] if selections: print(selections[0]) else: print('Nothing selected !') window.close()
how to return value inside a dictionary which is changed by a radio button
I created a dictionary with two keys, when selecting one of the keys, the dictionary items are updated, the problem is that I am not returning the selected value within the updated list. for example, when selecting 'male', and then 'Executed', I would like to receive 'Executed' as a value import PySimpleGUI as sg genero = { 'male': ['Required','Executed'], 'female': ['Required', 'Performed'] } layout = [ [sg.Radio('male', "RADIO1", default=False, key="-IN1-")], [sg.Radio('female', "RADIO1", default=False, key="-IN2-")], [sg.Listbox(genero.keys(), size=(30, 3), enable_events=True, key='-PART-')], [sg.Push(),sg.Button('GENERATE'), sg.Exit("Exit")] ] window = sg.Window("GENERATE PETITION", layout) while True: event, values = window.read() if event == sg.WIN_CLOSED or event == "Exit": break elif values["-IN1-"] == True: window['-PART-'].update(genero['male']) elif values["-IN2-"] == True: window['-PART-'].update(genero['female']) elif event == 'GENERATE': print('-PART-') window.close() print(event,values) atualmente está retornando assim: Exit {'-IN1-': True, '-IN2-': False, '-PART-': []}
[ "There's programming logic issue in the event loop, it will be better for all the cases starts with the event decision, not the value(s) decision. In your code, the case for the event GENERATE will be never executed after any one of the Radio element clicked.\nimport PySimpleGUI as sg\n\ngenero = {\n 'male': ['Required','Executed'],\n 'female': ['Required', 'Performed']\n }\n\nlayout = [\n [sg.Radio('male', \"RADIO1\", default=False, enable_events=True, key=\"-IN1-\")],\n [sg.Radio('female', \"RADIO1\", default=False, enable_events=True, key=\"-IN2-\")],\n [sg.Listbox(genero.keys(), size=(30, 3), enable_events=True, key='-PART-')],\n [sg.Push(),sg.Button('GENERATE'), sg.Exit(\"Exit\")]\n ]\n\n\nwindow = sg.Window(\"GENERATE PETITION\", layout)\n\n\nwhile True:\n\n event, values = window.read()\n\n if event == sg.WIN_CLOSED or event == \"Exit\":\n break\n\n elif event in ('-IN1-', '-IN2-'):\n if values[\"-IN1-\"] == True:\n window['-PART-'].update(genero['male'])\n else:\n window['-PART-'].update(genero['female'])\n\n elif event == 'GENERATE':\n selections = values['-PART-']\n if selections:\n print(selections[0])\n else:\n print('Nothing selected !')\n\nwindow.close()\n\n\n" ]
[ 0 ]
[]
[]
[ "dictionary", "pysimplegui", "python" ]
stackoverflow_0074589814_dictionary_pysimplegui_python.txt
Q: Calculate a date difference between two dates in a series of a dataframe by ID? Sorry if my question is simple i'm starting(so thank you for your help and understanding) I am trying to get a date discrepancy by 'identifier' A B C D in the DF example. Using Python how can i add a column to establish the delta between each contract knowing that a person can have only one contract as he can have 10 or more. Thank you in advance. header 1 header 2 cell 1 cell 2 cell 3 cell 4 I have try many things by DSS and Python but my result is false.... A: You mean something like: df['new_col'] = df['header1'] - df['header2'] For timedeltas use: import numpy as np df['diff_days'] = (df['end_date'] - df['start_date']) / np.timedelta64(1, 'D') D stands for timediffernce in days. Use "W", "M", "Y" for weeks, months or years.
Calculate a date difference between two dates in a series of a dataframe by ID?
Sorry if my question is simple i'm starting(so thank you for your help and understanding) I am trying to get a date discrepancy by 'identifier' A B C D in the DF example. Using Python how can i add a column to establish the delta between each contract knowing that a person can have only one contract as he can have 10 or more. Thank you in advance. header 1 header 2 cell 1 cell 2 cell 3 cell 4 I have try many things by DSS and Python but my result is false....
[ "You mean something like:\ndf['new_col'] = df['header1'] - df['header2']\n\nFor timedeltas use:\nimport numpy as np\ndf['diff_days'] = (df['end_date'] - df['start_date']) / np.timedelta64(1, 'D')\n\nD stands for timediffernce in days. Use \"W\", \"M\", \"Y\" for weeks, months or years.\n" ]
[ 0 ]
[]
[]
[ "dataiku", "python", "timedelta" ]
stackoverflow_0074590883_dataiku_python_timedelta.txt
Q: Python: How to specify type hints of a function that returns an attribute of a class with generic types? import typing as typ T = typ.TypeVar("T") class Foo(typ.Generic[T]): """The generic class.""" def __init__(self, var: T): self.var = var def var_getter(foo_obj: ??) -> ??: """Var getter.""" return foo_obj.var These are the test cases that should be satisfied: class Bar(Foo[str]): pass test_1 = var_getter(Bar("a")) # test_1 should be string according to type hints class Baz(Foo[int]): pass test_2 = var_getter(Bar(1)) # test_2 should be int according to type hints How would this be achieved? What would I need to use to replace the question marks in var_getter? A: from typing import Generic, TypeVar T = TypeVar("T") class Foo(Generic[T]): var: T def __init__(self, var: T): self.var = var class Bar(Foo[str]): pass class Baz(Foo[int]): pass def var_getter(foo_obj: Foo[T]) -> T: return foo_obj.var reveal_type(var_getter(Bar("a"))) # Revealed type is "builtins.str" reveal_type(var_getter(Baz(1))) # Revealed type is "builtins.int"
Python: How to specify type hints of a function that returns an attribute of a class with generic types?
import typing as typ T = typ.TypeVar("T") class Foo(typ.Generic[T]): """The generic class.""" def __init__(self, var: T): self.var = var def var_getter(foo_obj: ??) -> ??: """Var getter.""" return foo_obj.var These are the test cases that should be satisfied: class Bar(Foo[str]): pass test_1 = var_getter(Bar("a")) # test_1 should be string according to type hints class Baz(Foo[int]): pass test_2 = var_getter(Bar(1)) # test_2 should be int according to type hints How would this be achieved? What would I need to use to replace the question marks in var_getter?
[ "from typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\nclass Foo(Generic[T]):\n var: T\n\n def __init__(self, var: T):\n self.var = var\n\nclass Bar(Foo[str]):\n pass\n\nclass Baz(Foo[int]):\n pass\n\ndef var_getter(foo_obj: Foo[T]) -> T:\n return foo_obj.var\n\nreveal_type(var_getter(Bar(\"a\"))) # Revealed type is \"builtins.str\"\nreveal_type(var_getter(Baz(1))) # Revealed type is \"builtins.int\"\n\n" ]
[ 1 ]
[]
[]
[ "python", "type_hinting" ]
stackoverflow_0074590269_python_type_hinting.txt
Q: How can I return a context from views.py in different html files in Django? So, I have a method called 'room' in my views.py file. I can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well. How can I do that? Views.py def room(request): rooms = Rooms.objects.all() photos = RoomImage.objects.all() context = {'rooms':rooms, 'photos':photos} return render(request, 'hotelbook/room.html', context) A: I can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well. Just pass Rooms.objects.all() also in that view which renders the index.html template. Below is an example. def index(request): rooms = Rooms.objects.all() photos = RoomImage.objects.all() context = {'rooms':rooms, 'photos':photos} return render(request, 'hotelbook/index.html', context) Now, you can also use rooms in index.html template. A: You can do one thing, just create a simple utility function in views.py for getting all rooms. create utils.py file in django application: # utils.py def get_all_rooms(): all_rooms = Room.objects.all() all_photos = RoomImage.objects.all() return {"rooms": all_rooms, "photos": all_photos} Then, import utils in views.py file # views.py from .utils import get_all_rooms data = get_all_rooms() def room(request): return render(request, "room.html", {"data": data}) def index(request): return render(request, "index.html", {"data": data}) This can be very efficient as we are calling cahced result instead of firing new db query!
How can I return a context from views.py in different html files in Django?
So, I have a method called 'room' in my views.py file. I can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well. How can I do that? Views.py def room(request): rooms = Rooms.objects.all() photos = RoomImage.objects.all() context = {'rooms':rooms, 'photos':photos} return render(request, 'hotelbook/room.html', context)
[ "\nI can only access this room on my room.html page as I'm returning it there but I would like to use this data on my index page as well.\n\nJust pass Rooms.objects.all() also in that view which renders the index.html template.\nBelow is an example.\ndef index(request):\n rooms = Rooms.objects.all()\n photos = RoomImage.objects.all()\n context = {'rooms':rooms, 'photos':photos} \n return render(request, 'hotelbook/index.html', context)\n\nNow, you can also use rooms in index.html template.\n", "You can do one thing, just create a simple utility function in views.py for getting all rooms.\ncreate utils.py file in django application:\n# utils.py\ndef get_all_rooms():\n all_rooms = Room.objects.all()\n all_photos = RoomImage.objects.all()\n return {\"rooms\": all_rooms, \"photos\": all_photos}\n\nThen, import utils in views.py file\n# views.py\n\nfrom .utils import get_all_rooms\n\ndata = get_all_rooms()\n\ndef room(request):\n return render(request, \"room.html\", {\"data\": data})\n\ndef index(request):\n return render(request, \"index.html\", {\"data\": data})\n\nThis can be very efficient as we are calling cahced result instead of firing new db query!\n" ]
[ 2, 2 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0074589771_django_django_templates_django_views_python.txt
Q: How can I automatically detect if a colum is categorical? I want to find a category of a pandas column. I can get the type but I'm struggling to figure out categories. titanic_df = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.csv') #ID datatype def idDataTypes(inputDataFrame): columnTypesDict = {} import numpy as np import numbers import pandas as pd from pandas.api.types import is_string_dtype from pandas.api.types import is_numeric_dtype for columns in inputDataFrame.columns.values: #print(columns) #try to convert to number. If it doesn't work it will convert to another type try: inputDataFrame[columns] = pd.to_numeric(inputDataFrame[columns], errors='ignore').apply(lambda x: x + 1 if isinstance(x, numbers.Number) else x) except: print(columns, " cannot convert.") #print(inputDataFrame[columns].dtype) #create dictionary with the label if is_numeric_dtype(inputDataFrame[columns]): #products[columns].dtype == np.float64: columnTypesDict[columns] = "numeric" elif is_string_dtype(inputDataFrame[columns]): # products[columns].dtype == np.object: columnTypesDict[columns] = "string" #print(is_string_dtype(products[columns])) else: print("something else", prinputDataFrameoducts[columns].dtype) #category cols = inputDataFrame.columns num_cols = inputDataFrame._get_numeric_data().columns #num_cols proposedCategory = list(set(cols) - set(num_cols)) for value in proposedCategory: columnTypesDict[value] = "category" return(columnTypesDict) idDataTypes(titanic_df) The results I'm getting are not what I expect: {'pclass': 'numeric', 'survived': 'numeric', 'name': 'category', 'sex': 'category', 'age': 'numeric', 'sibsp': 'numeric', 'parch': 'numeric', 'ticket': 'category', 'fare': 'numeric', 'cabin': 'category', 'embarked': 'category', 'boat': 'category', 'body': 'numeric', 'home.dest': 'category'} pclass should be a category and name should not be. I'm not sure how to assess if something is a category or not. Any ideas? A: Here's the bug in your code: proposedCategory = list(set(cols) - set(num_cols)) Everything other than the numeric columns are to become categories. There is no right way to do this either, since whether a column is categorical is best decided manually with knowledge of the data the column contains. You are trying to do it automatically. One way to do it is to count the number of unique values in the column. It there are relatively few unique values, the column is likely categorical. #category for name, column in inputDataFrame.iteritems(): unique_count = column.unique().shape[0] total_count = column.shape[0] if unique_count / total_count < 0.05: columnTypesDict[name] = 'category' The 5% threshold is random. No column will be identified as categorical if there are fewer than 20 rows in your dataframe. For best result, you will have to adjust that ratio of small and big dataframes. A: One quick (and lazy) workaround I've found out is using the Pandas .corr() method to automatically slash out numerical columns for you. As per my observation, .corr() automatically selects numerical columns when it returns the pairwise correlations for the entire dataframe. (Provided you have applied it on the entire dataset). Hence you can always linear search for the categorical columns in your original dataframe, if its not in the dataframe returned by .corr(). This might not be 100% effective but it does the job most of the time. corr_df = df.corr() #returns a dataframe num_cols = corr_df.columns cat_cols = [cols for cols in df.columns if not cols in num_cols] PS : Might be a bit time/memory intensive if dataset contains a lot of columns.
How can I automatically detect if a colum is categorical?
I want to find a category of a pandas column. I can get the type but I'm struggling to figure out categories. titanic_df = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic3.csv') #ID datatype def idDataTypes(inputDataFrame): columnTypesDict = {} import numpy as np import numbers import pandas as pd from pandas.api.types import is_string_dtype from pandas.api.types import is_numeric_dtype for columns in inputDataFrame.columns.values: #print(columns) #try to convert to number. If it doesn't work it will convert to another type try: inputDataFrame[columns] = pd.to_numeric(inputDataFrame[columns], errors='ignore').apply(lambda x: x + 1 if isinstance(x, numbers.Number) else x) except: print(columns, " cannot convert.") #print(inputDataFrame[columns].dtype) #create dictionary with the label if is_numeric_dtype(inputDataFrame[columns]): #products[columns].dtype == np.float64: columnTypesDict[columns] = "numeric" elif is_string_dtype(inputDataFrame[columns]): # products[columns].dtype == np.object: columnTypesDict[columns] = "string" #print(is_string_dtype(products[columns])) else: print("something else", prinputDataFrameoducts[columns].dtype) #category cols = inputDataFrame.columns num_cols = inputDataFrame._get_numeric_data().columns #num_cols proposedCategory = list(set(cols) - set(num_cols)) for value in proposedCategory: columnTypesDict[value] = "category" return(columnTypesDict) idDataTypes(titanic_df) The results I'm getting are not what I expect: {'pclass': 'numeric', 'survived': 'numeric', 'name': 'category', 'sex': 'category', 'age': 'numeric', 'sibsp': 'numeric', 'parch': 'numeric', 'ticket': 'category', 'fare': 'numeric', 'cabin': 'category', 'embarked': 'category', 'boat': 'category', 'body': 'numeric', 'home.dest': 'category'} pclass should be a category and name should not be. I'm not sure how to assess if something is a category or not. Any ideas?
[ "Here's the bug in your code:\nproposedCategory = list(set(cols) - set(num_cols))\n\nEverything other than the numeric columns are to become categories.\n\nThere is no right way to do this either, since whether a column is categorical is best decided manually with knowledge of the data the column contains. You are trying to do it automatically. One way to do it is to count the number of unique values in the column. It there are relatively few unique values, the column is likely categorical.\n#category \nfor name, column in inputDataFrame.iteritems():\n unique_count = column.unique().shape[0]\n total_count = column.shape[0]\n if unique_count / total_count < 0.05:\n columnTypesDict[name] = 'category'\n\nThe 5% threshold is random. No column will be identified as categorical if there are fewer than 20 rows in your dataframe. For best result, you will have to adjust that ratio of small and big dataframes.\n", "One quick (and lazy) workaround I've found out is using the Pandas .corr() method to automatically slash out numerical columns for you. As per my observation, .corr() automatically selects numerical columns when it returns the pairwise correlations for the entire dataframe. (Provided you have applied it on the entire dataset). Hence you can always linear search for the categorical columns in your original dataframe, if its not in the dataframe returned by .corr(). This might not be 100% effective but it does the job most of the time.\ncorr_df = df.corr() #returns a dataframe\nnum_cols = corr_df.columns\ncat_cols = [cols for cols in df.columns if not cols in num_cols]\n\nPS : Might be a bit time/memory intensive if dataset contains a lot of columns.\n" ]
[ 1, 0 ]
[]
[]
[ "algorithm", "pandas", "python" ]
stackoverflow_0059384802_algorithm_pandas_python.txt
Q: Disable Tensorflow debugging information By debugging information I mean what TensorFlow shows in my terminal about loaded libraries and found devices etc. not Python errors. I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties: name: Graphics Device major: 5 minor: 2 memoryClockRate (GHz) 1.0885 pciBusID 0000:04:00.0 Total memory: 12.00GiB Free memory: 11.83GiB I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0 I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0: Y I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Graphics Device, pci bus id: 0000:04:00.0) I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.0KiB ... A: You can disable all debugging logs using os.environ : import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import tensorflow as tf Tested on tf 0.12 and 1.0 In details, 0 = all messages are logged (default behavior) 1 = INFO messages are not printed 2 = INFO and WARNING messages are not printed 3 = INFO, WARNING, and ERROR messages are not printed A: 2.0 Update (10/8/19) Setting TF_CPP_MIN_LOG_LEVEL should still work (see below in v0.12+ update), but there was a reported issue for version 2.0 until 2.3.z fixed in 2.4 and later. If setting TF_CPP_MIN_LOG_LEVEL does not work for you (again, see below), try doing the following to set the log level: import tensorflow as tf tf.get_logger().setLevel('INFO') In addition, please see the documentation on tf.autograph.set_verbosity which sets the verbosity of autograph log messages - for example: # Can also be set using the AUTOGRAPH_VERBOSITY environment variable tf.autograph.set_verbosity(1) v0.12+ Update (5/20/17), Working through TF 2.0+: In TensorFlow 0.12+, per this issue, you can now control logging via the environmental variable called TF_CPP_MIN_LOG_LEVEL; it defaults to 0 (all logs shown) but can be set to one of the following values under the Level column. Level | Level for Humans | Level Description -------|------------------|------------------------------------ 0 | DEBUG | [Default] Print all messages 1 | INFO | Filter out INFO messages 2 | WARNING | Filter out INFO & WARNING messages 3 | ERROR | Filter out all messages See the following generic OS example using Python: import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'} import tensorflow as tf You can set this environmental variable in the environment that you run your script in. For example, with bash this can be in the file ~/.bashrc, /etc/environment, /etc/profile, or in the actual shell as: TF_CPP_MIN_LOG_LEVEL=2 python my_tf_script.py To be thorough, you call also set the level for the Python tf_logging module, which is used in e.g. summary ops, tensorboard, various estimators, etc. # append to lines above tf.logging.set_verbosity(tf.logging.ERROR) # or any {DEBUG, INFO, WARN, ERROR, FATAL} For 1.14 you will receive warnings if you do not change to use the v1 API as follows: # append to lines above tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) # or any {DEBUG, INFO, WARN, ERROR, FATAL} **For Prior Versions of TensorFlow or TF-Learn Logging (v0.11.x or lower):** View the page below for information on TensorFlow logging; with the new update, you're able to set the logging verbosity to either DEBUG, INFO, WARN, ERROR, or FATAL. For example: tf.logging.set_verbosity(tf.logging.ERROR) The page additionally goes over monitors which can be used with TF-Learn models. Here is the page. This doesn't block all logging, though (only TF-Learn). I have two solutions; one is a 'technically correct' solution (Linux) and the other involves rebuilding TensorFlow. script -c 'python [FILENAME].py' | grep -v 'I tensorflow/' For the other, please see this answer which involves modifying source and rebuilding TensorFlow. A: For compatibility with Tensorflow 2.0, you can use tf.get_logger import logging tf.get_logger().setLevel(logging.ERROR) A: I have had this problem as well (on tensorflow-0.10.0rc0), but could not fix the excessive nose tests logging problem via the suggested answers. I managed to solve this by probing directly into the tensorflow logger. Not the most correct of fixes, but works great and only pollutes the test files which directly or indirectly import tensorflow: # Place this before directly or indirectly importing tensorflow import logging logging.getLogger("tensorflow").setLevel(logging.WARNING) A: To anyone still struggling to get the os.environ solution to work as I was, check that this is placed before you import tensorflow in your script, just like mwweb's answer: import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'} import tensorflow as tf A: I solved with this post Cannot remove all warnings #27045 , and the solution was: import logging logging.getLogger('tensorflow').disabled = True A: As TF_CPP_MIN_LOG_LEVEL didn't work for me you can try: tf.logging.set_verbosity(tf.logging.WARN) Worked for me in tensorflow v1.6.0 A: I am using Tensorflow version 2.3.1 and none of the solutions above have been fully effective. Until, I find this package. Install like this: with Anaconda, python -m pip install silence-tensorflow with IDEs, pip install silence-tensorflow And add to the first line of code: from silence_tensorflow import silence_tensorflow silence_tensorflow() That's It! A: Usual python3 log manager works for me with tensorflow==1.11.0: import logging logging.getLogger('tensorflow').setLevel(logging.INFO) A: for tensorflow 2.1.0, following code works fine. import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) A: To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like: logging.getLogger('tensorflow').addFilter(my_filter_func) where my_filter_func accepts a LogRecord object as input [LogRecord docs] and returns zero if you want the message thrown out; nonzero otherwise. Here's an example filter that only keeps every nth info message (Python 3 due to the use of nonlocal here): def keep_every_nth_info(n): i = -1 def filter_record(record): nonlocal i i += 1 return int(record.levelname != 'INFO' or i % n == 0) return filter_record # Example usage for TensorFlow: logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5)) All of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity() before adding a filter. A: Yeah, I'm using tf 2.0-beta and want to enable/disable the default logging. The environment variable and methods in tf1.X don't seem to exist anymore. I stepped around in PDB and found this to work: # close the TF2 logger tf2logger = tf.get_logger() tf2logger.error('Close TF2 logger handlers') tf2logger.root.removeHandler(tf2logger.root.handlers[0]) I then add my own logger API (in this case file-based) logtf = logging.getLogger('DST') logtf.setLevel(logging.DEBUG) # file handler logfile='/tmp/tf_s.log' fh = logging.FileHandler(logfile) fh.setFormatter( logging.Formatter('fh %(asctime)s %(name)s %(filename)s:%(lineno)d :%(message)s') ) logtf.addHandler(fh) logtf.info('writing to %s', logfile) A: I was struggling from this for a while, tried almost all the solutions here but could not get rid of debugging info in TF 1.14, I have tried following multiple solutions: import os import logging import sys os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL stderr = sys.stderr sys.stderr = open(os.devnull, 'w') import tensorflow as tf tf.get_logger().setLevel(tf.compat.v1.logging.FATAL) tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) logging.getLogger('tensorflow').setLevel(tf.compat.v1.logging.FATAL) sys.stderr = stderr import absl.logging logging.root.removeHandler(absl.logging._absl_handler) absl.logging._warn_preinit_stderr = False The debugging info still showed up, what finally helped was restarting my pc (actually restarting the kernel should work). So if somebody has similar problem, try restart kernel after you set your environment vars, simple but might not come in mind. A: If you only need to get rid of warning outputs on the screen, you might want to clear the console screen right after importing the tensorflow by using this simple command (Its more effective than disabling all debugging logs in my experience): In windows: import os os.system('cls') In Linux or Mac: import os os.system('clear') A: None of the solutions above could solve my problem in Jupyter Notebook, so I use the following snippet code bellow from Cicoria, and issues solved. import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore",category=FutureWarning) import tensorflow as tf from tensorflow import keras from tensorflow.keras.preprocessing.text import Tokenizer print('Done') A: Most of the answers here work, but you have to use them every time you open a new session (e.g. with JupyterLab). To make the changes stick, you have to set the environment variable. Linux: export TF_CPP_MIN_LOG_LEVEL="3" (Also add the above line to .bashrc to make the change permanent, not just for the session) Windows: setx TF_CPP_MIN_LOG_LEVEL "3" Both set the environment variables for the user.
Disable Tensorflow debugging information
By debugging information I mean what TensorFlow shows in my terminal about loaded libraries and found devices etc. not Python errors. I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties: name: Graphics Device major: 5 minor: 2 memoryClockRate (GHz) 1.0885 pciBusID 0000:04:00.0 Total memory: 12.00GiB Free memory: 11.83GiB I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0 I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0: Y I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Graphics Device, pci bus id: 0000:04:00.0) I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.0KiB ...
[ "You can disable all debugging logs using os.environ :\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \nimport tensorflow as tf\n\nTested on tf 0.12 and 1.0\nIn details, \n0 = all messages are logged (default behavior)\n1 = INFO messages are not printed\n2 = INFO and WARNING messages are not printed\n3 = INFO, WARNING, and ERROR messages are not printed\n\n", "2.0 Update (10/8/19)\nSetting TF_CPP_MIN_LOG_LEVEL should still work (see below in v0.12+ update), but there was a reported issue for version 2.0 until 2.3.z fixed in 2.4 and later. If setting TF_CPP_MIN_LOG_LEVEL does not work for you (again, see below), try doing the following to set the log level:\nimport tensorflow as tf\ntf.get_logger().setLevel('INFO')\n\nIn addition, please see the documentation on tf.autograph.set_verbosity which sets the verbosity of autograph log messages - for example:\n# Can also be set using the AUTOGRAPH_VERBOSITY environment variable\ntf.autograph.set_verbosity(1)\n\nv0.12+ Update (5/20/17), Working through TF 2.0+:\nIn TensorFlow 0.12+, per this issue, you can now control logging via the environmental variable called TF_CPP_MIN_LOG_LEVEL; it defaults to 0 (all logs shown) but can be set to one of the following values under the Level column.\n Level | Level for Humans | Level Description \n -------|------------------|------------------------------------ \n 0 | DEBUG | [Default] Print all messages \n 1 | INFO | Filter out INFO messages \n 2 | WARNING | Filter out INFO & WARNING messages \n 3 | ERROR | Filter out all messages \n\nSee the following generic OS example using Python:\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}\nimport tensorflow as tf\n\nYou can set this environmental variable in the environment that you run your script in. For example, with bash this can be in the file ~/.bashrc, /etc/environment, /etc/profile, or in the actual shell as:\nTF_CPP_MIN_LOG_LEVEL=2 python my_tf_script.py\n\nTo be thorough, you call also set the level for the Python tf_logging module, which is used in e.g. summary ops, tensorboard, various estimators, etc.\n# append to lines above\ntf.logging.set_verbosity(tf.logging.ERROR) # or any {DEBUG, INFO, WARN, ERROR, FATAL}\n\nFor 1.14 you will receive warnings if you do not change to use the v1 API as follows:\n# append to lines above\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) # or any {DEBUG, INFO, WARN, ERROR, FATAL}\n\n\n**For Prior Versions of TensorFlow or TF-Learn Logging (v0.11.x or lower):**\nView the page below for information on TensorFlow logging; with the new update, you're able to set the logging verbosity to either DEBUG, INFO, WARN, ERROR, or FATAL. For example:\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nThe page additionally goes over monitors which can be used with TF-Learn models. Here is the page.\nThis doesn't block all logging, though (only TF-Learn). I have two solutions; one is a 'technically correct' solution (Linux) and the other involves rebuilding TensorFlow.\nscript -c 'python [FILENAME].py' | grep -v 'I tensorflow/'\n\nFor the other, please see this answer which involves modifying source and rebuilding TensorFlow.\n", "For compatibility with Tensorflow 2.0, you can use tf.get_logger \nimport logging\ntf.get_logger().setLevel(logging.ERROR)\n\n", "I have had this problem as well (on tensorflow-0.10.0rc0), but could not fix the excessive nose tests logging problem via the suggested answers.\nI managed to solve this by probing directly into the tensorflow logger. Not the most correct of fixes, but works great and only pollutes the test files which directly or indirectly import tensorflow:\n# Place this before directly or indirectly importing tensorflow\nimport logging\nlogging.getLogger(\"tensorflow\").setLevel(logging.WARNING)\n\n", "To anyone still struggling to get the os.environ solution to work as I was, check that this is placed before you import tensorflow in your script, just like mwweb's answer:\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}\nimport tensorflow as tf\n\n", "I solved with this post Cannot remove all warnings #27045 , and the solution was:\nimport logging\nlogging.getLogger('tensorflow').disabled = True\n\n", "As TF_CPP_MIN_LOG_LEVEL didn't work for me you can try:\ntf.logging.set_verbosity(tf.logging.WARN)\n\nWorked for me in tensorflow v1.6.0\n", "I am using Tensorflow version 2.3.1 and none of the solutions above have been fully effective.\nUntil, I find this package.\nInstall like this:\nwith Anaconda,\npython -m pip install silence-tensorflow\n\nwith IDEs,\npip install silence-tensorflow\n\nAnd add to the first line of code:\nfrom silence_tensorflow import silence_tensorflow\nsilence_tensorflow()\n\nThat's It!\n", "Usual python3 log manager works for me with tensorflow==1.11.0:\nimport logging\nlogging.getLogger('tensorflow').setLevel(logging.INFO)\n\n", "for tensorflow 2.1.0, following code works fine.\nimport tensorflow as tf\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\n", "To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like:\nlogging.getLogger('tensorflow').addFilter(my_filter_func)\n\nwhere my_filter_func accepts a LogRecord object as input [LogRecord docs] and\nreturns zero if you want the message thrown out; nonzero otherwise.\nHere's an example filter that only keeps every nth info message (Python 3 due\nto the use of nonlocal here):\ndef keep_every_nth_info(n):\n i = -1\n def filter_record(record):\n nonlocal i\n i += 1\n return int(record.levelname != 'INFO' or i % n == 0)\n return filter_record\n\n# Example usage for TensorFlow:\nlogging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))\n\nAll of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity() before adding a filter.\n", "Yeah, I'm using tf 2.0-beta and want to enable/disable the default logging. The environment variable and methods in tf1.X don't seem to exist anymore.\nI stepped around in PDB and found this to work:\n# close the TF2 logger\ntf2logger = tf.get_logger()\ntf2logger.error('Close TF2 logger handlers')\ntf2logger.root.removeHandler(tf2logger.root.handlers[0])\n\nI then add my own logger API (in this case file-based)\nlogtf = logging.getLogger('DST')\nlogtf.setLevel(logging.DEBUG)\n\n# file handler\nlogfile='/tmp/tf_s.log'\nfh = logging.FileHandler(logfile)\nfh.setFormatter( logging.Formatter('fh %(asctime)s %(name)s %(filename)s:%(lineno)d :%(message)s') )\nlogtf.addHandler(fh)\nlogtf.info('writing to %s', logfile)\n\n", "I was struggling from this for a while, tried almost all the solutions here but could not get rid of debugging info in TF 1.14, I have tried following multiple solutions:\nimport os\nimport logging\nimport sys\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL\nstderr = sys.stderr\nsys.stderr = open(os.devnull, 'w')\n\nimport tensorflow as tf\ntf.get_logger().setLevel(tf.compat.v1.logging.FATAL)\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\nlogging.getLogger('tensorflow').setLevel(tf.compat.v1.logging.FATAL)\n\nsys.stderr = stderr\n\nimport absl.logging\nlogging.root.removeHandler(absl.logging._absl_handler)\nabsl.logging._warn_preinit_stderr = False\n\nThe debugging info still showed up, what finally helped was restarting my pc (actually restarting the kernel should work). So if somebody has similar problem, try restart kernel after you set your environment vars, simple but might not come in mind.\n", "If you only need to get rid of warning outputs on the screen, you might want to clear the console screen right after importing the tensorflow by using this simple command (Its more effective than disabling all debugging logs in my experience):\nIn windows:\nimport os\nos.system('cls')\n\nIn Linux or Mac:\nimport os\nos.system('clear')\n\n", "None of the solutions above could solve my problem in Jupyter Notebook, so I use the following snippet code bellow from Cicoria, and issues solved.\nimport warnings \nwith warnings.catch_warnings(): \n warnings.filterwarnings(\"ignore\",category=FutureWarning)\n import tensorflow as tf\n from tensorflow import keras\n from tensorflow.keras.preprocessing.text import Tokenizer\n\nprint('Done') \n\n", "Most of the answers here work, but you have to use them every time you open a new session (e.g. with JupyterLab). To make the changes stick, you have to set the environment variable.\nLinux:\nexport TF_CPP_MIN_LOG_LEVEL=\"3\"\n\n(Also add the above line to .bashrc to make the change permanent, not just for the session)\nWindows:\nsetx TF_CPP_MIN_LOG_LEVEL \"3\"\n\nBoth set the environment variables for the user.\n" ]
[ 386, 235, 55, 20, 13, 12, 11, 11, 6, 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0035911252_python_tensorflow.txt
Q: Copying only non-relation attributes django/python I am copying a model object to another, but I want that it doesn’t copy the relations For example, assume you have a model like this: class Dish(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) def __str__(self): return self.name Then I do: my_dish = Dish.objects.get(pk=dish.id) serializer = Dish_Serializer(my_dish) my_new_object = serializer.data I want my_new_object to include only those attributes that are not relations, in this case, name and description. How do I do that without accessing name and description directly? A: I assume in your serializer you don't want to explicitly define which field to serialize. Otherwise you could do the following: class Dish_Serializer(serializers.ModelSerializer): class Meta: model = Dish fields = ['id','name', 'description'] You probably can define these fields dynamically: fields = [f.name for f in Dish._meta.concrete_fields] or fields = [f.name for f in Dish._meta.fields if not isinstance(f,ForeignKey)] A: Ultimately, you want my_new_object in dictionary format and as per condition pk will give you only one object of dish. So, you can do this instead : my_new_object = Dish.objects.filter(pk=dish.id).values("name", "description")[0] It will give you exact what you want, just declare the fields you need in values as an attribute fields. A: You can remove a field from your serializer using .fields.pop(field_name) method like the below example According that I took from Dynamically modifying fields [drf-docs]: class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` >argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) Also, you can do this in your view like the below code snippet: my_dish = Dish.objects.get(pk=dish.id) serializer = Dish_Serializer(my_dish) desired_fields = {'id', 'name', 'description'} all_fields = set(serializer.fields) for field in all_fields: if field not in desired_fields: serializer.fields.pop(field) my_new_object = serializer.data
Copying only non-relation attributes django/python
I am copying a model object to another, but I want that it doesn’t copy the relations For example, assume you have a model like this: class Dish(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) def __str__(self): return self.name Then I do: my_dish = Dish.objects.get(pk=dish.id) serializer = Dish_Serializer(my_dish) my_new_object = serializer.data I want my_new_object to include only those attributes that are not relations, in this case, name and description. How do I do that without accessing name and description directly?
[ "I assume in your serializer you don't want to explicitly define which field to serialize. Otherwise you could do the following:\nclass Dish_Serializer(serializers.ModelSerializer):\n class Meta:\n model = Dish\n fields = ['id','name', 'description']\n\nYou probably can define these fields dynamically:\n fields = [f.name for f in Dish._meta.concrete_fields] \n\nor\n fields = [f.name for f in Dish._meta.fields if not isinstance(f,ForeignKey)]\n\n", "Ultimately, you want my_new_object in dictionary format and as per condition pk will give you only one object of dish.\nSo, you can do this instead :\nmy_new_object = Dish.objects.filter(pk=dish.id).values(\"name\", \"description\")[0]\n\nIt will give you exact what you want, just declare the fields you need in values as an attribute fields.\n", "You can remove a field from your serializer using .fields.pop(field_name) method like the below example According that I took from Dynamically modifying fields [drf-docs]:\n\nclass DynamicFieldsModelSerializer(serializers.ModelSerializer):\n \"\"\"\n A ModelSerializer that takes an additional `fields` argument that\n controls which fields should be displayed.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Don't pass the 'fields' arg up to the superclass\n fields = kwargs.pop('fields', None)\n\n # Instantiate the superclass normally\n super().__init__(*args, **kwargs)\n\n if fields is not None:\n # Drop any fields that are not specified in the `fields` >argument.\n allowed = set(fields)\n existing = set(self.fields)\n for field_name in existing - allowed:\n self.fields.pop(field_name)\n\n\nAlso, you can do this in your view like the below code snippet:\nmy_dish = Dish.objects.get(pk=dish.id)\nserializer = Dish_Serializer(my_dish)\ndesired_fields = {'id', 'name', 'description'}\nall_fields = set(serializer.fields)\nfor field in all_fields:\n if field not in desired_fields:\n serializer.fields.pop(field)\nmy_new_object = serializer.data\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "django_serializer", "python" ]
stackoverflow_0074590516_django_django_models_django_rest_framework_django_serializer_python.txt
Q: how to download youtube video in the highest quality available This code works perfectly, but I don't want the lowest quality. I want the highest one. When I tried changing the video = youtube. streams.first() to video = youtube.streams.last() I encountered a problem where the video that I downloaded was just a black screen with the audio playing in the background. from tkinter import * import pytube # Functions def download(): video_url = url.get() try: youtube = pytube.YouTube(video_url) video = youtube.streams.first() video.download("C:/Users/iwanh/Desktop/MP4_MP3s") notif.config(fg="green", text="Download complete") except Exception as e: print(e) notif.config(fg="red", text="Video could not be downloaded") # Main Screen master = Tk() master.title("Youtube Video Downloader") # Labels Label(master, text="Youtube Video Converter", fg="red", font=("Calibri", 15)).grid(sticky=N, padx=100, row=0) Label(master, text="Please enter the link to your video below : ", font=("Calibri", 15)).grid(sticky=N, row=1, pady=15) notif = Label(master, font=("Calibri", 12)) notif.grid(sticky=N, pady=1, row=4) # Vars url = StringVar() # Entry Entry(master, width=50, textvariable=url).grid(sticky=N, row=2) # Button Button(master, width=20, text="Download", font=("Calibri", 12), command=download).grid(sticky=N, row=3, pady=15) master.mainloop() A: Try To Use get_highest_resolution() Instant Of Contact With Streams This Func. Returns Highest Progressive Quality : ) May Be Checking The Documentation Will Help You Next Time : ) A: There are two types of streams 1- Dynamic Adaptive Streaming over HTTP (DASH): save audio and video on the different tracks so you need to download both of them 2- Progressive Stream: save audio and video on the same track The Difference is: Progressive Stream is used only for resolutions 720p and below DASH for the highest quality streams so if you need to download a resolution higher than 720p like 1080p you must use DASH but you require to download both the audio and video tracks and then post-process them with software like FFmpeg to merge them. According to the Docs: some streams listed have both a video codec and audio codec, while others have just video or just audio, this is a result of YouTube supporting a streaming technique called Dynamic Adaptive Streaming over HTTP (DASH). In the context of pytube, the implications are for the highest quality streams; you now need to download both the audio and video tracks and then post-process them with software like FFmpeg to merge them. The legacy streams that contain the audio and video in a single file (referred to as “progressive download”) are still available, but only for resolutions 720p and below. so now you can replace your code: video = youtube.streams.first() with: video = youtube.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download() A: video = youtube.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first() without the attribute "download()" will work well
how to download youtube video in the highest quality available
This code works perfectly, but I don't want the lowest quality. I want the highest one. When I tried changing the video = youtube. streams.first() to video = youtube.streams.last() I encountered a problem where the video that I downloaded was just a black screen with the audio playing in the background. from tkinter import * import pytube # Functions def download(): video_url = url.get() try: youtube = pytube.YouTube(video_url) video = youtube.streams.first() video.download("C:/Users/iwanh/Desktop/MP4_MP3s") notif.config(fg="green", text="Download complete") except Exception as e: print(e) notif.config(fg="red", text="Video could not be downloaded") # Main Screen master = Tk() master.title("Youtube Video Downloader") # Labels Label(master, text="Youtube Video Converter", fg="red", font=("Calibri", 15)).grid(sticky=N, padx=100, row=0) Label(master, text="Please enter the link to your video below : ", font=("Calibri", 15)).grid(sticky=N, row=1, pady=15) notif = Label(master, font=("Calibri", 12)) notif.grid(sticky=N, pady=1, row=4) # Vars url = StringVar() # Entry Entry(master, width=50, textvariable=url).grid(sticky=N, row=2) # Button Button(master, width=20, text="Download", font=("Calibri", 12), command=download).grid(sticky=N, row=3, pady=15) master.mainloop()
[ "Try To Use\n\nget_highest_resolution()\n\nInstant Of Contact With Streams\nThis Func. Returns Highest Progressive Quality : )\nMay Be Checking The Documentation Will Help You Next Time : )\n", "There are two types of streams\n1- Dynamic Adaptive Streaming over HTTP (DASH): save audio and video on the different tracks so you need to download both of them\n2- Progressive Stream: save audio and video on the same track\nThe Difference is:\nProgressive Stream is used only for resolutions 720p and below\nDASH for the highest quality streams\nso if you need to download a resolution higher than 720p like 1080p\nyou must use DASH but you require to download both the audio and video tracks and then post-process them with software like FFmpeg to merge them.\nAccording to the Docs:\n\nsome streams listed have both a video codec and audio codec, while others have just video or just audio, this is a result of YouTube supporting a streaming technique called Dynamic Adaptive Streaming over HTTP (DASH).\n\n\nIn the context of pytube, the implications are for the highest quality streams; you now need to download both the audio and video tracks and then post-process them with software like FFmpeg to merge them.\n\n\nThe legacy streams that contain the audio and video in a single file (referred to as “progressive download”) are still available, but only for resolutions 720p and below.\n\nso now you can replace your code:\nvideo = youtube.streams.first()\n\nwith:\nvideo = youtube.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download()\n\n", "video = youtube.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first() \n\nwithout the attribute \"download()\" will work well\n" ]
[ 2, 0, 0 ]
[]
[]
[ "python", "python_3.x", "pytube", "youtube" ]
stackoverflow_0065802599_python_python_3.x_pytube_youtube.txt
Q: How to find stat (min, max, quantile, etc) of a list without using pandas.series? I have a variable list of elements. I want to be able to find, count mean std min 25% 50% 75% max . I know I can use pandas.Series.describe(). However, I have a restriction that I cannot use pandas for the specific problem. Is there any built in function/package that will give me the same output? Thanks. A: As mentioned in the comments count, min, and max are all built in so you can simply call count(your_list), max(your_list), min(your_list). I would recommend using libraries such as Pandas, Numpy etc. if you can. If you are restricted only to the standard library you can also take a look at the statistics module. For the others: Mean def mean(li): return sum(li) / len(li) Standard Deviation def std(li): mu = mean(li) return (sum((x-mu)**2 for x in li)/len(li)) ** 0.5 Quartiles I will implement for any percentile, you can then use percentile(your_list, 25) or others as needed. def percentile(li, percentile): n = len(li) idx = n * percentile / 100 return sorted(li)[math.floor(idx)] If you want to replicate Pandas describe function: def describe(li): return f""" count {len(li)} mean {mean(li)} std {std(li)} min {min(li)} 25% {percentile(li, 25)} 50% {percentile(li, 50)} 75% {percentile(li, 75)} max {max(li)}"""
How to find stat (min, max, quantile, etc) of a list without using pandas.series?
I have a variable list of elements. I want to be able to find, count mean std min 25% 50% 75% max . I know I can use pandas.Series.describe(). However, I have a restriction that I cannot use pandas for the specific problem. Is there any built in function/package that will give me the same output? Thanks.
[ "As mentioned in the comments count, min, and max are all built in so you can simply call count(your_list), max(your_list), min(your_list).\nI would recommend using libraries such as Pandas, Numpy etc. if you can. If you are restricted only to the standard library you can also take a look at the statistics module.\nFor the others:\nMean\ndef mean(li):\n return sum(li) / len(li)\n\nStandard Deviation\ndef std(li):\n mu = mean(li)\n return (sum((x-mu)**2 for x in li)/len(li)) ** 0.5\n\nQuartiles\nI will implement for any percentile, you can then use percentile(your_list, 25) or others as needed.\ndef percentile(li, percentile):\n n = len(li)\n idx = n * percentile / 100\n return sorted(li)[math.floor(idx)]\n\nIf you want to replicate Pandas describe function:\ndef describe(li):\n return f\"\"\"\n count {len(li)}\n mean {mean(li)}\n std {std(li)}\n min {min(li)}\n 25% {percentile(li, 25)}\n 50% {percentile(li, 50)}\n 75% {percentile(li, 75)}\n max {max(li)}\"\"\"\n\n" ]
[ 3 ]
[]
[]
[ "max", "min", "percentile", "python", "stat" ]
stackoverflow_0074590410_max_min_percentile_python_stat.txt
Q: is there a better way to get the data form beautiful soup query? I am trying to extract the m/z data for different ions from "https://www.lipidmaps.org/databases/lmsd/LMFA08040013". I can get access to the ions and thier data, however to extract the formula and m/z, I am thinking to convert it to a string and the use striping tool to extract it. Is thier another way using beautifulsoup? from bs4 import BeautifulSoup #used to interact with the website import requests soup = BeautifulSoup(requests.get("https://www.lipidmaps.org/databases/lmsd/LMFA08040013").text, "html.parser") for option in soup.find_all('option'): ion = option.text option = str(option) m_z = ion ion_formula = return ([m_z,ion-formula,ion] example of option data: <option data-display-formula="C&lt;sub&gt;18&lt;/sub&gt;H&lt;sub&gt;38&lt;/sub&gt;NO&lt;sub&gt;2&lt;/sub&gt;" data-formula="C18H38NO2" data-mass-z-ratio="300.2897" value="MplusH"> [M+H]+ </option> Example of output data: m_z = 300.2897 ion-formula = C18H38NO2 ion = \[M+H\]+ A: Not sure what you mean by more elegant but if all you want is the first option with the given ion value you can get the output you want this way: import requests from bs4 import BeautifulSoup url = "https://www.lipidmaps.org/databases/lmsd/LMFA08040013" soup = ( BeautifulSoup(requests.get(url).text, "lxml") .select_one(".change\:calculate-mz > option:nth-child(2)") ) mz = soup["data-mass-z-ratio"] formula = soup["data-formula"] ion = soup.getText(strip=True) print(f"{mz} {formula} {ion}") Output: 300.2897 C18H38NO2 [M+H]+ To list them all, try this: import requests from bs4 import BeautifulSoup url = "https://www.lipidmaps.org/databases/lmsd/LMFA08040013" options = ( BeautifulSoup(requests.get(url).text, "lxml") .select(".change\:calculate-mz > option")[1:] ) for option in options: mz = option["data-mass-z-ratio"] formula = option["data-formula"] ion = option.getText(strip=True) print(f"m_z = {mz}\nion-formula = {formula}\nion = {ion}") print("-" * 30) Output: m_z = 300.2897 ion-formula = C18H38NO2 ion = [M+H]+ ------------------------------ m_z = 282.2791 ion-formula = C18H36NO ion = [M+H-H2O]+ ------------------------------ m_z = 299.2819 ion-formula = C18H37NO2 ion = [M.]+ ------------------------------ m_z = 150.6485 ion-formula = C18H39NO2 ion = [M+2H]2+ ------------------------------ m_z = 100.7681 ion-formula = C18H40NO2 ion = [M+3H]3+ ------------------------------ m_z = 75.8279 ion-formula = C18H41NO2 ion = [M+4H]4+ ------------------------------ m_z = 338.2456 ion-formula = C18H37KNO2 ion = [M+K]+ ------------------------------ m_z = 188.6044 ion-formula = C18H37K2NO2 ion = [M+2K]2+ ------------------------------ m_z = 376.2015 ion-formula = C18H36K2NO2 ion = [M+2K-H]+ ------------------------------ m_z = 322.2716 ion-formula = C18H37NNaO2 ion = [M+Na]+ ------------------------------ m_z = 172.6304 ion-formula = C18H37NNa2O2 ion = [M+2Na]2+ ------------------------------ m_z = 344.2536 ion-formula = C18H36NNa2O2 ion = [M+2Na-H]+ ------------------------------ m_z = 306.2979 ion-formula = C18H37LiNO2 ion = [M+Li]+ ------------------------------ m_z = 156.6567 ion-formula = C18H37Li2NO2 ion = [M+2Li]2+ ------------------------------ m_z = 317.3162 ion-formula = C18H41N2O2 ion = [M+NH4]+ ------------------------------ m_z = 298.2752 ion-formula = C18H36NO2 ion = [M-H]- ------------------------------ m_z = 148.6339 ion-formula = C18H35NO2 ion = [M-2H]2- ------------------------------ m_z = 98.7535 ion-formula = C18H34NO2 ion = [M-3H]3- ------------------------------ m_z = 73.8133 ion-formula = C18H33NO2 ion = [M-4H]4- ------------------------------ m_z = 334.2518 ion-formula = C18H37ClNO2 ion = [M+Cl]- ------------------------------ m_z = 358.2963 ion-formula = C20H40NO4 ion = [M+OAc]- ------------------------------ m_z = 344.2806 ion-formula = C19H38NO4 ion = [M+HCOO]- ------------------------------ m_z = 299.2824 ion-formula = C18H37NO2 ion = M(neutral) ------------------------------ A: I can't say what could be considered elegant, but I usually get data like this using .get and list comprehension ionOptions = [{ 'ion': option.get_text(' ').strip(), 'ion-formula': option.get('data-formula'), 'm_z': option.get('data-mass-z-ratio') } for option in soup.select('option[data-mass-z-ratio][data-formula]')] and ionOptions would look like [{'ion': '[M+H]+', 'ion-formula': 'C18H38NO2', 'm_z': '300.2897'}, {'ion': '[M+H-H2O]+', 'ion-formula': 'C18H36NO', 'm_z': '282.2791'}, {'ion': '[M.]+', 'ion-formula': 'C18H37NO2', 'm_z': '299.2819'}, {'ion': '[M+2H]2+', 'ion-formula': 'C18H39NO2', 'm_z': '150.6485'}, {'ion': '[M+3H]3+', 'ion-formula': 'C18H40NO2', 'm_z': '100.7681'}, {'ion': '[M+4H]4+', 'ion-formula': 'C18H41NO2', 'm_z': '75.8279'}, {'ion': '[M+K]+', 'ion-formula': 'C18H37KNO2', 'm_z': '338.2456'}, {'ion': '[M+2K]2+', 'ion-formula': 'C18H37K2NO2', 'm_z': '188.6044'}, {'ion': '[M+2K-H]+', 'ion-formula': 'C18H36K2NO2', 'm_z': '376.2015'}, {'ion': '[M+Na]+', 'ion-formula': 'C18H37NNaO2', 'm_z': '322.2716'}, {'ion': '[M+2Na]2+', 'ion-formula': 'C18H37NNa2O2', 'm_z': '172.6304'}, {'ion': '[M+2Na-H]+', 'ion-formula': 'C18H36NNa2O2', 'm_z': '344.2536'}, {'ion': '[M+Li]+', 'ion-formula': 'C18H37LiNO2', 'm_z': '306.2979'}, {'ion': '[M+2Li]2+', 'ion-formula': 'C18H37Li2NO2', 'm_z': '156.6567'}, {'ion': '[M+NH4]+', 'ion-formula': 'C18H41N2O2', 'm_z': '317.3162'}, {'ion': '[M-H]-', 'ion-formula': 'C18H36NO2', 'm_z': '298.2752'}, {'ion': '[M-2H]2-', 'ion-formula': 'C18H35NO2', 'm_z': '148.6339'}, {'ion': '[M-3H]3-', 'ion-formula': 'C18H34NO2', 'm_z': '98.7535'}, {'ion': '[M-4H]4-', 'ion-formula': 'C18H33NO2', 'm_z': '73.8133'}, {'ion': '[M+Cl]-', 'ion-formula': 'C18H37ClNO2', 'm_z': '334.2518'}, {'ion': '[M+OAc]-', 'ion-formula': 'C20H40NO4', 'm_z': '358.2963'}, {'ion': '[M+HCOO]-', 'ion-formula': 'C19H38NO4', 'm_z': '344.2806'}, {'ion': 'M(neutral)', 'ion-formula': 'C18H37NO2', 'm_z': '299.2824'}] Note: You can use .find_all('option') or .select('option') instead of .select('option[data-mass-z-ratio][data-formula]'), but then the first option tag would also get included: {'ion': '(Select m/z)', 'ion-formula': None, 'm_z': None} You could print it in sections for o in ionOptions: for k, v in o.items(): print(f'{k:>15} = {v}') print('-'*40) output: ion = [M+H]+ ion-formula = C18H38NO2 m_z = 300.2897 ---------------------------------------- ion = [M+H-H2O]+ ion-formula = C18H36NO m_z = 282.2791 ---------------------------------------- ion = [M.]+ ion-formula = C18H37NO2 m_z = 299.2819 ---------------------------------------- ion = [M+2H]2+ ion-formula = C18H39NO2 m_z = 150.6485 ---------------------------------------- ion = [M+3H]3+ ion-formula = C18H40NO2 m_z = 100.7681 ---------------------------------------- ion = [M+4H]4+ ion-formula = C18H41NO2 m_z = 75.8279 ---------------------------------------- ion = [M+K]+ ion-formula = C18H37KNO2 m_z = 338.2456 ---------------------------------------- ion = [M+2K]2+ ion-formula = C18H37K2NO2 m_z = 188.6044 ---------------------------------------- ion = [M+2K-H]+ ion-formula = C18H36K2NO2 m_z = 376.2015 ---------------------------------------- ion = [M+Na]+ ion-formula = C18H37NNaO2 m_z = 322.2716 ---------------------------------------- ion = [M+2Na]2+ ion-formula = C18H37NNa2O2 m_z = 172.6304 ---------------------------------------- ion = [M+2Na-H]+ ion-formula = C18H36NNa2O2 m_z = 344.2536 ---------------------------------------- ion = [M+Li]+ ion-formula = C18H37LiNO2 m_z = 306.2979 ---------------------------------------- ion = [M+2Li]2+ ion-formula = C18H37Li2NO2 m_z = 156.6567 ---------------------------------------- ion = [M+NH4]+ ion-formula = C18H41N2O2 m_z = 317.3162 ---------------------------------------- ion = [M-H]- ion-formula = C18H36NO2 m_z = 298.2752 ---------------------------------------- ion = [M-2H]2- ion-formula = C18H35NO2 m_z = 148.6339 ---------------------------------------- ion = [M-3H]3- ion-formula = C18H34NO2 m_z = 98.7535 ---------------------------------------- ion = [M-4H]4- ion-formula = C18H33NO2 m_z = 73.8133 ---------------------------------------- ion = [M+Cl]- ion-formula = C18H37ClNO2 m_z = 334.2518 ---------------------------------------- ion = [M+OAc]- ion-formula = C20H40NO4 m_z = 358.2963 ---------------------------------------- ion = [M+HCOO]- ion-formula = C19H38NO4 m_z = 344.2806 ---------------------------------------- ion = M(neutral) ion-formula = C18H37NO2 m_z = 299.2824 ---------------------------------------- I personally prefer to use pandas to get a tabular format: # import pandas print(pandas.DataFrame(ionOptions).to_markdown(index=False)) output: | ion | ion-formula | m_z | |:-----------|:--------------|---------:| | [M+H]+ | C18H38NO2 | 300.29 | | [M+H-H2O]+ | C18H36NO | 282.279 | | [M.]+ | C18H37NO2 | 299.282 | | [M+2H]2+ | C18H39NO2 | 150.649 | | [M+3H]3+ | C18H40NO2 | 100.768 | | [M+4H]4+ | C18H41NO2 | 75.8279 | | [M+K]+ | C18H37KNO2 | 338.246 | | [M+2K]2+ | C18H37K2NO2 | 188.604 | | [M+2K-H]+ | C18H36K2NO2 | 376.202 | | [M+Na]+ | C18H37NNaO2 | 322.272 | | [M+2Na]2+ | C18H37NNa2O2 | 172.63 | | [M+2Na-H]+ | C18H36NNa2O2 | 344.254 | | [M+Li]+ | C18H37LiNO2 | 306.298 | | [M+2Li]2+ | C18H37Li2NO2 | 156.657 | | [M+NH4]+ | C18H41N2O2 | 317.316 | | [M-H]- | C18H36NO2 | 298.275 | | [M-2H]2- | C18H35NO2 | 148.634 | | [M-3H]3- | C18H34NO2 | 98.7535 | | [M-4H]4- | C18H33NO2 | 73.8133 | | [M+Cl]- | C18H37ClNO2 | 334.252 | | [M+OAc]- | C20H40NO4 | 358.296 | | [M+HCOO]- | C19H38NO4 | 344.281 | | M(neutral) | C18H37NO2 | 299.282 |
is there a better way to get the data form beautiful soup query?
I am trying to extract the m/z data for different ions from "https://www.lipidmaps.org/databases/lmsd/LMFA08040013". I can get access to the ions and thier data, however to extract the formula and m/z, I am thinking to convert it to a string and the use striping tool to extract it. Is thier another way using beautifulsoup? from bs4 import BeautifulSoup #used to interact with the website import requests soup = BeautifulSoup(requests.get("https://www.lipidmaps.org/databases/lmsd/LMFA08040013").text, "html.parser") for option in soup.find_all('option'): ion = option.text option = str(option) m_z = ion ion_formula = return ([m_z,ion-formula,ion] example of option data: <option data-display-formula="C&lt;sub&gt;18&lt;/sub&gt;H&lt;sub&gt;38&lt;/sub&gt;NO&lt;sub&gt;2&lt;/sub&gt;" data-formula="C18H38NO2" data-mass-z-ratio="300.2897" value="MplusH"> [M+H]+ </option> Example of output data: m_z = 300.2897 ion-formula = C18H38NO2 ion = \[M+H\]+
[ "Not sure what you mean by more elegant but if all you want is the first option with the given ion value you can get the output you want this way:\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.lipidmaps.org/databases/lmsd/LMFA08040013\"\nsoup = (\n BeautifulSoup(requests.get(url).text, \"lxml\")\n .select_one(\".change\\:calculate-mz > option:nth-child(2)\")\n)\n\nmz = soup[\"data-mass-z-ratio\"]\nformula = soup[\"data-formula\"]\nion = soup.getText(strip=True)\n\nprint(f\"{mz} {formula} {ion}\")\n\nOutput:\n300.2897 C18H38NO2 [M+H]+\n\nTo list them all, try this:\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.lipidmaps.org/databases/lmsd/LMFA08040013\"\noptions = (\n BeautifulSoup(requests.get(url).text, \"lxml\")\n .select(\".change\\:calculate-mz > option\")[1:]\n)\n\nfor option in options:\n mz = option[\"data-mass-z-ratio\"]\n formula = option[\"data-formula\"]\n ion = option.getText(strip=True)\n print(f\"m_z = {mz}\\nion-formula = {formula}\\nion = {ion}\")\n print(\"-\" * 30)\n\nOutput:\nm_z = 300.2897\nion-formula = C18H38NO2\nion = [M+H]+\n------------------------------\nm_z = 282.2791\nion-formula = C18H36NO\nion = [M+H-H2O]+\n------------------------------\nm_z = 299.2819\nion-formula = C18H37NO2\nion = [M.]+\n------------------------------\nm_z = 150.6485\nion-formula = C18H39NO2\nion = [M+2H]2+\n------------------------------\nm_z = 100.7681\nion-formula = C18H40NO2\nion = [M+3H]3+\n------------------------------\nm_z = 75.8279\nion-formula = C18H41NO2\nion = [M+4H]4+\n------------------------------\nm_z = 338.2456\nion-formula = C18H37KNO2\nion = [M+K]+\n------------------------------\nm_z = 188.6044\nion-formula = C18H37K2NO2\nion = [M+2K]2+\n------------------------------\nm_z = 376.2015\nion-formula = C18H36K2NO2\nion = [M+2K-H]+\n------------------------------\nm_z = 322.2716\nion-formula = C18H37NNaO2\nion = [M+Na]+\n------------------------------\nm_z = 172.6304\nion-formula = C18H37NNa2O2\nion = [M+2Na]2+\n------------------------------\nm_z = 344.2536\nion-formula = C18H36NNa2O2\nion = [M+2Na-H]+\n------------------------------\nm_z = 306.2979\nion-formula = C18H37LiNO2\nion = [M+Li]+\n------------------------------\nm_z = 156.6567\nion-formula = C18H37Li2NO2\nion = [M+2Li]2+\n------------------------------\nm_z = 317.3162\nion-formula = C18H41N2O2\nion = [M+NH4]+\n------------------------------\nm_z = 298.2752\nion-formula = C18H36NO2\nion = [M-H]-\n------------------------------\nm_z = 148.6339\nion-formula = C18H35NO2\nion = [M-2H]2-\n------------------------------\nm_z = 98.7535\nion-formula = C18H34NO2\nion = [M-3H]3-\n------------------------------\nm_z = 73.8133\nion-formula = C18H33NO2\nion = [M-4H]4-\n------------------------------\nm_z = 334.2518\nion-formula = C18H37ClNO2\nion = [M+Cl]-\n------------------------------\nm_z = 358.2963\nion-formula = C20H40NO4\nion = [M+OAc]-\n------------------------------\nm_z = 344.2806\nion-formula = C19H38NO4\nion = [M+HCOO]-\n------------------------------\nm_z = 299.2824\nion-formula = C18H37NO2\nion = M(neutral)\n------------------------------\n\n", "I can't say what could be considered elegant, but I usually get data like this using .get and list comprehension\nionOptions = [{\n 'ion': option.get_text(' ').strip(),\n 'ion-formula': option.get('data-formula'),\n 'm_z': option.get('data-mass-z-ratio')\n} for option in soup.select('option[data-mass-z-ratio][data-formula]')]\n\nand ionOptions would look like\n[{'ion': '[M+H]+', 'ion-formula': 'C18H38NO2', 'm_z': '300.2897'},\n {'ion': '[M+H-H2O]+', 'ion-formula': 'C18H36NO', 'm_z': '282.2791'},\n {'ion': '[M.]+', 'ion-formula': 'C18H37NO2', 'm_z': '299.2819'},\n {'ion': '[M+2H]2+', 'ion-formula': 'C18H39NO2', 'm_z': '150.6485'},\n {'ion': '[M+3H]3+', 'ion-formula': 'C18H40NO2', 'm_z': '100.7681'},\n {'ion': '[M+4H]4+', 'ion-formula': 'C18H41NO2', 'm_z': '75.8279'},\n {'ion': '[M+K]+', 'ion-formula': 'C18H37KNO2', 'm_z': '338.2456'},\n {'ion': '[M+2K]2+', 'ion-formula': 'C18H37K2NO2', 'm_z': '188.6044'},\n {'ion': '[M+2K-H]+', 'ion-formula': 'C18H36K2NO2', 'm_z': '376.2015'},\n {'ion': '[M+Na]+', 'ion-formula': 'C18H37NNaO2', 'm_z': '322.2716'},\n {'ion': '[M+2Na]2+', 'ion-formula': 'C18H37NNa2O2', 'm_z': '172.6304'},\n {'ion': '[M+2Na-H]+', 'ion-formula': 'C18H36NNa2O2', 'm_z': '344.2536'},\n {'ion': '[M+Li]+', 'ion-formula': 'C18H37LiNO2', 'm_z': '306.2979'},\n {'ion': '[M+2Li]2+', 'ion-formula': 'C18H37Li2NO2', 'm_z': '156.6567'},\n {'ion': '[M+NH4]+', 'ion-formula': 'C18H41N2O2', 'm_z': '317.3162'},\n {'ion': '[M-H]-', 'ion-formula': 'C18H36NO2', 'm_z': '298.2752'},\n {'ion': '[M-2H]2-', 'ion-formula': 'C18H35NO2', 'm_z': '148.6339'},\n {'ion': '[M-3H]3-', 'ion-formula': 'C18H34NO2', 'm_z': '98.7535'},\n {'ion': '[M-4H]4-', 'ion-formula': 'C18H33NO2', 'm_z': '73.8133'},\n {'ion': '[M+Cl]-', 'ion-formula': 'C18H37ClNO2', 'm_z': '334.2518'},\n {'ion': '[M+OAc]-', 'ion-formula': 'C20H40NO4', 'm_z': '358.2963'},\n {'ion': '[M+HCOO]-', 'ion-formula': 'C19H38NO4', 'm_z': '344.2806'},\n {'ion': 'M(neutral)', 'ion-formula': 'C18H37NO2', 'm_z': '299.2824'}]\n\nNote: You can use .find_all('option') or .select('option') instead of .select('option[data-mass-z-ratio][data-formula]'), but then the first option tag would also get included:\n{'ion': '(Select m/z)', 'ion-formula': None, 'm_z': None}\n\n\nYou could print it in sections\nfor o in ionOptions:\n for k, v in o.items(): print(f'{k:>15} = {v}')\n print('-'*40)\n\noutput:\n ion = [M+H]+\n ion-formula = C18H38NO2\n m_z = 300.2897\n----------------------------------------\n ion = [M+H-H2O]+\n ion-formula = C18H36NO\n m_z = 282.2791\n----------------------------------------\n ion = [M.]+\n ion-formula = C18H37NO2\n m_z = 299.2819\n----------------------------------------\n ion = [M+2H]2+\n ion-formula = C18H39NO2\n m_z = 150.6485\n----------------------------------------\n ion = [M+3H]3+\n ion-formula = C18H40NO2\n m_z = 100.7681\n----------------------------------------\n ion = [M+4H]4+\n ion-formula = C18H41NO2\n m_z = 75.8279\n----------------------------------------\n ion = [M+K]+\n ion-formula = C18H37KNO2\n m_z = 338.2456\n----------------------------------------\n ion = [M+2K]2+\n ion-formula = C18H37K2NO2\n m_z = 188.6044\n----------------------------------------\n ion = [M+2K-H]+\n ion-formula = C18H36K2NO2\n m_z = 376.2015\n----------------------------------------\n ion = [M+Na]+\n ion-formula = C18H37NNaO2\n m_z = 322.2716\n----------------------------------------\n ion = [M+2Na]2+\n ion-formula = C18H37NNa2O2\n m_z = 172.6304\n----------------------------------------\n ion = [M+2Na-H]+\n ion-formula = C18H36NNa2O2\n m_z = 344.2536\n----------------------------------------\n ion = [M+Li]+\n ion-formula = C18H37LiNO2\n m_z = 306.2979\n----------------------------------------\n ion = [M+2Li]2+\n ion-formula = C18H37Li2NO2\n m_z = 156.6567\n----------------------------------------\n ion = [M+NH4]+\n ion-formula = C18H41N2O2\n m_z = 317.3162\n----------------------------------------\n ion = [M-H]-\n ion-formula = C18H36NO2\n m_z = 298.2752\n----------------------------------------\n ion = [M-2H]2-\n ion-formula = C18H35NO2\n m_z = 148.6339\n----------------------------------------\n ion = [M-3H]3-\n ion-formula = C18H34NO2\n m_z = 98.7535\n----------------------------------------\n ion = [M-4H]4-\n ion-formula = C18H33NO2\n m_z = 73.8133\n----------------------------------------\n ion = [M+Cl]-\n ion-formula = C18H37ClNO2\n m_z = 334.2518\n----------------------------------------\n ion = [M+OAc]-\n ion-formula = C20H40NO4\n m_z = 358.2963\n----------------------------------------\n ion = [M+HCOO]-\n ion-formula = C19H38NO4\n m_z = 344.2806\n----------------------------------------\n ion = M(neutral)\n ion-formula = C18H37NO2\n m_z = 299.2824\n----------------------------------------\n\n\nI personally prefer to use pandas to get a tabular format:\n# import pandas\n\nprint(pandas.DataFrame(ionOptions).to_markdown(index=False)) \n\noutput:\n| ion | ion-formula | m_z |\n|:-----------|:--------------|---------:|\n| [M+H]+ | C18H38NO2 | 300.29 |\n| [M+H-H2O]+ | C18H36NO | 282.279 |\n| [M.]+ | C18H37NO2 | 299.282 |\n| [M+2H]2+ | C18H39NO2 | 150.649 |\n| [M+3H]3+ | C18H40NO2 | 100.768 |\n| [M+4H]4+ | C18H41NO2 | 75.8279 |\n| [M+K]+ | C18H37KNO2 | 338.246 |\n| [M+2K]2+ | C18H37K2NO2 | 188.604 |\n| [M+2K-H]+ | C18H36K2NO2 | 376.202 |\n| [M+Na]+ | C18H37NNaO2 | 322.272 |\n| [M+2Na]2+ | C18H37NNa2O2 | 172.63 |\n| [M+2Na-H]+ | C18H36NNa2O2 | 344.254 |\n| [M+Li]+ | C18H37LiNO2 | 306.298 |\n| [M+2Li]2+ | C18H37Li2NO2 | 156.657 |\n| [M+NH4]+ | C18H41N2O2 | 317.316 |\n| [M-H]- | C18H36NO2 | 298.275 |\n| [M-2H]2- | C18H35NO2 | 148.634 |\n| [M-3H]3- | C18H34NO2 | 98.7535 |\n| [M-4H]4- | C18H33NO2 | 73.8133 |\n| [M+Cl]- | C18H37ClNO2 | 334.252 |\n| [M+OAc]- | C20H40NO4 | 358.296 |\n| [M+HCOO]- | C19H38NO4 | 344.281 |\n| M(neutral) | C18H37NO2 | 299.282 |\n\n" ]
[ 1, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074590759_beautifulsoup_python.txt
Q: How to separate elements of a line having multiple delimiters via Python? date Mon Jan 4 15:59:21.129 2021 base hex timestamps absolute no internal events logged // version 13.0.0 //545285.973861 previous log file: Myfile_0.asc // Measurement UUID: 4520e127-a0b6-48d2-9e23-2588160af285 545333.620639 LoggingString := "Log,11:28 PM, Sunday, January 10, 2021,11:28:17.4,34.72,12,0.01058,11.99,0.01077,12,0.01127,11.99,0.01142,11.76,0.1053,11.99,0.01076,11.96,0.01092,2.516,0,2,OM_2_1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" 545335.691676 LoggingString := "Log,11:28 PM, Sunday, January 10, 2021,11:28:19.5,34.61,12,0.01058,11.99,0.01072,11.99,0.01127,11.99,0.01139,11.87,0.1118,12.01,0.01046,11.99,0.01145,2.581,0,2,OM_2_1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" 545337.796715 LoggingString := "Log,11:28 PM, Sunday, January 10, 2021,11:28:21.6,34.52,11.99,0.0106,11.99,0.01077,11.99,0.01151,11.99,0.01139,11.72,0.1081,12,0.0109,11.96,0.01107,2.543,0,2,OM_2_1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" 545339.919752 LoggingString := "Log,11:28 PM, Sunday, January 10, 2021,11:28:23.7,34.41,12,0.01082,11.99,0.01104,11.99,0.01156,11.99,0.01164,11.62,0.1042,11.99,0.01105,11.96,0.01126,2.596,0,2,OM_2_1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" The above text represents my input data from a log file (below available in image format too) : I want to perform certain operations with the data shown in the image. However, i am unable to figure out a method to split each element in the line. The data starting after 11:28:17.4 is of importance for me . I have used the numpy.genfromtxt function & usecols arg to print data between columns 6 and 22..however, i wanted to be able to split each element of the row so that i could use the elements as identifiers to begin recording the important data for me. For e.g in line 7, there is "whitespace, comma" as separators. How do i split the data so that at the end i get the following as output : List = ['545333.620639','Logging String:=', 'Log', .........., 2021, 11:28:17.4, 34.72 .....] Also, when i use "Readlines()", is the data stored as one complete string in the List or as individual string elements in List? This is a more hardcoded approach to the solution i want. This gives me a .csv file at the end with specific data extracted from a larger dataset.. However, i want a better approach to this. Instead of manually defining line number as counter to start storing data into .csv, i want to be able to define that if "// Measurement UUID:" is detected, then start storing data into .csv from next line To be able to separate each line into individual elements How to define multipe delimiters for "np.genfromtxt" function import numpy as np Testfile = open('C:/Documents/Myfile.asc','r') Read_data = Testfile.readlines() count = 0 for line in Read_data: count += 1 if count < 7: ## counter to start saving data into .csv from 7th line print("Line{}: {}".format(count, line.strip())) else: mydat = np.genfromtxt("C:/Documents/Myfile.asc",skip_header=(count-1),usecols= (4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23),delimiter=',') Data_frame = pd.DataFrame(mydat) Data_frame.to_csv("Triall_3.csv",sep=';') exit() A: I hope I've understood your question well. You can check if there's LoggingString := inside the line and if is, split the string: import pandas as pd out = [] with open("your_file.txt", "r") as f_in: for line in map(str.strip, f_in): if "LoggingString :=" in line: first_quote = line.index('"') last_quote = line.index('"', first_quote + 1) out.append( line[:first_quote].split(maxsplit=1) + line[first_quote + 1 : last_quote].split(","), ) df = pd.DataFrame(out) print(df) Prints: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 0 545333.620639 LoggingString := Log 11:28 PM Sunday January 10 2021 11:28:17.4 34.72 12 0.01058 11.99 0.01077 12 0.01127 11.99 0.01142 11.76 0.1053 11.99 0.01076 11.96 0.01092 2.516 0 2 OM_2_1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 545335.691676 LoggingString := Log 11:28 PM Sunday January 10 2021 11:28:19.5 34.61 12 0.01058 11.99 0.01072 11.99 0.01127 11.99 0.01139 11.87 0.1118 12.01 0.01046 11.99 0.01145 2.581 0 2 OM_2_1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 545337.796715 LoggingString := Log 11:28 PM Sunday January 10 2021 11:28:21.6 34.52 11.99 0.0106 11.99 0.01077 11.99 0.01151 11.99 0.01139 11.72 0.1081 12 0.0109 11.96 0.01107 2.543 0 2 OM_2_1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 545339.919752 LoggingString := Log 11:28 PM Sunday January 10 2021 11:28:23.7 34.41 12 0.01082 11.99 0.01104 11.99 0.01156 11.99 0.01164 11.62 0.1042 11.99 0.01105 11.96 0.01126 2.596 0 2 OM_2_1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
How to separate elements of a line having multiple delimiters via Python?
date Mon Jan 4 15:59:21.129 2021 base hex timestamps absolute no internal events logged // version 13.0.0 //545285.973861 previous log file: Myfile_0.asc // Measurement UUID: 4520e127-a0b6-48d2-9e23-2588160af285 545333.620639 LoggingString := "Log,11:28 PM, Sunday, January 10, 2021,11:28:17.4,34.72,12,0.01058,11.99,0.01077,12,0.01127,11.99,0.01142,11.76,0.1053,11.99,0.01076,11.96,0.01092,2.516,0,2,OM_2_1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" 545335.691676 LoggingString := "Log,11:28 PM, Sunday, January 10, 2021,11:28:19.5,34.61,12,0.01058,11.99,0.01072,11.99,0.01127,11.99,0.01139,11.87,0.1118,12.01,0.01046,11.99,0.01145,2.581,0,2,OM_2_1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" 545337.796715 LoggingString := "Log,11:28 PM, Sunday, January 10, 2021,11:28:21.6,34.52,11.99,0.0106,11.99,0.01077,11.99,0.01151,11.99,0.01139,11.72,0.1081,12,0.0109,11.96,0.01107,2.543,0,2,OM_2_1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" 545339.919752 LoggingString := "Log,11:28 PM, Sunday, January 10, 2021,11:28:23.7,34.41,12,0.01082,11.99,0.01104,11.99,0.01156,11.99,0.01164,11.62,0.1042,11.99,0.01105,11.96,0.01126,2.596,0,2,OM_2_1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" The above text represents my input data from a log file (below available in image format too) : I want to perform certain operations with the data shown in the image. However, i am unable to figure out a method to split each element in the line. The data starting after 11:28:17.4 is of importance for me . I have used the numpy.genfromtxt function & usecols arg to print data between columns 6 and 22..however, i wanted to be able to split each element of the row so that i could use the elements as identifiers to begin recording the important data for me. For e.g in line 7, there is "whitespace, comma" as separators. How do i split the data so that at the end i get the following as output : List = ['545333.620639','Logging String:=', 'Log', .........., 2021, 11:28:17.4, 34.72 .....] Also, when i use "Readlines()", is the data stored as one complete string in the List or as individual string elements in List? This is a more hardcoded approach to the solution i want. This gives me a .csv file at the end with specific data extracted from a larger dataset.. However, i want a better approach to this. Instead of manually defining line number as counter to start storing data into .csv, i want to be able to define that if "// Measurement UUID:" is detected, then start storing data into .csv from next line To be able to separate each line into individual elements How to define multipe delimiters for "np.genfromtxt" function import numpy as np Testfile = open('C:/Documents/Myfile.asc','r') Read_data = Testfile.readlines() count = 0 for line in Read_data: count += 1 if count < 7: ## counter to start saving data into .csv from 7th line print("Line{}: {}".format(count, line.strip())) else: mydat = np.genfromtxt("C:/Documents/Myfile.asc",skip_header=(count-1),usecols= (4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23),delimiter=',') Data_frame = pd.DataFrame(mydat) Data_frame.to_csv("Triall_3.csv",sep=';') exit()
[ "I hope I've understood your question well. You can check if there's LoggingString := inside the line and if is, split the string:\nimport pandas as pd\n\nout = []\nwith open(\"your_file.txt\", \"r\") as f_in:\n for line in map(str.strip, f_in):\n if \"LoggingString :=\" in line:\n first_quote = line.index('\"')\n last_quote = line.index('\"', first_quote + 1)\n out.append(\n line[:first_quote].split(maxsplit=1)\n + line[first_quote + 1 : last_quote].split(\",\"),\n )\n\ndf = pd.DataFrame(out)\nprint(df)\n\nPrints:\n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43\n0 545333.620639 LoggingString := Log 11:28 PM Sunday January 10 2021 11:28:17.4 34.72 12 0.01058 11.99 0.01077 12 0.01127 11.99 0.01142 11.76 0.1053 11.99 0.01076 11.96 0.01092 2.516 0 2 OM_2_1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 545335.691676 LoggingString := Log 11:28 PM Sunday January 10 2021 11:28:19.5 34.61 12 0.01058 11.99 0.01072 11.99 0.01127 11.99 0.01139 11.87 0.1118 12.01 0.01046 11.99 0.01145 2.581 0 2 OM_2_1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n2 545337.796715 LoggingString := Log 11:28 PM Sunday January 10 2021 11:28:21.6 34.52 11.99 0.0106 11.99 0.01077 11.99 0.01151 11.99 0.01139 11.72 0.1081 12 0.0109 11.96 0.01107 2.543 0 2 OM_2_1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n3 545339.919752 LoggingString := Log 11:28 PM Sunday January 10 2021 11:28:23.7 34.41 12 0.01082 11.99 0.01104 11.99 0.01156 11.99 0.01164 11.62 0.1042 11.99 0.01105 11.96 0.01126 2.596 0 2 OM_2_1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n\n" ]
[ 1 ]
[]
[]
[ "arrays", "export_to_csv", "file", "numpy", "python" ]
stackoverflow_0074589537_arrays_export_to_csv_file_numpy_python.txt
Q: How to get the value of a selected treeview item? I've looked at several posts regarding this and they've done the following -The output i get is blank -The output i get is the id, which is practically useless unless somebody can show me how to manipulate it -No output at all i just want to be able to click an item in treeview, and instantly be given the text i just clicked def OnDoubleClick(event): item = course1_assessments.focus() print (item) course1_assessments.bind("<<TreeviewSelect>>", OnDoubleClick) This code gives me 'I001' if i click the first item, and 'I002' when i click the second; id assume these are column values in the tree, but still useless to me A: You can get a list of the selected items with the selection method of the widget. It will return a list of item ids. You can use the item method to get information about each item. For example: import tkinter as tk from tkinter import ttk class App: def __init__(self): self.root = tk.Tk() self.tree = ttk.Treeview() self.tree.pack(side="top", fill="both") self.tree.bind("<<TreeviewSelect>>", self.on_tree_select) for i in range(10): self.tree.insert("", "end", text="Item %s" % i) self.root.mainloop() def on_tree_select(self, event): print("selected items:") for item in self.tree.selection(): item_text = self.tree.item(item,"text") print(item_text) if __name__ == "__main__": app = App() A: I tried this as well to retrieve the ID in one of the columns for use in another function. I noticed when selecting multiple elements, they return the same ID as the last selected when doing mouseclicks combined with SHIFT. Selecting one at a time with mouseclick and CTRL works when printing to console. I also found that to change output from ID to another column change the value inside square brackets. Combine this with the above answer as needed. To give context of my implementation, I am using the ID returned from the below code to query a database to retrieve the text I want and then outputting that into another frame or textbox widget. def db_reader_selector(self, event): return print(self.db_reader.selection()[0]) A: Here's a dead simple piece of code that I believe answers the question "How do I get a value from a selected Treeview item:' The tree has columns 'MTD' and 'YTD'. The 'item' retrieved by the tree.selection() call is a tuple of strings, the first value being the iid of the selected item. This value is passed to the set method, along with the name of the column value you want to retrieve. All of this seems grossly counter-intuitive to me, but it works. import tkinter.ttk as ttk if __name__ == '__main__': def tree_select(event): tree: ttk.Treeview = event.widget item = tree.selection() mtd_var.set(tree.set(item[0], 'MTD')) ytd_var.set(tree.set(item[0], 'YTD')) pass iid_map: dict[str, str] = {} root = tk.Tk() ttk.Label(master=root, text='MTD', width=4, anchor=tk.E).grid(column=0, row=0, padx=5, pady=5) mtd_var = tk.StringVar() mtd_entry = ttk.Entry(master=root, textvariable=mtd_var, width=10) mtd_entry.grid(column=1, row=0, padx=5, pady=5, sticky=tk.W) ttk.Label(master=root, text='YTD', width=4, anchor=tk.E).grid(column=2, row=0, padx=5, pady=5) ytd_var = tk.StringVar() ytd_entry = ttk.Entry(master=root, textvariable=ytd_var, width=10) ytd_entry.grid(column=3, row=0, padx=5, pady=5, sticky=tk.W) tree_root = ttk.Treeview(master=root, columns=('MTD', 'YTD')) tree_root.column('MTD', width=30) tree_root.heading('MTD', text='Month to Date', anchor=tk.E) tree_root.column('YTD', width=30) tree_root.heading('YTD', text='Year to Date', anchor=tk.E) iid = tree_root.insert(parent='', index='end', text='Branch One', open=False) tree_root.insert(parent=iid, index='end', text='Item 0', values=(100, 1500), tags=('detail',)) iid = tree_root.insert(parent='', index='end', text='Branch Two', open=True) tree_root.insert(parent=iid, index='end', text='Item 1', values=(250, 12000), tags=('detail',)) tree_root.insert(parent=iid, index=0, text='Item 0') tree_root.grid(column=0, row=1, padx=5, pady=5, columnspan=4) tree_root.insert(parent=iid, index=1, text='Item 0.5', values=(100, 150)) tree_root.bind('<<TreeviewSelect>>', tree_select) root.mainloop()
How to get the value of a selected treeview item?
I've looked at several posts regarding this and they've done the following -The output i get is blank -The output i get is the id, which is practically useless unless somebody can show me how to manipulate it -No output at all i just want to be able to click an item in treeview, and instantly be given the text i just clicked def OnDoubleClick(event): item = course1_assessments.focus() print (item) course1_assessments.bind("<<TreeviewSelect>>", OnDoubleClick) This code gives me 'I001' if i click the first item, and 'I002' when i click the second; id assume these are column values in the tree, but still useless to me
[ "You can get a list of the selected items with the selection method of the widget. It will return a list of item ids. You can use the item method to get information about each item.\nFor example:\nimport tkinter as tk\nfrom tkinter import ttk\n\nclass App:\n def __init__(self):\n self.root = tk.Tk()\n self.tree = ttk.Treeview()\n self.tree.pack(side=\"top\", fill=\"both\")\n self.tree.bind(\"<<TreeviewSelect>>\", self.on_tree_select)\n\n for i in range(10):\n self.tree.insert(\"\", \"end\", text=\"Item %s\" % i)\n\n self.root.mainloop()\n\n def on_tree_select(self, event):\n print(\"selected items:\")\n for item in self.tree.selection():\n item_text = self.tree.item(item,\"text\")\n print(item_text)\n\nif __name__ == \"__main__\":\n app = App()\n\n", "I tried this as well to retrieve the ID in one of the columns for use in another function. I noticed when selecting multiple elements, they return the same ID as the last selected when doing mouseclicks combined with SHIFT. Selecting one at a time with mouseclick and CTRL works when printing to console.\nI also found that to change output from ID to another column change the value inside square brackets. Combine this with the above answer as needed. To give context of my implementation, I am using the ID returned from the below code to query a database to retrieve the text I want and then outputting that into another frame or textbox widget.\n def db_reader_selector(self, event):\n return print(self.db_reader.selection()[0])\n\n", "Here's a dead simple piece of code that I believe answers the question \"How do I get a value from a selected Treeview item:' The tree has columns 'MTD' and 'YTD'. The 'item' retrieved by the tree.selection() call is a tuple of strings, the first value being the iid of the selected item. This value is passed to the set method, along with the name of the column value you want to retrieve. All of this seems grossly counter-intuitive to me, but it works.\n\nimport tkinter.ttk as ttk\n\n\nif __name__ == '__main__':\n def tree_select(event):\n tree: ttk.Treeview = event.widget\n item = tree.selection()\n mtd_var.set(tree.set(item[0], 'MTD'))\n ytd_var.set(tree.set(item[0], 'YTD'))\n pass\n\n iid_map: dict[str, str] = {}\n root = tk.Tk()\n ttk.Label(master=root, text='MTD', width=4, anchor=tk.E).grid(column=0, row=0, padx=5, pady=5)\n mtd_var = tk.StringVar()\n mtd_entry = ttk.Entry(master=root, textvariable=mtd_var, width=10)\n mtd_entry.grid(column=1, row=0, padx=5, pady=5, sticky=tk.W)\n ttk.Label(master=root, text='YTD', width=4, anchor=tk.E).grid(column=2, row=0, padx=5, pady=5)\n ytd_var = tk.StringVar()\n ytd_entry = ttk.Entry(master=root, textvariable=ytd_var, width=10)\n ytd_entry.grid(column=3, row=0, padx=5, pady=5, sticky=tk.W)\n tree_root = ttk.Treeview(master=root, columns=('MTD', 'YTD'))\n tree_root.column('MTD', width=30)\n tree_root.heading('MTD', text='Month to Date', anchor=tk.E)\n tree_root.column('YTD', width=30)\n tree_root.heading('YTD', text='Year to Date', anchor=tk.E)\n iid = tree_root.insert(parent='', index='end', text='Branch One', open=False)\n tree_root.insert(parent=iid, index='end', text='Item 0', values=(100, 1500), tags=('detail',))\n iid = tree_root.insert(parent='', index='end', text='Branch Two', open=True)\n tree_root.insert(parent=iid, index='end', text='Item 1', values=(250, 12000), tags=('detail',))\n tree_root.insert(parent=iid, index=0, text='Item 0')\n tree_root.grid(column=0, row=1, padx=5, pady=5, columnspan=4)\n tree_root.insert(parent=iid, index=1, text='Item 0.5', values=(100, 150))\n tree_root.bind('<<TreeviewSelect>>', tree_select)\n root.mainloop()\n\n\n" ]
[ 12, 0, 0 ]
[]
[]
[ "python", "python_2.7", "python_3.x", "tkinter", "treeview" ]
stackoverflow_0034849035_python_python_2.7_python_3.x_tkinter_treeview.txt
Q: Shipping Python interpreter with C++ project Problem description: I have a Visual Studio 2022 C++ project that involves live python script interpretation. Naturally, I need a valid Python installation to do this. However, I intend to ship this as an application, so I'd like to have a localized Python installation, to avoid consumer-side installation, but that doesn't interfere with Windows' Environmental Variables. What I've done: I included "Python.h" from my Python installation's "include" folder, I've added its "libs" folder to "Additional Library Directories", I've added "python311.lib" to "Additional Dependencies", and I remembered to copy Python311.dll to my project's Solution Directory. Everything is linked properly. However, when I run compile and execute my program, I receive a long list of errors, which are as follows: Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = 'C:\Coding Projects\MaSGE\Lib' sys._base_executable = 'C:\\Coding Projects\\MaSGE\\x64\\Release\\MaSGE.exe' sys.base_prefix = 'C:\\Coding Projects\\MaSGE' sys.base_exec_prefix = 'C:\\Coding Projects\\MaSGE' sys.platlibdir = 'DLLs' sys.executable = 'C:\\Coding Projects\\MaSGE\\x64\\Release\\MaSGE.exe' sys.prefix = 'C:\\Coding Projects\\MaSGE' sys.exec_prefix = 'C:\\Coding Projects\\MaSGE' sys.path = [ 'C:\\Coding Projects\\MaSGE\\python311.zip', 'C:\\Coding Projects\\MaSGE\\Lib', 'C:\\Coding Projects\\MaSGE\\DLLs', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x0000399c (most recent call first): <no Python frame> Of particular interest to me are the first two lines, plus the "PYTHONHOME = (not set)" and "PYTHONPATH = (not set)" on lines 4 and 5 which, to my knowledge, are Environmental Variables. This brings me to the crux of the problem: Is there some way in which I can install a portable Python interpreter to a specific folder to circumvent the issue with Environmental Variables? A: To embed python into your application, you need two things: Initialize isolated python This will not let user's system interfere with your app. https://docs.python.org/3/c-api/init_config.html#init-isolated-conf Deploy python stuff with your application On windows, you need: Python DLL (python311.dll). Python standard library. Either copy Lib folder from python installation, or zip its contents and name it after python dll (e.g. python311.zip), or use the same zip from Windows embeddable package) Python modules (DLLs directory) On linux, situation is slightly different: Python shared library (libpython311.so) Python standard library (Either copy lib/python311/ folder from python installation, or zip its contents except lib-dynload folder and name it lib/python311.zip) (If using zipped standard library) Copy lib-dynload to lib/python3.11/lib-dynload Of course, you have to replace 311 and 3.11 with your version of python.
Shipping Python interpreter with C++ project
Problem description: I have a Visual Studio 2022 C++ project that involves live python script interpretation. Naturally, I need a valid Python installation to do this. However, I intend to ship this as an application, so I'd like to have a localized Python installation, to avoid consumer-side installation, but that doesn't interfere with Windows' Environmental Variables. What I've done: I included "Python.h" from my Python installation's "include" folder, I've added its "libs" folder to "Additional Library Directories", I've added "python311.lib" to "Additional Dependencies", and I remembered to copy Python311.dll to my project's Solution Directory. Everything is linked properly. However, when I run compile and execute my program, I receive a long list of errors, which are as follows: Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = 'C:\Coding Projects\MaSGE\Lib' sys._base_executable = 'C:\\Coding Projects\\MaSGE\\x64\\Release\\MaSGE.exe' sys.base_prefix = 'C:\\Coding Projects\\MaSGE' sys.base_exec_prefix = 'C:\\Coding Projects\\MaSGE' sys.platlibdir = 'DLLs' sys.executable = 'C:\\Coding Projects\\MaSGE\\x64\\Release\\MaSGE.exe' sys.prefix = 'C:\\Coding Projects\\MaSGE' sys.exec_prefix = 'C:\\Coding Projects\\MaSGE' sys.path = [ 'C:\\Coding Projects\\MaSGE\\python311.zip', 'C:\\Coding Projects\\MaSGE\\Lib', 'C:\\Coding Projects\\MaSGE\\DLLs', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x0000399c (most recent call first): <no Python frame> Of particular interest to me are the first two lines, plus the "PYTHONHOME = (not set)" and "PYTHONPATH = (not set)" on lines 4 and 5 which, to my knowledge, are Environmental Variables. This brings me to the crux of the problem: Is there some way in which I can install a portable Python interpreter to a specific folder to circumvent the issue with Environmental Variables?
[ "To embed python into your application, you need two things:\nInitialize isolated python\nThis will not let user's system interfere with your app.\nhttps://docs.python.org/3/c-api/init_config.html#init-isolated-conf\nDeploy python stuff with your application\nOn windows, you need:\n\nPython DLL (python311.dll).\nPython standard library.\nEither copy Lib folder from python installation, or zip its contents and name it after python dll (e.g. python311.zip), or use the same zip from Windows embeddable package)\nPython modules (DLLs directory)\n\nOn linux, situation is slightly different:\n\nPython shared library (libpython311.so)\nPython standard library (Either copy lib/python311/ folder from python installation, or zip its contents except lib-dynload folder and name it lib/python311.zip)\n(If using zipped standard library) Copy lib-dynload to lib/python3.11/lib-dynload\n\nOf course, you have to replace 311 and 3.11 with your version of python.\n" ]
[ 1 ]
[]
[]
[ "c++", "python", "python_install", "visual_studio_2022" ]
stackoverflow_0074590755_c++_python_python_install_visual_studio_2022.txt
Q: AttributeError: 'Player' object has no attribute 'pos' I'm following a tutorial on youtube on how to make a doom type game in python. And I'm at a point where finished Raycasting and implementing 3D environment. But when I wanted to test the progress an attribute error occurred. Here is the terminals response: File "d:\School Documents\SMGS\PDM\PyDom\raycasting.py", line 10, in ray_cast ox, oy = self.game.player.pos AttributeError: 'Player' object has no attribute 'pos' Here is the code from player.py file: from settings import * import pygame as pg import math class Player: def __init__(self, game): self.game = game self.x, self.y = PLAYER_POS self.angle = PLAYER_ANGLE def movement(self): sin_a = math.sin(self.angle) cos_a = math.cos(self.angle) dx, dy = 0, 0 speed = PLAYER_SPEED * self.game.delta_time speed_sin = speed * sin_a speed_cos = speed * cos_a keys = pg.key.get_pressed() if keys[pg.K_w]: dx += speed_cos dy += speed_sin if keys[pg.K_s]: dx += -speed_cos dy += -speed_sin if keys[pg.K_a]: dx += speed_sin dy += -speed_cos if keys[pg.K_d]: dx += -speed_sin dy += speed_cos self.check_wall_collision(dx, dy) if keys[pg.K_LEFT]: self.angle -= PLAYER_ROT_SPEED * self.game.delta_time if keys[pg.K_RIGHT]: self.angle += PLAYER_ROT_SPEED * self.game.delta_time self.angle %= math.tau def check_wall(self, x, y): return (x, y) not in self.game.map.world_map def check_wall_collision(self, dx, dy): if self.check_wall(int(self.x + dx), int(self.y)): self.x += dx if self.check_wall(int(self.x), int(self.y + dy)): self.y += dy def draw(self): # pg.draw.line(self.game.screen, 'yellow', (self.x * 100, self.y * 100), (self.x * 100 + WIDTH * math.cos(self.angle), self.y * 100 + WIDTH * math.sin(self.angle)), 2) pg.draw.circle(self.game.screen, 'green', (self.x * 100, self.y * 100), 15) def update(self): self.movement() @property def pos(self): return self.x, self.y @property def map_pos(self): return int(self.x), int(self.y) Here is the code from raycasting.py file: import pygame as pg import math from settings import * class RayCasting: def __init__(self, game): self.game = game def ray_cast(self): ox, oy = self.game.player.pos x_map, y_map = self.game.player.map_pos ray_angle = self.game.player.angle - HALF_FOV + 0.0001 for ray in range(NUM_RAYS): sin_a = math.sin(ray_angle) cos_a = math.cos(ray_angle) # horizontale y_hor, dy = (y_map + 1, 1) if sin_a > 0 else (y_map - 1e-6, -1) depth_hor = (y_hor - oy) / sin_a x_hor = ox + depth_hor * cos_a delta_depth = dy / sin_a dx = delta_depth * cos_a for i in range(MAX_DEPTH): tile_hor = int(x_hor), int(y_hor) if tile_hor in self.game.map.world_map: break x_hor += dx y_hor += dy depth_hor += delta_depth # vertikale x_vert, dx = (x_map + 1, 1) if cos_a > 0 else (x_map - 1e-6, -1) depth_vert = (x_vert - ox) / cos_a y_vert = oy + depth_vert * sin_a delta_depth = dx / cos_a dy = delta_depth * sin_a for i in range(MAX_DEPTH): tile_vert = int(x_vert), int(y_vert) if tile_vert in self.game.map.world_map: break x_vert += dx y_vert += dy depth_vert += delta_depth # globina if depth_vert < depth_hor: depth = depth_vert else: depth = depth_hor # projekcija proj_height = SCREEN_DIST / (depth + 0.0001) # izris sten pg.draw.rect(self.game.screen, 'white', (ray * SCALE, HALF_HEIGHT - proj_height // 2, SCALE, proj_height)) ray_angle += DELTA_ANGLE def update(self): self.ray_cast() Here is the main.py file code: import pygame as pg import sys from settings import * from map import * from player import * from raycasting import * class Game: def __init__(self): pg.init() self.screen = pg.display.set_mode(RES) self.clock = pg.time.Clock() self.delta_time = 1 self.new_game() def new_game(self): self.map = Map(self) self.player = Player(self) self.raycasting = RayCasting(self) def update(self): self.player.update() self.raycasting.update() pg.display.flip() self.delta_time = self.clock.tick(FPS) pg.display.set_caption(f'{self.clock.get_fps() :.1f}') def draw(self): self.screen.fill('black') #self.map.draw() #self.player.draw() def check_events(self): for event in pg.event.get(): if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): pg.quit() sys.exit() def run(self): while True: self.check_events() self.update() self.draw() if __name__ == '__main__': game = Game() game.run() I searched if someone had the same issue as I do, I found something on youtube and all of those "fixes" didn't work. So I'm hoping that you guys can help me. A: You need to indent the pos and map_pos properties, which are currently just dangling functions on the module - not a part of the Player class. class Player: @property def pos(self): return self.x, self.y @property def map_pos(self): return int(self.x), int(self.y) # ...
AttributeError: 'Player' object has no attribute 'pos'
I'm following a tutorial on youtube on how to make a doom type game in python. And I'm at a point where finished Raycasting and implementing 3D environment. But when I wanted to test the progress an attribute error occurred. Here is the terminals response: File "d:\School Documents\SMGS\PDM\PyDom\raycasting.py", line 10, in ray_cast ox, oy = self.game.player.pos AttributeError: 'Player' object has no attribute 'pos' Here is the code from player.py file: from settings import * import pygame as pg import math class Player: def __init__(self, game): self.game = game self.x, self.y = PLAYER_POS self.angle = PLAYER_ANGLE def movement(self): sin_a = math.sin(self.angle) cos_a = math.cos(self.angle) dx, dy = 0, 0 speed = PLAYER_SPEED * self.game.delta_time speed_sin = speed * sin_a speed_cos = speed * cos_a keys = pg.key.get_pressed() if keys[pg.K_w]: dx += speed_cos dy += speed_sin if keys[pg.K_s]: dx += -speed_cos dy += -speed_sin if keys[pg.K_a]: dx += speed_sin dy += -speed_cos if keys[pg.K_d]: dx += -speed_sin dy += speed_cos self.check_wall_collision(dx, dy) if keys[pg.K_LEFT]: self.angle -= PLAYER_ROT_SPEED * self.game.delta_time if keys[pg.K_RIGHT]: self.angle += PLAYER_ROT_SPEED * self.game.delta_time self.angle %= math.tau def check_wall(self, x, y): return (x, y) not in self.game.map.world_map def check_wall_collision(self, dx, dy): if self.check_wall(int(self.x + dx), int(self.y)): self.x += dx if self.check_wall(int(self.x), int(self.y + dy)): self.y += dy def draw(self): # pg.draw.line(self.game.screen, 'yellow', (self.x * 100, self.y * 100), (self.x * 100 + WIDTH * math.cos(self.angle), self.y * 100 + WIDTH * math.sin(self.angle)), 2) pg.draw.circle(self.game.screen, 'green', (self.x * 100, self.y * 100), 15) def update(self): self.movement() @property def pos(self): return self.x, self.y @property def map_pos(self): return int(self.x), int(self.y) Here is the code from raycasting.py file: import pygame as pg import math from settings import * class RayCasting: def __init__(self, game): self.game = game def ray_cast(self): ox, oy = self.game.player.pos x_map, y_map = self.game.player.map_pos ray_angle = self.game.player.angle - HALF_FOV + 0.0001 for ray in range(NUM_RAYS): sin_a = math.sin(ray_angle) cos_a = math.cos(ray_angle) # horizontale y_hor, dy = (y_map + 1, 1) if sin_a > 0 else (y_map - 1e-6, -1) depth_hor = (y_hor - oy) / sin_a x_hor = ox + depth_hor * cos_a delta_depth = dy / sin_a dx = delta_depth * cos_a for i in range(MAX_DEPTH): tile_hor = int(x_hor), int(y_hor) if tile_hor in self.game.map.world_map: break x_hor += dx y_hor += dy depth_hor += delta_depth # vertikale x_vert, dx = (x_map + 1, 1) if cos_a > 0 else (x_map - 1e-6, -1) depth_vert = (x_vert - ox) / cos_a y_vert = oy + depth_vert * sin_a delta_depth = dx / cos_a dy = delta_depth * sin_a for i in range(MAX_DEPTH): tile_vert = int(x_vert), int(y_vert) if tile_vert in self.game.map.world_map: break x_vert += dx y_vert += dy depth_vert += delta_depth # globina if depth_vert < depth_hor: depth = depth_vert else: depth = depth_hor # projekcija proj_height = SCREEN_DIST / (depth + 0.0001) # izris sten pg.draw.rect(self.game.screen, 'white', (ray * SCALE, HALF_HEIGHT - proj_height // 2, SCALE, proj_height)) ray_angle += DELTA_ANGLE def update(self): self.ray_cast() Here is the main.py file code: import pygame as pg import sys from settings import * from map import * from player import * from raycasting import * class Game: def __init__(self): pg.init() self.screen = pg.display.set_mode(RES) self.clock = pg.time.Clock() self.delta_time = 1 self.new_game() def new_game(self): self.map = Map(self) self.player = Player(self) self.raycasting = RayCasting(self) def update(self): self.player.update() self.raycasting.update() pg.display.flip() self.delta_time = self.clock.tick(FPS) pg.display.set_caption(f'{self.clock.get_fps() :.1f}') def draw(self): self.screen.fill('black') #self.map.draw() #self.player.draw() def check_events(self): for event in pg.event.get(): if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): pg.quit() sys.exit() def run(self): while True: self.check_events() self.update() self.draw() if __name__ == '__main__': game = Game() game.run() I searched if someone had the same issue as I do, I found something on youtube and all of those "fixes" didn't work. So I'm hoping that you guys can help me.
[ "You need to indent the pos and map_pos properties, which are currently just dangling functions on the module - not a part of the Player class.\nclass Player:\n @property\n def pos(self):\n return self.x, self.y\n\n @property\n def map_pos(self):\n return int(self.x), int(self.y)\n \n # ...\n\n\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "python" ]
stackoverflow_0074591155_attributeerror_python.txt
Q: Checking if certain phrases are on a website with python I've written a function that is ment to check if a phrase is in a certain website, however, it is always telling me that it isn't in the website even when it is. I'm relativly new to webscraping so any help would be appreciated. def check_availability(url,phrase): global log try: # page = urllib.request.urlopen(url) r = requests.get(url) soup = BeautifulSoup(url, 'html.parser') if phrase in soup.text: return False return True except: log += "Error parsing website " this always returned true for some reason please help. A: Modified function: import requests from bs4 import BeautifulSoup def url_contains(url, phrase): soup = BeautifulSoup(requests.get(url).content, 'html.parser') return phrase in soup.get_text() Example: url = 'https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss' >>> url_contains(url, 'Princeps mathematicorum') True >>> url_contains(url, 'foo bar') False Slightly optimized: import requests from bs4 import BeautifulSoup from functools import lru_cache @lru_cache(maxsize=4) def get_soup(url): return BeautifulSoup(requests.get(url).content, 'html.parser') def url_contains(url, phrase): return phrase in get_soup(url).get_text() This caches the soup obtained from a url, so you can repeatedly query many phrases for a given url. For the above: the first query takes ~1/3s; subsequent queries against that URL take ~4ms.
Checking if certain phrases are on a website with python
I've written a function that is ment to check if a phrase is in a certain website, however, it is always telling me that it isn't in the website even when it is. I'm relativly new to webscraping so any help would be appreciated. def check_availability(url,phrase): global log try: # page = urllib.request.urlopen(url) r = requests.get(url) soup = BeautifulSoup(url, 'html.parser') if phrase in soup.text: return False return True except: log += "Error parsing website " this always returned true for some reason please help.
[ "Modified function:\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef url_contains(url, phrase):\n soup = BeautifulSoup(requests.get(url).content, 'html.parser')\n return phrase in soup.get_text()\n\nExample:\nurl = 'https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss'\n\n>>> url_contains(url, 'Princeps mathematicorum')\nTrue\n\n>>> url_contains(url, 'foo bar')\nFalse\n\nSlightly optimized:\nimport requests\nfrom bs4 import BeautifulSoup\nfrom functools import lru_cache\n\n@lru_cache(maxsize=4)\ndef get_soup(url):\n return BeautifulSoup(requests.get(url).content, 'html.parser')\n\ndef url_contains(url, phrase):\n return phrase in get_soup(url).get_text()\n\nThis caches the soup obtained from a url, so you can repeatedly query many phrases for a given url. For the above: the first query takes ~1/3s; subsequent queries against that URL take ~4ms.\n" ]
[ 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074590288_python_web_scraping.txt
Q: if-else statement not working correctly in python for loop I have a block of code that I am iterating through a dictionary looking for keywords found and the number of times each is found. The if statement works and returns the expected output if keywords are found. However, the else statement is not working when no keywords are found it should return "No keywords found". This seems simple enough but I just can't put my finger on why this is not working. I'm fairly new to coding, so I apologize if this seems extremely basic. Here is the code block I'm using: with open(keyword_file_path, 'r') as file: data = file.read() kw_found = {} for keyword in keywords: found = re.findall(keyword, data, re.I) if found: kw_found[keyword] = len(found) for key in kw_found.keys(): if key in kw_found.keys(): width = max(len(x) for x in key) output_fp.write("{0:<{1}} : {2}\n".format(key, width, kw_found[key])) else: output_fp.write("No Keywords Found\n") The if statement works and we get the following output if it does find the predefined keywords: dog : 5 cat : 2 bird : 100 What should happen when it does not find the keywords is return "No Keywords Found"; however, it just doesn't return anything. No errors are reported, so it seems it just never sees the else statement as True if I'm understanding it correctly. Any advice to get this to work would be greatly appreciated! Thank you in advanced! A: for key in kw_found.keys(): The above line will go through each element of kw_found.keys(), binding them to key. if key in kw_found.keys(): This asks if the thing we're looking at from kw_found.keys() is in kw_found.keys() - which, yes, it is. width = max(len(x) for x in key) output_fp.write("{0:<{1}} : {2}\n".format(key, width, kw_found[key])) This next line will never fire. If kw_found.keys() is empty, the block it's in will never fire. else: output_fp.write("No Keywords Found\n") Basically, you're mixing a list traversal where you inspect each element individually, with list comprehensions that deal with the entire list. You almost always want to use one or the other. Also, if you want to see if something is true anywhere in a list, you don't want an if/else block in your loop - that will evaluate the true branch correctly, but it will evaluate the false branch on each element that doesn't match the condition (even if it's matched elsewhere.) It's confusing "nowhere" with "not here". A: The observed behavior is correct. In your code, you are iterating over all detected keywords, which are stored in kw_found. And then you are checking if the current keyword is part of the dictionary you are iterating through. And this is always true. A: I'm new to this, but I think your for loop should be iterating through keywords, not kw_found. If it only looks at the keys that have been found, the if statement will always be right, and the else statement will never execute. Here's the working code: with open(keyword_file_path, 'r') as file: data = file.read() kw_found = {} for keyword in keywords: found = re.findall(keyword, data, re.I) if found: kw_found[keyword] = len(found) for key in keywords.keys(): if key in kw_found.keys(): width = max(len(x) for x in key) output_fp.write("{0:<{1}} : {2}\n".format(key, width, kw_found[key])) else: output_fp.write("No Keywords Found\n") A: It seems like that else statement is in the wrong loop: with open(keyword_file_path, 'r') as file: data = file.read() kw_found = {} for keyword in keywords: found = re.findall(keyword, data, re.I) if found: kw_found[keyword] = len(found) else: output_fp.write("No Keywords Found\n") for key in kw_found.keys(): if key in kw_found.keys(): width = max(len(x) for x in key) output_fp.write("{0:<{1}} : {2}\n".format(key, width, kw_found[key])) A: After playing with this for a while, I finally got the else statement to trigger when the kw_found dictionary is empty. Now I get the expected output for the else statement when no keywords are found in the file. I appreciate everyone's feedback and suggestions. with open(keyword_file_path, 'r') as file: data = file.read() kw_found = {} for keyword in keywords: found = re.findall(keyword, data, re.I) if found: kw_found[keyword] = len(found) if kw_found: for key in kw_found.keys(): if key in kw_found.keys(): width = max(len(x) for x in key) output_fp.write("{0:<{1}} : {2}\n".format(key, width, kw_found[key])) else: output_fp.write("No Keyword Found \n")
if-else statement not working correctly in python for loop
I have a block of code that I am iterating through a dictionary looking for keywords found and the number of times each is found. The if statement works and returns the expected output if keywords are found. However, the else statement is not working when no keywords are found it should return "No keywords found". This seems simple enough but I just can't put my finger on why this is not working. I'm fairly new to coding, so I apologize if this seems extremely basic. Here is the code block I'm using: with open(keyword_file_path, 'r') as file: data = file.read() kw_found = {} for keyword in keywords: found = re.findall(keyword, data, re.I) if found: kw_found[keyword] = len(found) for key in kw_found.keys(): if key in kw_found.keys(): width = max(len(x) for x in key) output_fp.write("{0:<{1}} : {2}\n".format(key, width, kw_found[key])) else: output_fp.write("No Keywords Found\n") The if statement works and we get the following output if it does find the predefined keywords: dog : 5 cat : 2 bird : 100 What should happen when it does not find the keywords is return "No Keywords Found"; however, it just doesn't return anything. No errors are reported, so it seems it just never sees the else statement as True if I'm understanding it correctly. Any advice to get this to work would be greatly appreciated! Thank you in advanced!
[ " for key in kw_found.keys():\n\nThe above line will go through each element of kw_found.keys(), binding them to key.\n if key in kw_found.keys():\n\nThis asks if the thing we're looking at from kw_found.keys() is in kw_found.keys() - which, yes, it is.\n width = max(len(x) for x in key)\n output_fp.write(\"{0:<{1}} : {2}\\n\".format(key, width, kw_found[key]))\n\nThis next line will never fire. If kw_found.keys() is empty, the block it's in will never fire.\n else:\n output_fp.write(\"No Keywords Found\\n\")\n\nBasically, you're mixing a list traversal where you inspect each element individually, with list comprehensions that deal with the entire list. You almost always want to use one or the other. Also, if you want to see if something is true anywhere in a list, you don't want an if/else block in your loop - that will evaluate the true branch correctly, but it will evaluate the false branch on each element that doesn't match the condition (even if it's matched elsewhere.) It's confusing \"nowhere\" with \"not here\".\n", "The observed behavior is correct. In your code, you are iterating over all detected keywords, which are stored in kw_found. And then you are checking if the current keyword is part of the dictionary you are iterating through. And this is always true.\n", "I'm new to this, but I think your for loop should be iterating through keywords, not kw_found. If it only looks at the keys that have been found, the if statement will always be right, and the else statement will never execute.\nHere's the working code:\nwith open(keyword_file_path, 'r') as file:\n data = file.read()\n\nkw_found = {}\nfor keyword in keywords:\n found = re.findall(keyword, data, re.I)\n if found:\n kw_found[keyword] = len(found)\n\nfor key in keywords.keys():\n if key in kw_found.keys():\n width = max(len(x) for x in key)\n output_fp.write(\"{0:<{1}} : {2}\\n\".format(key, width, kw_found[key]))\n else:\n output_fp.write(\"No Keywords Found\\n\")\n\n", "It seems like that else statement is in the wrong loop:\nwith open(keyword_file_path, 'r') as file:\n data = file.read()\n\nkw_found = {}\nfor keyword in keywords:\n found = re.findall(keyword, data, re.I)\n if found:\n kw_found[keyword] = len(found)\n else:\n output_fp.write(\"No Keywords Found\\n\")\n\nfor key in kw_found.keys():\n if key in kw_found.keys():\n width = max(len(x) for x in key)\n output_fp.write(\"{0:<{1}} : {2}\\n\".format(key, width, kw_found[key]))\n\n", "After playing with this for a while, I finally got the else statement to trigger when the kw_found dictionary is empty. Now I get the expected output for the else statement when no keywords are found in the file. I appreciate everyone's feedback and suggestions.\nwith open(keyword_file_path, 'r') as file:\n data = file.read()\n\nkw_found = {}\nfor keyword in keywords:\n found = re.findall(keyword, data, re.I)\n if found:\n kw_found[keyword] = len(found)\n\nif kw_found:\n for key in kw_found.keys():\n if key in kw_found.keys():\n width = max(len(x) for x in key)\n output_fp.write(\"{0:<{1}} : {2}\\n\".format(key, width, kw_found[key]))\nelse:\n output_fp.write(\"No Keyword Found \\n\")\n\n" ]
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "if_statement", "python" ]
stackoverflow_0074553450_dictionary_if_statement_python.txt
Q: Python function for taking formatted input from user similar to scanf() in 'C' I was wondering if there is a function in Python to take formatted input from user similar to taking the input from user in 'C' using scanf() and format strings such as %d, %lf, etc. Hypothetical example in which scanf() returns a list: input_date_list = scanf("%d-%d-%d") # User enters "1969-04-20" input_time_list = scanf("%d:%d") # User enters "04:20" print(input_date_list, input_time_list) # Output is "[1969, 4, 20] [4, 20]" A: What the Standard Library provides There is no direct scanf(3) equivalent in the standard library. The documentation for the re module suggests itself as a replacement, providing this explanation: Python does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though also more verbose, than scanf() format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions. Modifying your hypothetical example, to work with regular expressions, we get... import re input_date_list = re.match(r"(?P<month>[-+]?\d+)-(?P<day>[-+]?\d+)-(?P<year>[-+]?\d+)", input()) print(f"[{input_date_list['year']}, {input_date_list['month']}, {input_date_list['day']}]") input_time_list = re.match(r"(?P<hour>[-+]?\d+):(?P<minute>[-+]?\d+)", input()) print(f"[{input_time_list['hour']}, {input_time_list['minute']}]") ...and when executed: python script.py << EOF 1-2-2023 11:59 EOF [2023, 1, 2] [11, 59] Community Implementation The scanf module on Pypi provides an interface much more akin to scanf(3). This provides a direct implementation of your hypothetical examples: from scanf import scanf input_date_list = scanf("%d-%d-%d") input_time_list = scanf("%d:%d") print(input_date_list, input_time_list) ...and when executed: python script.py << EOF 1-2-2023 11:59 EOF (1, 2, 2023) (11, 59) A: input(). For example this could be used as: Name = input("Please enter your name?") For use in Python 2, this would be raw_input(). For example this could be used as: Name = raw_input("Please enter your name?") A: There is no (built-in) direct and easy way to specify the input's format in Python. The input function in Python 3 (raw_input in Python 2) will simply return the string that was typed to STDIN. Any parsing will be done manually on the string. The input function in Python 2 (eval(input()) in Python 3, which is not recommended) did a very basic built-in parsing and would work for only a single element (i.e. equivalent to scanf("%d") for instance). With some basic parsing you can get to not-so-complicated code that emulates scanf: # scanf("%d-%d-%d") input_date_list = [int(x) for x in input().split('-')] # scanf("%d:%d") input_time_list = [int(x) for x in input().split(':')] For anything more complicated, more lines of code are needed. For example: # scanf("%d,%f - %s") nums, s = input().split(' - ') i, f = nums.split(',') i = int(i) f = float(f)
Python function for taking formatted input from user similar to scanf() in 'C'
I was wondering if there is a function in Python to take formatted input from user similar to taking the input from user in 'C' using scanf() and format strings such as %d, %lf, etc. Hypothetical example in which scanf() returns a list: input_date_list = scanf("%d-%d-%d") # User enters "1969-04-20" input_time_list = scanf("%d:%d") # User enters "04:20" print(input_date_list, input_time_list) # Output is "[1969, 4, 20] [4, 20]"
[ "What the Standard Library provides\nThere is no direct scanf(3) equivalent in the standard library. The documentation for the re module suggests itself as a replacement, providing this explanation:\n\nPython does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though also more verbose, than scanf() format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions.\n\nModifying your hypothetical example, to work with regular expressions, we get...\nimport re\n\ninput_date_list = re.match(r\"(?P<month>[-+]?\\d+)-(?P<day>[-+]?\\d+)-(?P<year>[-+]?\\d+)\", input())\nprint(f\"[{input_date_list['year']}, {input_date_list['month']}, {input_date_list['day']}]\")\n\ninput_time_list = re.match(r\"(?P<hour>[-+]?\\d+):(?P<minute>[-+]?\\d+)\", input())\nprint(f\"[{input_time_list['hour']}, {input_time_list['minute']}]\")\n\n...and when executed:\npython script.py << EOF\n1-2-2023\n11:59\nEOF\n[2023, 1, 2]\n[11, 59]\n\n\nCommunity Implementation\nThe scanf module on Pypi provides an interface much more akin to scanf(3).\nThis provides a direct implementation of your hypothetical examples:\nfrom scanf import scanf\n\ninput_date_list = scanf(\"%d-%d-%d\")\ninput_time_list = scanf(\"%d:%d\")\n\nprint(input_date_list, input_time_list)\n\n...and when executed:\npython script.py << EOF\n1-2-2023\n11:59\nEOF\n(1, 2, 2023) (11, 59)\n\n", "input(). For example this could be used as:\nName = input(\"Please enter your name?\")\n\nFor use in Python 2, this would be raw_input(). For example this could be used as:\nName = raw_input(\"Please enter your name?\")\n\n", "There is no (built-in) direct and easy way to specify the input's format in Python.\nThe input function in Python 3 (raw_input in Python 2) will simply return the string that was typed to STDIN. Any parsing will be done manually on the string.\nThe input function in Python 2 (eval(input()) in Python 3, which is not recommended) did a very basic built-in parsing and would work for only a single element (i.e. equivalent to scanf(\"%d\") for instance).\nWith some basic parsing you can get to not-so-complicated code that emulates scanf:\n# scanf(\"%d-%d-%d\")\ninput_date_list = [int(x) for x in input().split('-')]\n\n# scanf(\"%d:%d\")\ninput_time_list = [int(x) for x in input().split(':')]\n\nFor anything more complicated, more lines of code are needed. For example:\n# scanf(\"%d,%f - %s\")\nnums, s = input().split(' - ')\ni, f = nums.split(',')\ni = int(i)\nf = float(f)\n\n" ]
[ 2, 1, 1 ]
[ "in Python 2, you can use input() or raw_input()\ns = input() // gets int value \n\nk = raw_input() // gets string value\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0041725535_python.txt
Q: How to concatenate multiple json as dict in pandas? I have two json files that I would like to concatenate into one. Is there any approach to combine these json? json1 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05 }, "105911": { "name": "Avatar - Yotian Frontliner", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05 } } json2 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.0007 }, "105911": { "name": "Avatar - Yotian Frontliner", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.0007 } } import pandas as pd from glob import glob arquivos = sorted(glob('price-history\*.json')) todos_dados = pd.concat((pd.read_json(cont, lines=True, orient='records') for cont in arquivos)) print(todos_dados) the error that is returning is ValueError: Expected object or value The expected output would be a dataframe to be able to filter data. A: Try: import pandas as pd json1 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05, }, "105911": { "name": "Avatar - Yotian Frontliner", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05, }, } json2 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.0007, }, "105911": { "name": "Avatar - Yotian Frontliner", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.0007, }, } jsons = json1, json2 df = pd.DataFrame( [v for j in jsons for v in j.values()], index=[k for j in jsons for k in j] ) print(df) Prints: name cardset rarity foil price 105912 Avatar - Tocasia, Dig Site Mentor VAN Rare 0 0.0500 105911 Avatar - Yotian Frontliner VAN Rare 0 0.0500 105912 Avatar - Tocasia, Dig Site Mentor VAN Rare 0 0.0007 105911 Avatar - Yotian Frontliner VAN Rare 0 0.0007 A: import pandas as pd json1 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05 }, "105911": { "name": "Avatar - Yotian Frontliner", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05 } } json2 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.0007 }, "105911": { "name": "Avatar - Yotian Frontliner", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.0007 } } list_jsons = [json1,json2] todos_dados = pd.concat(([pd.DataFrame.from_dict(json_obj,orient='index') for json_obj in list_jsons])) todos_dados
How to concatenate multiple json as dict in pandas?
I have two json files that I would like to concatenate into one. Is there any approach to combine these json? json1 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05 }, "105911": { "name": "Avatar - Yotian Frontliner", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.05 } } json2 = { "105912": { "name": "Avatar - Tocasia, Dig Site Mentor", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.0007 }, "105911": { "name": "Avatar - Yotian Frontliner", "cardset": "VAN", "rarity": "Rare", "foil": 0, "price": 0.0007 } } import pandas as pd from glob import glob arquivos = sorted(glob('price-history\*.json')) todos_dados = pd.concat((pd.read_json(cont, lines=True, orient='records') for cont in arquivos)) print(todos_dados) the error that is returning is ValueError: Expected object or value The expected output would be a dataframe to be able to filter data.
[ "Try:\nimport pandas as pd\n\njson1 = {\n \"105912\": {\n \"name\": \"Avatar - Tocasia, Dig Site Mentor\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.05,\n },\n \"105911\": {\n \"name\": \"Avatar - Yotian Frontliner\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.05,\n },\n}\n\njson2 = {\n \"105912\": {\n \"name\": \"Avatar - Tocasia, Dig Site Mentor\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.0007,\n },\n \"105911\": {\n \"name\": \"Avatar - Yotian Frontliner\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.0007,\n },\n}\n\njsons = json1, json2\n\ndf = pd.DataFrame(\n [v for j in jsons for v in j.values()], index=[k for j in jsons for k in j]\n)\nprint(df)\n\nPrints:\n name cardset rarity foil price\n105912 Avatar - Tocasia, Dig Site Mentor VAN Rare 0 0.0500\n105911 Avatar - Yotian Frontliner VAN Rare 0 0.0500\n105912 Avatar - Tocasia, Dig Site Mentor VAN Rare 0 0.0007\n105911 Avatar - Yotian Frontliner VAN Rare 0 0.0007\n\n", "import pandas as pd\n\njson1 = {\n \"105912\": {\n \"name\": \"Avatar - Tocasia, Dig Site Mentor\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.05\n },\n \"105911\": {\n \"name\": \"Avatar - Yotian Frontliner\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.05\n }\n}\n\njson2 = {\n \"105912\": {\n \"name\": \"Avatar - Tocasia, Dig Site Mentor\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.0007\n },\n \"105911\": {\n \"name\": \"Avatar - Yotian Frontliner\",\n \"cardset\": \"VAN\",\n \"rarity\": \"Rare\",\n \"foil\": 0,\n \"price\": 0.0007\n }\n}\n\nlist_jsons = [json1,json2]\ntodos_dados = pd.concat(([pd.DataFrame.from_dict(json_obj,orient='index') for json_obj in list_jsons]))\n\ntodos_dados\n\n" ]
[ 2, 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074590923_json_pandas_python.txt
Q: Changing the value of values after a particular index along one axis in a 3D numpy array I have a 3d array of format given below. The below is the one sample of the 3D array, like it , it contain more than 1000. sample shape of the 3D array is (1000 x 10 x 5) The image contain one element (10 x 5) I want to change the value to 0 after the 3rd one on the last value check the figure below desired I want to change like it for all the 1000 elements in my array. Is there a better way to do it other than using "for loop" ? A: import numpy as np # Your array here: arr = np.arange(50000).reshape(1000, 10, 5) # Solution: arr[:, 3:, -1] = 0
Changing the value of values after a particular index along one axis in a 3D numpy array
I have a 3d array of format given below. The below is the one sample of the 3D array, like it , it contain more than 1000. sample shape of the 3D array is (1000 x 10 x 5) The image contain one element (10 x 5) I want to change the value to 0 after the 3rd one on the last value check the figure below desired I want to change like it for all the 1000 elements in my array. Is there a better way to do it other than using "for loop" ?
[ "import numpy as np\n\n# Your array here:\narr = np.arange(50000).reshape(1000, 10, 5)\n\n# Solution:\narr[:, 3:, -1] = 0\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "multidimensional_array", "numpy", "python", "vectorization" ]
stackoverflow_0074591237_dataframe_multidimensional_array_numpy_python_vectorization.txt
Q: Numpy Sort 3D Array of Coordinates I got a 3D array of rects' coordinates from CRAFT text detector that looks like this. arr = np.array( [ [ [13.715625, 149.62498], [68.99374, 149.62498], [68.99374, 162.50937], [13.715625, 162.50937], ], [ [22.44375, 96.84062], [64.8375, 96.84062], [64.8375, 111.80312], [22.44375, 111.80312], ], [ [76.890625, 96.84062], [120.53125, 96.84062], [120.53125, 111.80312], [76.890625, 111.80312], ], [ [83.54063, 122.609375], [102.24375, 122.609375], [102.24375, 135.49374], [83.54063, 135.49374], ], [ [99.75, 124.6875], [150.04062, 124.6875], [150.04062, 137.57187], [99.75, 137.57187], ], [[133.0, 96.425], [176.225, 96.425], [176.225, 111.80312], [133.0, 111.80312]], [ [189.3869, 97.28999], [232.66872, 96.73509], [232.85771, 111.47669], [189.57588, 112.03161], ], [ [201.99374, 150.04062], [254.77812, 150.04062], [254.77812, 158.76874], [201.99374, 158.76874], ], [ [208.64375, 8.728125], [248.95938, 8.728125], [248.95938, 21.6125], [208.64375, 21.6125], ], [ [209.05937, 23.275], [254.3625, 23.275], [254.3625, 35.74375], [209.05937, 35.74375], ], [ [218.86273, 71.343155], [253.87411, 70.50955], [254.11385, 80.5778], [219.10246, 81.41141], ], ], ) Those are actually some parts of the texts detected by CRAFT after being sorted with this code: boxes = prediction["boxes"] idx = np.lexsort((boxes[:, 3][:, 1], boxes[:, 3][:, 0])) sorted_pred = { "boxes": prediction["boxes"][idx], "boxes_as_ratio": prediction["boxes_as_ratios"][idx], "polys": prediction["polys"][idx], "polys_as_ratio": prediction["polys_as_ratios"][idx] } If we take a look at this credit card below: The problem is that the text Adrian W. is placed first since it is the leftmost text on the card. How can we use Numpy sort such that the order of the detected text would be: HSBC.., world, the card number from left to right 5183, 2301, 1234, 5678, valid date, Adrian W. which means that we sort the texts by using the y coordinate of the top-left point of each rect's and only sort by x if there are same y coordinates? A: which means that we sort the texts by using the y coordinate of the top-left point of each rect's and only sort by x if there are same y coordinates? Wouldn't the following give you the desired result? arr = sorted(arr, key=lambda x: (x[0][1], x[0][0])) Then you can add arr = np.array(arr) to get a numpy array.
Numpy Sort 3D Array of Coordinates
I got a 3D array of rects' coordinates from CRAFT text detector that looks like this. arr = np.array( [ [ [13.715625, 149.62498], [68.99374, 149.62498], [68.99374, 162.50937], [13.715625, 162.50937], ], [ [22.44375, 96.84062], [64.8375, 96.84062], [64.8375, 111.80312], [22.44375, 111.80312], ], [ [76.890625, 96.84062], [120.53125, 96.84062], [120.53125, 111.80312], [76.890625, 111.80312], ], [ [83.54063, 122.609375], [102.24375, 122.609375], [102.24375, 135.49374], [83.54063, 135.49374], ], [ [99.75, 124.6875], [150.04062, 124.6875], [150.04062, 137.57187], [99.75, 137.57187], ], [[133.0, 96.425], [176.225, 96.425], [176.225, 111.80312], [133.0, 111.80312]], [ [189.3869, 97.28999], [232.66872, 96.73509], [232.85771, 111.47669], [189.57588, 112.03161], ], [ [201.99374, 150.04062], [254.77812, 150.04062], [254.77812, 158.76874], [201.99374, 158.76874], ], [ [208.64375, 8.728125], [248.95938, 8.728125], [248.95938, 21.6125], [208.64375, 21.6125], ], [ [209.05937, 23.275], [254.3625, 23.275], [254.3625, 35.74375], [209.05937, 35.74375], ], [ [218.86273, 71.343155], [253.87411, 70.50955], [254.11385, 80.5778], [219.10246, 81.41141], ], ], ) Those are actually some parts of the texts detected by CRAFT after being sorted with this code: boxes = prediction["boxes"] idx = np.lexsort((boxes[:, 3][:, 1], boxes[:, 3][:, 0])) sorted_pred = { "boxes": prediction["boxes"][idx], "boxes_as_ratio": prediction["boxes_as_ratios"][idx], "polys": prediction["polys"][idx], "polys_as_ratio": prediction["polys_as_ratios"][idx] } If we take a look at this credit card below: The problem is that the text Adrian W. is placed first since it is the leftmost text on the card. How can we use Numpy sort such that the order of the detected text would be: HSBC.., world, the card number from left to right 5183, 2301, 1234, 5678, valid date, Adrian W. which means that we sort the texts by using the y coordinate of the top-left point of each rect's and only sort by x if there are same y coordinates?
[ "\nwhich means that we sort the texts by using the y coordinate of the\ntop-left point of each rect's and only sort by x if there are same y\ncoordinates?\n\nWouldn't the following give you the desired result?\n arr = sorted(arr, key=lambda x: (x[0][1], x[0][0]))\n\nThen you can add arr = np.array(arr) to get a numpy array.\n" ]
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074591019_numpy_python.txt
Q: Extracting from List What I have coded students = ['Rose', 'Dorothy', 'Sophia', 'Blanch'] for i in range(len(students)): print('Hey',students[i],',please input the folowing grades:') weightAvg = [] discussionGrade = int(input('What was your discussion grade?: ')) # prompt grade 1 quizGrade = int(input('What was your quiz grade?: ')) # prompt grade 2 programGrade = int(input('What was your programming assignment grade?: ')) #prompt grade 3 weightAvg.append (discussionGrade*0.20 + quizGrade*0.30 + programGrade*0.50) #calculate weighted average print('Your weighted grade point average is: ',weightAvg, '\n')` The Output so far Hey Rose ,please input the folowing grades: What was your discussion grade?: 78 What was your quiz grade?: 88 What was your programming assignment grade?: 98 Your weighted grade point average is: [91.0] Hey Dorothy ,please input the folowing grades: What was your discussion grade?: 45 What was your quiz grade?: 99 What was your programming assignment grade?: 87 Your weighted grade point average is: [82.2] Hey Sophia ,please input the folowing grades: What was your discussion grade?: 67 What was your quiz grade?: 95 What was your programming assignment grade?: 77 Your weighted grade point average is: [80.4] Hey Blanch ,please input the folowing grades: What was your discussion grade?: 7 What was your quiz grade?: 45 What was your programming assignment grade?: 99 Your weighted grade point average is: [64.4] My Question Essentially I want this output print("The best student is (student name) with a score of (highest average)") I have placed my first block in a function and tried to return weightAvg but im still not outputing what I would like. Any help and explanation would be fantastic! Thank you! A: You need to store the averages outside the loop, to be able to have all of them once ended Put the pairs (avg, student) in the loop, and at the end use max function, as we put the average value in the tuple, the items will be compared by that, if we had add (student, avg), we would have had the max in term of lexicographical order (the nearest from end of alphabet weightAvg = [] for student in students: print('Hey', student, ',please input the folowing grades:') discussionGrade = int(input('What was your discussion grade?: ')) quizGrade = int(input('What was your quiz grade?: ')) programGrade = int(input('What was your programming assignment grade?: ')) avg = discussionGrade * 0.20 + quizGrade * 0.30 + programGrade * 0.50 weightAvg.append((avg, student)) # calculate weighted average print('Your weighted grade point average is: ', avg, '\n') best_avg, best_student = max(weightAvg) print(f"The best student is {best_student} with a score of {best_avg}")
Extracting from List
What I have coded students = ['Rose', 'Dorothy', 'Sophia', 'Blanch'] for i in range(len(students)): print('Hey',students[i],',please input the folowing grades:') weightAvg = [] discussionGrade = int(input('What was your discussion grade?: ')) # prompt grade 1 quizGrade = int(input('What was your quiz grade?: ')) # prompt grade 2 programGrade = int(input('What was your programming assignment grade?: ')) #prompt grade 3 weightAvg.append (discussionGrade*0.20 + quizGrade*0.30 + programGrade*0.50) #calculate weighted average print('Your weighted grade point average is: ',weightAvg, '\n')` The Output so far Hey Rose ,please input the folowing grades: What was your discussion grade?: 78 What was your quiz grade?: 88 What was your programming assignment grade?: 98 Your weighted grade point average is: [91.0] Hey Dorothy ,please input the folowing grades: What was your discussion grade?: 45 What was your quiz grade?: 99 What was your programming assignment grade?: 87 Your weighted grade point average is: [82.2] Hey Sophia ,please input the folowing grades: What was your discussion grade?: 67 What was your quiz grade?: 95 What was your programming assignment grade?: 77 Your weighted grade point average is: [80.4] Hey Blanch ,please input the folowing grades: What was your discussion grade?: 7 What was your quiz grade?: 45 What was your programming assignment grade?: 99 Your weighted grade point average is: [64.4] My Question Essentially I want this output print("The best student is (student name) with a score of (highest average)") I have placed my first block in a function and tried to return weightAvg but im still not outputing what I would like. Any help and explanation would be fantastic! Thank you!
[ "You need to store the averages outside the loop, to be able to have all of them once ended\nPut the pairs (avg, student) in the loop, and at the end use max function, as we put the average value in the tuple, the items will be compared by that, if we had add (student, avg), we would have had the max in term of lexicographical order (the nearest from end of alphabet\nweightAvg = []\nfor student in students:\n print('Hey', student, ',please input the folowing grades:')\n discussionGrade = int(input('What was your discussion grade?: ')) \n quizGrade = int(input('What was your quiz grade?: ')) \n programGrade = int(input('What was your programming assignment grade?: ')) \n avg = discussionGrade * 0.20 + quizGrade * 0.30 + programGrade * 0.50\n weightAvg.append((avg, student)) # calculate weighted average\n print('Your weighted grade point average is: ', avg, '\\n')\n\nbest_avg, best_student = max(weightAvg)\nprint(f\"The best student is {best_student} with a score of {best_avg}\")\n\n" ]
[ 2 ]
[]
[]
[ "function", "indexing", "list", "python", "weighted_average" ]
stackoverflow_0074591222_function_indexing_list_python_weighted_average.txt
Q: BeautifulSoup select_all does not work with data-testid attribute I am trying to scrape the current prices from the search result page of Booking.com such as: https://www.booking.com/searchresults.ja.html?lang=ja&dest_id=6411914&dest_type=hotel&checkin=2022-12-22&checkout=2022-12-23&group_adults=4&no_rooms=1&group_children=0&sb_travel_purpose=leisure As you can see, each property's information are stored in <div data-testid="property-card" ...> So I tried with this code, which returns 0 result. cards = soup.find_all('div', attrs={'data-testid': 'property-card'}) Trying to filter with CSS works okay off-course, but in this case I'd love to go with data-testid. Does the code above work at your end? What do you think I am missing? Thanks! A: The tag that you are looking for isn't in the soup object. Here is the soup for the first hotel from your URL, which is Cup of Tea Ensemble <div class="bui-carousel__item" data-bui-ref="carousel-item" data-lp-ga-click="hotel-group-3:click:4"> <div class="hotel-card__default bui-card bui-card--media" data-et-click="customGoal:BPHMAbFJfYCSKBZBLSRe:5" itemscope="" itemtype="http://schema.org/Hotel" onclick="location.href='/hotel/jp/cup-of-tea-ensemble.ja.html'"> <div class="bui-card__image-container"> <img alt="cup of tea ensemble、高山市のホテル" class="bui-card__image" itemprop="image" src="https://cf.bstatic.com/xdata/images/hotel/270x200/284494395.jpg?k=44610a2487cb129768a450003e9cd7582e8c04c8db251f005b80d533244e1a39&amp;o="> </img> </div> <div class="bui-card__content"> <header class="bui-card__header bui-spacer--medium"> <a class="bui-card__header_full_link_wrap" href="/hotel/jp/cup-of-tea-ensemble.ja.html" title="cup of tea ensemble"> <h3 class="bui-card__title" itemprop="name"> cup of tea ensemble </h3> <p class="bui-card__subtitle" itemprop="address" itemscope="" itemtype="http://schema.org/PostalAddress"> <span itemprop="addressLocality"> 高山市(高山市)のホテル </span> </p> </a> </header> <div class="bui-spacer--medium"> <span class="bui-badge bui-badge--outline"> ロケーションが良い </span> </div> <div class="hotel-card__text bui-spacer--medium"> <p class="bui-card__text hotel-card__text--wrapped"> cup of tea ensembleは高山市の飛騨高山温泉にあり、高山駅まで1km以内、飛騨民俗村・飛騨の里まで2.5km、藤井美術民芸館まで徒歩6分です。3つ星のホテルで、共用ラウンジ、エアコン付きのお部屋(無料WiFi、専用バスルーム付)を提供しています。共用キッチンと荷物預かりを提供しています。 cup of tea ensembleのお部屋にはそれぞれベッドリネンとタオルが備わります。... <span class="hotel-card__text_review"> Super nice design, very good location close to the city center with coffee shops, bakerys and market... </span> </p> <div class="hotel-card__read_more_container js-hotel-card__read_more_container"> <span class="hotel-card__read_more_button js-hotel-card__read_more_button" role="button" tabindex="0"> <span class="hotel-card__read_more bui-link bui-link--secondary"> もっと見る </span> <span class="hotel-card__read_less bui-link bui-link--secondary"> 折りたたむ </span> </span> </div> </div> <div class="bui-card__text"> <div class="hotel-card__price bui-spacer--small"> 1泊あたり¥14,500~ </div> <span class="review-score-widget review-score-widget__very_good review-score-widget__text-only review-score-widget__inline"> <span aria-label="スコアは8.5" class="review-score-badge"> 8.5 </span> <span aria-label="評価はとても良い" class="review-score-widget__text"> とても良い </span> <span aria-label="クチコミ全77件をもとにしています" class="review-score-widget__subtext"> クチコミ77件 </span> </span> </div> </div> </div> </div> The hotels are under this tag soup.find_all('div', attrs={'class', 'bui-carousel__item'})
BeautifulSoup select_all does not work with data-testid attribute
I am trying to scrape the current prices from the search result page of Booking.com such as: https://www.booking.com/searchresults.ja.html?lang=ja&dest_id=6411914&dest_type=hotel&checkin=2022-12-22&checkout=2022-12-23&group_adults=4&no_rooms=1&group_children=0&sb_travel_purpose=leisure As you can see, each property's information are stored in <div data-testid="property-card" ...> So I tried with this code, which returns 0 result. cards = soup.find_all('div', attrs={'data-testid': 'property-card'}) Trying to filter with CSS works okay off-course, but in this case I'd love to go with data-testid. Does the code above work at your end? What do you think I am missing? Thanks!
[ "The tag that you are looking for isn't in the soup object.\nHere is the soup for the first hotel from your URL, which is Cup of Tea Ensemble\n<div class=\"bui-carousel__item\" data-bui-ref=\"carousel-item\" data-lp-ga-click=\"hotel-group-3:click:4\">\n <div class=\"hotel-card__default bui-card bui-card--media\" data-et-click=\"customGoal:BPHMAbFJfYCSKBZBLSRe:5\" itemscope=\"\" itemtype=\"http://schema.org/Hotel\" onclick=\"location.href='/hotel/jp/cup-of-tea-ensemble.ja.html'\">\n <div class=\"bui-card__image-container\">\n <img alt=\"cup of tea ensemble、高山市のホテル\" class=\"bui-card__image\" itemprop=\"image\" src=\"https://cf.bstatic.com/xdata/images/hotel/270x200/284494395.jpg?k=44610a2487cb129768a450003e9cd7582e8c04c8db251f005b80d533244e1a39&amp;o=\">\n </img>\n </div>\n <div class=\"bui-card__content\">\n <header class=\"bui-card__header bui-spacer--medium\">\n <a class=\"bui-card__header_full_link_wrap\" href=\"/hotel/jp/cup-of-tea-ensemble.ja.html\" title=\"cup of tea ensemble\">\n <h3 class=\"bui-card__title\" itemprop=\"name\">\n cup of tea ensemble\n </h3>\n <p class=\"bui-card__subtitle\" itemprop=\"address\" itemscope=\"\" itemtype=\"http://schema.org/PostalAddress\">\n <span itemprop=\"addressLocality\">\n 高山市(高山市)のホテル\n </span>\n </p>\n </a>\n </header>\n <div class=\"bui-spacer--medium\">\n <span class=\"bui-badge bui-badge--outline\">\n ロケーションが良い\n </span>\n </div>\n <div class=\"hotel-card__text bui-spacer--medium\">\n <p class=\"bui-card__text hotel-card__text--wrapped\">\n cup of tea ensembleは高山市の飛騨高山温泉にあり、高山駅まで1km以内、飛騨民俗村・飛騨の里まで2.5km、藤井美術民芸館まで徒歩6分です。3つ星のホテルで、共用ラウンジ、エアコン付きのお部屋(無料WiFi、専用バスルーム付)を提供しています。共用キッチンと荷物預かりを提供しています。 cup of tea ensembleのお部屋にはそれぞれベッドリネンとタオルが備わります。...\n <span class=\"hotel-card__text_review\">\n Super nice design, very good location close to the city center with coffee shops, bakerys and market...\n </span>\n </p>\n <div class=\"hotel-card__read_more_container js-hotel-card__read_more_container\">\n <span class=\"hotel-card__read_more_button js-hotel-card__read_more_button\" role=\"button\" tabindex=\"0\">\n <span class=\"hotel-card__read_more bui-link bui-link--secondary\">\n もっと見る\n </span>\n <span class=\"hotel-card__read_less bui-link bui-link--secondary\">\n 折りたたむ\n </span>\n </span>\n </div>\n </div>\n <div class=\"bui-card__text\">\n <div class=\"hotel-card__price bui-spacer--small\">\n 1泊あたり¥14,500~\n </div>\n <span class=\"review-score-widget review-score-widget__very_good review-score-widget__text-only review-score-widget__inline\">\n <span aria-label=\"スコアは8.5\" class=\"review-score-badge\">\n 8.5\n </span>\n <span aria-label=\"評価はとても良い\" class=\"review-score-widget__text\">\n とても良い\n </span>\n <span aria-label=\"クチコミ全77件をもとにしています\" class=\"review-score-widget__subtext\">\n クチコミ77件\n </span>\n </span>\n </div>\n </div>\n </div>\n </div>\n\nThe hotels are under this tag soup.find_all('div', attrs={'class', 'bui-carousel__item'})\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074591178_beautifulsoup_python.txt
Q: Commas between numbers in Python or Django hi this is my code for Percentage for the price of a product: def get_discounted_malile_price(self): result = int(self.price - (self.price * (self.discount / 100))) round_result = round(result, 3) return round_result and this is my result: i have add , for result number ,for example(1936000 -> 193.600.0) I would appreciate it if someone could help me. A: Are you looking for this? https://stackoverflow.com/a/10742904/17320013 value = 123456789 print(f'{value:,}') # 123,456,789 If yes, your code should be def get_discounted_malile_price(self) -> str: result = int(self.price - (self.price * (self.discount / 100))) round_result = f'{round(result, 3):,}' return round_result # NOTE: it returns str type
Commas between numbers in Python or Django
hi this is my code for Percentage for the price of a product: def get_discounted_malile_price(self): result = int(self.price - (self.price * (self.discount / 100))) round_result = round(result, 3) return round_result and this is my result: i have add , for result number ,for example(1936000 -> 193.600.0) I would appreciate it if someone could help me.
[ "Are you looking for this? https://stackoverflow.com/a/10742904/17320013\nvalue = 123456789\nprint(f'{value:,}') # 123,456,789\n\nIf yes, your code should be\ndef get_discounted_malile_price(self) -> str:\n result = int(self.price - (self.price * (self.discount / 100)))\n round_result = f'{round(result, 3):,}'\n return round_result # NOTE: it returns str type\n\n" ]
[ 0 ]
[]
[]
[ "python", "web" ]
stackoverflow_0074591105_python_web.txt
Q: Changing the colour of tkinter menubar I have the following code, what I'm trying to do is change the color the the menubar to be the same as my window. I have tried what you see below, adding to bg="#20232A" to menubar but this seems to have no affect.. My Question: The below image is the window (albeit a snippet of the window), it showcases both the menubar and background. I want the menubar to be the same color as the background seen below, how can I achieve this? from tkinter import * config = {"title":"Editor", "version":"[Version: 0.1]"} window = Tk() window.title(config["title"] + " " +config["version"]) window.config(bg="#20232A") window.state('zoomed') def Start(): menubar = Menu(window, borderwidth=0, bg="#20232A") # Tried adding background to this, but it doesent work filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Open") filemenu.add_command(label="Save") menubar.add_cascade(label="File", menu=filemenu) window.config(menu=menubar) Start() window.mainloop() A: You cannot change the color of the menubar on Windows or OSX. It might be possible on some window managers on linux, though I don't know for certain. The reason is that the menubar is drawn using native widgets that aren't managed by tkinter, so you're limited to what the platform allows. A: On Linux it is possible: def main(): root =Tk() menubar = Menu(root, background='lightblue', foreground='black', activebackground='#004c99', activeforeground='white') file = Menu(menubar, tearoff=1, background='lightblue', foreground='black') file.add_command(label="Receive") file.add_command(label="Issue") file.add_command(label="Track") file.add_command(label="Search") file.add_command(label="Allocate") file.add_separator() file.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="Goods", menu=file) edit = Menu(menubar, tearoff=0) edit.add_command(label="Undo") edit.add_separator() edit.add_command(label="Cut") edit.add_command(label="Copy") edit.add_command(label="Paste") edit.add_command(label="Delete") edit.add_command(label="Select All") menubar.add_cascade(label="Accounts", menu=edit) help = Menu(menubar, tearoff=0) help.add_command(label="About") menubar.add_cascade(label="Help", menu=help) root.config(menu=menubar) ex = MainWin() root.geometry("2000x1391") root.mainloop() if __name__ == '__main__': main() Just add foreground and background attributes. A: To follow on from Brian Oakley's response. The menu bar on Linux (at least on my Linux Mint installation) renders the desired color.
Changing the colour of tkinter menubar
I have the following code, what I'm trying to do is change the color the the menubar to be the same as my window. I have tried what you see below, adding to bg="#20232A" to menubar but this seems to have no affect.. My Question: The below image is the window (albeit a snippet of the window), it showcases both the menubar and background. I want the menubar to be the same color as the background seen below, how can I achieve this? from tkinter import * config = {"title":"Editor", "version":"[Version: 0.1]"} window = Tk() window.title(config["title"] + " " +config["version"]) window.config(bg="#20232A") window.state('zoomed') def Start(): menubar = Menu(window, borderwidth=0, bg="#20232A") # Tried adding background to this, but it doesent work filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Open") filemenu.add_command(label="Save") menubar.add_cascade(label="File", menu=filemenu) window.config(menu=menubar) Start() window.mainloop()
[ "You cannot change the color of the menubar on Windows or OSX. It might be possible on some window managers on linux, though I don't know for certain. \nThe reason is that the menubar is drawn using native widgets that aren't managed by tkinter, so you're limited to what the platform allows. \n", "On Linux it is possible:\ndef main():\n\n root =Tk()\n menubar = Menu(root, background='lightblue', foreground='black',\n activebackground='#004c99', activeforeground='white') \n file = Menu(menubar, tearoff=1, background='lightblue', foreground='black') \n file.add_command(label=\"Receive\") \n file.add_command(label=\"Issue\") \n file.add_command(label=\"Track\") \n file.add_command(label=\"Search\") \n file.add_command(label=\"Allocate\") \n \n file.add_separator() \n \n file.add_command(label=\"Exit\", command=root.quit) \n \n menubar.add_cascade(label=\"Goods\", menu=file) \n edit = Menu(menubar, tearoff=0) \n edit.add_command(label=\"Undo\") \n \n edit.add_separator() \n \n edit.add_command(label=\"Cut\") \n edit.add_command(label=\"Copy\") \n edit.add_command(label=\"Paste\") \n edit.add_command(label=\"Delete\") \n edit.add_command(label=\"Select All\") \n \n menubar.add_cascade(label=\"Accounts\", menu=edit) \n help = Menu(menubar, tearoff=0) \n help.add_command(label=\"About\") \n menubar.add_cascade(label=\"Help\", menu=help) \n \n root.config(menu=menubar) \n ex = MainWin()\n root.geometry(\"2000x1391\")\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n\nJust add foreground and background attributes.\n", "To follow on from Brian Oakley's response. The menu bar on Linux (at least on my Linux Mint installation) renders the desired color.\n\n" ]
[ 9, 2, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0049088785_python_tkinter.txt
Q: How to scrap publication date from news? I have a scraper of headlines, but I want a publication date also. That's my code: news = [] url = 1 while url != 100: website = f"https://www.newscientist.com/subject/space/page/{url}" r = requests.get( website, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0", "Referer": website } ) soup = bs(r.text, 'html.parser') for h2 in soup.find_all("h2"): news.append(h2.get_text(strip=True)) The problem is the publication date is ''inside'' news and I don't know how to get there. A: There are different options, simplest one in my opinion is to uses their RSS-Feed: import pandas as pd pd.read_xml('https://www.newscientist.com/subject/space/feed/', xpath='*/item') title link pubDate description guid {http://search.yahoo.com/mrss/}thumbnail 0 Bluewalker 3 satellite is brighter than 99.8 per cent of visible stars https://www.newscientist.com/article/2348615-bluewalker-3-satellite-is-brighter-than-99-8-per-cent-of-visible-stars/?utm_campaign=RSS%7CNSNS&utm_source=NSNS&utm_medium=RSS&utm_content=space Fri, 25 Nov 2022 15:54:32 +0000 Observations of a huge test satellite that launched in September have fuelled concerns about the impact a planned fleet could have on astronomy 2348615-bluewalker-3-satellite-is-brighter-than-99-8-per-cent-of-visible-stars 2348615 ... ... ... ... ... ... 99 JWST's dazzling nebula image shows stars we have never seen before https://www.newscientist.com/article/2336822-jwsts-dazzling-nebula-image-shows-stars-we-have-never-seen-before/?utm_campaign=RSS%7CNSNS&utm_source=NSNS&utm_medium=RSS&utm_content=space Tue, 06 Sep 2022 18:36:28 +0100 Astronomers have used the James Webb Space Telescope to peer through the filaments of dust and gas in the Tarantula Nebula, the brightest and biggest stellar nursery around 2336822-jwsts-dazzling-nebula-image-shows-stars-we-have-never-seen-before 2336822 Alternative would be to iterate over each article: ... soup = BeautifulSoup(r.text, 'html.parser') for a in soup.select('h2+a'): soup_article = BeautifulSoup( requests.get( 'https://www.newscientist.com'+a.get('href'), headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0", } ).text ) news.append( { 'title':soup_article.h1.text, 'date':soup_article.select_one('.published-date').get_text(strip=True) if soup_article.select_one('.published-date') else None } ) news A: Here is an alternative, constructed upon @HedgeHog's answer: import requests from bs4 import BeautifulSoup as bs space_rss = "https://www.newscientist.com/subject/space/feed/" r = requests.get( space_rss, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0", "Referer": space_rss, }, ) if r.ok: soup = bs(r.text, "xml") news = [ (item.select_one("pubDate").text, item.select_one("title").text) for item in soup.find_all("item") ] It will populate news with a list of tuple(pubDate, title) from the RSS feed.
How to scrap publication date from news?
I have a scraper of headlines, but I want a publication date also. That's my code: news = [] url = 1 while url != 100: website = f"https://www.newscientist.com/subject/space/page/{url}" r = requests.get( website, headers={ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0", "Referer": website } ) soup = bs(r.text, 'html.parser') for h2 in soup.find_all("h2"): news.append(h2.get_text(strip=True)) The problem is the publication date is ''inside'' news and I don't know how to get there.
[ "There are different options, simplest one in my opinion is to uses their RSS-Feed:\nimport pandas as pd\npd.read_xml('https://www.newscientist.com/subject/space/feed/', xpath='*/item')\n\n\n\n\n\n\ntitle\nlink\npubDate\ndescription\nguid\n{http://search.yahoo.com/mrss/}thumbnail\n\n\n\n\n0\nBluewalker 3 satellite is brighter than 99.8 per cent of visible stars\nhttps://www.newscientist.com/article/2348615-bluewalker-3-satellite-is-brighter-than-99-8-per-cent-of-visible-stars/?utm_campaign=RSS%7CNSNS&utm_source=NSNS&utm_medium=RSS&utm_content=space\nFri, 25 Nov 2022 15:54:32 +0000\nObservations of a huge test satellite that launched in September have fuelled concerns about the impact a planned fleet could have on astronomy\n2348615-bluewalker-3-satellite-is-brighter-than-99-8-per-cent-of-visible-stars\n2348615\n\n\n...\n...\n...\n...\n...\n...\n\n\n\n99\nJWST's dazzling nebula image shows stars we have never seen before\nhttps://www.newscientist.com/article/2336822-jwsts-dazzling-nebula-image-shows-stars-we-have-never-seen-before/?utm_campaign=RSS%7CNSNS&utm_source=NSNS&utm_medium=RSS&utm_content=space\nTue, 06 Sep 2022 18:36:28 +0100\nAstronomers have used the James Webb Space Telescope to peer through the filaments of dust and gas in the Tarantula Nebula, the brightest and biggest stellar nursery around\n2336822-jwsts-dazzling-nebula-image-shows-stars-we-have-never-seen-before\n2336822\n\n\n\n\nAlternative would be to iterate over each article:\n...\nsoup = BeautifulSoup(r.text, 'html.parser')\nfor a in soup.select('h2+a'):\n soup_article = BeautifulSoup(\n requests.get(\n 'https://www.newscientist.com'+a.get('href'),\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0\",\n }\n ).text\n )\n news.append(\n {\n 'title':soup_article.h1.text,\n 'date':soup_article.select_one('.published-date').get_text(strip=True) if soup_article.select_one('.published-date') else None\n }\n )\nnews\n\n", "Here is an alternative, constructed upon @HedgeHog's answer:\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\nspace_rss = \"https://www.newscientist.com/subject/space/feed/\"\n\nr = requests.get(\n space_rss,\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0\",\n \"Referer\": space_rss,\n },\n)\n\nif r.ok:\n soup = bs(r.text, \"xml\")\n news = [\n (item.select_one(\"pubDate\").text, item.select_one(\"title\").text)\n for item in soup.find_all(\"item\")\n ]\n\nIt will populate news with a list of tuple(pubDate, title) from the RSS feed.\n" ]
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074590801_beautifulsoup_python_web_scraping.txt
Q: How to draw grid lines behind matplotlib bar graph x = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=0.3,align='center',color='skyblue') plt.xticks(range(len(y)), x, size='small') plt.savefig('/home/user/graphimages/foo2.png') plt.close() I want to draw grid lines (of x & y) behind the bar graph. A: To add a grid you simply need to add ax.grid() If you want the grid to be behind the bars then add ax.grid(zorder=0) ax.bar(range(len(y)), y, width=0.3, align='center', color='skyblue', zorder=3) The important part is that the zorder of the bars is greater than grid. Experimenting it seems zorder=3 is the lowest value that actually gives the desired effect. I have no idea why zorder=1 isn't sufficient. EDIT: I have noticed this question has already been answered here using a different method although it suffers some link rot. Both methods yield the same result as far as I can see but andrew cooke's answer is more elegant. A: I am suggesting another solution since the most voted answer did not work for me. You can use the following code to set the gridlines behind the plot. ax.set_axisbelow(True) ax.grid(color='gray', linestyle='dashed') I got this code from this answer. A: plt.grid(True, color = "grey", linewidth = "1.4", linestyle = "-.") This worked for me, the grid lines will be in grey border color,if you want can change border design to linestyle = ".." Like this plt.grid(True, color = "grey", linewidth = "1.4", linestyle = "..") Summing up entire code block: fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=0.3,align='center',color='skyblue') plt.xticks(range(len(y)), x, size='small') plt.grid(True, color = "grey", linewidth = "1.4", linestyle = "-.") plt.savefig('/home/user/graphimages/foo2.png') plt.close() A: use .grid() it makes the order go to 0 (back) ax.grid(zorder=0)
How to draw grid lines behind matplotlib bar graph
x = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=0.3,align='center',color='skyblue') plt.xticks(range(len(y)), x, size='small') plt.savefig('/home/user/graphimages/foo2.png') plt.close() I want to draw grid lines (of x & y) behind the bar graph.
[ "To add a grid you simply need to add\nax.grid()\nIf you want the grid to be behind the bars then add \nax.grid(zorder=0)\nax.bar(range(len(y)), y, width=0.3, align='center', color='skyblue', zorder=3)\n\nThe important part is that the zorder of the bars is greater than grid. Experimenting it seems zorder=3 is the lowest value that actually gives the desired effect. I have no idea why zorder=1 isn't sufficient. \nEDIT: \nI have noticed this question has already been answered here using a different method although it suffers some link rot. Both methods yield the same result as far as I can see but andrew cooke's answer is more elegant. \n", "I am suggesting another solution since the most voted answer did not work for me. You can use the following code to set the gridlines behind the plot.\nax.set_axisbelow(True)\nax.grid(color='gray', linestyle='dashed')\n\nI got this code from this answer.\n", "plt.grid(True, color = \"grey\", linewidth = \"1.4\", linestyle = \"-.\")\n\nThis worked for me, the grid lines will be in grey border color,if you want can change border design to linestyle = \"..\"\nLike this\nplt.grid(True, color = \"grey\", linewidth = \"1.4\", linestyle = \"..\")\n\nSumming up entire code block:\nfig, ax = plt.subplots(1, 1)\nax.bar(range(len(y)), y, width=0.3,align='center',color='skyblue')\nplt.xticks(range(len(y)), x, size='small')\nplt.grid(True, color = \"grey\", linewidth = \"1.4\", linestyle = \"-.\")\nplt.savefig('/home/user/graphimages/foo2.png')\nplt.close()\n\n", "use .grid() it makes the order go to 0 (back)\nax.grid(zorder=0)\n\n" ]
[ 113, 15, 1, 0 ]
[ "ax.grid(zorder=0) Woud work. But First Place the Bar and then Place the Grid.Not the orther way.\nax = df.plot.bar(x='Index', y='Values', rot=90)\nax.grid(zorder=0)\n\nI took some currency Correlation with Year and Sorted it as my Data Frame df, and below is the result of the code run. \n\n" ]
[ -2 ]
[ "matplotlib", "python" ]
stackoverflow_0023357798_matplotlib_python.txt
Q: Rendering issues in FrozenLake-v1 environment I am using the FrozenLake-v1 gym environment for testing q-table algorithms. When I use the default map size 4x4 and call the env.render() function, I see the image as shown: [] But when I call the same env.render() function for map size 8x8, I see no such results! The code runs fine with no error message, but the render window doesn't show up at all! I have tried using the following two commands for invoking the gym environment: env = gym.make("FrozenLake8x8-v1") env = gym.make("FrozenLake-v1", map_name="8x8") but still, the issue persists. Any reason why the render window doesn't show up for any other map apart from the default 4x4 setting? Or am I making a mistake somewhere in calling the 8x8 frozen lake environment? Link to the FrozenLake openai gym environment: https://gym.openai.com/envs/FrozenLake8x8-v0/ A: Ran into the same problem. I was able to fix it by passing in render_mode="human". For example env = gym.make("FrozenLake-v1", map_name="8x8", render_mode="human") This worked on my own custom maps in addition to the built in ones.
Rendering issues in FrozenLake-v1 environment
I am using the FrozenLake-v1 gym environment for testing q-table algorithms. When I use the default map size 4x4 and call the env.render() function, I see the image as shown: [] But when I call the same env.render() function for map size 8x8, I see no such results! The code runs fine with no error message, but the render window doesn't show up at all! I have tried using the following two commands for invoking the gym environment: env = gym.make("FrozenLake8x8-v1") env = gym.make("FrozenLake-v1", map_name="8x8") but still, the issue persists. Any reason why the render window doesn't show up for any other map apart from the default 4x4 setting? Or am I making a mistake somewhere in calling the 8x8 frozen lake environment? Link to the FrozenLake openai gym environment: https://gym.openai.com/envs/FrozenLake8x8-v0/
[ "Ran into the same problem. I was able to fix it by passing in render_mode=\"human\". For example\nenv = gym.make(\"FrozenLake-v1\", map_name=\"8x8\", render_mode=\"human\")\n\nThis worked on my own custom maps in addition to the built in ones.\n" ]
[ 0 ]
[]
[]
[ "openai", "openai_gym", "python", "render" ]
stackoverflow_0071334309_openai_openai_gym_python_render.txt
Q: Sort with custom function I can sort a 2D-array in Javascript like the following: const a = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]] a.sort((a,b) => { if (a[0] != b[0]) { return a[0] - b[0] } else { return b[1] - a[1] * 2 + 3 } }) How to perform the same task in Python? A: x = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]] >>> sorted(x) [[-25, 1], [-1, 5], [3, 2], [12, 1], [12, 3]] If you wanted to customize the order, e.g. order by b, a (for each [a, b] sublist): >>> sorted(x, key=lambda ab: ab[::-1]) [[-25, 1], [12, 1], [3, 2], [12, 3], [-1, 5]] However, in your JavaScript you define a specific comparison (not a key that is in turn used for comparison). This is a little different in Python. You would define a class that has a custom ordering. For example, here, using total_ordering: from functools import total_ordering @total_ordering class weird(list): def __lt__(a, b): if a[0] != b[0]: return a[0] < b[0] return b[1] < a[1] * 2 + 3 And now: >>> sorted([weird(xi) for xi in x]) [[-25, 1], [-1, 5], [3, 2], [12, 1], [12, 3]] In JavaScript, the result is slightly different: [[-25,1],[-1,5],[3,2],[12,3],[12,1]] (the last two elements are swapped), why is that? The reason is that the order you specified is not consistent: >>> weird([12,1]) < weird([12,3]) True >>> weird([12,3]) < weird([12,1]) True Thus, the order of the result is dependent on the sort implementation. A: you can use the sorted built-iin function with key parameter and define a lambda function that will sort the list according to the condition defined list_ = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]] sorted_list=sorted(list_, key=lambda arr: arr[0]-arr[1])
Sort with custom function
I can sort a 2D-array in Javascript like the following: const a = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]] a.sort((a,b) => { if (a[0] != b[0]) { return a[0] - b[0] } else { return b[1] - a[1] * 2 + 3 } }) How to perform the same task in Python?
[ "x = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]]\n>>> sorted(x)\n[[-25, 1], [-1, 5], [3, 2], [12, 1], [12, 3]]\n\nIf you wanted to customize the order, e.g. order by b, a (for each [a, b] sublist):\n>>> sorted(x, key=lambda ab: ab[::-1])\n[[-25, 1], [12, 1], [3, 2], [12, 3], [-1, 5]]\n\nHowever, in your JavaScript you define a specific comparison (not a key that is in turn used for comparison). This is a little different in Python. You would define a class that has a custom ordering. For example, here, using total_ordering:\nfrom functools import total_ordering\n\n@total_ordering\nclass weird(list):\n def __lt__(a, b):\n if a[0] != b[0]:\n return a[0] < b[0]\n return b[1] < a[1] * 2 + 3\n\nAnd now:\n>>> sorted([weird(xi) for xi in x])\n[[-25, 1], [-1, 5], [3, 2], [12, 1], [12, 3]]\n\nIn JavaScript, the result is slightly different: [[-25,1],[-1,5],[3,2],[12,3],[12,1]] (the last two elements are swapped), why is that?\nThe reason is that the order you specified is not consistent:\n>>> weird([12,1]) < weird([12,3])\nTrue\n\n>>> weird([12,3]) < weird([12,1])\nTrue\n\nThus, the order of the result is dependent on the sort implementation.\n", "you can use the sorted built-iin function with key parameter and define a lambda function that will sort the list according to the condition defined\nlist_ = [[-1, 5], [3, 2], [-25, 1], [12, 3], [12, 1]]\nsorted_list=sorted(list_, key=lambda arr: arr[0]-arr[1])\n\n" ]
[ 1, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0074591136_python_sorting.txt
Q: how to check if a number is a power of base b? In python, how can you check if a number n is an exact power of base b? Note: it needs to be generalized to any base which is given as a parameter. Here is what I got: Assume n and base are integers > 0. import math def is_power(n,base): return math.log(n,base) == base**n A: First, assuming you have a specific logarithm operator (many languages provide logarithms to base 10 or base e only), logab can be calculated as logxb / logxa (where x is obviously a base that your language provides). Python goes one better since it can work out the logarithm for an arbitrary base without that tricky equality above. So one way or another, you have a way to get logarithm to a specific base. From there, if the log of b in base a is an integer(note 1), then b is a power of a. So I'd start with the following code, now with added edge-case detection: # Don't even think about using this for negative powers :-) def isPower (num, base): if base in {0, 1}: return num == base power = int (math.log (num, base) + 0.5) return base ** power == num See for example the following complete program which shows this in action: import math def isPower (num, base): if base in {0, 1}: return num == base power = int (math.log (num, base) + 0.5) return base ** power == num print isPower (127,2) # false print isPower (128,2) # true print isPower (129,2) # false print print isPower (26,3) # false print isPower (27,3) # true print isPower (28,3) # false print isPower (3**10,3) # true print isPower (3**129,3) # true print print isPower (5,5) # true print isPower (1,1) # true print isPower (10,1) # false If you're the sort that's worried about floating point operations, you can do it with repeated multiplications but you should test the performance of such a solution since it's likely to be substantially slower in software than it is in hardware. That won't matter greatly for things like isPower(128,2) but it may become a concern for isPower(verybignum,2). For a non-floating point variant of the above code: def isPower (num, base): if base in {0, 1}: return num == base testnum = base while testnum < num: testnum = testnum * base return testnum == num But make sure it's tested against your largest number and smallest base to ensure you don't get any performance shocks. (Note 1) Keep in mind here the possibility that floating point imprecision may mean it's not exactly an integer. You may well have to use a "close enough" comparison. A: A very simple solution could go like this: def ispower(n, base): if n == base: return True if base == 1: return False temp = base while (temp <= n): if temp == n: return True temp *= base return False Result: >>> ispower(32, 2) True >>> ispower(81, 3) True >>> ispower(625, 5) True >>> ispower(50, 5) False >>> ispower(32, 4) False >>> ispower(2,1) False >>> ispower(1,1) True A: >>> def isPower(n, b): ... return b**int(math.log(n, b)+.5)==n ... >>> isPower(128, 2) True >>> isPower(129, 2) False >>> isPower(3**10, 3) True >>> isPower(3**129, 3) True >>> isPower(10**500, 10) True >>> isPower(10**(10**6), 10) True EDIT: This code does fail for 1,1: >>> isPower(1,1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in isPower ZeroDivisionError: float division by zero I'll leave it to the OP to decide if he wants to apply the trivial fix or rewrite his requirements. A: Here's a constant-time solution that handles every special case mentioned in the comments so far: import math def is_power(a, b, precision=14): if a == 1 or a == b: return True if b in (0, 1): return False return round(math.log(a, b), precision).is_integer() Behavior for each special case: a b is_power(a, b) 3^10 3 True ✔️ 3^129 3 True ✔️ 2 1 False ✔️ 1 1 True ✔️ 1 0 True ✔️ 17^3 17 True ✔️
how to check if a number is a power of base b?
In python, how can you check if a number n is an exact power of base b? Note: it needs to be generalized to any base which is given as a parameter. Here is what I got: Assume n and base are integers > 0. import math def is_power(n,base): return math.log(n,base) == base**n
[ "First, assuming you have a specific logarithm operator (many languages provide logarithms to base 10 or base e only), logab can be calculated as logxb / logxa (where x is obviously a base that your language provides).\nPython goes one better since it can work out the logarithm for an arbitrary base without that tricky equality above.\nSo one way or another, you have a way to get logarithm to a specific base. From there, if the log of b in base a is an integer(note 1), then b is a power of a.\nSo I'd start with the following code, now with added edge-case detection:\n# Don't even think about using this for negative powers :-)\n\ndef isPower (num, base):\n if base in {0, 1}:\n return num == base\n power = int (math.log (num, base) + 0.5)\n return base ** power == num\n\nSee for example the following complete program which shows this in action:\nimport math\n\ndef isPower (num, base):\n if base in {0, 1}:\n return num == base\n power = int (math.log (num, base) + 0.5)\n return base ** power == num\n\nprint isPower (127,2) # false\nprint isPower (128,2) # true\nprint isPower (129,2) # false\nprint\n\nprint isPower (26,3) # false\nprint isPower (27,3) # true\nprint isPower (28,3) # false\nprint isPower (3**10,3) # true\nprint isPower (3**129,3) # true\nprint\n\nprint isPower (5,5) # true\nprint isPower (1,1) # true\nprint isPower (10,1) # false\n\n\nIf you're the sort that's worried about floating point operations, you can do it with repeated multiplications but you should test the performance of such a solution since it's likely to be substantially slower in software than it is in hardware. That won't matter greatly for things like isPower(128,2) but it may become a concern for isPower(verybignum,2).\nFor a non-floating point variant of the above code:\ndef isPower (num, base):\n if base in {0, 1}:\n return num == base\n testnum = base\n while testnum < num:\n testnum = testnum * base\n return testnum == num\n\nBut make sure it's tested against your largest number and smallest base to ensure you don't get any performance shocks.\n\n(Note 1) Keep in mind here the possibility that floating point imprecision may mean it's not exactly an integer. You may well have to use a \"close enough\" comparison.\n", "A very simple solution could go like this:\ndef ispower(n, base): \n\n if n == base:\n return True\n\n if base == 1:\n return False\n\n temp = base\n\n while (temp <= n):\n if temp == n:\n return True\n temp *= base\n\n return False\n\nResult:\n>>> ispower(32, 2)\nTrue\n>>> ispower(81, 3)\nTrue\n>>> ispower(625, 5)\nTrue\n>>> ispower(50, 5)\nFalse\n>>> ispower(32, 4)\nFalse\n>>> ispower(2,1)\nFalse\n>>> ispower(1,1)\nTrue\n\n", ">>> def isPower(n, b):\n... return b**int(math.log(n, b)+.5)==n\n... \n>>> isPower(128, 2)\nTrue\n>>> isPower(129, 2)\nFalse\n>>> isPower(3**10, 3)\nTrue\n>>> isPower(3**129, 3)\nTrue\n>>> isPower(10**500, 10)\nTrue\n>>> isPower(10**(10**6), 10)\nTrue\n\n\nEDIT: This code does fail for 1,1:\n>>> isPower(1,1)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in isPower\nZeroDivisionError: float division by zero\n\nI'll leave it to the OP to decide if he wants to apply the trivial fix or rewrite his requirements.\n", "Here's a constant-time solution that handles every special case mentioned in the comments so far:\nimport math\n\ndef is_power(a, b, precision=14):\n if a == 1 or a == b:\n return True\n if b in (0, 1):\n return False\n return round(math.log(a, b), precision).is_integer()\n\nBehavior for each special case:\n\n\n\n\na\nb\nis_power(a, b)\n\n\n\n\n3^10\n3\nTrue ✔️\n\n\n3^129\n3\nTrue ✔️\n\n\n2\n1\nFalse ✔️\n\n\n1\n1\nTrue ✔️\n\n\n1\n0\nTrue ✔️\n\n\n17^3\n17\nTrue ✔️\n\n\n\n" ]
[ 10, 5, 0, 0 ]
[ ">>>(math.log(int(num),int(base))).is_integer()\nThis will return a boolean value either true or false. This should work fine. Hope it helps\n" ]
[ -1 ]
[ "logarithm", "python" ]
stackoverflow_0015352593_logarithm_python.txt
Q: How to specify a directory for "spark.sparkContext.textFile()"? I have downloaded the following code rating.py to see if my Spark working correctly. from pyspark import SparkConf, SparkContext import collections conf = SparkConf().setMaster("local").setAppName("RatingsHistogram") sc = SparkContext(conf = conf) lines = sc.textFile("file:///SparkCourse/ml-100k/u.data") ratings = lines.map(lambda x: x.split()[2]) result = ratings.countByValue() sortedResults = collections.OrderedDict(sorted(result.items())) for key, value in sortedResults.items(): print("%s %i" % (key, value)) Both rating.pyfile and ml-100k folder are inside C:\\SpikeCourse directory, and the code uses the following line to loading them up: lines = sc.textFile("file:///SparkCourse/ml-100k/u.data") But I can't understand how C:\\SpikeCourse changed to file:///SparkCourse/ml-100k/u.data? Or for example, if my files are within E:\\ instead of C:\\ directory, how should I specify that? PS: I am using Windows 10 machine. A: In windows you have to escape "\" Try: lines = sc.textFile("C:\\SparkCourse\\ml-100k\\u.data")
How to specify a directory for "spark.sparkContext.textFile()"?
I have downloaded the following code rating.py to see if my Spark working correctly. from pyspark import SparkConf, SparkContext import collections conf = SparkConf().setMaster("local").setAppName("RatingsHistogram") sc = SparkContext(conf = conf) lines = sc.textFile("file:///SparkCourse/ml-100k/u.data") ratings = lines.map(lambda x: x.split()[2]) result = ratings.countByValue() sortedResults = collections.OrderedDict(sorted(result.items())) for key, value in sortedResults.items(): print("%s %i" % (key, value)) Both rating.pyfile and ml-100k folder are inside C:\\SpikeCourse directory, and the code uses the following line to loading them up: lines = sc.textFile("file:///SparkCourse/ml-100k/u.data") But I can't understand how C:\\SpikeCourse changed to file:///SparkCourse/ml-100k/u.data? Or for example, if my files are within E:\\ instead of C:\\ directory, how should I specify that? PS: I am using Windows 10 machine.
[ "In windows you have to escape \"\\\"\nTry:\nlines = sc.textFile(\"C:\\\\SparkCourse\\\\ml-100k\\\\u.data\")\n\n" ]
[ 0 ]
[]
[]
[ "apache_spark", "directory", "pyspark", "python", "windows_10" ]
stackoverflow_0074576551_apache_spark_directory_pyspark_python_windows_10.txt
Q: if else condition in pandas with multiple column as arguements I have a df like so: import pandas as pd df = pd.DataFrame({"code": [sp,wh,sp], "qty": [20, 30, 10]}) I want to create a new column based on data from the two columns with the value the new column as the same as an existing column if a condition is met. This is what I’ve tried: df['out'] = df.apply(lambda x: x['qty']) if x['code'] == 'sp' else 0) so my output in this case should be: df = [ {'code':'sp', 'qty':20, 'out':20} {'code':'wh', 'qty':30, 'out':0} {'code':'sp', 'qty':10, 'out':10} ] A: You can use numpy's where: import numpy as np df['out'] = np.where(df['code']=='sp', df['qty'], 0) A: here is one way to do it using mask # mask the qty as zero when code is not 'sp' df['out']=df['qty'].mask(df['code'].ne('sp'), 0) df code qty out 0 sp 20 20 1 wh 30 0 2 sp 10 10 A: You just need to add the parameter axis=1 in the apply() method in order to apply the method on the columns : df['out'] = df.apply(lambda x: x['qty'] if x['code'] == 'sp' else 0, axis=1)
if else condition in pandas with multiple column as arguements
I have a df like so: import pandas as pd df = pd.DataFrame({"code": [sp,wh,sp], "qty": [20, 30, 10]}) I want to create a new column based on data from the two columns with the value the new column as the same as an existing column if a condition is met. This is what I’ve tried: df['out'] = df.apply(lambda x: x['qty']) if x['code'] == 'sp' else 0) so my output in this case should be: df = [ {'code':'sp', 'qty':20, 'out':20} {'code':'wh', 'qty':30, 'out':0} {'code':'sp', 'qty':10, 'out':10} ]
[ "You can use numpy's where:\nimport numpy as np\ndf['out'] = np.where(df['code']=='sp', df['qty'], 0)\n\n", "here is one way to do it using mask\n# mask the qty as zero when code is not 'sp'\n\ndf['out']=df['qty'].mask(df['code'].ne('sp'), 0)\ndf\n\ncode qty out\n0 sp 20 20\n1 wh 30 0\n2 sp 10 10\n\n\n", "You just need to add the parameter axis=1 in the apply() method in order to apply the method on the columns :\ndf['out'] = df.apply(lambda x: x['qty'] if x['code'] == 'sp' else 0, axis=1)\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074591165_dataframe_pandas_python.txt
Q: How to move all items one item forward in a list I'm trying to do the following (consider this list): ['Hello, 'Hi', 'Nice', Cool'] I would like to change 'Hi' to 'Love' But, I wouldn't want it to stay that way: ['Hello, 'Love', 'Nice', Cool'] I'm trying to get ahead of the others, even cropping the last one, getting like this: ['Hello, 'Love', 'Hi', Nice'] Note that Hi passed one along with the entire list, that's what I want! Anybody know? Thanks in advance! A: old_list = ['Hello', 'Hi', 'Nice', 'Cool'] new_item_index = 1 new_item = 'Love' new_list = old_list[0:new_item_index] + [new_item] + old_list[new_item_index+1:] print(old_list) print(new_list) ['Hello', 'Hi', 'Nice', 'Cool'] ['Hello', 'Love', 'Hi', 'Nice'] A: You can insert the item into the desired position, and then remove the last item. Here is the code: # Starting list x = ['Hello', "Hi", 'Nice', 'Cool'] items_to_insert = 'Love' item_to_find = "Hi" if item_to_find in x: x.insert( x.index(item_to_find), items_to_insert) x.pop() print(x) else: print(f"{item_to_find} is not in the list") OUTPUT: ['Hello', 'Love', 'Hi', 'Nice'] Working with integers in the list: x = ['Hello', 6, 'Nice', 'Cool'] items_to_insert = 'Love' item_to_find = 6 if item_to_find in x: x.insert( x.index(item_to_find), items_to_insert) x.pop() print(x) else: print(f"{item_to_find} is not in the list") OUTPUT: ['Hello', 'Love', 6, 'Nice']
How to move all items one item forward in a list
I'm trying to do the following (consider this list): ['Hello, 'Hi', 'Nice', Cool'] I would like to change 'Hi' to 'Love' But, I wouldn't want it to stay that way: ['Hello, 'Love', 'Nice', Cool'] I'm trying to get ahead of the others, even cropping the last one, getting like this: ['Hello, 'Love', 'Hi', Nice'] Note that Hi passed one along with the entire list, that's what I want! Anybody know? Thanks in advance!
[ "old_list = ['Hello', 'Hi', 'Nice', 'Cool']\nnew_item_index = 1\nnew_item = 'Love'\n\nnew_list = old_list[0:new_item_index] + [new_item] + old_list[new_item_index+1:]\nprint(old_list)\nprint(new_list)\n\n['Hello', 'Hi', 'Nice', 'Cool']\n['Hello', 'Love', 'Hi', 'Nice']\n\n", "You can insert the item into the desired position, and then remove the last item.\nHere is the code:\n# Starting list\nx = ['Hello', \"Hi\", 'Nice', 'Cool']\n\nitems_to_insert = 'Love'\nitem_to_find = \"Hi\"\n\nif item_to_find in x:\n x.insert( x.index(item_to_find), items_to_insert)\n x.pop()\n print(x)\nelse:\n print(f\"{item_to_find} is not in the list\")\n\nOUTPUT:\n['Hello', 'Love', 'Hi', 'Nice']\n\n\n\nWorking with integers in the list:\nx = ['Hello', 6, 'Nice', 'Cool']\n\nitems_to_insert = 'Love'\nitem_to_find = 6\n\nif item_to_find in x:\n x.insert( x.index(item_to_find), items_to_insert)\n x.pop()\n print(x)\nelse:\n print(f\"{item_to_find} is not in the list\")\n\nOUTPUT:\n['Hello', 'Love', 6, 'Nice']\n\n" ]
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074591309_list_python.txt
Q: For loop using Pandas dataframe to predict price doesn't append I'm currently using a TensorFlow model that I've made to predict the X next prices for a curve using a for loop that calls the append() fonction of the pandas dataframe. The model is a time series one so at each loop I calculate the "next date" uing the last dataframe row and I calculate the predicted price using the last row of the Dataframe, then I append the new row containing the "next date" and the predicted price to the dataframe so that it can predict the next price in the following loop. The problem is that the dataframe doesn't get appended Here's the code if anyone knows, also if it's not the way that it should be done don't hesitate to correct me I did this knowing that I'm new to the whole TensorFlow / Pandas modules last_data = pd.read_excel("Nickel.xlsx") print('Old dataset before loop : ', last_data) for i in range(10): new_df = last_data.filter(['Valeur']) last_60_days = new_df[-60+(-i):].values last_60_days_scaled = scaler.transform(last_60_days) X_test = [] X_test.append(last_60_days_scaled) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) pred_price = model.predict(X_test) pred_price = scaler.inverse_transform(pred_price) #print('Prix predit : ', pred_price) dernieredate = last_data['Date'].iloc[-1] datecorrect = pd.to_datetime(dernieredate) print('Old date : ', datecorrect) nextdate = datecorrect + pd.to_timedelta(1,unit='d') print('New date : ', nextdate) last_data.append([nextdate, pred_price]) print('New dataset final after loop : ', last_data) Here's the log : Old dataset before loop : Date Valeur 0 2002-09-16 6770 1 2002-09-17 6550 2 2002-09-18 6590 3 2002-09-19 6610 4 2002-09-20 6580 ... ... ... 4995 2022-11-14 27000 4996 2022-11-15 29595 4997 2022-11-16 28550 4998 2022-11-17 26050 4999 2022-11-18 24800 [5000 rows x 2 columns] 1/1 [==============================] - 0s 20ms/step Prix predit : [[26672.488]] Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 22ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 21ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 20ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 22ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 21ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 22ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 21ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 20ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 22ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 New dataset final after loop : Date Valeur 0 2002-09-16 6770 1 2002-09-17 6550 2 2002-09-18 6590 3 2002-09-19 6610 4 2002-09-20 6580 ... ... ... 4995 2022-11-14 27000 4996 2022-11-15 29595 4997 2022-11-16 28550 4998 2022-11-17 26050 4999 2022-11-18 24800 [5000 rows x 2 columns] Thank you a lot! A: Try changing: last_data.append([nextdate, pred_price]) to: last_data = last_data.append([nextdate, pred_price]) or: last_data = pd.concat([nextdate, pred_price]) A: Thank you a lot @9769953 ! The append fonction didn't worked as the list.append() fonction from Python as he said, the solution was assigning the pred_price and next_data to a new variable ! last_data = pd.read_excel("Nickel.xlsx") print('Old dataset before loop : ', last_data) for i in range(10): new_df = last_data.filter(['Valeur']) last_60_days = new_df[-60+(-i):].values last_60_days_scaled = scaler.transform(last_60_days) X_test = [] X_test.append(last_60_days_scaled) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) pred_price = model.predict(X_test) pred_price = scaler.inverse_transform(pred_price) #print('Prix predit : ', pred_price) dernieredate = last_data['Date'].iloc[-1] datecorrect = pd.to_datetime(dernieredate) print('Old date : ', datecorrect) nextdate = datecorrect + pd.to_timedelta(1,unit='d') print('New date : ', nextdate) Data_Temp = {'Date':nextdate, 'Valeur':pred_price[0]} New_data = last_data.append(Data_Temp, ignore_index=True) print('New dataset final after loop : ', New_data) A: the pd.DataFrame.append deprecated since versions 1.4.0 pd.DataFrame.append and pd.concat() is more flexible since you telling that it does not update the Dataframe see the below examples. Sample: Simple codes initialized variables and simulate the shape of the data in the DataFrame. import tensorflow as tf import pandas as pd variables = pd.read_excel('F:\\temp\\20220305\\Book 2.xlsx', , index_col=None, header=[0]) print( 'variables: ' ) print( variables ) print( tf.constant(variables).numpy() ) # (6, 6) print( 'variables.append: ' ) temp = tf.constant(variables.append( pd.DataFrame([[0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 2, 0], [0, 0, 0, 2, 0, 0]]) ) ).numpy() temp = pd.DataFrame( temp ) print( temp ) print( 'variables.append: ' ) print( tf.constant(temp.append( pd.DataFrame([[0, 0, 0, 0, 0, 0, 0, 4]]) ) ).numpy() ) print( 'pd.concat: ' ) temp = tf.constant( pd.concat([ variables, pd.DataFrame([0, 0, 0, 0, 0, 2]) ], axis=1) ).numpy() print( temp ) print( 'pd.concat: ' ) print( tf.constant( pd.concat([ pd.DataFrame(temp), pd.DataFrame([0, 0, 0, 0, 0, 3]) ], axis=1) ).numpy() ) Sample: Create datasets from input as Dataframe variables, inquiry of fixed sizes variables match of data and label. for Index, Image, Label in variables.values: print( Label ) list_label.append( Label ) image = tf.io.read_file( Image ) image = tfio.experimental.image.decode_tiff(image, index=0) list_file_actual.append(image) image = tf.image.resize(image, [32,32], method='nearest') list_Image.append(image) list_label = tf.cast( list_label, dtype=tf.int32 ) list_label = tf.constant( list_label, shape=( 33, 1, 1 ) ) list_Image = tf.cast( list_Image, dtype=tf.int32 ) list_Image = tf.constant( list_Image, shape=( 33, 1, 32, 32, 4 ) ) dataset = tf.data.Dataset.from_tensor_slices(( list_Image, list_label )) Output: Pandas read input from Book 2.xlsx 0 1 2 3 4 5 0 1 0 0 0 0 0 1 0 1 0 0 0 0 2 0 0 1 0 0 0 3 0 0 0 1 0 0 4 0 0 0 0 1 0 5 0 0 0 0 0 1 [[1 0 0 0 0 0] [0 1 0 0 0 0] [0 0 1 0 0 0] [0 0 0 1 0 0] [0 0 0 0 1 0] [0 0 0 0 0 1]] Output: DataFrame.append() at the y-axis : tf.constant(variables.append( pd.DataFrame([[0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 2, 0], [0, 0, 0, 2, 0, 0]]) ) ).numpy() variables.append: 0 1 2 3 4 5 0 1 0 0 0 0 0 1 0 1 0 0 0 0 2 0 0 1 0 0 0 3 0 0 0 1 0 0 4 0 0 0 0 1 0 5 0 0 0 0 0 1 6 0 0 0 0 0 2 7 0 0 0 0 2 0 8 0 0 0 2 0 0 Output: DataFrame.append() at the x-axis : tf.constant(variables.append( pd.DataFrame([[0, 0, 0, 0, 0, 0, 0, 4]]) ) ).numpy() variables.append: [[ 1. 0. 0. 0. 0. 0. nan nan] [ 0. 1. 0. 0. 0. 0. nan nan] [ 0. 0. 1. 0. 0. 0. nan nan] [ 0. 0. 0. 1. 0. 0. nan nan] [ 0. 0. 0. 0. 1. 0. nan nan] [ 0. 0. 0. 0. 0. 1. nan nan] [ 0. 0. 0. 0. 0. 2. nan nan] [ 0. 0. 0. 0. 2. 0. nan nan] [ 0. 0. 0. 2. 0. 0. nan nan] [ 0. 0. 0. 0. 0. 0. 0. 4.]] Output: DataFrame.concat() at the y-axis : tf.constant( pd.concat([ variables, pd.DataFrame([0, 0, 0, 0, 0, 2]) ], axis=1) ).numpy() pd.concat: [[1 0 0 0 0 0 0] [0 1 0 0 0 0 0] [0 0 1 0 0 0 0] [0 0 0 1 0 0 0] [0 0 0 0 1 0 0] [0 0 0 0 0 1 2]] Output: DataFrame.concat() at the x-axis : tf.constant( pd.concat([ pd.DataFrame(variables), pd.DataFrame([0, 0, 0, 0, 0, 3]) ], axis=1) ).numpy() pd.concat: [[1 0 0 0 0 0 0 0] [0 1 0 0 0 0 0 0] [0 0 1 0 0 0 0 0] [0 0 0 1 0 0 0 0] [0 0 0 0 1 0 0 0] [0 0 0 0 0 1 2 3]]
For loop using Pandas dataframe to predict price doesn't append
I'm currently using a TensorFlow model that I've made to predict the X next prices for a curve using a for loop that calls the append() fonction of the pandas dataframe. The model is a time series one so at each loop I calculate the "next date" uing the last dataframe row and I calculate the predicted price using the last row of the Dataframe, then I append the new row containing the "next date" and the predicted price to the dataframe so that it can predict the next price in the following loop. The problem is that the dataframe doesn't get appended Here's the code if anyone knows, also if it's not the way that it should be done don't hesitate to correct me I did this knowing that I'm new to the whole TensorFlow / Pandas modules last_data = pd.read_excel("Nickel.xlsx") print('Old dataset before loop : ', last_data) for i in range(10): new_df = last_data.filter(['Valeur']) last_60_days = new_df[-60+(-i):].values last_60_days_scaled = scaler.transform(last_60_days) X_test = [] X_test.append(last_60_days_scaled) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1)) pred_price = model.predict(X_test) pred_price = scaler.inverse_transform(pred_price) #print('Prix predit : ', pred_price) dernieredate = last_data['Date'].iloc[-1] datecorrect = pd.to_datetime(dernieredate) print('Old date : ', datecorrect) nextdate = datecorrect + pd.to_timedelta(1,unit='d') print('New date : ', nextdate) last_data.append([nextdate, pred_price]) print('New dataset final after loop : ', last_data) Here's the log : Old dataset before loop : Date Valeur 0 2002-09-16 6770 1 2002-09-17 6550 2 2002-09-18 6590 3 2002-09-19 6610 4 2002-09-20 6580 ... ... ... 4995 2022-11-14 27000 4996 2022-11-15 29595 4997 2022-11-16 28550 4998 2022-11-17 26050 4999 2022-11-18 24800 [5000 rows x 2 columns] 1/1 [==============================] - 0s 20ms/step Prix predit : [[26672.488]] Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 22ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 21ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 20ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 22ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 21ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 22ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 21ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 20ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 1/1 [==============================] - 0s 22ms/step Old date : 2022-11-18 00:00:00 New date : 2022-11-19 00:00:00 New dataset final after loop : Date Valeur 0 2002-09-16 6770 1 2002-09-17 6550 2 2002-09-18 6590 3 2002-09-19 6610 4 2002-09-20 6580 ... ... ... 4995 2022-11-14 27000 4996 2022-11-15 29595 4997 2022-11-16 28550 4998 2022-11-17 26050 4999 2022-11-18 24800 [5000 rows x 2 columns] Thank you a lot!
[ "Try changing:\nlast_data.append([nextdate, pred_price])\n\nto:\nlast_data = last_data.append([nextdate, pred_price])\n\nor:\nlast_data = pd.concat([nextdate, pred_price])\n\n", "Thank you a lot @9769953 !\nThe append fonction didn't worked as the list.append() fonction from Python as he said, the solution was assigning the pred_price and next_data to a new variable !\nlast_data = pd.read_excel(\"Nickel.xlsx\")\nprint('Old dataset before loop : ', last_data)\nfor i in range(10):\n new_df = last_data.filter(['Valeur'])\n last_60_days = new_df[-60+(-i):].values\n last_60_days_scaled = scaler.transform(last_60_days)\n X_test = []\n X_test.append(last_60_days_scaled)\n X_test = np.array(X_test)\n X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\n pred_price = model.predict(X_test)\n pred_price = scaler.inverse_transform(pred_price)\n #print('Prix predit : ', pred_price)\n dernieredate = last_data['Date'].iloc[-1]\n datecorrect = pd.to_datetime(dernieredate)\n print('Old date : ', datecorrect)\n nextdate = datecorrect + pd.to_timedelta(1,unit='d')\n print('New date : ', nextdate)\n Data_Temp = {'Date':nextdate, 'Valeur':pred_price[0]}\n New_data = last_data.append(Data_Temp, ignore_index=True)\n \nprint('New dataset final after loop : ', New_data)\n\n", "the pd.DataFrame.append deprecated since versions 1.4.0 pd.DataFrame.append and pd.concat() is more flexible since you telling that it does not update the Dataframe see the below examples.\n\nSample: Simple codes initialized variables and simulate the shape of the data in the DataFrame.\n\nimport tensorflow as tf\nimport pandas as pd\n\n\nvariables = pd.read_excel('F:\\\\temp\\\\20220305\\\\Book 2.xlsx', , index_col=None, header=[0])\nprint( 'variables: ' )\nprint( variables )\nprint( tf.constant(variables).numpy() ) # (6, 6)\nprint( 'variables.append: ' )\ntemp = tf.constant(variables.append( pd.DataFrame([[0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 2, 0], [0, 0, 0, 2, 0, 0]]) ) ).numpy()\ntemp = pd.DataFrame( temp )\nprint( temp ) \nprint( 'variables.append: ' )\nprint( tf.constant(temp.append( pd.DataFrame([[0, 0, 0, 0, 0, 0, 0, 4]]) ) ).numpy() ) \n\n\nprint( 'pd.concat: ' )\ntemp = tf.constant( pd.concat([ variables, pd.DataFrame([0, 0, 0, 0, 0, 2]) ], axis=1) ).numpy()\nprint( temp )\nprint( 'pd.concat: ' )\nprint( tf.constant( pd.concat([ pd.DataFrame(temp), pd.DataFrame([0, 0, 0, 0, 0, 3]) ], axis=1) ).numpy() )\n\n\nSample: Create datasets from input as Dataframe variables, inquiry of fixed sizes variables match of data and label.\n\nfor Index, Image, Label in variables.values:\n print( Label )\n list_label.append( Label )\n\n image = tf.io.read_file( Image )\n image = tfio.experimental.image.decode_tiff(image, index=0)\n list_file_actual.append(image)\n image = tf.image.resize(image, [32,32], method='nearest')\n list_Image.append(image)\n\n list_label = tf.cast( list_label, dtype=tf.int32 )\n list_label = tf.constant( list_label, shape=( 33, 1, 1 ) )\n list_Image = tf.cast( list_Image, dtype=tf.int32 )\n list_Image = tf.constant( list_Image, shape=( 33, 1, 32, 32, 4 ) )\n\ndataset = tf.data.Dataset.from_tensor_slices(( list_Image, list_label ))\n\n\nOutput: Pandas read input from Book 2.xlsx\n\n 0 1 2 3 4 5\n0 1 0 0 0 0 0\n1 0 1 0 0 0 0\n2 0 0 1 0 0 0\n3 0 0 0 1 0 0\n4 0 0 0 0 1 0\n5 0 0 0 0 0 1\n\n[[1 0 0 0 0 0]\n [0 1 0 0 0 0]\n [0 0 1 0 0 0]\n [0 0 0 1 0 0]\n [0 0 0 0 1 0]\n [0 0 0 0 0 1]]\n\n\nOutput: DataFrame.append() at the y-axis : tf.constant(variables.append( pd.DataFrame([[0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 2, 0], [0, 0, 0, 2, 0, 0]]) ) ).numpy()\n\nvariables.append:\n\n 0 1 2 3 4 5\n0 1 0 0 0 0 0\n1 0 1 0 0 0 0\n2 0 0 1 0 0 0\n3 0 0 0 1 0 0\n4 0 0 0 0 1 0\n5 0 0 0 0 0 1\n6 0 0 0 0 0 2\n7 0 0 0 0 2 0\n8 0 0 0 2 0 0\n\n\nOutput: DataFrame.append() at the x-axis : tf.constant(variables.append( pd.DataFrame([[0, 0, 0, 0, 0, 0, 0, 4]]) ) ).numpy()\n\nvariables.append:\n\n[[ 1. 0. 0. 0. 0. 0. nan nan]\n [ 0. 1. 0. 0. 0. 0. nan nan]\n [ 0. 0. 1. 0. 0. 0. nan nan]\n [ 0. 0. 0. 1. 0. 0. nan nan]\n [ 0. 0. 0. 0. 1. 0. nan nan]\n [ 0. 0. 0. 0. 0. 1. nan nan]\n [ 0. 0. 0. 0. 0. 2. nan nan]\n [ 0. 0. 0. 0. 2. 0. nan nan]\n [ 0. 0. 0. 2. 0. 0. nan nan]\n [ 0. 0. 0. 0. 0. 0. 0. 4.]]\n\n\nOutput: DataFrame.concat() at the y-axis : tf.constant( pd.concat([ variables, pd.DataFrame([0, 0, 0, 0, 0, 2]) ], axis=1) ).numpy()\n\npd.concat:\n[[1 0 0 0 0 0 0]\n [0 1 0 0 0 0 0]\n [0 0 1 0 0 0 0]\n [0 0 0 1 0 0 0]\n [0 0 0 0 1 0 0]\n [0 0 0 0 0 1 2]]\n\n\nOutput: DataFrame.concat() at the x-axis : tf.constant( pd.concat([ pd.DataFrame(variables), pd.DataFrame([0, 0, 0, 0, 0, 3]) ], axis=1) ).numpy()\n\npd.concat:\n[[1 0 0 0 0 0 0 0]\n [0 1 0 0 0 0 0 0]\n [0 0 1 0 0 0 0 0]\n [0 0 0 1 0 0 0 0]\n [0 0 0 0 1 0 0 0]\n [0 0 0 0 0 1 2 3]]\n\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python", "tensorflow" ]
stackoverflow_0074590893_dataframe_jupyter_notebook_pandas_python_tensorflow.txt
Q: How to correct the count number after groupby? I am trying to get a dataframe which has Date and Section to count the items in each Section per hour. I use the following: new_df = df.groupby([pd.Grouper(key='Date',freq='H'),'Section']).agg(PPT=('Section','count')).reset_index() The problem is that the count does not take into account the 0 values. I have tried so many variations of groupby and Grouper and could not solve it. I am trying to get the count for each hour according to each Section, even if the count if the count 0. Please let me know if I was not clear, I will try to come up with example. A: I found the answer in another thread: I added .unstack(fill_value=0).stack().reset_index()
How to correct the count number after groupby?
I am trying to get a dataframe which has Date and Section to count the items in each Section per hour. I use the following: new_df = df.groupby([pd.Grouper(key='Date',freq='H'),'Section']).agg(PPT=('Section','count')).reset_index() The problem is that the count does not take into account the 0 values. I have tried so many variations of groupby and Grouper and could not solve it. I am trying to get the count for each hour according to each Section, even if the count if the count 0. Please let me know if I was not clear, I will try to come up with example.
[ "I found the answer in another thread: I added\n.unstack(fill_value=0).stack().reset_index()\n\n" ]
[ 1 ]
[]
[]
[ "aggregate", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074586456_aggregate_dataframe_group_by_pandas_python.txt
Q: TKinter weird behavior using grid location manager with arguments row=0, column=0 I'm using two frames to organize my main frame into two subframes. One subframe is one the left and it contains a few buttons and a label. The subframe on the right contains a treeview. The items in the left_frame don't show up when I use the arguments row=0, column=0 as show in the example below. class MainFrame(ttk.Frame): def __init__(self, container): super().__init__(container) # containers self.left_frame = ttk.Frame() # contains all the buttons and icons on the left self.left_frame.grid(row=0, column=0) self.right_frame = ttk.Frame() # contains the spreadsheet preview self.right_frame.grid(row=0, column=1) # labels self.label = ttk.Label(self.left_frame, text="Platzhalter für Icon") self.label.grid(row=0, column=0) # buttons self.analyse_button = ttk.Button(self.left_frame, text="auswählen") self.analyse_button.grid(row=1, column=0) self.analyse_button = ttk.Button(self.left_frame, text="importieren") self.analyse_button.grid(row=2, column=0) self.rate_button = ttk.Button(self.left_frame, text="bewerten") self.rate_button.grid(row=3, column=0) self.rate_button1 = ttk.Button(self.left_frame, text="analysieren") self.rate_button1.grid(row=4, column=0) # treeview widget for spreadsheets self.sp_preview = ttk.Treeview(self.right_frame) self.sp_preview.grid(row=0, column=0) If I change the code as below self.left_frame.grid(row=0, column=1) self.right_frame.grid(row=0, column=2) it works as intended. But that feels wrong, because I'm not using column 0. A: It is most likely because you did not specify the parent of left_frame and right_frame, so they will be children of root window, not instance of MainFrame. If instance of MainFrame or other frame is also a child of root window and put in row 0 and column 0 as well, it may overlap/cover left_frame. Set the parent of the two frames to self may fix the issue: class MainFrame(ttk.Frame): def __init__(self, container): super().__init__(container) # containers self.left_frame = ttk.Frame(self) # contains all the buttons and icons on the left self.left_frame.grid(row=0, column=0) self.right_frame = ttk.Frame(self) # contains the spreadsheet preview self.right_frame.grid(row=0, column=1) ...
TKinter weird behavior using grid location manager with arguments row=0, column=0
I'm using two frames to organize my main frame into two subframes. One subframe is one the left and it contains a few buttons and a label. The subframe on the right contains a treeview. The items in the left_frame don't show up when I use the arguments row=0, column=0 as show in the example below. class MainFrame(ttk.Frame): def __init__(self, container): super().__init__(container) # containers self.left_frame = ttk.Frame() # contains all the buttons and icons on the left self.left_frame.grid(row=0, column=0) self.right_frame = ttk.Frame() # contains the spreadsheet preview self.right_frame.grid(row=0, column=1) # labels self.label = ttk.Label(self.left_frame, text="Platzhalter für Icon") self.label.grid(row=0, column=0) # buttons self.analyse_button = ttk.Button(self.left_frame, text="auswählen") self.analyse_button.grid(row=1, column=0) self.analyse_button = ttk.Button(self.left_frame, text="importieren") self.analyse_button.grid(row=2, column=0) self.rate_button = ttk.Button(self.left_frame, text="bewerten") self.rate_button.grid(row=3, column=0) self.rate_button1 = ttk.Button(self.left_frame, text="analysieren") self.rate_button1.grid(row=4, column=0) # treeview widget for spreadsheets self.sp_preview = ttk.Treeview(self.right_frame) self.sp_preview.grid(row=0, column=0) If I change the code as below self.left_frame.grid(row=0, column=1) self.right_frame.grid(row=0, column=2) it works as intended. But that feels wrong, because I'm not using column 0.
[ "It is most likely because you did not specify the parent of left_frame and right_frame, so they will be children of root window, not instance of MainFrame.\nIf instance of MainFrame or other frame is also a child of root window and put in row 0 and column 0 as well, it may overlap/cover left_frame.\nSet the parent of the two frames to self may fix the issue:\nclass MainFrame(ttk.Frame):\n def __init__(self, container):\n super().__init__(container)\n\n # containers\n self.left_frame = ttk.Frame(self) # contains all the buttons and icons on the left\n self.left_frame.grid(row=0, column=0)\n\n self.right_frame = ttk.Frame(self) # contains the spreadsheet preview\n self.right_frame.grid(row=0, column=1)\n\n ...\n\n" ]
[ 2 ]
[]
[]
[ "python", "tkinter", "ttk", "user_interface" ]
stackoverflow_0074591158_python_tkinter_ttk_user_interface.txt
Q: How to locate a block with certain text using python selenium With selenium in python, I want to collect data about a user called "GrahamDumpleton" on the website below: https://github.com/GrahamDumpleton/wrapt/graphs/contributors And this is the block I want to locate with the user name "GrahamDumpleton": How to locate this block using selenium? Thank you. A: This can be clearly done with XPath since XPath is the only approach supporting locating elements based on their text content. So, that user block element can be located with the following XPath: //li[contains(@class,'contrib-person')][contains(.,'Graham')] In case you want only the header part of that block this XPath can be used: //h3[contains(@class,'border-bottom')][contains(.,'Graham')] So, Selenium code returning those elements can be correspondingly driver.find_elements(By.XPATH, "//li[contains(@class,'contrib-person')][contains(.,'Graham')]") And driver.find_elements(By.XPATH, "//h3[contains(@class,'border-bottom')][contains(.,'Graham')]")
How to locate a block with certain text using python selenium
With selenium in python, I want to collect data about a user called "GrahamDumpleton" on the website below: https://github.com/GrahamDumpleton/wrapt/graphs/contributors And this is the block I want to locate with the user name "GrahamDumpleton": How to locate this block using selenium? Thank you.
[ "This can be clearly done with XPath since XPath is the only approach supporting locating elements based on their text content.\nSo, that user block element can be located with the following XPath:\n//li[contains(@class,'contrib-person')][contains(.,'Graham')]\n\nIn case you want only the header part of that block this XPath can be used:\n//h3[contains(@class,'border-bottom')][contains(.,'Graham')]\n\nSo, Selenium code returning those elements can be correspondingly\ndriver.find_elements(By.XPATH, \"//li[contains(@class,'contrib-person')][contains(.,'Graham')]\")\n\nAnd\ndriver.find_elements(By.XPATH, \"//h3[contains(@class,'border-bottom')][contains(.,'Graham')]\")\n\n" ]
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping", "xpath" ]
stackoverflow_0074591353_python_selenium_selenium_webdriver_web_scraping_xpath.txt
Q: How to sum random.choices? I have a list of songs: my_favorite_songs = [ ['Waste a Moment', 3.03], ['New Salvation', 4.02], ['Staying\' Alive', 3.40], ['Out of Touch', 3.03], ['A Sorta Fairytale', 5.28], ['Easy', 4.15], ['Beautiful Day', 4.04], ['Nowhere to Run', 2.58], ['In This World', 4.02], My task is to find a sum of 3 random songs? Can you please help me with that? I tried this res = sum(random.choices(time, k=3)), but had an error. A: Try sum([x[1] for x in random.choices(my_favorite_songs, k=3)])
How to sum random.choices?
I have a list of songs: my_favorite_songs = [ ['Waste a Moment', 3.03], ['New Salvation', 4.02], ['Staying\' Alive', 3.40], ['Out of Touch', 3.03], ['A Sorta Fairytale', 5.28], ['Easy', 4.15], ['Beautiful Day', 4.04], ['Nowhere to Run', 2.58], ['In This World', 4.02], My task is to find a sum of 3 random songs? Can you please help me with that? I tried this res = sum(random.choices(time, k=3)), but had an error.
[ "Try\nsum([x[1] for x in random.choices(my_favorite_songs, k=3)])\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074591489_python.txt
Q: Take random samples from the data with different number each time I have a pandas dataframe that I want to randomly pick samples from it. The first time I want to pick 10, then 20, 30, 40, and 50 random samples (without replacment). I'm trying to do it with a for loop, altough I don't know how good this is cause a list can't contain data frames, right? (my coding is better with R and there the lists can contain dataframes). number = [10,20,30,40,50] sample = [] for i in range(len(number)): sample[i].append(data.sample(n = number[i])) And the error is IndexError: list index out of range I dont want to copy past the code so what is the right way to do it? A: You could do that using radint method for choosing random element from the list number: import random number = [10,20,30,40,50] sample = [] for i in range(len(number)): sample.append(data.sample(n = number[random.randint(0, len(number)-1])) Update: Assuming you have this dataframe for Movies Rating dataset: data = [['avengers', 5.4 ,'PG-13'], ['captain america', 6.7, 'PG-13'], ['spiderman', 7, 'R'], ['daredevil', 8.2, 'R'], ['iron man', 8.6, 'PG-13'], ['deadpool', 10, 'R']] df = pd.DataFrame(data, columns=['title', 'score', 'rating']) You can take random samples from it using sample method: # taking random 3 records from dataframe samples = df.sample(3) Output: title score rating 1 captain america 6.7 PG-13 5 deadpool 10.0 R 3 daredevil 8.2 R Another execution: title score rating 4 iron man 8.6 PG-13 0 avengers 5.4 PG-13 2 spiderman 7.0 R Also you can randomize the number of samples according to your dataframe # of rows: df.sample(random.randint(1, len(df))) Alternate Approach: If you want you could write your own function for generating random samples from dataframe in this way: import random def generate_rand_sample(df): start_i = end_i = 0 while end_i == start_i: start_i = random.randint(0, len(df) - 1) end_i = random.randint(start_i, len(df)) return df.iloc[start_i:end_i] generate_rand_sample(df) First Run: title score rating 1 captain america 6.7 PG-13 2 spiderman 7.0 R Second Run: title score rating 2 spiderman 7.0 R 3 daredevil 8.2 R 4 iron man 8.6 PG-13 5 deadpool 10.0 R A: Try range(len(number)-1). The reason is for loop starts from 0 to n. So in this case it will start from 0 then till 5. Which makes a total of 6 loops (0,1,2,3,4,5). That's why your list goes out of range
Take random samples from the data with different number each time
I have a pandas dataframe that I want to randomly pick samples from it. The first time I want to pick 10, then 20, 30, 40, and 50 random samples (without replacment). I'm trying to do it with a for loop, altough I don't know how good this is cause a list can't contain data frames, right? (my coding is better with R and there the lists can contain dataframes). number = [10,20,30,40,50] sample = [] for i in range(len(number)): sample[i].append(data.sample(n = number[i])) And the error is IndexError: list index out of range I dont want to copy past the code so what is the right way to do it?
[ "You could do that using radint method for choosing random element from the list number:\nimport random \nnumber = [10,20,30,40,50]\nsample = []\nfor i in range(len(number)):\n sample.append(data.sample(n = number[random.randint(0, len(number)-1]))\n\nUpdate:\nAssuming you have this dataframe for Movies Rating dataset:\ndata = [['avengers', 5.4 ,'PG-13'],\n['captain america', 6.7, 'PG-13'],\n['spiderman', 7, 'R'],\n['daredevil', 8.2, 'R'],\n['iron man', 8.6, 'PG-13'],\n['deadpool', 10, 'R']]\n\ndf = pd.DataFrame(data, columns=['title', 'score', 'rating'])\n\nYou can take random samples from it using sample method:\n# taking random 3 records from dataframe\nsamples = df.sample(3)\n\nOutput:\n title score rating\n1 captain america 6.7 PG-13\n5 deadpool 10.0 R\n3 daredevil 8.2 R\n\nAnother execution:\n title score rating\n4 iron man 8.6 PG-13\n0 avengers 5.4 PG-13\n2 spiderman 7.0 R\n\nAlso you can randomize the number of samples according to your dataframe # of rows:\ndf.sample(random.randint(1, len(df)))\n\nAlternate Approach:\nIf you want you could write your own function for generating random samples from dataframe in this way:\nimport random \ndef generate_rand_sample(df):\n start_i = end_i = 0\n while end_i == start_i:\n start_i = random.randint(0, len(df) - 1)\n end_i = random.randint(start_i, len(df))\n return df.iloc[start_i:end_i]\n\ngenerate_rand_sample(df)\n\nFirst Run:\n title score rating\n1 captain america 6.7 PG-13\n2 spiderman 7.0 R\n\nSecond Run:\n title score rating\n2 spiderman 7.0 R\n3 daredevil 8.2 R\n4 iron man 8.6 PG-13\n5 deadpool 10.0 R\n\n", "Try range(len(number)-1). The reason is for loop starts from 0 to n. So in this case it will start from 0 then till 5. Which makes a total of 6 loops (0,1,2,3,4,5). That's why your list goes out of range\n" ]
[ 0, 0 ]
[]
[]
[ "pandas", "python", "random" ]
stackoverflow_0074591439_pandas_python_random.txt
Q: ModuleNotFoundError with a python requests library Is anyone else receiving a moduleNotFoundError with their requests library? Not sure why this is happening. The library is installed as well which is even more confusing. import csv from datetime import datetime import requests from bs4 import BeautifulSoup and the resulting error was this: --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In [1], line 4 2 import csv 3 from datetime import datetime ----> 4 import requests 5 from bs4 import BeautifulSoup ModuleNotFoundError: No module named 'requests' when i run pip freeze I can confirm I have requests installed as well, see below: Screenshot from my terminal I have requests version requests==2.28.1 A: Most likely, you don't have the requests module installed. Run the following command: pip install requests to install the package. A: corrected the error by referencing this question (i didnt see it when I first searched) running sudo pip3 install requests and it recognized the library now.
ModuleNotFoundError with a python requests library
Is anyone else receiving a moduleNotFoundError with their requests library? Not sure why this is happening. The library is installed as well which is even more confusing. import csv from datetime import datetime import requests from bs4 import BeautifulSoup and the resulting error was this: --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In [1], line 4 2 import csv 3 from datetime import datetime ----> 4 import requests 5 from bs4 import BeautifulSoup ModuleNotFoundError: No module named 'requests' when i run pip freeze I can confirm I have requests installed as well, see below: Screenshot from my terminal I have requests version requests==2.28.1
[ "Most likely, you don't have the requests module installed. Run the following command:\npip install requests to install the package.\n", "corrected the error by referencing this question (i didnt see it when I first searched)\nrunning sudo pip3 install requests and it recognized the library now.\n" ]
[ 0, 0 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0074584661_pip_python_python_3.x.txt
Q: How to round Matrix elements in sympy? As we know from sympy import * x = sin(pi/4) y = sin(pi/5) A = Matrix([x, y]) print(x) print(A.evalf()) displays sqrt(2)/2 Matrix([[0.707106781186548], [0.587785252292473]]) So print(round(x.evalf(), 3)) print(round(y.evalf(), 3)) displays 0.707 0.588 But how can we round all the elements in a Matrix in a terse way, so that print(roundMatrix(A, 3)) can displays Matrix([[0.707], [0.588]]) A: Why you do not use method evalf with args like evalf(3)? from sympy import * x = sin(pi/4) y = sin(pi/5) A = Matrix([x, y]) print(x) print(A.evalf(3)) Output sqrt(2)/2 Matrix([[0.707], [0.588]]) A: This works for me # Z is a matrix from functools import partial round3 = partial(round, ndigits=3) Z.applyfunc(round3) # if you want to save the result # Z = Z.applyfunc(round3) A: from sympy import * roundMatrix = lambda m, n: Matrix([[round(m[x, y], n) for y in range(m.shape[1])] for x in range(m.shape[0])]) x = sin(pi/4) y = sin(pi/5) A = Matrix([x, y]) print(x) print(roundMatrix(A.evalf(), 3))`
How to round Matrix elements in sympy?
As we know from sympy import * x = sin(pi/4) y = sin(pi/5) A = Matrix([x, y]) print(x) print(A.evalf()) displays sqrt(2)/2 Matrix([[0.707106781186548], [0.587785252292473]]) So print(round(x.evalf(), 3)) print(round(y.evalf(), 3)) displays 0.707 0.588 But how can we round all the elements in a Matrix in a terse way, so that print(roundMatrix(A, 3)) can displays Matrix([[0.707], [0.588]])
[ "Why you do not use method evalf with args like evalf(3)?\nfrom sympy import *\n\nx = sin(pi/4)\ny = sin(pi/5)\n\nA = Matrix([x, y])\n\nprint(x)\nprint(A.evalf(3))\n\nOutput\nsqrt(2)/2\nMatrix([[0.707], [0.588]])\n\n", "This works for me\n# Z is a matrix\nfrom functools import partial\n\nround3 = partial(round, ndigits=3)\nZ.applyfunc(round3)\n# if you want to save the result\n# Z = Z.applyfunc(round3)\n\n", "from sympy import *\n\nroundMatrix = lambda m, n: Matrix([[round(m[x, y], n) for y in range(m.shape[1])] for x in range(m.shape[0])])\n\nx = sin(pi/4)\ny = sin(pi/5)\n\nA = Matrix([x, y])\n\nprint(x)\nprint(roundMatrix(A.evalf(), 3))`\n\n" ]
[ 3, 1, 0 ]
[]
[]
[ "python", "rounding", "sympy" ]
stackoverflow_0053844884_python_rounding_sympy.txt
Q: Find values of specific parameters from XML I have tried this approach but it doesn't work for me. I want to get the releaseDate value from the below xml <Product prodID="bed" lang="en"> <ProductState stateType="Published" stateDateTime="2019-04" testDate="2019-04" releaseDate="2019"/> I have tried the below code: from pathlib import Path import os import tempfile import xml.etree.ElementTree as ET xmlfile = 'path_to_xml' tree = ET.parse(xmlfile) root = tree.getroot() for elm in root.findall("./Product/ProductStatus/releaseDate"): print(elm.attrib) A: Listing [Python.Docs]: xml.etree.ElementTree - The ElementTree XML API. Considering this exact XML blob, there are 2 errors in your code: The root node is Product node, so if you search for (other) Product sub-nodes it won't find anything releaseDate is an attribute (not a tag) so it doesn't belong in the path Here''s an example. blob.xml <?xml version="1.0" encoding="UTF-8"?> <Product prodID="bed" lang="en"> <ProductState stateType="Published" stateDateTime="2019-04" testDate="2019-04" releaseDate="2019"/> <!-- Other nodes --> </Product> code00.py: #!/usr/bin/env python import sys import xml.etree.ElementTree as ET def main(*argv): xmlfile = "./blob.xml" root = ET.parse(xmlfile).getroot() print("Root node:", root) for product_state_node in root.findall("ProductState"): print("Release date: ", product_state_node.attrib.get("releaseDate")) if __name__ == "__main__": print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform)) rc = main(*sys.argv[1:]) print("\nDone.\n") sys.exit(rc) Output: [cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q074401612]> "e:\Work\Dev\VEnvs\py_pc064_03.09_test0\Scripts\python.exe" ./code00.py Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32 Root node: <Element 'Product' at 0x0000020698C4A860> Release date: 2019 Done. Although for this simple example it's might not be the case I prefer XPath when iterating XML trees. For more details you could check (there are many more): [SO]: get attribute of and iter only with elementTree (@CristiFati's answer) [SO]: Parsing XML by specifying name of child where multiple exist (@CristiFati's answer) [SO]: parsing some XML fields to text file in python (@CristiFati's answer) A: With .get("attributeName") you can ask for the attribute value of your interest tag. If you change your code to: for elm in root.findall("ProductState"): print(elm.get("releaseDate")) it will work, if Product is your root. print(elm.attrib) # prints all attributes as a dic of key:values
Find values of specific parameters from XML
I have tried this approach but it doesn't work for me. I want to get the releaseDate value from the below xml <Product prodID="bed" lang="en"> <ProductState stateType="Published" stateDateTime="2019-04" testDate="2019-04" releaseDate="2019"/> I have tried the below code: from pathlib import Path import os import tempfile import xml.etree.ElementTree as ET xmlfile = 'path_to_xml' tree = ET.parse(xmlfile) root = tree.getroot() for elm in root.findall("./Product/ProductStatus/releaseDate"): print(elm.attrib)
[ "Listing [Python.Docs]: xml.etree.ElementTree - The ElementTree XML API.\nConsidering this exact XML blob, there are 2 errors in your code:\n\nThe root node is Product node, so if you search for (other) Product sub-nodes it won't find anything\n\nreleaseDate is an attribute (not a tag) so it doesn't belong in the path\n\n\nHere''s an example.\nblob.xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Product prodID=\"bed\" lang=\"en\"> \n <ProductState stateType=\"Published\" stateDateTime=\"2019-04\" testDate=\"2019-04\" releaseDate=\"2019\"/>\n <!-- Other nodes -->\n</Product>\n\ncode00.py:\n#!/usr/bin/env python\n\nimport sys\nimport xml.etree.ElementTree as ET\n\n\ndef main(*argv):\n xmlfile = \"./blob.xml\"\n root = ET.parse(xmlfile).getroot()\n print(\"Root node:\", root)\n for product_state_node in root.findall(\"ProductState\"):\n print(\"Release date: \", product_state_node.attrib.get(\"releaseDate\"))\n\n\nif __name__ == \"__main__\":\n print(\"Python {:s} {:03d}bit on {:s}\\n\".format(\" \".join(elem.strip() for elem in sys.version.split(\"\\n\")),\n 64 if sys.maxsize > 0x100000000 else 32, sys.platform))\n rc = main(*sys.argv[1:])\n print(\"\\nDone.\\n\")\n sys.exit(rc)\n\nOutput:\n\n[cfati@CFATI-5510-0:e:\\Work\\Dev\\StackOverflow\\q074401612]> \"e:\\Work\\Dev\\VEnvs\\py_pc064_03.09_test0\\Scripts\\python.exe\" ./code00.py\nPython 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32\n\nRoot node: <Element 'Product' at 0x0000020698C4A860>\nRelease date: 2019\n\nDone.\n\n\nAlthough for this simple example it's might not be the case I prefer XPath when iterating XML trees. For more details you could check (there are many more):\n\n[SO]: get attribute of and iter only with elementTree (@CristiFati's answer)\n\n[SO]: Parsing XML by specifying name of child where multiple exist (@CristiFati's answer)\n\n[SO]: parsing some XML fields to text file in python (@CristiFati's answer)\n\n\n", "With .get(\"attributeName\") you can ask for the attribute value of your interest tag.\nIf you change your code to:\nfor elm in root.findall(\"ProductState\"):\n print(elm.get(\"releaseDate\"))\n\nit will work, if Product is your root.\nprint(elm.attrib) # prints all attributes as a dic of key:values\n\n" ]
[ 1, 0 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0074401612_python_xml_xml_parsing.txt
Q: Linked list implementation in python issue I have been trying to implement a linked-list in python.Any call of a variable inside a function in Python is by default call by reference.I have this code: For the list_node: class list_node: def __init__(self,obj,next_listnode): self.obj = obj self.next_listnode = next_listnode For the linked_list: class linked_list: def __init__(self,list_node): self.list_node =list_node def add_node(self,obj): current = self.list_node while(current.next_listnode is not None): current = current.next_listnode current.next_listnode = obj; def print_linkedlist(self): current = self.list_node while(current.next_listnode is not None): print("",current.obj) print("\n") current = current.next_listnode I I create 2 list_nodes 1 of which I add it as the initial list_node of the linked list and the other using the function add_node: A = list_node("John",None) B = list_node("Mike",None) liste = linked_list(A) liste.add_node(B) liste.print_linkedlist(); However when I call the print_linkedlist function it only prints A list_node What am I doing wrong? However I tried not calling the add_node function but it didnt print anything. A: If you add one more node to your list, the problem becomes a bit more clear: A = list_node("John",None) B = list_node("Mike",None) C = list_node("Biff",None) liste = linked_list(A) liste.add_node(B) liste.add_node(C) liste.print_linkedlist() This prints "John" and "Mike" -- so the problem isn't that you're only printing the first node, it's that you're not printing the last node. That's because your print_linkedlist function stops iterating when current.next_listnode is not None -- i.e. it will stop as soon as it reaches the last node (the one with no "next" node), and it won't print that node. I'd suggest doing this instead: def print_linkedlist(self): current = self.list_node while current: print(current.obj) current = current.next_listnode in order to print all nodes of the list.
Linked list implementation in python issue
I have been trying to implement a linked-list in python.Any call of a variable inside a function in Python is by default call by reference.I have this code: For the list_node: class list_node: def __init__(self,obj,next_listnode): self.obj = obj self.next_listnode = next_listnode For the linked_list: class linked_list: def __init__(self,list_node): self.list_node =list_node def add_node(self,obj): current = self.list_node while(current.next_listnode is not None): current = current.next_listnode current.next_listnode = obj; def print_linkedlist(self): current = self.list_node while(current.next_listnode is not None): print("",current.obj) print("\n") current = current.next_listnode I I create 2 list_nodes 1 of which I add it as the initial list_node of the linked list and the other using the function add_node: A = list_node("John",None) B = list_node("Mike",None) liste = linked_list(A) liste.add_node(B) liste.print_linkedlist(); However when I call the print_linkedlist function it only prints A list_node What am I doing wrong? However I tried not calling the add_node function but it didnt print anything.
[ "If you add one more node to your list, the problem becomes a bit more clear:\nA = list_node(\"John\",None)\nB = list_node(\"Mike\",None)\nC = list_node(\"Biff\",None)\nliste = linked_list(A)\nliste.add_node(B)\nliste.add_node(C)\n\nliste.print_linkedlist()\n\nThis prints \"John\" and \"Mike\" -- so the problem isn't that you're only printing the first node, it's that you're not printing the last node.\nThat's because your print_linkedlist function stops iterating when current.next_listnode is not None -- i.e. it will stop as soon as it reaches the last node (the one with no \"next\" node), and it won't print that node.\nI'd suggest doing this instead:\n def print_linkedlist(self):\n current = self.list_node\n while current:\n print(current.obj)\n current = current.next_listnode\n\nin order to print all nodes of the list.\n" ]
[ 1 ]
[]
[]
[ "class", "linked_list", "pass_by_reference", "python" ]
stackoverflow_0074591485_class_linked_list_pass_by_reference_python.txt
Q: How to plot a vertical thermal plot in Matplotlib? Hi Anyone has an idea about how to plot this kind of thermal plot in python?. I tried to search any sample plot like this, but didn't find. Highly appreciate if someone can help me to draw a graph like this. This image I got from the internet. I want to plot something same like this A: FROM TO 3 weeks later… Probably the OP resorted to display their time dependent temperature field with, surprise! a heat map, so that, notwithstanding the fact that SO is not a code writing service, I feel free to answer their question. First and above all, this is an exercise, to represent this type of data the canonical solution is, of course, a heat map. Here it is the code to produce both the figures at the top of this post. Enjoy . import numpy as np import matplotlib.pyplot as plt t = np.linspace(0, 5, 501) x = np.linspace(0, 1, 201)[:, None] T = 50 + (30-6*t)*(4*x*(1-x)) + 4*t fig, ax = plt.subplots(layout='constrained') hm = ax.imshow(T, cmap='plasma', aspect='auto', origin='lower', extent=(0, 5, 0, 1)) fig.colorbar(hm) def heat_lines(x, t, T, n): from matplotlib.cm import ScalarMappable from matplotlib.collections import LineCollection lx, lt = T.shape ones = np.ones(lx) norm = plt.Normalize(np.min(T), np.max(T)) plasma = plt.cm.plasma fig, ax = plt.subplots(figsize=(1+1.2*n, 9), layout='constrained') ax.set_xlim((-0.6, n-0.4)) ax.set_ylim((x[0], x[-1])) ax.set_xticks(range(n)) ax.tick_params(right=False,top=False, bottom=False) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.grid(axis='y') fig.colorbar(ScalarMappable(cmap=plasma, norm=norm)) dt = round(lt/(n-1)) for pos, ix in enumerate(range(0, len(t)+dt//2, dt)): points = np.array([ones*pos, x[:,0]]).T.reshape(-1,1,2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection(segments, linewidth=72, ec=None, color=plasma(norm(T[:,ix]))) lc.set_array(T[:,ix]) ax.add_collection(lc) heat_lines(x, t, T, 6) PS : I have NOT waited three weeks to answer, I've found the question yesterday night and I was intrigued...
How to plot a vertical thermal plot in Matplotlib?
Hi Anyone has an idea about how to plot this kind of thermal plot in python?. I tried to search any sample plot like this, but didn't find. Highly appreciate if someone can help me to draw a graph like this. This image I got from the internet. I want to plot something same like this
[ "FROM\n\nTO\n\n\n3 weeks later…\nProbably the OP resorted to display their time dependent temperature field with, surprise! a heat map, so that, notwithstanding the fact that SO is not a code writing service, I feel free to answer their question.\nFirst and above all, this is an exercise, to represent this type of data the canonical solution is, of course, a heat map. Here it is the code to produce both the figures at the top of this post. Enjoy .\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nt = np.linspace(0, 5, 501)\nx = np.linspace(0, 1, 201)[:, None]\n\n\nT = 50 + (30-6*t)*(4*x*(1-x)) + 4*t\n\nfig, ax = plt.subplots(layout='constrained')\nhm = ax.imshow(T, cmap='plasma',\n aspect='auto', origin='lower', extent=(0, 5, 0, 1))\nfig.colorbar(hm)\n\ndef heat_lines(x, t, T, n):\n from matplotlib.cm import ScalarMappable\n from matplotlib.collections import LineCollection\n\n lx, lt = T.shape\n ones = np.ones(lx)\n norm = plt.Normalize(np.min(T), np.max(T))\n plasma = plt.cm.plasma\n \n fig, ax = plt.subplots(figsize=(1+1.2*n, 9), layout='constrained')\n ax.set_xlim((-0.6, n-0.4))\n ax.set_ylim((x[0], x[-1]))\n ax.set_xticks(range(n))\n ax.tick_params(right=False,top=False, bottom=False)\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.spines[\"bottom\"].set_visible(False)\n ax.grid(axis='y')\n fig.colorbar(ScalarMappable(cmap=plasma, norm=norm))\n\n dt = round(lt/(n-1))\n for pos, ix in enumerate(range(0, len(t)+dt//2, dt)):\n points = np.array([ones*pos, x[:,0]]).T.reshape(-1,1,2) \n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n lc = LineCollection(segments, linewidth=72, ec=None,\n color=plasma(norm(T[:,ix])))\n lc.set_array(T[:,ix])\n ax.add_collection(lc)\n\nheat_lines(x, t, T, 6)\n\n\nPS : I have NOT waited three weeks to answer, I've found the question yesterday night and I was intrigued...\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "plot", "python", "seaborn" ]
stackoverflow_0074356558_matplotlib_plot_python_seaborn.txt
Q: I want to create custom signup form and add extra fields in Django default user model I want to add full name instead of first and last name and I also want to add some others fields like address, phone number, city. from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): full_name=forms.CharField(max_length=50,required=True) phone_number=forms.CharField(widget=forms.TextInput(attrs={'type':'number'})) address=forms.CharField(max_length=200,required=True) city=forms.CharField(max_length=200,required=True) class Meta: model = User fields = ('username', 'email', 'password1', 'password2','full_name','phone_number','address','city') def register(self): self.save() I created form by using this method. First, created forms.py for extra fields then inherited it. It is working; but still some fields disappear. A: Because, you are adding additional fields to the default user model. First you have to -Create a Custom User Model by using AbstractUser Then -Create a Custom Form for UserCreationForm You can search google for: Extend-existing-user-model-in-django
I want to create custom signup form and add extra fields in Django default user model
I want to add full name instead of first and last name and I also want to add some others fields like address, phone number, city. from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): full_name=forms.CharField(max_length=50,required=True) phone_number=forms.CharField(widget=forms.TextInput(attrs={'type':'number'})) address=forms.CharField(max_length=200,required=True) city=forms.CharField(max_length=200,required=True) class Meta: model = User fields = ('username', 'email', 'password1', 'password2','full_name','phone_number','address','city') def register(self): self.save() I created form by using this method. First, created forms.py for extra fields then inherited it. It is working; but still some fields disappear.
[ "Because, you are adding additional fields to the default user model. First you have to\n-Create a Custom User Model by using AbstractUser\nThen\n-Create a Custom Form for UserCreationForm\nYou can search google for:\nExtend-existing-user-model-in-django\n" ]
[ 0 ]
[]
[]
[ "django", "forms", "model", "python" ]
stackoverflow_0074591257_django_forms_model_python.txt
Q: how to return user email on google api, python ive been trying to use google sheets api for a project and for this project it requires the users email to be compaired to a list of emails in the sheets and only return the rows with the users email in. so if the google sheets as A _______________________ B personA@gmail.com ___apples personB@gmail.con ___ bananas personC@gmail.com __ oranges and you log into the app using personB@gmail.com then the code returns bananas, without returning apples and oranges because those are associated with other emails. but I haven't been able to get the email that the user authenticated with to return. and most other solutions where either too old and couldn't run on modern python (3.4.10) or where in different languages entirely. and I don't want to have to have the user enter their email twice. I have code that I've attempted to use but its mostly irrelevant as the fixes to make it function in modern python make it not function for retrieving the users email after the oauth2.0 process. A: This is going to depend a bit on what scope you authorized the user with. Assuming that you authorized them with one of the drive scopes. You can go though the google drive api the about.get method this will return the email address of the currently authenticated user. "kind": "drive#about", "user": { "kind": "drive#user", "displayName": "Linda Lawton", "me": true, "permissionId": "437243", "emailAddress": "xxxx@gmail.com" }, If you have authorized the user with say the profile and email scopes then you could go though the google people api. The person.get method
how to return user email on google api, python
ive been trying to use google sheets api for a project and for this project it requires the users email to be compaired to a list of emails in the sheets and only return the rows with the users email in. so if the google sheets as A _______________________ B personA@gmail.com ___apples personB@gmail.con ___ bananas personC@gmail.com __ oranges and you log into the app using personB@gmail.com then the code returns bananas, without returning apples and oranges because those are associated with other emails. but I haven't been able to get the email that the user authenticated with to return. and most other solutions where either too old and couldn't run on modern python (3.4.10) or where in different languages entirely. and I don't want to have to have the user enter their email twice. I have code that I've attempted to use but its mostly irrelevant as the fixes to make it function in modern python make it not function for retrieving the users email after the oauth2.0 process.
[ "This is going to depend a bit on what scope you authorized the user with. Assuming that you authorized them with one of the drive scopes.\nYou can go though the google drive api the about.get method this will return the email address of the currently authenticated user.\n\"kind\": \"drive#about\",\n \"user\": {\n \"kind\": \"drive#user\",\n \"displayName\": \"Linda Lawton\",\n \"me\": true,\n \"permissionId\": \"437243\",\n \"emailAddress\": \"xxxx@gmail.com\"\n },\n\nIf you have authorized the user with say the profile and email scopes then you could go though the google people api. The person.get method\n" ]
[ 0 ]
[]
[]
[ "email", "google_api", "python", "python_3.10" ]
stackoverflow_0074591548_email_google_api_python_python_3.10.txt
Q: compare two list and set zero for not exist value I want to compare lst2 with lst and set zero for value who is not exist lst = ['IDP','Remote.CMD.Shell','log4j'] lst2 = ['IDP'] I want output like this in for example loop { IDP:1, Remote.CMD.Shell:0, log4j:0 } { IDP:0, Remote.CMD.Shell:0, log4j:0 } { IDP:0, Remote.CMD.Shell:0, log4j:0 } I would be glad if anyone can help me A: Here is how i can achieve this first you can create a new dictionary and then manipulate the data inside lst = ['IDP','Remote.CMD.Shell','log4j'] lst2 = ['IDP'] result = {} for i in lst: result[i] = 0 # if one of result keys is in lst2, set the value to 1 for i in lst2: if i in result: result[i] = 1 print(result) result: {'IDP': 1, 'Remote.CMD.Shell': 0, 'log4j': 0} A: This should work: result = {key : 1 if key in lst2 else 0 for key in lst}
compare two list and set zero for not exist value
I want to compare lst2 with lst and set zero for value who is not exist lst = ['IDP','Remote.CMD.Shell','log4j'] lst2 = ['IDP'] I want output like this in for example loop { IDP:1, Remote.CMD.Shell:0, log4j:0 } { IDP:0, Remote.CMD.Shell:0, log4j:0 } { IDP:0, Remote.CMD.Shell:0, log4j:0 } I would be glad if anyone can help me
[ "Here is how i can achieve this\nfirst you can create a new dictionary and then manipulate the data inside\nlst = ['IDP','Remote.CMD.Shell','log4j']\n\nlst2 = ['IDP']\n\nresult = {}\n\nfor i in lst:\n result[i] = 0\n\n# if one of result keys is in lst2, set the value to 1\nfor i in lst2:\n if i in result:\n result[i] = 1\n \nprint(result)\n\nresult:\n{'IDP': 1, 'Remote.CMD.Shell': 0, 'log4j': 0}\n", "This should work:\nresult = {key : 1 if key in lst2 else 0 for key in lst}\n\n" ]
[ 0, 0 ]
[]
[]
[ "compare", "list", "python", "python_3.x" ]
stackoverflow_0074591397_compare_list_python_python_3.x.txt
Q: How to make a grid of the size a rows x b columns from a list containing exactly a*b items? Python grid, list, matrix? How do I make a 3x5 grid out of a list containing 15 items/strings? I have a list containing 15 symbols but it could very well also just be a list such as mylist = list(range(15)), that I want to portray in a grid with 3 rows and columns. How does that work without importing another module? I've been playing around with the for loop a bit to try and find a way but it's not very intuitive yet so I've been printing long lines of 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 etc I do apologize for this 'dumb' question but I'm an absolute beginner as you can tell and I don't know how to move forward with this simple problem This is what I was expecting for an output, as I want to slowly work my way up to making a playing field or a tictactoe game but I want to understand portraying grids, lists etc as best as possible first 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 A: A mxn Grid? There are multiple ways to do it. Print for every n elements. mylist = list(range(15)) n = 5 chunks = (mylist[i:i+n] for i in range(0, len(mylist), n)) for chunk in chunks: print(*chunk) Gives 3x5 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Method 2 If you want more cosmetic then you can try Ref pip install tabulate Code mylist = list(range(15)) wrap = [mylist[x:x+5] for x in range(0, len(mylist),5)] from tabulate import tabulate print(tabulate(wrap)) Gives # -- -- -- -- -- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -- -- -- -- --
How to make a grid of the size a rows x b columns from a list containing exactly a*b items? Python grid, list, matrix?
How do I make a 3x5 grid out of a list containing 15 items/strings? I have a list containing 15 symbols but it could very well also just be a list such as mylist = list(range(15)), that I want to portray in a grid with 3 rows and columns. How does that work without importing another module? I've been playing around with the for loop a bit to try and find a way but it's not very intuitive yet so I've been printing long lines of 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 etc I do apologize for this 'dumb' question but I'm an absolute beginner as you can tell and I don't know how to move forward with this simple problem This is what I was expecting for an output, as I want to slowly work my way up to making a playing field or a tictactoe game but I want to understand portraying grids, lists etc as best as possible first 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
[ "A mxn Grid? There are multiple ways to do it. Print for every n elements.\nmylist = list(range(15))\n\nn = 5\nchunks = (mylist[i:i+n] for i in range(0, len(mylist), n))\nfor chunk in chunks:\n print(*chunk)\n\nGives 3x5\n0 1 2 3 4\n5 6 7 8 9\n10 11 12 13 14\n\nMethod 2\nIf you want more cosmetic then you can try\nRef\npip install tabulate\n\nCode\nmylist = list(range(15))\n\nwrap = [mylist[x:x+5] for x in range(0, len(mylist),5)]\n\nfrom tabulate import tabulate\nprint(tabulate(wrap))\n\nGives #\n-- -- -- -- --\n 0 1 2 3 4\n 5 6 7 8 9\n10 11 12 13 14\n-- -- -- -- --\n\n" ]
[ 0 ]
[]
[]
[ "field", "grid", "list", "matrix", "python" ]
stackoverflow_0074591109_field_grid_list_matrix_python.txt
Q: Difficulty decoding image with base64 library I'm having trouble decoding an image when I import it from another file. I have four .py files to make two buttons. In the first, on line 21, the button works and brings the image, in the second, on line 28, which is imported from another file, it appears as a button but without an image. How can I resolve this? lab.py import tkinter as tk import base64 from imagens import * from cores import * from widgets import * class Janela(Images): def __init__(self) -> None: self.images_base64() self.tamJanela() def tamJanela(self): self.janela_doMenu = tk.Tk() janela = self.janela_doMenu # janela.state('zoomed') janela.title('Disk Gás Gonçalves') janela.configure(background=preto_claro) janela.geometry("%dx%d" % (janela.winfo_screenwidth(), janela.winfo_screenheight())) # Here the code works ############################################################### self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser)) self.rotulo_nome2 = tk.Button(master=janela, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F', highlightbackground='#4F4F4F', highlightcolor='#4F4F4F') self.rotulo_nome2.grid(row=0, column=0) # Here the code does not work ####################################################### # I'm importing from widgets.py ##################################################### Botoes(janela) janela.minsize(1200, 640) janela.mainloop() Janela() widgets.py import tkinter as tk import base64 from imagens import * from cores import * class Botoes(Images): def __init__(self, local) -> None: self.images_base64() self.local = local self.bt() def bt(self): self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser)) self.rotulo_nome2 = tk.Button(master=self.local, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F', highlightbackground='#4F4F4F', highlightcolor='#4F4F4F') self.rotulo_nome2.grid(row=1, column=0) cores.py preto_claro = '#4F4F4F' verde_médio = '#00FA9A' vermelho_salmão = '#FA8072' azul_seleção = '#F0FFFF' verde_limão = '#00FF00' branco_gelo = '#EDEBE6' imagens.py import base64 class Images: def images_base64(self): self.addUser = 'iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAFiVAABYlQHZbTfTAAAAB3RJTUUH5gkWFg4SATq7CQAADcJJREFUaN7NmXtwXNV9x7/n3Pe9e+++Vyut5LUkyy/AWECJE0MShwTjOAEPQ5hJoFBa7MGQaRNwOy1NO0070yGBkk4GGxqSQM1kajKTkAyQmpCEeMzAFEJiPDxs2ZKxHitptbva5717n6d/yJYtJCzJspv+NDvaPffec+/nfH+/c3+/cwiWaE/v3AJCCIIgAGNsxjFCKALGwFGCP3v8v5d6q3MaOZ+L/vPeLfB9BoBB4HkYYR03/es+8s2tl0mSJAmEENJs2s6Df7Oz+eOf/ALNpg1KKe56Yv//H5Cn7rkBjuNCUWR8e/eL5Kt3bWrXdf2qkKZeqShylyDwUQJCbccp1Gr1N8qV6v4Hn3y576Edmxkv8Lhj94t/fJCndm6B67hoa2vBSG6sPRGPfSWdStyaSiVWh8O6psgyeJ4DAYHruSiXa/7QcO7dweHcv+Vy4/siEcPhOA537vnFHw/kqXtugOt62PGDX2HvfVuv7ci0/lN3V/aTLakEL0rCma5OxwmZ+m03bRwf+KD0/tH+bx452r+nPZP2ps4DKCW48wLFDreQk57euQWu6+GqK9bhmq74dT0rOvesu2z11alUgnIcPee1vMAjFgkrvh/02rYzXCiUhu/be6B588dW4o5vfwOd5VH87HfH/29APnd5FuGQhqHh3JruruzudZeuvlzXQ2dGfx6jHAdD10KSKH4qGglv2trbGanVGgPvHXjdvGP3i+iaeAM/e3NpMPOCPL1zCwRKMZIbk7o6s99Yd9nqbdFoZMEQp00QBKSScTXdkuzUQ9p1ruumi6Xy6+/+8tmGHzD8fImq0PlOUBQFqqKgNZ1a355Jb0vEoouGAAFACAghkBUZncs7hDWrVtyWiEfvfO6Fl8/rFbBoENM0ceujP0XY0D/b0pJso9yCvPEsCIJ6rYFcbhyO406DtbW2CC0tyVs3f+aaDM9xePqeLRcXhDHgoZuv0nQ9dJUR0hY3eoSgWqnh+MggiqSKIycHUK3WABCIooB4LNqjaeoaVZEBf0kc4OclpQSapuqqqnQIorAwtyIEge8jP1HEaKWAtt4MUtkE8icnMPCHYazil0PRVIQ0VZVlaXkkEka9YV5cRSilEHheEXg+RCmdflAQAsYYguDUhzEEQQDbdlCYKOL94/0oBBV0XdOFls4kCCFo6WxBuDuCXD4PMAZB5Hme4xIbru5dmhwLUQRgABhjp6UgBJZpIV8owrSbCHCqGUAABp8E4HUB8ctTSLTHwYv8DBVblidx7IPjcB0XlFBCKOG1z30SeG5pb/t5QfyAwXbchuO4pcCfGvG+wQ+gZw0k02nwAgewKVTKUYiKCEmRQDk6BXC2KzIGUZVAJQrHdeH5vu/7QfWtx3548RVhAUO5Uqs1GuYJ23E+USxNQs8a6L6ya0qGWSHDTos4Z3+EEBCOwPcDmKZl2U37xNDw6JJB5o0RMIJ7t3+lWas13qhUa17TdRCKh075Ejsz6tOfhd3Y8zyUy9WResN8v7HEQF8QSMeGAC/sewuBXJ/IT0w4QeCfzgfP3whBo95AsToxZizzK3LSQ2tvcHFBmE+Q/lQx1rZWv90kNbVWM7FkEsYwXixAaUVvukvf1LZaX3KX87sWgMCHroXVTiMjozBZXLD7zGWEAJbVRNWtILk8YlDKdbYuzyw661k0CGMMvutVHNsZ0lMytJQAQpZ2VyIyxLs0EBpYnuueGBkYAjm/qnvhIGDAjV87UDZrjRfspukkVygQFLIkVcJtPEJxHrVy9bBt2a9bDXMp3S0QBMDL398CyzSfLY5N/MRq1D2yoKvmtqlYCFAczw/VypVHtuz81qDv+9i8Y2kLE/M+UkAIivkCBEHIlwvFXY1a/b+C4PxnGMYAz/VypXzhr6qTlef2P/G3IEueBhcAsmXHfsSScTi2jUgimQt8f7/dtOzzvaHvuXBd52itXPqNoio+x3PYvOOliw8CAJt3vAReENC0LDRN891aeXI88M8j7yYEZr2ORq3y+5HBE3UG4PrtF2atawFJ4xmY/f9xPSrlUt/kxPgrjWrlTj0aW1S1yAIfxfHRfL1aefGKjZt827IAALd9/+uggQCQqSwaOLO8w059p5SCMYZntj88Z9+LKvf+9MYViCaSXqNWLXI895lwLBGh/ALHghBM5sfZ4PEjeydywz+kHOf1kTiMjdeByjxEgUdPph2vv/euwBgLOZ4bsmxbrjTq9OeP7/E2XvdZOK6Ly77wcVx+40Ycfv61md0vBuSl721G4PsYHfqA61p96b3LelY/1NG9SuWFeQouQlApTqD/vcMHx4cH7xIkqf8Zsg6O40ARJRwbGRQ6ki0rDVW7JqQoVymStIznOC1gzHNct9hoWu/XTOvVSqP+Zm/PymLf0CAkQYTju3jm7ocXD3IaBgAC3+/RI5H9Le3ZrnRHJzTdAKF0JhAhcB0bpfFR5Ab7Ucrn/2Vl7/p/7P+f1/A99OK69evx67cPrUoYkbtb4/FtLdFYNqxqgigI4CgFA4Pn+WjYTZSqlXKuWHwjP1n6Qb5SfiEWMsx8pYiEEcUz2x9enGvt2nMQJ3EN2ukhUN+MRVPx22RVjJXyo6hXK+A4DqKsgBAKx7aRHxnE2NAALKsCSRFg1c1XUtd+7cBTbw/hvfE8ZzrOF7ta2757aWf3Ld1tbbGobnCyKILnOHCUgqMcRJ6HpiiIG2E5FYl2y5J4PWMsUa7XD8d0o1asVfGxL22aP9gf2H3wrO0CAlFWkV6+Hifefp1PE0pCRghqKIBlWhg+cQSyooMXBFiNGkB8qIYKUTJg1hsIAsK1qvsI8F32F08/eGtPpv1bq5dlOzRZOVWDznZPBkyrHFIUrO7Ihg1V++o7Hwykhifyu+JGeEQVpXMrcv/ugwj8AILA45F7b8H6T9+U5ji6sd9c+yVPv+TLafFkbyQsipTjIMoSJEVEELjwAweyKkIzQuB4HoQQOM0mjtfXRNfdvK37ks//ydXZjLLr0s6urCrJswA4wkHgBFBC59hzITBUjSiivLbetNSxyeIBEDhzxsiuPa+CEgLP83HXn1+LJ5880BWOaLfE4sa2WExfa4Q1QxZBtNyP0C4dhWaEcJZoICAzHoAFPsbyNorJO1EiaRwd+mWwpjNCw1poThUyoTa0h9pg+U30TR5D05v9/mWM4djIUP1Q//H7tn58495Zijyw51V0tMRQrlmoVU2lf6Dw5Y5s8pEVPZnbl3e2LEskw7KmSUSUJQRiAs7EO1B4G7zwEV7KApRLdZTkjeDbP42xylFocpmko9E5E0UGhpSaRFpLgyMUY41xOIE7KzumlEKVZbFmmonf/P53v5oBsmvPq4iGNeSLVTSbTjzdGvv77p62f1ixMtMVjYYo96FVRiJF4XJxNPNHwbP61N4IPbO94Do2JksWivyVINmbYAcMg2Nvoj2pQzzH+ycqRRGTo3ADD6ONMbhzgACAyPFwfT9eqlX7ZvRGQDBZrsOynFi6NfbPPasy21vbEgLHkY98TdDEelhSFCNjr0CZOAaJmiBg8AIeFknAiW4ASW0AFWRUJwfBczYUMbrktH3qgQniRjhkqNrWaZD7HzsIz/dRmaxLHdmWr69Ymbm7LZMQCCHzZiHUyAKh22E2S2g0i0DgAYIOoiRAhdD0eTWzBFXip9MNYCqwOXpaaQYGTP8mIBA4AWIgTmfIjDF4gQeGqVlOlSRosnzFNAgLGJZ1pjAm8p9ftjy1sy0TFxecXjMAhAdRUyBqamb7Wd8dtwFFnOmeaa0FmVDbjDaJl6b+cyLWxlYjYGfKBttv4uhZEwDHcZBFMc0DwAOPHQShBMf7RtKdXa1/2d6RjHMcXXwdzc59KGA+ppddT42/zMsIS8bcShMKXQzNaGt64tS0DAZyKnIooWemmmxXGqPDhRtaM/ENqiYteTHgw0YAcFSA7wdntRFUnSpG6rkZA6FLOgxRhxd4KFhF+IE/3YnjO/ACbzr4p1zNt/jTI/OHN/tCq9Ys+2I8YcgXFuEMiSzqsJruDOkmzAIKZnGGSt2RThiiDidw0V85AdM1Z8xa7Kz1Ztf30bTtQfrA7oMQBB66oWYjkdAVsnzh1ThtupaAaQfwP1Qqsw//zVgunnX0rMEhqFsWqzet1ygAKKoERRZ7QoaS5LgLshM22xhgqDGA6Khb5gWp0xljmKhMlqqNxvM8AMRiOvKe3yEKvOr7wUVThBIBMb0LY6VD0BXtI2DI9KojwUfXGYQQVOp1jBQKB0r12kH+VCs8z7cGT+bfyefLmKnfBTRC4LgU46ZtREPlbCoaI7OSQgBVp4aRem4qsJk351vd9TwMjOZy45Olx7OplkmeEIJDbx1DNKb/+MTA6P6zZ5WLYRykoB4qdnCDlUdFQfhEJKTPShwnzAIKVvHUDsVsUD8IMDA60hgYyz16cnzst23xxFQ9EosbAFCVZbF6USkABHARC0Vzg+PH7ifAv6/NLt+QCEdAyIcy5jn8mxAC23EwMJqrHhk6+Z3RYvGJTCLpUUqXuOB6Hnb7k38Nx3WxLJVCrlS8pDUW/7vOdNuNmURSVyXpIycBz/dRqlWDE2OjRwbz498ZKxV/FNZCFs/xCHxvcaXuhbDDz7+G3m3XolSrQZOViZFC4ZVqo56brNWWNR0nxXGU8BwHekohy7ExNllC3/BQtW9oaN9gfvzBZ3/76xd7V/S4As8h8H3s3f4w/hdjSyoPRFIhbAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMi0wOS0yMlQyMjoxNDowMCswMDowMOZEiVcAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjItMDktMjJUMjI6MTQ6MDArMDA6MDCXGTHrAAAAAElFTkSuQmCC' self.editUser = 'iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAFiVAABYlQHZbTfTAAAAB3RJTUUH5gkWFhApZHBt8gAADaRJREFUaN7NmXtwVNd9x7/n3Nfu3ae0Wu1qtXpLICNhG/AjDrEhAQS4pHadGbedcRPHIAxx/ODRJs6jbrHjtHHrqRPjENu1HXDbqRvbk+IgwHVcB49pDY4BSwgJCb2FHvvevXf37t57T/8QUAN6rBB0+pu5M3tn73l8fr/fOfd7fpfgKthrm9dO/ofBAbyO+1/YfzWGmdbIXCZPCYFumuB5DrLVigK3C7fefCNswRK8/3YLxkJhpNMZMMZAKcX9P2/5/wPy2uY7QQiDYZhwOOw49lm7UBbwl9ps1nmSJFUKPF8IgMvl9DElrR6PRGKtpQG/mkikIAg8vrnr2kRnViCvbV6L8VAYvmIvBofOisFS/xc8hQX3ejwFywrczjJZlmVBEHgCEC2bzUUisdDw2bH9o2Pjz61bs+L4W3v3QxSEawKTN8hrm9cikUzB6ylEIpkK+H3ehyvKS78RDJaUuBwO8AJ3WXemaSIajeFU55ljPb392+rn1fz2ROspCIIA0zSvaqrlBbLnoTvx0cfHcPttN0FNZ6rKgiU/WVBf90eBkmKOchzA2DQjEKSSKRz7rP337R1d65tf2n3sjW0PQVFUUErBcTz+7Pm9cwbh8nnoD5fUoKzUj6SieCrKS39y4/UL/iQQ8FFC8guoKEmQrVa/YRiLjv/m38uUlKqNjoVGrFarSSnB20dO/9+A3LWkBi//cj9Z9eWbHmxsmP9osNSfV7vPmyxbid/nDXq9nmUWSWqilGRD4cgxQeCNu2+uw6+Pdl1bkFc3rYEoCmi4rry2tqbix/PrqgMcN2sOgBDwAg+7TYa3qNDFGG5RVLWzvq6mfTwUmTMInXl8gvp5tXC7nF8J+H31oijOehBdN6AqaTDTBBiDIAiorizz+IqL1h8+8mlBvik6JxDTZNjb8p7kdDiWFrhds6MgBLmcjq7eXrT1deFM/wByOR0Agyxb4S3yLHY6HPMtFmlqdXC1QAglcLudDrvNWitZxOl3qEsgVEVFZ08P+BIJDU0LYBZRdPf3wdANEErhdNrdVqtU53DY5wSRFwglBJIg2ERRLLhobRAy+QVA07IYHDyLjsFeOOcXoHpJFWSnjJrFVWBuDiNjIYAQSKIoCoLgq6+rnjMIP7NjCQghHCFkgoIApmEikVSgptMwDOPCc6ZpIp3VkDY0WLxW1C6phcNjBxgAxkB5DoH6EvR/1Ae/7gXHcYRSKlfftx6HPjpybUFMk0HXjXRO11PMZNBNA939/cgIOdg8NvAiBzBMCEOOg9tRiDKPA1a7BYTSi1ORMcguGUwEsloWpmkyZpqZwTd2X/uImKaJlKIm0un0QE7PLY7GEtCdDAtuuw6CKPyvNmC4+Ddjk64nylFQgUI3DGQympbN5gZPtJ4CuXIhPtHvTA8QAjz+9lE1mVKPp1IqUqoKT7AQgiRMTNQ8d136ewYzDBPxRDKsqulTiUQKeW4hVw7iqQN+9edfY0omeTwUDismM0D5GZvN6J1MJoNwNHI6Yyh9OjSULDLm1OWMqSU5GURnRC4gzlURNWy1ic45HMfOcQAIhSMwbKnqeV9yNlIIH+RymTn1OXNqgcDIkiK3z3mHxcvT8VBkTvlMyMT2PJ4IwV9XUC4Iwhcq51fMzTP5gACAaZgZxliioFSGKeXA8n0pTmE5IwfZz0Oy87ppmNHQaAhzVSkzgjDGEItEw2pSOQROR+A6BwQLwVxWpysgoKjSBjWpDGQz2n8nY/E8XToHEPBAoDxopBV1d2Qs9CmjWdAZV9Y0RgDeCqQSMS0eib2ajCfa9KwOpl9rEAPIahqamve3Rscjjyai8cNzSi0G5LRccvzs6N+qKeVnDrdLBwFWP3hgTiAz+nZ18wEceHE19u9aheLS4KFkLLY7l83enE/bycw0DBiG3p6IRnbaXe4YLwgwcvmF46PlywE64fvzziSETMiffDpYvfEAKMchGYshq6VPKsl4LG8V/HkjBFomjXQqeVJJxOLMNGFkc2hqnrmqsu9r96I8FQOjFLdt3IjE6KglNjQkeoLBCXmU/yQALZOGkky2xUJjn2bSKma91TCGWHhcTSVi7zbc9EWNEoqmjTOn1NNP/B3WvvkG3lm6FrZYxP3Jnj0PBhcufKXshht+ER8buyenaZa8z6yv7+3GfetqsPCmW9NnB3qZxWptcroLxbxPd4RASSXQ33nqvdDI8LO5rKYwBrz+Tve0zb77zEv4q+8/jB88/QJGJNkrO51PzispftxXVbnIVVx8IycIX8lpmjKrw/d9X61BeHQESjLeYxpmsUW2LbY5nDNH9VxK9XW2nxkd7PuO2+NtS6tJrNn07rTNnnr2Gdy67dvYbS9BQtU8wWDpk9K8+mZB4MUATyBKEiSbzZZJJhtmBfL6O93YcG8DKM9n06nUoJpKrON5wSXbHKCTFSTORUtJxNHT0Yqz/T2vDp458xIvCIxyFK/vnToa77/8ZXz9Wy/in//eDSWTKQqUlu+4fmHjhnkLFghDjCIZjsDLcuAohRKJyLN+DWW17HmBkhJELhsLD6O7/TjGhweRy2oXToqMMaRiUQx0d6Cvuw2MaeB4LvGNp75nUo5i9caDU45x8KXVqFn/W+z86XeQTGlFPn/5UzcsbGyuLC8TLJKImoYGjNVfj1ZqRVpRoSnK7/PaQrftPARKKQzDwMEcRZV0HHX6L01BKEWBtwBaRkN4tBeR8WEUFJVAEEUkYxGkEmGIFgFujwtaJgM6OsZ27b8Bw8yPrc//ABPykeHZb9/+OYg1WLXhe/iPf1yL+XzYU1Z1y46YrfaBwkKPQCkFYwyiIKC2oRGnslmMf9Df7otGn+CnB/gQqkLAmAlR4vHJx91cdU3A18WWVKcl+ZY7zMMuQgisNhkW2YpMOoNoaACMMfACD7fXDZ6fGEJLM4ybtUvO9Kl3ZzWpK5lI9d2+vDF5srUfW372OxBKsEZ8Cqs2/CXefXkHMmrK4w3U7micH9iQJIrQ2nsctPpGOOy2iczIakjo5ulet3/7Xx88eGDKLWfb84egGyasVhGjI1GLp8h5s9Ml3+Vy25c5nbYqu0V3+KN7hEpPlAgWy+Xaa8LZ54whPJ5ED7fOjEmL0qmkEorHlWPxmLIvmVBb7vv68oF//ZcPMa9WRM3gE1CVlKe4pGxHVX1jc3FpmUAIwekhE63DAVTULAIhDMc/a+vo6up+7Efb1+/ftXnb5JXG7S98CMMw8fQjd+Ddwz2NgaDnh5VVJT+sqQ00lZV7A0Vel+xwuziDSISFT0C2chPn80mMEEBNKhjXqyHW3EXcngLRU+RyF3ld9U6nvFoQ+Ns/OdqtJxNqdyD7QVZS2y+DAACPk4AnSbSfiaFnYOx0b++ZLU9uXd+S4T1IuTyXg0xAGBgfi/GfdkXuKasofm5efdkflAa9dptNAv3chInVj0xGhxntgEUEKMefr7pgQjmYUBIpjKpe6BV/CiJ7ATYhK0SRh9Nl4wo9zqBkEVeajPj05NmzC/zxrVX1jRuLS8uFi95RhEDmFIT6WzvbuqNbdmx/ZV/GkgMRJPz48c0Xg2zbeQimYSIUivPlFb77q2tLnqmbH6xxumRM+uIjFMRZjbThgBoZgpGOw9A16Nks0oqGaNxEmDRAL78X1B6cNGKCwMFV4BBtgraoOPdfTQvr/cuLS8vFSyEyioLejrYOZaRtyzcfeqHlF4XtUFgRnv6Lb13I5AsQhmHiHx5Zhu++ePiPq2sDz9XUBXyiyOclq1gmDBY/DZIZATFzYIILzF4J4qgE4cWpzy8EYFoCfP+bqHaOwldaiskgejpaO4d6uh5duX7f/rd23g3CS7hn0xsXLUkAwGM//U9YZQu0THZxVXXJnvqGigUWi5C/Nvx8KWiy+5kgXKPwBaaGGO7pemzF+n0tLT9fCY7jL5P99Hw0KOUwPhqzeYpcj1RU+WYHcX7CbJr7qwGxawU4npv07MKfawOb3QqOo0tLAp51Lrf9ilR63kYAlomD638T1e6xySHUSyOxAhzPT6kIKDBRFu1o7xddbts9Xp/bQ+ncv1dMH4k4+P5foWaqSKgKek61dg5dmk7TyBq6feeH4DgO3mJ3wF1gX2q3Wa5pNEwtBf3UPyEg9MAfDE4N0dv12MoLEBxWP3hw2n6pIiqwWERYrVKd0ymXcfwVfFabRTTU/iOwx04gpyaRVpQpI7HygX0tLbtWTqTTDBAAQOWcDKdLhigJlVbZYqN06k8fc70MTQFGjqLC74FMBAx0nEQqEQcoPQ/RNdTTtWXlRemUX1GCJyBwOGVEIylHJJTIZLM6mXMFbtJoUCDaJtZiRHTYCkGoHTQRw3B3JzyBUowND3YPnuna2tTcsu832krwPJc3BHBu1+rrGUUup7/T3TXcdS5lrzIIQSatSlz/W48uXC5/ieMoTAbYbQ4kR9NoO3K0K5tVtjY3t+zd+/wKkDzWxKQgVqsEwzA6RUno5Lg5lvwmsYH2j3Hid//WIEqyX6ZePLDGAso0DI1Gh0fHo+9ntOTLgYKTH+zcuRKUUty5aXYQE666xra8aR0qPTnSMSp+3zCxg6Mk98V66+lFZdreeCLx65FQ/MSyW4Oqkk5BFHis3XRlhbprDrJ0xTpwBL6sQd5iQICAvWLo+pss2dWx/qt1hpHTYDACSoCH/+a9Kx7nfwAPPztG5sk4owAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMi0wOS0yMlQyMjoxNjoxNyswMDowMOu8Z3oAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjItMDktMjJUMjI6MTY6MTcrMDA6MDCa4d/GAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAABJRU5ErkJggg==' I tried to create a button by importing the base64 image from another file. There are two buttons in the application, one works and the image appears, the other does not work and the image does not appear. I would like to make the second one work. All the code will generate this image. The bottom button that doesn't show the image is in the widgets.py file I don't know why, but when I import it, it doesn't work. Thank you in advance for your attention and I apologize if something was wrong or out of standard, my English is not very good. A: It is because there is no variable referencing the instance of Botoes(), so it will be garbage collected (so as the image inside it). Just use a variable to store the instance of Botoes(): class Janela(Images): def __init__(self) -> None: self.images_base64() self.tamJanela() def tamJanela(self): self.janela_doMenu = tk.Tk() janela = self.janela_doMenu # janela.state('zoomed') janela.title('Disk Gás Gonçalves') janela.configure(background=preto_claro) janela.geometry("%dx%d" % (janela.winfo_screenwidth(), janela.winfo_screenheight())) # Here the code works ############################################################### self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser)) self.rotulo_nome2 = tk.Button(master=janela, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F', highlightbackground='#4F4F4F', highlightcolor='#4F4F4F') self.rotulo_nome2.grid(row=0, column=0) # need a variable to store the instance of Botoes # to avoid garbage collection botoes = Botoes(janela) janela.minsize(1200, 640) janela.mainloop() Result:
Difficulty decoding image with base64 library
I'm having trouble decoding an image when I import it from another file. I have four .py files to make two buttons. In the first, on line 21, the button works and brings the image, in the second, on line 28, which is imported from another file, it appears as a button but without an image. How can I resolve this? lab.py import tkinter as tk import base64 from imagens import * from cores import * from widgets import * class Janela(Images): def __init__(self) -> None: self.images_base64() self.tamJanela() def tamJanela(self): self.janela_doMenu = tk.Tk() janela = self.janela_doMenu # janela.state('zoomed') janela.title('Disk Gás Gonçalves') janela.configure(background=preto_claro) janela.geometry("%dx%d" % (janela.winfo_screenwidth(), janela.winfo_screenheight())) # Here the code works ############################################################### self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser)) self.rotulo_nome2 = tk.Button(master=janela, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F', highlightbackground='#4F4F4F', highlightcolor='#4F4F4F') self.rotulo_nome2.grid(row=0, column=0) # Here the code does not work ####################################################### # I'm importing from widgets.py ##################################################### Botoes(janela) janela.minsize(1200, 640) janela.mainloop() Janela() widgets.py import tkinter as tk import base64 from imagens import * from cores import * class Botoes(Images): def __init__(self, local) -> None: self.images_base64() self.local = local self.bt() def bt(self): self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser)) self.rotulo_nome2 = tk.Button(master=self.local, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F', highlightbackground='#4F4F4F', highlightcolor='#4F4F4F') self.rotulo_nome2.grid(row=1, column=0) cores.py preto_claro = '#4F4F4F' verde_médio = '#00FA9A' vermelho_salmão = '#FA8072' azul_seleção = '#F0FFFF' verde_limão = '#00FF00' branco_gelo = '#EDEBE6' imagens.py import base64 class Images: def images_base64(self): self.addUser = 'iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAFiVAABYlQHZbTfTAAAAB3RJTUUH5gkWFg4SATq7CQAADcJJREFUaN7NmXtwXNV9x7/n3Pe9e+++Vyut5LUkyy/AWECJE0MShwTjOAEPQ5hJoFBa7MGQaRNwOy1NO0070yGBkk4GGxqSQM1kajKTkAyQmpCEeMzAFEJiPDxs2ZKxHitptbva5717n6d/yJYtJCzJspv+NDvaPffec+/nfH+/c3+/cwiWaE/v3AJCCIIgAGNsxjFCKALGwFGCP3v8v5d6q3MaOZ+L/vPeLfB9BoBB4HkYYR03/es+8s2tl0mSJAmEENJs2s6Df7Oz+eOf/ALNpg1KKe56Yv//H5Cn7rkBjuNCUWR8e/eL5Kt3bWrXdf2qkKZeqShylyDwUQJCbccp1Gr1N8qV6v4Hn3y576Edmxkv8Lhj94t/fJCndm6B67hoa2vBSG6sPRGPfSWdStyaSiVWh8O6psgyeJ4DAYHruSiXa/7QcO7dweHcv+Vy4/siEcPhOA537vnFHw/kqXtugOt62PGDX2HvfVuv7ci0/lN3V/aTLakEL0rCma5OxwmZ+m03bRwf+KD0/tH+bx452r+nPZP2ps4DKCW48wLFDreQk57euQWu6+GqK9bhmq74dT0rOvesu2z11alUgnIcPee1vMAjFgkrvh/02rYzXCiUhu/be6B588dW4o5vfwOd5VH87HfH/29APnd5FuGQhqHh3JruruzudZeuvlzXQ2dGfx6jHAdD10KSKH4qGglv2trbGanVGgPvHXjdvGP3i+iaeAM/e3NpMPOCPL1zCwRKMZIbk7o6s99Yd9nqbdFoZMEQp00QBKSScTXdkuzUQ9p1ruumi6Xy6+/+8tmGHzD8fImq0PlOUBQFqqKgNZ1a355Jb0vEoouGAAFACAghkBUZncs7hDWrVtyWiEfvfO6Fl8/rFbBoENM0ceujP0XY0D/b0pJso9yCvPEsCIJ6rYFcbhyO406DtbW2CC0tyVs3f+aaDM9xePqeLRcXhDHgoZuv0nQ9dJUR0hY3eoSgWqnh+MggiqSKIycHUK3WABCIooB4LNqjaeoaVZEBf0kc4OclpQSapuqqqnQIorAwtyIEge8jP1HEaKWAtt4MUtkE8icnMPCHYazil0PRVIQ0VZVlaXkkEka9YV5cRSilEHheEXg+RCmdflAQAsYYguDUhzEEQQDbdlCYKOL94/0oBBV0XdOFls4kCCFo6WxBuDuCXD4PMAZB5Hme4xIbru5dmhwLUQRgABhjp6UgBJZpIV8owrSbCHCqGUAABp8E4HUB8ctTSLTHwYv8DBVblidx7IPjcB0XlFBCKOG1z30SeG5pb/t5QfyAwXbchuO4pcCfGvG+wQ+gZw0k02nwAgewKVTKUYiKCEmRQDk6BXC2KzIGUZVAJQrHdeH5vu/7QfWtx3548RVhAUO5Uqs1GuYJ23E+USxNQs8a6L6ya0qGWSHDTos4Z3+EEBCOwPcDmKZl2U37xNDw6JJB5o0RMIJ7t3+lWas13qhUa17TdRCKh075Ejsz6tOfhd3Y8zyUy9WResN8v7HEQF8QSMeGAC/sewuBXJ/IT0w4QeCfzgfP3whBo95AsToxZizzK3LSQ2tvcHFBmE+Q/lQx1rZWv90kNbVWM7FkEsYwXixAaUVvukvf1LZaX3KX87sWgMCHroXVTiMjozBZXLD7zGWEAJbVRNWtILk8YlDKdbYuzyw661k0CGMMvutVHNsZ0lMytJQAQpZ2VyIyxLs0EBpYnuueGBkYAjm/qnvhIGDAjV87UDZrjRfspukkVygQFLIkVcJtPEJxHrVy9bBt2a9bDXMp3S0QBMDL398CyzSfLY5N/MRq1D2yoKvmtqlYCFAczw/VypVHtuz81qDv+9i8Y2kLE/M+UkAIivkCBEHIlwvFXY1a/b+C4PxnGMYAz/VypXzhr6qTlef2P/G3IEueBhcAsmXHfsSScTi2jUgimQt8f7/dtOzzvaHvuXBd52itXPqNoio+x3PYvOOliw8CAJt3vAReENC0LDRN891aeXI88M8j7yYEZr2ORq3y+5HBE3UG4PrtF2atawFJ4xmY/f9xPSrlUt/kxPgrjWrlTj0aW1S1yAIfxfHRfL1aefGKjZt827IAALd9/+uggQCQqSwaOLO8w059p5SCMYZntj88Z9+LKvf+9MYViCaSXqNWLXI895lwLBGh/ALHghBM5sfZ4PEjeydywz+kHOf1kTiMjdeByjxEgUdPph2vv/euwBgLOZ4bsmxbrjTq9OeP7/E2XvdZOK6Ly77wcVx+40Ycfv61md0vBuSl721G4PsYHfqA61p96b3LelY/1NG9SuWFeQouQlApTqD/vcMHx4cH7xIkqf8Zsg6O40ARJRwbGRQ6ki0rDVW7JqQoVymStIznOC1gzHNct9hoWu/XTOvVSqP+Zm/PymLf0CAkQYTju3jm7ocXD3IaBgAC3+/RI5H9Le3ZrnRHJzTdAKF0JhAhcB0bpfFR5Ab7Ucrn/2Vl7/p/7P+f1/A99OK69evx67cPrUoYkbtb4/FtLdFYNqxqgigI4CgFA4Pn+WjYTZSqlXKuWHwjP1n6Qb5SfiEWMsx8pYiEEcUz2x9enGvt2nMQJ3EN2ukhUN+MRVPx22RVjJXyo6hXK+A4DqKsgBAKx7aRHxnE2NAALKsCSRFg1c1XUtd+7cBTbw/hvfE8ZzrOF7ta2757aWf3Ld1tbbGobnCyKILnOHCUgqMcRJ6HpiiIG2E5FYl2y5J4PWMsUa7XD8d0o1asVfGxL22aP9gf2H3wrO0CAlFWkV6+Hifefp1PE0pCRghqKIBlWhg+cQSyooMXBFiNGkB8qIYKUTJg1hsIAsK1qvsI8F32F08/eGtPpv1bq5dlOzRZOVWDznZPBkyrHFIUrO7Ihg1V++o7Hwykhifyu+JGeEQVpXMrcv/ugwj8AILA45F7b8H6T9+U5ji6sd9c+yVPv+TLafFkbyQsipTjIMoSJEVEELjwAweyKkIzQuB4HoQQOM0mjtfXRNfdvK37ks//ydXZjLLr0s6urCrJswA4wkHgBFBC59hzITBUjSiivLbetNSxyeIBEDhzxsiuPa+CEgLP83HXn1+LJ5880BWOaLfE4sa2WExfa4Q1QxZBtNyP0C4dhWaEcJZoICAzHoAFPsbyNorJO1EiaRwd+mWwpjNCw1poThUyoTa0h9pg+U30TR5D05v9/mWM4djIUP1Q//H7tn58495Zijyw51V0tMRQrlmoVU2lf6Dw5Y5s8pEVPZnbl3e2LEskw7KmSUSUJQRiAs7EO1B4G7zwEV7KApRLdZTkjeDbP42xylFocpmko9E5E0UGhpSaRFpLgyMUY41xOIE7KzumlEKVZbFmmonf/P53v5oBsmvPq4iGNeSLVTSbTjzdGvv77p62f1ixMtMVjYYo96FVRiJF4XJxNPNHwbP61N4IPbO94Do2JksWivyVINmbYAcMg2Nvoj2pQzzH+ycqRRGTo3ADD6ONMbhzgACAyPFwfT9eqlX7ZvRGQDBZrsOynFi6NfbPPasy21vbEgLHkY98TdDEelhSFCNjr0CZOAaJmiBg8AIeFknAiW4ASW0AFWRUJwfBczYUMbrktH3qgQniRjhkqNrWaZD7HzsIz/dRmaxLHdmWr69Ymbm7LZMQCCHzZiHUyAKh22E2S2g0i0DgAYIOoiRAhdD0eTWzBFXip9MNYCqwOXpaaQYGTP8mIBA4AWIgTmfIjDF4gQeGqVlOlSRosnzFNAgLGJZ1pjAm8p9ftjy1sy0TFxecXjMAhAdRUyBqamb7Wd8dtwFFnOmeaa0FmVDbjDaJl6b+cyLWxlYjYGfKBttv4uhZEwDHcZBFMc0DwAOPHQShBMf7RtKdXa1/2d6RjHMcXXwdzc59KGA+ppddT42/zMsIS8bcShMKXQzNaGt64tS0DAZyKnIooWemmmxXGqPDhRtaM/ENqiYteTHgw0YAcFSA7wdntRFUnSpG6rkZA6FLOgxRhxd4KFhF+IE/3YnjO/ACbzr4p1zNt/jTI/OHN/tCq9Ys+2I8YcgXFuEMiSzqsJruDOkmzAIKZnGGSt2RThiiDidw0V85AdM1Z8xa7Kz1Ztf30bTtQfrA7oMQBB66oWYjkdAVsnzh1ThtupaAaQfwP1Qqsw//zVgunnX0rMEhqFsWqzet1ygAKKoERRZ7QoaS5LgLshM22xhgqDGA6Khb5gWp0xljmKhMlqqNxvM8AMRiOvKe3yEKvOr7wUVThBIBMb0LY6VD0BXtI2DI9KojwUfXGYQQVOp1jBQKB0r12kH+VCs8z7cGT+bfyefLmKnfBTRC4LgU46ZtREPlbCoaI7OSQgBVp4aRem4qsJk351vd9TwMjOZy45Olx7OplkmeEIJDbx1DNKb/+MTA6P6zZ5WLYRykoB4qdnCDlUdFQfhEJKTPShwnzAIKVvHUDsVsUD8IMDA60hgYyz16cnzst23xxFQ9EosbAFCVZbF6USkABHARC0Vzg+PH7ifAv6/NLt+QCEdAyIcy5jn8mxAC23EwMJqrHhk6+Z3RYvGJTCLpUUqXuOB6Hnb7k38Nx3WxLJVCrlS8pDUW/7vOdNuNmURSVyXpIycBz/dRqlWDE2OjRwbz498ZKxV/FNZCFs/xCHxvcaXuhbDDz7+G3m3XolSrQZOViZFC4ZVqo56brNWWNR0nxXGU8BwHekohy7ExNllC3/BQtW9oaN9gfvzBZ3/76xd7V/S4As8h8H3s3f4w/hdjSyoPRFIhbAAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMi0wOS0yMlQyMjoxNDowMCswMDowMOZEiVcAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjItMDktMjJUMjI6MTQ6MDArMDA6MDCXGTHrAAAAAElFTkSuQmCC' self.editUser = 'iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAFiVAABYlQHZbTfTAAAAB3RJTUUH5gkWFhApZHBt8gAADaRJREFUaN7NmXtwVNd9x7/n3Nfu3ae0Wu1qtXpLICNhG/AjDrEhAQS4pHadGbedcRPHIAxx/ODRJs6jbrHjtHHrqRPjENu1HXDbqRvbk+IgwHVcB49pDY4BSwgJCb2FHvvevXf37t57T/8QUAN6rBB0+pu5M3tn73l8fr/fOfd7fpfgKthrm9dO/ofBAbyO+1/YfzWGmdbIXCZPCYFumuB5DrLVigK3C7fefCNswRK8/3YLxkJhpNMZMMZAKcX9P2/5/wPy2uY7QQiDYZhwOOw49lm7UBbwl9ps1nmSJFUKPF8IgMvl9DElrR6PRGKtpQG/mkikIAg8vrnr2kRnViCvbV6L8VAYvmIvBofOisFS/xc8hQX3ejwFywrczjJZlmVBEHgCEC2bzUUisdDw2bH9o2Pjz61bs+L4W3v3QxSEawKTN8hrm9cikUzB6ylEIpkK+H3ehyvKS78RDJaUuBwO8AJ3WXemaSIajeFU55ljPb392+rn1fz2ROspCIIA0zSvaqrlBbLnoTvx0cfHcPttN0FNZ6rKgiU/WVBf90eBkmKOchzA2DQjEKSSKRz7rP337R1d65tf2n3sjW0PQVFUUErBcTz+7Pm9cwbh8nnoD5fUoKzUj6SieCrKS39y4/UL/iQQ8FFC8guoKEmQrVa/YRiLjv/m38uUlKqNjoVGrFarSSnB20dO/9+A3LWkBi//cj9Z9eWbHmxsmP9osNSfV7vPmyxbid/nDXq9nmUWSWqilGRD4cgxQeCNu2+uw6+Pdl1bkFc3rYEoCmi4rry2tqbix/PrqgMcN2sOgBDwAg+7TYa3qNDFGG5RVLWzvq6mfTwUmTMInXl8gvp5tXC7nF8J+H31oijOehBdN6AqaTDTBBiDIAiorizz+IqL1h8+8mlBvik6JxDTZNjb8p7kdDiWFrhds6MgBLmcjq7eXrT1deFM/wByOR0Agyxb4S3yLHY6HPMtFmlqdXC1QAglcLudDrvNWitZxOl3qEsgVEVFZ08P+BIJDU0LYBZRdPf3wdANEErhdNrdVqtU53DY5wSRFwglBJIg2ERRLLhobRAy+QVA07IYHDyLjsFeOOcXoHpJFWSnjJrFVWBuDiNjIYAQSKIoCoLgq6+rnjMIP7NjCQghHCFkgoIApmEikVSgptMwDOPCc6ZpIp3VkDY0WLxW1C6phcNjBxgAxkB5DoH6EvR/1Ae/7gXHcYRSKlfftx6HPjpybUFMk0HXjXRO11PMZNBNA939/cgIOdg8NvAiBzBMCEOOg9tRiDKPA1a7BYTSi1ORMcguGUwEsloWpmkyZpqZwTd2X/uImKaJlKIm0un0QE7PLY7GEtCdDAtuuw6CKPyvNmC4+Ddjk64nylFQgUI3DGQympbN5gZPtJ4CuXIhPtHvTA8QAjz+9lE1mVKPp1IqUqoKT7AQgiRMTNQ8d136ewYzDBPxRDKsqulTiUQKeW4hVw7iqQN+9edfY0omeTwUDismM0D5GZvN6J1MJoNwNHI6Yyh9OjSULDLm1OWMqSU5GURnRC4gzlURNWy1ic45HMfOcQAIhSMwbKnqeV9yNlIIH+RymTn1OXNqgcDIkiK3z3mHxcvT8VBkTvlMyMT2PJ4IwV9XUC4Iwhcq51fMzTP5gACAaZgZxliioFSGKeXA8n0pTmE5IwfZz0Oy87ppmNHQaAhzVSkzgjDGEItEw2pSOQROR+A6BwQLwVxWpysgoKjSBjWpDGQz2n8nY/E8XToHEPBAoDxopBV1d2Qs9CmjWdAZV9Y0RgDeCqQSMS0eib2ajCfa9KwOpl9rEAPIahqamve3Rscjjyai8cNzSi0G5LRccvzs6N+qKeVnDrdLBwFWP3hgTiAz+nZ18wEceHE19u9aheLS4KFkLLY7l83enE/bycw0DBiG3p6IRnbaXe4YLwgwcvmF46PlywE64fvzziSETMiffDpYvfEAKMchGYshq6VPKsl4LG8V/HkjBFomjXQqeVJJxOLMNGFkc2hqnrmqsu9r96I8FQOjFLdt3IjE6KglNjQkeoLBCXmU/yQALZOGkky2xUJjn2bSKma91TCGWHhcTSVi7zbc9EWNEoqmjTOn1NNP/B3WvvkG3lm6FrZYxP3Jnj0PBhcufKXshht+ER8buyenaZa8z6yv7+3GfetqsPCmW9NnB3qZxWptcroLxbxPd4RASSXQ33nqvdDI8LO5rKYwBrz+Tve0zb77zEv4q+8/jB88/QJGJNkrO51PzispftxXVbnIVVx8IycIX8lpmjKrw/d9X61BeHQESjLeYxpmsUW2LbY5nDNH9VxK9XW2nxkd7PuO2+NtS6tJrNn07rTNnnr2Gdy67dvYbS9BQtU8wWDpk9K8+mZB4MUATyBKEiSbzZZJJhtmBfL6O93YcG8DKM9n06nUoJpKrON5wSXbHKCTFSTORUtJxNHT0Yqz/T2vDp458xIvCIxyFK/vnToa77/8ZXz9Wy/in//eDSWTKQqUlu+4fmHjhnkLFghDjCIZjsDLcuAohRKJyLN+DWW17HmBkhJELhsLD6O7/TjGhweRy2oXToqMMaRiUQx0d6Cvuw2MaeB4LvGNp75nUo5i9caDU45x8KXVqFn/W+z86XeQTGlFPn/5UzcsbGyuLC8TLJKImoYGjNVfj1ZqRVpRoSnK7/PaQrftPARKKQzDwMEcRZV0HHX6L01BKEWBtwBaRkN4tBeR8WEUFJVAEEUkYxGkEmGIFgFujwtaJgM6OsZ27b8Bw8yPrc//ABPykeHZb9/+OYg1WLXhe/iPf1yL+XzYU1Z1y46YrfaBwkKPQCkFYwyiIKC2oRGnslmMf9Df7otGn+CnB/gQqkLAmAlR4vHJx91cdU3A18WWVKcl+ZY7zMMuQgisNhkW2YpMOoNoaACMMfACD7fXDZ6fGEJLM4ybtUvO9Kl3ZzWpK5lI9d2+vDF5srUfW372OxBKsEZ8Cqs2/CXefXkHMmrK4w3U7micH9iQJIrQ2nsctPpGOOy2iczIakjo5ulet3/7Xx88eGDKLWfb84egGyasVhGjI1GLp8h5s9Ml3+Vy25c5nbYqu0V3+KN7hEpPlAgWy+Xaa8LZ54whPJ5ED7fOjEmL0qmkEorHlWPxmLIvmVBb7vv68oF//ZcPMa9WRM3gE1CVlKe4pGxHVX1jc3FpmUAIwekhE63DAVTULAIhDMc/a+vo6up+7Efb1+/ftXnb5JXG7S98CMMw8fQjd+Ddwz2NgaDnh5VVJT+sqQ00lZV7A0Vel+xwuziDSISFT0C2chPn80mMEEBNKhjXqyHW3EXcngLRU+RyF3ld9U6nvFoQ+Ns/OdqtJxNqdyD7QVZS2y+DAACPk4AnSbSfiaFnYOx0b++ZLU9uXd+S4T1IuTyXg0xAGBgfi/GfdkXuKasofm5efdkflAa9dptNAv3chInVj0xGhxntgEUEKMefr7pgQjmYUBIpjKpe6BV/CiJ7ATYhK0SRh9Nl4wo9zqBkEVeajPj05NmzC/zxrVX1jRuLS8uFi95RhEDmFIT6WzvbuqNbdmx/ZV/GkgMRJPz48c0Xg2zbeQimYSIUivPlFb77q2tLnqmbH6xxumRM+uIjFMRZjbThgBoZgpGOw9A16Nks0oqGaNxEmDRAL78X1B6cNGKCwMFV4BBtgraoOPdfTQvr/cuLS8vFSyEyioLejrYOZaRtyzcfeqHlF4XtUFgRnv6Lb13I5AsQhmHiHx5Zhu++ePiPq2sDz9XUBXyiyOclq1gmDBY/DZIZATFzYIILzF4J4qgE4cWpzy8EYFoCfP+bqHaOwldaiskgejpaO4d6uh5duX7f/rd23g3CS7hn0xsXLUkAwGM//U9YZQu0THZxVXXJnvqGigUWi5C/Nvx8KWiy+5kgXKPwBaaGGO7pemzF+n0tLT9fCY7jL5P99Hw0KOUwPhqzeYpcj1RU+WYHcX7CbJr7qwGxawU4npv07MKfawOb3QqOo0tLAp51Lrf9ilR63kYAlomD638T1e6xySHUSyOxAhzPT6kIKDBRFu1o7xddbts9Xp/bQ+ncv1dMH4k4+P5foWaqSKgKek61dg5dmk7TyBq6feeH4DgO3mJ3wF1gX2q3Wa5pNEwtBf3UPyEg9MAfDE4N0dv12MoLEBxWP3hw2n6pIiqwWERYrVKd0ymXcfwVfFabRTTU/iOwx04gpyaRVpQpI7HygX0tLbtWTqTTDBAAQOWcDKdLhigJlVbZYqN06k8fc70MTQFGjqLC74FMBAx0nEQqEQcoPQ/RNdTTtWXlRemUX1GCJyBwOGVEIylHJJTIZLM6mXMFbtJoUCDaJtZiRHTYCkGoHTQRw3B3JzyBUowND3YPnuna2tTcsu832krwPJc3BHBu1+rrGUUup7/T3TXcdS5lrzIIQSatSlz/W48uXC5/ieMoTAbYbQ4kR9NoO3K0K5tVtjY3t+zd+/wKkDzWxKQgVqsEwzA6RUno5Lg5lvwmsYH2j3Hid//WIEqyX6ZePLDGAso0DI1Gh0fHo+9ntOTLgYKTH+zcuRKUUty5aXYQE666xra8aR0qPTnSMSp+3zCxg6Mk98V66+lFZdreeCLx65FQ/MSyW4Oqkk5BFHis3XRlhbprDrJ0xTpwBL6sQd5iQICAvWLo+pss2dWx/qt1hpHTYDACSoCH/+a9Kx7nfwAPPztG5sk4owAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMi0wOS0yMlQyMjoxNjoxNyswMDowMOu8Z3oAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjItMDktMjJUMjI6MTY6MTcrMDA6MDCa4d/GAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAABJRU5ErkJggg==' I tried to create a button by importing the base64 image from another file. There are two buttons in the application, one works and the image appears, the other does not work and the image does not appear. I would like to make the second one work. All the code will generate this image. The bottom button that doesn't show the image is in the widgets.py file I don't know why, but when I import it, it doesn't work. Thank you in advance for your attention and I apologize if something was wrong or out of standard, my English is not very good.
[ "It is because there is no variable referencing the instance of Botoes(), so it will be garbage collected (so as the image inside it).\nJust use a variable to store the instance of Botoes():\nclass Janela(Images):\n def __init__(self) -> None:\n self.images_base64()\n self.tamJanela()\n\n def tamJanela(self):\n self.janela_doMenu = tk.Tk()\n janela = self.janela_doMenu\n # janela.state('zoomed')\n janela.title('Disk Gás Gonçalves')\n janela.configure(background=preto_claro)\n janela.geometry(\"%dx%d\" % (janela.winfo_screenwidth(), janela.winfo_screenheight()))\n\n # Here the code works ###############################################################\n self.img_icoName = tk.PhotoImage(data=base64.b64decode(self.editUser))\n self.rotulo_nome2 = tk.Button(master=janela, image=self.img_icoName, activebackground='#00FA9A', bg='#4F4F4F',\n highlightbackground='#4F4F4F', highlightcolor='#4F4F4F')\n self.rotulo_nome2.grid(row=0, column=0)\n\n # need a variable to store the instance of Botoes\n # to avoid garbage collection\n botoes = Botoes(janela)\n\n janela.minsize(1200, 640)\n\n janela.mainloop()\n\nResult:\n\n" ]
[ 0 ]
[]
[]
[ "base64", "python", "tkinter" ]
stackoverflow_0074589749_base64_python_tkinter.txt
Q: I am getting TypeError: Person() takes no arguments I have 2 underscores for init class Person: def __int__(self, name): self.name = name def talk(self): print('talk') john = Person("John Smith") print(john.name) john.talk() what could be the problem?
I am getting TypeError: Person() takes no arguments I have 2 underscores for init
class Person: def __int__(self, name): self.name = name def talk(self): print('talk') john = Person("John Smith") print(john.name) john.talk() what could be the problem?
[]
[]
[ "You have wrote __int__, and not __init__\n" ]
[ -1 ]
[ "pycharm", "python" ]
stackoverflow_0074591587_pycharm_python.txt
Q: making a sort algorithm but it works only sometimes trying to make a basic sorting algorithm that slowly puts one number from list1 to list2. it should be lowest to highest. i do know there are better sorting algorithm but i want to make my own shitty own list1 = [3,1,2,8,4,73,6,9,14,12,6712,23,76,111,312,42] list2 = [-1] w = 0 for i in range(len(list1)): while w != len(list1): if list1[w] > list2[w]: list2.append(list1[w]) print(list2) w+=1 elif list1[w] < list2[w]: if list1[w] < list2[w-1]: list2.insert(w-1,list1[w]) print(list2) w+=1 list2.insert(w,list1[w]) print(list2) w+=1 break print(list2) output: [-1, 3] [-1, 1, 3] [-1, 1, 2, 3] [-1, 1, 2, 3, 8] [-1, 1, 2, 3, 4, 8] [-1, 1, 2, 3, 4, 8, 73] [-1, 1, 2, 3, 4, 6, 8, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 14, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 6712, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73, 111] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73, 111, 312] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73, 42, 111, 312] Traceback (most recent call last): File "C:/Users/alexi/Downloads/test.py", line 17, in <module> list2.insert(w,list1[w]) IndexError: list index out of range it all works fine until 6712 is introducted the it starts breaking. not sure about the error aswell but it probally has to do with a number being in list2 at the very start. it doesnt work if there isnt a number in list2 at the very start so i put in -1 as a starting number. would like to make list2 completely empty at the start but not sure how to do that. only thing i could think of to fix the sorting is making a def but have no idea where to start with that. any help with the error/sorting/making list2 empty at the start? any help is great :) A: not sure about the error aswell but it probally has to do with a number being in list2 at the very start The first item in list2 is not your problem. The issue is that you are at times making two insertions to your list (check code block under condition elif list1[w] < list2[w]:), but evaluating the loop condition only once in the beginning, thus the indexing error occurring. not sure about the error as well but it probably has to do with a number being in list2 at the very start If list2 is empty you are not able to evaluate your conditions like list1[w] > list2[w], because there is no index 0 in an empty list. The solution is to insert the first element from your list1 to list2 outside your loop. To me, it seems you are trying to implement something similar to the insertion sort algorithm, so checking that out might help you further. For example: https://www.geeksforgeeks.org/insertion-sort/ The success rate of your current solution is related to how sorted the list is to begin with. This is why it "works only sometimes".
making a sort algorithm but it works only sometimes
trying to make a basic sorting algorithm that slowly puts one number from list1 to list2. it should be lowest to highest. i do know there are better sorting algorithm but i want to make my own shitty own list1 = [3,1,2,8,4,73,6,9,14,12,6712,23,76,111,312,42] list2 = [-1] w = 0 for i in range(len(list1)): while w != len(list1): if list1[w] > list2[w]: list2.append(list1[w]) print(list2) w+=1 elif list1[w] < list2[w]: if list1[w] < list2[w-1]: list2.insert(w-1,list1[w]) print(list2) w+=1 list2.insert(w,list1[w]) print(list2) w+=1 break print(list2) output: [-1, 3] [-1, 1, 3] [-1, 1, 2, 3] [-1, 1, 2, 3, 8] [-1, 1, 2, 3, 4, 8] [-1, 1, 2, 3, 4, 8, 73] [-1, 1, 2, 3, 4, 6, 8, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 14, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 6712, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73, 111] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73, 111, 312] [-1, 1, 2, 3, 4, 6, 8, 9, 12, 14, 23, 6712, 76, 73, 42, 111, 312] Traceback (most recent call last): File "C:/Users/alexi/Downloads/test.py", line 17, in <module> list2.insert(w,list1[w]) IndexError: list index out of range it all works fine until 6712 is introducted the it starts breaking. not sure about the error aswell but it probally has to do with a number being in list2 at the very start. it doesnt work if there isnt a number in list2 at the very start so i put in -1 as a starting number. would like to make list2 completely empty at the start but not sure how to do that. only thing i could think of to fix the sorting is making a def but have no idea where to start with that. any help with the error/sorting/making list2 empty at the start? any help is great :)
[ "\nnot sure about the error aswell but it probally has to do with a\nnumber being in list2 at the very start\n\nThe first item in list2 is not your problem. The issue is that you are at times making two insertions to your list (check code block under condition elif list1[w] < list2[w]:), but evaluating the loop condition only once in the beginning, thus the indexing error occurring.\n\nnot sure about the error as well but it probably has to do with a\nnumber being in list2 at the very start\n\nIf list2 is empty you are not able to evaluate your conditions like list1[w] > list2[w], because there is no index 0 in an empty list. The solution is to insert the first element from your list1 to list2 outside your loop.\nTo me, it seems you are trying to implement something similar to the insertion sort algorithm, so checking that out might help you further. For example: https://www.geeksforgeeks.org/insertion-sort/ The success rate of your current solution is related to how sorted the list is to begin with. This is why it \"works only sometimes\".\n" ]
[ 1 ]
[]
[]
[ "algorithm", "python", "sorting" ]
stackoverflow_0074591342_algorithm_python_sorting.txt
Q: NotFoundError using BERT Preprocessing from TFHub I'm trying to use the pre-trained BERT models on TensorFlow Hub to do some simple NLP. I'm on a 2021 MacBook Pro (Apple Silicon) with Python 3.9.13 and TensorFlow v2.9.2. However, preprocessing any amount of text returns a "NotFoundError" that I can't seem to resolve. The link to the preprocessing model is here: (https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3) and I have pasted my code/error messages below. Does anyone know why this is happening and how I can fix it? Thanks in advance. Code bert_preprocess = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3") bert_encoder = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4") print(bert_preprocess(["test"])) Output Output exceeds the size limit. Open the full output data in a text editor --------------------------------------------------------------------------- NotFoundError Traceback (most recent call last) Cell In [42], line 3 1 bert_preprocess = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3") 2 bert_encoder = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4") ----> 3 print(bert_preprocess(["test"])) File ~/miniforge3/envs/tfenv/lib/python3.9/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs) 65 except Exception as e: # pylint: disable=broad-except 66 filtered_tb = _process_traceback_frames(e.__traceback__) ---> 67 raise e.with_traceback(filtered_tb) from None 68 finally: 69 del filtered_tb File ~/miniforge3/envs/tfenv/lib/python3.9/site-packages/tensorflow_hub/keras_layer.py:237, in KerasLayer.call(self, inputs, training) 234 else: 235 # Behave like BatchNormalization. (Dropout is different, b/181839368.) 236 training = False --> 237 result = smart_cond.smart_cond(training, 238 lambda: f(training=True), 239 lambda: f(training=False)) 241 # Unwrap dicts returned by signatures. 242 if self._output_key: File ~/miniforge3/envs/tfenv/lib/python3.9/site-packages/tensorflow_hub/keras_layer.py:239, in KerasLayer.call.<locals>.<lambda>() ... [[StatefulPartitionedCall/StatefulPartitionedCall/bert_pack_inputs/PartitionedCall/RaggedConcat/ArithmeticOptimizer/AddOpsRewrite_Leaf_0_add_2]] [Op:__inference_restored_function_body_209194] Call arguments received by layer "keras_layer_6" (type KerasLayer): • inputs=["'test'"] • training=None A: Update: While using BERT preprocessing from TFHub, Tensorflow and tensorflow_text versions should be same so please make sure that installed both versions are same. It happens because you're using latest version for tensorflow_text but you're using other versions for python and tensorflow but there is internal dependancy with versions for Tensorflow and tensorflow_text which should be same. !pip install -U tensorflow !pip install -U tensorflow-text import tensorflow as tf import tensorflow_text as text # Or install with a specific Version !pip install -U tensorflow==2.11.* !pip install -U tensorflow-text==2.11.* import tensorflow as tf import tensorflow_text as text I have executed below lines of code in Google Colab and It's working fine, bert_preprocess = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3") bert_encoder = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4") print(bert_preprocess(["test"])) Here is output: {'input_type_ids': <tf.Tensor: shape=(1, 128), dtype=int32, numpy= array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)>, 'input_mask': <tf.Tensor: shape=(1, 128), dtype=int32, numpy= array([[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)>, 'input_word_ids': <tf.Tensor: shape=(1, 128), dtype=int32, numpy= array([[ 101, 3231, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32)>} I hope it will help you to resolve your issue, Thank You!
NotFoundError using BERT Preprocessing from TFHub
I'm trying to use the pre-trained BERT models on TensorFlow Hub to do some simple NLP. I'm on a 2021 MacBook Pro (Apple Silicon) with Python 3.9.13 and TensorFlow v2.9.2. However, preprocessing any amount of text returns a "NotFoundError" that I can't seem to resolve. The link to the preprocessing model is here: (https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3) and I have pasted my code/error messages below. Does anyone know why this is happening and how I can fix it? Thanks in advance. Code bert_preprocess = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3") bert_encoder = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4") print(bert_preprocess(["test"])) Output Output exceeds the size limit. Open the full output data in a text editor --------------------------------------------------------------------------- NotFoundError Traceback (most recent call last) Cell In [42], line 3 1 bert_preprocess = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3") 2 bert_encoder = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4") ----> 3 print(bert_preprocess(["test"])) File ~/miniforge3/envs/tfenv/lib/python3.9/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs) 65 except Exception as e: # pylint: disable=broad-except 66 filtered_tb = _process_traceback_frames(e.__traceback__) ---> 67 raise e.with_traceback(filtered_tb) from None 68 finally: 69 del filtered_tb File ~/miniforge3/envs/tfenv/lib/python3.9/site-packages/tensorflow_hub/keras_layer.py:237, in KerasLayer.call(self, inputs, training) 234 else: 235 # Behave like BatchNormalization. (Dropout is different, b/181839368.) 236 training = False --> 237 result = smart_cond.smart_cond(training, 238 lambda: f(training=True), 239 lambda: f(training=False)) 241 # Unwrap dicts returned by signatures. 242 if self._output_key: File ~/miniforge3/envs/tfenv/lib/python3.9/site-packages/tensorflow_hub/keras_layer.py:239, in KerasLayer.call.<locals>.<lambda>() ... [[StatefulPartitionedCall/StatefulPartitionedCall/bert_pack_inputs/PartitionedCall/RaggedConcat/ArithmeticOptimizer/AddOpsRewrite_Leaf_0_add_2]] [Op:__inference_restored_function_body_209194] Call arguments received by layer "keras_layer_6" (type KerasLayer): • inputs=["'test'"] • training=None
[ "Update: While using BERT preprocessing from TFHub, Tensorflow and tensorflow_text versions should be same so please make sure that installed both versions are same. It happens because you're using latest version for tensorflow_text but you're using other versions for python and tensorflow but there is internal dependancy with versions for Tensorflow and tensorflow_text which should be same.\n!pip install -U tensorflow\n!pip install -U tensorflow-text\nimport tensorflow as tf\nimport tensorflow_text as text\n\n# Or install with a specific Version\n!pip install -U tensorflow==2.11.*\n!pip install -U tensorflow-text==2.11.*\nimport tensorflow as tf\nimport tensorflow_text as text\n\nI have executed below lines of code in Google Colab and It's working fine,\nbert_preprocess = hub.KerasLayer(\"https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3\")\nbert_encoder = hub.KerasLayer(\"https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4\")\nprint(bert_preprocess([\"test\"])) \n\nHere is output:\n{'input_type_ids': <tf.Tensor: shape=(1, 128), dtype=int32, numpy=\narray([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],\n dtype=int32)>, 'input_mask': <tf.Tensor: shape=(1, 128), dtype=int32, numpy=\narray([[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],\n dtype=int32)>, 'input_word_ids': <tf.Tensor: shape=(1, 128), dtype=int32, numpy=\narray([[ 101, 3231, 102, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0]], dtype=int32)>}\n\nI hope it will help you to resolve your issue, Thank You!\n" ]
[ 0 ]
[]
[]
[ "bert_language_model", "data_preprocessing", "python", "tensorflow", "tensorflow_hub" ]
stackoverflow_0074554805_bert_language_model_data_preprocessing_python_tensorflow_tensorflow_hub.txt
Q: Passing a list of strings to from python/ctypes to C function expecting char ** I have a C function which expects a list \0 terminated strings as input: void external_C( int length , const char ** string_list) { // Inspect the content of string_list - but not modify it. } From python (with ctypes) I would like to call this function based on a list of python strings: def call_c( string_list ): lib.external_C( ?? ) call_c( ["String1" , "String2" , "The last string"]) Any tips on how to build up the datastructure on the python side? Observe that I guarantee that the C function will NOT alter content of the strings in string_list. Regards joakim A: def call_c(L): arr = (ctypes.c_char_p * len(L))() arr[:] = L lib.external_C(len(L), arr) A: Thank you very much; that worked like charm. I also did an alternative variation like this: def call_c( L ): arr = (ctypes.c_char_p * (len(L) + 1))() arr[:-1] = L arr[ len(L) ] = None lib.external_C( arr ) And then in C-function I iterated through the (char **) list until I found a NULL. A: Using ctypes create list of expiries( strings) expiries = ["1M", "2M", "3M", "6M","9M", "1Y", "2Y", "3Y","4Y", "5Y", "6Y", "7Y","8Y", "9Y", "10Y", "11Y","12Y", "15Y", "20Y", "25Y", "30Y"] Logic to send string array convert strings array to bytes array by looping in the array expiries_bytes = [] for i in range(len(expiries)): expiries_bytes.append(bytes(expiries[i], 'utf-8')) Logic ctypes to initiate a pointer with a length of array expiries_array = (ctypes.c_char_p * (len(expiries_bytes)+1))() assigning the byte array into the pointer expiries_array[:-1] = expiries_bytes A: I just make it using SWIG typemap 1.write customized typemap in demo.i interface file. %module demo /* tell SWIG to treat char ** as a list of strings */ %typemap(in) char ** { // check if is a list if(PyList_Check($input)) { int size = PyList_Size($input); int i = 0; $1 = (char **)malloc((size + 1)*sizeof(char *)); for(i = 0; i < size; i++) { PyObject * o = PyList_GetItem($input, i); if(PyString_Check(o)) $1[i] = PyString_AsString(o); else { PyErr_SetString(PyExc_TypeError, "list must contain strings"); free($1); return NULL; } } } else { PyErr_SetString(PyExc_TypeError, "not a list"); return NULL; } } // clean up the char ** array %typemap(freearg) char ** { free((char *) $1); } 2.generate extension $ swig -python demo.i // generate wrap code $ gcc -c -fpic demo.c demo_wrap.c $ gcc -shared demo.o demo_wrap.o -o _demo.so 3.import the module in python. >>> from demo import yourfunction A: This is a pretty old question, but I think worth to add if people still search for similar question. using numpy, would be probably easiest way for handling all the low level manipulations and linking with with libraries. example = ["String1" , "String2" , "The last string"] example_np = m = np.array(example, dtype=np.chararray) when you build you numpy array of char*, you could just get the pointer to array (with ctypes and directly give it to the lib expecting char**. example_ptr = ctypes.cast(example_np.ctypes.data, ctypes.POINTER(ctypes.c_char_p)) # this is char** and you could just call lib.external_C(len(example), example_ptr)
Passing a list of strings to from python/ctypes to C function expecting char **
I have a C function which expects a list \0 terminated strings as input: void external_C( int length , const char ** string_list) { // Inspect the content of string_list - but not modify it. } From python (with ctypes) I would like to call this function based on a list of python strings: def call_c( string_list ): lib.external_C( ?? ) call_c( ["String1" , "String2" , "The last string"]) Any tips on how to build up the datastructure on the python side? Observe that I guarantee that the C function will NOT alter content of the strings in string_list. Regards joakim
[ "def call_c(L):\n arr = (ctypes.c_char_p * len(L))()\n arr[:] = L\n lib.external_C(len(L), arr)\n\n", "Thank you very much; that worked like charm. I also did an alternative variation like this:\ndef call_c( L ):\n arr = (ctypes.c_char_p * (len(L) + 1))()\n arr[:-1] = L\n arr[ len(L) ] = None\n lib.external_C( arr )\n\nAnd then in C-function I iterated through the (char **) list until I found a NULL.\n", "Using ctypes\ncreate list of expiries( strings)\nexpiries = [\"1M\", \"2M\", \"3M\", \"6M\",\"9M\", \"1Y\", \"2Y\", \"3Y\",\"4Y\", \"5Y\", \"6Y\", \"7Y\",\"8Y\", \"9Y\", \"10Y\", \"11Y\",\"12Y\", \"15Y\", \"20Y\", \"25Y\", \"30Y\"]\n\nLogic to send string array\nconvert strings array to bytes array by looping in the array\n expiries_bytes = []\n for i in range(len(expiries)):\n expiries_bytes.append(bytes(expiries[i], 'utf-8'))\n\nLogic ctypes to initiate a pointer with a length of array\nexpiries_array = (ctypes.c_char_p * (len(expiries_bytes)+1))()\n\nassigning the byte array into the pointer\nexpiries_array[:-1] = expiries_bytes\n\n", "I just make it using SWIG typemap\n1.write customized typemap in demo.i interface file.\n%module demo\n\n/* tell SWIG to treat char ** as a list of strings */\n%typemap(in) char ** {\n // check if is a list\n if(PyList_Check($input))\n {\n int size = PyList_Size($input);\n int i = 0;\n $1 = (char **)malloc((size + 1)*sizeof(char *));\n for(i = 0; i < size; i++)\n {\n PyObject * o = PyList_GetItem($input, i);\n if(PyString_Check(o))\n $1[i] = PyString_AsString(o);\n else\n {\n PyErr_SetString(PyExc_TypeError, \"list must contain strings\");\n free($1);\n return NULL;\n }\n }\n }\n else\n {\n PyErr_SetString(PyExc_TypeError, \"not a list\");\n return NULL;\n }\n}\n\n// clean up the char ** array\n%typemap(freearg) char ** {\n free((char *) $1);\n}\n\n2.generate extension\n$ swig -python demo.i // generate wrap code\n$ gcc -c -fpic demo.c demo_wrap.c\n$ gcc -shared demo.o demo_wrap.o -o _demo.so\n\n3.import the module in python.\n>>> from demo import yourfunction\n\n", "This is a pretty old question, but I think worth to add if people still search for similar question.\nusing numpy, would be probably easiest way for handling all the low level manipulations and linking with with libraries.\nexample = [\"String1\" , \"String2\" , \"The last string\"]\nexample_np = m = np.array(example, dtype=np.chararray)\n\nwhen you build you numpy array of char*, you could just get the pointer to array (with ctypes and directly give it to the lib expecting char**.\nexample_ptr = ctypes.cast(example_np.ctypes.data, ctypes.POINTER(ctypes.c_char_p)) # this is char**\n\nand you could just call\nlib.external_C(len(example), example_ptr)\n\n" ]
[ 26, 6, 5, 1, 0 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0003494598_c_ctypes_python.txt
Q: how do I keep track of a minimum across recursion calls I am trying my way around practising recursion and I want to find the minimum ways to generate a sum with given coins. I did figure out a way to do using a global variable but I've heard it's not really optimal to do it this way This is my code minres = 10000 def count(sum, i, coins, temp, res): global minres if sum == 0: minres = min(minres, res) return if sum < 0: return if i == len(coins): return temp.append(coins[i]) count(sum-coins[i], i, coins, temp, res+1) temp.pop() count(sum, i+1, coins, temp, res) return minres coins = [9, 6, 5, 1] print(count(11, 0, coins, [], 0)) This code works and I get the answer 2, but is there a way I can do it without a global variable or something of the sort? A: Here's a modified version of your function that doesn't rely on a global definition of minres. By passing minres to and returning it from every function call, it no longer needs to be "remembered" outside the scope of each function call: def count(sm, i, coins, res, temp=None, minres = 10000): if temp is None: temp = [] if sm == 0: minres = min(minres, res) if sm < 0: return minres if i == len(coins): return minres temp.append(coins[i]) minres = count(sm-coins[i], i, coins, res+1, temp, minres) temp.pop() minres = count(sm, i+1, coins, res, temp, minres) return minres A couple of other changes I've made: temp = [] in your call signature is dicey because the default argument is mutable. Better to use None as a cue within your call to default temp to []. I've avoided using sum as a variable name given it is a builtin function within Python. By reassigning something to the name sum other than its original meaning, you risk confusing things later on.
how do I keep track of a minimum across recursion calls
I am trying my way around practising recursion and I want to find the minimum ways to generate a sum with given coins. I did figure out a way to do using a global variable but I've heard it's not really optimal to do it this way This is my code minres = 10000 def count(sum, i, coins, temp, res): global minres if sum == 0: minres = min(minres, res) return if sum < 0: return if i == len(coins): return temp.append(coins[i]) count(sum-coins[i], i, coins, temp, res+1) temp.pop() count(sum, i+1, coins, temp, res) return minres coins = [9, 6, 5, 1] print(count(11, 0, coins, [], 0)) This code works and I get the answer 2, but is there a way I can do it without a global variable or something of the sort?
[ "Here's a modified version of your function that doesn't rely on a global definition of minres. By passing minres to and returning it from every function call, it no longer needs to be \"remembered\" outside the scope of each function call:\ndef count(sm, i, coins, res, temp=None, minres = 10000):\n if temp is None:\n temp = []\n if sm == 0:\n minres = min(minres, res)\n\n if sm < 0:\n return minres\n\n if i == len(coins):\n return minres\n\n temp.append(coins[i])\n minres = count(sm-coins[i], i, coins, res+1, temp, minres)\n temp.pop()\n minres = count(sm, i+1, coins, res, temp, minres)\n\n return minres\n\nA couple of other changes I've made:\n\ntemp = [] in your call signature is dicey because the default argument is mutable. Better to use None as a cue within your call to default temp to [].\nI've avoided using sum as a variable name given it is a builtin function within Python. By reassigning something to the name sum other than its original meaning, you risk confusing things later on.\n\n" ]
[ 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074591092_python_recursion.txt
Q: How to convert an "attribute call" into a "method call" in Python? From my understanding of OOP in Python, if there is no attribute named xyz on an object a, then invoking a.xyz raises "AttributeError." But in beautifulsoup, if we call any arbitrary attribute on an object of type Tag, we always get some output. For instance, >>> from bs4 import BeautifulSoup >>> import requests >>> html = requests.get("https://wwww.bing.com").text >>> tag = BeautifulSoup(html, 'html5lib') >>> print(tag.title) # makes sense <title>Bing</title> >>> print(tag.no_such_attrib) # should throw AttributeError None Here, it is implied that tag_obj.anything.something gets executed as tag_obj.find("anything").find("something"). But I just can't imagine which type of construct transforms the former form into the later one. A: No imagination necessary. We can just look at the source: (abbreviated by me) class Tag(PageElement): ... def __getattr__(self, tag): """Calling tag.subtag is the same as calling tag.find(name="subtag")""" if not tag.startswith("__") and not tag == "contents": return self.find(tag) raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__, tag)) See the Python data model documentation for more information about attribute access. Here is another very simple illustration of how you can override attribute access to get None instead of an AttributeError, when an attribute does not exist on an object: class Foo: def __getattr__(self, item: str): return self.__dict__.get(item) if __name__ == "__main__": foo = Foo() foo.bar = 1 print(foo.bar) # 1 print(foo.baz) # None Making use of dict.get defaulting to None here. In short: Attribute access is a method call. Always. Though not always via the same method. A: Are you familiar with getattr(obj,"no_such_attrib","xxx") form? xxx can be anything: None, an empty dict, a default value. Even another function call. It needs no complicated __getattr__ method and you can vary what you are up at the point of call. So,yes find_something(). Not sure if it gets called anyway if nothing is found (I assume so). If that is undesirable, boolean short circuiting helps: X = getattr(obj,"no_such_attrib",None) or find_something() Within a an predefined set of classes, __getattr__ is likely to be doing the job- as stated in DF’s answer- , as the provider. As a user, or just to avoid edge case work on your own classes for particular internal uses, getattr is low effort (and avoids recursion errors that often whack you on __getattr__): def __getattr__(self, attrname): " sloppy __getattr__ love recursion error :-( " if attrname = "missing_attribute"): return self.another_missing_attribute elif attrname = "another_missing_attribute"): return self.missing_attribute else: raise AttributeError(attrname) Note: similarly dict subclasses can implement __missing__.
How to convert an "attribute call" into a "method call" in Python?
From my understanding of OOP in Python, if there is no attribute named xyz on an object a, then invoking a.xyz raises "AttributeError." But in beautifulsoup, if we call any arbitrary attribute on an object of type Tag, we always get some output. For instance, >>> from bs4 import BeautifulSoup >>> import requests >>> html = requests.get("https://wwww.bing.com").text >>> tag = BeautifulSoup(html, 'html5lib') >>> print(tag.title) # makes sense <title>Bing</title> >>> print(tag.no_such_attrib) # should throw AttributeError None Here, it is implied that tag_obj.anything.something gets executed as tag_obj.find("anything").find("something"). But I just can't imagine which type of construct transforms the former form into the later one.
[ "No imagination necessary. We can just look at the source: (abbreviated by me)\nclass Tag(PageElement):\n ...\n\n def __getattr__(self, tag):\n \"\"\"Calling tag.subtag is the same as calling tag.find(name=\"subtag\")\"\"\"\n if not tag.startswith(\"__\") and not tag == \"contents\":\n return self.find(tag)\n raise AttributeError(\"'%s' object has no attribute '%s'\" % (self.__class__, tag))\n\nSee the Python data model documentation for more information about attribute access.\nHere is another very simple illustration of how you can override attribute access to get None instead of an AttributeError, when an attribute does not exist on an object:\nclass Foo:\n def __getattr__(self, item: str):\n return self.__dict__.get(item)\n\n\nif __name__ == \"__main__\":\n foo = Foo()\n foo.bar = 1\n print(foo.bar) # 1\n print(foo.baz) # None\n\nMaking use of dict.get defaulting to None here.\n\nIn short: Attribute access is a method call. Always. Though not always via the same method.\n", "Are you familiar with getattr(obj,\"no_such_attrib\",\"xxx\") form? xxx can be anything: None, an empty dict, a default value. Even another function call. It needs no complicated __getattr__ method and you can vary what you are up at the point of call.\nSo,yes find_something(). Not sure if it gets called anyway if nothing is found (I assume so). If that is undesirable, boolean short circuiting helps:\n\nX = getattr(obj,\"no_such_attrib\",None) or find_something()\n\n\nWithin a an predefined set of classes, __getattr__ is likely to be doing the job- as stated in DF’s answer- , as the provider. As a user, or just to avoid edge case work on your own classes for particular internal uses, getattr is low effort\n(and avoids recursion errors that often whack you on __getattr__):\n\ndef __getattr__(self, attrname):\n \" sloppy __getattr__ love recursion error :-( \"\n\n if attrname = \"missing_attribute\"):\n return self.another_missing_attribute\n elif attrname = \"another_missing_attribute\"):\n return self.missing_attribute\n else:\n raise AttributeError(attrname)\n\n\nNote: similarly dict subclasses can implement __missing__.\n" ]
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "class", "oop", "python" ]
stackoverflow_0074590670_beautifulsoup_class_oop_python.txt
Q: Is there a way to count the frequency of an element in a list without using predefined functions/sets/dictionaries? first want to say I am new to Python but I am eager to learn and have searched around for a solution, can't seem to figure this problem out without resorting to many lines of code. We recently recieved an assignment for our course which looks this: Write a program that, given a text, computes the frequency of every letter and outputs the most and the least frequent one. Do not use:  • external libraries (no "import" statement is allowed) • dictionaries • sets • predefined functions (e.g., max(), min() ) I have asked for clarification on the predefined functions but have not received a reply. Would be grateful for your input or feedback, I'll paste my code so far below, it's unfinished but gives an idea of what it will look like. I did use "count" in it but I can replace that with my own counters if we aren't allowed to use "count." txt = input('Skriv en text: ').replace(" ","").lower() counters = [] for c in txt: counters.append(c) a = counters.count("a") b = counters.count("b") c = counters.count("c") d = counters.count("d") e = counters.count("e") f = counters.count("f") g = counters.count("g") h = counters.count("h") i = counters.count("i") j = counters.count("j") k = counters.count("k") l = counters.count("l") m = counters.count("m") n = counters.count("n") o = counters.count("o") p = counters.count("p") q = counters.count("q") r = counters.count("r") s = counters.count("s") t = counters.count("t") u = counters.count("u") v = counters.count("v") x = counters.count("x") y = counters.count("y") z = counters.count("z") if a >= b or c or d or e or f or g or h or i or j or k or l or m or n or o or p or q or r or s or t or u or v or x or y or z: print ("A has the highest frequency.") elif b >= a or c or d or e or f or g or h or i or j or k or l or m or n or o or p or q or r or s or t or u or v or x or y or z: print() # Will do this for each letter and for the minimum value as well A: For each character in the string, add it and its count to a list if it's not already in the list. This requires nested loops and therefore has terrible performance implications for large strings. def count(s): counts = [] for c in s: if not any(True for (k, _) in counts if k == c): counts.append((c, s.count(c))) return counts >>> count("hello world") [('h', 1), ('e', 1), ('l', 3), ('o', 2), (' ', 1), ('w', 1), ('r', 1), ('d', 1)] A: I believe Chris solution is the smallest possible, I however prefer readability, so here it's an alternative solution: def count_char(word): counter_list = [] for char in word: index = get_index(char, counter_list) if(index == -1): counter_list.append((char, 1)) else: char, value = counter_list[index] value += 1 counter_list[index] = (char, value) return counter_list def get_index(character, haystack) -> int: for index, char_tuple in enumerate(haystack): char, _ = char_tuple if char == character: return index return -1 count_char("myrepeatedword") As already stated, due to the constraints of your problem, the performance here is far away from being optimal.
Is there a way to count the frequency of an element in a list without using predefined functions/sets/dictionaries?
first want to say I am new to Python but I am eager to learn and have searched around for a solution, can't seem to figure this problem out without resorting to many lines of code. We recently recieved an assignment for our course which looks this: Write a program that, given a text, computes the frequency of every letter and outputs the most and the least frequent one. Do not use:  • external libraries (no "import" statement is allowed) • dictionaries • sets • predefined functions (e.g., max(), min() ) I have asked for clarification on the predefined functions but have not received a reply. Would be grateful for your input or feedback, I'll paste my code so far below, it's unfinished but gives an idea of what it will look like. I did use "count" in it but I can replace that with my own counters if we aren't allowed to use "count." txt = input('Skriv en text: ').replace(" ","").lower() counters = [] for c in txt: counters.append(c) a = counters.count("a") b = counters.count("b") c = counters.count("c") d = counters.count("d") e = counters.count("e") f = counters.count("f") g = counters.count("g") h = counters.count("h") i = counters.count("i") j = counters.count("j") k = counters.count("k") l = counters.count("l") m = counters.count("m") n = counters.count("n") o = counters.count("o") p = counters.count("p") q = counters.count("q") r = counters.count("r") s = counters.count("s") t = counters.count("t") u = counters.count("u") v = counters.count("v") x = counters.count("x") y = counters.count("y") z = counters.count("z") if a >= b or c or d or e or f or g or h or i or j or k or l or m or n or o or p or q or r or s or t or u or v or x or y or z: print ("A has the highest frequency.") elif b >= a or c or d or e or f or g or h or i or j or k or l or m or n or o or p or q or r or s or t or u or v or x or y or z: print() # Will do this for each letter and for the minimum value as well
[ "For each character in the string, add it and its count to a list if it's not already in the list. This requires nested loops and therefore has terrible performance implications for large strings.\ndef count(s):\n counts = []\n for c in s:\n if not any(True for (k, _) in counts if k == c):\n counts.append((c, s.count(c)))\n return counts \n\n>>> count(\"hello world\")\n[('h', 1), ('e', 1), ('l', 3), ('o', 2), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]\n\n", "I believe Chris solution is the smallest possible, I however prefer readability, so here it's an alternative solution:\ndef count_char(word):\n counter_list = []\n\n for char in word: \n index = get_index(char, counter_list)\n if(index == -1):\n counter_list.append((char, 1))\n else:\n char, value = counter_list[index]\n value += 1\n counter_list[index] = (char, value)\n \n return counter_list\n\n\n\ndef get_index(character, haystack) -> int:\n\n for index, char_tuple in enumerate(haystack):\n char, _ = char_tuple\n if char == character:\n return index\n\n return -1\n\ncount_char(\"myrepeatedword\")\n\nAs already stated, due to the constraints of your problem, the performance here is far away from being optimal.\n" ]
[ 0, 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074591588_list_python_python_3.x.txt
Q: python endpoint starting a thread with locking I'm using FASTApi and trying to implement an endpoint, which starts a job. Once the job is started, the endpoint shall be "locked" until the previous job finished. So far its implemented like this: myapp.lock = threading.Lock() @myapp.get("/jobs") def start_job(some_args): if myapp.lock.acquire(False): th = threading.Thread(target=job,kwargs=some_args) th.start() return "Job started" else: raise HTTPException(status_code=400,detail="Job already running.") So, when the job gets started, a thread will be created using the method job: def job(some_args): try: #doing some stuff, creating objects and writing to files finally: myapp.lock.release() So far so good, the endpoint is working, starts a job and locks as long as the job is running. But my problem is that the thread is still alive although the job "finished" and released the lock. I was hoping that the thread would close itself after execution. Maybe the problem is that myapp is keeping it alive? How can I stop it? A: I figured out this kind of solution: myapp.lock = False @myapp.get("/jobs") async def start_job(some_args, background_tasks: BackgroundTasks): if not myapp.lock: background_tasks.add_task(job, some_args) return "Job started" else: raise HTTPException(status_code=400,detail="Job already running.") def job(some_args): try: myapp.lock = True #doing some stuff, creating objects and writing to files finally: myapp.lock = False A: I have faced the similar issue. I would like to block the request that want to change the state of a specific object (an object is a simulation in my case). I use PostgreSQL and have created the following Table create table simulation_lock (simulation_id INTEGER PRIMARY KEY, is_locked BOOLEAN DEFAULT False); Lock context: from starlette.exceptions import HTTPException from fmr.database import SessionContext class SimulationLock: def __init__(self, simulation_id: int): self._simulation_id = simulation_id self._was_acquired = False def __enter__(self): with SessionContext() as session: query = f"update simulation_lock set is_locked = true where " \ f"simulation_id = {self._simulation_id} " \ f"and is_locked = false returning is_locked;" result = session.execute(query).first() session.commit() if result is not None and result[0] is True: self._was_acquired = True else: raise HTTPException( status_code=500, detail="Already some operations on the " "simulation are performed.") def __exit__(self, exc_type, exc_val, exc_tb): if self._was_acquired: with SessionContext() as session: query = f"update simulation_lock set is_locked = false " \ f"where simulation_id = {self._simulation_id};" session.execute(query) session.commit() Endpoint: @scenario_router.post( "/run" ) async def run( run_scenario_request: RunScenarioRequest, ): with SimulationLock(run_scenario_request.scenario_id): run_scenario(run_scenario_request)
python endpoint starting a thread with locking
I'm using FASTApi and trying to implement an endpoint, which starts a job. Once the job is started, the endpoint shall be "locked" until the previous job finished. So far its implemented like this: myapp.lock = threading.Lock() @myapp.get("/jobs") def start_job(some_args): if myapp.lock.acquire(False): th = threading.Thread(target=job,kwargs=some_args) th.start() return "Job started" else: raise HTTPException(status_code=400,detail="Job already running.") So, when the job gets started, a thread will be created using the method job: def job(some_args): try: #doing some stuff, creating objects and writing to files finally: myapp.lock.release() So far so good, the endpoint is working, starts a job and locks as long as the job is running. But my problem is that the thread is still alive although the job "finished" and released the lock. I was hoping that the thread would close itself after execution. Maybe the problem is that myapp is keeping it alive? How can I stop it?
[ "I figured out this kind of solution:\nmyapp.lock = False\n\n@myapp.get(\"/jobs\")\nasync def start_job(some_args, background_tasks: BackgroundTasks):\n if not myapp.lock:\n background_tasks.add_task(job, some_args)\n return \"Job started\"\n else:\n raise HTTPException(status_code=400,detail=\"Job already running.\")\n\ndef job(some_args):\n try:\n myapp.lock = True\n #doing some stuff, creating objects and writing to files\n finally:\n myapp.lock = False\n\n", "I have faced the similar issue. I would like to block the request that want to change the state of a specific object (an object is a simulation in my case). I use PostgreSQL and have created the following\n\nTable\n\n create table simulation_lock (simulation_id INTEGER PRIMARY KEY, is_locked BOOLEAN DEFAULT False);\n\n\nLock context:\n\nfrom starlette.exceptions import HTTPException\n\nfrom fmr.database import SessionContext\n\n\nclass SimulationLock:\n\n def __init__(self, simulation_id: int):\n self._simulation_id = simulation_id\n self._was_acquired = False\n\n def __enter__(self):\n with SessionContext() as session:\n query = f\"update simulation_lock set is_locked = true where \" \\\n f\"simulation_id = {self._simulation_id} \" \\\n f\"and is_locked = false returning is_locked;\"\n result = session.execute(query).first()\n session.commit()\n\n if result is not None and result[0] is True:\n self._was_acquired = True\n else:\n raise HTTPException(\n status_code=500, detail=\"Already some operations on the \"\n \"simulation are performed.\")\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if self._was_acquired:\n with SessionContext() as session:\n query = f\"update simulation_lock set is_locked = false \" \\\n f\"where simulation_id = {self._simulation_id};\"\n session.execute(query)\n session.commit()\n\n\n\nEndpoint:\n\n@scenario_router.post(\n \"/run\"\n)\nasync def run(\n run_scenario_request: RunScenarioRequest,\n):\n with SimulationLock(run_scenario_request.scenario_id):\n run_scenario(run_scenario_request)\n\n" ]
[ 0, 0 ]
[]
[]
[ "fastapi", "multithreading", "python" ]
stackoverflow_0067193397_fastapi_multithreading_python.txt
Q: Folium - KeyErrors I'm currently trying to plot AirBnb locations in Paris using folium. My code is as below: f = folium.Figure(width = 800, height = 500) map = folium.Map(location = [48.8569421129686, 2.3503337285332204], # Coords for Paris zoom_start = 10, tiles = 'CartoDB positron').add_to(f) for index in range(0, len(df4)-1): lat = df4['latitude'][index] long = df4['longitude'][index] temp = lat, long folium.Marker(temp, marker_icon = 'cloud').add_to(map) map df4 is structured with the following columns: Index(['id', 'name', 'host_id', 'host_since', 'host_location', 'host_acceptance_rate', 'host_is_superhost', 'host_neighbourhood', 'neighbourhood_cleansed', 'latitude', 'longitude', 'property_type', 'room_type', 'accommodates', 'bedrooms', 'beds', 'price', 'minimum_nights', 'maximum_nights', 'number_of_reviews', 'review_scores_rating', 'review_scores_accuracy', 'review_scores_communication', 'review_scores_location', 'review_scores_value'], dtype='object') Why am I getting KeyError: 6 when I attempt to run my code? I attempted to use an if statement to catch index 6, but then I got KeyError 10. The data is formatted correctly, and all of the latitudes and longitudes are formatted uniformly. Why is it getting hung up on random rows? A: In your case, it is better to use the iterrows() method from the Pandas dataframe to iterate over the rows of the dataframe : for row in df4.iterrows(): lat = row[1]['latitude'] long = row[1]['longitude'] temp = lat, long folium.Marker(temp, marker_icon = 'cloud').add_to(map)
Folium - KeyErrors
I'm currently trying to plot AirBnb locations in Paris using folium. My code is as below: f = folium.Figure(width = 800, height = 500) map = folium.Map(location = [48.8569421129686, 2.3503337285332204], # Coords for Paris zoom_start = 10, tiles = 'CartoDB positron').add_to(f) for index in range(0, len(df4)-1): lat = df4['latitude'][index] long = df4['longitude'][index] temp = lat, long folium.Marker(temp, marker_icon = 'cloud').add_to(map) map df4 is structured with the following columns: Index(['id', 'name', 'host_id', 'host_since', 'host_location', 'host_acceptance_rate', 'host_is_superhost', 'host_neighbourhood', 'neighbourhood_cleansed', 'latitude', 'longitude', 'property_type', 'room_type', 'accommodates', 'bedrooms', 'beds', 'price', 'minimum_nights', 'maximum_nights', 'number_of_reviews', 'review_scores_rating', 'review_scores_accuracy', 'review_scores_communication', 'review_scores_location', 'review_scores_value'], dtype='object') Why am I getting KeyError: 6 when I attempt to run my code? I attempted to use an if statement to catch index 6, but then I got KeyError 10. The data is formatted correctly, and all of the latitudes and longitudes are formatted uniformly. Why is it getting hung up on random rows?
[ "In your case, it is better to use the iterrows() method from the Pandas dataframe to iterate over the rows of the dataframe :\nfor row in df4.iterrows():\n lat = row[1]['latitude']\n long = row[1]['longitude']\n temp = lat, long\n folium.Marker(temp, marker_icon = 'cloud').add_to(map)\n\n" ]
[ 0 ]
[]
[]
[ "folium", "geospatial", "python" ]
stackoverflow_0074578542_folium_geospatial_python.txt
Q: The same message appears when I type `yes` in the loop When I enter yes to repeat the game, then instead of repeating, this message appears: do you want to play again (yes or no): This only happens when I enter yes. But if I enter no, then it exits from the game. Code I have print(' Welcome to the gussing game :)') print("\n\nyou have only 3 attempts to win ") hidden_word = 'zak' guess_word = '' count_attempts = 0 limit_attempts = 3 play_again = 'yes' while play_again == 'yes': while (guess_word != hidden_word) and (count_attempts < limit_attempts): guess_word = input("\nplease enter your word: ") count_attempts += 1 if count_attempts == limit_attempts and guess_word != hidden_word: print("Sorry, you lose due to Out of attempts ") elif guess_word != hidden_word: print("Wrong attempt, try again ...") #Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one } else: print(" Wow you won !!") play_again = input('\ndo you want to play again (yes or no): ').lower() Question A: This is because you didn't reset the value of your variable, guess_word and count_attempts. Therefore, while (guess_word != hidden_word) and (count_attempts < limit_attempts): is always false in your second iteration onwards, and the inner while loop is skipped. You can reset the value before the inner while loop. while play_again == 'yes': guess_word = '' count_attempts = 0 while (guess_word != hidden_word) and (count_attempts < limit_attempts): guess_word = input("\nplease enter your word: ") count_attempts += 1 if count_attempts == limit_attempts and guess_word != hidden_word: print("Sorry, you lose due to Out of attempts ") elif guess_word != hidden_word: print("Wrong attempt, try again ...") #Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one } else: print(" Wow you won !!") play_again = input('\ndo you want to play again (yes or no): ').lower() A: The problem you're having is that after the user enters "yes", you need to set guess_word back to an empty string and reset count_attempts, otherwise the inner while loop conditional check is already false. In a final implementation you would also reset the hidden word at this time as well. The simplest solution would be to move almost all of the setup code inside of the outer while loop limit_attempts = 3 play_again = 'yes' while play_again == 'yes': print(' Welcome to the gussing game :)') print("\n\nyou have only 3 attempts to win ") hidden_word = 'zak' guess_word = '' count_attempts = 0 while (guess_word != hidden_word) and (count_attempts < limit_attempts): guess_word = input("\nplease enter your word: ") count_attempts += 1 if count_attempts == limit_attempts and guess_word != hidden_word: print("Sorry, you lose due to Out of attempts ") elif guess_word != hidden_word: print("Wrong attempt, try again ...") #Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one } else: print(" Wow you won !!") play_again = input('\ndo you want to play again (yes or no): ').lower()
The same message appears when I type `yes` in the loop
When I enter yes to repeat the game, then instead of repeating, this message appears: do you want to play again (yes or no): This only happens when I enter yes. But if I enter no, then it exits from the game. Code I have print(' Welcome to the gussing game :)') print("\n\nyou have only 3 attempts to win ") hidden_word = 'zak' guess_word = '' count_attempts = 0 limit_attempts = 3 play_again = 'yes' while play_again == 'yes': while (guess_word != hidden_word) and (count_attempts < limit_attempts): guess_word = input("\nplease enter your word: ") count_attempts += 1 if count_attempts == limit_attempts and guess_word != hidden_word: print("Sorry, you lose due to Out of attempts ") elif guess_word != hidden_word: print("Wrong attempt, try again ...") #Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one } else: print(" Wow you won !!") play_again = input('\ndo you want to play again (yes or no): ').lower() Question
[ "This is because you didn't reset the value of your variable, guess_word and count_attempts. Therefore, while (guess_word != hidden_word) and (count_attempts < limit_attempts): is always false in your second iteration onwards, and the inner while loop is skipped.\nYou can reset the value before the inner while loop.\nwhile play_again == 'yes':\n guess_word = ''\n count_attempts = 0\n while (guess_word != hidden_word) and (count_attempts < limit_attempts):\n guess_word = input(\"\\nplease enter your word: \")\n count_attempts += 1\n if count_attempts == limit_attempts and guess_word != hidden_word:\n print(\"Sorry, you lose due to Out of attempts \")\n elif guess_word != hidden_word:\n print(\"Wrong attempt, try again ...\")\n #Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one }\n else:\n print(\" Wow you won !!\")\n play_again = input('\\ndo you want to play again (yes or no): ').lower()\n\n", "The problem you're having is that after the user enters \"yes\", you need to set guess_word back to an empty string and reset count_attempts, otherwise the inner while loop conditional check is already false. In a final implementation you would also reset the hidden word at this time as well.\nThe simplest solution would be to move almost all of the setup code inside of the outer while loop\nlimit_attempts = 3\nplay_again = 'yes'\n\n\nwhile play_again == 'yes':\n print(' Welcome to the gussing game :)')\n print(\"\\n\\nyou have only 3 attempts to win \")\n\n hidden_word = 'zak'\n guess_word = ''\n count_attempts = 0\n while (guess_word != hidden_word) and (count_attempts < limit_attempts):\n guess_word = input(\"\\nplease enter your word: \")\n count_attempts += 1\n if count_attempts == limit_attempts and guess_word != hidden_word:\n print(\"Sorry, you lose due to Out of attempts \")\n elif guess_word != hidden_word:\n print(\"Wrong attempt, try again ...\")\n #Remember that {the order of the if statments is imporatnt and can change your result to be the unwanted one }\n else:\n print(\" Wow you won !!\")\n play_again = input('\\ndo you want to play again (yes or no): ').lower()\n\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074591692_python.txt
Q: When I want to remove an element from the list, it deletes it incorrectly pasw = "1234abc" mylist = list(pasw) a = list(map(lambda x: mylist.remove(x) if x.isnumeric() == True else False, mylist)) print(mylist) Output: ['2', '4', 'a', 'b', 'c'] I want to check if there is a number in the list, and if there is a number, I want to delete it from the list. A: As a general rule, it's not recommanded to modify a sequence you are iterating upon. The below function is similar to your map. def deleting_while_iterating(iterable): for i in iterable: iterable.remove(i) print(f"i: {i}, iterable: {iterable}") If I give this function your input, the output is: i: 1, iterable: ['2', '3', '4', 'a', 'b', 'c'] i: 3, iterable: ['2', '4', 'a', 'b', 'c'] i: a, iterable: ['2', '4', 'b', 'c'] i: c, iterable: ['2', '4', 'b'] As you can see, after the first iteration, "2" who originally was at index 1 is now at index 0. However, i is now at index 1 and thus "2" will be skipped. That's why it's better to create a new list containing only the elements you want. There are different ways to do it.
When I want to remove an element from the list, it deletes it incorrectly
pasw = "1234abc" mylist = list(pasw) a = list(map(lambda x: mylist.remove(x) if x.isnumeric() == True else False, mylist)) print(mylist) Output: ['2', '4', 'a', 'b', 'c'] I want to check if there is a number in the list, and if there is a number, I want to delete it from the list.
[ "As a general rule, it's not recommanded to modify a sequence you are iterating upon. The below function is similar to your map.\ndef deleting_while_iterating(iterable):\n for i in iterable:\n iterable.remove(i)\n print(f\"i: {i}, iterable: {iterable}\")\n\nIf I give this function your input, the output is:\ni: 1, iterable: ['2', '3', '4', 'a', 'b', 'c']\ni: 3, iterable: ['2', '4', 'a', 'b', 'c']\ni: a, iterable: ['2', '4', 'b', 'c']\ni: c, iterable: ['2', '4', 'b']\n\nAs you can see, after the first iteration, \"2\" who originally was at index 1 is now at index 0. However, i is now at index 1 and thus \"2\" will be skipped. That's why it's better to create a new list containing only the elements you want. There are different ways to do it.\n" ]
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074591788_list_python.txt
Q: Is there a way to insert an arbitrary symbol before the Python output value? I'm calculating the matrix value with Python, but I want to distinguish the value of equtaion, is there a way? x - y - 2z = 4 2x - y - z = 2 2x +y +4z = 16 I want to make the expression above like this when I print out the matrix from the function I created 1 -1 -2 | 4 2 -1 -1 | 2 2 1 4 | 16 Same as the rref result of this 1 0 0 | 24 0 1 0 | 72 0 0 1 | -26 def showMatrix(): print("\n") for i in sd: for j in i: print(j, end="\t") print("\n") def getone(pp): for i in range(len(sd[0])): if sd[pp][pp] != 1: q00 = sd[pp][pp] for j in range(len(sd[0])): sd[pp][j] = sd[pp][j] / q00 def getzero(r, c): for i in range(len(sd[0])): if sd[r][c] != 0: q04 = sd[r][c] for j in range(len(sd[0])): sd[r][j] = sd[r][j] - ((q04) * sd[c][j]) sd = [ [1, 1, 2, 9], [2, 4, -3, 1], [3, 6, -5, 0] ] showMatrix() for i in range(len(sd)): getone(i) for j in range(len(sd)): if i != j: getzero(j, i) showMatrix() print("FiNAL result") showMatrix() A: Here is a function which takes a list of 4 numbers and returns a string representing an equation in x,y,z. It handles coefficients which are negative, zero, or +/-1 appropriately: def make_equation(nums): coefficients = nums[:3] variables = 'xyz' terms = [] for c,v in zip(coefficients,variables): if c == 0: continue elif c == 1: coef = '' elif c == -1: coef = '-' else: coef = str(c) terms.append(coef + v) s = ' + '.join(terms) s = s.replace('+ -','- ') return s + ' = ' + str(nums[3]) Typical example: make_equation([2,-3,1,6]) With output: '2x - 3y + z = 6'
Is there a way to insert an arbitrary symbol before the Python output value?
I'm calculating the matrix value with Python, but I want to distinguish the value of equtaion, is there a way? x - y - 2z = 4 2x - y - z = 2 2x +y +4z = 16 I want to make the expression above like this when I print out the matrix from the function I created 1 -1 -2 | 4 2 -1 -1 | 2 2 1 4 | 16 Same as the rref result of this 1 0 0 | 24 0 1 0 | 72 0 0 1 | -26 def showMatrix(): print("\n") for i in sd: for j in i: print(j, end="\t") print("\n") def getone(pp): for i in range(len(sd[0])): if sd[pp][pp] != 1: q00 = sd[pp][pp] for j in range(len(sd[0])): sd[pp][j] = sd[pp][j] / q00 def getzero(r, c): for i in range(len(sd[0])): if sd[r][c] != 0: q04 = sd[r][c] for j in range(len(sd[0])): sd[r][j] = sd[r][j] - ((q04) * sd[c][j]) sd = [ [1, 1, 2, 9], [2, 4, -3, 1], [3, 6, -5, 0] ] showMatrix() for i in range(len(sd)): getone(i) for j in range(len(sd)): if i != j: getzero(j, i) showMatrix() print("FiNAL result") showMatrix()
[ "Here is a function which takes a list of 4 numbers and returns a string representing an equation in x,y,z. It handles coefficients which are negative, zero, or +/-1 appropriately:\ndef make_equation(nums):\n coefficients = nums[:3]\n variables = 'xyz'\n terms = []\n for c,v in zip(coefficients,variables):\n if c == 0:\n continue\n elif c == 1:\n coef = ''\n elif c == -1:\n coef = '-'\n else:\n coef = str(c)\n terms.append(coef + v)\n s = ' + '.join(terms)\n s = s.replace('+ -','- ')\n return s + ' = ' + str(nums[3])\n\nTypical example:\nmake_equation([2,-3,1,6])\n\nWith output:\n'2x - 3y + z = 6'\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074591197_python.txt
Q: Trying to understand signature in numpy.vectorize I am trying to understand the signature functionality in numpy.vectorize. I have some examples but did not help much in the understanding. >>import scipy.stats >>pearsonr = np.vectorize(scipy.stats.pearsonr, signature='(n),(n)->(),()') >>pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]]) (array([ 1., -1.]), array([ 0., 0.])) >>convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)') >>convolve(np.eye(4), [1, 2, 1]) array([[1., 2., 1., 0., 0., 0.], [0., 1., 2., 1., 0., 0.], [0., 0., 1., 2., 1., 0.], [0., 0., 0., 1., 2., 1.]]) >>>import numpy as np >>>qr = np.vectorize(np.linalg.qr, signature='(m,n)->(m,k),(k,n)') >>>qr(np.random.normal(size=(1, 3, 2))) (array([[-0.31622777, -0.9486833 ], [-0.9486833 , 0.31622777]]), array([[-3.16227766, -4.42718872, -5.69209979], [ 0. , -0.63245553, -1.26491106]])) >>>import scipy >>>logm = np.vectorize(scipy.linalg.logm, signature='(m,m)->(m,m)') >>>logm(np.random.normal(size=(1, 3, 2))) array([[[ 1.08226288, -2.29544602], [ 2.12599894, -1.26335203]]]) Can you please someone explain the functionality-syntax of the signatures signature='(n),(n)->(),()' signature='(n),(m)->(k)' signature='(m,n)->(m,k),(k,n)' signature='(m,m)->(m,m)' used in the aforementioned examples? If we didn't use the signatures, how the examples would have been implemented in a more easy-naive way? Any help is highly appreciated. The aforementioned examples can be found here and here. A: I think the explanation would be clearer if we knew the 'signature' of the individual functions - what they expect, and what they produce. But I can make some deductions from the code you show. >>pearsonr = np.vectorize(scipy.stats.pearsonr, signature='(n),(n)->(),()') >>pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]]) (array([ 1., -1.]), array([ 0., 0.])) This is called with a (4,) and (2,4) arrays (well, lists that become such arrays). They broadcast together to (2,4). The stats function is then called twice, once for each row of the pair, getting two (4,) arrays, and returning 2 scalar values (maybe the mean and std?) >>convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)') >>convolve(np.eye(4), [1, 2, 1]) array([[1., 2., 1., 0., 0., 0.], [0., 1., 2., 1., 0., 0.], [0., 0., 1., 2., 1., 0.], [0., 0., 0., 1., 2., 1.]]) This called with (4,4) and (3,) arrays. I think convolve gets called 4 times, once for each row of the eye, and getting the same [1,2,1] each time. The result is a 4 row array (with 6 columns - determined by convolve itself, not vectorize. >>>import numpy as np >>>qr = np.vectorize(np.linalg.qr, signature='(m,n)->(m,k),(k,n)') >>>qr(np.random.normal(size=(1, 3, 2))) (array([[-0.31622777, -0.9486833 ], [-0.9486833 , 0.31622777]]), array([[-3.16227766, -4.42718872, -5.69209979], [ 0. , -0.63245553, -1.26491106]])) Signature: np.linalg.qr(a, mode='reduced') a : array_like, shape (M, N) 'reduced' : returns q, r with dimensions (M, K), (K, N) (default) vectorize signature just repeats the information in the docs. a is (1,3,2) shape array; so qr is called once (1st dimension), with a (3,2) array. The result is 2 arrays, (2,k) and (k,3) shapes. When I run it I get an added size 1 dimension (1,2,3) and (1,2,2). Different numbers because of random: In [120]: qr = np.vectorize(np.linalg.qr, signature='(m,n)->(m,k),(k,n)') ...: qr(np.random.normal(size=(1, 3,2))) Out[120]: (array([[[-0.61362528, 0.09161174], [ 0.63682861, -0.52978942], [-0.46681188, -0.84316692]]]), array([[[-0.65301725, -1.00494992], [ 0. , 0.8068886 ]]])) >>>import scipy >>> logm = np.vectorize(scipy.linalg.logm, signature='(m,m)->(m,m)') >>>logm(np.random.normal(size=(1, 3, 2))) array([[[ 1.08226288, -2.29544602], [ 2.12599894, -1.26335203]]]) scipy.linalg.logm expects square array, and returns the same. Calling logm with a (1,3,2) produces an error, because (3,2) is not a square array: ValueError: inconsistent size for core dimension 'm': 2 vs 3 Calling scipy.linalg.logm directly produces the same error, worded differently: linalg.logm(np.random.normal(size=(3, 2))) ValueError: expected square array_like input When I say the function is called twice, or something like that, I'm ignoring the test call that's used to determine the return dtype.
Trying to understand signature in numpy.vectorize
I am trying to understand the signature functionality in numpy.vectorize. I have some examples but did not help much in the understanding. >>import scipy.stats >>pearsonr = np.vectorize(scipy.stats.pearsonr, signature='(n),(n)->(),()') >>pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]]) (array([ 1., -1.]), array([ 0., 0.])) >>convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)') >>convolve(np.eye(4), [1, 2, 1]) array([[1., 2., 1., 0., 0., 0.], [0., 1., 2., 1., 0., 0.], [0., 0., 1., 2., 1., 0.], [0., 0., 0., 1., 2., 1.]]) >>>import numpy as np >>>qr = np.vectorize(np.linalg.qr, signature='(m,n)->(m,k),(k,n)') >>>qr(np.random.normal(size=(1, 3, 2))) (array([[-0.31622777, -0.9486833 ], [-0.9486833 , 0.31622777]]), array([[-3.16227766, -4.42718872, -5.69209979], [ 0. , -0.63245553, -1.26491106]])) >>>import scipy >>>logm = np.vectorize(scipy.linalg.logm, signature='(m,m)->(m,m)') >>>logm(np.random.normal(size=(1, 3, 2))) array([[[ 1.08226288, -2.29544602], [ 2.12599894, -1.26335203]]]) Can you please someone explain the functionality-syntax of the signatures signature='(n),(n)->(),()' signature='(n),(m)->(k)' signature='(m,n)->(m,k),(k,n)' signature='(m,m)->(m,m)' used in the aforementioned examples? If we didn't use the signatures, how the examples would have been implemented in a more easy-naive way? Any help is highly appreciated. The aforementioned examples can be found here and here.
[ "I think the explanation would be clearer if we knew the 'signature' of the individual functions - what they expect, and what they produce. But I can make some deductions from the code you show.\n>>pearsonr = np.vectorize(scipy.stats.pearsonr, signature='(n),(n)->(),()')\n>>pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]])\n(array([ 1., -1.]), array([ 0., 0.]))\n\nThis is called with a (4,) and (2,4) arrays (well, lists that become such arrays). They broadcast together to (2,4). The stats function is then called twice, once for each row of the pair, getting two (4,) arrays, and returning 2 scalar values (maybe the mean and std?)\n>>convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)')\n>>convolve(np.eye(4), [1, 2, 1])\narray([[1., 2., 1., 0., 0., 0.],\n [0., 1., 2., 1., 0., 0.],\n [0., 0., 1., 2., 1., 0.],\n [0., 0., 0., 1., 2., 1.]])\n\nThis called with (4,4) and (3,) arrays. I think convolve gets called 4 times, once for each row of the eye, and getting the same [1,2,1] each time. The result is a 4 row array (with 6 columns - determined by convolve itself, not vectorize.\n>>>import numpy as np\n>>>qr = np.vectorize(np.linalg.qr, signature='(m,n)->(m,k),(k,n)')\n>>>qr(np.random.normal(size=(1, 3, 2)))\n(array([[-0.31622777, -0.9486833 ],\n [-0.9486833 , 0.31622777]]), \narray([[-3.16227766, -4.42718872, -5.69209979],\n [ 0. , -0.63245553, -1.26491106]]))\n\n\nSignature: np.linalg.qr(a, mode='reduced')\na : array_like, shape (M, N)\n\n'reduced' : returns q, r with dimensions (M, K), (K, N) (default)\n\n\nvectorize signature just repeats the information in the docs.\na is (1,3,2) shape array; so qr is called once (1st dimension), with a (3,2) array. The result is 2 arrays, (2,k) and (k,3) shapes. When I run it I get an added size 1 dimension (1,2,3) and (1,2,2). Different numbers because of random:\nIn [120]: qr = np.vectorize(np.linalg.qr, signature='(m,n)->(m,k),(k,n)')\n ...: qr(np.random.normal(size=(1, 3,2)))\nOut[120]: \n(array([[[-0.61362528, 0.09161174],\n [ 0.63682861, -0.52978942],\n [-0.46681188, -0.84316692]]]),\n array([[[-0.65301725, -1.00494992],\n [ 0. , 0.8068886 ]]]))\n \n>>>import scipy\n>>> logm = np.vectorize(scipy.linalg.logm, signature='(m,m)->(m,m)')\n>>>logm(np.random.normal(size=(1, 3, 2)))\narray([[[ 1.08226288, -2.29544602],\n [ 2.12599894, -1.26335203]]])\n\nscipy.linalg.logm expects square array, and returns the same.\nCalling logm with a (1,3,2) produces an error, because (3,2) is not a square array:\nValueError: inconsistent size for core dimension 'm': 2 vs 3\n\nCalling scipy.linalg.logm directly produces the same error, worded differently:\nlinalg.logm(np.random.normal(size=(3, 2)))\nValueError: expected square array_like input\n\nWhen I say the function is called twice, or something like that, I'm ignoring the test call that's used to determine the return dtype.\n" ]
[ 2 ]
[]
[]
[ "numpy", "python", "vectorization" ]
stackoverflow_0074589308_numpy_python_vectorization.txt