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: How to get the values of instances using classes? i'am new into classes in python. And i'am running into an error, so i wanted to calculate the distance between two coordinates. But i'am struggling to get the values x and y values from p1 and p2 or p2 and p3,... And to use theses values in a method for calculate t...
How to get the values of instances using classes?
i'am new into classes in python. And i'am running into an error, so i wanted to calculate the distance between two coordinates. But i'am struggling to get the values x and y values from p1 and p2 or p2 and p3,... And to use theses values in a method for calculate the distance between the 2 given coordinates. import mat...
[ "You have to pass the second point as an argument to the distance method. Then you can access the x and y attributes of the two points self and other.\ndef distance(self, other):\n dist = math.sqrt( (other.x - self.x)**2 + (other.y - self.y)**2 )\n return dist\n\n\nprint(p1.distance()) # Error, missing arg...
[ 1 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0074193982_class_methods_python.txt
Q: QComboBox adjust drop down width Not sure why I cant get it to work, so maybe one of you will be able to see my mistake... : combo_type = QComboBox() combo_type.setMaximumWidth(50) combo_type.addItems(["TEsst1111","TEsst11111111111111","TEsst1111111111111111111111111"]) combo_type.setStyleSheet('''* QComboBox ...
QComboBox adjust drop down width
Not sure why I cant get it to work, so maybe one of you will be able to see my mistake... : combo_type = QComboBox() combo_type.setMaximumWidth(50) combo_type.addItems(["TEsst1111","TEsst11111111111111","TEsst1111111111111111111111111"]) combo_type.setStyleSheet('''* QComboBox QAbstractItemView::item { min-...
[ "Sorted... it was naming error. Correct answer posted below.\ncombo_type.setStyleSheet('''* \nQComboBox QAbstractItemView \n {\n min-width: 150px;\n }\n''')\n\n", "Using the QListView:\ncombo_type = QComboBox()\ncombo_type.SizeAdjustPolicy(QComboBox.AdjustToContentsOnFirstShow)\n\nview = QListView() ...
[ 4, 1, 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qcombobox" ]
stackoverflow_0037632845_pyqt_pyqt4_python_qcombobox.txt
Q: How to efficiently generate an array using 2 arrays and a formula as input with NumPy I have two arrays, x and t with n elements (t's elements are in strict ascending order, so no dividing by 0) and a formula on which the creation of my new array, v is based: v[i] = (x[i+1] - x[i]) / (t[i+1] - t[i]) How can I wri...
How to efficiently generate an array using 2 arrays and a formula as input with NumPy
I have two arrays, x and t with n elements (t's elements are in strict ascending order, so no dividing by 0) and a formula on which the creation of my new array, v is based: v[i] = (x[i+1] - x[i]) / (t[i+1] - t[i]) How can I write this in NumPy? I tried using numpy.fromfunction but didn't manage to make it work. I did...
[ "You can use np.diff():\ndef gen_v(x,t):\n return np.diff(x)/np.diff(t)\n\nThe benchmark give us:\n# Your function:\n8.45 ms +- 557 us per loop (mean +- std. dev. of 7 runs, 100 loops each)\n# My function:\n63.4 us +- 1.62 us per loop (mean +- std. dev. of 7 runs, 10000 loops each)\n\n", "You could use array s...
[ 2, 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074193950_arrays_numpy_python.txt
Q: Compressed Sqlite database and indexing I read that it is possible to compress sqlite databases with extensions like sqlite-zstd. In Sqlite3, are there methods, ready to use in Python, that allow both: compression of a text column (let's say 1 billion of rows, with at least one text column of < 20 characters) kee...
Compressed Sqlite database and indexing
I read that it is possible to compress sqlite databases with extensions like sqlite-zstd. In Sqlite3, are there methods, ready to use in Python, that allow both: compression of a text column (let's say 1 billion of rows, with at least one text column of < 20 characters) keep the fast lookup that we have when this colu...
[ "SQLITE doesn't compress it's data bydefault, but they do have some Proprietary SQLite Extensions that can do the required work.\nZIPVFS is one such extension/addon that can allow you to read and write the compressed data using zlib or any other application-supplied compression and decompression functions.\n", "S...
[ 0, 0 ]
[]
[]
[ "compression", "database", "full_text_search", "python", "sqlite" ]
stackoverflow_0074078555_compression_database_full_text_search_python_sqlite.txt
Q: django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed') I'm new to python and django. When I run python manage.py runserver I get this error: django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed')' mysql Server version: 8.0.13 MySQL Community...
django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed')
I'm new to python and django. When I run python manage.py runserver I get this error: django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed')' mysql Server version: 8.0.13 MySQL Community Server - GPL. I can't find this error on the web.
[ "I had this issue too when installing from Anaconda, but I could work around it using the \"use_pure=True\" mysql.connector.connect() parameter.\n", "I ran into the same error when I tried to connect to MySQL to Python (in Anaconda). \nThis feed is particularly helpful for various case scenarios leading to the sa...
[ 6, 5, 0, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0053385113_django_mysql_python.txt
Q: How to create a vector of indexes with numpy.where I have a vector, and i want to create a new one with indexes of positions where it follows sign change. I have to use numpy.where() , and i don't know how to create the condtion for sign change, to acces an element and the next one. Example: for v = [1, 2, -1, 2,...
How to create a vector of indexes with numpy.where
I have a vector, and i want to create a new one with indexes of positions where it follows sign change. I have to use numpy.where() , and i don't know how to create the condtion for sign change, to acces an element and the next one. Example: for v = [1, 2, -1, 2, 3, -1, 3, -10, -10, -10] return [1, 2, 4, 5, 6]
[ "Use a combination of numpy.diff and numpy.sign\na = np.array([1, 2, -1, 2, 3, -1, 3, -10, -10, -10])\nnp.where(np.diff(np.sign(a)))[0].tolist()\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074194044_python.txt
Q: Log everything from every module except one third party module I have a main.py: import logging, sys logging.basicConfig( level=logging.DEBUG, handlers=[logging.FileHandler("test.log"), logging.StreamHandler(sys.stdout)] ) # log everything to file and stdout logger = logging.getLogger("main") logger.info...
Log everything from every module except one third party module
I have a main.py: import logging, sys logging.basicConfig( level=logging.DEBUG, handlers=[logging.FileHandler("test.log"), logging.StreamHandler(sys.stdout)] ) # log everything to file and stdout logger = logging.getLogger("main") logger.info("hello main!") import thirdparty_module thirdpary_module.foo() im...
[ "If the example is correct, then you can get thirdparty.logger. Logger objects have propagate attribute - this sets whether logs propagate to the upper loggers and their handlers. By default it's set to True, just switch it to False:\n# main.py\n...\nimport thirdparty_module\nthirdparty_module.logger.propagate = Fa...
[ 2 ]
[]
[]
[ "logging", "python", "python_logging" ]
stackoverflow_0074193984_logging_python_python_logging.txt
Q: Selenium driver.get is slow I try to connect to a web page www.wooclap.com/EPUUJK. Its a website for create event and ask questions. At the bottom of the page we can see the users connected. from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument(...
Selenium driver.get is slow
I try to connect to a web page www.wooclap.com/EPUUJK. Its a website for create event and ask questions. At the bottom of the page we can see the users connected. from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('-no-sandbox') options.add_argume...
[ "Trying disabling the image like this:\nprefs = {\"profile.managed_default_content_settings.images\": 2}\noptions.add_experimental_option(\"prefs\", prefs)\n\nDisabling gpu:\noptions.add_argument('--disable-gpu')\n\nDisabling extensions:\nchrome_options.add_argument(\"--disable-extensions\")\n\nIf this doesn't work...
[ 1 ]
[]
[]
[ "python", "selenium", "web_scraping" ]
stackoverflow_0074193782_python_selenium_web_scraping.txt
Q: Create new dictionary based on user input for values in Python I have the following dict: dict_ = {'one':['a','b','c','d'], 'two':['e','f','g'], 'three':['x']} For the keys that have more than one value, I want to prompt the user to pick one from the list of values and remove the others from the list. What I have...
Create new dictionary based on user input for values in Python
I have the following dict: dict_ = {'one':['a','b','c','d'], 'two':['e','f','g'], 'three':['x']} For the keys that have more than one value, I want to prompt the user to pick one from the list of values and remove the others from the list. What I have attempted is: dupl_dict = {} for k, v in dict_.items(): if len(v)...
[ "Here is my solution to the problem:\n\nI use dict_.update() to update the dictionary with the user response.\nI also check to make sure that they type in a valid response.\n\ndict_ = {'one':['a','b','c','d'],\n 'two':['e','f','g'],\n 'three':['x']}\n\n\nfor k, v in dict_.items():\n valid_respons...
[ 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074193922_dictionary_list_python.txt
Q: How to get plotly.express.timeline overlapped bars to be visible I'd like to know if anyone has a solution to overlapping timeline bars? import plotly.express as px import pandas as pd df = pd.DataFrame([ dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"), dict(Task="Job B", Star...
How to get plotly.express.timeline overlapped bars to be visible
I'd like to know if anyone has a solution to overlapping timeline bars? import plotly.express as px import pandas as pd df = pd.DataFrame([ dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"), dict(Task="Job B", Start='2009-02-25', Finish='2009-04-15', Resource="Alex"), dict(Task="...
[ "The best that I was able to figure out was using different colors for all of the \"Tasks\" or \"Jobs\", and having to opacity lower so that it was possible to see the traces/bars that were getting covered\nThe code looks like:\nimport plotly.express as px\nimport pandas as pd\n\ndf = pd.DataFrame([\n dict(Task=...
[ 2, 2, 0 ]
[]
[]
[ "plotly", "python", "timeline" ]
stackoverflow_0067129085_plotly_python_timeline.txt
Q: Google BigQuery Batch Query - job state is not updating after the job finished I run a google BigQuery batch query in a python script in jupyter notebook. Usually, the query takes about an hour when running in interactive mode. Today in the morning I checked and the script still displays the job is in state RUNNIN...
Google BigQuery Batch Query - job state is not updating after the job finished
I run a google BigQuery batch query in a python script in jupyter notebook. Usually, the query takes about an hour when running in interactive mode. Today in the morning I checked and the script still displays the job is in state RUNNING - after 16 hours. So I checked the INFORMATION_SCHEMA.JOBS and there it says that ...
[ "You are not updating the job in the while loop. Add a client.get_job inside the loop to get an updated state and it should work:\nwhile(query_job.state != 'DONE'):\n time.sleep(60)\n query_job = client.get_job(\n query_job.job_id, location=query_job.location\n ) \n\n", "Adding to @Ingar Pedersen'...
[ 1, 1 ]
[]
[]
[ "google_bigquery", "information_schema", "jobs", "python" ]
stackoverflow_0074004343_google_bigquery_information_schema_jobs_python.txt
Q: Convert grouped by df to a dict with a list of dicts I've the following df: timestamp min max count 0 2022-10-23 22:00:00+00:00 1.000000e+09 9.000000e+99 0 1 2022-10-23 22:00:00+00:00 1.000000e+08 1.000000e+09 2 2 2022-10-23 22:00:00+00:00 1.000000e+07 1.00000...
Convert grouped by df to a dict with a list of dicts
I've the following df: timestamp min max count 0 2022-10-23 22:00:00+00:00 1.000000e+09 9.000000e+99 0 1 2022-10-23 22:00:00+00:00 1.000000e+08 1.000000e+09 2 2 2022-10-23 22:00:00+00:00 1.000000e+07 1.000000e+08 39 3 2022-10-23 22:00:00+00:00 1.000000e+06 1....
[ "You can use a dictionary comprehension with to_dict:\nitems = {k: g.to_dict('records') for k,g in\n df.set_index('timestamp').groupby('timestamp')}\n\noutput:\n{'2022-10-23 22:00:00+00:00': [{'min': 1000000000.0, 'max': 9e+99, 'count': 0},\n {'min': 100000000.0, 'max': 1000000...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074194187_pandas_python.txt
Q: How do I get Selenium Button Click to work? I'm a complete beginner, I have a website in which I want to click a button through python selenium, I've tried a lot of things, but I can't get it to work. import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.w...
How do I get Selenium Button Click to work?
I'm a complete beginner, I have a website in which I want to click a button through python selenium, I've tried a lot of things, but I can't get it to work. import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdri...
[ "You have a syntax error inside the XPath expression.\nAlso, you need to scroll the page down and switch to the iframe block since that button is inside an iframe.\nThe following code works\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074194075_python_selenium_selenium_chromedriver_selenium_webdriver_webdriverwait.txt
Q: AttributeError: 'NoneType' object has no attribute 'get_text' in the line 9 from bs4 import BeautifulSoup import requests response = requests.get(url="https://news.ycombinator.com/") page = response.text this is a code for webscraping.when I run it, it gives me an error in this line print(soup_title.get_text())....
AttributeError: 'NoneType' object has no attribute 'get_text' in the line 9
from bs4 import BeautifulSoup import requests response = requests.get(url="https://news.ycombinator.com/") page = response.text this is a code for webscraping.when I run it, it gives me an error in this line print(soup_title.get_text()). my mentor typed the same code but did not got an error why. soup = BeautifulSoup...
[ "To print all the titles you can use this:\ntitles = soup.find_all(name=\"span\", class_=\"titleline\")\nfor title in titles:\n print(title.findChildren(\"a\")[0].text)\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x", "python_requests", "web_scraping" ]
stackoverflow_0074188784_beautifulsoup_python_python_3.x_python_requests_web_scraping.txt
Q: Tagged Duplicate Entries After user submits the form Django can someone help me figure out... I would want to automatically trigger in database if the entries that was posted by a different user is a possible duplicate. if entries like date, time and location are the same... how can I do this? Thank you So far I h...
Tagged Duplicate Entries After user submits the form Django
can someone help me figure out... I would want to automatically trigger in database if the entries that was posted by a different user is a possible duplicate. if entries like date, time and location are the same... how can I do this? Thank you So far I have below code, where can I insert possible duplicate in the data...
[ "In your models.py you can add unique together\nclass UserReport(models.Model):\n class Meta:\n unique_together = ('date','time','geo_location')\n\nthen migrate. This will restrict duplication.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074191510_django_python.txt
Q: How to append client names to listbox? I have a listbox that, when server accepts a connection, should display the names of the clients. The server code is as follows: class GUI2(GUI): #server GUI def __init__(self): self.clientlist = tk.Listbox(self.clientframe) #listbox that should display client ...
How to append client names to listbox?
I have a listbox that, when server accepts a connection, should display the names of the clients. The server code is as follows: class GUI2(GUI): #server GUI def __init__(self): self.clientlist = tk.Listbox(self.clientframe) #listbox that should display client names self.clientlist.pack(expand = ...
[ "Thanks to @acw1668 I was guided to the answer: I just needed to remove the INITSERVER class and move all of its functions and attributes to GUI2 class, then use Threading instead of Process to target startChat to bypass Tkinter pickle errors. The new code is as follows:\nclass GUI2(GUI): #server GUI\n\n def __i...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074145366_python_tkinter.txt
Q: Read from two different forms in Flask In my page I have two different forms. I want to read the information from the first form whenever I press a button in the second form. Is this possible? First form: <form id="loadData" method="post" action="/loadData"> {% if day %} Day: <input id="day" name="day"...
Read from two different forms in Flask
In my page I have two different forms. I want to read the information from the first form whenever I press a button in the second form. Is this possible? First form: <form id="loadData" method="post" action="/loadData"> {% if day %} Day: <input id="day" name="day" size="5px" value={{day}}> Month: <i...
[ "Despite corresponding in the comments i'm not entirely sure this is your end goal, but let's give it a go?\nbasically all i did was copy stuff from the links attached in the comment.\na.html:\n<form id=\"form_id\" action=\"/loadData\" method=\"POST\">\n <input type=\"text\" name=\"q\" value=\"abcd\">\n <butt...
[ 0 ]
[]
[]
[ "flask", "html", "python" ]
stackoverflow_0074192438_flask_html_python.txt
Q: How to read multiple DICOM files from a folder? I have the following code in which I am loading a single DICOM file and checking if there are sagittal and coronal view present or not. I want to modify this to read all DICOM files from the folder. print there is no sagittal and coronal view if sag_aspect,cor_aspec...
How to read multiple DICOM files from a folder?
I have the following code in which I am loading a single DICOM file and checking if there are sagittal and coronal view present or not. I want to modify this to read all DICOM files from the folder. print there is no sagittal and coronal view if sag_aspect,cor_aspect value is zero How do I do this? import pydicom imp...
[ "For reading multiple dicom files from a folder you can use the code below.\nimport os\nfrom pathlib import Path\nimport pydicom\n\ndir_path = r\"path\\to\\dicom\\files\"\n\ndicom_set = []\nfor root, _, filenames in os.walk(dir_path):\n for filename in filenames:\n dcm_path = Path(root, filename)\n ...
[ 0 ]
[]
[]
[ "numpy", "pydicom", "python", "python_3.x" ]
stackoverflow_0074190157_numpy_pydicom_python_python_3.x.txt
Q: Check and compare if first 3 row value of dataframe for each day is greater than the value on corresponding column I have a 5-minute time series dataframe with the titles Open and Pivot. The Pivot column value is the same throughout the day. I need to extract the first three 5-minute Open data and compare each of ...
Check and compare if first 3 row value of dataframe for each day is greater than the value on corresponding column
I have a 5-minute time series dataframe with the titles Open and Pivot. The Pivot column value is the same throughout the day. I need to extract the first three 5-minute Open data and compare each of the values to the value on the pivot column and see if it is larger or not. If it is larger, then a 3rd column titled 'R...
[ "Here's a basic solution:\ndf_s = df.reset_index()\ndf_s['result'] = 0 \n\nstart_day = -1\n\nfor i in range(len(df_s)):\n if df_s['Datetime'][i].day != start_day :\n start_day = df_s['Datetime'][i].day\n res = np.all(df_s['Open'][i:i+3] > df_s['pivot'][i])\n \n df_s['result'][i] = res\n\nSinc...
[ 2 ]
[]
[]
[ "dataframe", "iteration", "pandas", "python" ]
stackoverflow_0074185841_dataframe_iteration_pandas_python.txt
Q: Trying to skip empty tags beautifulsoup AttributeError: 'NoneType' object has no attribute 'text' I'm trying to read a page with python and print each element for the ratings. I've got a AttributeError: 'NoneType' object has no attribute 'text' error and I don't understand how to fix it. Here is my code: rating = ...
Trying to skip empty tags beautifulsoup AttributeError: 'NoneType' object has no attribute 'text'
I'm trying to read a page with python and print each element for the ratings. I've got a AttributeError: 'NoneType' object has no attribute 'text' error and I don't understand how to fix it. Here is my code: rating = movie.find('td', class_='ratingColumn imdbRating').strong.text if rating: try: print(rating...
[ "Simply check None Type as below:\nrating = movie.find('td', class_=\"ratingColumn imdbRating\").strong\n\nif rating is not None:\n rating = rating.text\nelse:\n rating = \"No Rating\"\n\n", "You can simply check for \"NoneType\" before printing .text\nrating = movie.find('td', class_='ratingColumn imdbRati...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0072356733_beautifulsoup_html_python.txt
Q: counting 1's in a bit string to keep positions in a variable and then accessing each value I am finding 1's in a bit string and then storing them. Sample Data: Sample code: def indices(chromosome): return {i for i,c in enumerate(chromosome) if c=='1'} for ind in df_initial_pop['initial_pop'].index: loca...
counting 1's in a bit string to keep positions in a variable and then accessing each value
I am finding 1's in a bit string and then storing them. Sample Data: Sample code: def indices(chromosome): return {i for i,c in enumerate(chromosome) if c=='1'} for ind in df_initial_pop['initial_pop'].index: locations = indices(df_initial_pop['initial_pop'] [ind]) print (locations) Output: {32, 29, 31...
[ "Sure it is possible, but using individual variables implies that the number of elements in your set is fixed.\ns = {32, 29, 31}\na,b,c = s\n# Now a=32, b=29, c=31\n\n" ]
[ 3 ]
[]
[]
[ "bit_manipulation", "dataframe", "genetic_algorithm", "genetic_programming", "python" ]
stackoverflow_0074194060_bit_manipulation_dataframe_genetic_algorithm_genetic_programming_python.txt
Q: Python game of life generates wrong structures I'm trying to program the game of Life in python. I keep getting the wrong structure generated after generation and pinpointed my mistake to the fuction bellow. What I want the program to do: It should iterate through an array to determine if the cell is going to be a...
Python game of life generates wrong structures
I'm trying to program the game of Life in python. I keep getting the wrong structure generated after generation and pinpointed my mistake to the fuction bellow. What I want the program to do: It should iterate through an array to determine if the cell is going to be alive or dead in next generation and places them in a...
[ "The problem was as @user2357112 suggested that cells = matrice doesn't make a copy.\nTo fix that I needed to change it to cells = np.copy(matrice) .\n" ]
[ 1 ]
[]
[]
[ "conways_game_of_life", "python" ]
stackoverflow_0074194250_conways_game_of_life_python.txt
Q: OSError: Unable to create file (unable to open file: name = , errno = 13, error message = 'Permission denied', flags = 13, o_flags = 302) I don't understand what I'm missing... I use Tensorflow-gpu 2.0.0, Keras-gpu 2.3.1, numpy 1.16.6, h5py 2.9.0, python 3.7.9. This is how I try to save my model: model_just_name =...
OSError: Unable to create file (unable to open file: name = , errno = 13, error message = 'Permission denied', flags = 13, o_flags = 302)
I don't understand what I'm missing... I use Tensorflow-gpu 2.0.0, Keras-gpu 2.3.1, numpy 1.16.6, h5py 2.9.0, python 3.7.9. This is how I try to save my model: model_just_name = 'LSTM_FA_SpGyZ_out1_6d_dno_seq_b_p_tmm' filepath = r'D:\test_data_pros\restructured' model.save(model_just_name + "model.h5", file...
[ "Ask administrator to give you access to \"D:\\test_data_pros\\restructured\"\n", "if the path is a folder then it may not work. Try to give some file name.\n" ]
[ 0, 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0065391733_keras_python_tensorflow.txt
Q: Wrong indexing of a string (Python) Something that should be very simple and yet I am not able to solve it. The indexing does not appear correctly when a character duplicates: For example: list=[] stringg="BAtmAn" for i in stringg: if i.isupper(): list.append(stringg.index(i)) print(list) And the outp...
Wrong indexing of a string (Python)
Something that should be very simple and yet I am not able to solve it. The indexing does not appear correctly when a character duplicates: For example: list=[] stringg="BAtmAn" for i in stringg: if i.isupper(): list.append(stringg.index(i)) print(list) And the output shows [0,1,1] instead of [0,1,4]. When...
[ "The following would do what you want\nstringg=\"BAtmAn\"\nprint([x for x in range(len(stringg)) if stringg[x].isupper()])\nprint([i for i, c in enumerate(stringg) if c.isupper()])\n\n", "list=[]\nstringg=\"BAtmAn\"\nfor i in range(len(stringg)):\n if stringg[i].isupper():\n list.append(i)\nprint(list)\...
[ 1, 0 ]
[]
[]
[ "for_loop", "indexing", "list", "python", "string" ]
stackoverflow_0074194115_for_loop_indexing_list_python_string.txt
Q: Duplicate/multiply rows in Dataframe if contain a certain condition/string Please see the following dataframe. import pandas as pd data = [['PMO', 10], ['LOL', 15], ['juli', 14], ['PMO', 10], ['LOL', 15], ['juli', 14]] df = pd.DataFrame(data, columns=['Name', 'Age']) print(df) I would like to iterate through th...
Duplicate/multiply rows in Dataframe if contain a certain condition/string
Please see the following dataframe. import pandas as pd data = [['PMO', 10], ['LOL', 15], ['juli', 14], ['PMO', 10], ['LOL', 15], ['juli', 14]] df = pd.DataFrame(data, columns=['Name', 'Age']) print(df) I would like to iterate through this illustrative dataframe and copy/multiply the rows so that if a row contains, ...
[ "Here is a small trick, check if Name equals PMO to get a boolean Series and add 1 to transform to an integer Series of 1/2. Use this to repeat the index:\nout = df.loc[df.index.repeat(df['Name'].eq('PMO').add(1))]\n\nFor a more classical way, use concat:\nout = pd.concat([df, df.loc[df['Name'].eq('PMO')]]).sort_in...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074194407_dataframe_pandas_python.txt
Q: 'Posts_update' object is not iterable in django i am just try to get data from db table and show on detail page but i am getting error -'Posts_update' object is not iterable. I have two tables posts and posts_update. in posts table i am doing CRUD operation and on each update i am adding information in posts_updat...
'Posts_update' object is not iterable in django
i am just try to get data from db table and show on detail page but i am getting error -'Posts_update' object is not iterable. I have two tables posts and posts_update. in posts table i am doing CRUD operation and on each update i am adding information in posts_update table now i am trying to get information from posts...
[ "In detail.html you are iterating over context object Posts_update\n{% for post in Posts_update %}\nWhich is just Posts_update model, due to views.py.\nI guess you meant the post variable there.\n" ]
[ 0 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0074193911_django_orm_python.txt
Q: Unable to reach json data element I have following script for stock data... import pandas as pd import requests import json baseurl = "https://www.nseindia.com/" url = f'https://www.nseindia.com/api/quote-derivative?symbol=ACC' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.3...
Unable to reach json data element
I have following script for stock data... import pandas as pd import requests import json baseurl = "https://www.nseindia.com/" url = f'https://www.nseindia.com/api/quote-derivative?symbol=ACC' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, ''like Gecko) ''Chrome/80.0.3...
[ "I am new to coding myself, but I got all the values out and put them in a dictionary with keys 'totalBuyQuantity', 'totalSellQuantity'. I think because the json is nested, you have to write a recursive function.\nIf there is a more simple solution I would also be happy to know (maybe I am still thinking to complex...
[ 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074193799_json_python.txt
Q: Find max of each column and its index with numpy (+ when max is duplicate in the same col) I have the following 2D numpy array: >>> A = ([[ 100, -5, 3, 200], [ 20, -100, 4, 8], [ 12, -10, 10, 4], [-100, 80, 4, 14]]) >>> A = np.array(A) I want to find the absol...
Find max of each column and its index with numpy (+ when max is duplicate in the same col)
I have the following 2D numpy array: >>> A = ([[ 100, -5, 3, 200], [ 20, -100, 4, 8], [ 12, -10, 10, 4], [-100, 80, 4, 14]]) >>> A = np.array(A) I want to find the absolute max value of each column and its index. For the absolute max I use: >>> max_col = abs(A).max...
[ "Yes, use numpy.where:\n# max_col = abs(A).max(axis=0)\nnp.where(abs(A) == max_col)\n\noutput: (array([0, 0, 1, 2, 3]), array([0, 3, 1, 2, 0]))\nIf you only want the column indices:\nnp.where(abs(A) == max_col)[1]\n\noutput: array([0, 3, 1, 2, 0])\n" ]
[ 2 ]
[]
[]
[ "indexing", "max", "numpy", "python" ]
stackoverflow_0074194495_indexing_max_numpy_python.txt
Q: Custom User Model, Custom Authentication not working I am a beginner in Django and I am working on a project which requires Custom user model as I Don't require is_staff, is_superuser, is_admin. So, but searching and other ways I made my own Custom user model. But it is not working and I am stuck on it for days. I...
Custom User Model, Custom Authentication not working
I am a beginner in Django and I am working on a project which requires Custom user model as I Don't require is_staff, is_superuser, is_admin. So, but searching and other ways I made my own Custom user model. But it is not working and I am stuck on it for days. It will be a huge help if someone can help me with the code...
[ "i think you cannot use the check_password function in your case, because it has been created for encrypted password case. Just make a user.password == password in your EmailAuthBackend\nFor second problem with get_user(), I think your userId is not the primary key for Django maybe, problem probably can be solved b...
[ 0, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074193685_django_django_forms_django_models_django_views_python.txt
Q: Python KustoManagementClient using my own credentials I'm trying to use azure-mgmt-kusto Pkg for some Kusto Cluster operations, using KustoManagementClient. This client requires TokenCredential on constructor. For my own scenario, I would like to use my own AAD credentials, preferably using interactive login or I...
Python KustoManagementClient using my own credentials
I'm trying to use azure-mgmt-kusto Pkg for some Kusto Cluster operations, using KustoManagementClient. This client requires TokenCredential on constructor. For my own scenario, I would like to use my own AAD credentials, preferably using interactive login or IWA (Integrated Windows Authentication). The closest I was a...
[ "Actually, after simply trying despite the Pycharm warning, this worked:\nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.kusto import KustoManagementClient\n\ncredential = DefaultAzureCredential()\nkusto_management_client = KustoManagementClient(credential, subId)\n\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_authentication", "azure_data_explorer", "python" ]
stackoverflow_0074193746_azure_azure_authentication_azure_data_explorer_python.txt
Q: Python matching pathnames that include an element from a list I have a list of numbers ['2054', '3271', '8671', '273'] and would like to find all files in a directory that include any one of those values in the pathname in a set pattern. I am using the glob module to find all the pathnames but I have not found a g...
Python matching pathnames that include an element from a list
I have a list of numbers ['2054', '3271', '8671', '273'] and would like to find all files in a directory that include any one of those values in the pathname in a set pattern. I am using the glob module to find all the pathnames but I have not found a good way of including the numbers from my list. This is what I have ...
[ "This is not (easily*) possible with globs. Either post-process the glob, or just use a regex search directly. In this case I'd probably post-process:\npathPac = '/Users/noah/Data/Docs'\ncandidates = Path(pathPac).glob('**/doc*.xml')\nsuffixes = ['2054', '3271', '8671', '273']\nfor f in (c for c in candidates if ...
[ 2, 2 ]
[]
[]
[ "glob", "python" ]
stackoverflow_0074194522_glob_python.txt
Q: Find start and end indexes of list of substrings For a sentence 'Foo bar was open on 12.03.2022 and closed on 3.05.22.' with respective list = [12.03.2022, 4.04.2022, 3.05.22] I want to get the start and end indices in the sentence as a tuple if a date in the list can be found in the sentence. In this case: [(20...
Find start and end indexes of list of substrings
For a sentence 'Foo bar was open on 12.03.2022 and closed on 3.05.22.' with respective list = [12.03.2022, 4.04.2022, 3.05.22] I want to get the start and end indices in the sentence as a tuple if a date in the list can be found in the sentence. In this case: [(20,29), (45, 51)] I have found the dates through regex b...
[ "Use re.search:\nsent = 'Foo bar was open on 12.03.2022 and closed on 3.05.22.'\ndate_list = ['12.03.2022', '4.04.2022', '3.05.22']\n\nhits = [re.search(date, sent) for date in date_list if re.search(date, sent)]\n\nFor the xth match,\n\nhits[x].span() will give you the indices\nand hits[x].group() will return the ...
[ 3, 1 ]
[]
[]
[ "indexing", "list", "python", "string" ]
stackoverflow_0074194441_indexing_list_python_string.txt
Q: Is there a way to suppress the path of the py file when running python? I have all my python files in the directory ..\..\pydir and run them elsewhere. At the moment I have to run my python file using: python ..\..\pydir\test.py I would rather not have to specify the path to the python files. I have put ..\..\p...
Is there a way to suppress the path of the py file when running python?
I have all my python files in the directory ..\..\pydir and run them elsewhere. At the moment I have to run my python file using: python ..\..\pydir\test.py I would rather not have to specify the path to the python files. I have put ..\..\pydir in the PATH environment variable and tried: python test.py But this doe...
[ "Command line:\n\nWhen invoking Python, you may specify any of these options:\npython [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]\n\n…\n<script> Execute the Python code contained in script, which\nmust be a filesystem path (absolute or relative) referring to either a Python file, a direc...
[ 1 ]
[]
[]
[ "path", "python", "windows" ]
stackoverflow_0074093353_path_python_windows.txt
Q: collections.abc.Iterable doesn't allows runtime structural checks according to Iterable API Existing Approaches to Structural Subtyping Abstract classes defined in collections.abc module are slightly more advanced since they implement a custom __subclasshook__() method that allows runtime structural checks withou...
collections.abc.Iterable doesn't allows runtime structural checks according to Iterable API
Existing Approaches to Structural Subtyping Abstract classes defined in collections.abc module are slightly more advanced since they implement a custom __subclasshook__() method that allows runtime structural checks without explicit registration: from collections.abc import Iterable class MyIterable: def __iter_...
[ "While you did cite most of the relevant passages, I would like to add a little bit of additional context and another perspective.\nThe problem lies (as it often does) in the definitions, of which there are two in this case.\n\nThe abstract base Iterable\nThe collections.abc.Iterable is not flawed, it just leans on...
[ 1 ]
[]
[]
[ "abc", "python", "python_typing", "structural_typing" ]
stackoverflow_0074191237_abc_python_python_typing_structural_typing.txt
Q: Django Integrity Error 1048 cannot be null Under views.py def addcomments(request): comment_text = request.POST.get('comment') user_id = request.POST.get('user_id') name = request.POST.get('name') email = request.POST.get('email') comment = Comment.objects.create(user_id=user_id, body=comm...
Django Integrity Error 1048 cannot be null
Under views.py def addcomments(request): comment_text = request.POST.get('comment') user_id = request.POST.get('user_id') name = request.POST.get('name') email = request.POST.get('email') comment = Comment.objects.create(user_id=user_id, body=comment_text, name=name, email=email) comment.sa...
[ "You don't have an user_id field in your html form that's why it becomes None or null and since you don't allow your user_id to be none (don't allow it to be none) django fails to create it. I suggest you get rid of the user_id in the creation and search for a user with that exact unique username that posted the fo...
[ 1, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074193929_django_django_models_python.txt
Q: Convert subset of columns to rows by combining columns Pandas 1.1.4 MRE: df = pd.DataFrame({"Code":[1,2], "view_A":[3000, 2300], "click_A":[3, 23], "view_B":[1200, 300], "click_B":[5, 3]}) df.set_index("Code", inplace=True) >>> view_A click_A view_B click_B Code 1 ...
Convert subset of columns to rows by combining columns
Pandas 1.1.4 MRE: df = pd.DataFrame({"Code":[1,2], "view_A":[3000, 2300], "click_A":[3, 23], "view_B":[1200, 300], "click_B":[5, 3]}) df.set_index("Code", inplace=True) >>> view_A click_A view_B click_B Code 1 3000 3 1200 5 2 2300 23 ...
[ "This is essentially a reshape operation using stack\ndf.columns = df.columns.str.split('_', expand=True)\ndf.stack().rename_axis(['code', 'type'])\n\n\n click view\ncode type \n1 A 3 3000\n B 5 1200\n2 A 23 2300\n B 3 300\n\n", "try with pd...
[ 12, 6, 4, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0069716911_pandas_python.txt
Q: Import a file with a different path, without binding to the name of the main folder or to the user of the pc I use this code to import a file from another folder with different path. It works properly. The problem, however, is that if in the future I change the name of the main folder or if the app is used on a PC...
Import a file with a different path, without binding to the name of the main folder or to the user of the pc
I use this code to import a file from another folder with different path. It works properly. The problem, however, is that if in the future I change the name of the main folder or if the app is used on a PC with a username different from mine, then the path will be different and the app breaks, it will not open. Is the...
[ "There are two ways to do this.\nUsing relative paths, you need to go back 5 spaces then go forward to path Folder1/Folder2. This can be done like this:\n\nimport sys\n\nsys.path.insert(1, \"../../../../../Folder1/Folder2\")\n\n\nYou can also do the same thing using pathlib:\n\nfrom pathlib import Path\nimport os\n...
[ 0 ]
[]
[]
[ "import", "module", "python", "python_3.x" ]
stackoverflow_0074188601_import_module_python_python_3.x.txt
Q: How would I go about getting the full commit hash in Dulwich? I would like to get the behavior of git show -s --format=%H in Dulwich; i.e. getting the full commit hash pointed to by HEAD. However, as it turns out the porcelain.show() function behaves pretty much like git show but doesn't seem to know any additiona...
How would I go about getting the full commit hash in Dulwich?
I would like to get the behavior of git show -s --format=%H in Dulwich; i.e. getting the full commit hash pointed to by HEAD. However, as it turns out the porcelain.show() function behaves pretty much like git show but doesn't seem to know any additional options like the Git CLI. I am not surprised, given porcelain.des...
[ "By consulting the code for porcelain.describe() we can pull the pieces together.\n\nopen_repo_closing offers a nice context manager for the dulwich.repo.BaseRepo class, with contextlib.closing behavior\nBaseRepo.head() contains the information as bytes\n\nA minimal implementation could look like this:\ndef get_lat...
[ 1 ]
[]
[]
[ "dulwich", "python" ]
stackoverflow_0074194840_dulwich_python.txt
Q: convert diction with single values to dataframe let us suppose we have following code : import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression,Ridge,Lasso,ElasticNet from sklearn.neighbors import KNeighborsRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.svm i...
convert diction with single values to dataframe
let us suppose we have following code : import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression,Ridge,Lasso,ElasticNet from sklearn.neighbors import KNeighborsRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.svm import SVR from sklearn.datasets import make_regressio...
[ "algo_dataframe =pd.DataFrame(algo_results, index =[0])\n\nOr put your dict in a list\nalgo_results =[{'linear_Regression': 0.999615308811996, 'Ridge': 0.9996150421204321, 'Lasso': 0.8758019197852375, 'KNN': 0.6274472685707742, 'CART': 0.46164502153497877, 'SVR': 0.17305435111869027}]\nalgo_dataframe =pd.DataFrame(...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074194791_dataframe_pandas_python.txt
Q: Python: I want from a program to ask me only once for input I'm practicing with a simple roulette program. At this moment, I have a problem with balance input(), if I put it outside the function, the function betting() doesn't recognize it. But, if I put it inside, the function, the program asks me again to input ...
Python: I want from a program to ask me only once for input
I'm practicing with a simple roulette program. At this moment, I have a problem with balance input(), if I put it outside the function, the function betting() doesn't recognize it. But, if I put it inside, the function, the program asks me again to input the amount of money and it overwrites the amount of money after t...
[ "Pass the balance as a function parameter to betting(). Then ask once in the choice() function\nimport random\n\ndef betting(balance):\n your_number = int(input(\"Choose the number between 0 and 36, including these: \"))\n if your_number < 0 or your_number > 36:\n print(\"Wrong input, try again!\")\n ...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074194282_python.txt
Q: how to manage column names containing multiple spaces when using read_csv I use the same piece of code which I use to import multiple dataframes. Usually the have the same column names with different data. However sometimes they have different spaces before or after the names of the columns. df = pd.read_csv( ...
how to manage column names containing multiple spaces when using read_csv
I use the same piece of code which I use to import multiple dataframes. Usually the have the same column names with different data. However sometimes they have different spaces before or after the names of the columns. df = pd.read_csv( file_path, delimiter="|", low_mem...
[ "I think it should be possible to match the column names with\npd.read_csv(..., usecols=lambda x: x.strip() in schema.keys())\n\nand then either strip them afterwards with\ndf.columns = df.columns.str.strip()\n\nor even better try to pass them explicitly with\npd.read_csv(..., header=0, names=schema.keys())\n\nif y...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074194745_dataframe_pandas_python.txt
Q: FileNotFoundError when passing a shared memory to a new process I have a multiprocessing application, where I want to pass numpy array data back and forth. The idea is to use a SharedMemoryManager.SharedMemory() and have numpy arrays pointing to the same buffer of this shared memory. Using locks should avoid race ...
FileNotFoundError when passing a shared memory to a new process
I have a multiprocessing application, where I want to pass numpy array data back and forth. The idea is to use a SharedMemoryManager.SharedMemory() and have numpy arrays pointing to the same buffer of this shared memory. Using locks should avoid race conditions. Here is the important part of the code: creating the proc...
[ "Here is how I was able to sort out the problem:\nIt seems (I'm wondering if anyone can confirm this) like the following was happening - at least this is what I can gather from debugging.\nThe code creating the process above was executed within a class method. Since the shared memory buffer was destroyed at the end...
[ 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0074193377_multiprocessing_python.txt
Q: Issue with virtualenv - cannot activate I created a virtualenv around my project, but when I try to activate it I cannot. It might just be syntax or folder location, but I am stumped right now. You can see below, I create the virtualenv and call it venv. Everything looks good, then I try to activate it by running ...
Issue with virtualenv - cannot activate
I created a virtualenv around my project, but when I try to activate it I cannot. It might just be syntax or folder location, but I am stumped right now. You can see below, I create the virtualenv and call it venv. Everything looks good, then I try to activate it by running source venv/bin/activate I'm thinking it migh...
[ "source is a shell command designed for users running on Linux (or any Posix, but whatever, not Windows).\nOn Windows, virtualenv creates a .bat/.ps1 file, so you should run venv\\Scripts\\activate instead (per the virtualenv documentation on the activate script).\nJust run activate, without an extension, so the ri...
[ 513, 42, 39, 29, 12, 11, 4, 4, 4, 3, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ "If you are using windows OS then in Gitbash terminal use the following command $source venv/Scripts/activate. This will help you to enter the virtual environment.\n", "\nOpen your project using VS code editor .\nChange the default shell in vs code terminal to git bash.\nnow your project is open with bash console...
[ -1, -1, -1, -1, -1, -1, -1, -2, -2 ]
[ "python", "virtualenv" ]
stackoverflow_0008921188_python_virtualenv.txt
Q: costum loss : check max and min values of variable of type <class 'tensorflow.python.framework.ops.Tensor' I wrote a costum loss function in tensorflow. But sth is going wrong, because the error is larger 1 which shouldnt be possible. So I want to look up the values of y_predicted and y_true as well as the new cal...
costum loss : check max and min values of variable of type <class 'tensorflow.python.framework.ops.Tensor'
I wrote a costum loss function in tensorflow. But sth is going wrong, because the error is larger 1 which shouldnt be possible. So I want to look up the values of y_predicted and y_true as well as the new calulated loss. but I don't know how to get acces to these values. y_pred and y_true are both of the type <class 't...
[ "I solved my problem by compiling the model with run_eagerly=True :\nmodel.compile(optimizer=opt, loss=square_loss_costum, run_eagerly=True)\n" ]
[ 0 ]
[]
[]
[ "loss_function", "python", "tensorflow" ]
stackoverflow_0074127178_loss_function_python_tensorflow.txt
Q: How to split a single value list to multiple values in same list I did some workarounds but none of them worked so here I am with a question on how can we split a value from a list based on a keyword and update in the same list here is my code, result_list = ['48608541\ncsm_radar_main_dev-7319-userdevsigne...
How to split a single value list to multiple values in same list
I did some workarounds but none of them worked so here I am with a question on how can we split a value from a list based on a keyword and update in the same list here is my code, result_list = ['48608541\ncsm_radar_main_dev-7319-userdevsigned\nLogd\nG2A0P3027145002X\nRadar\ncompleted 2022-10-25T10:43:01\nPASS:...
[ "You need to split each of the string by \\n which results in a list that you need to flatten. You can use list-comprehension:\n>>> [x for item in result_list for x in item.split('\\n') ]\n# output:\n['48608541', 'csm_radar_main_dev-7319-userdevsigned', 'Logd', 'G2A0P3027145002X', 'Radar', 'completed 2022-10-25T10:...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074194611_python.txt
Q: Write a code with collection library in python I have a list in which there are several characters, for example, the characters of the first word have the same letters as the characters of the third word, but their order has changed. I want to write a code that uses the collection library to create a main list at ...
Write a code with collection library in python
I have a list in which there are several characters, for example, the characters of the first word have the same letters as the characters of the third word, but their order has changed. I want to write a code that uses the collection library to create a main list at the output and the number of words The ones that ar...
[ "lst = ['abc', 'acb', 'hds', 'sdh', 'nm', 'mn']\n\n\ndef match(lst: list[str]) -> list[list[str]]:\n new_lst = []\n for i in range(0, len(lst)):\n for j in range(i + 1, len(lst)):\n if sorted(lst[i]) == sorted(lst[j]):\n create_new_pair = True\n # check if it al...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074194568_python.txt
Q: Prove that this algorithm is correct I don't get how this works. Could you please prove this? Thanks. def binary_search(array) -> int: def condition(value) -> bool: pass left, right = min(search_space), max(search_space) # could be [0, n], [1, n] etc. Depends on problem while left < right: ...
Prove that this algorithm is correct
I don't get how this works. Could you please prove this? Thanks. def binary_search(array) -> int: def condition(value) -> bool: pass left, right = min(search_space), max(search_space) # could be [0, n], [1, n] etc. Depends on problem while left < right: mid = left + (right - left) // 2 ...
[ "I believe you would benefit from reading/watching a video on BinarySearch\nhttps://www.youtube.com/watch?v=P3YID7liBug.\n" ]
[ 0 ]
[]
[]
[ "algorithm", "arrays", "binary_search", "proof_of_correctness", "python" ]
stackoverflow_0074148395_algorithm_arrays_binary_search_proof_of_correctness_python.txt
Q: Convert Python Class with Inner Classes and Static Attributes to JSON I am trying to convert the following to json. @dataclass class Attribute: name: str description: str class A: class B: attr1 = Attribute(name="attr1",description="description") attr2 = Attribute(name="attr2",descript...
Convert Python Class with Inner Classes and Static Attributes to JSON
I am trying to convert the following to json. @dataclass class Attribute: name: str description: str class A: class B: attr1 = Attribute(name="attr1",description="description") attr2 = Attribute(name="attr2",description="description") class C: attr3 = Attribute(name="attr3",des...
[ "In this case, the simplest option I could suggest would be to define a recursive helper function to iterate over the static fields in a class and call dataclasses.asdict() on each, such as below.\n\nNote: the following should work in Python 3.8+, as it uses the := walrus operator.\n\n# noinspection PyProtectedMemb...
[ 1 ]
[]
[]
[ "json", "object", "python", "serialization", "static" ]
stackoverflow_0074188275_json_object_python_serialization_static.txt
Q: Raspberry: USB to RS232 (FT4232H chip) can't communicate with Device via Python I want to set up my serial connection to a pump with a USB to 4xRS232 (FT4232H chip). However, my serial connection can't write output from the pump. The whole setup works with a single usb to rs232 converter but not with my USB to 4xR...
Raspberry: USB to RS232 (FT4232H chip) can't communicate with Device via Python
I want to set up my serial connection to a pump with a USB to 4xRS232 (FT4232H chip). However, my serial connection can't write output from the pump. The whole setup works with a single usb to rs232 converter but not with my USB to 4xRS232 converter. My raspberry recognizes all 4 USB ports: /dev/ttyAMA0: ttyAMA0 [fe201...
[ "Closed: had to swap PIN 2 and 3 before using the female-female coupler, as they are swapped inside.\n" ]
[ 0 ]
[]
[]
[ "python", "raspberry_pi", "serial_port" ]
stackoverflow_0074192090_python_raspberry_pi_serial_port.txt
Q: Ubuntu 20.04 upgrade, Python missing libffi.so.6 I recently upgraded my OS to Ubuntu 20.04 LTS. Now when I try to import a library like Numpy in Python, I get the following error: ImportError: libffi.so.6: cannot open shared object file: No such file or directory I tried installing the libffi package, but apt can...
Ubuntu 20.04 upgrade, Python missing libffi.so.6
I recently upgraded my OS to Ubuntu 20.04 LTS. Now when I try to import a library like Numpy in Python, I get the following error: ImportError: libffi.so.6: cannot open shared object file: No such file or directory I tried installing the libffi package, but apt can't locate it : sudo apt-get install libffi Reading pac...
[ "It seems like I fixed it. I could be wrong, but here is what I think happened:\n\nUbuntu 20.04 upgraded libffi6 to libffi7\nPython is still looking for libffi6\n\nWhat I did to fix it :\nLocate libffi.so.7 in your system\n$ find /usr/lib -name \"libffi.so*\"\n\nCreate a simlink named libffi.so.6 that points to lib...
[ 86, 86, 69, 19, 2, 2, 0, 0 ]
[ "The problem with libffi can also be tackled with making a symlink:\nsudo ln -s /usr/path/to/libffi.so.8 /usr/lib/path/to/libffi.so.7\nThen you get another error in xorg log concerning wayland. What helped me was to reinstall wayland and lib32-wayland. After that I could boot normally (although I use xorg in Cinnam...
[ -1 ]
[ "python", "ubuntu", "ubuntu_20.04" ]
stackoverflow_0061875869_python_ubuntu_ubuntu_20.04.txt
Q: Plotting specgram with matplotlib for multiple arrays I have the values like this and I would like to plot the spectrogram for these values and I am using the following code and getting an error : pad_xextent = (NFFT-noverlap) / Fs / 2 TypeError: unsupported operand type(s) for /: 'int' and 'NoneType' [[ 0. ...
Plotting specgram with matplotlib for multiple arrays
I have the values like this and I would like to plot the spectrogram for these values and I am using the following code and getting an error : pad_xextent = (NFFT-noverlap) / Fs / 2 TypeError: unsupported operand type(s) for /: 'int' and 'NoneType' [[ 0. 35.34028168 36.09317546 20.88056919 35.65257548 36.39...
[ "If you look into the documentation of specgram, you will find that it only takes 1D arrays as input.\nAssuming that you want the spectrogram of the data row wise, I'd try the following (using some random data for show)\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = fig.subplots(3,...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074194333_matplotlib_python.txt
Q: Python: cannot iterate over elements, if several identical elements stay in a row I'm a beginner, so sorry for such question. I would like to iterate over the array and find unique values. However, it doesn't iterate further than "A". How could I solve it? Thank you a lot in advance! Code -> def letters_learned_to...
Python: cannot iterate over elements, if several identical elements stay in a row
I'm a beginner, so sorry for such question. I would like to iterate over the array and find unique values. However, it doesn't iterate further than "A". How could I solve it? Thank you a lot in advance! Code -> def letters_learned_today(word): unique_letters = [] for letter in word: already_exists = Fa...
[ "Here is the answer:\ndef letters_learned_today(word):\n unique_letters = []\n\n for letter in word:\n if letter not in unique_letters:\n unique_letters.append(letter)\n return unique_letters\n\n\nword = \"AAABBVSCDDDERZAUJJFFPOUSST\"\nprint(letters_learned_today(word))\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "python", "unique_values" ]
stackoverflow_0074194944_arrays_python_unique_values.txt
Q: Create a new column==1 when another column is NaN I try to create a new column displaying 1 if another column is a missing value. I have the following dataframe Col1 Col2 NaN 5.5 2.5 1.6 NaN 2.0 I want to get the following result : Col1 Col2 new_col NaN 5.5 1.0 2.5 1.6 0.0 NaN 2.0 1.0 I tried the follow...
Create a new column==1 when another column is NaN
I try to create a new column displaying 1 if another column is a missing value. I have the following dataframe Col1 Col2 NaN 5.5 2.5 1.6 NaN 2.0 I want to get the following result : Col1 Col2 new_col NaN 5.5 1.0 2.5 1.6 0.0 NaN 2.0 1.0 I tried the following code : df['new_col']=[1 if (p...
[ "df['col3']=np.where(df['Col1'].isna(), 1, 0)\ndf\n\n Col1 Col2 col3\n0 NaN 5.5 1\n1 2.5 1.6 0\n2 NaN 2.0 1\n\n", "If you want to match any missing value per row:\ndf['new_col'] = df.isna().any(axis=1).astype(int)\n\noutput:\n Col1 Col2 new_col\n0 5.5 NaN 1\n1...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074195022_dataframe_pandas_python.txt
Q: How to mock a property I'm asking how to mock a class property in a unit test using Python 3. I've tried the following, which makes sense for me following the docs, but it doesn't work: foo.py: class Foo(): @property def bar(self): return 'foobar' def test_foo_bar(mocker): foo = Foo() mock...
How to mock a property
I'm asking how to mock a class property in a unit test using Python 3. I've tried the following, which makes sense for me following the docs, but it doesn't work: foo.py: class Foo(): @property def bar(self): return 'foobar' def test_foo_bar(mocker): foo = Foo() mocker.patch.object(foo, 'bar',...
[ "The property mechanism relies on the property attribute being defined on the object's class. You can't create a \"property like\" method or attribute on a single instance of a class (for a better understanding, read about Python's descriptor protocol) \nTherefore you have to apply the patch to your class - you can...
[ 21, 1 ]
[]
[]
[ "pytest", "python", "python_3.x", "python_mock", "python_unittest" ]
stackoverflow_0042704506_pytest_python_python_3.x_python_mock_python_unittest.txt
Q: Sending information through the parameters of the FLASK URL - (SERVER IIS WINDOWS) I created a server to receive data from a data_logger, It is connected through a flask api that I created, and stores the data in a posgreSQL database. When I run the api locally, through the terminal, I can send hundreds of thousan...
Sending information through the parameters of the FLASK URL - (SERVER IIS WINDOWS)
I created a server to receive data from a data_logger, It is connected through a flask api that I created, and stores the data in a posgreSQL database. When I run the api locally, through the terminal, I can send hundreds of thousands of data per minutes. But when I do the Deploy on IIS windows it limits me a lot. I al...
[ "alright.\nI managed to resolve this error.\nInstead of passing the values ​​in the url parameters I send a json through the request body\n" ]
[ 0 ]
[]
[]
[ "flask", "iis", "python" ]
stackoverflow_0073977169_flask_iis_python.txt
Q: Convert list elements to tuples I'm trying to convert a list of elements to tuples and then add the tuples to a new list but keep running into issues with how the results are presented. My list is: list = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)'] When I try to convert it to a tuple using: for a in list1...
Convert list elements to tuples
I'm trying to convert a list of elements to tuples and then add the tuples to a new list but keep running into issues with how the results are presented. My list is: list = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)'] When I try to convert it to a tuple using: for a in list1: list2.append(tuple([a.replace("...
[ "list1 = ['(One, 1)', '(Two, 2)', '(Three, 3)', '(Four, 4)']\nlist2 = []\n\nfor a in list1:\n str = a.replace(\"(\", \"\").replace(\")\", \"\").split(\",\")\n list2.append((str[0], int(str[1])))\n \nprint(list2)\n\nOutput:\n[('One', 1), ('Two', 2), ('Three', 3), ('Four', 4)]\n\n", "a.replace(\"(\", \"\")...
[ 1, 1, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074194869_list_python_tuples.txt
Q: strings are throwing errors In this project I am checking the number is even or odd with the help of user input. The problem I am stuck on is that when the user types a str character the whole project blows up. I want to write a program where even if the user typed a string the program won't blow up would print("P...
strings are throwing errors
In this project I am checking the number is even or odd with the help of user input. The problem I am stuck on is that when the user types a str character the whole project blows up. I want to write a program where even if the user typed a string the program won't blow up would print("Please type a number") a message l...
[ "Not sure why you are using typeat the beginning, but this may help you:\nwhile True:\n try:\n num = int(input('Enter a number: '))\n break\n except ValueError:\n print('Please type a number.')\n continue\n \nif num % 2 == 0:\n print(str(num) + ' is an even number')\nelse:\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074195052_python.txt
Q: By is not getting recognized while using driver.find_elements in selenium I was trying to fetch an element using its XPATH and was expecting for the result to get print A: You are missing an import from selenium.webdriver.common.by import By
By is not getting recognized while using driver.find_elements in selenium
I was trying to fetch an element using its XPATH and was expecting for the result to get print
[ "You are missing an import\nfrom selenium.webdriver.common.by import By\n\n" ]
[ 2 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "unrecognized_selector" ]
stackoverflow_0074195129_python_selenium_selenium_webdriver_unrecognized_selector.txt
Q: Terminal output to a text.insert tkinter below 2 functions that I used to convert PDF 2 Docx, i am trying to get Terminal output into a text box or label, in the subprocess.Popen which command shall is start with? thanks in advance. Max ` def directing(): process = subprocess.Popen(['cv.convert'],stdout=subpro...
Terminal output to a text.insert tkinter
below 2 functions that I used to convert PDF 2 Docx, i am trying to get Terminal output into a text box or label, in the subprocess.Popen which command shall is start with? thanks in advance. Max ` def directing(): process = subprocess.Popen(['cv.convert'],stdout=subprocess.PIPE,bufsize=1, text=True, shell=True) ...
[ "Try polling the process\ndef directing():\n process = subprocess.Popen(\n ['cv.convert'], \n stdout=subprocess.PIPE,\n bufsize=1,\n text=True, \n shell=True\n )\n while process.poll() is None: \n output = process.stdout.read()\n output = str(output).replace...
[ 0 ]
[]
[]
[ "python", "stdout", "tkinter" ]
stackoverflow_0074195097_python_stdout_tkinter.txt
Q: E0401:Unable to import 'flask' Am new in flask development and trying to import flask in my project but Pylint is giving this error in VSCode E0401:Unable to import 'flask', but I installed flask already in my project but I don't know how to solve this, how can I resolve it. My virtual environment is installed ,...
E0401:Unable to import 'flask'
Am new in flask development and trying to import flask in my project but Pylint is giving this error in VSCode E0401:Unable to import 'flask', but I installed flask already in my project but I don't know how to solve this, how can I resolve it. My virtual environment is installed , and the image which proves is below...
[ "Solution is to switch Interpreter\nSimple solution :\nGo to command palette\nType-- Python:Select Interpreter\nSelect virtual environment that you created\nanswered specifically for vscode can work for other also .\n", "Go to Command Palette using Ctrl + Shift + P.\nselect python:select interpreter and then c...
[ 34, 14, 10, 4, 3, 1, 0, 0 ]
[ "In my case, the vscode cannot run the lint becouse my flask install with venv environment, so I deactivate the vent and install flask again in the normal environment , the lint will be work~\n", "In my case, I have disabled pylint. and it works\nUse Ctrl+Shift+P to open the command pallet in VSCode and type pyth...
[ -1, -1, -1 ]
[ "flask", "python", "visual_studio_code" ]
stackoverflow_0050905636_flask_python_visual_studio_code.txt
Q: Can't import torch that could not be resolved I'm trying to run this code take from https://github.com/ultralytics/yolov5. I installed all the files in requirements.txt, and when I check the pip list, I see the version of torch is available. I tried to run pip3 install torch but it announced "Requirement already s...
Can't import torch that could not be resolved
I'm trying to run this code take from https://github.com/ultralytics/yolov5. I installed all the files in requirements.txt, and when I check the pip list, I see the version of torch is available. I tried to run pip3 install torch but it announced "Requirement already satisfied". How can I fix this? import torch # Mode...
[ "Problems like this with Python are often caused by packages getting installed to the wrong instance of Python.\nFirst off, are you using a virtual environment to run your code? If you are, make sure you're enabling the virtual env when you're installing torch.\nYou can use the following two commands to check if th...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074194376_python.txt
Q: Pandas - inconsistent join behaviour for NaN keys depending on Index or Multiindex I have a simple left dataframe and I'd like to left join a right dataframe to it using their indexes. left dataframe (Multiindex consisting of key_1 and key_2): key_1 key_2 a a NaN NaN right dataframe (key_1 is index, desired_co...
Pandas - inconsistent join behaviour for NaN keys depending on Index or Multiindex
I have a simple left dataframe and I'd like to left join a right dataframe to it using their indexes. left dataframe (Multiindex consisting of key_1 and key_2): key_1 key_2 a a NaN NaN right dataframe (key_1 is index, desired_column is a column) key_1 desired_column a desired_value_a b desired_v...
[ "My guess (this is just an hypothesis), as you use left/right_index=True for both, a reindexing occurs to have the same levels for both DataFrames, which leads to a null level of key_2 for right.\nIndeed, setting a dummy level for key_2 does not lead to the same issue:\nright = pd.DataFrame({\n 'key_1': ['a', 'b...
[ 0 ]
[]
[]
[ "dataframe", "join", "pandas", "python" ]
stackoverflow_0074195130_dataframe_join_pandas_python.txt
Q: buildroot package using scanpypi: ImportError: No module named 'setup' I want to install some python packages ( importlib_metadata threadpoolctl) from source. They have pyproject.toml setup.cfg files, but there's no setup.py file. So when I try to install them, they give the same errors: Traceback (most recent cal...
buildroot package using scanpypi: ImportError: No module named 'setup'
I want to install some python packages ( importlib_metadata threadpoolctl) from source. They have pyproject.toml setup.cfg files, but there's no setup.py file. So when I try to install them, they give the same errors: Traceback (most recent call last): File "utils/scanpypi", line 750, in <module> main() File "u...
[ "Your package uses PEP517 rather than setuptools or distutils. Support for PEP517 was added to Buildroot in 2022.05. Make sure you have a recent Buildroot version and set PYTHON_FOO_SETUP_TYPE to flit. See the manual for details.\nSupport for PEP517 was not yet added to the scanpypi utility, but there's a patch for...
[ 2 ]
[]
[]
[ "buildroot", "embedded_linux", "python", "python_3.x" ]
stackoverflow_0074178244_buildroot_embedded_linux_python_python_3.x.txt
Q: How do I import a python library while behind a proxy? I am trying to import a python library using: import cenpy as cp but I get an error message: ConnectionError: HTTPSConnectionPool(host='api.census.gov', port=443): Max retries exceeded with url: /data.json (Caused by NewConnectionError('<urllib3.connection.HT...
How do I import a python library while behind a proxy?
I am trying to import a python library using: import cenpy as cp but I get an error message: ConnectionError: HTTPSConnectionPool(host='api.census.gov', port=443): Max retries exceeded with url: /data.json (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000013167B552B0>: Failed to estab...
[ "So I did some more digging and found out the library does place a call to the API during import. There seems to be a workaround for this but it is not implemented their code yet. I tried a few more things and I wanted to share what worked for me. You have to make sure that the code below runs prior to importing th...
[ 0 ]
[]
[]
[ "api", "proxy", "python", "python_requests", "session" ]
stackoverflow_0074157956_api_proxy_python_python_requests_session.txt
Q: rethrowing python exception. Which to catch? I'm learning to use python. I just came across this article: http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html It describes rethrowing exceptions in python, like this: try: do_something_dangerous() except: do_something_to_apologize() ...
rethrowing python exception. Which to catch?
I'm learning to use python. I just came across this article: http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html It describes rethrowing exceptions in python, like this: try: do_something_dangerous() except: do_something_to_apologize() raise Since you re-throw the exception, there sho...
[ "Try it and see:\ndef failure():\n raise ValueError, \"Real error\"\n\ndef apologize():\n raise TypeError, \"Apology error\"\n\ntry:\n failure()\nexcept ValueError:\n apologize()\n raise\n\nThe result:\nTraceback (most recent call last):\n File \"<pyshell#14>\", line 10, in <module>\n apologize()...
[ 79, 8, 0 ]
[]
[]
[ "exception", "python", "rethrow", "throw" ]
stackoverflow_0025001971_exception_python_rethrow_throw.txt
Q: How to achieve autocomplete on a substring of QLineEdit in PyQt6? I'm very new to QT so please assume I know nothing. I want an auto-complete where it only matches against the text after the last comma. e.g. if my word bank is ["alpha", "beta", "vector space"], and the user currently has typed "epsilon,dog,space" ...
How to achieve autocomplete on a substring of QLineEdit in PyQt6?
I'm very new to QT so please assume I know nothing. I want an auto-complete where it only matches against the text after the last comma. e.g. if my word bank is ["alpha", "beta", "vector space"], and the user currently has typed "epsilon,dog,space" then it should match against "vector space" since "space" is a substrin...
[ "One solution is to use the textChanged signal to set the completion prefix, and bypass the built-in behaviour of the line-edit to allow greater control of when and how the completions happen.\nBelow is a basic implementation that shows how to do that. By default, it only shows completions when the text after the l...
[ 2, 0 ]
[]
[]
[ "pyqt", "python", "qcompleter", "qt", "substring" ]
stackoverflow_0074189826_pyqt_python_qcompleter_qt_substring.txt
Q: Eland - TypeError: count() got an unexpected keyword argument 'query' I'm trying to get my ES index as a dataframe using the Eland API in Python. However, i'm getting a typerror. es = Elasticsearch(hosts=["http://1.1.1.1:9100"], send_get_body_as='POST', http_auth=('es-automation', ...
Eland - TypeError: count() got an unexpected keyword argument 'query'
I'm trying to get my ES index as a dataframe using the Eland API in Python. However, i'm getting a typerror. es = Elasticsearch(hosts=["http://1.1.1.1:9100"], send_get_body_as='POST', http_auth=('es-automation', 'my_passwor...
[ "Try downgrading all the supported libs to fit your ES server version (ealsticsearch==7.16; eland==7.16; pandas==1.2.x ...)\n" ]
[ 0 ]
[]
[]
[ "eland", "elasticsearch", "http", "python", "python_3.x" ]
stackoverflow_0072271055_eland_elasticsearch_http_python_python_3.x.txt
Q: Print Statement using two data types print("this is your "+t+" warning") t is supposed to be an integer. this is probably a silly and stupid question but is it possible to print a variable(in the case t with an int value) and a string("this is your" & "warning") together in one print statement[print()]. If I reme...
Print Statement using two data types
print("this is your "+t+" warning") t is supposed to be an integer. this is probably a silly and stupid question but is it possible to print a variable(in the case t with an int value) and a string("this is your" & "warning") together in one print statement[print()]. If I remember it correctly it's possible in java, n...
[ "You can use string formatting to pass your print statement as one string.\nprint(f\"this is your {t} warning\")\n\nIn case if you would like to get familiar with string formatting: https://realpython.com/python-f-strings/\n", "t = 0\nprint(\"this is your\", t, \"warning\")\nprint(f\"this is your {t} warning\")\n...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074194628_python.txt
Q: Fetching values from a list in Python values = ['random word1', 20, 'random word2', 54] values = list(map(list,zip(values[::2], values[1::2]))) print(values) [['random word1', 20], ['random word2', 54]] Now I want to fetch values like this: if ‘random word2’ in values: get the value associated with random word...
Fetching values from a list in Python
values = ['random word1', 20, 'random word2', 54] values = list(map(list,zip(values[::2], values[1::2]))) print(values) [['random word1', 20], ['random word2', 54]] Now I want to fetch values like this: if ‘random word2’ in values: get the value associated with random word 2 which is in this case 54. Note: string...
[ "I think a dictionary over a list is the way to go\nd = dict(zip(values[::2], values[1::2]))\nprint(d['random word1']) # -> 20\n\n", "try:\n value = values[values.index(\"random words2\") + 1]\nexcept ValueError:\n value = None \n\nOr, if you need to fecth more values, convert your list to a dictionary and...
[ 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074195306_list_python.txt
Q: How to count value in column and groupby I want to to get the count of OK & NOK for each ITCD & Indicateur RDV, here a sample of my table : _ITCD_ | _Indicateur RDV_ | Week | Workers OK OK 41 John OK NOK 41 John NOK NOK 40 Liam I want t...
How to count value in column and groupby
I want to to get the count of OK & NOK for each ITCD & Indicateur RDV, here a sample of my table : _ITCD_ | _Indicateur RDV_ | Week | Workers OK OK 41 John OK NOK 41 John NOK NOK 40 Liam I want to get the count of each workers for each week...
[ "You can use lists in crosstab, combine it with melt:\ndf2 = df.melt(['Week', 'Workers'])\n\npd.crosstab([df2['Week'], df2['Workers']], [df2['variable'], df2['value']])\n\noutput:\nvariable _ITCD_ _Indicateur RDV_ \nvalue NOK OK NOK OK\nWeek Workers \n40 ...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074195342_numpy_pandas_python.txt
Q: Input multiple string in list - python Hello so im new on python, i want to know how to do multiple string input on list. I already try to append the input to the list, but it doesn't give me expected output. Here is the source code: test=[] input1=input("Enter multiple strings: ") splitinput1=input1.split() for x...
Input multiple string in list - python
Hello so im new on python, i want to know how to do multiple string input on list. I already try to append the input to the list, but it doesn't give me expected output. Here is the source code: test=[] input1=input("Enter multiple strings: ") splitinput1=input1.split() for x in range(len(splitinput1)): test.append...
[ "strings = input(\"Enter multiple strings: \")\ntest = strings.split()\nprint(test)\nprint(len(test))\n\n", "You have slight error in your code. Do this:\ntest=[]\ninput1=input(\"Enter multiple strings: \")\nsplitinput1=input1.split()\nfor x in splitinput1:\n test.append(x)\nprint(test)\nprint(len(test))\n\n" ]
[ 1, 1 ]
[]
[]
[ "input", "list", "python", "string" ]
stackoverflow_0074195370_input_list_python_string.txt
Q: Python While Loop W/ "Go Back" Option So I am trying to think of a way to have a go back option if the user scans the wrong barcode. Some insight, my company scans in a lot of equipment and sometimes there are barcodes very close to each other and it easy to scan the wrong one. The problem I am currently having wi...
Python While Loop W/ "Go Back" Option
So I am trying to think of a way to have a go back option if the user scans the wrong barcode. Some insight, my company scans in a lot of equipment and sometimes there are barcodes very close to each other and it easy to scan the wrong one. The problem I am currently having with my code is that if the user scans the wr...
[ "What about introducing another command that just delete the last element of the list with the .pop() method?\nSomething like\nif s==\"e\":\n serial_numbers.pop()\n\nSo if the user insert \"e\", he would be able to insert again the last code. I don't know if this is sufficient but may be a start...\n", "Follow...
[ 1, 1 ]
[]
[]
[ "loops", "ms_access", "python" ]
stackoverflow_0074195017_loops_ms_access_python.txt
Q: How can I get pip to list the repositories it's using? I'm trying to get a codebase running on my machine, and pip isn't finding some of the dependencies. It seems to find them on another machine, so I'd like to see which repos pip is using on the two machines so I can compare. How can I do this? A: Update for 2...
How can I get pip to list the repositories it's using?
I'm trying to get a codebase running on my machine, and pip isn't finding some of the dependencies. It seems to find them on another machine, so I'd like to see which repos pip is using on the two machines so I can compare. How can I do this?
[ "Update for 21.1.2\n(copied from @Bryan Roach's comment):\npip download --no-cache-dir --verbose \"foo<0\" 2>&1 |grep 'location(s) to search' -A5\n\nUpdate for pip>=20\nThe repositories are now listed by default, no need to pass the --verbose arg:\n$ pip download --no-cache-dir \"foo<0\" 2>&1 | grep Looking\nLookin...
[ 20, 1 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0051874974_pip_python.txt
Q: How to make Python-Telegram_bot send a message without getting a commad? I'm Making a telegram bot using Python-Telegram-bot. I wanna make it send a message to one specific user (myself in this case) to select an option. after that, it should take that option as a command and work as usual. but after 30 min... it ...
How to make Python-Telegram_bot send a message without getting a commad?
I'm Making a telegram bot using Python-Telegram-bot. I wanna make it send a message to one specific user (myself in this case) to select an option. after that, it should take that option as a command and work as usual. but after 30 min... it should send me the same message making me choose an option just like before. H...
[ "You can get the bot object either from the updater or the dispatcher:\nupdater = Updater('<bot-token>')\nupdater.bot.sendMessage(chat_id='<user-id>', text='Hello there!')\n\n# alternative:\nupdater.dispatcher.bot.sendMessage(chat_id='<user-id>', text='Hello there!')\n\n", "v20.x\nSince version v20.x, there has b...
[ 14, 1 ]
[]
[]
[ "python", "python_telegram_bot", "telegram", "telegram_bot" ]
stackoverflow_0065349950_python_python_telegram_bot_telegram_telegram_bot.txt
Q: python logging - how do I truncate the pathname to just the last few characters or just the filename? I'm using python logging and I have a formatter that looks like the following: formatter = logging.Formatter( '%(asctime)s - %(pathname)86s - %(lineno)4s - %(message)s', '%d %H:%M' ) As you can see, I lik...
python logging - how do I truncate the pathname to just the last few characters or just the filename?
I'm using python logging and I have a formatter that looks like the following: formatter = logging.Formatter( '%(asctime)s - %(pathname)86s - %(lineno)4s - %(message)s', '%d %H:%M' ) As you can see, I like the information in my log files to line up neatly in columns. The reason I have 86 spaces reserved for t...
[ "You'll have to implement your own Formatter subclass that truncates the path for you; the formatting string cannot do this:\nimport logging\nimport os\n\nclass PathTruncatingFormatter(logging.Formatter):\n def format(self, record):\n if isinstance(record.args, dict) and 'pathname' in record.args:\n ...
[ 13, 2, 1, 0, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0014429724_logging_python.txt
Q: Making the element of a list a class attribute of an instance variable I'm trying to build an UNO game and I'm in the process of creating the deck. Right now I'm stuck with creating the action cards to then append to the entire deck. This is my code: class Card: def __init__(self, symbol, colour, is_action_card ...
Making the element of a list a class attribute of an instance variable
I'm trying to build an UNO game and I'm in the process of creating the deck. Right now I'm stuck with creating the action cards to then append to the entire deck. This is my code: class Card: def __init__(self, symbol, colour, is_action_card = False, is_wild_card = False): self.symbol = symbol self.colour = c...
[ "You are appending the same Card instance 4 times to the list and keep changing its colour attribute. The last one that persists is \"yellow\".\nYou are missing to create a separate Card instance for each colour:\nfor colour in colour_list:\n reverse_card = Card(\"reverse\", colour, True)\n reverse_cards.append([...
[ 0 ]
[]
[]
[ "for_loop", "list", "python" ]
stackoverflow_0074195380_for_loop_list_python.txt
Q: How can I make my recursion program to output factorial of a number more efficient? I have made a program which outputs the factorial of a number by calling the function: factorial() which uses recursion to calculate and return the value. I have also included a loop to break the program when the User inputs the wo...
How can I make my recursion program to output factorial of a number more efficient?
I have made a program which outputs the factorial of a number by calling the function: factorial() which uses recursion to calculate and return the value. I have also included a loop to break the program when the User inputs the word "off". Please suggest any improvements Here is the code: def factorial(base): if b...
[ "While recursive approach seems like a natural thing to do, sadly that is not very efficient, as each call requires a separate stack frame to be created. It also causes problems due to Python's recursion depth limit, which means you this program will raise an exception for any base > 1000. Iterative approach (with ...
[ 1, 0 ]
[]
[]
[ "coding_efficiency", "factorial", "python", "recursion" ]
stackoverflow_0074193164_coding_efficiency_factorial_python_recursion.txt
Q: PySyde6 path of setWindowIcon didn't work with PyInstaller on Windows I am following a step by step tutorial on PySide6 and PyInstaller in order to do my first one-file build EXE application. But I am stuck at the step "Setting an application icon". My window created with PySide6 doesn't display my logo icon when ...
PySyde6 path of setWindowIcon didn't work with PyInstaller on Windows
I am following a step by step tutorial on PySide6 and PyInstaller in order to do my first one-file build EXE application. But I am stuck at the step "Setting an application icon". My window created with PySide6 doesn't display my logo icon when I build the source file with PyInstaller. I have used app.setWindowIcon(QtG...
[ "Ok so as mentioned by @musicamante, I need to bundle my icon as a resource : pyinstaller --windowed --icon=hand.ico --add-data=\"hand.ico;.\" app.py or by modifying the datas list in the Analysis section of the spec file.\n" ]
[ 0 ]
[]
[]
[ "path", "pyinstaller", "pyqt6", "pyside6", "python" ]
stackoverflow_0074194862_path_pyinstaller_pyqt6_pyside6_python.txt
Q: How to total up values from dictionary when creating a new list Stock = { 'apple': .40, 'cheese': .90, 'banana': .60, 'pear': .60, 'steak': 3.00, 'salad': 1.00, 'ketchup': 1.00, 'wine': 5.00, 'beer': 4.50, } shoplist = [] for key, value in Stock.items(): print(key, value) ...
How to total up values from dictionary when creating a new list
Stock = { 'apple': .40, 'cheese': .90, 'banana': .60, 'pear': .60, 'steak': 3.00, 'salad': 1.00, 'ketchup': 1.00, 'wine': 5.00, 'beer': 4.50, } shoplist = [] for key, value in Stock.items(): print(key, value) # def checkout(): # answer = input('Would you like to checkout a...
[ "As Axe319 commented, the solution would be total = sum(Stock[i] for i in shoplist)\nThank you\n" ]
[ 0 ]
[]
[]
[ "cumulative_sum", "dictionary", "key_value_store", "list", "python" ]
stackoverflow_0074181693_cumulative_sum_dictionary_key_value_store_list_python.txt
Q: One legend entry when plotting several curves using one `plot` call I am creating a grid by plotting several curves using one plot call as: import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.array([[0,1], [0,1], [0,1]]) y = np.array([[0,0], [1,1], [2,2]]) ax.plot([0,1],[0,2], lab...
One legend entry when plotting several curves using one `plot` call
I am creating a grid by plotting several curves using one plot call as: import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.array([[0,1], [0,1], [0,1]]) y = np.array([[0,0], [1,1], [2,2]]) ax.plot([0,1],[0,2], label='foo', color='b') ax.plot(x.T, y.T, label='bar', color='k') ax.legen...
[ "Here is one possible solution: You may use the fact that underscores do not produce legend entries. So setting all but the first label to \"_\" suppresses those to appear in the legend.\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig, ax = plt.subplots()\n\nx = np.array([[0,1], [0,1], [0,1]])\ny = np.a...
[ 8, 4, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0052497476_matplotlib_python.txt
Q: Is there a way in python to execute a statement like 'for min(x, y) do z' without an if-else logic? Is there a shorter way of writing an if-else loop in a scenario where I have a comparison between two numbers as condition? Here is a pseudo-code example: a = 10 b = 15 c = None if a > b: c = b elif a < b: ...
Is there a way in python to execute a statement like 'for min(x, y) do z' without an if-else logic?
Is there a shorter way of writing an if-else loop in a scenario where I have a comparison between two numbers as condition? Here is a pseudo-code example: a = 10 b = 15 c = None if a > b: c = b elif a < b: c = a Is there a way in python to take the expression above and shorten it? My thoughts so far hav...
[ "Yes there are two ways you could do that. Python has a built in function min() which, like you said, will return the minimum of two values\nc = min(a,b)\n\nOr you can put an if in one line like this\nc = b if b<a else a\n\nHope this helps\n" ]
[ 0 ]
[]
[]
[ "algorithm", "if_statement", "python" ]
stackoverflow_0074195550_algorithm_if_statement_python.txt
Q: How to cast Date column from string to datetime in pyspark/python? I have a date column with string datatype when inferred in pyspark: Mon Oct 17 15:57:48 EST 2022 How to cast string datatype as datetime? A: you can use the required datetime formatters - 'E MMM dd HH:mm:ss z yyyy'. the resulting timestamp will ...
How to cast Date column from string to datetime in pyspark/python?
I have a date column with string datatype when inferred in pyspark: Mon Oct 17 15:57:48 EST 2022 How to cast string datatype as datetime?
[ "you can use the required datetime formatters - 'E MMM dd HH:mm:ss z yyyy'. the resulting timestamp will be in UTC and, thus, you'll see that it will add 5 hours to the source ts.\nspark.conf.set('spark.sql.legacy.timeParserPolicy', 'LEGACY')\n\nspark.sparkContext.parallelize([('Mon Oct 17 15:57:48 EST 2022', )]).t...
[ 1 ]
[]
[]
[ "apache_spark_sql", "pyspark", "pyspark_pandas", "python", "python_3.x" ]
stackoverflow_0074193537_apache_spark_sql_pyspark_pyspark_pandas_python_python_3.x.txt
Q: Multiple functions plotted as f(y) instead of f(x) in pandas I'm new to Python so I hope you'll forgive my silly questions. I have read a dataset from excel with pandas. The dataset is composed by 3 functions (U22, U35, U55) and related same index (called y/75). enter image description here now I would like to "tu...
Multiple functions plotted as f(y) instead of f(x) in pandas
I'm new to Python so I hope you'll forgive my silly questions. I have read a dataset from excel with pandas. The dataset is composed by 3 functions (U22, U35, U55) and related same index (called y/75). enter image description here now I would like to "turn" the graph so that the index "y/75" goes on the y-axis instead ...
[ "I am not very familiar with dataframes plot. And to be honest, I've been stalking this question expecting that someone would give an obvious answer. But since no one has one (1 hour old questions, is already late for obvious answers), I can at least tell you how I would do it, without the plot method of the datafr...
[ 0 ]
[]
[]
[ "graph", "pandas", "python" ]
stackoverflow_0074194292_graph_pandas_python.txt
Q: Writing string to a file on a new line every time I want to append a newline to my string every time I call file.write(). What's the easiest way to do this in Python? A: Use "\n": file.write("My String\n") See the Python manual for reference. A: You can do this in two ways: f.write("text to write\n") or, dep...
Writing string to a file on a new line every time
I want to append a newline to my string every time I call file.write(). What's the easiest way to do this in Python?
[ "Use \"\\n\":\nfile.write(\"My String\\n\")\n\nSee the Python manual for reference.\n", "You can do this in two ways:\nf.write(\"text to write\\n\")\n\nor, depending on your Python version (2 or 3):\nprint >>f, \"text to write\" # Python 2.x\nprint(\"text to write\", file=f) # Python 3.x\n\n", "You ...
[ 434, 150, 104, 35, 21, 14, 11, 7, 4, 2, 2, 1, 1, 1, 1 ]
[ "Usually you would use \\n but for whatever reason in Visual Studio Code 2019 Individual it won't work. But you can use this:\n# Workaround to \\n not working\nprint(\"lorem ipsum\", file=f) # Python 3.0 onwards only\nprint >>f, \"Text\" # Python 2.0 and under\n\n", "If write is a callback, you may n...
[ -1, -1, -1, -1 ]
[ "newline", "python" ]
stackoverflow_0002918362_newline_python.txt
Q: Advice on combining and adding values in Python I am quite new to Python, and I have currently been doing this manually in Microsoft excel. I would like to identify duplicate columns and then add together the total votes for each column using Python. For example: Person Variable 1 Variable 2 Variable 3 Vote 1 0 ...
Advice on combining and adding values in Python
I am quite new to Python, and I have currently been doing this manually in Microsoft excel. I would like to identify duplicate columns and then add together the total votes for each column using Python. For example: Person Variable 1 Variable 2 Variable 3 Vote 1 0 1 1 1000 2 0 1 1 710 3 1 0 0 750 In the...
[ "Assuming this is a pandas dataframe (You can use pd.read_excel('file_name') to pull in your data as a pandas dataframe), you can use .groupby() to group by the 3 variable columns, then sum() to get the sum of the vote column:\ndf.groupby(['Variable 1', 'Variable 2', 'Variable 3'], as_index=False)['Vote'].sum()\n\n...
[ 1 ]
[]
[]
[ "duplicates", "python" ]
stackoverflow_0074195692_duplicates_python.txt
Q: Python requests PUT not updating data I have a yaml file : file.yaml structured as follows : index: - uid: "uid" name: "name" headline: "headline" overview: "overview" features: "features" instructions: "instructions" callback_url: "https://some-url.com/params" edit_url: "https://edit...
Python requests PUT not updating data
I have a yaml file : file.yaml structured as follows : index: - uid: "uid" name: "name" headline: "headline" overview: "overview" features: "features" instructions: "instructions" callback_url: "https://some-url.com/params" edit_url: "https://edit-url/params" uninstall_hook: "https://u...
[ "I've got additional resources that helped.\nAs I was trying to solve my issue, I found this. It happens I didn't wrote files part as it should, plus I was having data as a JSON string. That causes a ValueError: Data must not be a string. error. This was useful to get it fixed.\nNow, for what it's worth, here's the...
[ 0 ]
[]
[]
[ "put", "python", "python_requests" ]
stackoverflow_0074184239_put_python_python_requests.txt
Q: Make Pipenv create the virtualenv in the same folder I want Pipenv to make virtual environment in the same folder with my project (Django). I searched and found the PIPENV_VENV_IN_PROJECT option but I don't know where and how to use this. A: PIPENV_VENV_IN_PROJECT is an environment variable, just set it (the val...
Make Pipenv create the virtualenv in the same folder
I want Pipenv to make virtual environment in the same folder with my project (Django). I searched and found the PIPENV_VENV_IN_PROJECT option but I don't know where and how to use this.
[ "PIPENV_VENV_IN_PROJECT is an environment variable, just set it (the value doesn't matter, but must not be empty). Make sure to export it so child processes of the shell can see it:\nexport PIPENV_VENV_IN_PROJECT=1\n\nThis causes the virtualenv to be created in the .venv directory next to the Pipfile file. Use unse...
[ 87, 73, 5, 3, 2, 0 ]
[]
[]
[ "pipenv", "python" ]
stackoverflow_0052540121_pipenv_python.txt
Q: How to send object in worker from master? Is have code class Tasks(SequentialTaskSet): @task def shopping(self): with self.parent.environment.parsed_options.shopping.request_airshopping( client=self.client, catch_response=True) as response: self.run_req(response, self.pa...
How to send object in worker from master?
Is have code class Tasks(SequentialTaskSet): @task def shopping(self): with self.parent.environment.parsed_options.shopping.request_airshopping( client=self.client, catch_response=True) as response: self.run_req(response, self.parent.environment.parsed_options.rsa) class Web...
[ "You can do this by sending a message from worker to master or master to worker. The message is just a string but you can include a data payload with it. You need a function that registers what your message is and what to do when it receives that message, which many times will be a function that does something with...
[ 1 ]
[]
[]
[ "locust", "python" ]
stackoverflow_0074194815_locust_python.txt
Q: interpret the performance of my model from confusion matrix how I can interpret the performance of my model from this matrix A: Its always better to evaluate through precision, recall and f-score. precision is defined as True positive/ True positives + False Positives and precision is True positive/ True positiv...
interpret the performance of my model from confusion matrix
how I can interpret the performance of my model from this matrix
[ "Its always better to evaluate through precision, recall and f-score. precision is defined as True positive/ True positives + False Positives\nand precision is True positive/ True positives + False Negatives. F-score is an mean of both precision and recall.\nThere is a way clearer than this. You can get the precisi...
[ 0 ]
[]
[]
[ "confusion_matrix", "python" ]
stackoverflow_0074195670_confusion_matrix_python.txt
Q: Iterate over an image directory, crop the images and save to a new directory I have a an image directory I have loaded into a dataframe with annotations coordinates, I am trying to crop the images according to the coordinates (xmin, xmax, ymin, ymax) and save them into a new dataframe but keep getting an error. Th...
Iterate over an image directory, crop the images and save to a new directory
I have a an image directory I have loaded into a dataframe with annotations coordinates, I am trying to crop the images according to the coordinates (xmin, xmax, ymin, ymax) and save them into a new dataframe but keep getting an error. This is the code I have so far: Here is the df I have File_Path xmin xmax ymin y...
[ "You don't use the correct way to crop the image, you should do like this:\ncrop = image[xmin:xmax, ymin:ymax]\n\n", "You are calling the image array with image((xmin, ymin), (xmax, ymax)), instead of slicing image[ymin:ymax, xmin: xmax].\nIn your case, if I want to read and save the image with 3 channels, I woul...
[ 0, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074195498_opencv_python.txt
Q: Python: How to get value from specific element from xml file I'm using xml.etree.ElementTree My XML looks like this: <?xml version="1.0" encoding="UTF-8"?> <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.0668.011.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:200...
Python: How to get value from specific element from xml file
I'm using xml.etree.ElementTree My XML looks like this: <?xml version="1.0" encoding="UTF-8"?> <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.0668.011.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02 pain.0668.011.02.xsd"> <CstmrDrct...
[ "You have to deal with your namespaces; try this:\nns = {'': 'urn:iso:std:iso:20022:tech:xsd:pain.0668.011.02'}\nroot.find('.//GrpHdr/CtrlSum',namespaces=ns).text\n\nand see if it works.\n" ]
[ 0 ]
[]
[]
[ "elementtree", "lxml", "python", "tags", "xml" ]
stackoverflow_0074195054_elementtree_lxml_python_tags_xml.txt
Q: Why requests raise_for_status() not called using pytest There is a class and a method _get_authorize_token class StsAPI: def _get_authorize_token(self) -> str: try: resp = requests.post(settings.AUTHORIZATION_SERVICE_URL, json=self.data) print(resp.statu...
Why requests raise_for_status() not called using pytest
There is a class and a method _get_authorize_token class StsAPI: def _get_authorize_token(self) -> str: try: resp = requests.post(settings.AUTHORIZATION_SERVICE_URL, json=self.data) print(resp.status_code) resp.raise_for_status() ...
[ "Since you mocked the response, accessing the raise_for_status attribute simply returns a new mock, rather than getting the actual raise_for_status method of a real response. Just like you configured the mock to produce a status_code of 500, you need to configure it to produce a method that raises the exception you...
[ 0 ]
[]
[]
[ "pytest", "python", "python_requests" ]
stackoverflow_0074195357_pytest_python_python_requests.txt
Q: Rename df column name with dictionary key in Python I have the following df and dict: df = pd.DataFrame({'a':[1,2,3,4], 'x':[11,12,13,14]}) dict_ = {'new_a':['a','b','c'],'new_x':['x','y','z']} I would like to check if column 'a' and 'x' exist in dict_ values, if so, rename them with their key values. Desired ou...
Rename df column name with dictionary key in Python
I have the following df and dict: df = pd.DataFrame({'a':[1,2,3,4], 'x':[11,12,13,14]}) dict_ = {'new_a':['a','b','c'],'new_x':['x','y','z']} I would like to check if column 'a' and 'x' exist in dict_ values, if so, rename them with their key values. Desired output: df = pd.DataFrame({'new_a':[1,2,3,4], 'new_x':[11,1...
[ "Invert/flatten the dictionary and rename:\nd2 = {k:v for v,l in dict_.items() for k in l}\n# {'a': 'new_a', 'b': 'new_a', 'c': 'new_a',\n# 'x': 'new_x', 'y': 'new_x', 'z': 'new_x'}\n\nout = df.rename(columns=d2)\n\noutput:\n new_a new_x\n0 1 11\n1 2 12\n2 3 13\n3 4 14\n\n" ]
[ 2 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074195764_dictionary_pandas_python.txt
Q: can't find all div classes using beautifulsoup in python I'm trying to extract data from a website. When using developer tools, I can see that the data I am interested in is held in multiple areas all with the same class name (flyers_flyer-col__ZN-6Z) I want to loop through each of these items, and extract inform...
can't find all div classes using beautifulsoup in python
I'm trying to extract data from a website. When using developer tools, I can see that the data I am interested in is held in multiple areas all with the same class name (flyers_flyer-col__ZN-6Z) I want to loop through each of these items, and extract information, specifically the aria label and target href. When I try...
[ "Page is created dynamically by Javascript, based on data existent in a script tag. Here is one way to get that data, using Requests:\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport json\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\n...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074195414_beautifulsoup_python_web_scraping.txt
Q: Unusual behaviour of Python multiprocessing pipe I have two processes where on runs the main loop and the other gets the latest prices with websocket api, these two processes can communicate with a pipe object. so my core process will send a request message to the other process and then will receive a message with...
Unusual behaviour of Python multiprocessing pipe
I have two processes where on runs the main loop and the other gets the latest prices with websocket api, these two processes can communicate with a pipe object. so my core process will send a request message to the other process and then will receive a message with the latest prices. One other thing is that unless the...
[ "It looks like the \"not needed websockets stuff\" is where your processing halts, and would be the ideal point to help you there - no need for them to be complete - but the fixed values in the .send line do not help: you could write a winded down method where you retrieve your values with the methods for I/O your ...
[ 0 ]
[]
[]
[ "multiprocessing", "python", "python_multiprocessing" ]
stackoverflow_0074195388_multiprocessing_python_python_multiprocessing.txt
Q: How do i get the document id in Marqo? i added a document to marqo add_documents() but i didn't pass an id and now i am trying to get the document but i don't know what the document_id is? Here is what my code look like: mq = marqo.Client(url='http://localhost:8882') mq.index("my-first-index").add_documents([ ...
How do i get the document id in Marqo?
i added a document to marqo add_documents() but i didn't pass an id and now i am trying to get the document but i don't know what the document_id is? Here is what my code look like: mq = marqo.Client(url='http://localhost:8882') mq.index("my-first-index").add_documents([ { "Title": title, "Descript...
[ "if you don't add the \"_id\" as part of key/value then by default marqo will generate a random id for you, to access it you can search the document using the document's Title,\ndoc = mq.index(\"my-first-index\").search(title_of_your_document, searchable_attributes=['Title'])\n\nyou should get a dictionary as the r...
[ 1 ]
[]
[]
[ "artificial_intelligence", "python", "python_3.x", "search" ]
stackoverflow_0074195574_artificial_intelligence_python_python_3.x_search.txt
Q: Working Poetry project with private dependencies inside Docker I have a Python library hosted in Google Cloud Platform Artifact Registry. Besides, I have a Python project, using Poetry, that depends on the library. This is my project file pyproject.toml: [tool.poetry] name = "Test" version = "0.0.1" description = ...
Working Poetry project with private dependencies inside Docker
I have a Python library hosted in Google Cloud Platform Artifact Registry. Besides, I have a Python project, using Poetry, that depends on the library. This is my project file pyproject.toml: [tool.poetry] name = "Test" version = "0.0.1" description = "Test project." authors = [ "Me <me@mycompany.com>" ] [tool.poe...
[ "You are using ${GOOGLE_APPLICATION_CREDENTIALS} in your dockerfile command but you have not defined it anywhere in the Dockerfile using ENV or ARG.\nFor example in your Dockerfile in this section\nRUN wget -q https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-${GCLOUD_VERSION}.tar.gz && \\...
[ 0, 0 ]
[]
[]
[ "gcloud", "google_artifact_registry", "python", "python_keyring", "python_poetry" ]
stackoverflow_0074106823_gcloud_google_artifact_registry_python_python_keyring_python_poetry.txt
Q: Every Nth Element In Convolution Is there a faster way to do np.convolve(A, B)[::N] using Numpy? It feels wasteful to compute all the convolutions and then throw N - 1 of N away... I could do a for loop or list comprehension, but I thought it would be faster to use only native Numpy methods. EDIT Or does Numpy d...
Every Nth Element In Convolution
Is there a faster way to do np.convolve(A, B)[::N] using Numpy? It feels wasteful to compute all the convolutions and then throw N - 1 of N away... I could do a for loop or list comprehension, but I thought it would be faster to use only native Numpy methods. EDIT Or does Numpy do lazy evaluation? I just saw this fr...
[ "A convolution is a product of your kernel and a window on your array, then the sum. You can achieve the same manually using a rolling window:\nFirst let's see a dummy example\nA = np.arange(30)\nB = np.ones(6)\nN = 3\n\nout = np.convolve(A, B)[::N]\nprint(out)\n\noutput: [ 0. 6. 21. 39. 57. 75. 93. 111. 12...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074194822_numpy_python.txt
Q: Python List of Functions without Executing I'm working on a Python project, and part of it is where it chooses a function from random via list. Unfortunately, when it's declaring the list, its executing the function. Is there a way to have a list of functions without them executing? Here's example code: import ran...
Python List of Functions without Executing
I'm working on a Python project, and part of it is where it chooses a function from random via list. Unfortunately, when it's declaring the list, its executing the function. Is there a way to have a list of functions without them executing? Here's example code: import random def a(): global var var = 1 def b(): g...
[ "You need to store the functions themselves, not the results of calling them.\nlist = [a, b]\n\n" ]
[ 3 ]
[]
[]
[ "list", "python", "random" ]
stackoverflow_0074195907_list_python_random.txt
Q: Django distinct selection i have this model: class Person: first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) sexe = models.TextChoices('M', 'F') arrival_date = models.DateField(max_length=30) reason = models.CharField(max_length=30) It turns out that the ...
Django distinct selection
i have this model: class Person: first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) sexe = models.TextChoices('M', 'F') arrival_date = models.DateField(max_length=30) reason = models.CharField(max_length=30) It turns out that the same person can be registered s...
[ "you can get data in this way:\nPerson.objects.values_list('first_name', 'last_name', 'sexe').distinct()\n\n", "for mysql\nPerson.objects.filter(positive = 1).order_by().values('first_name').distinct()\n\nfor Postgre:\nPerson.objects.order_by('first_name').distinct('first_name')\n\nDocumentation Here\n" ]
[ 1, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074194091_django_django_views_python.txt