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 check if in a string of words all the words start with the same letter With a list like: 'apple,and,as' All the words start with the same letter. If this is the case, I would like to return true and if not return false. How can I do that? A is just the example!! I need to check if the words begin in every r...
How to check if in a string of words all the words start with the same letter
With a list like: 'apple,and,as' All the words start with the same letter. If this is the case, I would like to return true and if not return false. How can I do that? A is just the example!! I need to check if the words begin in every random same letter I'm a Beginner.
[ "You can split the string into a list, then use a list comprehension to check if each word starts with 'a'. Then use the all function on the resulting list to see if they're all True.\nwords = 'apple,and,as'\nprint(all([word.startswith('a') for word in words.split(',')]))\n\n", "Simply add the first letter of eac...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074142183_python.txt
Q: Updating multiple entries in a notion database with API I have a notion database which I call with the API like so: url = f"https://api.notion.com/v1/databases/{NotionDB}/query" payload = {"page_size": 200} headers = { "Authorization": NotionKEY, "accept": "application/json", "Notion-Versio...
Updating multiple entries in a notion database with API
I have a notion database which I call with the API like so: url = f"https://api.notion.com/v1/databases/{NotionDB}/query" payload = {"page_size": 200} headers = { "Authorization": NotionKEY, "accept": "application/json", "Notion-Version": "2022-06-28", "content-type": "application/js...
[ "According to Notion support this is not possible. The feature has been requested but is not available on Oct. 20th 2022.\n" ]
[ 0 ]
[]
[]
[ "json", "notion", "notion_api", "python" ]
stackoverflow_0073826652_json_notion_notion_api_python.txt
Q: Python CanOpen canGetNumberOfChannels not defined | kvaser canlib is unavailable i tried to run my Python Program on my Linux maschine but when i try to run it it is having a hard time finding all the nessasary modules needed for it to work. i installed CanOpen to my project import threading import sys sys.path.a...
Python CanOpen canGetNumberOfChannels not defined | kvaser canlib is unavailable
i tried to run my Python Program on my Linux maschine but when i try to run it it is having a hard time finding all the nessasary modules needed for it to work. i installed CanOpen to my project import threading import sys sys.path.append('venv/Lib/site-packages') sys.path.append('venv/Lib/site-packages/can/interfaces...
[ "You have to install the canlib on your machine as well. Right now, you just have installed the SDK. If you are running on linux you have to install libcanlib.so on your machine. Take a look at the part that is related to your operating system on this link: https://pypi.org/project/canlib/\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074141418_python.txt
Q: How can I copy a dataframe to my clipboard (or workaround) from Google Colaboratory? I'm building a web scraper for a non-technical user on google colaboratory and want the output of that scraper which is in the form of a pandas dataframe to be "copy pastable" with a single inline command. The execution of df.to_c...
How can I copy a dataframe to my clipboard (or workaround) from Google Colaboratory?
I'm building a web scraper for a non-technical user on google colaboratory and want the output of that scraper which is in the form of a pandas dataframe to be "copy pastable" with a single inline command. The execution of df.to_clipboard() results in the following error: /usr/local/lib/python3.6/dist-packages/pandas/c...
[ "Got the answer!\nNot intuitive but located in Google's Colab documentation:\nfrom google.colab import files\n\nwith open('example.csv', 'w') as f:\n f.write(df.to_csv())\n\nfiles.download('example.csv')\n\n", "you can use this library: https://github.com/scwilkinson/pd-replicator which implements HTML clipboard...
[ 2, 2 ]
[]
[]
[ "google_colaboratory", "pandas", "pyperclip", "python" ]
stackoverflow_0058687491_google_colaboratory_pandas_pyperclip_python.txt
Q: Python - Add string after a word in a specific line of a file I need to add string after a word in a specific line of a text file. The original file is: line 1: value1 line 2: value2 line 3: value3 line 4: value4 line 5: value5 For example, I want to add "NAME" in the line number 3 just after "line" so the file w...
Python - Add string after a word in a specific line of a file
I need to add string after a word in a specific line of a text file. The original file is: line 1: value1 line 2: value2 line 3: value3 line 4: value4 line 5: value5 For example, I want to add "NAME" in the line number 3 just after "line" so the file would become: line 1: value1 line 2: value2 line NAME 3: value3 line...
[ "This looks for line that starts with “line 3:” and edits just this line, retains the rest as is, and writes the text to a new file.\nwith open('f1.txt', 'r') as f:\n lines = []\n for line in f:\n if line.startswith(\"line 3:\"):\n split_line = line.split()\n split_line.insert(spl...
[ 4, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0046582683_python.txt
Q: Send file using POST from a Python script Is there a way to send a file using POST from a Python script? A: From: https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file Requests makes it very simple to upload Multipart-encoded files: with open('report.xls', 'rb') as f: r = r...
Send file using POST from a Python script
Is there a way to send a file using POST from a Python script?
[ "From: https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file\nRequests makes it very simple to upload Multipart-encoded files:\nwith open('report.xls', 'rb') as f:\n r = requests.post('http://httpbin.org/post', files={'report.xls': f})\n\nThat's it. I'm not joking - this is one...
[ 244, 30, 5, 4, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "file_upload", "http_post", "post", "python" ]
stackoverflow_0000068477_file_upload_http_post_post_python.txt
Q: How to process Vector of probability with UDF in Pyspark? I have a column with vectors like: {"vectorType": "dense", "length": 7, "values": [0.6514390482520993, 0.195419935311166, 0.07402558401796841, 0.032660728394633604, 0.01775634445896352, 0.009769471437190208, 0.018928888127979045]} and I would like to creat...
How to process Vector of probability with UDF in Pyspark?
I have a column with vectors like: {"vectorType": "dense", "length": 7, "values": [0.6514390482520993, 0.195419935311166, 0.07402558401796841, 0.032660728394633604, 0.01775634445896352, 0.009769471437190208, 0.018928888127979045]} and I would like to create a UDF function to process this probabilities like so: @udf("i...
[ "I just found out that I have to use .item to access parts of a vector\nlike so:\n@udf(\"integer\")\ndef process_probability(x):\n vector_values = x.values\n if vector_values.item(0) > 0.65: return 0\n elif vector_values.item(1) > 0.198: return 1\n elif vector_values.item(2) > 0.08: return 2\n elif vector_valu...
[ 0 ]
[]
[]
[ "dataframe", "pyspark", "python", "user_defined_functions" ]
stackoverflow_0074142522_dataframe_pyspark_python_user_defined_functions.txt
Q: SQLAlchemy. Creating tables that share enum Models FacebookPost and TwitterPost share an enum called types. This enum is correctly created when creating facebook_posts table, but when trying to create twitter_posts table, there is an attempt to recreate this type which results in an error. sqlalchemy.exc.Programmi...
SQLAlchemy. Creating tables that share enum
Models FacebookPost and TwitterPost share an enum called types. This enum is correctly created when creating facebook_posts table, but when trying to create twitter_posts table, there is an attempt to recreate this type which results in an error. sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) type "types"...
[ "The generic Enum class does not offer any control over emitting the CREATE TYPE statement. But a PostgreSQL-specific alternative ENUM has a parameter create_type which can be used to disable it:\nfrom sqlalchemy.dialects.postgresql import ENUM\n\n\nclass TwitterPost(Base):\n ...\n type = Column(\"type\", ENU...
[ 23, 6, 5, 0 ]
[]
[]
[ "enums", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0039023877_enums_postgresql_python_sqlalchemy.txt
Q: How can I copy to the clipboard the output of a cell in a Jupyter notebook? How can I copy to the clipboard the output of a cell in a Jupyter notebook, without having to select it with drag-and-drop? A: Jupyter notebook runs in browser so you can use some javascript to select and copy cells to clipboard. After s...
How can I copy to the clipboard the output of a cell in a Jupyter notebook?
How can I copy to the clipboard the output of a cell in a Jupyter notebook, without having to select it with drag-and-drop?
[ "Jupyter notebook runs in browser so you can use some javascript to select and copy cells to clipboard. After some trial and error I came up with this bookmarklet:\njavascript:(function%20()%20%7B%20function%20SelectText(element)%20%7B%20var%20range%3B%20var%20selection%3B%20if%20(document.body.createTextRange)%20%...
[ 30, 19, 16, 2, 1, 1, 0, 0 ]
[]
[]
[ "clipboard", "jupyter_notebook", "python" ]
stackoverflow_0044229820_clipboard_jupyter_notebook_python.txt
Q: Pandas rename columns from a JSON I am reading a JSON with the following contents {"aa": 10, "bb": 20} df = pd.read_json("filename.json", orient='index') print(df) 0 aa 10 bb 20 How can I rename the columns of the data frame to something like "country, value"? A: here is one way about it df.reset_i...
Pandas rename columns from a JSON
I am reading a JSON with the following contents {"aa": 10, "bb": 20} df = pd.read_json("filename.json", orient='index') print(df) 0 aa 10 bb 20 How can I rename the columns of the data frame to something like "country, value"?
[ "here is one way about it\ndf.reset_index(inplace=True)\ncols = ['Country','value']\ndf.columns=cols\ndf\n\n Country value\n0 aa 10\n1 bb 20\n\nOR\n\ncols = [ 'value']\ndf.columns=cols\ndf.rename_axis(columns=['Country'], inplace=True)\n\ndf\n\n\nCountry value\naa 10\nbb 20\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074142644_pandas_python.txt
Q: No module named "panel. pane'; 'panel' is not a package Panel and other holoviz package was working fine. But since yesterday, it is not working and gives following error. I checked the site packages, tried creating cond and venv based virtual environments, but dint help me. Has anyone faced similar issue? Code: f...
No module named "panel. pane'; 'panel' is not a package
Panel and other holoviz package was working fine. But since yesterday, it is not working and gives following error. I checked the site packages, tried creating cond and venv based virtual environments, but dint help me. Has anyone faced similar issue? Code: from panel.pane import PaneBase Error message: ModuleNotFound...
[ "This error:\nModuleNotFoundError: No module named 'panel.pane'; 'panel' is not a package\n\nmay also occur if you have named the main program file you created as panel.py and try to run it as python panel.py or another file has the name panel.py in the same folder from which you run your program. Python will consi...
[ 1 ]
[]
[]
[ "holoviews", "holoviz", "panel", "python" ]
stackoverflow_0073596254_holoviews_holoviz_panel_python.txt
Q: Get current Fiscal date range in python? How can i get the current fiscal date range? Expected output : start_date = '2022-04-01' last_date = '2023-03-31' Please help. Many thanks in advance. A: Did you tried the Fiscalyear Libary? https://pypi.org/project/fiscalyear/ There you can get Info about the Fiscal year...
Get current Fiscal date range in python?
How can i get the current fiscal date range? Expected output : start_date = '2022-04-01' last_date = '2023-03-31' Please help. Many thanks in advance.
[ "Did you tried the Fiscalyear Libary?\nhttps://pypi.org/project/fiscalyear/\nThere you can get Info about the Fiscal year, quarter, month and day\n>>> e = FiscalDateTime.now()\n>>> e\nFiscalDateTime(2017, 4, 8, 20, 30, 31, 105323)\n>>> e.fiscal_year\n2017\n>>> e.fiscal_quarter\n3\n>>> e.next_fiscal_quarter\nFiscalQ...
[ 0 ]
[]
[]
[ "datetime", "fiscal", "python" ]
stackoverflow_0074142696_datetime_fiscal_python.txt
Q: How to change str(nparray) to original nparray with UDP in python I want to build an camera Android app based on OpenCv in Kivy, then send the frame to the server with UDP. The server will use the frame to do something else,but it shoud be nparray. I'm inspired from here. this is my code server import socket impo...
How to change str(nparray) to original nparray with UDP in python
I want to build an camera Android app based on OpenCv in Kivy, then send the frame to the server with UDP. The server will use the frame to do something else,but it shoud be nparray. I'm inspired from here. this is my code server import socket import cv2 import numpy as np HOST = '127.0.0.1' PORT = 5067 s = socket.s...
[ "You can use tobytes to get the image raw data from a numpy array and send it to the server like this:\nimg = np.array([[0, 1], [2, 3]], dtype='uint8') # 2x2 example\ns.sendto(img.tobytes())\n\nOn server side get the image data from the buffer and reshape it to the original shape:\nbuffer, addr = s.recv(2*2) # re...
[ 0 ]
[]
[]
[ "android", "buildozer", "kivy", "opencv", "python" ]
stackoverflow_0074139727_android_buildozer_kivy_opencv_python.txt
Q: Django dump data got module not found error from Allauth and other package After run python manage.py dumpdata > data.json I get this ModuleNotFoundError: No module named 'allauth' and if i comment the allauth in the installed apps i still get another error on another package that might have a data A: You need ...
Django dump data got module not found error from Allauth and other package
After run python manage.py dumpdata > data.json I get this ModuleNotFoundError: No module named 'allauth' and if i comment the allauth in the installed apps i still get another error on another package that might have a data
[ "You need to install it in your environment using pip. You should also add it to your requirements.txt file.\nIf you get more of the same errors, continue to install the missing packages.\nAs per our comments, it turns out that whilst yes, the package was not installed, the ultimate issue was quite specific to your...
[ 1 ]
[]
[]
[ "database", "django", "dump", "modulenotfounderror", "python" ]
stackoverflow_0074142224_database_django_dump_modulenotfounderror_python.txt
Q: tkinter grid layout: empty cells smaller than filled ones? I have a grid layout in tkinter: import tkinter as tk from tkinter import ttk root = tk.Tk() root.geometry('500x500') root.rowconfigure(0, weight = 1) root.rowconfigure(1, weight = 1) root.rowconfigure(2, weight = 1) root.columnconfigure(0, weight = 1) r...
tkinter grid layout: empty cells smaller than filled ones?
I have a grid layout in tkinter: import tkinter as tk from tkinter import ttk root = tk.Tk() root.geometry('500x500') root.rowconfigure(0, weight = 1) root.rowconfigure(1, weight = 1) root.rowconfigure(2, weight = 1) root.columnconfigure(0, weight = 1) root.columnconfigure(1, weight = 1) root.columnconfigure(2, weigh...
[ "\nWhen I measure it I get a default width for filled cells of about 215 while the empty ones only have 165. Is there a reason for this?\n\nThe reason is that empty rows and empty columns have a default size of zero. In your code you're giving a non-zero weight to all columns, so after grid has added the widgets, i...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074142600_python_tkinter.txt
Q: Filter out values that are in a list I have a pandas dataframe that looks like this but with more columns. The values are beside "Department" in a list and are connected like for the first on Jenny is located in New York and is 30 years old: Index Department Team Location Age 0 Accounting [Jenny, Juliet, John, M...
Filter out values that are in a list
I have a pandas dataframe that looks like this but with more columns. The values are beside "Department" in a list and are connected like for the first on Jenny is located in New York and is 30 years old: Index Department Team Location Age 0 Accounting [Jenny, Juliet, John, Mark] [New York, Madrid, Los Angeles,...
[ "you can use a function with lambda and apply:\ndef check (a,b,c): \n if ('Romeo' in a) and ('New York' in b) and (32 in c):\n a.remove('Romeo')\n b.remove('New York')\n c.remove(32)\n \n \ndf['Team','Location','Age']=df.apply(lambda x: check(x['Team'], x['Location'], x['Age']),axis=...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074136013_dataframe_pandas_python.txt
Q: Cannot launch debugger for azure function app in vs code I am trying to debug an azure function app in VSCode using Python in a Windows10 environment. Whenever I launch the debugger it hangs for a long period of time and then opens a message box that says ECONNREFUSED 127.0.0.1:9091 There are a bunch of posts ab...
Cannot launch debugger for azure function app in vs code
I am trying to debug an azure function app in VSCode using Python in a Windows10 environment. Whenever I launch the debugger it hangs for a long period of time and then opens a message box that says ECONNREFUSED 127.0.0.1:9091 There are a bunch of posts about this but none seem helpful/can solve the problem. Here is ...
[ "\nCannot launch debugger for azure function app in VScode-\nECONNREFUSED 127.0.0.1:9091\n\nThis type of generic error may occur for a variety of reasons.\nNeed to check and modify:\n\nFirst and foremost, check whether the versions of Azure functions core tools and Pip are upgraded to the current version:\nTo upgra...
[ 0, 0 ]
[]
[]
[ "azure", "azure_functions", "python", "visual_studio_code" ]
stackoverflow_0074131631_azure_azure_functions_python_visual_studio_code.txt
Q: Get sum of nested JSON I have this JSON data where "logs" is called as another serializer. { "id": 1, "logs": [ { "work_hours": 7, "user": "admin" }, { "work_hours": 8, "user": "admin" }, { "work_hours": 6, ...
Get sum of nested JSON
I have this JSON data where "logs" is called as another serializer. { "id": 1, "logs": [ { "work_hours": 7, "user": "admin" }, { "work_hours": 8, "user": "admin" }, { "work_hours": 6, "user": "admin" ...
[ "I will wager a guess and say you want something like\n User.objects.aggregate(Sum('logs__work_hours'))\n\nOR\nUser.objects.aggregate(hours_worked=Sum('logs__work_hours'))\n\nAnd then it will be accessible on all objects in the queryset as if it was a declared property or field.\n" ]
[ 2 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074142853_django_django_rest_framework_python.txt
Q: Converting a pandas Interval into a string (and back again) I'm relatively new to Python and am trying to get some data prepped to train a RandomForest. For various reasons, we want the data to be discrete, so there are a few continuous variables that need to be discretized. I found qcut in pandas, which seems t...
Converting a pandas Interval into a string (and back again)
I'm relatively new to Python and am trying to get some data prepped to train a RandomForest. For various reasons, we want the data to be discrete, so there are a few continuous variables that need to be discretized. I found qcut in pandas, which seems to do what I want - I can set a number of bins, and it will discre...
[ "Use the labelsargument in qcut and use pandas Categorical.\nEither of those can help you create categories instead of interval for your variable. Then, you can use a form of encoding, for example Label Encoding or Ordinal Encoding to convert the categories (the factors if you're used to R) to numerical values whic...
[ 3, 0 ]
[ "While it may not be the cleanest-looking method, converting a string back into an interval is indeed possible:\nimport pandas as pd\nstr_intervals = [i.replace(\"(\",\"\").replace(\"]\", \"\").split(\", \") for i in str_cuts]\noriginal_cuts = [pd.Interval(float(i), float(j)) for i, j in str_intervals]\n\n" ]
[ -2 ]
[ "binning", "discretization", "pandas", "python", "random_forest" ]
stackoverflow_0057653844_binning_discretization_pandas_python_random_forest.txt
Q: Django error. Cannot assign must be an instance I get the following error when I try to run an insert into one of my tables. Cannot assign "1": "Team.department_id" must be a "Department" instance Admittedly I'm slightly unsure if I'm using the foreign key concept correctly. The insert I'm trying to run and a sn...
Django error. Cannot assign must be an instance
I get the following error when I try to run an insert into one of my tables. Cannot assign "1": "Team.department_id" must be a "Department" instance Admittedly I'm slightly unsure if I'm using the foreign key concept correctly. The insert I'm trying to run and a snippet from my models.py are given below. What I'm tr...
[ "You don't need to pass the department id, the instance itself is enough. The following should work just fine:\nnew_team = Team(\n nickname = team_name,\n employee_id = employee_id,\n department_id = Department.objects.get(password = password, department_name = department_name)\n)\n\nJust a note, don't eve...
[ 71, 11, 0 ]
[]
[]
[ "django", "foreign_keys", "model", "python" ]
stackoverflow_0037839867_django_foreign_keys_model_python.txt
Q: I got an error when using mkdir command with " ! " - Python There is a SyntaxError message when using mkdir command. I already import os library. I want to run !mkdir. I have no idea because I already implemented the correct path format. please kindly help me. import cv2 import time import uuid import os IMAGES_...
I got an error when using mkdir command with " ! " - Python
There is a SyntaxError message when using mkdir command. I already import os library. I want to run !mkdir. I have no idea because I already implemented the correct path format. please kindly help me. import cv2 import time import uuid import os IMAGES_PATH = 'Tensorflow/workspace/images/collectedimages' lables = ['...
[ "Use os module to create directory instead of using shell commands.\nimport os\n \ndirectory = \"<your_directory_name>\"\nparent_dir = \"T:/<parent_directory>/\"\npath = os.path.join(parent_dir, directory)\n \nos.mkdir(path)\n\nprint(\"Directory '% s' created\" % directory)\n\n", "If you are running on windows,...
[ 1, 0 ]
[ "If you are running on windows, then you can use the below code:\nimport cv2 \nimport time\nimport uuid\nimport os\n\nIMAGES_PATH = 'Tensorflow/workspace/images/collectedimages'\n\nlables = ['hello', 'thanks', 'yes', 'no', 'iloveyou']\nnumber_imgs = 15\n\nfor lable in lables:\n\n path = 'Tensorflow\\workspace\\i...
[ -3 ]
[ "python", "tensorflow" ]
stackoverflow_0066983571_python_tensorflow.txt
Q: How to transform excel range (e.g. AA1:BA2) to a [rows,columns] list? I am coding a python function that has as input parameter certain excel range (e.g. "A1:B2"). How can I make python return a list of nº rows and nº columns from here?? (for instance if A1:B2 is the input, this list shall return [2,2]) This is wh...
How to transform excel range (e.g. AA1:BA2) to a [rows,columns] list?
I am coding a python function that has as input parameter certain excel range (e.g. "A1:B2"). How can I make python return a list of nº rows and nº columns from here?? (for instance if A1:B2 is the input, this list shall return [2,2]) This is what I did: def return_rows_columns_from_excel_range(excel_range): # import s...
[ "This is the most straightforward solution that I've come up with:\nimport re\nimport string\ndef return_rows_columns_from_excel_range_v1(excel_range):\n \n def col2num(col):\n # Thx https://stackoverflow.com/a/12640614/8972132\n num = 0\n for c in col:\n if c in string.ascii_l...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074139941_python_python_3.x.txt
Q: MultiIndex (multilevel) column names from Dataframe rows I have a rather messy dataframe in which I need to assign first 3 rows as a multilevel column names. This is my dataframe and I need index 3, 4 and 5 to be my multiindex column names. For example, 'MINERAL TOTAL' should be the level 0 until next item; 'TRAT...
MultiIndex (multilevel) column names from Dataframe rows
I have a rather messy dataframe in which I need to assign first 3 rows as a multilevel column names. This is my dataframe and I need index 3, 4 and 5 to be my multiindex column names. For example, 'MINERAL TOTAL' should be the level 0 until next item; 'TRATAMIENTO (ts)' should be level 1 until 'LEY Cu(%)' comes up. Wh...
[ "You can pass a list of row indexes to the header argument and pandas will combine them into a MultiIndex.\nimport pandas as pd\n\ndf = pd.read_excel('ExcelFile.xlsx', header=[0,1,2])\n\nBy default, pandas will read in the top row as the sole header row. You can pass the header argument into pandas.read_excel() tha...
[ 2, 1 ]
[]
[]
[ "dataframe", "multi_index", "pandas", "python" ]
stackoverflow_0074141417_dataframe_multi_index_pandas_python.txt
Q: Python, pysimplegui, combine Text and ButtonMenu resulting in an array I have a python recipe app utilizing pysimplegui. I want to fill in an ingredient and then have a dropdown for the amount of the ingredient, ie. 2 tbs, 1.5 tbs, 1 tbs, ...etc. Currently my layout is: layout = [ [sg.Text('Name', size=(15,1)...
Python, pysimplegui, combine Text and ButtonMenu resulting in an array
I have a python recipe app utilizing pysimplegui. I want to fill in an ingredient and then have a dropdown for the amount of the ingredient, ie. 2 tbs, 1.5 tbs, 1 tbs, ...etc. Currently my layout is: layout = [ [sg.Text('Name', size=(15,1)), sg.InputText(key='dish_name')], [sg.Text('Ingredient', size=(15,1)),...
[ "Example Code\nimport PySimpleGUI as sg\n\namounts = ['Amount', ['2', '1.5', '1', '.5', '3/4', '1/8']]\n\nlayout = [\n [sg.Text('Name', size=(15,1)), sg.InputText(key='dish_name')],\n [sg.Text('Ingredient', size=(15,1)), sg.InputText(key='ingredient_name')],\n [sg.Text('Amount', size=(15, 1)), sg.InputText...
[ 1 ]
[]
[]
[ "drop_down_menu", "pysimplegui", "python" ]
stackoverflow_0074141898_drop_down_menu_pysimplegui_python.txt
Q: How do a return a subset of a dictionary based on a search string? I have a dictionary with a list of file locations dict1 = {'news1':'link1','news2':'link2','sports1':'link3','weather1':'link4'} Now I want to search for a string and return a new dictionary with only the relevant key value pairs. Something like s...
How do a return a subset of a dictionary based on a search string?
I have a dictionary with a list of file locations dict1 = {'news1':'link1','news2':'link2','sports1':'link3','weather1':'link4'} Now I want to search for a string and return a new dictionary with only the relevant key value pairs. Something like searchstring = 'news' dict2 = if searchstring in dict1 dict2 = {'news1':...
[ "You can this with dictionary comprehension,\nIn [1]: {k:v for k,v in dict1.items() if 'news' in k}\nOut[1]: {'news1': 'link1', 'news2': 'link2'}\n\n", "I assume you are using Python3\ndict2 = dict()\nfor k in dict1.keys():\n if dict1[k] == searchstring:\n dict2[k] = searchstring\n\nNot elegant but sho...
[ 3, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074143060_dictionary_python.txt
Q: How do I use r"\b \b" when replacing text in a file while working with a list? from bs4 import BeautifulSoup as bs import requests import tkinter as tk root = tk.Tk() root.title('Language Filter') root.geometry('500x100+700+200') def rip (): page = requests.get(scriptE.get()) rawscript = bs(page.content...
How do I use r"\b \b" when replacing text in a file while working with a list?
from bs4 import BeautifulSoup as bs import requests import tkinter as tk root = tk.Tk() root.title('Language Filter') root.geometry('500x100+700+200') def rip (): page = requests.get(scriptE.get()) rawscript = bs(page.content, "html.parser") script = rawscript.find('td', class_='scrtext') with open('...
[ "You will need to use regex for this. You can be a bit clever and turn the entire banned list into one big regex. Then you don't need to worry about loops. Since the first argument of sub can either be the replacement string or a function, we can use a lambda to return an asterisk for every character in the match.\...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074142762_list_python.txt
Q: Returning two arrays from a python script in Django and utilizing in Ajax simultaneously I have a python script running in views.py within Django which returns two very large string arrays, x and y. It currently is able to run off a button press within my index.html. def python_file(request): final() retur...
Returning two arrays from a python script in Django and utilizing in Ajax simultaneously
I have a python script running in views.py within Django which returns two very large string arrays, x and y. It currently is able to run off a button press within my index.html. def python_file(request): final() return HttpResponse("ran") The ajax code I have running to do the button press. <script src="http:...
[ "You can add parameters to the ajax.done(function) in order to get what your server returned.\n\n\n $.ajax({\n url: \"/python_file\",\n context: document.body\n }).done(function (response, textStatus, jqXHR) {\n // What happens when the call is successful (200 <= status code <...
[ 0, 0 ]
[]
[]
[ "ajax", "django", "jquery", "python" ]
stackoverflow_0074142510_ajax_django_jquery_python.txt
Q: Why Random Forest Regressor predicts single output for all the time series? I fitted the Random Forest Regressor on my x_train (datetime series) and y_train and it predicted the y_train very well. Here is the initial part that worked: from sklearn.ensemble import RandomForestRegressor regressor=RandomForestRegress...
Why Random Forest Regressor predicts single output for all the time series?
I fitted the Random Forest Regressor on my x_train (datetime series) and y_train and it predicted the y_train very well. Here is the initial part that worked: from sklearn.ensemble import RandomForestRegressor regressor=RandomForestRegressor(n_estimators=25) regressor.fit(x.values.reshape(-1,1),y.reshape(-1,1)) # type...
[ "Help, please!\nEverything is the same but regressor.predict gives different answers!\nSee picture below\nThe only thing I can think of is that I used x to fit the regressor. Is it the reason that it works for x but not for x_23?\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "pandas", "python", "regression", "scikit_learn" ]
stackoverflow_0074118889_machine_learning_pandas_python_regression_scikit_learn.txt
Q: How can I add conditional logic to fill certain rows of a dataframe with certain strings when certain conditions are met? I am trying to write some Python logic to fill a csv file/pandas dataframe table called (table) with certain conditions, but I can't seem to get it to do what I want. I have two columns in tabl...
How can I add conditional logic to fill certain rows of a dataframe with certain strings when certain conditions are met?
I am trying to write some Python logic to fill a csv file/pandas dataframe table called (table) with certain conditions, but I can't seem to get it to do what I want. I have two columns in table: 1. trade_type and 2. execution_venue. Conditional statement I want to write in Python: The execution_venue entry will only b...
[ "Lets use replace for substitution of old values where trade_type os DARK\nd = {'AQXE': 'XUBS', 'AQEU': 'AQED'}\ntable.loc[table['trade_type'] == 'DARK', 'execution_venue'] = table['execution_venue'].replace(d)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074143034_dataframe_pandas_python.txt
Q: color current value cell dataframe I'm looking how I can color in red the current value cell when this value is above the 3sigma+ value please ? I did not succeed with the df.apply() method... If anyone have a simple method, this is welcome. I want to color only the current value cell based on the value of avg cel...
color current value cell dataframe
I'm looking how I can color in red the current value cell when this value is above the 3sigma+ value please ? I did not succeed with the df.apply() method... If anyone have a simple method, this is welcome. I want to color only the current value cell based on the value of avg cell. For example, for the first column, th...
[ "Try subset argument\ndef color(score):\n return [f\"background-color:\" + (\" red;\" if score.item() < test.loc['3sigma+', score.name] else \"green\")]\n\ns = test.style.apply(color, subset=('current value', slice(None)))\n\ns.to_html('74143101.html')\n\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python", "styles" ]
stackoverflow_0074143101_pandas_python_styles.txt
Q: Avoiding script crash - gspread Recently I had to run a pretty long script using gspread. The script runs for more than one hour and updates many worksheets. Because it runs for so long, I am encountering two errors, that don't appear for regular scripts that run for up to 3 minutes or something like that. gspread...
Avoiding script crash - gspread
Recently I had to run a pretty long script using gspread. The script runs for more than one hour and updates many worksheets. Because it runs for so long, I am encountering two errors, that don't appear for regular scripts that run for up to 3 minutes or something like that. gspread.exceptions.APIError: {'code': 429, '...
[ "recently a new Client has been introduced, the BackOffClient it can be passed to one of the 2 functions: gspread.auth.oauth and gspread.auth.service_account in order to use that client instead of the regular one.\nThat client will check the API return code and sleep each time you reach the quota. If the sleep it n...
[ 1 ]
[]
[]
[ "google_sheets_api", "gspread", "python", "python_3.x" ]
stackoverflow_0074109617_google_sheets_api_gspread_python_python_3.x.txt
Q: Purpose of `numpy.log1p( )`? I just came across one of these Kernels and couldn't understand what does numpy.log1p() do in the third pipeline of this code (House Prediction dataset in Kaggle). Numpy documentation said   Returns:   - An array with natural logarithmic value of x + 1   - where x belongs to all elemen...
Purpose of `numpy.log1p( )`?
I just came across one of these Kernels and couldn't understand what does numpy.log1p() do in the third pipeline of this code (House Prediction dataset in Kaggle). Numpy documentation said   Returns:   - An array with natural logarithmic value of x + 1   - where x belongs to all elements of input array. What is the pur...
[ "The NumPy docs give a hint:\n\nFor real-valued input, log1p is accurate also for x so small that 1 + x == 1 in floating-point accuracy.\n\nSo for example let's add a tiny non-zero number and 1.0. Rounding errors make it a 1.0.\n>>> 1e-100 == 0.0\nFalse\n>>> 1e-100 + 1.0 == 1.0\nTrue\n\nIf we try to take the log of...
[ 66, 11, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0049538185_numpy_python.txt
Q: how to find index of a string inside the string Hey (bad english) so i am working on a function that is going to check if a string1 is inside another string2. i do belive i have accomplished this, but after that, i am trying to find the index of where the string2 was found in the string1. if the string is not in t...
how to find index of a string inside the string
Hey (bad english) so i am working on a function that is going to check if a string1 is inside another string2. i do belive i have accomplished this, but after that, i am trying to find the index of where the string2 was found in the string1. if the string is not in the string at all it will return (-1). i have tried go...
[ "Apparently you have a small logic problem.\nWhen you use contains_string(str1,str2), you want to see if for example \"Ron\" is in \"Ronaldo'. But you are checking this:\nif str1 in str2:\n\nThis is basically saying is \"Ronaldo\" in \"Ron\" which is false.\nThus, you'll only need to change that line\nif str2 in st...
[ 0 ]
[]
[]
[ "if_statement", "python", "string" ]
stackoverflow_0074143121_if_statement_python_string.txt
Q: Bokeh & CustomJS: integrate HoverTool + CustomJS with TapTool This is part of a series of questions related to this project: I have a dataset with 5000+ (x,y) coordinates divvied up into 1300+ groups. Using bokeh and its HoverTool function, I can plot the points and make it such that, when I hover over a given poi...
Bokeh & CustomJS: integrate HoverTool + CustomJS with TapTool
This is part of a series of questions related to this project: I have a dataset with 5000+ (x,y) coordinates divvied up into 1300+ groups. Using bokeh and its HoverTool function, I can plot the points and make it such that, when I hover over a given point, line segments appear between that point and every other point i...
[ "Okay, a guy at work helped me out immensely: according to the documentation, when you use the HoverTool(callback) parameter, cb_data contains an index field. However, when you use the TapTool(callback) parameter, cb_data doesn't contain that field. Instead, the indices are accessed through the cb_obj object:\n# im...
[ 0 ]
[]
[]
[ "bokeh", "javascript", "python" ]
stackoverflow_0074073301_bokeh_javascript_python.txt
Q: Access Denied When running FastAPI I have just started working with FastAPI, but quickly hitting an issue. Tried running a sample code on the FastAPI website, but got access denied error. I'm on Windows, and have access to the all the folders - so not sure why the error message. I would appreciate if someone can h...
Access Denied When running FastAPI
I have just started working with FastAPI, but quickly hitting an issue. Tried running a sample code on the FastAPI website, but got access denied error. I'm on Windows, and have access to the all the folders - so not sure why the error message. I would appreciate if someone can help please, thanks. I have included a li...
[ "In windows when opening CMD choose run as administrator.\n" ]
[ 0 ]
[]
[]
[ "fastapi", "python" ]
stackoverflow_0074140626_fastapi_python.txt
Q: How to fast pagination csv dataset data in any language I have a dataset in csv (comma separated value) format. want to page 40 000 rows. Is there a tool which satisfies this request? Or How can I do in python3? A: there is a python library called https://vaex.io/ which is for parsing millions of data. It's for ...
How to fast pagination csv dataset data in any language
I have a dataset in csv (comma separated value) format. want to page 40 000 rows. Is there a tool which satisfies this request? Or How can I do in python3?
[ "there is a python library called https://vaex.io/ which is for parsing millions of data.\nIt's for when it takes a long time or you get blocked by pandas.\nA dataset of 50,000 rows and 40 columns takes me 7s with pandas. I don't think it's much\n" ]
[ 0 ]
[]
[]
[ "csv", "dataset", "python" ]
stackoverflow_0074142425_csv_dataset_python.txt
Q: swapping upper and lower with ASCII values and incorporating numbers I want to swap upper and lower case letters with each other using ASCII values. The swapping of the letters works but the numbers get dropped. How can I use this same method without altering the numbers in the string. # input the sentance def g...
swapping upper and lower with ASCII values and incorporating numbers
I want to swap upper and lower case letters with each other using ASCII values. The swapping of the letters works but the numbers get dropped. How can I use this same method without altering the numbers in the string. # input the sentance def get_sentence(): sentence = input("Please input the sentence:") word...
[ "Just use else: and ans += s so only ascii will change others remain same.\nelse :\n ans += s\n\nRemove unwanted lines elif ord(s) >= 60 and ord(s) <= 71: and ans = chr(order(s)).\nFull code:\ndef get_sentence():\n sentence = input(\"Please input the sentence:\")\n words = sentence.split(' ')\n sentence =...
[ 0, 0, 0 ]
[]
[]
[ "ascii", "lowercase", "python", "swap", "uppercase" ]
stackoverflow_0074143211_ascii_lowercase_python_swap_uppercase.txt
Q: Create nested dictionary with loop I would like to build the nested function looks like this. test = {} test[0] = {} test[0][1] = {} test[0][1][2] = {} test result {0: {1: {2: {}}}} Is there any way to create one with for loop? Thank you very much. A: You can try building the dict starting from the inner most ...
Create nested dictionary with loop
I would like to build the nested function looks like this. test = {} test[0] = {} test[0][1] = {} test[0][1][2] = {} test result {0: {1: {2: {}}}} Is there any way to create one with for loop? Thank you very much.
[ "You can try building the dict starting from the inner most part:\noutput = {}\nfor x in [2, 1, 0]:\n output = {x: output}\n\nprint(output) # {0: {1: {2: {}}}}\n\nTo build it from the outer most layer, you can consider a temporary \"pointer\" for sub-dicts:\noutput = subdict = {}\n\nfor x in [0, 1, 2]:\n subd...
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074143318_python_python_3.x.txt
Q: Add custom labels to seaborn color palette import matplotlib.pyplot as plt import seaborn as sns low = '#00FF00' medium = '#FFFF00' high = '#FF0000' plt.figure(figsize=(1,2)) sns.color_palette("blend:#00FF00,#FFFF00,#FF0000",as_cmap=True) The result that I get is: But the labels are "under, bad, over". Not su...
Add custom labels to seaborn color palette
import matplotlib.pyplot as plt import seaborn as sns low = '#00FF00' medium = '#FFFF00' high = '#FF0000' plt.figure(figsize=(1,2)) sns.color_palette("blend:#00FF00,#FFFF00,#FF0000",as_cmap=True) The result that I get is: But the labels are "under, bad, over". Not sure from where it is pulling it, is there a way ...
[ "Using appropriate grid of subplots, we can create the expected figure. However, it involves fine adjustments to the plot size and grid size to really get the expected result:\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sns\n\nlow = '#00FF00'\nmedium = '#FFFF00'\nhigh = '#FF0000'\n...
[ 1 ]
[]
[]
[ "python", "seaborn", "visualization" ]
stackoverflow_0074141445_python_seaborn_visualization.txt
Q: looping over a list and define dataframe using the list element in Python I have a list of names. for each name, I start with my dataframe df, and use the elements in the list to define new columns for the df. after my data manipulation is complete, I eventually create a new data frame whose name is partially deri...
looping over a list and define dataframe using the list element in Python
I have a list of names. for each name, I start with my dataframe df, and use the elements in the list to define new columns for the df. after my data manipulation is complete, I eventually create a new data frame whose name is partially derived from the list element. list = ['foo','bar'] for x in list : df = prio...
[ "IIUC, you only want the filenames, i.e. the stored parquet files to have the foo and bar markers, and you can reuse the variable name itself.\nlist = ['foo','bar']\nfor x in list :\n df = prior_df\n (long code for manipulating df)\n df.to_parquet(f'new_df_{x}.parquet')\n del df\n\nnew_df_foo = ...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074142650_pandas_python.txt
Q: Pytest: Mock every invocation of a method for an entire test module? I have a Python class, and for one of the methods of the class, I want every test that calls the method to call a mocked version of the method. For example, if I have this class: class TestClass: def func(): print("func") And these te...
Pytest: Mock every invocation of a method for an entire test module?
I have a Python class, and for one of the methods of the class, I want every test that calls the method to call a mocked version of the method. For example, if I have this class: class TestClass: def func(): print("func") And these tests (using pytest): def test_1(): myTestObj1 = TestClass() myTestO...
[ "You can patch func using pytest-mock from inside the test.\nhttps://pytest-mock.readthedocs.io/en/latest/\nimport pytest\n\nclass TestClass:\n def func(self):\n return \"Func\"\n\n@pytest.fixture(scope=\"function\")\ndef class_fixture():\n yield TestClass() \n\ndef test_1(class_fixture, mocker):\...
[ 0 ]
[]
[]
[ "mocking", "pytest", "python" ]
stackoverflow_0074128749_mocking_pytest_python.txt
Q: ModuleNotFoundError: No module named 'tinkoff.invest'; 'tinkoff' is not a package I have trouble with tinkoff API 2.0. Venv does not see tinkoff-investments, but it was installed successfully. What did I try: downgrade from 3.10 to 3.8 python version update from 3.10 to 3.10.7 deleted and installed module tinkoff...
ModuleNotFoundError: No module named 'tinkoff.invest'; 'tinkoff' is not a package
I have trouble with tinkoff API 2.0. Venv does not see tinkoff-investments, but it was installed successfully. What did I try: downgrade from 3.10 to 3.8 python version update from 3.10 to 3.10.7 deleted and installed module tinkoff-investments CODE: image from tinkoff.invest import Client TOKEN = 'my_token' with C...
[ "This error:\nModuleNotFoundError: No module named 'tinkoff.invest'; 'tinkoff' is not a package\n\nmay also occur if you have named the main program file you created as tinkoff.py and try to run it as python tinkoff.py or another file has the name tinkoff.py in the same folder from which you run your program. Pytho...
[ 0 ]
[]
[]
[ "modulenotfounderror", "python" ]
stackoverflow_0073678018_modulenotfounderror_python.txt
Q: Disable a button after it is clicked on discord.py I am trying to disable the "Next" button after it has been clicked once. When a user clicks on "Next", the bot replies to itself with the next page of the weekly tasks. global WEEK_NUM next_button = interactions.Button( style=interactions.ButtonStyle.PRIMARY,...
Disable a button after it is clicked on discord.py
I am trying to disable the "Next" button after it has been clicked once. When a user clicks on "Next", the bot replies to itself with the next page of the weekly tasks. global WEEK_NUM next_button = interactions.Button( style=interactions.ButtonStyle.PRIMARY, label="Next", custom_id="next", disabled = ...
[ "You could try this one:\nI've used this with the discord.py but I am not sure if it's the same as in interactions.py\nnext_button.disabled = True\nawait ctx.send(embeds = embeds1, ephermeral=False, components=next_button)\n\n", "I recommend using interactions.py's official wait_for extension. Wait for a button p...
[ 0, 0 ]
[]
[]
[ "button", "discord", "discord.py", "discord_interactions", "python" ]
stackoverflow_0073792776_button_discord_discord.py_discord_interactions_python.txt
Q: How to generate all mutan with X number of mutation for a given RNA sequence I want to find all the possible mutan from a DNA / RNA sequence with x mutation. I made the code for getting all the mutant with 1 mutation, but I don't know how to generalise it for x number of mutation. def generateAllMutan(baseSeq): ...
How to generate all mutan with X number of mutation for a given RNA sequence
I want to find all the possible mutan from a DNA / RNA sequence with x mutation. I made the code for getting all the mutant with 1 mutation, but I don't know how to generalise it for x number of mutation. def generateAllMutan(baseSeq): base= ["A", "T", "C", "G"] mutantList = [] for i in range(len(baseSeq)):...
[ "Try comparing against the specified number of matches: n\ndef function(s, n):\n for x in range(len(s)):\n for a in b:\n if a != s[x] and count <= n:\n #code\n count +=1\n\n" ]
[ 0 ]
[]
[]
[ "bioinformatics", "biopython", "mutation", "python" ]
stackoverflow_0074137419_bioinformatics_biopython_mutation_python.txt
Q: python manage.py makemigrations django doesn't create all the fields I have one question when I am doing python manage.py makemigrations django doesn't create all the fields for the Todo Model, please help what's wrong here? class Todo(models.Model): task = models.CharField(max_length=255) title = models...
python manage.py makemigrations django doesn't create all the fields
I have one question when I am doing python manage.py makemigrations django doesn't create all the fields for the Todo Model, please help what's wrong here? class Todo(models.Model): task = models.CharField(max_length=255) title = models.CharField(max_length=100), _date = models.CharField(max_length=100),...
[ "python3 manage.py makemigrations\nand\npython3 manage.py migrate\n", "It worked after removing , in Todo model.\nclass Todo(models.Model):\n task = models.CharField(max_length=255)\n title = models.CharField(max_length=100)\n _date = models.CharField(max_length=100)\n categories = models.CharField(max_le...
[ 2, 1 ]
[ "Create an __init__.py file in the migrations/ directory.\n" ]
[ -1 ]
[ "django", "django_migrations", "django_models", "djongo", "python" ]
stackoverflow_0066443957_django_django_migrations_django_models_djongo_python.txt
Q: No module named 'paho.mqtt'; 'paho' is not a package resolved I have set up a conda environment with anaconda, with python 3.9 and paho-mqtt 1.6.1. I have also tested an Environment that worked for someone else but it doesn't work on my System. Other packages work, like numpy. The code fails at the first row impor...
No module named 'paho.mqtt'; 'paho' is not a package
resolved I have set up a conda environment with anaconda, with python 3.9 and paho-mqtt 1.6.1. I have also tested an Environment that worked for someone else but it doesn't work on my System. Other packages work, like numpy. The code fails at the first row import paho.mqtt.client as mqtt wit the error ModuleNotFoundErr...
[ "This error:\nModuleNotFoundError: No module named 'paho.mqtt'; 'paho' is not a package\n\nmay also occur if you have named the main program file you created as paho.py and try to run it as python paho.py or another file has the name paho.py in the same folder from which you run your program. Python will consider y...
[ 1 ]
[]
[]
[ "paho", "python" ]
stackoverflow_0073799752_paho_python.txt
Q: neural network from scratch in python using sigmoid activation i am new to python,trying to learn machine learning in python.i have tried to write a neural network from scratch with one hidden layer on the famous iris dataset.this is a three class classifier with out put as one hot vectors.i have also taken help f...
neural network from scratch in python using sigmoid activation
i am new to python,trying to learn machine learning in python.i have tried to write a neural network from scratch with one hidden layer on the famous iris dataset.this is a three class classifier with out put as one hot vectors.i have also taken help from already written algos for help.for instance i used the same trai...
[ "In Python range generates a tuple of numbers from x to y with range(x, y). If you generate something like range(10) then it is the same as (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). Lists in Python need an integer index such as list[0] or list[4], not list[0, 4], however, there is a built-in thing in Python that allows acces...
[ 0, 0 ]
[]
[]
[ "iris_recognition", "kaggle", "neural_network", "numpy", "python" ]
stackoverflow_0044830975_iris_recognition_kaggle_neural_network_numpy_python.txt
Q: How to change the default loading icon in a Python flet app? I am building a graphical user interface using flet in python. However, I am stuck with the default flet logo while loading the app in the browser viewer, and I don't see any hints about changing it in the documentation. Is this possible? A: Create a ...
How to change the default loading icon in a Python flet app?
I am building a graphical user interface using flet in python. However, I am stuck with the default flet logo while loading the app in the browser viewer, and I don't see any hints about changing it in the documentation. Is this possible?
[ "Create a folder in your root directory named assets.\nInside place your logo named favicon.png\nFinally, point flet to your assets folder\nflet.app(target=main, assets_dir=\"assets\", view=flet.WEB_BROWSER)\n\n\nAdditionally, check here how to add your own manifest\n\n" ]
[ 1 ]
[]
[]
[ "icons", "python", "web_applications" ]
stackoverflow_0073540154_icons_python_web_applications.txt
Q: How to add duplicate columns together after converting from excel to json in python? I have excel file in the format : Name Question Answer N1 Q1 a1 N2 Q2 a2 N3 Q3 a3 N4 Q4 a4 N3 Q5 a3 Here some name are same and their correspondings answers are also same. I want to convert this into json in the format wher...
How to add duplicate columns together after converting from excel to json in python?
I have excel file in the format : Name Question Answer N1 Q1 a1 N2 Q2 a2 N3 Q3 a3 N4 Q4 a4 N3 Q5 a3 Here some name are same and their correspondings answers are also same. I want to convert this into json in the format where all the columns with same name are merged. { { "name":"N1", "exam...
[ "The problem in your code is you are iterating through a set of items and at every iteration you should check the previous items to see if your current element is already present. You can avoid this problem if you use an initially empty dictionary d storing key, value pairs in the form d[name] = {\"exampleSentences...
[ 0 ]
[]
[]
[ "excel", "json", "python", "python_3.x" ]
stackoverflow_0074110064_excel_json_python_python_3.x.txt
Q: How do I read in a txt file as a dictionary in Python? I have a txt file that is of the following format (dictionary format): {'EX1':'No Information Stored', 'EX2':'Foundation', 'EX3':'Foundation', 'EX4':'No Information Stored'} Does anyone know how I would go about reading this into python to be able to use it ...
How do I read in a txt file as a dictionary in Python?
I have a txt file that is of the following format (dictionary format): {'EX1':'No Information Stored', 'EX2':'Foundation', 'EX3':'Foundation', 'EX4':'No Information Stored'} Does anyone know how I would go about reading this into python to be able to use it like the dictionary that it is?
[ "import json\n\nwith open('file.txt', 'r') as w:\n data = w.read()\n data_as_dict = json.loads(data)\n\n\n", "Text file with this structure are JSON, so you can use the json module.\nimport json\n\ndef load_file(filename):\n with open(filename) as f:\n data = json.load(f)\n return data\n\nThi...
[ 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "python", "txt" ]
stackoverflow_0074143321_dictionary_python_txt.txt
Q: Dataframe - find last time of the day, grouped by day I have a simple dataframe with datetime and their date df = pd.DataFrame( [['2021-01-01 10:10', '2021-01-01'], ['2021-01-03 13:33', '2021-01-03'], ['2021-01-03 14:44', '2021-01-03'], ['2021-01-07 17:17...
Dataframe - find last time of the day, grouped by day
I have a simple dataframe with datetime and their date df = pd.DataFrame( [['2021-01-01 10:10', '2021-01-01'], ['2021-01-03 13:33', '2021-01-03'], ['2021-01-03 14:44', '2021-01-03'], ['2021-01-07 17:17', '2021-01-07'], ['2021-01-07 07:07', ...
[ "You are probably looking for transform which will return the result to every row in the group.\ndf['eod'] = df.groupby('date').transform('last')\n\nOutput\n datetime date eod\n0 2021-01-01 10:10 2021-01-01 2021-01-01 10:10\n1 2021-01-03 13:33 2021-01-03 2021-01-03 14:44\n2 202...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074143380_dataframe_pandas_python.txt
Q: Python Selenium - Constantly changing web element ID I'm trying to use Selenium to find a web element that I know is the To field in a web email application (please see picture). I am able to successfully identify this web element and use send_keys to send an email address to this field. However, the issue is the ...
Python Selenium - Constantly changing web element ID
I'm trying to use Selenium to find a web element that I know is the To field in a web email application (please see picture). I am able to successfully identify this web element and use send_keys to send an email address to this field. However, the issue is the id always seems to cycle between 299 and 3 other numbers l...
[ "Since the ID attribute is changing, you have to build your locator on some other, stable parameter. The following CSS Selector is stable:\nto_field = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, \".s-compose-to textarea\")))\nprint(to_field)\nto_field.send_keys(email_reciever)\n\nThe same can be done wi...
[ 1, 0 ]
[]
[]
[ "css_selectors", "python", "python_3.x", "selenium", "xpath" ]
stackoverflow_0074142788_css_selectors_python_python_3.x_selenium_xpath.txt
Q: How can I get a specific file from hundreds of folders to move to one folder and rename it? the file location is: /Users/D/Desktop/Files/1/no.h5 and its the same filename (no.h5) in the folders 1-400. I want all these files to collect in the same folder with their number as their new names. Your help is greatly ap...
How can I get a specific file from hundreds of folders to move to one folder and rename it?
the file location is: /Users/D/Desktop/Files/1/no.h5 and its the same filename (no.h5) in the folders 1-400. I want all these files to collect in the same folder with their number as their new names. Your help is greatly appreciated!
[ "You could use a glob pattern to find the target files to do the move. The pathlib library provides a convenient way to manage the paths.\nfrom pathlib import Path\n\nbase = Path(\" /Users/D/Desktop/Files\")\ntarget_folder = Path(\"/some/where/else\")\n\nfor target in base.glob(\"*/no.h5\"):\n name = target.pare...
[ 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0074143253_python.txt
Q: Load excel files within python based on date modified I am tring to load the last 30 days of excel files into python so I can check work isn't duplicated. The location has 1000's of old excel files (archived). I only want to look at the last 30 days of files. My current code adds them alltogether: for f in files_x...
Load excel files within python based on date modified
I am tring to load the last 30 days of excel files into python so I can check work isn't duplicated. The location has 1000's of old excel files (archived). I only want to look at the last 30 days of files. My current code adds them alltogether: for f in files_xlsx: os.chdir("path") data = pd.read_excel(f, 'Deal...
[ "If the problem you're having is selecting only the files that are younger than 30 days, you can filter them for example like this:\nnow = datetime.datetime.now()\ndef file_age(file):\n return now - datetime.datetime.fromtimestamp(os.path.getmtime(file))\nrelevant_files = [file for file in files \n ...
[ 1 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0074143451_excel_python.txt
Q: Read in a CSV file in lower case with Python I'm reading a CSV file into a namedtuple as so: import csv from collections import namedtuple #So we can handle bad CSV files gracefully def unfussy_reader(reader): while True: try: yield next(reader.lower()) # This is a bad row that ha...
Read in a CSV file in lower case with Python
I'm reading a CSV file into a namedtuple as so: import csv from collections import namedtuple #So we can handle bad CSV files gracefully def unfussy_reader(reader): while True: try: yield next(reader.lower()) # This is a bad row that has an error in it (csv.Error) # Alternately...
[ "You can apply the lower transform to the stream before you create a CSV reader for it.\nlower_stream = (line.lower() for line in file_stream)\ncsv_reader = csv.reader(lower_stream, delimiter=' ', quotechar='\"', escapechar='^')\n\nThe parentheses around the lower_stream assignment target designate a generator expr...
[ 4, 0, 0 ]
[]
[]
[ "csv", "map_function", "python", "python_3.x" ]
stackoverflow_0034578820_csv_map_function_python_python_3.x.txt
Q: they give me empty output using selenium I am using wait method to find element but they give me empty output. What is the mistake? link https://www.amazon.co.uk//dp/B094FZ1XFJ from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.support.wai...
they give me empty output using selenium
I am using wait method to find element but they give me empty output. What is the mistake? link https://www.amazon.co.uk//dp/B094FZ1XFJ from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdr...
[ "This should be visibility_of_all_elements_located() which returns list of elements.\nabout_this_item_divs = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, \"//div[@id='featurebullets_feature_div']//ul//li//span\")))\n\nThis will returns only web element NOT list of web elements.\n...
[ 0 ]
[]
[]
[ "python", "selenium", "web_scraping", "webdriver", "webdriverwait" ]
stackoverflow_0074143128_python_selenium_web_scraping_webdriver_webdriverwait.txt
Q: Why is python showing empty brackets for my web scraping project? I thought it might be because the site asks that you login, so I went to cURL converter and got the cookies and header information. I also thought it could've been an outdated version of python, I installed the latest one and started a new project. ...
Why is python showing empty brackets for my web scraping project?
I thought it might be because the site asks that you login, so I went to cURL converter and got the cookies and header information. I also thought it could've been an outdated version of python, I installed the latest one and started a new project. I pip install lxml, bs4, and requests to be sure. Here's the code: from...
[ "Using the dev tool of your browser, look at the request made to the server.\nLook at the html, and check that it is mostly empty andd then notice that it makes a json request to https://static.newsfilter.io/landing-page/articles-latest-news.json\nIt is just a matter to get that and parse it.\nimport requests\n ...
[ 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074142899_python_web_scraping.txt
Q: python requests for load more data i want to scrap product images from https://society6.com/art/i-already-want-to-take-a-nap-tomorrow-pink of each product > step=1 first i go in div', class_='card_card__l44w (which is having each product link) step=2 then parse the href of each product > but its getting back only ...
python requests for load more data
i want to scrap product images from https://society6.com/art/i-already-want-to-take-a-nap-tomorrow-pink of each product > step=1 first i go in div', class_='card_card__l44w (which is having each product link) step=2 then parse the href of each product > but its getting back only first 15 product link inspite of all 44 ...
[ "All the information is loaded at first visit and all 66 products are stored in window.__INITIAL_STATE.\nIf you scroll almost to the end of the file you can see it.\nYou can use that to parse the information.\nimport re\nimport json\n\ndata = json.loads((soup\n .find(\"script\", text=re.compile(\"...
[ 0 ]
[]
[]
[ "python", "python_requests", "web_scraping" ]
stackoverflow_0074137958_python_python_requests_web_scraping.txt
Q: Overflow bin is not showing up in plotly/python? Here is my code: import plotly.graph_objects as go import numpy as np a = dataset['reportNum'].to_numpy() np.random.seed(1) hist, bins = np.histogram(a, bins=[0,500,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000,7500,8000,15000]) fig = go.Fi...
Overflow bin is not showing up in plotly/python?
Here is my code: import plotly.graph_objects as go import numpy as np a = dataset['reportNum'].to_numpy() np.random.seed(1) hist, bins = np.histogram(a, bins=[0,500,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000,7500,8000,15000]) fig = go.Figure(go.Bar(x=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1...
[ "You should add 100 to the bins in the np.histogram\nnp.histogram(a, bins=[0,100,500,.....]) #<----- add the 100 \n\n\n" ]
[ 2 ]
[]
[]
[ "histogram", "numpy", "plotly", "python" ]
stackoverflow_0074143396_histogram_numpy_plotly_python.txt
Q: Python Regex: Chain Multiple Substitutions In Function I am looking to clean URL's in the else block of an if. Specifically, strip the ? and all query parameters after it as well as everything before the first "/". Example Input = 'somesite.com/somepage?param=1&else=2' Example Output = 'somepage' ** All that is le...
Python Regex: Chain Multiple Substitutions In Function
I am looking to clean URL's in the else block of an if. Specifically, strip the ? and all query parameters after it as well as everything before the first "/". Example Input = 'somesite.com/somepage?param=1&else=2' Example Output = 'somepage' ** All that is left is our page (no query params and no domain) ** Below is w...
[ "howabout using re.search and setting what you want aside as a group?\nre.search(r'.*\\.com\\/(.*)\\?.*', x).group(1)\n\n", "You'll have to assign to x or return the result of your re.sub call, and the regex should include some requirements that concern the forward slash. Also there is the # symbol that has a spe...
[ 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074143399_python_regex.txt
Q: How to handle SSL Error with Python requests I want to send request to one PDF link. link = "https://publicationtc.fr.ch/tribunavtplus/ServletDownload/605_2022_1_a514394f9f18429995d4cd5c64fbc6de.pdf?path=89599fc4428b36e430bdf3f8a743749b72d66ad9c60b26ec73eca465d87e271c4ac6ee641573804bc4054a0a0676852bfe9af512f200424...
How to handle SSL Error with Python requests
I want to send request to one PDF link. link = "https://publicationtc.fr.ch/tribunavtplus/ServletDownload/605_2022_1_a514394f9f18429995d4cd5c64fbc6de.pdf?path=89599fc4428b36e430bdf3f8a743749b72d66ad9c60b26ec73eca465d87e271c4ac6ee641573804bc4054a0a0676852bfe9af512f2004244ba03d7aac8659e1637de9fb6178bb32ca6bb9c945937d5eb&...
[ "The website requires you to set a User-Agent as header. With requests you can to that like this:\nlink = \"https://publicationtc.fr.ch/tribunavtplus/ServletDownload/605_2022_1_a514394f9f18429995d4cd5c64fbc6de.pdf?path=89599fc4428b36e430bdf3f8a743749b72d66ad9c60b26ec73eca465d87e271c4ac6ee641573804bc4054a0a0676852bf...
[ 0 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074137604_python_python_requests.txt
Q: Why I am getting "TypeError: string indices must be integers"? I have a input which looks like it is in json format {'server': 'apple'} while writing It is throwing TypeError: string indices must be integers error. What is wrong in this? A: servernames.append(server["hostname"]) TypeError: string indices must...
Why I am getting "TypeError: string indices must be integers"?
I have a input which looks like it is in json format {'server': 'apple'} while writing It is throwing TypeError: string indices must be integers error. What is wrong in this?
[ "servernames.append(server[\"hostname\"])\n\n\nTypeError: string indices must be integers\n\nThe error message suggests server is a string, and it's complaining \"hostname\" is not an integer.\nIf server is a string containing JSON data, you can convert it with the json module:\nimport json\n\nserver_names = []\nfo...
[ 0 ]
[]
[]
[ "json", "python", "typeerror" ]
stackoverflow_0074143623_json_python_typeerror.txt
Q: Why is my python script unable to copy a file which definitely exists? Source code: import os import shutil import errno from pathlib import Path def copyFile(src, dst, buffer_size=10485760, perserveFileDate=True): ''' Copies a file to a new location. Much faster performance than Apache Commons due to use...
Why is my python script unable to copy a file which definitely exists?
Source code: import os import shutil import errno from pathlib import Path def copyFile(src, dst, buffer_size=10485760, perserveFileDate=True): ''' Copies a file to a new location. Much faster performance than Apache Commons due to use of larger buffer @param src: Source File @param dst: Destinat...
[ "It has nothing to do with the input file. The stack trace indicates that the error is happening in mkdir(). I believe that since you are passing a simple filename as the destination to copyFile(), then dstParent will be an empty string which causes os.makedirs() to throw this error.\n", "I add check condition f...
[ 3, 0 ]
[]
[]
[ "file_copying", "python" ]
stackoverflow_0074143475_file_copying_python.txt
Q: Efficient drawing of video frames in python GUI Currently I am working on a project where I have some hardware including a camera. The hardware will stream the camera frames over the network to my python program. This is working already, basically I have a numpy array available with the raw pixel data of the image...
Efficient drawing of video frames in python GUI
Currently I am working on a project where I have some hardware including a camera. The hardware will stream the camera frames over the network to my python program. This is working already, basically I have a numpy array available with the raw pixel data of the image in BGR Format. I want to have a GUI that will rapidl...
[ "So I decided to try it with moderngl / moderngl_window and the results seem to be performant enough. Monderngl_window had an interesting example code (a video player), that was very similar to what I wanted to achieve: https://github.com/moderngl/moderngl-window/blob/master/examples/video.py\nMy code is using the ...
[ 0 ]
[]
[]
[ "drawing", "numpy", "python", "user_interface" ]
stackoverflow_0074125155_drawing_numpy_python_user_interface.txt
Q: Can you read from serial buffer without knowing baudrate? I'm just wondering why it's necessary to know the baud rate when reading serial data from the buffer with PySerial. Shouldn't the byte data in the buffer be the same regardless of 9600 or 38400 baud rate, with the exception that the latter fills faster? I'm...
Can you read from serial buffer without knowing baudrate?
I'm just wondering why it's necessary to know the baud rate when reading serial data from the buffer with PySerial. Shouldn't the byte data in the buffer be the same regardless of 9600 or 38400 baud rate, with the exception that the latter fills faster? I'm asking because I might have a scenario where I don't know the ...
[ "Nope.\nWe're talking about an asynchronous protocol here, so both sides need to know when to sample the data. Imagine you're standing next to a conveyor belt that's carrying chocolates that you need to pick up. Now imagine that your eyes are closed... You need to know how fast the belt is moving and how much space...
[ 1 ]
[]
[]
[ "baud_rate", "buffer", "port", "pyserial", "python" ]
stackoverflow_0074143726_baud_rate_buffer_port_pyserial_python.txt
Q: Django - Unable to find object using pk (Matching query DoesNotExist) Whenever I try to create a "Tour" for a "User" I get this error: "DoesNotExist at /add-tour/FAjK5CryF8/ - User matching query does not exist." Specifically the problems seems to come from this line of code: user = User.objects.get(pk=pk) models...
Django - Unable to find object using pk (Matching query DoesNotExist)
Whenever I try to create a "Tour" for a "User" I get this error: "DoesNotExist at /add-tour/FAjK5CryF8/ - User matching query does not exist." Specifically the problems seems to come from this line of code: user = User.objects.get(pk=pk) models.py class Tour(models.Model): user = models.ForeignKey(User, on_delete=...
[ "You need to make sure your user instance does exist, so you should instead of user = User.objects.get(pk=pk)call user = get_object_or_404(User, pk=pk), then you need to pass user as an instance:\nif request.method == \"POST\":\n form = TourForm(request.POST, instance=user)\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0074138966_django_django_views_python.txt
Q: How to fetch a boolean value from models for a specific user in Django? I have an extended user model and I want to check it to see if the logged-in user has completed_application as per the model: Models.py: class Completed(models.Model): class Meta: verbose_name_plural = 'Completed Application' user = mode...
How to fetch a boolean value from models for a specific user in Django?
I have an extended user model and I want to check it to see if the logged-in user has completed_application as per the model: Models.py: class Completed(models.Model): class Meta: verbose_name_plural = 'Completed Application' user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) complete...
[ "Hi the problem is you have to change your queryset\nCompleted.objects.get(completed_application ...etc\n\nTo:\nCompleted.objects.filter(completed_application=True,user=request.user).exists()\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0074143781_django_django_models_django_views_python.txt
Q: PgAdmin Saved Passwords on Shared Servers Broken for Non-Admins On a clean installation of PgAdmin in server mode based on official docker image version 6.10 I have the following issue: Add a shared server as admin. Login as an unprivileged user, set server Username under Properties > Connection. Try to connect in...
PgAdmin Saved Passwords on Shared Servers Broken for Non-Admins
On a clean installation of PgAdmin in server mode based on official docker image version 6.10 I have the following issue: Add a shared server as admin. Login as an unprivileged user, set server Username under Properties > Connection. Try to connect inserting the password and saving it - works. Disconnect Server (or log...
[ "This was fixed on version 6.15: https://www.pgadmin.org/docs/pgadmin4/latest/release_notes_6_15.html\nIssue #5367 - Ensure that the correct value should be returned if an exception occurs while decoding the password.\n" ]
[ 1 ]
[]
[]
[ "docker", "oauth", "pgadmin", "pgadmin_4", "python" ]
stackoverflow_0072528927_docker_oauth_pgadmin_pgadmin_4_python.txt
Q: With the Ursina game engine, how would I scale a Button to Text when fit_to_text() provides unexpected results? I am currently writing a class as a derivative to the Button class, creating "Text Buttons" in their stead. However, while I was testing the Button class itself, I seem to be missing something about the...
With the Ursina game engine, how would I scale a Button to Text when fit_to_text() provides unexpected results?
I am currently writing a class as a derivative to the Button class, creating "Text Buttons" in their stead. However, while I was testing the Button class itself, I seem to be missing something about the Button's surface scaling, rather than scaling both the Text and the Button. How do I actually make the Button fit to...
[ "I think Text.size = 0.06 is the culprit here. There's some padding around the text built in when using fit_to_text() and that becomes too large when changing the default text size.\nSince you made the text size more than twice as big, the padding will also be more than twice as large, because it takes the Text.siz...
[ 1 ]
[ "The Button class in Ursina has a method called scale_to_text() which can be used to scale a button to fit its text.\nIf the results of fit_to_text() are unexpected, you can try using scale_to_text() instead.\n" ]
[ -1 ]
[ "game_engine", "python", "python_3.x", "ursina", "user_interface" ]
stackoverflow_0074135006_game_engine_python_python_3.x_ursina_user_interface.txt
Q: ROS-Melodic image from webcam I'm using ROS Melodic. The project is line-detection in Python. I get images from webcam logitech C390E. How can i synchronize between publisher & image processing in subscriber? The code is below: Publisher class Camera(object): def __init__(self): self.height = 640 ...
ROS-Melodic image from webcam
I'm using ROS Melodic. The project is line-detection in Python. I get images from webcam logitech C390E. How can i synchronize between publisher & image processing in subscriber? The code is below: Publisher class Camera(object): def __init__(self): self.height = 640 self.width = 480 self.f...
[ "You should only subscribe once and call rospy.spin() so node won't exit. Try this:\nif __name__ == '__main__': \n rospy.init_node(\"PC_process\")\n camera = Camera()\n\n camera.run() # Subscribe once, callback will be called on each new message\n rospy.spin() # Keep node from exiting\n\n" ]
[ 0 ]
[]
[]
[ "opencv", "python", "ros" ]
stackoverflow_0073400055_opencv_python_ros.txt
Q: How do I stop text from moving when I resize the screen in tkinter I am creating a registration form, and I have coded labels to show next to the text box for someone's username and password. This is the code I am using to place the text boxes and labels: usernamebx.place(relx=0.5, rely=0.5, width=225, height=25, ...
How do I stop text from moving when I resize the screen in tkinter
I am creating a registration form, and I have coded labels to show next to the text box for someone's username and password. This is the code I am using to place the text boxes and labels: usernamebx.place(relx=0.5, rely=0.5, width=225, height=25, anchor= CENTER) userbx_label.place(relx=0.1, rely=0.5, anchor=CENTER) ...
[ "\nThe code for usernamebx and passwbx means that the text boxes don't move when I resize the tkinter window.\n\nActually, they do move! If you put a widget at relx 0.5 in a window that is 200 pixels wide, that means the center of the widget will be 100 pixels from the left edge of the window. When you grow the win...
[ 0 ]
[]
[]
[ "python", "tkinter", "ttk" ]
stackoverflow_0074138235_python_tkinter_ttk.txt
Q: Re-arrange string in pandas I have a column in a dataframe whose type is object. This column contains both arrays and strings and its unique values are these: array(['[nan]', "['3. Medical and Health Sciences']", "['1. Natural Sciences']", "['2. Engineering and Technology']", "['1. Natural Sciences' ...
Re-arrange string in pandas
I have a column in a dataframe whose type is object. This column contains both arrays and strings and its unique values are these: array(['[nan]', "['3. Medical and Health Sciences']", "['1. Natural Sciences']", "['2. Engineering and Technology']", "['1. Natural Sciences' '3. Medical and Health Sciences']...
[ "I would use a regex pattern to find all the matching occurrences:\ndf['new_var1'] = df['Fields'].str.findall(r\"'\\d+\\.\\s*(.*?)'\")\ndf['new_var2'] = df['new_var1'].str.join(', ')\n\n\n docdb cited_patents dist_cited_patents Fields ...
[ 1 ]
[]
[]
[ "pandas", "python", "string" ]
stackoverflow_0074143758_pandas_python_string.txt
Q: How to send direct message to specific user in ms teams using python? I want to send Send direct message to specific user in ms teams through python with Odoo? A: This is a little more complicated task, but definitely doable. Sending an individual message using python is not as easy as using Webhook to send the ...
How to send direct message to specific user in ms teams using python?
I want to send Send direct message to specific user in ms teams through python with Odoo?
[ "This is a little more complicated task, but definitely doable. Sending an individual message using python is not as easy as using Webhook to send the message in Teams. You have to go through Authentication, get your token and then send the chat. Here are the steps that I used to get this to work using selenium to ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0070938049_python.txt
Q: Seeing output of shell script in python via subprocess I have a simple shell file that has this: #! /bin/bash echo "Hello" echo "Full Name: $1"; echo "Age: $2"; I am calling this file from the python jupyter notebook like this: import subprocess filePath = 'testScript.sh' arg1 = 'John Doe' arg2 = 2 subprocess.run...
Seeing output of shell script in python via subprocess
I have a simple shell file that has this: #! /bin/bash echo "Hello" echo "Full Name: $1"; echo "Age: $2"; I am calling this file from the python jupyter notebook like this: import subprocess filePath = 'testScript.sh' arg1 = 'John Doe' arg2 = 2 subprocess.run([filePath, arg1, str(arg2)], shell=True, check=True) The f...
[ "You can pass the capture_output keyword-argument to the subprocess.run() function.\nLike this:\nsubprocess.run([\"ls\", \"-a\"], capture_output=True)\n\nThis would return a CompletedProcess instance with a property called stdout, which contains all the output.\nIn this case all the files and directories in the wor...
[ 1, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0074143799_bash_python.txt
Q: Pandas: get all positive delta values efficiently I am looking for an efficient way to turn this pandas dataframe: A B C 0 0 1 0 1 0 1 1 2 1 1 1 3 1 1 0 4 0 0 1 into A B C 0 0 1 0 1 0 0 1 2 1 0 0 3 0 0 0 4 0 0 1 I only want "1" in a cell, if in the original dataframe the v...
Pandas: get all positive delta values efficiently
I am looking for an efficient way to turn this pandas dataframe: A B C 0 0 1 0 1 0 1 1 2 1 1 1 3 1 1 0 4 0 0 1 into A B C 0 0 1 0 1 0 0 1 2 1 0 0 3 0 0 0 4 0 0 1 I only want "1" in a cell, if in the original dataframe the value jumps from "0" to "1". If it's the first row, I wa...
[ "You can use:\ndf.diff().clip(0).fillna(df)\n\noutput:\n A B C\n0 0 1 0\n1 0 0 1\n2 1 0 0\n3 0 0 0\n4 0 0 1\n\n", "This code snippet should do exactly what you need:\nimport pandas as pd\ndf = pd.DataFrame({'A':[0,0,1,1,0],'B':[1,1,1,1,0],'C':[0,1,1,1,1]})\ndf.loc[-1] = len(df.columns)*[0]\ndf....
[ 2, 2, 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074140606_pandas_python.txt
Q: How to override a python instance's __exit__ method I want to change the __exit__ method from within the __enter__ method in a python class. How can I do this? Here is what I tried: class TestClass: def __enter__(self): func_type = type(self.__exit__) self.__exit__ = func_type(lambda *_: print(...
How to override a python instance's __exit__ method
I want to change the __exit__ method from within the __enter__ method in a python class. How can I do this? Here is what I tried: class TestClass: def __enter__(self): func_type = type(self.__exit__) self.__exit__ = func_type(lambda *_: print("exit override"), self) # Also tried the next li...
[ "You can't do that with __exit__, because it's always taken from the class:\nmgr = (EXPR)\nexit = type(mgr).__exit__ <---- here\nvalue = type(mgr).__enter__(mgr)\n\nhttps://peps.python.org/pep-0343/#specification-the-with-statement\nAs suggested in the comments, the natural way to do that would be to attach a cond...
[ 3 ]
[]
[]
[ "overriding", "python" ]
stackoverflow_0074143405_overriding_python.txt
Q: Does an arithmetic operation copy the value of the variables involved? Let's say I have a function "f(x) -> x.value + 1", where x is the reference to an object or data structure, and I call it one million times, asynchronously and in parallel. It's possible that at some point I will have one million copies of "val...
Does an arithmetic operation copy the value of the variables involved?
Let's say I have a function "f(x) -> x.value + 1", where x is the reference to an object or data structure, and I call it one million times, asynchronously and in parallel. It's possible that at some point I will have one million copies of "value" in the main memory? I'm assuming any programming language that supports ...
[ "There will only be one 256 object and one {\"value\": 256} object, but each called function will have a reference to the dict and a temporary reference to 256 when d[\"value\"] is active. In cpython, a reference is just a pointer (likely 8 bytes), which is smaller than a python int object, but still not zero.\nWhe...
[ 1 ]
[]
[]
[ "computer_science", "multithreading", "python", "symbolic_math" ]
stackoverflow_0074143775_computer_science_multithreading_python_symbolic_math.txt
Q: Text vocabulary coverage using sklearn I have a trained sklearn's CountVectorizer object on some corpus. When vectorizing a new document, the vector contains only the tokens that appear in the vectorizer's vocabulary. I'd like to add another feature to the vector which is the vocabulary coverage, or in other words...
Text vocabulary coverage using sklearn
I have a trained sklearn's CountVectorizer object on some corpus. When vectorizing a new document, the vector contains only the tokens that appear in the vectorizer's vocabulary. I'd like to add another feature to the vector which is the vocabulary coverage, or in other words, the percentage of tokens that are in the v...
[ "transform method of CountVectorizer may be useful:\ndef get_vocab_coverage(vectorizer, sent: str):\n\n preprocessor = vectorizer.build_preprocessor()\n tokenizer = vectorizer.build_tokenizer()\n\n processed = preprocessor(sent)\n tokenized_license = tokenizer(processed)\n\n if len(tokenized_license):\n ret...
[ 1 ]
[]
[]
[ "nlp", "python", "scikit_learn" ]
stackoverflow_0074140883_nlp_python_scikit_learn.txt
Q: In a pandas dataframe, how do I make a new column that is populated by values from a different row? I have three columns, "Date", "Name" and "Value" in my dataframe df. "Date" and "Name" combinations are unique, i.e., no two rows have the same date-name combination. I want to create a new column ("Yesterday Value"...
In a pandas dataframe, how do I make a new column that is populated by values from a different row?
I have three columns, "Date", "Name" and "Value" in my dataframe df. "Date" and "Name" combinations are unique, i.e., no two rows have the same date-name combination. I want to create a new column ("Yesterday Value") which is populated by the "Value" for a particular "Name" from the day before the row in question (plea...
[ "Suppose you have a DataFrame, which is ordered by dates for each name:\ndf = pd.DataFrame({'date':[datetime.date(2022, 10, 10), datetime.date(2022, 10, 11)]*2,\n 'name':['a','a','b','b'],\n 'value':[1.,2.,3.,4.]})\n\n date name value\n0 2022-10-10 a 1.0\n1 2022-10-11 ...
[ 1 ]
[]
[]
[ "datetime", "pandas", "python", "time_series" ]
stackoverflow_0074143965_datetime_pandas_python_time_series.txt
Q: code suddenly stops working with flask and zenora (Discord oauth2) when i went to restart my code because i have made changes to the index.html file and no chages to python i get the error Traceback (most recent call last): File "main.py", line 8, in <module> from server import server File "/home/runner/HangoutNet...
code suddenly stops working with flask and zenora (Discord oauth2)
when i went to restart my code because i have made changes to the index.html file and no chages to python i get the error Traceback (most recent call last): File "main.py", line 8, in <module> from server import server File "/home/runner/HangoutNet-Bot-Web/server.py", line 13, in <module> client = APIClient(OAUTH_TOKEN...
[ "You are going to need to import this from zenora:\nfrom zenora import BadTokenError\n\nnext you will need to add a try statement to your route like this for an example:\n@app.route('/')\ndef home():\n try:\n if \"token\" in session:\n bearer_client = APIClient(session.get(\"token\"), bearer=Tr...
[ 0 ]
[]
[]
[ "discord", "flask", "oauth", "python" ]
stackoverflow_0072076637_discord_flask_oauth_python.txt
Q: Trying to deploy API on Heroku issue Preparing metadata (pyproject.toml) did not run successfully I'm using Python 3.9.2. to develop a Flask API and my code runs fine and I'm able to run the API locally and return the expected data but I want to deploy it to for more testing. I've tried downgrading my version of N...
Trying to deploy API on Heroku issue Preparing metadata (pyproject.toml) did not run successfully
I'm using Python 3.9.2. to develop a Flask API and my code runs fine and I'm able to run the API locally and return the expected data but I want to deploy it to for more testing. I've tried downgrading my version of Numpy in requirements.txt but still getting same error. Preparing metadata (pyproject.toml): finished wi...
[ "in your requirements.txt try to set a lower version of setuptools and numpy as reported by the error message\nrequirements.txt:\n...\nsetuptools==59.8.0\nnumpy==1.19.2\n...\n\n", "The issue was with the Python version that Heroku was using to build the app. I created a runtime.txt file and specified Python 3.9.1...
[ 0, 0, 0 ]
[]
[]
[ "heroku", "python" ]
stackoverflow_0072966128_heroku_python.txt
Q: List index out of range error caused by empty cells when using CSV reader in Python I'm trying to figure out how to deal with empty cells when iterating through a CSV file. I am currently receiving an IndexError whenever I run the loop. This is because the rows are not empty, just some of the cells in the columns ...
List index out of range error caused by empty cells when using CSV reader in Python
I'm trying to figure out how to deal with empty cells when iterating through a CSV file. I am currently receiving an IndexError whenever I run the loop. This is because the rows are not empty, just some of the cells in the columns that I am iterating through. I am using a standard for loop for the iteration. Is there a...
[ "You may wish to handle the exception with a try and except block.\ntry:\n print('This is your code')\nexcept IndexError:\n print('This is where you handle the error if it occurs')\n\nIf it is appropriate to ignore the exception, you may use the pass keyword. This is a null statement and is used to maintain p...
[ 0 ]
[]
[]
[ "csvreader", "for_loop", "python" ]
stackoverflow_0074143705_csvreader_for_loop_python.txt
Q: Field x does not exist in model "res.partner" Odoo15 i would like to know why im recieving this error even thought my source code is correct. the error : Field "contact_prenom" does not exist in model "res.partner"View error context: {'file': '/opt/odoo15/custom-addons/om_/views/x.xml', 'line': 3, 'name': 'res.p...
Field x does not exist in model "res.partner" Odoo15
i would like to know why im recieving this error even thought my source code is correct. the error : Field "contact_prenom" does not exist in model "res.partner"View error context: {'file': '/opt/odoo15/custom-addons/om_/views/x.xml', 'line': 3, 'name': 'res.partner.inherit', 'view': ir.ui.view(1981,), 'view.model':...
[ "Remove line _name='x.y'\n_name attribute is used to create a new table in the database. According to your code, you want to extend res.partner table.\nYou can review this model inheritance documentation for your future development.\n" ]
[ 1 ]
[]
[]
[ "odoo", "odoo_15", "python" ]
stackoverflow_0074144074_odoo_odoo_15_python.txt
Q: Best approach for processing csv files with different headers I am just building a personal finance planner. What i want to do is, the following. Download account statements in csv files of different bank accounts. loop via Python code over each fiel in the folder and read data. write data from each column into s...
Best approach for processing csv files with different headers
I am just building a personal finance planner. What i want to do is, the following. Download account statements in csv files of different bank accounts. loop via Python code over each fiel in the folder and read data. write data from each column into sql database The problem that i have is now the following. Every cs...
[ "You could create a dictionary that has all the possible names for a given column:\ncolumn_names = {\n 'date': ['date', 'valutadate'],\n 'amount': ['amount', 'amount_withdrawal']\n}\n\nThen you can look up a given input csv column name in this dictionary to find the \"real\" name for that column in the final ...
[ 0 ]
[]
[]
[ "csv", "data_processing", "database", "pandas", "python" ]
stackoverflow_0074141358_csv_data_processing_database_pandas_python.txt
Q: Invalid classes inferred from unique values of `y`. Expected: [0 1 2 3 4 5], got [1 2 3 4 5 6] I've trained dataset using XGB Classifier, but I got this error in local. It worked on Colab and also my friends don't have any problem with same code. I don't know what that error means... Invalid classes inferred from ...
Invalid classes inferred from unique values of `y`. Expected: [0 1 2 3 4 5], got [1 2 3 4 5 6]
I've trained dataset using XGB Classifier, but I got this error in local. It worked on Colab and also my friends don't have any problem with same code. I don't know what that error means... Invalid classes inferred from unique values of y. Expected: [0 1 2 3 4 5], got [1 2 3 4 5 6] this is my code, but I guess it's no...
[ "That happens because the class column has to start from 0 (as required since version 1.3.2). An easy way to solve that is using LabelEncoder from sklearn.preprocssing library.\nSolution (works for version 1.6):\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\ny_train = le.fit_transform(y_train...
[ 21, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "classification", "machine_learning", "python", "xgbclassifier", "xgboost" ]
stackoverflow_0071996617_classification_machine_learning_python_xgbclassifier_xgboost.txt
Q: How to get a for loop outputs in a straight vertical line I'm a student who is recently been studying the basics of Python. So I faced this problem while doing one of my projects. If someone could explain a solution that is not too complex for my stage I would be grateful. students = ['Sam', 'Ben', 'John', 'Michae...
How to get a for loop outputs in a straight vertical line
I'm a student who is recently been studying the basics of Python. So I faced this problem while doing one of my projects. If someone could explain a solution that is not too complex for my stage I would be grateful. students = ['Sam', 'Ben', 'John', 'Michael'] marks = [27, 68, 34, 21] print('Student Name - Mark') for n...
[ "You can f-string to specify fixed length.\nstudents = ['Sam', 'Ben', 'John', 'Michael']\nmarks = [27, 68, 34, 21]\n\nprint('Student Name - Mark')\nfor student, mark in zip(students, marks):\n print(f\"{student:14} {mark}\")\n\nOutput:\nStudent Name - Mark\nSam 27\nBen 68\nJohn 34...
[ 0 ]
[]
[]
[ "for_loop", "list", "python" ]
stackoverflow_0074144288_for_loop_list_python.txt
Q: How do I find the time difference between two datetime objects in python? How do I tell the time difference in minutes between two datetime objects? A: >>> import datetime >>> first_time = datetime.datetime.now() >>> later_time = datetime.datetime.now() >>> difference = later_time - first_time datetime.timedelta...
How do I find the time difference between two datetime objects in python?
How do I tell the time difference in minutes between two datetime objects?
[ ">>> import datetime\n>>> first_time = datetime.datetime.now()\n>>> later_time = datetime.datetime.now()\n>>> difference = later_time - first_time\ndatetime.timedelta(0, 8, 562000)\n>>> seconds_in_day = 24 * 60 * 60\n>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)\n(0, 8) # 0 minutes, 8 s...
[ 502, 247, 170, 51, 31, 19, 13, 12, 12, 5, 4, 3, 2, 2, 1, 1, 1, 1, 0, 0 ]
[ "import datetime\ndate = datetime.date(1, 1, 1)\n#combine a dummy date to the time\ndatetime1 = datetime.datetime.combine(date, start_time)\ndatetime2 = datetime.datetime.combine(date, stop_time) \n#compute the difference\ntime_elapsed = datetime1 - datetime2\n\nstart_time --> start time for datetime object \nend_...
[ -1 ]
[ "date_arithmetic", "datetime", "python" ]
stackoverflow_0001345827_date_arithmetic_datetime_python.txt
Q: How do I make sure a model field is and incremental number for my model? I have the following model in django: class Page(models.Model): page_number = models.IntegerField() ... and I would like to make sure that this page number keeps being a sequence of integers without gaps, even if I delete some pages ...
How do I make sure a model field is and incremental number for my model?
I have the following model in django: class Page(models.Model): page_number = models.IntegerField() ... and I would like to make sure that this page number keeps being a sequence of integers without gaps, even if I delete some pages in the middle of the existing pages in the data base. For example, I have page...
[ "Basically you'd have to manually bump all of the pages down\nWhen you get to custom views you'd do something like this:\ndef deletePage(request):\n if request.method = 'POST':\n pageObj = Page.objects.filter(page_number=request.POST.get('page_number')).first()\n if pageObj:\n pageObj.de...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074143700_django_python.txt
Q: ValueError: You must specify a period or x must be a pandas object with a DatetimeIndex with a freq not set to None Hello and thank you in advance for your help! I am getting ValueError: You must specify a period or x must be a pandas object with a DatetimeIndex with a freq not set to None when I try to do a time ...
ValueError: You must specify a period or x must be a pandas object with a DatetimeIndex with a freq not set to None
Hello and thank you in advance for your help! I am getting ValueError: You must specify a period or x must be a pandas object with a DatetimeIndex with a freq not set to None when I try to do a time series decomposition that pulls from GitHub. I think I have a basic understanding of the error, but I do not get this err...
[ "Try this:\nimport pandas as pd\nimport numpy as np \n%matplotlib inline\nfrom statsmodels.tsa.seasonal import seasonal_decompose\n\ntopsoil = pd.read_csv('https://raw.githubusercontent.com/the-datadudes/deepSoilTemperature/master/meanDickinson.csv',parse_dates=True)\n\ntopsoil = topsoil.dropna()\ntopsoil.head()\n\...
[ 7, 2 ]
[]
[]
[ "matplotlib", "pandas", "python", "statsmodels", "time_series" ]
stackoverflow_0064617482_matplotlib_pandas_python_statsmodels_time_series.txt
Q: How to count words that end with a letter? (python) I am a beginner and this is what I came up with so far. However, it does not output the correct number of words that end with "a" or "b." Any tips on how to correct this code? names = input("Enter list of names: ") name = names.split(" ") num = len(name) ab = ...
How to count words that end with a letter? (python)
I am a beginner and this is what I came up with so far. However, it does not output the correct number of words that end with "a" or "b." Any tips on how to correct this code? names = input("Enter list of names: ") name = names.split(" ") num = len(name) ab = "" print("Number of words:", num) for i in range(num): ...
[ "In Python boolean (True and False) are the same as the integers 1 and 0. This means you can use sum() to count True booleans. str.endswith() returns a boolean. This means you can just do this:\nwords = [\"stab\", \"drama\", \"hello\", \"magma\", \"test\"]\n\na_b = sum(word.endswith(('a', 'b')) for word in words) \...
[ 4, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0074144082_python_split.txt
Q: How to pass parameters of Ajax URL in Django? I used Ajax to add items to wishlist: <a href="{% url 'listing:wishlist' list.slug %}" id="wishlistbtn" data-slug='{{ list.slug }}'>Add to wishlist</a> the url looks like: path('wishlist/<slug:title_slug>/', wishlist, name='wishlist'), but I don't know how to pass li...
How to pass parameters of Ajax URL in Django?
I used Ajax to add items to wishlist: <a href="{% url 'listing:wishlist' list.slug %}" id="wishlistbtn" data-slug='{{ list.slug }}'>Add to wishlist</a> the url looks like: path('wishlist/<slug:title_slug>/', wishlist, name='wishlist'), but I don't know how to pass list.slug or title_slug in above url using Ajax: $(do...
[ "is this your solution to pass the data-slug ?\n$(document).on('click', '#wishlistbtn', function (e) {\n let el = $(this);\n $.ajax({\n type: 'GET',\n url: \"{% url 'listing:wishlist' %}\",\n \n data: {\n title_slug: el.att...
[ 0, 0 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0062499905_ajax_django_python.txt
Q: For loop that takes turns between printing one thing or the other python Not sure how else to word the title, but this is what I need: Print either the number zero, the number one or a phrase in no consecutive order twenty times. This is what I have: n = 0 x = “hello” for i in range(20): print(...
For loop that takes turns between printing one thing or the other python
Not sure how else to word the title, but this is what I need: Print either the number zero, the number one or a phrase in no consecutive order twenty times. This is what I have: n = 0 x = “hello” for i in range(20): print(n, end= ‘’) or print(n+1, end= ‘’) or print(x) The only problem is that it pr...
[ "import random\nchoices = [1, 0, \"hello\"]\nfor i in range(20):\n print(random.choice(choices))\n\n", "Your question is hard to understand, but I think this will help.\nIf you want to randomize, then try importing random\nimport random\nmy_strings=[\"foo\", \"bar\", \"baz\"]\n\nfor i in range(10):\n print(...
[ 8, 7, 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0074144004_python.txt
Q: Pad string to the left of a character I have a float that is stored as a string: float1 = 638045.11 float2 = 638045.1 I want to print this: float1 = 0000638045.11 float2 = 0000638045.1 I've tried zfill but that pads the entire string. How can I pad only to the left of the decimal? A: You can use str.split to spi...
Pad string to the left of a character
I have a float that is stored as a string: float1 = 638045.11 float2 = 638045.1 I want to print this: float1 = 0000638045.11 float2 = 0000638045.1 I've tried zfill but that pads the entire string. How can I pad only to the left of the decimal?
[ "You can use str.split to spilt the string to the left and right parts then use zfill on the left part.\nfloat1 = 638045.11 \nfloat2 = 638045.1\n\nsf11, sf12 = str(float1).split('.') # -> ['638045', '11']\nsf21, sf22 = str(float2).split('.') # -> ['638045', '1']\n\nprint(f\"{sf11.zfill(10)}.{sf12}\")\nprint(f\"{sf2...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074144392_python.txt
Q: Comma separated inputs instead of space separated inputs for argparse I'm using argparse to receive inputs from the command line to run my script. My current input string looks like this: path> python <\filename\\> -t T1 T2 T3 -f F1 F2 Is there a parameter in argparse such that instead of separating inputs by spa...
Comma separated inputs instead of space separated inputs for argparse
I'm using argparse to receive inputs from the command line to run my script. My current input string looks like this: path> python <\filename\\> -t T1 T2 T3 -f F1 F2 Is there a parameter in argparse such that instead of separating inputs by space, I can separate them by commas? In other words: path> python <\filename\...
[ "There is no such feature in argparse. \nAlternatives:\n\npost-process the args namespace and split/parse the values manually\ndefine a custom action and split/parse the values manually\ndefine a custom type and split/parse the values manually\nsubclass ArgumentParser and customise ArgumentParser.convert_arg_line_...
[ 5, 3, 2, 0, 0 ]
[ "If you're okay with space not comma separated, then it's builtin to argparse:\nIn [1]: from argparse import ArgumentParser\n\nIn [2]: parser = ArgumentParser()\n\nIn [3]: parser.add_argument('-a', nargs='+')\nOut[3]: _StoreAction(option_strings=['-a'], dest='a', nargs='+', const=None, \n defaul...
[ -1 ]
[ "command_line_arguments", "python" ]
stackoverflow_0048714523_command_line_arguments_python.txt
Q: Replace Only Integer Values with a sequence of consecutive numbers in a column How do I replace only the integer values in the ID column with a sequence of consecutive numbers? I'd like any non-integer or NaN cells skipped. Current df: ID AMOUNT 1 0.00 test 5.00 test test 0.00 tes...
Replace Only Integer Values with a sequence of consecutive numbers in a column
How do I replace only the integer values in the ID column with a sequence of consecutive numbers? I'd like any non-integer or NaN cells skipped. Current df: ID AMOUNT 1 0.00 test 5.00 test test 0.00 test 0.00 1 0.00 xx 304.95 x xx 304.95 1 0.00 ...
[ "You can use:\ndf['ID'] = (pd\n .to_numeric(df['ID'], errors='coerce') # convert to numeric\n .cumsum() # increment numbers\n .convert_dtypes().astype(object) # back to integer\n .fillna(df['ID']) # restore non-numeric\n)\n\nAlternative using slici...
[ 2, 2, 1 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074144204_pandas_python_python_3.x.txt
Q: start primary key by 1001 in Django model, auto_increment gives error Please describe how to start the primary key by 1001 in the Django model(database). I found some examples with auto_increment, but it gives me errors of undefined. Inside the project, we have to alter fields using migrations. So, Please notice ...
start primary key by 1001 in Django model, auto_increment gives error
Please describe how to start the primary key by 1001 in the Django model(database). I found some examples with auto_increment, but it gives me errors of undefined. Inside the project, we have to alter fields using migrations. So, Please notice that It does not affect our previous data. The database key must increment ...
[ "You can do this with the code snippet below:\nfrom django.db import models\n\ndef field_start_from_1001():\n \"\"\"\n Returns the next default value for the with auto-increment fields,\n starts from 1001\n \"\"\"\n last_entry = YourModel.objects.all().order_by('pk_field').last()\n if last_entry:\...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074017532_django_django_models_python.txt
Q: How do I do a case-insensitive string comparison? How can I compare strings in a case insensitive way in Python? I would like to encapsulate comparison of a regular strings to a repository string, using simple and Pythonic code. I also would like to have ability to look up values in a dict hashed by strings using ...
How do I do a case-insensitive string comparison?
How can I compare strings in a case insensitive way in Python? I would like to encapsulate comparison of a regular strings to a repository string, using simple and Pythonic code. I also would like to have ability to look up values in a dict hashed by strings using regular python strings.
[ "Assuming ASCII strings:\nstring1 = 'Hello'\nstring2 = 'hello'\n\nif string1.lower() == string2.lower():\n print(\"The strings are the same (case insensitive)\")\nelse:\n print(\"The strings are NOT the same (case insensitive)\")\n\nAs of Python 3.3, casefold() is a better alternative:\nstring1 = 'Hello'\nstr...
[ 766, 685, 65, 53, 9, 8, 4, 2, 2, 0, 0, 0, 0 ]
[ "def insenStringCompare(s1, s2):\n \"\"\" Method that takes two strings and returns True or False, based\n on if they are equal, regardless of case.\"\"\"\n try:\n return s1.lower() == s2.lower()\n except AttributeError:\n print \"Please only pass strings into this method.\"\n p...
[ -3, -3 ]
[ "case_insensitive", "comparison", "python" ]
stackoverflow_0000319426_case_insensitive_comparison_python.txt
Q: Python decorator - Check if user is admin I am creating simple API using flask, and I want to check if user which is trying to access is admin. This is function which should decide if user is admin or not def admin_required(f): wraps(f) @jwt_required() def decorated_function(*args, **kwargs): c...
Python decorator - Check if user is admin
I am creating simple API using flask, and I want to check if user which is trying to access is admin. This is function which should decide if user is admin or not def admin_required(f): wraps(f) @jwt_required() def decorated_function(*args, **kwargs): current_user = get_jwt_identity() if cur...
[ "Is the indentation in your post what is actually in your code, because it is indented wrong. Here is an example of an authentication check (not an admin check), but you can see how the indentation should look. You are also missing the decorator on wraps(f).\ndef requires_auth(f):\n @wraps(f)\n def decorated(...
[ 2 ]
[]
[]
[ "flask_restful", "jwt", "python" ]
stackoverflow_0074144214_flask_restful_jwt_python.txt
Q: Python: How to disable main window while secondary window is open (Tkinter) I would like to disable the main window of my text adventure program while the character creation window is up. I am relatively new to this. When I try my code below, the main window stays interactable even though the secondary window (cre...
Python: How to disable main window while secondary window is open (Tkinter)
I would like to disable the main window of my text adventure program while the character creation window is up. I am relatively new to this. When I try my code below, the main window stays interactable even though the secondary window (creator) is open. There is no error that the console puts out, it just doesn't work ...
[ "You should create your creator window as an instance of tkinter.Toplevel() rather than declaring a new instance of Tk() altogether, then you can use grab_set to prevent the user from interacting with the root window while the creator window is open.\nimport tkinter as tk\n\n\nroot = tk.Tk()\n# usual root configs l...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074144399_python_tkinter.txt
Q: How do I make dynamic reconfigure have the ability to change the angles at which my lidar can see? I am trying to make a simulated robot only be able to see the 180 degrees in front of it with a lidar and I'm using dynamic reconfigure to control the angles/window that it should be able to detect objects within but...
How do I make dynamic reconfigure have the ability to change the angles at which my lidar can see?
I am trying to make a simulated robot only be able to see the 180 degrees in front of it with a lidar and I'm using dynamic reconfigure to control the angles/window that it should be able to detect objects within but I'm struggling to figure out how to implement that ability in my code. Dynamic Reconfigure that I set u...
[ "If you ok with publishing lidar data for filtering you could use LaserScanAngularBoundsFilter\n\nOr manually:\nFrom LaserScan.msg data.angle_max and data.angle_min doesn't seem to discard measurements. That must be done manually.\nFor example to keep it simple you have lidar which scans from 0 to 360 deg (angle_mi...
[ 0 ]
[]
[]
[ "python", "ros", "rospy" ]
stackoverflow_0072853885_python_ros_rospy.txt