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: Text is cut-off in Plotly horizontal bar chart I created horizontal bar chart in Plotly-dash, but bar text size doesn't fit to the figure size, so part of the text is cut (please see red-framed area on the screenshot attached). I tried the following: Changing left and right margin in figure layout. The whole figu...
Text is cut-off in Plotly horizontal bar chart
I created horizontal bar chart in Plotly-dash, but bar text size doesn't fit to the figure size, so part of the text is cut (please see red-framed area on the screenshot attached). I tried the following: Changing left and right margin in figure layout. The whole figure is moving, but the text remains cut. Setting 'off...
[ "Unlike minuses on SO, I gained real help from Plotly community. Hope it will help not only me.\nTo avoid behaviour described xaxis range could be set manually:\nfig = fig.update_layout(\n xaxis_range=[-1.0e5, 1.3e5]\n)\n\nNow my dashboard looks much better. Finally I used the following expression to fit xaxis r...
[ 3, 0 ]
[]
[]
[ "bar_chart", "plotly", "plotly_dash", "python" ]
stackoverflow_0064856728_bar_chart_plotly_plotly_dash_python.txt
Q: While Loop Not Working As Intended in Python I need my program to show a list and then ask the user if they want to add anything; then it adds that input to the list. It then asks the user again in separate input if they want to add anything else and if they hit enter it prints the list including all the new input...
While Loop Not Working As Intended in Python
I need my program to show a list and then ask the user if they want to add anything; then it adds that input to the list. It then asks the user again in separate input if they want to add anything else and if they hit enter it prints the list including all the new inputs and ends the big while loop. list1 = [1,2,3,4,5,...
[ "Make counter = counter + 1 and try rerunning the code.\nAlso, please change x == False to x = False\nThere would be other errors related to to_do_list not being defined. I believe you need to change it to liist.\nThe below code should work fine for your requirements:\nlist1 = [1,2,3,4,5,6]\n\ndef list_adder(liist)...
[ 0, 0, 0, 0 ]
[]
[]
[ "function", "if_statement", "python", "while_loop" ]
stackoverflow_0074418406_function_if_statement_python_while_loop.txt
Q: Python pandas create new dataframe out of column entries In the pandas package of python, how would one do the following the most easily? df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'], 'Max Speed': [380., 370., 24., 26.]}) Resulting in: ...
Python pandas create new dataframe out of column entries
In the pandas package of python, how would one do the following the most easily? df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'], 'Max Speed': [380., 370., 24., 26.]}) Resulting in: Animal Max Speed 0 Falcon 380.0 1 Falcon 370.0 2 Parr...
[ "here is one way to do it\n(df.assign(seq=df.groupby('Animal').cumcount()) # add temp sequence to the dup rows\n .pivot(index='seq', columns='Animal') # pivot using seq\n .droplevel(level=0, axis=1) # drop level 0 in column, resulting from Pivot\n .reset_index() ...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074417495_dataframe_pandas_python.txt
Q: How to check timestamps and day period, then drop mismatch I have data with timestamps. Users respond to questions and they also select day period (morning or evening). I want to drop rows where recorded timestamp and day period mismatch. So check, if timestamp is between 6am-12pm and discard if "daytime" is "even...
How to check timestamps and day period, then drop mismatch
I have data with timestamps. Users respond to questions and they also select day period (morning or evening). I want to drop rows where recorded timestamp and day period mismatch. So check, if timestamp is between 6am-12pm and discard if "daytime" is "evening", etc. df timestamps daytime 2020-04-10 11:40 Mo...
[ "\n6< df['timestamp'].dt.hour < 12\n\nsuch a triple operation isn't possible on Python yet...\nI will create a function like\ndef get_part_of_day(h):\n return (\n \"morning\"\n if 6 <= h <= 12\n else \"afternoon\"\n if 18 <= h <= 23\n else \"night\"\n )\n\nand\ndf['datetime'...
[ 2, 2 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074418107_dataframe_datetime_pandas_python.txt
Q: Python match statement with enum I'm trying to match "header" to one of the header types in my ENUM class. I've tried header to match Header.PROFILE_NAME, Header.PROFILE_NAME.name, Header.PROFILE_NAME.name. However none of these worked so far. Can't find a lot of information about it either. Hope someone can help ...
Python match statement with enum
I'm trying to match "header" to one of the header types in my ENUM class. I've tried header to match Header.PROFILE_NAME, Header.PROFILE_NAME.name, Header.PROFILE_NAME.name. However none of these worked so far. Can't find a lot of information about it either. Hope someone can help me out on this one. Cheers in advance....
[ "The match statement will work directly with enums, so convert your header into an enum first:\nfor index, header in enumerate(profile):\n header = Header[header.upper()] # or whatever is needed to match the name\n match header:\n ...\n\n" ]
[ 1 ]
[]
[]
[ "case", "enumeration", "enums", "python", "switch_statement" ]
stackoverflow_0074417696_case_enumeration_enums_python_switch_statement.txt
Q: Python: List index Out of Range Error when list indexing I have a list of lists property_lists which is structured as follows: property_lists = [['Semi-Detached', '|', '', '2', '|', '', '2'], ['Detached', '|', '', '5', '|', '', '3'], ['Detached', '|', '', '5', '|', '', '5']] and so on. I am attempting list indexi...
Python: List index Out of Range Error when list indexing
I have a list of lists property_lists which is structured as follows: property_lists = [['Semi-Detached', '|', '', '2', '|', '', '2'], ['Detached', '|', '', '5', '|', '', '3'], ['Detached', '|', '', '5', '|', '', '5']] and so on. I am attempting list indexing in order to put all the elements into separate lists of the...
[ "First can you please give example, of what you want in the output?\nIf you want the output like the below:\n\npropertyList1 = ['Semi-Detached', '|', '', '2', '|', '', '2']\npropertyList2 = ['Detached', '|', '', '5', '|', '', '3']\npropertyList3 = ['Detached', '|', '', '5', '|', '', '5']\n\nthen Here's the solution...
[ 0, 0 ]
[]
[]
[ "indexing", "list", "python" ]
stackoverflow_0074417212_indexing_list_python.txt
Q: Django: managing permissions, groups and users during data migrations Problem During a data migration, I'm trying to create a django.contrib.auth.models.Group and some Users and then attaching said group to one of the users. Problem I'm finding (other than the permissions still not being created, but I've already ...
Django: managing permissions, groups and users during data migrations
Problem During a data migration, I'm trying to create a django.contrib.auth.models.Group and some Users and then attaching said group to one of the users. Problem I'm finding (other than the permissions still not being created, but I've already found a solution to that), is that for some reason the many-to-many manager...
[ "Turns out that the problem comes up when you use the django.contrib.auth.models.Group model directly. If instead you use apps.get_model(\"auth.Group\"), everything works fine.\n" ]
[ 0 ]
[]
[]
[ "django", "django_authentication", "django_migrations", "django_orm", "python" ]
stackoverflow_0074418576_django_django_authentication_django_migrations_django_orm_python.txt
Q: Scikit-learn, get accuracy scores for each class Is there a built-in way for getting accuracy scores for each class separatetly? I know in sklearn we can get overall accuracy by using metric.accuracy_score. Is there a way to get the breakdown of accuracy scores for individual classes? Something similar to metrics....
Scikit-learn, get accuracy scores for each class
Is there a built-in way for getting accuracy scores for each class separatetly? I know in sklearn we can get overall accuracy by using metric.accuracy_score. Is there a way to get the breakdown of accuracy scores for individual classes? Something similar to metrics.classification_report. from sklearn.metrics import cla...
[ "from sklearn.metrics import confusion_matrix\ny_true = [2, 0, 2, 2, 0, 1]\ny_pred = [0, 0, 2, 2, 0, 2]\nmatrix = confusion_matrix(y_true, y_pred)\nmatrix.diagonal()/matrix.sum(axis=1)\n\n", "You can use sklearn's confusion matrix to get the accuracy\nfrom sklearn.metrics import confusion_matrix\nimport numpy as ...
[ 29, 15, 6, 4, 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "machine_learning", "python", "scikit_learn" ]
stackoverflow_0039770376_machine_learning_python_scikit_learn.txt
Q: Google Colab: How to use LateX fonts in matplotlib? Following the suggestions here, I thought I could include the following code snipped to render latex fonts in matplotlib plt.rcParams.update({ "text.usetex": True, "font.family": "Computer Modern Roman" }) To make sure latex was installed, I also ran !pi...
Google Colab: How to use LateX fonts in matplotlib?
Following the suggestions here, I thought I could include the following code snipped to render latex fonts in matplotlib plt.rcParams.update({ "text.usetex": True, "font.family": "Computer Modern Roman" }) To make sure latex was installed, I also ran !pip install latex. I am running Google Colab on Windows 11....
[ "Run this code in Google colab, it will work\nplt.rcParams['mathtext.fontset'] = 'cm'\nplt.rcParams['font.family'] = 'STIXGeneral'\n\n\n" ]
[ 0 ]
[]
[]
[ "google_colaboratory", "matplotlib", "python" ]
stackoverflow_0074368506_google_colaboratory_matplotlib_python.txt
Q: Magical method __len__() How to call the __len__() function using an object of the class ? class foo(object): def __init__(self,data) self.data = data def __len__(self): return len(self.data) x = foo([1,2,3,4]) A: You can do it this way: >>>x = foo([1,2,3,4]) >>>len(x) 4 A: The id...
Magical method __len__()
How to call the __len__() function using an object of the class ? class foo(object): def __init__(self,data) self.data = data def __len__(self): return len(self.data) x = foo([1,2,3,4])
[ "You can do it this way:\n>>>x = foo([1,2,3,4])\n>>>len(x)\n4\n\n", "The idea behind a magic method is to be able to call it as x.__len__() or len(x). They don't return the output until explicitly called or have or stored in class variables.\nMethod 1: Call function explicitly\nYou can simply call the function ex...
[ 2, 2, 0 ]
[ "Same way you call any other function. By its name.\nprint(x.__len__())\n\nwhich will give 4 for your code\n", "If we go with your class called foo() we can call the method __len__ like this.\na = foo([1,2,3,4])\nb = a.__len__()\n\nOr if you want to save the length within the class:\nclass foo(object):\n def ...
[ -1, -1 ]
[ "arraylist", "list", "python", "python_2.7", "python_3.x" ]
stackoverflow_0066748868_arraylist_list_python_python_2.7_python_3.x.txt
Q: how to restructure data in python I'm new to Python. I need to restructure the inputed string data into entered/separated by carriage return characters like this one: Input: D A P U R N U W A Y Output: D N A U P W U A R Y I tried to use the replace() method but no...
how to restructure data in python
I'm new to Python. I need to restructure the inputed string data into entered/separated by carriage return characters like this one: Input: D A P U R N U W A Y Output: D N A U P W U A R Y I tried to use the replace() method but nothing solved. Below is my current code:...
[ "I am pretty sure there is a better way out there. But here is something that can do the job.\nNote: Only works for this particular structure and equal number of characters.\nFirst, I will assume that your input looks something like this:\ninput_string = \"D A P U R\\nN U W A Y\"\n\nOutput:\nD A P U R\nN U W A Y\n\...
[ 1 ]
[]
[]
[ "newline", "python", "python_3.x" ]
stackoverflow_0074418460_newline_python_python_3.x.txt
Q: using android pre build tensorflow tflight model from android example in python code I recently downloaded an android demo app for text classification made by TensorFlow and this is the GitHub link android GitHub demo and within that app it has 2 mode to predict if the text is positive or negative using (AverageWo...
using android pre build tensorflow tflight model from android example in python code
I recently downloaded an android demo app for text classification made by TensorFlow and this is the GitHub link android GitHub demo and within that app it has 2 mode to predict if the text is positive or negative using (AverageWordVec / MobileBERT ) but MobileBERT accuracy is way better Now i tried to search for alter...
[ "Method 1: You can use tflite-support by installing pip install tflite-support.\nfrom tflite_support.task import text\nclassifier = text.BertNLClassifier.create_from_file('mobilebert.tflite')\nclassifier.classify('go to hell')\n\n#Output:\n[Classifications(categories=[Category(index=0, score=0.9992809891700745, dis...
[ 1 ]
[]
[]
[ "android", "python", "tensorflow", "text_classification" ]
stackoverflow_0074361653_android_python_tensorflow_text_classification.txt
Q: Python - Can't copy elements in a stack from another class I have this python program that is a simple stack implementation. It simply pushes, pops, and displays elements. The program is doing well whenever it pushes, pops, and displays the user inputted elements. But my problem is, I can't seem to print a copy of...
Python - Can't copy elements in a stack from another class
I have this python program that is a simple stack implementation. It simply pushes, pops, and displays elements. The program is doing well whenever it pushes, pops, and displays the user inputted elements. But my problem is, I can't seem to print a copy of the elements. Whenever I'm trying to make a copy, it displays [...
[ "To me this seems like it might be because you aren't actually copying a pre-existing stack.\nI am going to assume that you were trying to run the copyOfStack method of a CopyStack class instance.\nThis method creates a new Stack object and copies from that. I imagine you want to copy from a pre-existing Stack obje...
[ 0 ]
[]
[]
[ "class", "oop", "python", "stack" ]
stackoverflow_0074418613_class_oop_python_stack.txt
Q: Unable to append values to specific columns in google sheets from a csv import pandas as pd import pygsheets import gspread from gspread_dataframe import set_with_dataframe from google.oauth2.service_account import Credentials def csv_to_sheets(): tokenPath ='path for service account file.json' scopes = ['h...
Unable to append values to specific columns in google sheets from a csv
import pandas as pd import pygsheets import gspread from gspread_dataframe import set_with_dataframe from google.oauth2.service_account import Credentials def csv_to_sheets(): tokenPath ='path for service account file.json' scopes = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googl...
[ "Modification points:\n\nIn the case of for ele in my_csv_values:, each row is uploaded and 3 API calls are used every loop.\nAnd, in your script, ele[0] is no array. And, ele[1:] is a 1-dimensional array. In this case, an error occurs. I thought that this might be the reason for your current error message.\n\nWhen...
[ 2 ]
[]
[]
[ "csv", "google_sheets", "google_sheets_api", "python" ]
stackoverflow_0074415088_csv_google_sheets_google_sheets_api_python.txt
Q: Tensorflow tf.math.tanh properly scale network output without requiring large batches I am trying to implement a network presented in this paper. This excerpt has a describing image and is accompanied by an explanation. The input is a feature of 353 floats and the label is a float (-1500, 1500) scaled to -1, 1....
Tensorflow tf.math.tanh properly scale network output without requiring large batches
I am trying to implement a network presented in this paper. This excerpt has a describing image and is accompanied by an explanation. The input is a feature of 353 floats and the label is a float (-1500, 1500) scaled to -1, 1. The output should also be scaled between -1, 1. I used tf.math.tanh() to do this. However...
[ "When using layers, each layer is matrics muliply of the of previous layer input with the weights.\nSo you can get big value, even you have \"good\" weights.\nWhen tanh get inputs of even >10, because it is base on exponent it easily returns 1 on every values that is big (mostly range of -2 to 2).\nIt can get only ...
[ 0 ]
[]
[]
[ "batch_normalization", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0061893750_batch_normalization_python_tensorflow_tensorflow2.0.txt
Q: ValueError: Expected object or value when reading json as pandas dataframe Sample data: { "_id": "OzE5vaa3p7", "categories": [ { "__type": "Pointer", "className": "Category", "objectId": "nebCwWd2Fr" } ], "isActive": true, "imageUrl": "https://firebasestorage.g...
ValueError: Expected object or value when reading json as pandas dataframe
Sample data: { "_id": "OzE5vaa3p7", "categories": [ { "__type": "Pointer", "className": "Category", "objectId": "nebCwWd2Fr" } ], "isActive": true, "imageUrl": "https://firebasestorage.googleapis.com/v0/b/shopgro-1376.appspot.com/o/Barcode%20Data%20Upload%28II%29%2F...
[ "Your JSON is malformed.\nValueError: Expected object or value can occur if you mistyped the file name. Does Data.json exist? I noticed for your other attempts you used gdb.json.\nOnce you confirm the file name is correct, you have to fix your JSON. What you have now is two disconnected records separated by a space...
[ 16, 14, 6, 5, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0044287011_json_pandas_python.txt
Q: How to write a function to zip two nested lists? My ultimate goal is a function combining two nested lists, like this: def tuples_maker(l1, l2): return sample_data I know that I can use zip, but I don't know how to utilize "for" loop. I got stuck at first step then I cannot continue.... for example, l1 ...
How to write a function to zip two nested lists?
My ultimate goal is a function combining two nested lists, like this: def tuples_maker(l1, l2): return sample_data I know that I can use zip, but I don't know how to utilize "for" loop. I got stuck at first step then I cannot continue.... for example, l1 = [[1,2,3,4], [10,11,12]] l2 = [[-1,-2,-3,-4], [-10,-1...
[ "Iterating the zip object yields a tuple of values, so you need to explicitly pass it to a list constructor if you want to create list out of those values\ndef combine_lists(l1,l2):\n return list([list(y) for y in zip(*x)] for x in zip(l1,l2))\n \n\nOUTPUT\nprint(combine_lists(l1,l2))\n#output\n[[[1, -1], [2, ...
[ 2, 2 ]
[]
[]
[ "for_loop", "function", "python" ]
stackoverflow_0074418650_for_loop_function_python.txt
Q: How to limit login to 3 attempts? Code : counter = 1 pg3_txtbox_username = Entry(page3, borderwidth=0, width=16, font=('Arial',30)) pg3_txtbox_username.place(x=116, y=256, height=92) pg3_txtbox_pass = Entry(page3, borderwidth=0, width=16, font=('Arial', 30), show='*') pg3_txtbox_pass.place(x=116, y=422, height=90...
How to limit login to 3 attempts?
Code : counter = 1 pg3_txtbox_username = Entry(page3, borderwidth=0, width=16, font=('Arial',30)) pg3_txtbox_username.place(x=116, y=256, height=92) pg3_txtbox_pass = Entry(page3, borderwidth=0, width=16, font=('Arial', 30), show='*') pg3_txtbox_pass.place(x=116, y=422, height=90) def verify(): conn = sql...
[ "You have\n global counter\n counter = 1\n\nwhich is setting counter to 1 every time verify() is called. verify() is called every time you check the password, I assume. Therefore, counter will be set to 1 every time you verify a password -- and since you add one when you find that the password is inco...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074418769_python.txt
Q: ImportError: cannot import name 'TimedJSONWebSignatureSerializer' from 'itsdangerous' I'm running a flask app using itsdangerous python package in AWS EC2 instance. Traceback (most recent call last): File "run.py", line 4, in <module> app = create_app() File "/home/ubuntu/RHS_US/application/portal/__init__...
ImportError: cannot import name 'TimedJSONWebSignatureSerializer' from 'itsdangerous'
I'm running a flask app using itsdangerous python package in AWS EC2 instance. Traceback (most recent call last): File "run.py", line 4, in <module> app = create_app() File "/home/ubuntu/RHS_US/application/portal/__init__.py", line 29, in create_app from portal.users.routes import users File "/home/ubuntu...
[ "In the latest version of itsdangerous, TimedJSONWebSignatureSerializer is no longer available. Try this instead. It worked for me. from itsdangerous import URLSafeTimedSerializer as Serializer\n", "Itsdangerous is a very common and popular package used for serialization in other packages and apps.\nTo fix this:\...
[ 1, 1, 0 ]
[]
[]
[ "python", "ubuntu" ]
stackoverflow_0074039971_python_ubuntu.txt
Q: How to store dataframe mean as a column wise If we have a dataframe like the below one A B C 0 5 3 8 1 5 3 9 2 8 4 9 We can calculate the mean using df.mean() and the output looks like A 6.000000 B 3.333333 C 8.666667 dtype: float64 Now, I want to save the mean in a column-wise...
How to store dataframe mean as a column wise
If we have a dataframe like the below one A B C 0 5 3 8 1 5 3 9 2 8 4 9 We can calculate the mean using df.mean() and the output looks like A 6.000000 B 3.333333 C 8.666667 dtype: float64 Now, I want to save the mean in a column-wise format like the below one. A B C 0 ...
[ "Just call to_frame then transpose the result:\ndf.mean().to_frame().T\n\n#output\n A B C\n0 6.0 3.333333 8.666667\n\n", "Use the DataFrame constructor:\nout = pd.DataFrame([df.mean()])\n\nOutput:\n A B C\n0 6.0 3.333333 8.666667\n\n" ]
[ 1, 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074418713_pandas_python_python_3.x.txt
Q: groupby and unstack from dataframe i have a data frame from tips.csv i want grouping data by day and sex like this : but my result like this : and this my code df.groupby(['day','sex'])['tip'].sum().unstack('sex').reset_index() Any ideas and suggestions would be very welcome. A: don use reset_index df.groupby...
groupby and unstack from dataframe
i have a data frame from tips.csv i want grouping data by day and sex like this : but my result like this : and this my code df.groupby(['day','sex'])['tip'].sum().unstack('sex').reset_index() Any ideas and suggestions would be very welcome.
[ "don use reset_index\ndf.groupby(['day','sex'])['tip'].sum().unstack('sex')\n\nIf this does not solve problem, make a simple example and upload it as text instead of image.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074418764_dataframe_pandas_python.txt
Q: What is going on? (Attemp at scraping multiple pages) url = "https://www.gumtree.com/search?search_category=all&q=ferrari" while url: response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") name = soup.find_all("div", class_="h3-responsive") price = soup.find_all("stron...
What is going on? (Attemp at scraping multiple pages)
url = "https://www.gumtree.com/search?search_category=all&q=ferrari" while url: response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") name = soup.find_all("div", class_="h3-responsive") price = soup.find_all("strong", "h3-responsive") next_page = soup.select_one("li.p...
[ "Here is a way to get those listings (didn't go for an infinite loop, you're welcome to increase page count and look up for the existence of an element in page (like next page url, etc) if you want). There are 10 pages:\nimport requests\nfrom bs4 import BeautifulSoup as bs\nfrom tqdm import tqdm\nimport pandas as p...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping", "web_scraping" ]
stackoverflow_0074411153_beautifulsoup_python_screen_scraping_web_scraping.txt
Q: OperationalError in Django while updating model I am facing OperationalError while updating the model in an existing Django project. These are my installed apps in settings INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", ...
OperationalError in Django while updating model
I am facing OperationalError while updating the model in an existing Django project. These are my installed apps in settings INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.stat...
[ "Simply you can migrate manually using below command:\npython3 manage.py makemigrations appname\n\npython3 manage.py sqlmigrate appname 0001\n\npython3 manage.py migrate\n\nAnd see if it solves\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "operationalerror", "python" ]
stackoverflow_0074413537_django_django_models_operationalerror_python.txt
Q: Connect python app container, postgres container, and persistent database on external harddrive with docker compose Using docker-compose, I am running a postgres container (db). The data itself is persistently stored on my Windows machine. And this works. I am unable to get another container running a python appli...
Connect python app container, postgres container, and persistent database on external harddrive with docker compose
Using docker-compose, I am running a postgres container (db). The data itself is persistently stored on my Windows machine. And this works. I am unable to get another container running a python application to access the database. My docker-compose file is as follows, where I use ## to denote some options that I've trie...
[ "It will be better to define the volumes before using them like here.\nAlso if you want postgres' data to persist you need to place inside the volume the folder\n\n/var/lib/postgresql/data\n\nsomething like\nvolumes:\n - fancy-volume:\n ... fancy definition..\n\nservices:\n fancy-app:\n ...\n volumes:\n - fan...
[ 1, 1 ]
[]
[]
[ "docker", "docker_compose", "port", "postgresql", "python" ]
stackoverflow_0074418139_docker_docker_compose_port_postgresql_python.txt
Q: Want to separate the positive and negitive words in wordcloud using Jupitor notbook I am doing sentiment analysis i already genrate wordcloud as a whole but stuck in the separation of positive and negitive words in wordcloud using jupitor notebook A: The wordcloud is just another way of displaying the frequency ...
Want to separate the positive and negitive words in wordcloud using Jupitor notbook
I am doing sentiment analysis i already genrate wordcloud as a whole but stuck in the separation of positive and negitive words in wordcloud using jupitor notebook
[ "The wordcloud is just another way of displaying the frequency of your words. It has nothing to do with the sentiment of such words. You will have to perform sentiment analysis on the \"words, sentences or document as a whole\". The level of granularity depends on the purpose of the task at hand.\nThings you may wa...
[ 0 ]
[]
[]
[ "code_separation", "jupyter_notebook", "python", "sentiment_analysis", "word_cloud" ]
stackoverflow_0073423894_code_separation_jupyter_notebook_python_sentiment_analysis_word_cloud.txt
Q: What is under the hood of a venv virtual enviornment? Lately I have started to use venv virtual environments for my development. (before I was just using docker images and conda environments) However I notice that virtual environments are created for some code you have. My question is isn't that wasteful? I mean i...
What is under the hood of a venv virtual enviornment?
Lately I have started to use venv virtual environments for my development. (before I was just using docker images and conda environments) However I notice that virtual environments are created for some code you have. My question is isn't that wasteful? I mean if we have 20 repos of code, and they all need opencv, havin...
[ "There's a classic trade-off involved here. YES, the liberal use of virtualenvs requires more disk space...but these days, disk space is super cheap. The common consensus, which if you're an old timer like me then you would have come to on your own by now, is that the benefits of having a separate virtualenv for ...
[ 2, 2 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0074418761_python_virtualenv.txt
Q: How to make a dataframe from a list of strings? I have multiple files .csv, containing the results of training/validating process. One file per model. Each line in a file contains the following information: Epoch,loss_train,acc_train,loss_val,acc_val,time. Each filename contains information on model parameters. I ...
How to make a dataframe from a list of strings?
I have multiple files .csv, containing the results of training/validating process. One file per model. Each line in a file contains the following information: Epoch,loss_train,acc_train,loss_val,acc_val,time. Each filename contains information on model parameters. I need to construct a dataframe that contains the last ...
[ "With the list of strings you provided:\nresults = [\n '\"0_0_2_200_0.4.csv\",66,67,0.42319968342781067,0.8733666720438781,0.9848468899726868,0.7532656023222061,0.2503340244293213\\n',\n '\"0_0_2_200_0.5.csv\",74,75,0.41233333945274353,0.8760283916760768,0.9206098318099976,0.7656023222060958,0.253538846969604...
[ 1 ]
[]
[]
[ "dataframe", "export_to_csv", "list", "pandas", "python" ]
stackoverflow_0074363472_dataframe_export_to_csv_list_pandas_python.txt
Q: How to Grouping, Selecting Several Value to be a columns And Select Certain Word in Python I have A Data like this, or you can see my Notebook here : link or the raw file here : link Id Type Label Value Value2 1 A Introduction This Project will be created By Mr.X 1 A Capacity 100MB 1 A Speed 10Km/h 1 A Weight...
How to Grouping, Selecting Several Value to be a columns And Select Certain Word in Python
I have A Data like this, or you can see my Notebook here : link or the raw file here : link Id Type Label Value Value2 1 A Introduction This Project will be created By Mr.X 1 A Capacity 100MB 1 A Speed 10Km/h 1 A Weight 10kg 2 A Introduction This-Project-will-be-created-By-Mr.A 2 A Capacity 100MB...
[ "You should melt to first reshape the \"Value...\" columns, then pivot using the new \"value\" column:\n(df.melt(['Id', 'Type', 'Label'])\n .dropna(subset=['value'])\n .pivot(index=['Id', 'Type'], columns='Label', values='value')\n .rename_axis(columns=None)\n .dropna(axis=1) # remove incomplete columns\n ...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074418584_dataframe_pandas_python.txt
Q: how to convert a string received from one dataframe to another dataframe I have the following code in a parquet file, which I convert into a variable using collect: mapping_in_parquet = [('filial','filial','S','string'),('doc','numero_do_documento','S','string'),('serie','serie_do_documento','S','string')] mappin...
how to convert a string received from one dataframe to another dataframe
I have the following code in a parquet file, which I convert into a variable using collect: mapping_in_parquet = [('filial','filial','S','string'),('doc','numero_do_documento','S','string'),('serie','serie_do_documento','S','string')] mapping = (df.select('mapping').distinct().collect()[0][0]) The problem is when I t...
[ "There are 2 issues in your code:\n\nFirst is typo while creating dataframe: Use df = (spark.createDataFrame(mapping_in_parquet, schema)).\nSecond, in mapping = (df.select('mapping').distinct().collect()[0][0]), there is no column mapping. Use either of [fieldName, alias, typeField, column_active].\n\nFull example ...
[ 0 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074414583_pyspark_python.txt
Q: How to query database and display on charts.js in django Hi I am trying to display all marketplace as label and the quantity of infringements in those marketplace as data on a pie chart. Please help. marketplace1 - 5 marketplae2 -4 marketplace3 -7 dashboard.html <!doctype html> <html lang="en"> <head> ...
How to query database and display on charts.js in django
Hi I am trying to display all marketplace as label and the quantity of infringements in those marketplace as data on a pie chart. Please help. marketplace1 - 5 marketplae2 -4 marketplace3 -7 dashboard.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> ...
[ "Found the way to query\nviews.py\nfrom django.db.models import Count\n def dashboard(request):\n \n mar_count = Marketplace.objects.annotate(infringement_count=Count('infringement'))\n\n context= {'mar_count': mar_count}\n return render(request, 'base/dashboard.html', context)\n\ndashboa...
[ 0 ]
[]
[]
[ "chart.js", "django", "python" ]
stackoverflow_0074417389_chart.js_django_python.txt
Q: How to add a specific input to the front a specific list item in Python I wanted to my program display a list and ask the user what list item they completed. After they input that which will be an item in the list, it should insert an "X " in front of it. E.g if the list is [homework, chores] the list should then ...
How to add a specific input to the front a specific list item in Python
I wanted to my program display a list and ask the user what list item they completed. After they input that which will be an item in the list, it should insert an "X " in front of it. E.g if the list is [homework, chores] the list should then become [X homework, chores] if the user inputs "homework". run = True ...
[ "list_item = [\"homework\", \"chores\"]\nwhile True:\n input000 = input(\"enter something\")\n for i in range(len(list_item)):\n if input000 == list_item[i]:\n list_item[i] = f\"X {list_item[i]}\"\n\n", "A more Pythonic approach is to use the list's index() method in conjunction with an ex...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074418804_python.txt
Q: Why is pygame.blit() reseting back to 0 after 65500 pixels? Im creating a program that will show every image from a folder, i created a function for scrolling because in case there were a lot of images it wouldn't fit the screen, the problem is that after reaching 65536 on the y value, it will start bliting at 0 a...
Why is pygame.blit() reseting back to 0 after 65500 pixels?
Im creating a program that will show every image from a folder, i created a function for scrolling because in case there were a lot of images it wouldn't fit the screen, the problem is that after reaching 65536 on the y value, it will start bliting at 0 again, like placing the new names on top of the old ones. This is ...
[ "\nit wouldn't fit the screen, the problem is that after reaching 65536\n\n65535 is 0xffff, which is the maximum number that can be represented by 2 bytes or a variable of type \"uint16\". Likely this is the internal data type pygame uses to represent a pixel on the screen or the size of a pygame.Surface. This is f...
[ 2 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0074418917_pygame_python_python_3.x.txt
Q: How to resolve conflicting dependencies in tox? I have been using tox to run the lintin packes over my code base. However I have ran into the issue of not having the dependecies up to date with my gitlab pipeline, because I was not updating my dependencies not to affect the deployed version. For this reason I want...
How to resolve conflicting dependencies in tox?
I have been using tox to run the lintin packes over my code base. However I have ran into the issue of not having the dependecies up to date with my gitlab pipeline, because I was not updating my dependencies not to affect the deployed version. For this reason I wanted to switch to using requirements-dev.txt in my tox ...
[ "The most elegant, and widely used solution is not to run each linter in a separate tox environment, but to have one linter environment, which runs pre-commit.\npre-commit is a linter runner and both takes care of running the linters and dependency management of the linters.\nYour tox.ini would look like that:\n[te...
[ 1 ]
[]
[]
[ "gitlab", "python", "requirements.txt", "tox" ]
stackoverflow_0074417283_gitlab_python_requirements.txt_tox.txt
Q: How to make BeautifulSoup go to the specific webpage I want instead of a random one on the site? I am trying to learn web scraping using BeautifulSoup by scraping UFC fight data off of the website Tapology. I have entered in the URL of a specific fight's webpage but every time I run the code it seems to jump to a ...
How to make BeautifulSoup go to the specific webpage I want instead of a random one on the site?
I am trying to learn web scraping using BeautifulSoup by scraping UFC fight data off of the website Tapology. I have entered in the URL of a specific fight's webpage but every time I run the code it seems to jump to a new random fight on the page instead of this fight. Here is the code: from bs4 import BeautifulSoup im...
[ "I got the same results (\"..every time I run the code it seems to jump to a new random fight...\") when I tried your code. Like some of the comments suggested, it's probably in an effort to evade bots. Maybe the right set of headers could resolve it, but I'm not very good with making requests imitate un-automated ...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074418118_beautifulsoup_python_web_scraping.txt
Q: Python pygame's keyboard move command does not operate I'm currently trying to build a game through vscode using pygame lib. My code to move character around with keyboard arrow keys won't apply to my module. My module won't close even though I click exit button or esc. Any thoughts why its not working? import p...
Python pygame's keyboard move command does not operate
I'm currently trying to build a game through vscode using pygame lib. My code to move character around with keyboard arrow keys won't apply to my module. My module won't close even though I click exit button or esc. Any thoughts why its not working? import pygame import os pygame.init() screen_width = 480 screen...
[ "\nevent is an object. You have to get the type of the event, e.g.:\nif event == pygame.KEYDOWN\nif event.type == pygame.KEYDOWN:\n\n\nYou have to limit the frames per second to limit CPU usage with pygame.time.Clock.tick and to control the speed of the game. Otherwise, the player moves much too fast and immediatel...
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074417243_pygame_python.txt
Q: Pascal's triangle in python issue I'm trying to create a pascal's triangle generator, but for some reason it's not giving me the correct output. I should get: [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] But instead I'm getting: [1, 1] [1, 2, 1] [1, 3, 4, 1] [1, 4, 8, 9, 1] Here's the code: length = 4 lst = [1...
Pascal's triangle in python issue
I'm trying to create a pascal's triangle generator, but for some reason it's not giving me the correct output. I should get: [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] But instead I'm getting: [1, 1] [1, 2, 1] [1, 3, 4, 1] [1, 4, 8, 9, 1] Here's the code: length = 4 lst = [1] for i in range(length): for j in...
[ "There should be a line added that clones the list since right now you are only referencing it.\nlength = 4\n\nlst = [1]\n\nfor i in range(length):\n temp = list(lst)\n for j in range(i):\n lst[j+1] = temp[j] +temp[j+1]\n lst.append(1)\n temp = lst\n print(lst)\n\nThis produces correct output\...
[ 0, 0, 0 ]
[]
[]
[ "list", "pascals_triangle", "python" ]
stackoverflow_0074417268_list_pascals_triangle_python.txt
Q: How to vectorize performing pairwise sums given two numpy arrays? I have two numpy arrays which look like this: x = [v1, v2, v3, ..., vm] y = [w1, w2, w3, ..., wn] where vi, wj are numpy arrays of length 3. I want to perform a pairwise summation of v's and w's and get a final array z = [v1+w1, v1+w2,...,v1+wn,v2+...
How to vectorize performing pairwise sums given two numpy arrays?
I have two numpy arrays which look like this: x = [v1, v2, v3, ..., vm] y = [w1, w2, w3, ..., wn] where vi, wj are numpy arrays of length 3. I want to perform a pairwise summation of v's and w's and get a final array z = [v1+w1, v1+w2,...,v1+wn,v2+w1, ..., vi+wj, ..., vm+wn] A simple way of obtaining z is as follows:...
[ "You can take advantage of broadcasting, creating a 2D array, then you can easily get z[i,j] = x[i] + y[j]\nx = np.reshape(x, (-1, 1)) # shape (N, 1)\ny = np.reshape(y, (-1, 1)) # shape (N, 1)\nz = x + y.T # shape (N, N)\n\nIf you want to have z as a 1D array you can do z.reshape(-1).\n", "If x is mx3 matrix, y i...
[ 0, 0 ]
[]
[]
[ "numpy", "python", "vectorization" ]
stackoverflow_0074417478_numpy_python_vectorization.txt
Q: Windows could not start the service on Local Computer. Error 193: 0xc1 I coded a python a program and converted it to an executable. It was working perfectly. Then I used sc.exe in cmd to make it a system service. But the problem is that when I try to start the service, this message pops up. By searching online, I...
Windows could not start the service on Local Computer. Error 193: 0xc1
I coded a python a program and converted it to an executable. It was working perfectly. Then I used sc.exe in cmd to make it a system service. But the problem is that when I try to start the service, this message pops up. By searching online, I came to know that the path to that exe file might be incorrect, but that's ...
[ "I think, there is no connection between .exe and service. That's why can't start. What kind of program is that? If is for network you have duplicated port.\nHave fun!!!\n" ]
[ 0 ]
[]
[]
[ "python", "system_services" ]
stackoverflow_0074419151_python_system_services.txt
Q: How to fetch more than 10000 records from Elasticsearch 7.X.X I need to fetch more than 10000 records from Elasticsearch but I'm unable to set the index.max_result_window in Elasticsearch 7.2 from python. I had used the following command to set the window limit to 100000 in Elasticsearch V6 which was working. es.i...
How to fetch more than 10000 records from Elasticsearch 7.X.X
I need to fetch more than 10000 records from Elasticsearch but I'm unable to set the index.max_result_window in Elasticsearch 7.2 from python. I had used the following command to set the window limit to 100000 in Elasticsearch V6 which was working. es.indices.create(index=prod_index, body={"settings": {"index.mapping....
[ "It's better not to and that's the reason why they set it 10 000 as a max number. Increasing index.max-result-window is not very good idea which can lead to cluster latency or crashes. When you set a size, ES creates a heap of the same size before fetching the data. Those records will stay in RAM and unless you hav...
[ 4, 0 ]
[]
[]
[ "elasticsearch", "python" ]
stackoverflow_0057058188_elasticsearch_python.txt
Q: Question on web-scraping hyperlinks with element criteria using python on tennisexplorer.com The problem I have with the code below is it prints all of the a-href stuff, I want to know how to change it so that it only prints the hyperlinks found in "info" on the far right of the tables on the webpage "https://www....
Question on web-scraping hyperlinks with element criteria using python on tennisexplorer.com
The problem I have with the code below is it prints all of the a-href stuff, I want to know how to change it so that it only prints the hyperlinks found in "info" on the far right of the tables on the webpage "https://www.tennisexplorer.com/results/?type=atp-single&year=2022&month=09&day=08". import requests from bs4 i...
[ "Here is a way to get a dataframe (with one column) with urls pointing to every match detail:\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nurl = 'https://www.tennisexplorer.com/results/?type=a...
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074419007_beautifulsoup_python_web_scraping.txt
Q: How to formulate a linear minimization problem with scipy I have a problem of the form: min (x1 - k1) + (x2 -k2) + ... k are constants with linear constraints: A*x = B B's size is 3x1, A is 3xn and x is nx1 I also have linear bounds inequalities in the form l1 <= x1 <= u1 l2 <= x2 <= u2 ...etc I'm trying to resolv...
How to formulate a linear minimization problem with scipy
I have a problem of the form: min (x1 - k1) + (x2 -k2) + ... k are constants with linear constraints: A*x = B B's size is 3x1, A is 3xn and x is nx1 I also have linear bounds inequalities in the form l1 <= x1 <= u1 l2 <= x2 <= u2 ...etc I'm trying to resolve it in python with scipy : import numpy as np from scipy.optim...
[ "Your \"vectors\" must be dimension 1; yours are dimension 2.\nimport numpy as np\nfrom scipy.optimize import Bounds, minimize, fmin_cobyla\n\nA = \\\nnp.array([[ 0.11, 0.1333, 0.1333, 0.01],\n [ 0.02, 6.667, 0.1333, 0.12],\n [0.0933, 0.6667, 0.6, 0.01]])\n\nB = \\\nnp.array([25,\n ...
[ 1, 1 ]
[]
[]
[ "minimize", "numpy", "optimization", "python", "scipy" ]
stackoverflow_0074416886_minimize_numpy_optimization_python_scipy.txt
Q: Lists and Loops in Python I am trying to find a maximum/minimum value corresponding to a day. list1 includes all 7 days of the week. list two is empty [] I have a loop that iterates as many times as the len of list 1,(7), which asks the user to input how many hours they did an activity each day. how can I print th...
Lists and Loops in Python
I am trying to find a maximum/minimum value corresponding to a day. list1 includes all 7 days of the week. list two is empty [] I have a loop that iterates as many times as the len of list 1,(7), which asks the user to input how many hours they did an activity each day. how can I print the day that has the max/min valu...
[ "Simply create a dictonary by zipping them out of values print max and min key value pairs\ncount = 0\nimport sys\nlist1 = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nlist2 = []\ntotal = 0\nfor x in range(len(list1)):\n try:\n num = float(input(f\"Enter ...
[ 1, 0, 0 ]
[ "Your approach also works pretty well. Here's the fix on your approach:\ncount = 0\nlist1 = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\n\nlist2 = []\ntotal = 0\nfor x in range(len(list1)):\n try:\n num = float(input(f\"Enter amount of hours of exercise for...
[ -1 ]
[ "list", "loops", "python" ]
stackoverflow_0074419203_list_loops_python.txt
Q: Merge hourly data with 15 minute data By using very inefficient string manipulation (replace the minute with zeros, i.e. '06:15:00' -> '06:00:00'), I am able to merge hourly data with the 15 minute data. I am wondering if there is a more elegant way of merging the data. Thanks in advance! import ccxt import pandas...
Merge hourly data with 15 minute data
By using very inefficient string manipulation (replace the minute with zeros, i.e. '06:15:00' -> '06:00:00'), I am able to merge hourly data with the 15 minute data. I am wondering if there is a more elegant way of merging the data. Thanks in advance! import ccxt import pandas as pd ex = ccxt.binance({'enableRateLimit...
[ "EXAMPLE\ndf\ndata = [['2022-11-13 05:00:00', 16853.68],\n ['2022-11-13 06:00:00', 16684.45],\n ['2022-11-13 07:00:00', 16731.94]]\ndf = pd.DataFrame(data, columns=['timestamp_h', 'close_h'])\n\n timestamp_h close_h\n0 2022-11-13 05:00:00 16853.6800\n1 2022-11-13 06:00:00 16...
[ 1 ]
[]
[]
[ "bitcoin", "ccxt", "dataframe", "pandas", "python" ]
stackoverflow_0074419165_bitcoin_ccxt_dataframe_pandas_python.txt
Q: dict comprehension in python New to python, and am learning about dict comprehension online. i saw this snippet of code but do not understand how it work. i understand this dict comprehension {k: D[k] for k in D.keys() but please help me understand - removeKeys}. I do not understand how the result to be. Thank y...
dict comprehension in python
New to python, and am learning about dict comprehension online. i saw this snippet of code but do not understand how it work. i understand this dict comprehension {k: D[k] for k in D.keys() but please help me understand - removeKeys}. I do not understand how the result to be. Thank you for your feedback
[ "First, let's understand list comprehension.\nList Comprehension:\nx = [i for i in range(10)]\n>>> Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nNow, similary in dict comprehension we use the same syntax. However, dicts have key: value pairs and hence that's how you need to do it.\nDict Comprehension:\nWhat the above c...
[ 0 ]
[]
[]
[ "dictionary_comprehension", "python" ]
stackoverflow_0074419303_dictionary_comprehension_python.txt
Q: PyAutoGui still not showing correct RGB pixel values on MacOS python3.8 I want to get the RGB value of the current mouse position on my macbook screen. Right now it is not showing correct: When I hover my mouse over a black image the RGB values don't go near (0, 0, 0) it stays like (181, 201, 233). When I put my m...
PyAutoGui still not showing correct RGB pixel values on MacOS python3.8
I want to get the RGB value of the current mouse position on my macbook screen. Right now it is not showing correct: When I hover my mouse over a black image the RGB values don't go near (0, 0, 0) it stays like (181, 201, 233). When I put my mouse cursor on a playing YT video the RGB values do not change. Only When I m...
[ "you can do this very easily\nyou should insall the pyscreeze module\nimport pyscreeze\n\n#the value of pixel whose value is to be get\nx=23\ny=23\n\n#screen object\nscreen=pyscreeze.screenshot()\n\nrgb_values=screen.getpixel((x,y))\n\n", "I sat on it for 5 hours because\nx, y = pyautogui.position()\npix = pyauto...
[ 0, 0 ]
[]
[]
[ "getpixel", "macos", "pyautogui", "python", "python_3.x" ]
stackoverflow_0067021450_getpixel_macos_pyautogui_python_python_3.x.txt
Q: How to Use Pyshark to Read a .pcapng file's content directly from memory instead of from disk? I am using the file capture API of pyshark like this. #!/usr/bin/env python3 # encoding:utf-8 import pyshark as ps filename: str = 'some_file.pcapng' with ps.FileCapture(input_file=filename) as capture: print(capt...
How to Use Pyshark to Read a .pcapng file's content directly from memory instead of from disk?
I am using the file capture API of pyshark like this. #!/usr/bin/env python3 # encoding:utf-8 import pyshark as ps filename: str = 'some_file.pcapng' with ps.FileCapture(input_file=filename) as capture: print(capture[0].pretty_print()) But now, I have another use case where the file content can be made availabl...
[ "Option 1\nAs per Pyshark's documentation on github:\n\nOther options\n\nparam input_file: Either a path or a file-like object containing either a packet capture file (PCAP, PCAP-NG..) or a TShark xml.\n...\n\n\nHence, FileCapture class can take as input_file a file-like object as well, which you can access using t...
[ 1 ]
[]
[]
[ "binaryfiles", "fastapi", "packet_capture", "pyshark", "python" ]
stackoverflow_0074417838_binaryfiles_fastapi_packet_capture_pyshark_python.txt
Q: How to serialize data and fix the wrong one in Python? I'm new to Python. I need to serialize the data by the first two chars is taken from the first and the last char in the given string plus the transposed number just like this one: Input: ["HOMAGE", "DESIGN", "PROTECTION", "COMPANY"] Output: ["HE01", "DN02", "P...
How to serialize data and fix the wrong one in Python?
I'm new to Python. I need to serialize the data by the first two chars is taken from the first and the last char in the given string plus the transposed number just like this one: Input: ["HOMAGE", "DESIGN", "PROTECTION", "COMPANY"] Output: ["HE01", "DN02", "PN03", "CY04"] Below is my current code: ls = ["HOMAGE", "DE...
[ "Here's a list comprehension approach:\nls = [\"HOMAGE\", \"DESIGN\", \"PROTECTION\", \"COMPANY\"]\nser = [f\"{j[0]}{j[-1]}{i+1:>02}\" for i,j in enumerate(ls)]\nprint(ser)\n\nWhat did I do above?\n\nUsing f-strings makes it easier to create strings with variables.\nenumerate(iterable) returns the (index, value) pa...
[ 3 ]
[]
[]
[ "arrays", "list", "python", "python_3.x", "serialization" ]
stackoverflow_0074419309_arrays_list_python_python_3.x_serialization.txt
Q: Update all rows in csv with same value using python I want to update all column values in respective rows using python. I am using the following code. def update_run_id_in_csv(rds_db_conn,test_case_name,file_name): df = pd.read_csv("{}/output/Float_Ingestion_Expected_Output_files/{}/{}.csv".format(str(parentDi...
Update all rows in csv with same value using python
I want to update all column values in respective rows using python. I am using the following code. def update_run_id_in_csv(rds_db_conn,test_case_name,file_name): df = pd.read_csv("{}/output/Float_Ingestion_Expected_Output_files/{}/{}.csv".format(str(parentDir), test_case_name, file_name)) for x in df: ...
[ "No need for a loop here. You can use either df.loc[:, \"Age\"] = 30 or simply df[\"Age\"] = 30.\nTry this :\ndef update_run_id_in_csv(rds_db_conn,test_case_name,file_name):\n df = pd.read_csv(\"{}/output/Float_Ingestion_Expected_Output_files/{}/{}.csv\".format(str(parentDir), test_case_name, file_name))\n d...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074419080_pandas_python.txt
Q: Add new column Pyspark that contains unique count I have a dataframe in pyspark that looks like this +------------------+--------------------+ | Community_Area| Date| +------------------+--------------------+ | New City|09/05/2015 01:30:...| | Austin|09/04/2015 11:30:...| | ...
Add new column Pyspark that contains unique count
I have a dataframe in pyspark that looks like this +------------------+--------------------+ | Community_Area| Date| +------------------+--------------------+ | New City|09/05/2015 01:30:...| | Austin|09/04/2015 11:30:...| | New City|09/05/2015 12:01:...| | Avonda...
[ "example\ndf = pd.DataFrame([list('ABACBDEC')], index=['col1']).T\n\noutput(df):\n col1\n0 A\n1 B\n2 A\n3 C\n4 B\n5 D\n6 E\n7 C\n\ngroupby + cumcount\ndf.groupby('col1').cumcount() + 1\n\nresult:\n0 1\n1 1\n2 2\n3 1\n4 2\n5 1\n6 1\n7 2\ndtype: int64\n\nmake rusult to colum...
[ 0, 0 ]
[]
[]
[ "dataframe", "pyspark", "python" ]
stackoverflow_0074409784_dataframe_pyspark_python.txt
Q: How to break out of a While True loop in Python I am reading cards in Python using an RFID Reader and I want to detect how long a card has been detected for in seconds, minutes and hours. The program begins to run once a card has been detected and starts the count but the problem is that the code does not break wh...
How to break out of a While True loop in Python
I am reading cards in Python using an RFID Reader and I want to detect how long a card has been detected for in seconds, minutes and hours. The program begins to run once a card has been detected and starts the count but the problem is that the code does not break when the card has been removed but instead it continues...
[ "You will never leave from second while True. You must read the card every second and check if the card has been removed. Add the code below to the second while True. I think that will may solve your problem and after removing the card, program break from while.\nif readCard.readCard() == '':\n break\n\n" ]
[ 0 ]
[]
[]
[ "python", "rfid", "time" ]
stackoverflow_0074419240_python_rfid_time.txt
Q: How to return all paths with Breadth First Search without printing? I am trying to print all paths from source= 2 to destination = 3 with a graph that has the following edges: g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(0, 3) g.addEdge(2, 0) g.addEdge(2, 1) g.addEdge(1, 3) When I print the variable "all_paths"...
How to return all paths with Breadth First Search without printing?
I am trying to print all paths from source= 2 to destination = 3 with a graph that has the following edges: g.addEdge(0, 1) g.addEdge(0, 2) g.addEdge(0, 3) g.addEdge(2, 0) g.addEdge(2, 1) g.addEdge(1, 3) When I print the variable "all_paths", it prints all possible paths correctly. However, when I try to append t...
[ "I fixed it by changing:\nif u == d:\n all_paths.append(path)\n print(path)\n\nto\nif u == d:\n print(path)\n path2 = copy.deepcopy(path)\n all_paths.append(path2)\n\n", "The error is pretty obvious when you run it through pythontutor\nYou only have one object path which you remove the elements in ...
[ 1, 0 ]
[]
[]
[ "breadth_first_search", "python" ]
stackoverflow_0074412691_breadth_first_search_python.txt
Q: How to generate config combinations from a dict? I want to generate all config from a dict like this: dict = { "a": [1,2,3], "b":{ "b1":[True, False], "b2":[0], } } List attributes are needed to be enumerated. And output is like this: config = [{ "a": 1, "b":{ "b1":True, "b2":0, }, {...
How to generate config combinations from a dict?
I want to generate all config from a dict like this: dict = { "a": [1,2,3], "b":{ "b1":[True, False], "b2":[0], } } List attributes are needed to be enumerated. And output is like this: config = [{ "a": 1, "b":{ "b1":True, "b2":0, }, { "a": 2, "b":{ "b1":True, "b2":0, }, ......
[ "There is no value in using recursion for this. A straightforward list comprehension will suffice:\n_dict = {\n \"a\": [1, 2, 3],\n \"b\": {\n \"b1\": [True, False],\n \"b2\": [0]\n }\n}\n\nconfig = [{'a': k, 'b': {'b1': True, 'b2': 0}} for k in _dict['a']]\n\nprint(config)\n\nOutput:\n[{'a':...
[ 0, 0 ]
[]
[]
[ "algorithm", "configuration", "python", "recursion" ]
stackoverflow_0074418977_algorithm_configuration_python_recursion.txt
Q: bin/sh: 1: visqol: not found When I execute my code it shows me error as below, I don't know what is this visqol_find.py:33 ERROR: /bin/sh: 1: visqol: not found meaning, and I pretty sure that visqol_value and visqol_threshold are both defined as float because the program is working fine with my professor. My syst...
bin/sh: 1: visqol: not found
When I execute my code it shows me error as below, I don't know what is this visqol_find.py:33 ERROR: /bin/sh: 1: visqol: not found meaning, and I pretty sure that visqol_value and visqol_threshold are both defined as float because the program is working fine with my professor. My system is Ubuntu 18.04 and python is 3...
[ "The error message is from /bin/sh. That means you are expecting your (bash/dash/other) shell to execute a Python script which isn't going to work.\nYou need to either put a Python shebang as the first line of your script, e.g.\n#!/usr/bin/env python3\n...\n... rest of script\n\nthen make it executable with:\nchmod...
[ 1, 0 ]
[]
[]
[ "bazel", "python" ]
stackoverflow_0074419277_bazel_python.txt
Q: Retrieve object from set in O(1) All the people's names are unique. How can I find the peter instance in O(1)? I'm thinking you need to access peter via its hash but am unsure how to specifically do it from dataclasses import dataclass @dataclass class Person: name: str age: int def __hash__(self)...
Retrieve object from set in O(1)
All the people's names are unique. How can I find the peter instance in O(1)? I'm thinking you need to access peter via its hash but am unsure how to specifically do it from dataclasses import dataclass @dataclass class Person: name: str age: int def __hash__(self): return hash(str(self)) ...
[ "sets can be thought of as an unordered collection of keys of a map (read dictionary) but without any auxiliary (associated) values. you'd usually use sets to check if some value is inside the set or not, but not to retrieve that value from the set nor to access its associated values (like maps - in python dictiona...
[ 1 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0074419480_data_structures_python.txt
Q: ValueError: Unable to expand environment variable in host setting: 'https://goerli.infura.io/v3/$WEB3_INFURA_PROJECT_ID' I wanted to deploy my Smart Contract on testnet but I got an error, below is the code from brownie import accounts, config,SimpleStorage def deploy_simple_storage(): account=accounts.load("...
ValueError: Unable to expand environment variable in host setting: 'https://goerli.infura.io/v3/$WEB3_INFURA_PROJECT_ID'
I wanted to deploy my Smart Contract on testnet but I got an error, below is the code from brownie import accounts, config,SimpleStorage def deploy_simple_storage(): account=accounts.load("freecodecamp-account") # print(account) simple_storage=SimpleStorage.deploy({"from":account}) stored_value=simple...
[ "If you do not yet have one, go sign up for an account with infura\ncreate a new ETH project in infura\nrun this command, with your project key of course, in the terminal where you have your brownie script being run\nnote: sometimes the terminal \"forgets\" and you have to re run this command\nexport WEB3_INFURA_PR...
[ 0, 0 ]
[]
[]
[ "brownie", "python", "solidity" ]
stackoverflow_0074097511_brownie_python_solidity.txt
Q: How to convert string with any date format to %m/%d/%y in Python I have a csv with with dates. The dates have inconsistent formatting and I want it all to change to mm/dd/yyyy upon importing. Is there a way to do it? I know about strptime but that requires a second argument for the format of the given date. A: I...
How to convert string with any date format to %m/%d/%y in Python
I have a csv with with dates. The dates have inconsistent formatting and I want it all to change to mm/dd/yyyy upon importing. Is there a way to do it? I know about strptime but that requires a second argument for the format of the given date.
[ "I would recommend strftime from datetime with this you can perform a format change without the given format.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0074419178_django_django_forms_python.txt
Q: Class attribute error while creating python object I am writing a small game. I want to create two objects from the same class and combine them into a group. But when creating the second object, an error occurs "AttributeError: 'Enemy' object has no attribute 'get_rect'" Here is the code related to the problem cla...
Class attribute error while creating python object
I am writing a small game. I want to create two objects from the same class and combine them into a group. But when creating the second object, an error occurs "AttributeError: 'Enemy' object has no attribute 'get_rect'" Here is the code related to the problem class Enemy(pygame.sprite.Sprite): def __init__(self): ...
[ "Yes, of course an Enemy does not have a get_rect method. The error message is very clear. The problem here is:\n\nclass Enemy(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = enemy #<---\n self.rect = self.image.get_rect() ...
[ 0 ]
[]
[]
[ "attributes", "class", "pygame", "python" ]
stackoverflow_0074419560_attributes_class_pygame_python.txt
Q: Combining annotation and filtering in Django for two different classes Hi I am trying to query and count marketplaces for every infringement only for the logged in user. Essentially trying to combine these two. mar_count = Marketplace.objects.annotate(infringement_count=Count('infringement')) inf=Infringement.obj...
Combining annotation and filtering in Django for two different classes
Hi I am trying to query and count marketplaces for every infringement only for the logged in user. Essentially trying to combine these two. mar_count = Marketplace.objects.annotate(infringement_count=Count('infringement')) inf=Infringement.objects.filter(groups__user=request.user) I found a below example but this is ...
[ "Aggregation functions can take a filter as named parameter so:\nmar_count = Marketplace.objects.annotate(infringement_count=Count('infringement', filter=Q(groups__user=request.user)))\n\n" ]
[ 1 ]
[]
[]
[ "annotations", "django", "filter", "python" ]
stackoverflow_0074419378_annotations_django_filter_python.txt
Q: I'm trying to deploy a smart contract on Goerli, but receiving an ImportError I'm deploying a contract on Goerli using Brownie, following all the steps of the guide correctly, I've compiled contract 'FundMe' successfully but it returns an error - ImportError: cannot import name 'FundMe' from 'brownie'. I'm using a...
I'm trying to deploy a smart contract on Goerli, but receiving an ImportError
I'm deploying a contract on Goerli using Brownie, following all the steps of the guide correctly, I've compiled contract 'FundMe' successfully but it returns an error - ImportError: cannot import name 'FundMe' from 'brownie'. I'm using a command - brownie run scripts/deploy.py --network goerli. Also .yaml file is corre...
[ "I've had the same issue before. It's like due to the Fundme was not loaded. The workaround was to use brownie console instead of the deploy script.\nIn your case, try:\n\ncd to your project path\nrun brownie console --network goerli, then FundMe should be loaded as a variable.\nrun accounts.add('YOUR_PRIVATE_KEY')...
[ 0 ]
[]
[]
[ "blockchain", "brownie", "python", "solidity" ]
stackoverflow_0074350345_blockchain_brownie_python_solidity.txt
Q: How to create a numpy array of lists? I want to create a numpy array in which each element must be a list, so later I can append new elements to each. I have looked on google and here on stack overflow already, yet it seems nowhere to be found. Main issue is that numpy assumes your list must become an array, but t...
How to create a numpy array of lists?
I want to create a numpy array in which each element must be a list, so later I can append new elements to each. I have looked on google and here on stack overflow already, yet it seems nowhere to be found. Main issue is that numpy assumes your list must become an array, but that is not what I am looking for.
[ "As you discovered, np.array tries to create a 2d array when given something like\n A = np.array([[1,2],[3,4]],dtype=object)\n\nYou have apply some tricks to get around this default behavior.\nOne is to make the sublists variable in length. It can't make a 2d array from these, so it resorts to the object array:\nI...
[ 69, 10, 3, 2, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "arrays", "list", "numpy", "python" ]
stackoverflow_0033983053_arrays_list_numpy_python.txt
Q: console.log in flask with javasript I want to print some string, for example, "Hello World". I use javasript with flask in pycharm for it: <script> function hello() { alert("Hello!!!!"); } </script> in html <button onclick="hello()">Click button!</button> It works well. Bu...
console.log in flask with javasript
I want to print some string, for example, "Hello World". I use javasript with flask in pycharm for it: <script> function hello() { alert("Hello!!!!"); } </script> in html <button onclick="hello()">Click button!</button> It works well. But when I try to change from alert to cons...
[ "If you press f12 you'll access the developer tools on the browser. there you'll see it's own console. that's where the message would appear.\n", "If you want to directly see the result on the HTML document,\nyou can use:\n document.write(\"Hello!!!\");\n document.writeln(\"Hello!!!\");\n\nbut if you want to lo...
[ 0, 0 ]
[]
[]
[ "flask", "javascript", "pycharm", "python" ]
stackoverflow_0067754106_flask_javascript_pycharm_python.txt
Q: Everytime I am running Brownie run scripts/deploy.py, its showing the problem below, I need to understand what might be the problem with my install? When I deploy this code, this is what happens? brownie run scripts/deploy.py Brownie v1.19.2 - Python development framework for Ethereum BrownieSimpleStorageProject ...
Everytime I am running Brownie run scripts/deploy.py, its showing the problem below, I need to understand what might be the problem with my install?
When I deploy this code, this is what happens? brownie run scripts/deploy.py Brownie v1.19.2 - Python development framework for Ethereum BrownieSimpleStorageProject is the active project. Launching 'ganache-cli --port 8545 --gasLimit 12000000 --accounts 10 --hardfork istanbul --mnemonic brownie'... File "brownie/_c...
[ "The return value totally depends on what's inside your deployment script, which is scripts/deploy.py. Check the script and make everything right.\n" ]
[ 0 ]
[]
[]
[ "brownie", "python", "solidity", "web3py" ]
stackoverflow_0074344900_brownie_python_solidity_web3py.txt
Q: filter rows from data where column salary has string datatype id name salary 0 1 shyam 10000 1 2 ram 20000 2 3 ravi abc 3 4 abhay 30000 4 5 karan fgh expected: id name salary 2 3 ravi abc 4 5 karan fgh A: We can use str.contains as follow...
filter rows from data where column salary has string datatype
id name salary 0 1 shyam 10000 1 2 ram 20000 2 3 ravi abc 3 4 abhay 30000 4 5 karan fgh expected: id name salary 2 3 ravi abc 4 5 karan fgh
[ "We can use str.contains as follows:\ndf_out = df[(df[\"name\"].str.contains(r'^[A-Za-z]+$', regex=True)) &\n (df[\"salary\"].str.contains(r'^[A-Za-z]+$', regex=True))]\n\nThe above logic will only match rows for which both the name and salary columns contain only alpha characters.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074419672_dataframe_pandas_python.txt
Q: I ran the smart contract and I linked them with the Python file on the virtual box, when running them it gives me error ERROR: raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=7545): Max retries exceeded with url: / (Caused by NewConnectionErr...
I ran the smart contract and I linked them with the Python file on the virtual box, when running them it gives me error
ERROR: raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=7545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f6e001a6400>: Failed to establish a new connection: [Errno 111] Connectio...
[ "First of all, don't post your Private Key online.\nIf you wanna test your contract locally, then you will have to have a local test net running.\nIf you wanna deploy your contract to any network, replace the RPC url with the chain's RPC url.\n" ]
[ 0 ]
[]
[]
[ "python", "solidity" ]
stackoverflow_0074416068_python_solidity.txt
Q: How to find similarity score between two rows in a pandas data frame I want to find the similarity of given sentences between two rows. In my sample data frame: import pandas as pd data = [f'Sent {str(i)}' for i in range(10)] df = pd.DataFrame(data=data, columns=['Sentences']) Sentences 0 Sent 0 1 Sent 1...
How to find similarity score between two rows in a pandas data frame
I want to find the similarity of given sentences between two rows. In my sample data frame: import pandas as pd data = [f'Sent {str(i)}' for i in range(10)] df = pd.DataFrame(data=data, columns=['Sentences']) Sentences 0 Sent 0 1 Sent 1 2 Sent 2 3 Sent 3 4 Sent 4 5 Sent 5 6 Sent 6 7 Sent 7 8...
[ "One option:\nfrom difflib import SequenceMatcher\nfrom itertools import combinations\nimport numpy as np\nimport pandas as pd\n\ndf = pd.DataFrame({'col': ['ABC', 'ABCD', 'DEF', 'GHI']})\n\n# set up empty array\na = np.zeros((len(df), len(df)))\n\n# compute difference for each unique pair and assign upper triangle...
[ 1 ]
[]
[]
[ "nlp", "pandas", "python", "sentence_similarity", "similarity" ]
stackoverflow_0074419603_nlp_pandas_python_sentence_similarity_similarity.txt
Q: Use Selenium to click a 'Load More' button (NOT WORKING) The goal is to get all the news articles from this page by clicking the load more button programmatically: https://money.tmx.com/en/quote/AMK/news Here's what I have tried so far: from bs4 import BeautifulSoup import urllib3 from selenium import webdriver i...
Use Selenium to click a 'Load More' button (NOT WORKING)
The goal is to get all the news articles from this page by clicking the load more button programmatically: https://money.tmx.com/en/quote/AMK/news Here's what I have tried so far: from bs4 import BeautifulSoup import urllib3 from selenium import webdriver import re import time import random from selenium.webdriver.sup...
[ "The below code example is loading the load more button effectively.\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nimport time\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\ns=Service('./chromedriver')\ndriver= webdriver....
[ 1, 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074417476_python_selenium_selenium_webdriver_web_scraping.txt
Q: How to append list entries to a JSON file through a for loop? In the following code, I am trying to append every oth element to a JSON file: title = [] # api_result['search_results']['title'] asin = [] # api_result['search_results']['asin'] link = [] # api_result['search_results']['link'] categories = [] # api...
How to append list entries to a JSON file through a for loop?
In the following code, I am trying to append every oth element to a JSON file: title = [] # api_result['search_results']['title'] asin = [] # api_result['search_results']['asin'] link = [] # api_result['search_results']['link'] categories = [] # api_result['search_results']['categories'][0]['name'] image_url = [] ...
[ "Opening the file must be done only once with the with open block, otherwise it opens and closes the file at each iteration.\nThereafter, just wrap at each iteration.\nLook at this code:\nimport json\n\n# I am assuming your data in this form\ntitle = ['title_0', 'title_1']\nlink = ['link_0', 'link_1']\n\nwith open(...
[ 1 ]
[]
[]
[ "dictionary", "json", "list", "python" ]
stackoverflow_0074419713_dictionary_json_list_python.txt
Q: Why is the code not working for the following input as the nodes of the tree [5,1,4,null,null,3,6] this is the input for which my code is failing -The expected output is False but I am getting True as the output. The link for the question i have written the code is -https://leetcode.com/problems/validate-binary-se...
Why is the code not working for the following input as the nodes of the tree
[5,1,4,null,null,3,6] this is the input for which my code is failing -The expected output is False but I am getting True as the output. The link for the question i have written the code is -https://leetcode.com/problems/validate-binary-search-tree/submissions/ ` # Definition for a binary tree node. # class TreeNode: # ...
[ "The main problem is that your isValidBST function always returns True. It makes the calls to lcheck and rcheck but then ignores their return values, and just returns True no matter what.\nSecondly, those lcheck and rcheck functions never return True. They also suffer from the same problem described above: they mak...
[ 0 ]
[]
[]
[ "binary", "binary_search_tree", "python", "tree" ]
stackoverflow_0074419548_binary_binary_search_tree_python_tree.txt
Q: Getting a tkinter window to be on top of a pygame window I'm trying to build a chess game in pygame. For pawn promotion I settled to use the function "get_piece_name" which opened a tkinter window with buttons to choose the "promotion piece". What I want is make the tkinter window to appear on top of the pygame on...
Getting a tkinter window to be on top of a pygame window
I'm trying to build a chess game in pygame. For pawn promotion I settled to use the function "get_piece_name" which opened a tkinter window with buttons to choose the "promotion piece". What I want is make the tkinter window to appear on top of the pygame one whenever it is on focus; and make the tk win. minimize when ...
[ "The combination of pygame and tkinter is not fully featured (see Embedding a Pygame window into a Tkinter or WxPython frame). It is never a good idea to mix frameworks. The frameworks may interact poorly with each other or conflict completely. If it works on your (operating) system, that doesn't mean it will work ...
[ 0 ]
[]
[]
[ "pygame", "python", "tkinter" ]
stackoverflow_0068236226_pygame_python_tkinter.txt
Q: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited client.load_extension(f'cogs.{filename[:-3]}') so before everyone screams at me saying there already is a response, no there is not. Ive tried every stack overflow post about this and none fix my problem. My code: my main.py (main) ` import disco...
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited client.load_extension(f'cogs.{filename[:-3]}')
so before everyone screams at me saying there already is a response, no there is not. Ive tried every stack overflow post about this and none fix my problem. My code: my main.py (main) ` import discord import os from discord.ext import commands import asyncio intents = discord.Intents.all() intents.members = True clie...
[ "Extensions are now asynchronous. The migration guide explains what to change in order to make the switch: https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous\nYou're not awaiting async functions, so the solution is to... await them...\n\"I tried this bu...
[ 0 ]
[]
[]
[ "coroutine", "discord", "discord.py", "python", "python_asyncio" ]
stackoverflow_0074419280_coroutine_discord_discord.py_python_python_asyncio.txt
Q: __repr__ inheritance with pygame.Rec In my test I created a list of instances of class B, which inherits from pygame.Rect, and has its own __repr__ method. When I print the list as print(blocks), it correctly calls the child __repr__, but if I print the single elements of the list using a loop, it prints the __rep...
__repr__ inheritance with pygame.Rec
In my test I created a list of instances of class B, which inherits from pygame.Rect, and has its own __repr__ method. When I print the list as print(blocks), it correctly calls the child __repr__, but if I print the single elements of the list using a loop, it prints the __repr__ method of the parent class instead. Wh...
[ "print(block) calls the __str__ method, not the __repr__ method. So you need to override __str__ in B.\n" ]
[ 0 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0070483098_pygame_python_python_3.x.txt
Q: How can I sum up entire columns in a QTableWidget? I'm trying to do a GUI that can calculate multiple vectors operations (sum, rest, multiplication, division). I'm using the "QTableWidget" from "Qt Designer" and doing the code in spyder. But I can't find the way to perform the operations, I'm new using "Qt Designe...
How can I sum up entire columns in a QTableWidget?
I'm trying to do a GUI that can calculate multiple vectors operations (sum, rest, multiplication, division). I'm using the "QTableWidget" from "Qt Designer" and doing the code in spyder. But I can't find the way to perform the operations, I'm new using "Qt Designer". I already got it to do the sums of the values, but...
[ "\nyou can iterate over rows an columns and sum up like this:\ndef sum_up(self):\n from collections import defaultdict\n output = defaultdict(list)\n for col in range(self.table.columnCount()):\n for row in range(self.table.rowCount()):\n value = int(self.table.item(row, col).text())\n ...
[ 0 ]
[]
[]
[ "pyqt5", "python", "qtablewidget" ]
stackoverflow_0074417067_pyqt5_python_qtablewidget.txt
Q: Store multiple data frames at the same time I have 4 different data frames and I am now storing these in a bucket in S3. I can do it manually one by one but I would like to store all 4 data frames by running the code just once. csv_buffer = StringIO() data_frame.to_csv(csv_buffer) s3_resource = boto3.resource('s3'...
Store multiple data frames at the same time
I have 4 different data frames and I am now storing these in a bucket in S3. I can do it manually one by one but I would like to store all 4 data frames by running the code just once. csv_buffer = StringIO() data_frame.to_csv(csv_buffer) s3_resource = boto3.resource('s3') s3_resource.Object(S3_BUCKET_NAME,'bucket_name/...
[ "You could create a list with your 4 data frames and then iterate through it:\nimport boto3\nfrom io import StringIO\n\ndef write_dataframe_to_csv_on_s3(dataframe, filename, S3_BUCKET_NAME):\n csv_buffer = StringIO()\n dataframe.to_csv(csv_buffer)\n s3_resource = boto3.resource(\"s3\")\n s3_resource.Obj...
[ 0 ]
[]
[]
[ "amazon_s3", "pandas", "python" ]
stackoverflow_0074417992_amazon_s3_pandas_python.txt
Q: filenotfounderror: [errno 2] no such file or directory: .txt file I am currently learning python and my instructor is telling me to open a text file using the open() meathod. I get the following error each time: FileNotFoundError: [Errno 2] No such file or directory: 'movies.txt' I have tried using online guides b...
filenotfounderror: [errno 2] no such file or directory: .txt file
I am currently learning python and my instructor is telling me to open a text file using the open() meathod. I get the following error each time: FileNotFoundError: [Errno 2] No such file or directory: 'movies.txt' I have tried using online guides but all I could find was for .csv files, whereas I'm trying to open a te...
[ "First of all you have to make sure that the file you are looking is in the same folder as your script as you are giving just the name and not the path.\nThen the code to read a file misses a parameter:\nwith open('movies.txt', 'r') as file_object:\n contents = file_object.read()\n print(contents.strip())\n\n...
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "txt" ]
stackoverflow_0074416915_python_txt.txt
Q: ValueError: mutable default for field name is not allowed: use default_factory when importing ext.commands I'm using pycord version 2.1.3, on macOS Monterey When I try to from discord.ext import commands, I get the following error message: /Users/montw/dev/gen2/src/bot/ext $ /Users/montw/d ev/gen2/.venv/bin/pytho...
ValueError: mutable default for field name is not allowed: use default_factory when importing ext.commands
I'm using pycord version 2.1.3, on macOS Monterey When I try to from discord.ext import commands, I get the following error message: /Users/montw/dev/gen2/src/bot/ext $ /Users/montw/d ev/gen2/.venv/bin/python -B /Users/montw/dev/gen2/src/bot/ext/core.p y Traceback (most recent call last): File "/Users/montw/dev/gen2/...
[ "This issue will be fixed on the next update, 2.2.3 or something similar. For now it is possible to use the development version.\n" ]
[ 0 ]
[]
[]
[ "discord", "pycord", "python", "python_dataclasses" ]
stackoverflow_0074419508_discord_pycord_python_python_dataclasses.txt
Q: Why Python native on M1 Max is greatly slower than Python on old Intel i5? I just got my new MacBook Pro with M1 Max chip and am setting up Python. I've tried several combinational settings to test speed - now I'm quite confused. First put my questions here: Why python run natively on M1 Max is greatly (~100%) sl...
Why Python native on M1 Max is greatly slower than Python on old Intel i5?
I just got my new MacBook Pro with M1 Max chip and am setting up Python. I've tried several combinational settings to test speed - now I'm quite confused. First put my questions here: Why python run natively on M1 Max is greatly (~100%) slower than on my old MacBook Pro 2016 with Intel i5? On M1 Max, why there isn't s...
[ "Update Mar 28 2022: Please see @AndrejHribernik's comment below.\n\nHow to install numpy on M1 Max, with the most accelerated performance (Apple's vecLib)? Here's the answer as of Dec 6 2021.\n\nSteps\nI. Install miniforge\nSo that your Python is run natively on arm64, not translated via Rosseta.\n\nDownload Minif...
[ 13, 8, 6, 0 ]
[]
[]
[ "anaconda", "apple_m1", "numpy", "python", "tensorflow" ]
stackoverflow_0070240506_anaconda_apple_m1_numpy_python_tensorflow.txt
Q: KafkaError{code=_UNKNOWN_TOPIC,val=-188,str="Unable to produce message: Local: Unknown topic"} error while using kafka producer in Python I am using python script for kafka producer and getting the following error: cimpl.KafkaException: KafkaError{code=\_UNKNOWN_TOPIC,val=-188,str="Unable to produce message: Local...
KafkaError{code=_UNKNOWN_TOPIC,val=-188,str="Unable to produce message: Local: Unknown topic"} error while using kafka producer in Python
I am using python script for kafka producer and getting the following error: cimpl.KafkaException: KafkaError{code=\_UNKNOWN_TOPIC,val=-188,str="Unable to produce message: Local: Unknown topic"} I am getting the following error: cimpl.KafkaException: KafkaError{code=_UNKNOWN_TOPIC,val=-188,str="Unable to produce messa...
[ "Looks like the topic you are producing to does not exist. You can create a topic using the create command. Read more here\n" ]
[ 0 ]
[]
[]
[ "apache_kafka", "confluent_kafka_python", "kafka_producer_api", "python" ]
stackoverflow_0074419931_apache_kafka_confluent_kafka_python_kafka_producer_api_python.txt
Q: FastAPI and Pydantic RecursionError Causing Exception in ASGI application Description I've seen similar issues about self-referencing Pydantic models causing RecursionError: maximum recursion depth exceeded in comparison but as far as I can tell there are no self-referencing models included in the code. I'm just j...
FastAPI and Pydantic RecursionError Causing Exception in ASGI application
Description I've seen similar issues about self-referencing Pydantic models causing RecursionError: maximum recursion depth exceeded in comparison but as far as I can tell there are no self-referencing models included in the code. I'm just just using Pydantic's BaseModel class. The code runs successfully until the func...
[ "This was a simple issue that was resolved by amending the output response to match the pydantic model\n", "ERROR: Exception in ASGI application\nSimply means one or more of the .py files have not been saved before trying to test/run\n", "In my own case, I was referencing a cache key from Redis that hadn't b...
[ 4, 1, 0 ]
[]
[]
[ "fastapi", "pydantic", "python", "uvicorn" ]
stackoverflow_0063830284_fastapi_pydantic_python_uvicorn.txt
Q: How to update records only storing changes? My backend using Python and Flask splits JSON data into various endpoints, to retrieve in my client Swift app rather than having to download the full data client-side. JSON file : { "pilots": [ { "cid": 1234567, "name": "John Smith", "callsign": "...
How to update records only storing changes?
My backend using Python and Flask splits JSON data into various endpoints, to retrieve in my client Swift app rather than having to download the full data client-side. JSON file : { "pilots": [ { "cid": 1234567, "name": "John Smith", "callsign": "TIA1", "server": "USA-WEST", "pilot_r...
[ "You can create a table with columns cid, raw_json_value, json_hash and check hash value before update / insert. Here is an example:\ndata = [{'cid': 1, ...}, {'cid': 2, ...}, {'cid': 3, ...}]\nfor item in data: # type: dict\n cid = item['cid']\n json_hash = hash(json.dumps(data))\n # Record - let's say a...
[ 1 ]
[]
[]
[ "flask", "json", "python", "sqlite" ]
stackoverflow_0074391451_flask_json_python_sqlite.txt
Q: Is there a way to access a python method in another file that is reliant on another method without specifying self? I have some trouble with creating a python class and methods, and I don't know how to resolve it. I have 2 files, 1 file contains a class with multiple methods. 2 of these are: def get_price_of(ticke...
Is there a way to access a python method in another file that is reliant on another method without specifying self?
I have some trouble with creating a python class and methods, and I don't know how to resolve it. I have 2 files, 1 file contains a class with multiple methods. 2 of these are: def get_price_of(ticker: str) -> float: URL = 'https://api.kucoin.com/api/v1/market/orderbook/level1?symbol=' r = requests.get(URL + ti...
[ "Yes. you can use @staticmethod.\nAs I can see in your get_price_of method, there is no need for your instance to be exist. You just pass a ticker and you get a result back. Same thing with get_price_of_list. They are kind of utility functions that happen to be inside the class namespace. You could also define them...
[ 2, 0 ]
[]
[]
[ "class", "methods", "oop", "python" ]
stackoverflow_0074420001_class_methods_oop_python.txt
Q: Create a specific json object from pandas dataframe Suppose I have a dataframe like this t = {'Tract_number': ['01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100'], 'Year': [2019, 2014...
Create a specific json object from pandas dataframe
Suppose I have a dataframe like this t = {'Tract_number': ['01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100', '01001020100'], 'Year': [2019, 2014, 2015, 2016, 2017, 2018, 2011, 2020, 2010, 2009, 2012, 2...
[ "With the dataframe you provided, here is one way to do it with Pandas groupby and MultiIndex.get_level_values, and median function from Python standard library's statistics module:\nimport pandas as pd\nfrom statistics import median\n\ndf = (\n pd.DataFrame(data=t)\n .sort_values([\"Tract_number\", \"Year\"]...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074341981_pandas_python.txt
Q: How to get chrome webdriver selenium path to profile files in python? I need "profile path" from chrome://version/ to download files from this profile. I tried using from selenium.webdriver.common.desired_capabilities import DesiredCapabilities but it only showed {'browserName': 'chrome'} . A: Just navigate to ...
How to get chrome webdriver selenium path to profile files in python?
I need "profile path" from chrome://version/ to download files from this profile. I tried using from selenium.webdriver.common.desired_capabilities import DesiredCapabilities but it only showed {'browserName': 'chrome'} .
[ "Just navigate to that page and retrieve the element you are looking for.\nI will insert a complete code explaining step by step.\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options i...
[ 1 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074419973_python_python_3.x_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: How to put an icon for my android app using kivy-buildozer? I made an android app using python-kivy (Buildozer make it to apk file) Now I want to put an image for the icon of the application. I mean the picture for the app-icon on your phone. how can I do this? I cannot find any code in kv A: Just uncomment ico...
How to put an icon for my android app using kivy-buildozer?
I made an android app using python-kivy (Buildozer make it to apk file) Now I want to put an image for the icon of the application. I mean the picture for the app-icon on your phone. how can I do this? I cannot find any code in kv
[ "Just uncomment icon.filename: in the buildozer spec file and write a path to your icon image.\n", "i presume you are using ubuntu for the build purpose , so u need to define the path as per linux naming convention , ideally keep it in the same path as the app file so that you don't to worry about the whole path....
[ 1, 0 ]
[]
[]
[ "appicon", "buildozer", "kivy", "python" ]
stackoverflow_0060695079_appicon_buildozer_kivy_python.txt
Q: HTML table to json dict with BeautifulSoup Python I have the following HTML data: <table> <tbody> <tr> <th class="left" colspan="7"> <p>Some text</p> </th> </tr> <tr> <td class="left print-wide" colspan="2">  </td> <td class="print-wide" colspan="13">some-text</td> ...
HTML table to json dict with BeautifulSoup Python
I have the following HTML data: <table> <tbody> <tr> <th class="left" colspan="7"> <p>Some text</p> </th> </tr> <tr> <td class="left print-wide" colspan="2">  </td> <td class="print-wide" colspan="13">some-text</td> </tr> <tr> <td class="left"><br /></td> ...
[ "Try:\nheaders = [s.get_text(strip=True) for s in soup.select(\"strong\")]\n\nout = {}\nfor tr in soup.select(\"tr:-soup-contains(month)\"):\n out[tr.td.text] = {k: v.text for k, v in zip(headers, tr.select(\"td\")[1:])}\n\nprint(out)\n\nPrints:\n{\n \"1 month\": {\n \"ABC\": \"3,93%\",\n \"≤25%...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074420065_beautifulsoup_python.txt
Q: Gevent cant be installed on M1 mac using poetry I tried to install many dependencies for a virtual environment using poetry. When it gets to gevent (20.9.0) it gets the following import error: ImportError: dlopen(/private/var/folders/21/wxg5bdsj1w3f3j_9sl_pktbw0000gn/T/pip-build-env-50mwte36/overlay/lib/python3.8...
Gevent cant be installed on M1 mac using poetry
I tried to install many dependencies for a virtual environment using poetry. When it gets to gevent (20.9.0) it gets the following import error: ImportError: dlopen(/private/var/folders/21/wxg5bdsj1w3f3j_9sl_pktbw0000gn/T/pip-build-env-50mwte36/overlay/lib/python3.8/site-packages/_cffi_backend.cpython-38-darwin.so, 0x...
[ "I've have this problem with other libraries also and this solution worked some times:\nsudo arch -arm64 <poetry or pip> install <lib to istall>\n\nUsing arch -arm64 allowed me to install the rigt wheel for the M1 processor\n", "You need to compile it from source.\nhttps://www.gevent.org/development/installing_fr...
[ 4, 1, 0 ]
[]
[]
[ "apple_m1", "gevent", "python", "python_poetry" ]
stackoverflow_0071443345_apple_m1_gevent_python_python_poetry.txt
Q: "eval" statement in Jinja2 template I'm trying to convert some old Smarty templates to Jinja2. Smarty uses an eval statement in the templates to render a templated string from the current context. Is there an eval equivalent in Jinja2 ? Or what is a good workaround for this case ? A: Use the @jinja2.contextfilte...
"eval" statement in Jinja2 template
I'm trying to convert some old Smarty templates to Jinja2. Smarty uses an eval statement in the templates to render a templated string from the current context. Is there an eval equivalent in Jinja2 ? Or what is a good workaround for this case ?
[ "Use the @jinja2.contextfilter decorator to make a Custom Filter for rendering variables:\nfrom jinja2 import contextfilter, Template\nfrom markupsafe import Markup\n\n\n@contextfilter\ndef dangerous_render(context, value):\n return Markup(Template(value).render(context)).render()\n\nThen in your template.html f...
[ 2, 2, 1 ]
[]
[]
[ "jinja2", "python", "smarty" ]
stackoverflow_0047769402_jinja2_python_smarty.txt
Q: Extraction of array list values in pandas dataframe I have a dataframe which looks like this: df= pd.DataFrame({'methods': {0: {'get': 12, 'post': 4, 'put': 1, 'delete': 1, 'patch': 0, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0}, 1: {'get': 13, 'post': 4, 'put': 1, 'delete...
Extraction of array list values in pandas dataframe
I have a dataframe which looks like this: df= pd.DataFrame({'methods': {0: {'get': 12, 'post': 4, 'put': 1, 'delete': 1, 'patch': 0, 'head': 0, 'options': 0, 'trace': 0, 'connect': 0}, 1: {'get': 13, 'post': 4, 'put': 1, 'delete': 1, 'patch': 0, 'head': 0, 'options': 0, 't...
[ "You can try:\ndf = pd.concat([df, df['methods'].agg(pd.Series)], axis=1) \n\nOutput:\nmethods get post put delete patch head options trace connect parameters\n0 {'get': 12, 'post': 4, 'put': 1, 'delete': 1, ... 12.0 4.0 1.0 1.0 0.0 0.0 0.0 0.0 0...
[ 1 ]
[]
[]
[ "arrays", "pandas", "python" ]
stackoverflow_0074420128_arrays_pandas_python.txt
Q: How to do "append if exists" in Python? I am trying to do the following operation. rating = [] for i in result['search_results']: rating.append(float(i['rating']) if i['rating'] exists else 'NaN') The API call sometimes does not return this value. How can I do an append if exists logic in Python...
How to do "append if exists" in Python?
I am trying to do the following operation. rating = [] for i in result['search_results']: rating.append(float(i['rating']) if i['rating'] exists else 'NaN') The API call sometimes does not return this value. How can I do an append if exists logic in Python?
[ "You can use the get method in a dictionary to retrieve a value if it exists and return a default value otherwise.\nrating = []\nfor i in result['search_results']:\n rating.append(float(i.get('rating', math.nan)))\n\n" ]
[ 3 ]
[]
[]
[ "append", "python" ]
stackoverflow_0074420197_append_python.txt
Q: Operational Error when running SQL statements in Python I am trying to run some SQL statements in a Python environment in Visual Studio Code. The database that I am querying is in MySQL Workbench 8.0. My program runs smoothly until it reaches the querying part. It connects to the database fine. Here is my code: fr...
Operational Error when running SQL statements in Python
I am trying to run some SQL statements in a Python environment in Visual Studio Code. The database that I am querying is in MySQL Workbench 8.0. My program runs smoothly until it reaches the querying part. It connects to the database fine. Here is my code: from gettext import install import pymysql con = pymysql.Conne...
[ "The statement in sql_query1\nsql_query1 = 'INSERT INTO ref_info VALUES(1, MuhammadMahd, Ansari, B&W)'\n\nmiss the \" quoting character for string literal; this statement would be sent to your mysql server as\nINSERT INTO ref_info VALUES(1, MuhammadMahd, Ansari, B&W)\n\nin which MuhammadMahd and Ansari and B&W do n...
[ 0 ]
[]
[]
[ "mysql", "operationalerror", "python" ]
stackoverflow_0074418829_mysql_operationalerror_python.txt
Q: How to set a list as a value in a dataframe? I want to insert the GitHub user's monthly activity (data type is list, with different lengths) into cells under columns with corresponding years & months (e.g., 2021_01, 2022_10). The Xpath of these texts is: //*[@id="js-contribution-activity"]/div/div/div/div This i...
How to set a list as a value in a dataframe?
I want to insert the GitHub user's monthly activity (data type is list, with different lengths) into cells under columns with corresponding years & months (e.g., 2021_01, 2022_10). The Xpath of these texts is: //*[@id="js-contribution-activity"]/div/div/div/div This is what my csv file (df1) looks like: LinkedIn...
[ "You get this message because you are trying to set a value at a specific index and column, but you pass a list of values.\nIf your intention is to use the list itself as a value, then:\n\nreplace df1.loc[index, f'{str(y)}_{str(m)}'] = list_cont\nwith df1.loc[index, f\"{str(y)}_{str(m)}\"] = str(list_cont)\n\nThen:...
[ 1 ]
[]
[]
[ "pandas", "python", "selenium_webdriver" ]
stackoverflow_0074340045_pandas_python_selenium_webdriver.txt
Q: discord.py bot not responding in channel text My python chat bot connect to the discord server and when a user DM the bot it replay fine, but it only works in DMS. As you see in the code it should respond when someone type "hi", but when someone types "hi" in the text channel, it doesn't reply. i gave the bot admi...
discord.py bot not responding in channel text
My python chat bot connect to the discord server and when a user DM the bot it replay fine, but it only works in DMS. As you see in the code it should respond when someone type "hi", but when someone types "hi" in the text channel, it doesn't reply. i gave the bot administrator permissions this is my code : # IMPORT DI...
[ "The problem is you are trying to use both the client syntax and bot syntax in the same code. You have to choose either one.\nYou can use one of these 2:\n\nClient syntax (Old)\n import discord\n\n intents = discord.Intents.default()\n intents.message_content = True\n client = discord.Client(intents = intents)\n\n ...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python", "python_3.x" ]
stackoverflow_0074420019_discord_discord.py_python_python_3.x.txt
Q: What's the canonical approach to creating multiple producers and consumers with coroutines in python asyncio? I am trying to understand Python asyncio. I have something that I think works but I don't think it's a canonical approach to coroutine programming. I essentially want to create arbitrary graphs of processi...
What's the canonical approach to creating multiple producers and consumers with coroutines in python asyncio?
I am trying to understand Python asyncio. I have something that I think works but I don't think it's a canonical approach to coroutine programming. I essentially want to create arbitrary graphs of processing such as the following: How do I create a coroutine that can receive data from multiple coroutines? Is it asend?...
[ "I think you can look at asyncio.Queue how to distribute the workload between producers-consumers.\nThis example will create 5 producers and 3 consumers, connected by queue:\nimport random\nimport asyncio\n\n\nasync def producer(n, q):\n for i in range(3):\n await asyncio.sleep(random.randint(1, 5))\n ...
[ 0 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074420108_python_python_asyncio.txt
Q: Python - how to return from n dimensional function a 1 dimensional function? - answered I’m trying to create a function that receives n variables and returns the same function with one veritable. my intention is to make a multi-dimentional search within a function in order to find its max point. lets say i have a ...
Python - how to return from n dimensional function a 1 dimensional function? - answered
I’m trying to create a function that receives n variables and returns the same function with one veritable. my intention is to make a multi-dimentional search within a function in order to find its max point. lets say i have a function: f(x1,x2,x3) = x1x2+4x3 my first phase of the algorithem will be to randomly choose ...
[ "I tried to understand your intent rather than your very confused and confusing example. Here's what I wrote:\ndef flatten(func, *args):\n def inner(x):\n return func(x,*args[1:])\n return inner\n\nExample 1\ndef f(x,y,z):\n return x+y+z\n\nf2 = flatten(f,1,2,3)\nprint(f2(10))\n\n# 15\n\nExample 2\n...
[ 0 ]
[]
[]
[ "function", "optimization", "python" ]
stackoverflow_0074420052_function_optimization_python.txt
Q: It sometimes reverse when I turn a string into a set The string is: x = 'ABBA' whenever I use this code: x = 'ABBA' x = ''.join(set(x)) print(x) It results in: BA but I want it to be the first letters instead of the second letters: AB Is there any way that I can do it without using reverse function? A: Sets are ...
It sometimes reverse when I turn a string into a set
The string is: x = 'ABBA' whenever I use this code: x = 'ABBA' x = ''.join(set(x)) print(x) It results in: BA but I want it to be the first letters instead of the second letters: AB Is there any way that I can do it without using reverse function?
[ "Sets are unordered. so try this.\n\nfrom collections import Counter\n\n\nx = 'ABBA'\n\nx = \"\".join(Counter(x).keys())\n\nprint(x) # AB\n\n\n", "Sets in Python are still unordered unfortunately. However, dictionaries in newer versions of Python already preserve insertion order.\nYou can take advantage of this, ...
[ 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0074420233_python_set.txt
Q: How to scrape amazon rating values in pyhton selenium I trying to get the rating values from amazon site I applied every method but unable to get the rating values. one more thing to consider that this ratings don't have any hyperlinks. for item in WebDriverWait(driver, 20).until(EC.presence_of_all_elements_locat...
How to scrape amazon rating values in pyhton selenium
I trying to get the rating values from amazon site I applied every method but unable to get the rating values. one more thing to consider that this ratings don't have any hyperlinks. for item in WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "[data-hook='review']"))): try: ...
[ "Instead of .text, you can use alternatively .get_attribute() to get the text content from a HTMl element. The following code worked for me:\nfrom selenium.webdriver.common.by import By\n lst_of_ratings = driver.find_elements(By.CLASS_NAME, \"review-rating\")\n for value in lst_of_ratings:\n rating = v...
[ 0, 0 ]
[]
[]
[ "amazon", "python", "selenium_webdriver", "web_scraping", "webdriver" ]
stackoverflow_0073496872_amazon_python_selenium_webdriver_web_scraping_webdriver.txt
Q: Selenium hangs at driver.get() only for one website I've been facing this issue for quite some time now and since I'm a novice in webscraping I cannot seem to find an answer. I want to scrape some websites I pass from a list. My Chrome driver works all of them but one: https://www.studentbeans.com/student-discount...
Selenium hangs at driver.get() only for one website
I've been facing this issue for quite some time now and since I'm a novice in webscraping I cannot seem to find an answer. I want to scrape some websites I pass from a list. My Chrome driver works all of them but one: https://www.studentbeans.com/student-discount/it/cats. The driver gets stuck already at the driver.get...
[ "Everything works well. Here's the code I've executed:\nfrom selenium import webdriver\n\n\ndriver = webdriver.Chrome()\ndriver.get('https://www.studentbeans.com/student-discount/it/cats')\n\nHere's the result I've got:\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074413165_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt
Q: Is there a way to run an exe inside --onfile python I created an main.py Where the code is on.system('program.exe') And I compiled it with auto-py-to-exe as one file added the program.exe as add files when I execute it says program.exe is not recognized as internal or external error lease help thank you The probl...
Is there a way to run an exe inside --onfile python
I created an main.py Where the code is on.system('program.exe') And I compiled it with auto-py-to-exe as one file added the program.exe as add files when I execute it says program.exe is not recognized as internal or external error lease help thank you The problem is too complex for me please help
[ "You are not supplying a ton of context but I am pretty sure this is because your compiled Python script cannot find program.exe. And this is probably because the \"current working directory\" is not the one containing program.exe. An easy solution would be to specify the complete path like C:\\path\\to\\program.ex...
[ 0 ]
[]
[]
[ "auto_py_to_exe", "pyinstaller", "python" ]
stackoverflow_0074419306_auto_py_to_exe_pyinstaller_python.txt
Q: Discord.py commands wont run when used under @client.command() i am attempting to use discord.ext commands to make my commands neater but the commands will not run imports and intents: import discord from dotenv import load_dotenv import requests from discord.ext import commands from discord.ext.commands import B...
Discord.py commands wont run when used under @client.command()
i am attempting to use discord.ext commands to make my commands neater but the commands will not run imports and intents: import discord from dotenv import load_dotenv import requests from discord.ext import commands from discord.ext.commands import Bot load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') #Delcare import...
[ "Try only using bot and not client:\nimport discord\nfrom dotenv import load_dotenv\nimport requests\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\n\nload_dotenv()\n\nTOKEN = os.getenv('DISCORD_TOKEN')\n\nintents = discord.Intents().all() \nbot = commands.Bot(command_prefix='$', intents=in...
[ 1 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074419438_discord.py_python.txt
Q: Django EmailBackend ConnectionRefusedError from app on PythonAnywhere My password reset feature was working fine in development, sending a password reset email, but now that I have deployed to PythonAnywhere, I am getting a ConnectionRefusedError, specifically: ConnectionRefusedError at /reset_password [Errno 111...
Django EmailBackend ConnectionRefusedError from app on PythonAnywhere
My password reset feature was working fine in development, sending a password reset email, but now that I have deployed to PythonAnywhere, I am getting a ConnectionRefusedError, specifically: ConnectionRefusedError at /reset_password [Errno 111] Connection refused Request Method: POST Django Version: 4.1 Exception Typ...
[ "Free accounts cannot send smtp email from PythonAnywhere\n" ]
[ 1 ]
[]
[]
[ "django", "python", "pythonanywhere", "reset_password" ]
stackoverflow_0074414851_django_python_pythonanywhere_reset_password.txt
Q: Mapping wordcloud color to a value for sentiment analysis So I'm looking to see if there is a way to map the color of a word cloud to a value, or maybe even overlap two word clouds (one positive and one negative list) with the end result being a dark color for negative sentiment and a bright color for a positive s...
Mapping wordcloud color to a value for sentiment analysis
So I'm looking to see if there is a way to map the color of a word cloud to a value, or maybe even overlap two word clouds (one positive and one negative list) with the end result being a dark color for negative sentiment and a bright color for a positive sentiment like in the picture only this is random. I'm not sure...
[ "I know this was asked a while back - and may no longer be relevant. \nHowever, if someone is looking to achieve the same thing, then this is the way to do it.\n\nAssuming you have a\n\nlist of words (word),\ntheir sentiment (score),\nand their frequency (freq)\n\nin a dataframe like this:\nimport pandas as pd\n\n#...
[ 1 ]
[]
[]
[ "colormap", "colors", "python", "word_cloud" ]
stackoverflow_0061919884_colormap_colors_python_word_cloud.txt