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:
Is there a typing hint in Python for a generic class?
I have some legacy code that I inherited that creates a class on the fly within a method. The type returned is just <class 'module'>. How do I type hint this?
I know I can use Any, but I was hoping for something a bit more specific.
A:
Well, if the type is ... | Is there a typing hint in Python for a generic class? | I have some legacy code that I inherited that creates a class on the fly within a method. The type returned is just <class 'module'>. How do I type hint this?
I know I can use Any, but I was hoping for something a bit more specific.
| [
"Well, if the type is <class 'module'> that means it returns modules. The annotation for that is the types.ModuleType. And it is not generic.\n",
"You can use Type.\nIt's a generic, and you have to provide it with the base class of the class you create on the flight.\nIf you don't know the base class, you can do ... | [
2,
0
] | [] | [] | [
"python",
"python_3.x",
"type_hinting"
] | stackoverflow_0074234908_python_python_3.x_type_hinting.txt |
Q:
How do I catch a psycopg2.errors.UniqueViolation error in a Python?
I have app for working with database that uses psycopg2. When I try to insert a column with repeating name I got this error:
> self.cursor.execute(str(query))
E psycopg2.errors.UniqueViolation: duplicate key value violates uniq... | How do I catch a psycopg2.errors.UniqueViolation error in a Python? | I have app for working with database that uses psycopg2. When I try to insert a column with repeating name I got this error:
> self.cursor.execute(str(query))
E psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "deposits_area_name_key"
E DETAIL: Key (area_nam... | [
"OperationalError is the wrong error class. See Exceptions:\n\nexception psycopg2.OperationalError\n\n\nException raised for errors that are related to the database’s operation and not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs, the data source name is not found, a transac... | [
0,
0
] | [] | [] | [
"exception",
"handleerror",
"psycopg2",
"python"
] | stackoverflow_0074136154_exception_handleerror_psycopg2_python.txt |
Q:
Python Tkinter: Attempt to get widget size
I am trying to find the size of my window by using the winfo_geometry() function but it ends up returning 1x1+0+0
I have also tried winfo_height, winfo_width but i keep getting 1
CODE
from tkinter import *
root=Tk()
root.geometry('400x600')
print (root.winfo_width())
p... | Python Tkinter: Attempt to get widget size | I am trying to find the size of my window by using the winfo_geometry() function but it ends up returning 1x1+0+0
I have also tried winfo_height, winfo_width but i keep getting 1
CODE
from tkinter import *
root=Tk()
root.geometry('400x600')
print (root.winfo_width())
print (root.winfo_height())
print (root.winfo_geo... | [
"You are trying to get the dimensions before the window has been rendered.\nAdd a root.update() before the prints and it shows the correct dimensions.\nfrom Tkinter import *\n\nroot=Tk()\n\nroot.geometry('400x600')\n\nroot.update()\n\nprint (root.winfo_width())\nprint (root.winfo_height())\nprint (root.winfo_geomet... | [
26,
0
] | [] | [] | [
"geometry",
"python",
"python_3.x",
"size",
"tkinter"
] | stackoverflow_0013327659_geometry_python_python_3.x_size_tkinter.txt |
Q:
extract the content of a html tag with all tags inside from beautifulsoup
I would like to extract the content of a tag without this tag itself and keeping all the tags inside.
html_text = "<TD WIDTH=60%>Portsmouth - Cherbourg<BR/>Portsmouth - Santander<BR/></TD>"
soup = BeautifulSoup(html_text, 'html.parser')
soup... | extract the content of a html tag with all tags inside from beautifulsoup | I would like to extract the content of a tag without this tag itself and keeping all the tags inside.
html_text = "<TD WIDTH=60%>Portsmouth - Cherbourg<BR/>Portsmouth - Santander<BR/></TD>"
soup = BeautifulSoup(html_text, 'html.parser')
soup_list = soup.find_all("td")
soup_object = soup_list[0]
text = soup_object.getTe... | [
"You might use decode_contents as follows\nfrom bs4 import BeautifulSoup\nhtml_text = \"<TD WIDTH=60%>Portsmouth - Cherbourg<BR/>Portsmouth - Santander<BR/></TD>\"\nsoup = BeautifulSoup(html_text, 'html.parser')\nsoup_list = soup.find_all(\"td\")\nsoup_object = soup_list[0]\ninner_html = soup_object.decode_contents... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074218243_beautifulsoup_python_web_scraping.txt |
Q:
How to get CallbackQuery from an inline button with url?
I defined a keyboard:
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(text=MOVIE_WATCH_BTN, callback_data=MOVIE_WATCH_CB, url=VIEWING_LINK)
]
]
)
now I want to catch the moment of pressing this b... | How to get CallbackQuery from an inline button with url? | I defined a keyboard:
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(text=MOVIE_WATCH_BTN, callback_data=MOVIE_WATCH_CB, url=VIEWING_LINK)
]
]
)
now I want to catch the moment of pressing this button:
@dp.callback_query_handler(text=[MOVIE_WATCH_CB])
async... | [
"Try this:\nfrom aiogram.utils.callback_data import CallbackData\n\ncb_inline = CallbackData(\"post\", 'action', \"data\")\nkeyboard = InlineKeyboardMarkup(\n inline_keyboard= [\n InlineKeyboardButton(text='MyText', callback_data=cb_inline.new(action='myact', data='MyText')\n ]\n )\n\nAnd:\n@dp.... | [
0
] | [] | [] | [
"aiogram",
"python",
"telegram_bot"
] | stackoverflow_0074233530_aiogram_python_telegram_bot.txt |
Q:
Error: type object 'Keys' has no attribute 'chord'
I am getting below error while executing selenium code.
Code:
driver.find_element_by_id(PlaylistManagerLocators.Folder_Name).send_keys(Keys.chord(Keys.CONTROL, "a"), "Auto_Folder5763")
Error:
AttributeError: type object 'Keys' has no attribute 'chord'
I have im... | Error: type object 'Keys' has no attribute 'chord' | I am getting below error while executing selenium code.
Code:
driver.find_element_by_id(PlaylistManagerLocators.Folder_Name).send_keys(Keys.chord(Keys.CONTROL, "a"), "Auto_Folder5763")
Error:
AttributeError: type object 'Keys' has no attribute 'chord'
I have imported all required files.
from selenium.webdriver.commo... | [
"There is no function as chord in class selenium.webdriver.common.keys.Keys (Check the docs). You can simply split it into 2 statements.\ndriver.find_element_by_id(id).send_keys(Keys.CONTROL + \"a\")\ndriver.find_element_by_id(id).send_keys(\"Auto_Folder5763\")\n\nOr if you want to simultaneously have the keys pres... | [
13,
0
] | [] | [] | [
"python",
"python_2.7",
"selenium",
"selenium_webdriver"
] | stackoverflow_0033915900_python_python_2.7_selenium_selenium_webdriver.txt |
Q:
Python multiprocessing : The object reference of a Manager.dict() value is changing when iterated over [Not Solved]
Here is a simple way to describe my problem:
From multiprocessing import Manager
class myObject():
#Do stuff
manager = Manager()
dictio = manager.dict()
dictio[(1)] = myObject()
print (dict... | Python multiprocessing : The object reference of a Manager.dict() value is changing when iterated over [Not Solved] |
Here is a simple way to describe my problem:
From multiprocessing import Manager
class myObject():
#Do stuff
manager = Manager()
dictio = manager.dict()
dictio[(1)] = myObject()
print (dictio[(1)])
dictio[(2)] = myObject()
print (dictio[(2)])
for key,value in dictio.items():
print (value)
... | [
"Let's consider a simpler version of your program:\nfrom multiprocessing import Manager\n\nclass myObject():\n pass\n\n\nif __name__ == '__main__':\n manager = Manager()\n dictio = manager.dict()\n\n\n obj1a = myObject()\n dictio[(1)] = obj1a\n obj1b = dictio[(1)]\n print(obj1a, obj1b, obj1a is... | [
1
] | [] | [] | [
"dictionary",
"multiprocessing",
"object",
"python"
] | stackoverflow_0074228905_dictionary_multiprocessing_object_python.txt |
Q:
Drawing a circle with Pyautogui from top to bottom
I would like to create a half circle from top to bottom with my mouse, using Pyautogui. Currently I am using a script that works from right to left or left to right. But I can't manage to make the script to work from top to bottom. Here is the current script,
impo... | Drawing a circle with Pyautogui from top to bottom | I would like to create a half circle from top to bottom with my mouse, using Pyautogui. Currently I am using a script that works from right to left or left to right. But I can't manage to make the script to work from top to bottom. Here is the current script,
import pyautogui
import math
R = 40
(x,y) = pyautogui.size(... | [
"Hello there GetRektOrElse,\nI would like to start this answer by apologising for my horrible code styling, I am primarily a mathematician and I am not very familiar with styling.\nI have taken a different approach to solving this problem to yourself by using the equation of a circle in cartesian coordinates: (x **... | [
1,
0
] | [] | [] | [
"geometry",
"mouse",
"pyautogui",
"python"
] | stackoverflow_0063253921_geometry_mouse_pyautogui_python.txt |
Q:
Replace spaces with commas using Regex in python
I want to replace space with comma for this particular pattern only not all spaces:
"21311 asd"
Input:
["dog,cat ax 21311 asd","131 MAN"]
Desired output:
["dog,cat ax 21311,asd","131,MAN"]
Code:
input = ["dog,cat ax 21311 asd","131 MAN"]
new_list = []
for i in in... | Replace spaces with commas using Regex in python | I want to replace space with comma for this particular pattern only not all spaces:
"21311 asd"
Input:
["dog,cat ax 21311 asd","131 MAN"]
Desired output:
["dog,cat ax 21311,asd","131,MAN"]
Code:
input = ["dog,cat ax 21311 asd","131 MAN"]
new_list = []
for i in input:
word = re.findall(r"\d*\s[a-zA-Z]*" , i)
... | [
"Try this:\ninput = [\"dog,cat,21311 asd\", \"131 MAN\"]\nprint([data.replace(' ', ',') for data in input])\n\n",
"You are using re.sub() with the wrong argument positions, the correct way is to call it like re.sub(regex, replace, string). Also you are iterating over input incorrectly. That's the right way to do ... | [
3,
1,
1,
1
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0074234786_python_regex_string.txt |
Q:
How can I connect to MySQL in Python 3 on Windows?
I am using ActiveState Python 3 on Windows and wanted to connect to my MySQL database.
I heard that mysqldb was the module to use.
I can't find mysqldb for Python 3.
Is there a repository available where the binaries exist for mysqldb?
How can I connect to MySQL i... | How can I connect to MySQL in Python 3 on Windows? | I am using ActiveState Python 3 on Windows and wanted to connect to my MySQL database.
I heard that mysqldb was the module to use.
I can't find mysqldb for Python 3.
Is there a repository available where the binaries exist for mysqldb?
How can I connect to MySQL in Python 3 on Windows?
| [
"There are currently a few options for using Python 3 with mysql:\nhttps://pypi.python.org/pypi/mysql-connector-python\n\nOfficially supported by Oracle\nPure python\nA little slow\nNot compatible with MySQLdb\n\nhttps://pypi.python.org/pypi/pymysql\n\nPure python\nFaster than mysql-connector\nAlmost completely com... | [
294,
73,
11,
7,
6,
5,
4,
2,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"mysql",
"python",
"python_3.x"
] | stackoverflow_0004960048_mysql_python_python_3.x.txt |
Q:
Add missing months to dataframe
I've seen plenty of examples and I can't make them work on my table. I have this table:
data = {'ID': ['Tom', 'Tom','Tom','Joseph','Joseph','Ben','Ben','Eden','Tim','Adam'], 'Tranche': ['Red', 'Red', 'Red', 'Blue','Blue','Blue','Blue','Red','Red','Blue'],'Totals':[100,100,100,50,50,... | Add missing months to dataframe | I've seen plenty of examples and I can't make them work on my table. I have this table:
data = {'ID': ['Tom', 'Tom','Tom','Joseph','Joseph','Ben','Ben','Eden','Tim','Adam'], 'Tranche': ['Red', 'Red', 'Red', 'Blue','Blue','Blue','Blue','Red','Red','Blue'],'Totals':[100,100,100,50,50,90,90,70,60,70],'Sent':['2022-01-18',... | [
"One option is with complete from pyjanitor to expose missing rows:\n# pip install pyjanitor\nimport pandas as pd\nimport janitor\n\n# build a sequence of periods from the 1st month in 2022: \nperiods={'SentMonth':pd.period_range('2022-01', '2022-12', freq='M')}\n\n#Build the new dataframe:\nout = (df\n .comp... | [
1,
1
] | [] | [] | [
"dataframe",
"datetime",
"pandas",
"python",
"resampling"
] | stackoverflow_0074233319_dataframe_datetime_pandas_python_resampling.txt |
Q:
how to solve django.db.utils.NotSupportedError in django
I got an error while running the project in Django. the thing is that unfortunately i upgraded my pip , MySQL client and Django versions
this is the error while running python manage.py run server
in check_database_version_supported
raise NotSupportedError(
... | how to solve django.db.utils.NotSupportedError in django | I got an error while running the project in Django. the thing is that unfortunately i upgraded my pip , MySQL client and Django versions
this is the error while running python manage.py run server
in check_database_version_supported
raise NotSupportedError(
django.db.utils.NotSupportedError: MariaDB 10.3 or later is re... | [
"You have a MariaDB-10.1.19 client installed to MySQL server, and your application found that 10.1.19. As in the error you need to have MariaDB 10.3 or later. You can upgrade MariaDB as\n\nFirst stop the xampp server completely.\nThen go to MariaDB download page and download the zip file of latest stable version\ne... | [
0
] | [] | [] | [
"database",
"django",
"mariadb",
"mysql",
"python"
] | stackoverflow_0074233986_database_django_mariadb_mysql_python.txt |
Q:
How to efficiently query with a long "WHERE IN [list]" clause?
I've got a database with production data in multiple tables. I want to analyze the history of the units produced and create a timeline. I am doing this in Python (jupyter lab notebook) and using a cloud based MySQL 8.0 database. Neither of the IDs (bot... | How to efficiently query with a long "WHERE IN [list]" clause? | I've got a database with production data in multiple tables. I want to analyze the history of the units produced and create a timeline. I am doing this in Python (jupyter lab notebook) and using a cloud based MySQL 8.0 database. Neither of the IDs (both strings and integers) is the primary ID in the database and the ID... | [
"\nI have over 800 000 IDs that goes into WHERE IN clause\n\nThat's way, way too many for IN .\nThe best way to handle this kind of volume is to use a temporary table with CREATE TEMPORARY TABLE and join the tables instead of using IN. A temporary table can have an index so that can help speed things up for the jo... | [
4
] | [] | [] | [
"mysql",
"python",
"sql",
"where_clause"
] | stackoverflow_0074235148_mysql_python_sql_where_clause.txt |
Q:
Python append list and for statement
I want to get a list with variables and filter it
I succeeded in removing unnecessary words, but
filtered = [] does not work from here.
print(filtered) = []
What I want is 'USD' or (and) 'EUR' according to the variable in filtered.
Append seems to be the problem... I don't know... | Python append list and for statement | I want to get a list with variables and filter it
I succeeded in removing unnecessary words, but
filtered = [] does not work from here.
print(filtered) = []
What I want is 'USD' or (and) 'EUR' according to the variable in filtered.
Append seems to be the problem... I don't know the cause
And in the second code, why is ... | [
"About your 1st code: response is a string and not a list, so \"for data in response\" will yield individual characters, not the words you expect.\nFor it to work as you intend, modify this part of the code:\n...\n else:\n response = response [0]['QA']\n response = [ word.replace('NZD','') for word... | [
1
] | [
"if I understood correctly what you wanted to do is this:\ndef test():\n response = [{'1': 0, '2': '2A', '3': True, '4': True, 'QA': ['NZDUSD','NZDEUR','NZDYEN','NZDGBP']}]\n if response == []:\n return\n\n else:\n response = str(response [0]['QA'][0])\n response = response.replace('NZ... | [
-1
] | [
"for_loop",
"list",
"python"
] | stackoverflow_0074235118_for_loop_list_python.txt |
Q:
poetry: how to install from git subdirectory?
I want to install feast python package with poetry.
pip3 install git+https://github.com/feast-dev/feast#subdirectory=sdk/python works okay,
but poetry add git+https://github.com/feast-dev/feast#subdirectory=sdk/pythongives an error:
CalledProcessError
Command '['g... | poetry: how to install from git subdirectory? | I want to install feast python package with poetry.
pip3 install git+https://github.com/feast-dev/feast#subdirectory=sdk/python works okay,
but poetry add git+https://github.com/feast-dev/feast#subdirectory=sdk/pythongives an error:
CalledProcessError
Command '['git', '--git-dir', '/tmp/pypoetry-git-feas51ct2_me/.... | [
"As of poetry 1.2 you can install VCS projects residing in remote subdirectories. Your pyproject.toml would contain the following;\n[tool.poetry.dependencies]\nfeast = { git = \"ssh://git@github.com/feast-dev/feast.git\", subdirectory = \"sdk/python\" }\n\nfor example.\n"
] | [
1
] | [] | [] | [
"pip",
"python",
"python_poetry"
] | stackoverflow_0071114135_pip_python_python_poetry.txt |
Q:
Why does mpi4py scatter not work as expected for integer array?
I was debugging an mpi4py script and the problem turned out to be an integer array not scattering as I expected. It works when I cast the array as floats but I was wondering why it doesn't work for integers so I can avoid the problem in future.
Runnin... | Why does mpi4py scatter not work as expected for integer array? | I was debugging an mpi4py script and the problem turned out to be an integer array not scattering as I expected. It works when I cast the array as floats but I was wondering why it doesn't work for integers so I can avoid the problem in future.
Running the following with 4 processes:
import numpy as np
from mpi4py impo... | [
"Ok I answered my own question; I guess its obvious once you think about it but I spent the morning scratching my head and only once I post it here I notice the obvious...\nThe arrays you're scattering to have to be cast to the same type as the scattered from array. Maybe I'm naive but it seems an odd way to silent... | [
0
] | [] | [] | [
"mpi4py",
"python"
] | stackoverflow_0074235069_mpi4py_python.txt |
Q:
get_config missing while loading previously saved model without custom layers
I have a problem with loading the previously saved model.
This is my save:
def build_rnn_lstm_model(tokenizer, layers):
model = tf.keras.Sequential([
tf.keras.layers.Embedding(len(tokenizer.word_index) + 1, layers,input_lengt... | get_config missing while loading previously saved model without custom layers | I have a problem with loading the previously saved model.
This is my save:
def build_rnn_lstm_model(tokenizer, layers):
model = tf.keras.Sequential([
tf.keras.layers.Embedding(len(tokenizer.word_index) + 1, layers,input_length=843),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(layers, kernel_r... | [
"Your example is missing the definition of f1, precision and recall functions. If the builtin metrics e.g. 'f1' (note it is a string) do not fit your usecase you can pass the custom_objects as follows:\ndef f1(y_true, y_pred):\n return 1\n\nmodel = tf.keras.models.load_model(path_to_model, custom_objects={'f1':f... | [
25,
0
] | [] | [] | [
"keras",
"machine_learning",
"python",
"tensorflow"
] | stackoverflow_0061767723_keras_machine_learning_python_tensorflow.txt |
Q:
List storing other lists keeping its old index values after doubling main list size?
I'm having issues with attempting to double the size of a list that contains lists like so:
main_list = [[], [], [], []]
Say I want to add the word "test" at main_list[1]. That can be done simply by just:
main_list[1].append("tes... | List storing other lists keeping its old index values after doubling main list size? | I'm having issues with attempting to double the size of a list that contains lists like so:
main_list = [[], [], [], []]
Say I want to add the word "test" at main_list[1]. That can be done simply by just:
main_list[1].append("test")
However, when I want to double the size of the main_list and therefor double the amou... | [
"You just need to make a new list of lists for main_list. When you do that, all the old lists will be lost:\nsize = len(main_list) * 2\nmain_list = [[] for _ in range(size)]\nmain_list[0].append(\"test\")\nprint(main_list)\n\nOutput as expected\n"
] | [
0
] | [] | [] | [
"indexing",
"list",
"python"
] | stackoverflow_0074235291_indexing_list_python.txt |
Q:
How can I convert iso-like date in dataframe such as '2022-10-28T08:00:19Z' to readable date in python?
I'm kinda new in Python.. help me find the solution.. I would like to convert iso-like date such as "2022-10-28T08:00:19Z" in a dataframe column into readable like '2022-10-28' or '28-10'2022' so I can filter an... | How can I convert iso-like date in dataframe such as '2022-10-28T08:00:19Z' to readable date in python? | I'm kinda new in Python.. help me find the solution.. I would like to convert iso-like date such as "2022-10-28T08:00:19Z" in a dataframe column into readable like '2022-10-28' or '28-10'2022' so I can filter and count the data if date >= '01-01-2022' then show the data.
this is the example of data:
date_published
202... | [
"df['date_published']=pd.to_datetime(df['date_published']).dt.date\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"datetime",
"datetime_format",
"pandas",
"python"
] | stackoverflow_0074235346_dataframe_datetime_datetime_format_pandas_python.txt |
Q:
Most efficient method of retrieving the last row of any size dataframe
I have a continually growing dataframe and periodically I want to retrieve the last row.
# dbdf.info(memory_usage='deep')
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 6652 entries, 2022-10-23 17:15:00-04:00 to 2022-10-28 08:06:00-04:00
... | Most efficient method of retrieving the last row of any size dataframe | I have a continually growing dataframe and periodically I want to retrieve the last row.
# dbdf.info(memory_usage='deep')
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 6652 entries, 2022-10-23 17:15:00-04:00 to 2022-10-28 08:06:00-04:00
Freq: T
Data columns (total 4 columns):
# Column Non-Null Count Dtype ... | [
"First select last row by DataFrame.iloc and then convert to dictionary by Series.to_dict:\nd = df.iloc[-1].to_dict()\n\n",
"There are 2 ways:\n\nUse Tail Function\n\nThe tail Function is used to show the last rows from the dataFrame. specifying the number 1 will show the last row of df.\ndf.tail(1)\n\n\nUse Iloc... | [
5,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074235283_pandas_python.txt |
Q:
Unable to activate a conda virtual environment on a remote computer on the same network in Powershell
I am using Windows Powershell to remote into another computer on the same network by using the following command:
C:\Users\User1>powershell
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\User... | Unable to activate a conda virtual environment on a remote computer on the same network in Powershell | I am using Windows Powershell to remote into another computer on the same network by using the following command:
C:\Users\User1>powershell
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\Users\User1> Enter-PSSession -ComputerName REMOTECOMPUTER1
After that, I want to activate a conda virtual envi... | [
"It turns out that you need to register a remote configuration on the remote server, and specify that configuration in your Enter-PSSession call.\nThe -StartupScript in the remote configuration should point to the file that contains your profile settings (with the conda initialize block) on the remote machine. For ... | [
0
] | [] | [] | [
"anaconda",
"powershell",
"python"
] | stackoverflow_0066590244_anaconda_powershell_python.txt |
Q:
How do I select a sub-folder as a directory containing tests in Python extension for Visual studio code
I am using VScode with python code and I have a folder with sub-directories (2-levels deep) containing python tests.
When I try "Python: Discover Tests" it asks for a test framework (selected pytest) and the di... | How do I select a sub-folder as a directory containing tests in Python extension for Visual studio code | I am using VScode with python code and I have a folder with sub-directories (2-levels deep) containing python tests.
When I try "Python: Discover Tests" it asks for a test framework (selected pytest) and the directory in which tests exist. At this option, it shows only the top-level directories and does not allow to s... | [
"I solved it by putting this in my settings.json (or in the Settings GUI, under \"Python > Testing: Cwd\"):\n\"python.testing.cwd\": \"${workspaceFolder}/path/to/tests/foo\"\nThen if you get the error No file or directory \"foo\", try this:\n\nOpen the test configuration dialogue (Ctrl/Cmd + Shift + P -> \"Python: ... | [
1,
0,
0
] | [
"Try opening the \"Output\" log (Ctrl+Shift+U) and run \"Python: Discover Tests\". Alternatively, you may type pytest --collect-only into the console. Maybe you are experiencing some errors with the tests themselves (such as importing errors).\nAlso, make sure to keep __init__.py file in your \"tests\" folder.\nI a... | [
-1
] | [
"python",
"visual_studio_code"
] | stackoverflow_0060665350_python_visual_studio_code.txt |
Q:
Time formatting in Python - strptime
I have a dates stored in a column. But i get errors when i format using strip time.Kindly someone help me with the code. It will be really helpful. Thanks in advance for anyone posting this.
Input:
fbtimenew= facebook['fbtime'][0:2]
fbtimenew
Output:
0 22:31:28
1 22:03:5... | Time formatting in Python - strptime | I have a dates stored in a column. But i get errors when i format using strip time.Kindly someone help me with the code. It will be really helpful. Thanks in advance for anyone posting this.
Input:
fbtimenew= facebook['fbtime'][0:2]
fbtimenew
Output:
0 22:31:28
1 22:03:50
Name: fbtime, dtype: object
Input:
for ... | [
"for times in fbtimenew:\n newtime=times.strftime(\"%I:%M %p\")\n\nIt works.\n"
] | [
0
] | [] | [] | [
"python",
"strptime"
] | stackoverflow_0074234538_python_strptime.txt |
Q:
I got an error of python flask htmlTemplateSyntaxError
I have studied python flask.
I look into programs and googled a lot of times.
The code are as follows;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" conte... | I got an error of python flask htmlTemplateSyntaxError | I have studied python flask.
I look into programs and googled a lot of times.
The code are as follows;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New ... | [
"You have a typo on the line with { % endfor %} (Line 21).\nYou have to delete the space between { and % like {% endfor %}\nIt didn't work because it waits that the {% for %} is closed\n"
] | [
0
] | [] | [] | [
"jinja2",
"python"
] | stackoverflow_0074233155_jinja2_python.txt |
Q:
Python TypeError: 'set' object is not subscriptable
def create(ids):
policy = {
'Statement': []
}
for i in range(0, len(ids), 200):
policy['Statement'].append({
'Principal': {
'AWS': list(map(lambda id: f"arn:aws:iam::{id}:root", ids[i:i + 200]))
... | Python TypeError: 'set' object is not subscriptable | def create(ids):
policy = {
'Statement': []
}
for i in range(0, len(ids), 200):
policy['Statement'].append({
'Principal': {
'AWS': list(map(lambda id: f"arn:aws:iam::{id}:root", ids[i:i + 200]))
}
})
return policy
when I make a function ca... | [
"As per the Python's Official Documentation, set data structure is referred as Unordered Collections of Unique Elements and that doesn't support operations like indexing or slicing etc.\n\nLike other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record el... | [
24,
8,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0059041955_python.txt |
Q:
Why Openshift adds cache-control private?
My flask python service on Openshift Origin is adding a Cache-Control: private.
My cache server does not make cache because this.
How can I remove this from service?
I Have added this configuration but has no effect:
apiVersion: v1
kind: Route
metadata:
annotations:
... | Why Openshift adds cache-control private? | My flask python service on Openshift Origin is adding a Cache-Control: private.
My cache server does not make cache because this.
How can I remove this from service?
I Have added this configuration but has no effect:
apiVersion: v1
kind: Route
metadata:
annotations:
haproxy.router.openshift.io/disable_cookies: 't... | [
"At a guess the haproxy router in OpenShift adds this because by default it uses a cookie to implement sticky sessions, to try and ensure traffic from a user goes back to same application instance.\n\nhttps://docs.openshift.com/container-platform/3.4/architecture/core_concepts/routes.html#haproxy-template-router\n\... | [
3,
2,
1
] | [] | [] | [
"caching",
"flask",
"openshift",
"openshift_origin",
"python"
] | stackoverflow_0043265960_caching_flask_openshift_openshift_origin_python.txt |
Q:
PyCharm getting different exceptions when running vs debugging
Recently I've been having this issue that I get different exceptions when running my code normally vs in debug mode, and sometimes even when it runs normally without hitting an Exception it will still hit an Exception during debugging, even with no bre... | PyCharm getting different exceptions when running vs debugging | Recently I've been having this issue that I get different exceptions when running my code normally vs in debug mode, and sometimes even when it runs normally without hitting an Exception it will still hit an Exception during debugging, even with no break points.
Sometimes instead of an exception I'll get "Process finis... | [
"Possible solutions:\n\nDowngrade Python. I've seen the same issue on 3.10, but not on 3.6.\nAdd extra breakpoints. In some cases adding more breakpoints prevents\nthe issue - even a breakpoint in unreachable code.\nAdd an environment variable: PYDEVD_USE_CYTHON=NO. I'm not sure what effect that has though.\n\n"
] | [
1
] | [] | [] | [
"pycharm",
"python"
] | stackoverflow_0071652377_pycharm_python.txt |
Q:
Django imagefield isn't showing any photo in the template
I'm working on a bookstore using Django. I'm trying to save each book's cover in each book created by the user using imagefield. I implemented every step in Django documentation about using imagefield but it doesn't work.
settings.py(in main project):
MEDIA... | Django imagefield isn't showing any photo in the template | I'm working on a bookstore using Django. I'm trying to save each book's cover in each book created by the user using imagefield. I implemented every step in Django documentation about using imagefield but it doesn't work.
settings.py(in main project):
MEDIA_DIR = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = MEDIA_DIR
ME... | [
"Remove / at the beginning of your MEDIA_URL.\n",
"Simply you can try this way:\nsettings.py file:\nMEDIA_URL='/media/'\nMEDIA_ROOT=os.path.join(BASE_DIR,'media')\n\nIn models.py file:\nclass books(models.Model):\n cover = models.ImageField(upload_to='cover/', blank=True) #I have removed co from here\n\nAfter ... | [
1,
0
] | [] | [] | [
"database",
"django",
"python",
"web"
] | stackoverflow_0074234431_database_django_python_web.txt |
Q:
Replace word starting with string anywhere in sentence in each row python
I am trying to replace words starting with string in text data stored in multiple rows of a dataframe. The df has 6 columns : date, user, tweet, language, coordinates, place. The replacement takes place in tweet column that has for example r... | Replace word starting with string anywhere in sentence in each row python | I am trying to replace words starting with string in text data stored in multiple rows of a dataframe. The df has 6 columns : date, user, tweet, language, coordinates, place. The replacement takes place in tweet column that has for example row 1 :
« Nous ne sommes pas très favorables au télétravail mais nous avons de s... | [
"You can try with pandas string methods. Also have a look at regex 101 to check which regex works best for your case.\ndf['tweets'] = df['tweets'].str.replace('@\\S+', '@user')\n>>>df['tweets']\n tweets\n0 « Une étude de la Spire Healthcare a révélé, q...\n1 @user @user Mais c'est super pratique car j'ai...\... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"replace",
"sentence",
"string"
] | stackoverflow_0074234739_pandas_python_replace_sentence_string.txt |
Q:
Allocate lowest value over n rows to n rows in DataFrame
I need to take the lowest value over n rows and add it to these n rows in a new colomn of the dataframe. For example:
n=3
Column 1 Column 2
5 3
3 3
4 3
7 2
8 2
2 2
5 4
... | Allocate lowest value over n rows to n rows in DataFrame | I need to take the lowest value over n rows and add it to these n rows in a new colomn of the dataframe. For example:
n=3
Column 1 Column 2
5 3
3 3
4 3
7 2
8 2
2 2
5 4
4 4
9 4
8 2
2 2
... | [
"I do not know any straight forward way to do this, but here is a working example (not elegant, but working...).\nIf you do not worry about the number of rows being dividable by n, you could use .groupby():\nimport pandas as pd\nd = {'col1': [1, 2,1,5,3,2,5,6,4,1,2] }\ndf = pd.DataFrame(data=d)\nn=3\ndf['new_col']=... | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074233005_dataframe_python.txt |
Q:
Is there a way to dispatch stored functions on a specific object?
So, what I'm trying to achieve is to collect some pandas functions in a dict object in which a key is a column name (string) and the value is a list (or any other collection) of functions. I then want to be able to dispatch those functions on a corr... | Is there a way to dispatch stored functions on a specific object? | So, what I'm trying to achieve is to collect some pandas functions in a dict object in which a key is a column name (string) and the value is a list (or any other collection) of functions. I then want to be able to dispatch those functions on a correlated column from a particular df.
I tried doing something like
dispa... | [
"A possible solution (using a toy dataframe as an example):\ntext = \"\"\"\na b\nNaN 2\n1 3\n\"\"\"\ndf = pd.read_csv(StringIO(text), sep='\\s+')\n\ndispatcher = {\"ABC\": pd.isnull}\ndispatcher.get('ABC')(df)\n\nOutput:\n a b\n0 True False\n1 False False\n\n\nIn case we want to specify the colu... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074235068_pandas_python.txt |
Q:
How to get the list of keys an `operator.itemgetter` was created with?
I have an operator.itemgetter() object, e.g.
import operator
keyfunc = operator.itemgetter("key1", "key2")
Now, I pass it around and later I wish to get the list of keys it was created with, e.g.
# doesn't exist, but should return something li... | How to get the list of keys an `operator.itemgetter` was created with? | I have an operator.itemgetter() object, e.g.
import operator
keyfunc = operator.itemgetter("key1", "key2")
Now, I pass it around and later I wish to get the list of keys it was created with, e.g.
# doesn't exist, but should return something like ("key1", "key2")
keys = keyfunc.keys()
The object stores the keys obviou... | [
"From the source code:\nclass itemgetter:\n __slots__ = ('_items', '_call')\n \n def __init__(self, item, *items):\n if not items:\n self._items = (item,) \n\nSo, the keys are stored in _items attribute. however, when you try to access it, you get an AttributeError:\n>>> a._items\nTraceb... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074235179_python.txt |
Q:
Running script every hour - deviating by few second/minutes
I am running a script every hour (timer at 3600 seconds). But with every run the timestamp of my export file (result of my script) is later than previous one. Its almost impossible to find the sweet spot and stick to approx. the same export time. Any sugg... | Running script every hour - deviating by few second/minutes | I am running a script every hour (timer at 3600 seconds). But with every run the timestamp of my export file (result of my script) is later than previous one. Its almost impossible to find the sweet spot and stick to approx. the same export time. Any suggestions to have a more stable and reliable timer?
Code:
import pa... | [
"The way to solve this is to adjust the run times based on the real clock. By real clock, I mean e.g., the UTC time, or whatever time you have on your system. The time zone is not important. What’s important is to do the scheduling based on what time it is, not based on what amount of time has elapsed since the las... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074235085_python.txt |
Q:
float() argument must be a string or a number, not 'Timestamp' - LSTM multivariate time series forecasting
I am attempting to build an LSTM model to forecast multivariant time series data.
My data looks like this:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from matpl... | float() argument must be a string or a number, not 'Timestamp' - LSTM multivariate time series forecasting | I am attempting to build an LSTM model to forecast multivariant time series data.
My data looks like this:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from matplotlib.pylab import rcParams
rcParams['figure.figsize']=20,10
from keras.models import Sequential
from keras.laye... | [
"You can convert a float to a string like this:\nfloat_to_string=str(the_float)\n\n"
] | [
0
] | [] | [] | [
"lstm",
"machine_learning",
"python"
] | stackoverflow_0074235392_lstm_machine_learning_python.txt |
Q:
how to extract rows from csv file in python?
In my code, I have tables for each expression. Each table is in csv format.
for example:
tables.csv
+-----+-----+----------------------------+
| a | b | a - b > 0 |
+-----+-----+----------------------------+
| 0 | 0 | 0 ... | how to extract rows from csv file in python? | In my code, I have tables for each expression. Each table is in csv format.
for example:
tables.csv
+-----+-----+----------------------------+
| a | b | a - b > 0 |
+-----+-----+----------------------------+
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1... | [
"I'm not sure for what you need the third column but you can easily select a subset of rows with a condition. Just use the following.\ndf[df.a - df.b > 0]\n\nor\ndf.loc[df.a - df.b > 0]\n\n"
] | [
0
] | [] | [] | [
"csv",
"dataframe",
"extract",
"pandas",
"python"
] | stackoverflow_0074235536_csv_dataframe_extract_pandas_python.txt |
Q:
For returning 3 result each loop
can someone help me out.
I need a loop that returns 3 results from a list for each loop
Example:
lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for x in lst:
print(x[0])
print(x[1])
print(x[2])
should return
1,2,3
4,5,6
7,8,9
10,11,12
13,14,15
16
im using flask
{% fo... | For returning 3 result each loop | can someone help me out.
I need a loop that returns 3 results from a list for each loop
Example:
lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for x in lst:
print(x[0])
print(x[1])
print(x[2])
should return
1,2,3
4,5,6
7,8,9
10,11,12
13,14,15
16
im using flask
{% for i in getdataasset %}
{{getdataa... | [
"Use slices\nlst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]\n\nfor i in range(0,len(lst),3):\n print(*lst[i:i+3])\n\n1 2 3\n4 5 6\n7 8 9\n10 11 12\n13 14 15\n16\n\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074235643_python.txt |
Q:
How to remove the commas from string with no spaces for int conversion
I'm trying to remove the commas from this data set so they can be converted to int and be summed up all but I can't seem to find any way to do it without introducing spaces to the number values.
parse = g.readlines()[8:]
for x in parse:
... | How to remove the commas from string with no spaces for int conversion |
I'm trying to remove the commas from this data set so they can be converted to int and be summed up all but I can't seem to find any way to do it without introducing spaces to the number values.
parse = g.readlines()[8:]
for x in parse:
val0 = x.strip(',')
val = val0.split(" ")
i15.append(val[1])
this ... | [
"parse = g.readlines()[8:]\nfor x in parse:\n val0 = x.replace(',' , '')\n val = val0.split(\" \")\n i15.append(val[1])\n\nTry this\n",
"Try this, it works like charm for me\nwith open(\"dataset.txt\") as f:\n contents=f.read()\n contents_without_comma=contents.replace(\",\",\"\")\n print(conten... | [
1,
0,
0,
0
] | [] | [] | [
"arrays",
"integer",
"python",
"python_3.x",
"string"
] | stackoverflow_0074235395_arrays_integer_python_python_3.x_string.txt |
Q:
Why I have to pause with gtts to hear the sound
I had this script working to hear an audio from text with gtts without having to save the mp3, using BytesIo, but now if I do not put a time.sleep at the end I cannot hear the sound. Why? Is there a solution different from putting a pause to the end?
from gtts import... | Why I have to pause with gtts to hear the sound | I had this script working to hear an audio from text with gtts without having to save the mp3, using BytesIo, but now if I do not put a time.sleep at the end I cannot hear the sound. Why? Is there a solution different from putting a pause to the end?
from gtts import gTTS
from io import BytesIO
import pygame
import tim... | [
"Maybe because the main thread ends before the sounds play. You can try to execute your .play() in an other thread and order the main thread to wait the end of this thread ?\n"
] | [
0
] | [] | [] | [
"gtts",
"python"
] | stackoverflow_0074235613_gtts_python.txt |
Q:
Replace multiple characters in string using dictionary in python
I have some strings that have the following characters: &, <, and >. In the project I am working on, these are reserved characters and need to be escaped using & for &, < for <, etc. What is this best approach to this? Currently thinking of ei... | Replace multiple characters in string using dictionary in python | I have some strings that have the following characters: &, <, and >. In the project I am working on, these are reserved characters and need to be escaped using & for &, < for <, etc. What is this best approach to this? Currently thinking of either multiple if statements that look for it one-by-one using str.repl... | [
"You can use html.escape function(html is part of python standard library) to replace the special characters &, < and > with &<>\n>>> import html\n>>>\n>>> html.escape(\"&<>\")\n'&<>'\n>>>\n>>> help(html.escape)\nHelp on function escape in module html:\n\nescape(s, quote=True)\n Replace speci... | [
3
] | [] | [] | [
"dictionary",
"python",
"python_3.x",
"str_replace",
"string"
] | stackoverflow_0074235734_dictionary_python_python_3.x_str_replace_string.txt |
Q:
python setup.py bdist_wheel did not run successfully , installing the psycopg2
I just want to install psycopg2 and I get the following error message:
PS D:\Visualalize_data> pip3 install psycopg2
Collecting psycopg2
Using cached psycopg2-2.9.5.tar.gz (384 kB)
Preparing metadata (setup.py) ... done
Building whe... | python setup.py bdist_wheel did not run successfully , installing the psycopg2 | I just want to install psycopg2 and I get the following error message:
PS D:\Visualalize_data> pip3 install psycopg2
Collecting psycopg2
Using cached psycopg2-2.9.5.tar.gz (384 kB)
Preparing metadata (setup.py) ... done
Building wheels for collected packages: psycopg2
Building wheel for psycopg2 (setup.py) ... er... | [
"Have you tried doing what the messege tells you to and downloaded\nMicrosoft Visual C++ 14.0 or greater?\nYou can install it at \"Microsoft C++ Build Tools\": https://visualstudio.microsoft.com/visual-cpp-build-tools/\n"
] | [
0
] | [] | [] | [
"psycopg2",
"python"
] | stackoverflow_0074235736_psycopg2_python.txt |
Q:
Threading error raised during KeyboardInterrupt
I am having a very basic function that takes in a string called name and a callback function. My objective is to be able to terminate from the function, by raising a Keyboard interrupt gracefully.
On the main thread, I am watching for Keyboard interrupt, while foo is... | Threading error raised during KeyboardInterrupt | I am having a very basic function that takes in a string called name and a callback function. My objective is to be able to terminate from the function, by raising a Keyboard interrupt gracefully.
On the main thread, I am watching for Keyboard interrupt, while foo is running on the background thread.
However at thread.... | [
"In other questions like linux - Cannot kill Python script with Ctrl-C - Stack Overflow you can see that Ctrl+C stops only code in main thread but not event_loop in thread`.\nAs for me you shouldn't use thread.join() if you have daemon=True - and it will automatically kill thread at the end of code.\ntry:\n whil... | [
0
] | [] | [] | [
"keyboardinterrupt",
"python",
"python_3.x",
"python_asyncio",
"python_multithreading"
] | stackoverflow_0074215817_keyboardinterrupt_python_python_3.x_python_asyncio_python_multithreading.txt |
Q:
How to use @token_required decorator for PyJWT in Flask App to access route after user gets logged in?
I've used PyJWT for authenticating the user now my main concern is how to use authentication decorator in API endpoints as I've addes SQL query to to fetch user detail using uid in my route but in token_required ... | How to use @token_required decorator for PyJWT in Flask App to access route after user gets logged in? | I've used PyJWT for authenticating the user now my main concern is how to use authentication decorator in API endpoints as I've addes SQL query to to fetch user detail using uid in my route but in token_required definition for current user do I've to add that query again?
Ex. After login I want to access API to display... | [
"First of all import flask and JWTManager\nfrom flask import Flask, jsonify\nfrom flask_jwt_extended import (create_access_token,get_jwt_identity,jwt_required,JWTManager)\n\nDefine the Flask app and set a JWT_SECRET_KEY\napp = Flask(__name__)\napp.config[\"JWT_SECRET_KEY\"] = \"supersecret\" # Change this!\n\nInit... | [
0
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"pyjwt",
"python",
"sqlalchemy"
] | stackoverflow_0074224094_flask_flask_sqlalchemy_pyjwt_python_sqlalchemy.txt |
Q:
How to calculate percentage of row value in sum of total values in that column in python?
I have data frame containing red and blue balloons and I want to see what is the percentage of either balloons using Python:
Current:
Balloons Count
Red 10
Blue 90
Wanted:
Balloons Count Percentage
Red 10 10%... | How to calculate percentage of row value in sum of total values in that column in python? | I have data frame containing red and blue balloons and I want to see what is the percentage of either balloons using Python:
Current:
Balloons Count
Red 10
Blue 90
Wanted:
Balloons Count Percentage
Red 10 10%
Blue 90 90%
| [
"maybe\nred_percent = 100 * red / (red + blue)\nblue_percent = 100 * blue / (red + blue)\n \n\nor:\nred_percent = 100 * red / (red + blue)\nblue_percent = 100 - red_percent \n\n",
"Resolved:\ndata['Percentage'] = (data['Count']/data['Count'].sum()) *100\n\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074102700_python.txt |
Q:
Minimax Optimization - Gekko
I am trying to formulate this minimax optimization function. I am not what part of this code is not written right.
This function seeks to schedule the charging start time of EVs in a way that the peak of the demand is minimized. On the other hand, peak of the demand is the maximum of t... | Minimax Optimization - Gekko |
I am trying to formulate this minimax optimization function. I am not what part of this code is not written right.
This function seeks to schedule the charging start time of EVs in a way that the peak of the demand is minimized. On the other hand, peak of the demand is the maximum of the equations, which determine in ... | [
"Minimax in gekko requires that the variable (e.g. x1-x3) are all Gekko types.\n min Z\n s.t. x1 + x2 + x3 = 15\n Z >= x1\n Z >= x2\n Z >= x3\n\nHere is an example for the above problem where the solution is x1=x2=x3=5.\nfrom gekko import GEKKO\nm = GEKKO(remote=False)\nx1,x2,x3,Z = m.Array(m.Var,4)\... | [
0
] | [] | [] | [
"gekko",
"minimax",
"optimization",
"python",
"scheduling"
] | stackoverflow_0074215767_gekko_minimax_optimization_python_scheduling.txt |
Q:
How do I create a dictionary with input symbols as keys and ascii codes as values?
I'm making a dictionary in which the keys will be one-character symbols separates by a space that the user inputs. I'm assuming that I have call the ord value in a separate line but I'm not sure how to correctly phrase it. Below is ... | How do I create a dictionary with input symbols as keys and ascii codes as values? | I'm making a dictionary in which the keys will be one-character symbols separates by a space that the user inputs. I'm assuming that I have call the ord value in a separate line but I'm not sure how to correctly phrase it. Below is the code I have currently:
inp = input()
inp = inp.split(" ")
d = dict.fromkeys(inp, o... | [
"A dictionary comprehension would give you what you want:\ninp = input()\nd = {x: ord(x) for x in inp}\nprint(d)\n\nThis iterates through the string inp and constructs the key/value pairs from the iterator, x, and ord(x).\nThis doesn't remove spaces, as you seem to possibly be after by inp.split(\" \"), but I inter... | [
1
] | [
"I converted the input with the split function into a list. Then I added the inputs with the ord() function to an empty list with the append function. Then i created a dictionary called d and combined the two lists with using the zip() function. In this way, created a dictionary with the single characters I entered... | [
-1
] | [
"dictionary",
"ord",
"python"
] | stackoverflow_0074235582_dictionary_ord_python.txt |
Q:
Can't Find SetupTools -
I'm trying to install Plotly through pip, and I'm unable to install the Plotly packaging in particular. I get the following error:
C:\Python 3.6>python -m pip show SetupTools
Name: setuptools
Version: 39.0.1
Summary: Easily download, build, install, upgrade, and uninstall Python packages
H... | Can't Find SetupTools - | I'm trying to install Plotly through pip, and I'm unable to install the Plotly packaging in particular. I get the following error:
C:\Python 3.6>python -m pip show SetupTools
Name: setuptools
Version: 39.0.1
Summary: Easily download, build, install, upgrade, and uninstall Python packages
Home-page: https://github.com/... | [
"You might need pip and setuptools installed for your user:\npip3 install -U pip setuptools\n\n"
] | [
0
] | [] | [] | [
"pip",
"plotly",
"python"
] | stackoverflow_0049437764_pip_plotly_python.txt |
Q:
Entry with tkinter
I am trying to enter variables to use in an API call app. When I use the normal python input thing, it works, but I want to be able to enter these via the entry widget with tkinter. When I try to use the tkinter entry widget, it does not work.
`
import API_test
import tkinter
from tkinter import... | Entry with tkinter | I am trying to enter variables to use in an API call app. When I use the normal python input thing, it works, but I want to be able to enter these via the entry widget with tkinter. When I try to use the tkinter entry widget, it does not work.
`
import API_test
import tkinter
from tkinter import *
import random
import ... | [
"import tkinter\n##root for Tkinter app\nroot = tkinter.Tk()\nroot.geometry(\"1000x400\")\n\nstringvar1 = tkinter.StringVar()\nstringvar2 = tkinter.StringVar()\n\n##tkinter labels\nL1 = tkinter.Label(text=\"Enter City \",)\nL2 = tkinter.Label(text = \"Enter Cuisine \",)\n\n##tkinter entry\nrootentry1 = tkinter.Entr... | [
0,
0
] | [] | [] | [
"api",
"input",
"python",
"tkinter"
] | stackoverflow_0074235709_api_input_python_tkinter.txt |
Q:
How to apply operations on each array item in a column in Presto?
We want to check if the array items in text_array column start with "a" in the input table, and store the results into the third column, so we get the following output table.
My first question is: Is there any way to get output table from input tab... | How to apply operations on each array item in a column in Presto? | We want to check if the array items in text_array column start with "a" in the input table, and store the results into the third column, so we get the following output table.
My first question is: Is there any way to get output table from input table using presto?
In python we can define a function for it, like:
def m... | [
"You can use transform from array functions:\n- sample data\nwith dataset(id, text_array) AS (\n values (1, array['ax', 'by']),\n (2, array['ax', 'ay', 'cz'])\n)\n\n-- query\nselect *,\n transform(text_array, el -> el like 'a%') starts_with_a\nfrom dataset;\n\nOutput:\n\n\n\n\nid\ntext_array\nstarts_with_a\n\... | [
1
] | [] | [] | [
"presto",
"python",
"sql",
"trino"
] | stackoverflow_0074232611_presto_python_sql_trino.txt |
Q:
How to write in a specific cell with pandas and iterrows?
I'm trying to learn how to use both excel and python. And i'm trying to found out how to write in a speicific cell with pandas. This is what i tought would work :
import pandas as pd
raw_data = pd.read_excel(filepath, sheet_name="Feuil2")
for row in raw_d... | How to write in a specific cell with pandas and iterrows? | I'm trying to learn how to use both excel and python. And i'm trying to found out how to write in a speicific cell with pandas. This is what i tought would work :
import pandas as pd
raw_data = pd.read_excel(filepath, sheet_name="Feuil2")
for row in raw_data.iterrows():
print(row[1]['name'])
row[1]['name'] = ... | [
"Your code doesn't work because df.itterrows() yields new Series, and you're modifying those instead of your original dataframe. Additionally, your \"row\" is a tuple of the row index and the row object, which may be confusing you. Here's how you could do it (or via some of the other indexing methods).\nfor i, row... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"pandas",
"python"
] | stackoverflow_0074235771_excel_openpyxl_pandas_python.txt |
Q:
Tweepy: filter tweets stream by keywords only
I am interested in retrieving tweet streams about the forth-coming Nigeria's general election. I want all tweets from Nigeria, which contains information about 4 major presidential candidates only ("atiku-abubakar-rabiu-kwankwaso-peter-obi-bola-tinubu-inec").
However, ... | Tweepy: filter tweets stream by keywords only | I am interested in retrieving tweet streams about the forth-coming Nigeria's general election. I want all tweets from Nigeria, which contains information about 4 major presidential candidates only ("atiku-abubakar-rabiu-kwankwaso-peter-obi-bola-tinubu-inec").
However, from what I am retrieving are the moments are tweet... | [
"The value of tag in the API call you are making is not a search term. The search term is the first value in the rule.\nThis is intended just to enable you to label your stream filter rules. When a Tweet is matched against the rule, it will be labelled with that tag. So, you might want to get Tweets about cats with... | [
0
] | [] | [] | [
"python",
"tweepy",
"twitter",
"twitter_api_v2",
"twitterapi_python"
] | stackoverflow_0074234337_python_tweepy_twitter_twitter_api_v2_twitterapi_python.txt |
Q:
how to convert list of dicts into dataframe
list_of_dict = [
{
'@id': '54',
'@name': '009de580ae2a20ad.jpg',
'@width': '1080',
'@height': '720',
'box': {
'@label': 'Television',
'@occluded': '0',
'@source': 'manual',
... | how to convert list of dicts into dataframe | list_of_dict = [
{
'@id': '54',
'@name': '009de580ae2a20ad.jpg',
'@width': '1080',
'@height': '720',
'box': {
'@label': 'Television',
'@occluded': '0',
'@source': 'manual',
'@xtl': '130.40833715734814',
'@ytl... | [
"If you just want to make a dataframe, with box containing more than one dict, you can just use\ndf = pd.DataFrame.from_records(list_of_dict)\n\nyou will get this datadframe\nA cleaner solution would be to create a row in the dataset for each dict inside the @box. To do so you would have to change the structure of ... | [
0,
0
] | [] | [] | [
"dataframe",
"dictionary",
"list",
"pandas",
"python"
] | stackoverflow_0074231599_dataframe_dictionary_list_pandas_python.txt |
Q:
matplotlib not showing x axis and y axis labels and values and chart title as well
I am new to python just following a tutorial but the output is not same as expected matplotlib is not showing any thing on chart except the bars.
Here is the code
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes... | matplotlib not showing x axis and y axis labels and values and chart title as well | I am new to python just following a tutorial but the output is not same as expected matplotlib is not showing any thing on chart except the bars.
Here is the code
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
packets = ['1.', '2', '3', '4', '5']
testTime = [2.3,1.7,3.5,2.9,1.2]
plt.ba... | [
"by this fig.add_axes([0,0,1,1]) the axes will cover the whole plot, remove it or add a fraction (less than 1) , and you will be fine :\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\n# ax = fig.add_axes([0,0,1,1])\npackets = ['1.', '2', '3', '4', '5']\ntestTime = [2.3,1.7,3.5,2.9,1.2]\nplt.bar(packets,test... | [
4,
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0072776363_matplotlib_python.txt |
Q:
Python:Compare 2 lists and get the results
I have 2 lists with lot of sub-lists in it (approx 28000) like below:
list1 = [[1,0,0],[1,0,1],[1,1,0],[1,2,0],[2,0,1],[2,1,1]]
list2 = [[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,2,0],[1,2,1],[2,0,1],[2,0,2],[2,1,1],[2,1,2],[3,0,1]]
Each sub-list would always have 3 val... | Python:Compare 2 lists and get the results | I have 2 lists with lot of sub-lists in it (approx 28000) like below:
list1 = [[1,0,0],[1,0,1],[1,1,0],[1,2,0],[2,0,1],[2,1,1]]
list2 = [[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,2,0],[1,2,1],[2,0,1],[2,0,2],[2,1,1],[2,1,2],[3,0,1]]
Each sub-list would always have 3 values. Consider them as [x,y,z]
Now I want to get ... | [
"I could not understand the relationship between the 2 lists, but I think that the better way you can do it is by using pattern matching.\nYou can make patterns and take an action per patter.\nExample:\nfor sublist in listA:\n match sublist:\n case [_,1,1]:\n # do something\n ...\n ... | [
0
] | [] | [] | [
"list",
"numpy",
"pandas",
"python"
] | stackoverflow_0074235164_list_numpy_pandas_python.txt |
Q:
Parallel alternative to subprocess.run() in Python
I'm trying to execute a command in a more efficient way than just using a for loop.
I have the following code which I'm currently running within a for loop, that I'd like to make faster by using all available CPUs:
__location__ = os.path.realpath(os.path.join(os.g... | Parallel alternative to subprocess.run() in Python | I'm trying to execute a command in a more efficient way than just using a for loop.
I have the following code which I'm currently running within a for loop, that I'd like to make faster by using all available CPUs:
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
for file in glob.gl... | [
"assuming that the file you are opening is a single-threaded application, you can just run it in parallel using python's ThreadPool, which by default creates as many threads as the threads your CPU can support, ie: if your CPU is 4C/8T it will spawn 8 threads.\nfrom multiprocessing.pool import ThreadPool\nimport gl... | [
0
] | [] | [] | [
"multiprocessing",
"parallel_processing",
"python"
] | stackoverflow_0074236025_multiprocessing_parallel_processing_python.txt |
Q:
Why is python not pythoning
print("Hello, this is my first mini-game. Let's test it out")
character = input("Please choose your gender (male, female): ")
age = input("Please choose your age (child, teen boomer): ")
hobby = input("Please choose your hobby(gaming, school, sport): ")
if (character != "male") or ("f... | Why is python not pythoning | print("Hello, this is my first mini-game. Let's test it out")
character = input("Please choose your gender (male, female): ")
age = input("Please choose your age (child, teen boomer): ")
hobby = input("Please choose your hobby(gaming, school, sport): ")
if (character != "male") or ("female") and (age != "child") or (... | [
"You have some mistakes in the way you check the options.\nFirstly how you check if a variable has value in a list:\n(character != \"male\") or (\"female\")\n\nThis is incorrect, the first part (character != \"male\") correctly checks if the value of character is not male, the second part ((\"female\")) though chec... | [
0
] | [] | [] | [
"conditional_statements",
"python"
] | stackoverflow_0074236124_conditional_statements_python.txt |
Q:
check variable in a different def function (python)
I am trying to check in def_2_is_apple if the variable APPLE is on the game board in def_1_print_game_board but if i try it like that i only get that i need to
define row and column in def_2
def_2_is_apple is a bool and should be set to True if the variable APPLE... | check variable in a different def function (python) | I am trying to check in def_2_is_apple if the variable APPLE is on the game board in def_1_print_game_board but if i try it like that i only get that i need to
define row and column in def_2
def_2_is_apple is a bool and should be set to True if the variable APPLE is in def_1_print_game_board
import random
BOARD_WIDTH... | [
"To sum up what I said in my comments, here is a correct code for the _2_is_apple function (independently of the rest of the code):\ndef _2_is_apple():\n for row in range(BOARD_HEIGHT):\n for column in range(BOARD_WIDTH):\n if APPLE == f\"{chr(row + 65)}{column}\":\n return True\... | [
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074235897_function_python.txt |
Q:
Trouble reading data from .dat file obtained from an SDR
I am trying to read data in Python for some signal processing. The data I have obtained from a SDR is stored as .dat
with open('test.dat', 'r', encoding="utf8") as f:
hackrf_data = f.read()
The error I am getting at the moment says "'utf-8' codec can't deco... | Trouble reading data from .dat file obtained from an SDR | I am trying to read data in Python for some signal processing. The data I have obtained from a SDR is stored as .dat
with open('test.dat', 'r', encoding="utf8") as f:
hackrf_data = f.read()
The error I am getting at the moment says "'utf-8' codec can't decode byte 0xe7 in position 3: invalid continuation byte" and I a... | [
"Try ignoring the errors in encoding,\nwith open('test.dat', 'r', encoding=\"utf8\", errors='ignore') as f:\n hackrf_data = f.read()\n\nOf course, it would be better if you can find the true encoding of the file.\n",
"The file encoding is uint8 alternating I & Q samples, not utf8.\n",
"if you use numpy it is... | [
0,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"signal_processing",
"signals",
"spyder"
] | stackoverflow_0056648676_python_python_3.x_signal_processing_signals_spyder.txt |
Q:
UserWarning: X does not have valid feature names, but LinearRegression was fitted with feature names warnings.warn(
screenshot here Help please?
Already tried adding .values to the X's, still resulted in an error. Any suggestions?
X = df[['Personal income','Personal saving']]
y = df['Gross domestic product']
X_tr... | UserWarning: X does not have valid feature names, but LinearRegression was fitted with feature names warnings.warn( | screenshot here Help please?
Already tried adding .values to the X's, still resulted in an error. Any suggestions?
X = df[['Personal income','Personal saving']]
y = df['Gross domestic product']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
regr = linear_model.LinearRegressio... | [
"As stated in this issue https://github.com/tylerjrichards/Getting-Started-with-Streamlit-for-Data-Science/issues/5 , converting X_train dataframe to np array (X_train.values) before fitting removes the warning.\nit did for my testing : you can either try :\nX_train, X_test, y_train, y_test = train_test_split(X.val... | [
0
] | [] | [] | [
"linear_regression",
"pandas",
"python",
"scikit_learn",
"sklearn_pandas"
] | stackoverflow_0074232045_linear_regression_pandas_python_scikit_learn_sklearn_pandas.txt |
Q:
How to increase the length of a python list based on a parameter?
I have the following lists:
l1 = list(range(10))
l2 = [False for i in range(10)]
I can merge them into a list of dictionaries by implementing the following code:
res = [{l1[i]: l2[i] for i in range(len(l1))}]
My result is the following:
[{0: False... | How to increase the length of a python list based on a parameter? | I have the following lists:
l1 = list(range(10))
l2 = [False for i in range(10)]
I can merge them into a list of dictionaries by implementing the following code:
res = [{l1[i]: l2[i] for i in range(len(l1))}]
My result is the following:
[{0: False,
1: False,
2: False,
3: False,
4: False,
5: False,
6: Fals... | [
"Just expand your comprehension by another loop like this:\nN=3\nres = [{l1[i]: l2[i] for i in range(len(l1))} for _ in range(N)]\nprint(res)\n\n[{0: False,\n 1: False,\n 2: False,\n 3: False,\n 4: False,\n 5: False,\n 6: False,\n 7: False,\n 8: False,\n 9: False},\n {0: False,\n 1: False,\n 2: False,\n ... | [
3,
2,
1
] | [
"res = [{l1[i]: l2[i] for i in range(len(l1))}] * x\n\n",
"You can multiply a list.\nres = [{i: False for i in range(10)}] * x\n\n"
] | [
-1,
-1
] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074235806_dictionary_list_python.txt |
Q:
plotly: bar stacking graph
I have a Dataframe with data as follows:
data={'A': {'2020_01': 3, '2020_02': 3, '2020_03': 1, '2020_04': 3, '2020_05': 1},
'B': {'2020_01': 0, '2020_02': 0, '2020_03': 3, '2020_04': 0, '2020_05': 2},
'other': {'2020_01': 0,
'2020_02': 0,
'2020_03': 3,
'2020_04': 0,
'2020_05': ... | plotly: bar stacking graph | I have a Dataframe with data as follows:
data={'A': {'2020_01': 3, '2020_02': 3, '2020_03': 1, '2020_04': 3, '2020_05': 1},
'B': {'2020_01': 0, '2020_02': 0, '2020_03': 3, '2020_04': 0, '2020_05': 2},
'other': {'2020_01': 0,
'2020_02': 0,
'2020_03': 3,
'2020_04': 0,
'2020_05': 2},
'total': {'2020_01': 3,
'... | [
"All you should do the following:\n\nReset the index and use it as column.\n\nUse melt function to convert the dataframe in the appropriate form.\n\nUse barmode=\"stack\" to plot the stacked bars.\nimport plotly.express as px\nimport pandas as pd\n\ndf.reset_index(inplace=True)\ndf = df.iloc[:,:-1].melt(id_vars='in... | [
2
] | [] | [] | [
"graph",
"plot",
"plotly",
"python"
] | stackoverflow_0074235638_graph_plot_plotly_python.txt |
Q:
Find shortest path in graph with a set starting node and that goes through a subset of nodes
Basically my goal is to find the target node to solve the TSP. In order to find this target node I need to know the shortest path between two nodes, specifying only the starting point where:
The minimum cost path visits a... | Find shortest path in graph with a set starting node and that goes through a subset of nodes | Basically my goal is to find the target node to solve the TSP. In order to find this target node I need to know the shortest path between two nodes, specifying only the starting point where:
The minimum cost path visits all nodes in subset of nodes.
Cost is minimum.
My return function would return a NodeId which woul... | [
"You want the minimum spanning tree algorithm, modified to span your subset of nodes.\nHere is how it goes:\n- LOOP over every pair of nodes in the subset\n - APPLY Dijkstra algorithm to find shortest path between node pair.\n- CREATE new graph, containing only the nodes in the subset\n- ADD links between nodes in... | [
0
] | [] | [] | [
"graph_theory",
"python",
"traveling_salesman"
] | stackoverflow_0074234281_graph_theory_python_traveling_salesman.txt |
Q:
extract .dxf data using ezdxf to add to a pandas dataframe
The end goal is to extract the text contained on a specific layer, inside of a named view, from the model space. I have the layer restriction (the text in yellow for visual), but I can't seem to figure out the syntax (if possible) to limit the query to eit... | extract .dxf data using ezdxf to add to a pandas dataframe | The end goal is to extract the text contained on a specific layer, inside of a named view, from the model space. I have the layer restriction (the text in yellow for visual), but I can't seem to figure out the syntax (if possible) to limit the query to either items inside one of the named views, or within a bounding bo... | [
"The ezdxf package does not have a feature for selecting entities based on location and size, but a bounding box based implementation is relatively easy.\nIt is important to know that bounding boxes of text based entities (TEXT, MTEXT) are inaccurate because matplotlib (used by ezdxf to render text) renders TTF fon... | [
1
] | [] | [] | [
"ezdxf",
"python"
] | stackoverflow_0074228489_ezdxf_python.txt |
Q:
How to obtain sheet names from XLS files without loading the whole file?
I'm currently using pandas to read an Excel file and present its sheet names to the user, so he can select which sheet he would like to use. The problem is that the files are really big (70 columns x 65k rows), taking up to 14s to load on a n... | How to obtain sheet names from XLS files without loading the whole file? | I'm currently using pandas to read an Excel file and present its sheet names to the user, so he can select which sheet he would like to use. The problem is that the files are really big (70 columns x 65k rows), taking up to 14s to load on a notebook (the same data in a CSV file is taking 3s).
My code in panda goes like... | [
"you can use the xlrd library and open the workbook with the \"on_demand=True\" flag, so that the sheets won't be loaded automaticaly.\nThan you can retrieve the sheet names in a similar way to pandas:\nimport xlrd\nxls = xlrd.open_workbook(r'<path_to_your_excel_file>', on_demand=True)\nprint xls.sheet_names() # <-... | [
80,
18,
17,
2,
2,
1,
0
] | [
"you can also use \ndata=pd.read_excel('demanddata.xlsx',sheet_name='oil&gas')\nprint(data) \n\nHere demanddata is the name of your file\noil&gas is one of your sheet name.Let there may be n number of sheet in your worksheet.Just Give the Name of the sheet which you like to fetch at Sheet_name=\"Name of Your requ... | [
-4
] | [
"excel",
"pandas",
"python",
"xlrd"
] | stackoverflow_0012250024_excel_pandas_python_xlrd.txt |
Q:
Updating values of a column from multiple columns if the values are present in those columns
I am trying to update Col1 with values from Col2,Col3... if values are found in any of them. A row would have only one value, but it can have "-" but that should be treated as NaN
df = pd.DataFrame(
[
['A',np.n... | Updating values of a column from multiple columns if the values are present in those columns | I am trying to update Col1 with values from Col2,Col3... if values are found in any of them. A row would have only one value, but it can have "-" but that should be treated as NaN
df = pd.DataFrame(
[
['A',np.nan,np.nan,np.nan,np.nan,np.nan],
[np.nan,np.nan,np.nan,'C',np.nan,np.nan],
[np.na... | [
"Here is one way to go about it\n\n# convert the values in the row to series, and sort, NaN moves to the end\ndf2=df.apply(lambda x: pd.Series(x).sort_values(ignore_index=True), axis=1)\n\n# rename df2 column as df columns\ndf2.columns=df.columns\n\n# drop where all values in the column as null\ndf2.dropna(axis=1, ... | [
2,
0,
0
] | [] | [] | [
"database",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074227788_database_dataframe_pandas_python.txt |
Q:
Make pool.apply_async wait to finish current jobs before submitting new jobs
I have a nested for loop which I have used multiprocessing.Pool to parallize my inner loop. Here is an example code:
for i in range(N):
for k in range(L):
x[k] = Do_Something(x[k])
So as you can see, every iteration of... | Make pool.apply_async wait to finish current jobs before submitting new jobs | I have a nested for loop which I have used multiprocessing.Pool to parallize my inner loop. Here is an example code:
for i in range(N):
for k in range(L):
x[k] = Do_Something(x[k])
So as you can see, every iteration of i depends on the previous interation while the k for loop is "embarassingly" par... | [
"There are a few of issues with your current code:\n\nThe args parameter to the apply_async method takes an iterable, e.g. a list or tuple. You have specified args=(k) but (k) is not a tuple, it is just a parenthesized expression. You need args=(k,).\nYour calls to pool.join() and pool.close() are in the wrong orde... | [
1
] | [] | [] | [
"multiprocessing",
"parallel_processing",
"python",
"python_3.x"
] | stackoverflow_0074228487_multiprocessing_parallel_processing_python_python_3.x.txt |
Q:
How to sort a list with two keys but one in reverse order?
I was wondering what would be a Pythonic way of sorting a list of tuples by two keys whereby sorting with one (and only one) key would be in a reverse order and sorting with the the other would be case insensitive.
More specifically, I have a list containi... | How to sort a list with two keys but one in reverse order? | I was wondering what would be a Pythonic way of sorting a list of tuples by two keys whereby sorting with one (and only one) key would be in a reverse order and sorting with the the other would be case insensitive.
More specifically, I have a list containing tuples like:
myList = [(ele1A, ele2A),(ele1B, ele2B),(ele1C, ... | [
"Two keys will be used when we need to sort a list with two constraints: one in ascending order and the other in descending, in the same list or any\nIn your example,\nsortedList = sorted(myList, key = lambda y: (y[0].lower(), y[1]))\n\nyou can sort entire list only in one order.\nYou can try these and check what's... | [
64,
50,
4,
4,
2,
1,
0
] | [] | [] | [
"key",
"python",
"sorting",
"tuples"
] | stackoverflow_0037693373_key_python_sorting_tuples.txt |
Q:
Implementing backtracking line search algorithm for unconstrained optimization problem
I cannot wrap my head around how to implement the backtracking line search algorithm into python. The algorithm itself is:
here
Another form of the algorithm is:
here
In theory, they are the exact same.
I am trying to implement ... | Implementing backtracking line search algorithm for unconstrained optimization problem | I cannot wrap my head around how to implement the backtracking line search algorithm into python. The algorithm itself is:
here
Another form of the algorithm is:
here
In theory, they are the exact same.
I am trying to implement this in python to solve an unconstrained optimization problem with a given start point. This... | [
"import numpy as np\nalpha = 0.3\nbeta = 0.8\n\nf = lambda x: (x[0]**2 + 3*x[1]*x[0] + 12)\ndfx1 = lambda x: (2*x[0] + 3*x[1])\ndfx2 = lambda x: (3*x[0])\n\nt = 1\ncount = 1\nx0 = np.array([2,3])\ndx0 = np.array([.1, 0.05])\n\n\ndef backtrack(x0, dfx1, dfx2, t, alpha, beta, count):\n while (f(x0) - (f(x0 - t*np.... | [
4,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0052204231_algorithm_python.txt |
Q:
Export Last Four Years' yfinance Balance Sheet Results Into Single Excel Workbook?
The code below exports the latest annual Balance Sheet data. I trying to get all the available annual Balance Sheet data. Four years is usually available (e.g., GOOG). Credit to Luis Alejandro Vargas Ramos, who basically created ... | Export Last Four Years' yfinance Balance Sheet Results Into Single Excel Workbook? | The code below exports the latest annual Balance Sheet data. I trying to get all the available annual Balance Sheet data. Four years is usually available (e.g., GOOG). Credit to Luis Alejandro Vargas Ramos, who basically created all this code from my other questions (Question 1 & Question 2).
import pandas as pd
imp... | [
"I was able to accomplish this using yahooquery, which is really fast instead of yfinance.\nimport pandas as pd\nimport yfinance as yf\nimport datetime\nimport time\nfrom yahooquery import Ticker\n\nsymbols = ['fb', 'aapl', 'amzn', 'nflx', 'goog']\n\nfaang = Ticker(symbols)\n\nfaang.balance_sheet()\n\n#Then build t... | [
0
] | [] | [] | [
"dataframe",
"excel",
"pandas",
"python",
"yfinance"
] | stackoverflow_0074226925_dataframe_excel_pandas_python_yfinance.txt |
Q:
Python How to check range of certain chars in a string, multiple times?
Let's say I have a string
s = "nnbbbnbbbnnnnbb"
How would I check the range of "b's" while it's seperated by "n's". I want it to look like:
arr = [(2,5),(6,9),(13,15)]
A:
Here is a possible solution using itertools.groupby:
from itertools i... | Python How to check range of certain chars in a string, multiple times? | Let's say I have a string
s = "nnbbbnbbbnnnnbb"
How would I check the range of "b's" while it's seperated by "n's". I want it to look like:
arr = [(2,5),(6,9),(13,15)]
| [
"Here is a possible solution using itertools.groupby:\nfrom itertools import groupby\n\nresult = []\nn = 0\nfor c, g in groupby(s):\n g = list(g)\n if c == 'b':\n result.append((n, n + len(g)))\n n += len(g)\n\nResult with s = \"nnbbbnbbbnnnnbb\":\n>>> result\n[(2, 5), (6, 9), (13, 15)]\n\n",
"You... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074236222_python.txt |
Q:
Django-allauth and logout issue with Google
I'm using django-allauth specifically and only for Google authentication. I'm experiencing a few odd issues:
Logout from a Chrome browser and the user is still remembered upon the next login. The user is never redirected to a Google login.
Log out from a Safari brows... | Django-allauth and logout issue with Google | I'm using django-allauth specifically and only for Google authentication. I'm experiencing a few odd issues:
Logout from a Chrome browser and the user is still remembered upon the next login. The user is never redirected to a Google login.
Log out from a Safari browser and the user is NOT remembered upon the next l... | [
"I was able to find the answer through documentation:\nHere, you can pass along an optional process parameter that indicates how to process the social login. You can choose between login and connect:\n<a href=\"{% provider_login_url \"twitter\" process=\"connect\" %}\">Connect a Twitter account</a>\n\nFurthermore, ... | [
0
] | [] | [] | [
"django",
"django_allauth",
"python"
] | stackoverflow_0074228840_django_django_allauth_python.txt |
Q:
Rotate a curve to a point in python
I would like to rotate a curve to a pass through a point on a 2D plot but l cant find a way of doing it .
Say l want to rotate
y=np.exp(x)+2 #pass through (x=5,y=6) point
A:
You can subtract value of y(x_0) from y and add desired y.
For example
x = np.arange(10)
y = np.exp(x... | Rotate a curve to a point in python | I would like to rotate a curve to a pass through a point on a 2D plot but l cant find a way of doing it .
Say l want to rotate
y=np.exp(x)+2 #pass through (x=5,y=6) point
| [
"You can subtract value of y(x_0) from y and add desired y.\nFor example\nx = np.arange(10)\ny = np.exp(x) + 2\n\nx_ind = 5 #This is not value of x, this is index of desired x\ny_desired = 6\ny -= y[x[x_ind]] + y_desired\n\nplt.plot(x, y, color='b')\nplt.scatter([x[x_ind]], [y_desired], color='r')\nplt.show()\n\n"
... | [
0
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0074236241_matplotlib_plot_python.txt |
Q:
How to optimize the electric vehicle charging cost using Gekko?
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
m = GEKKO()
m.options.SOLVER = 1
m.options.IMODE = 3
Num_car = 1
TOU = [64.9,64.9,64.9,64.9,64.9,64.9,64.9,64.9,152.6,239.8,239.8,152.6,239.8,239.8,2... | How to optimize the electric vehicle charging cost using Gekko? | from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
m = GEKKO()
m.options.SOLVER = 1
m.options.IMODE = 3
Num_car = 1
TOU = [64.9,64.9,64.9,64.9,64.9,64.9,64.9,64.9,152.6,239.8,239.8,152.6,239.8,239.8,239.8,239.8,152.6,152.6,152.6,152.6,152.6,152.6,152.6,64.9]
n=len(TOU... | [
"The intention appears to be to decide when to charge a battery over a 24 hour time period given a specific Time of Use (TOU). Here is a modified version of the script that charges (integer values 0-7) from 30 to 70 on the SOC. It has the capability to add additional vehicles but there is currently only one.\n\nfro... | [
1
] | [] | [] | [
"cost_based_optimizer",
"gekko",
"minimize",
"python"
] | stackoverflow_0074234285_cost_based_optimizer_gekko_minimize_python.txt |
Q:
Is there a way to print a list of the most important features of an Light GBM Classifier model?
Running an LGBM Classifier model and I'm able to use lgbm.plot_importance to plot the most important features but I would prefer having a list of these features instead, does anybody know how to go about doing this?
A:... | Is there a way to print a list of the most important features of an Light GBM Classifier model? | Running an LGBM Classifier model and I'm able to use lgbm.plot_importance to plot the most important features but I would prefer having a list of these features instead, does anybody know how to go about doing this?
| [
"The lightgbm.Booster object has a method .feature_importance() which can be used to access feature importances.\nThat method returns an array with one importance value per feature, and supports two types of importance, based on the value of importance_type:\n\n\"gain\" = \"cumulative gain of all splits using this ... | [
2,
0
] | [] | [] | [
"lightgbm",
"python"
] | stackoverflow_0069441258_lightgbm_python.txt |
Q:
How to reimplement lsof +D on MacOS two avoid calling stat(2) twice?
I am using lsof to detect which files are opened by which process for a given directory. Example:
% lsof +D /Users/jack/Downloads
Spotify 1431 jack 75r DIR 1,6 128 37333 /Users/jack/Downloads/file1.png
Dock 1439 jack 13r DIR ... | How to reimplement lsof +D on MacOS two avoid calling stat(2) twice? | I am using lsof to detect which files are opened by which process for a given directory. Example:
% lsof +D /Users/jack/Downloads
Spotify 1431 jack 75r DIR 1,6 128 37333 /Users/jack/Downloads/file1.png
Dock 1439 jack 13r DIR 1,6 128 37333 /Users/jack/Downloads/foo.psd
zsh 6644 jack cwd ... | [
"You can easily find open files by process using the /proc filesystem. From the manpage:\n\n/proc/[pid]/fd/\nThis is a subdirectory containing one entry for each file\nwhich the process has open, named by its file descriptor,\nand which is a symbolic link to the actual file. Thus, 0\nis standard input, 1 standard ... | [
0
] | [] | [] | [
"file_descriptor",
"lsof",
"macos",
"python"
] | stackoverflow_0074133348_file_descriptor_lsof_macos_python.txt |
Q:
Plot the results of a cluster analysis on a two-dimensional space
I'm not sure this can be done retrospectively, so I'm not sure my question makes sense.
I used k-means in a 20-dimensional space, resulting in 17 clusters.
I thus obtained a data frame containing the coordinates of the centers, df_center (just an ex... | Plot the results of a cluster analysis on a two-dimensional space | I'm not sure this can be done retrospectively, so I'm not sure my question makes sense.
I used k-means in a 20-dimensional space, resulting in 17 clusters.
I thus obtained a data frame containing the coordinates of the centers, df_center (just an example):
cluster x1 x2 x3 ... x20
0 0.2 0.1 -0.1 ... ... | [
"Yes, it is possible to plot the results of a cluster analysis on a two-dimensional space, using UMAP or other dimensionality reduction techniques. However, you need to apply the same technique to both the centers and the points, and then plot them on the same axes.\nFor example, using UMAP in Python, you could do ... | [
0
] | [] | [] | [
"cluster_analysis",
"matplotlib",
"python",
"scikit_learn",
"seaborn"
] | stackoverflow_0074232578_cluster_analysis_matplotlib_python_scikit_learn_seaborn.txt |
Q:
Creating python dataframe from nested xml
this is the portion of xml the file I am interested:
</Section>
<Section id="21" name="Event Strips" itemsCount="18">
<Event title="HR Min" start="10707646" end="10709446"/>
<Event title="HR Max" start="1043646" end="1045446"/>
<Event title="RR Min" start="1244... | Creating python dataframe from nested xml | this is the portion of xml the file I am interested:
</Section>
<Section id="21" name="Event Strips" itemsCount="18">
<Event title="HR Min" start="10707646" end="10709446"/>
<Event title="HR Max" start="1043646" end="1045446"/>
<Event title="RR Min" start="12441170" end="12442970"/>
<Event title="RR Max... | [
"You cat just use read_xml after install lxml libruary.\n\nInstall lxml lib\n\n\npip install lxml\n\n\n\nLoad xml data in dataframe\n\n\nimport pandas as pd\n\npd.read_xml('data.xml')\n\n\n",
"\n\nimport xml.etree.ElementTree as ET\nimport xmltodict\nimport pandas as pd\nimport re\nimport glob\nimport os\n\nfor f... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"python",
"xml",
"xml_parsing"
] | stackoverflow_0074210266_beautifulsoup_python_xml_xml_parsing.txt |
Q:
I have a list of images "Image1, Image2, Image3...". Is it possible to use for loop to add all of them to a list?
So I have 20 images and I want to put them to a list. But I only know how to do it by appending them one by one which wastes a lot of space. I did try for loop, but I do not know how to make it work.
T... | I have a list of images "Image1, Image2, Image3...". Is it possible to use for loop to add all of them to a list? | So I have 20 images and I want to put them to a list. But I only know how to do it by appending them one by one which wastes a lot of space. I did try for loop, but I do not know how to make it work.
This is what I want to do, but by using a loop:
list = []
list.append(image1)
list.append(image2)
...
list.append(image2... | [
"You can simply do that using glob by filtering image extensions from folder itself.\nimport glob\nimg_list = []\nfor img in glob.glob(\"Path/to/dir/*.jpg\"): #If extension of image is .jpg\n img_list.append(img)\n\n",
"I didn't understand if you want to include images or image names, I believe this solution c... | [
0,
0,
0
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0074236080_list_loops_python.txt |
Q:
How to custom the configuration of sphinx-quickstart
When I run sphinx-quickstart
It's so annoying to me to show those options
Can I have a default configuration ? without check those options one by one?
Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docs... | How to custom the configuration of sphinx-quickstart | When I run sphinx-quickstart
It's so annoying to me to show those options
Can I have a default configuration ? without check those options one by one?
Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/n) [n]:
> doctest: automatically te... | [
"I use a custom script (a custom quickstart) to pass default configuration to generate function :\n# -*- coding: utf-8 -*-\n\nimport re\nimport sys\n\nfrom sphinx.quickstart import generate, do_prompt\nif __name__ == '__main__':\n sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n d= {\n ... | [
1,
0,
0
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0022625078_python_python_sphinx.txt |
Q:
What is causing this strange focus behavior with my PlaceholderEntry class?
I've put together a simple class that inherits from ttk.Entry in order to toggle some placeholder text on focus events (based on this answer).
The odd thing is that my placeholder text is only cleared on '<FocusIn>' if I include print(self... | What is causing this strange focus behavior with my PlaceholderEntry class? | I've put together a simple class that inherits from ttk.Entry in order to toggle some placeholder text on focus events (based on this answer).
The odd thing is that my placeholder text is only cleared on '<FocusIn>' if I include print(self['foreground']) in my set_placeholder() method, otherwise the placeholder text is... | [
"The short answer is that cget returns a <class '_tkinter.Tcl_Obj'> and not a string that is whats causing your evaluation to fail. You could solve it in different ways.\n\nself.cget('foreground').string\nstr(self.cget('foreground'))\n\nA slightly longer answer, but I'm not aware of all the details, is that in tcl ... | [
2
] | [] | [] | [
"placeholder",
"python",
"tkinter"
] | stackoverflow_0074236274_placeholder_python_tkinter.txt |
Q:
Change ‘eye button’ that appears in dashtable columns where hideable property is True
I have several dashtables where columns have the property hideable=True. I am using the eye-button as a toggle button to show/hide certain components. My question is can this eye-button be changed to something like arrows? My tab... | Change ‘eye button’ that appears in dashtable columns where hideable property is True | I have several dashtables where columns have the property hideable=True. I am using the eye-button as a toggle button to show/hide certain components. My question is can this eye-button be changed to something like arrows? My table currently looks like this. Alternatively, if there is a way to add buttons/icons to tabl... | [
"span.column-header–hide svg {\nheight: 0;\nwidth: 0;\n}\n\nspan.column-header–hide:before{\nfont-family: “Font Awesome 5 Free”;\ncontent: “\\f060”; /* Unicode of icon */\ndisplay: inline-block;\npadding-right: 3px;\nvertical-align: middle;\nfont-weight: 900;\n}\n\n"
] | [
0
] | [] | [] | [
"css",
"dashboard",
"plotly_dash",
"python"
] | stackoverflow_0074222983_css_dashboard_plotly_dash_python.txt |
Q:
Python Multiprocessing - Start N threads and run new thread after one completes till timeout and capture results
I am basically trying create a script to do load testing where I have to keep running N number of queries in parallel and as soon as one thread finishes, I want to kickoff next thread and so on until th... | Python Multiprocessing - Start N threads and run new thread after one completes till timeout and capture results | I am basically trying create a script to do load testing where I have to keep running N number of queries in parallel and as soon as one thread finishes, I want to kickoff next thread and so on until the timeout seconds are reached. This way at all times N threads are running in parallel. I want to keep it running till... | [
"you should use concurrent.futures.ThreadPoolExecutor which allows you to cancel work if it hasn't started yet when you call shutdown\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\nimport datetime\n\ndef query_data(q):\n start_time = datetime.datetime.utcnow()\n id = q # Runs the main logic... | [
1
] | [] | [] | [
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0074236302_multiprocessing_multithreading_python.txt |
Q:
Pip freeze for only project requirements
When I run pip freeze > requirements.txt it seems to include all installed packages. This appears to be the documented behavior.
I have, however, done something wrong as this now includes things like Django in projects that have no business with Django.
How do I get require... | Pip freeze for only project requirements | When I run pip freeze > requirements.txt it seems to include all installed packages. This appears to be the documented behavior.
I have, however, done something wrong as this now includes things like Django in projects that have no business with Django.
How do I get requirements for just this project? or in the future ... | [
"pipreqs can save the day for a specific project.\nJust\npip install pipreqs\n#then\npipreqs path/to/project\n\nGithub Page\n",
"I have tried both pipreqs and pigar and found pigar is better because it also generates information about where it is used, it also has more options.\n",
"I use this command\nEDIT: Th... | [
122,
23,
11,
8,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0032390291_pip_python.txt |
Q:
Python Change the time AM to PM and Vice Versa
I have a list of time. I want all AM to be PM and all PM to AM.
Input
newtimes
Output
['10:31 PM', '10:03 PM', '12:26 AM', '07:40 PM', '09:32 PM']
Input
for items in newtimes:
newtimes1 = items.replace('AM','PM').replace('PM','AM')
print(newtimes1... | Python Change the time AM to PM and Vice Versa | I have a list of time. I want all AM to be PM and all PM to AM.
Input
newtimes
Output
['10:31 PM', '10:03 PM', '12:26 AM', '07:40 PM', '09:32 PM']
Input
for items in newtimes:
newtimes1 = items.replace('AM','PM').replace('PM','AM')
print(newtimes1)
Output i am getting:
10:31 AM
10:03 AM
12:26 AM
0... | [
"Just check before you replace:\nfor old_time in old_times:\n if 'AM' in old_time:\n new_time = old_time.replace('AM', 'PM')\n else:\n new_time = old_time.replace('PM', 'AM')\n print(new_time)\n\n",
"You are converting all string to have PM, then all to AM with your code. Here is an example... | [
1,
0
] | [] | [] | [
"python",
"replace",
"strftime",
"strptime",
"time"
] | stackoverflow_0074236435_python_replace_strftime_strptime_time.txt |
Q:
How to replicate index/match (with multiple criteria) in in python with multiple dataframes?
I am trying to replicate a excel model I have in python to automate it as I scale it up but I am stuck on how to translate the complex formula's into python.
I have information in three dataframes:
DF1:
ID type 1
ID type ... | How to replicate index/match (with multiple criteria) in in python with multiple dataframes? | I am trying to replicate a excel model I have in python to automate it as I scale it up but I am stuck on how to translate the complex formula's into python.
I have information in three dataframes:
DF1:
ID type 1
ID type 2
Unit
a
1_a
400
b
1_b
26
c
1_c
23
d
1_b
45
e
1_d
24
f
1_b
85
g
1_a
98
DF2:... | [
"For the first part of your question you want to do a left merge on those 2 columns twice like this:\ndf3 = (\n df3\n .merge(df1, on=['ID type 1', 'ID type 2'], how='left')\n .merge(df2, on=['ID type 1', 'ID type 2'], how='left')\n)\nprint(df3)\n\n Date Time ID type 1 ID type 2 Period outpu... | [
1
] | [] | [] | [
"dataframe",
"excel",
"jupyter",
"pandas",
"python"
] | stackoverflow_0074235996_dataframe_excel_jupyter_pandas_python.txt |
Q:
How does one get the model of the GPU in python and save it as a string?
I was trying to get a simple concise way to get the model/name of the GPU I am using in python and saving it as a string. I tried nvidia-smi but that gives a giant string and I don't need something that complicated. Is there a simple way that... | How does one get the model of the GPU in python and save it as a string? | I was trying to get a simple concise way to get the model/name of the GPU I am using in python and saving it as a string. I tried nvidia-smi but that gives a giant string and I don't need something that complicated. Is there a simple way that returns something simple like:
gpu_mdl = get_mdl() # 'V100 16Gigs'
for instan... | [
"You can use nvidia-smi -L to get a list with one line per GPU in the following format:\n\nGPU 0: GeForce GTX 1660 Ti (UUID: GPU-159d5c28-e2e7-c8ed-c153-72879c7a6e84)\n\nYou can then extract the relevant information (\"Geforce GTX 1660 Ti\") by splitting at the first : and the first (.\nimport subprocess\n\n\ndef g... | [
1,
0
] | [] | [] | [
"gpu",
"python"
] | stackoverflow_0064526139_gpu_python.txt |
Q:
Update the values of one column to other column based on condition
The values from column A to be replaced to column C if the column A values startswith '2'
Data
A B C
12525 1FWE23 na
14654 22354 na
24798 32684 na
28945 45368 na
46456 46485 na
2D545 45346 na... | Update the values of one column to other column based on condition | The values from column A to be replaced to column C if the column A values startswith '2'
Data
A B C
12525 1FWE23 na
14654 22354 na
24798 32684 na
28945 45368 na
46456 46485 na
2D545 45346 na
A5D66 58446 na
Expected
A B C
12525 1FWE23 n... | [
"# using loc identify the rows where column 'A' value starts with 'A',\n# when true replace with 'C' with 'A'\ndf.loc[df['A'].str.startswith('2'), 'C'] = df['A']\ndf\n\n\n A B C\n0 12525 1FWE23 na\n1 14654 22354 na\n2 24798 32684 24798\n3 28945 45368 28945\n4 46456 46485 ... | [
1
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074236492_dataframe_python.txt |
Q:
How to append results from a for loop in a DataFrame
I have created a function that manipulates a couple of datasets and outputs a merged DataFrame. I have passed an array of variables in a loop, which outputs a merged DataFrame for each one - now I want all the results appended in a single DataFrame:
Function:
`
... | How to append results from a for loop in a DataFrame | I have created a function that manipulates a couple of datasets and outputs a merged DataFrame. I have passed an array of variables in a loop, which outputs a merged DataFrame for each one - now I want all the results appended in a single DataFrame:
Function:
`
def backtest(ticker, data):
fin = si.get_data(ticker)
... | [
"Long story short, you should not dynamically append rows to a DataFrame. To achieve the result you want, you can append everything in a list and then call pd.concat to create a DataFrame from it. Something like\noutput=[]\nfor ticker in tickers: \n try:\n backtest(ticker, data)\n except:\n p... | [
0
] | [] | [] | [
"back_testing",
"python"
] | stackoverflow_0074236432_back_testing_python.txt |
Q:
Pyomo indexed constraint works with lambda-rule only
I am puzzled by a pyomo error that I obtained when replacing a lambda-expression by a function.
Consider the following working example:
import pyomo.environ as pyomo
model = pyomo.ConcreteModel()
model.time_set = pyomo.Set(initialize=range(1, 3))
model.thermal_s... | Pyomo indexed constraint works with lambda-rule only | I am puzzled by a pyomo error that I obtained when replacing a lambda-expression by a function.
Consider the following working example:
import pyomo.environ as pyomo
model = pyomo.ConcreteModel()
model.time_set = pyomo.Set(initialize=range(1, 3))
model.thermal_set = pyomo.Set(initialize=range(1, 3))
model.thermal_gener... | [
"You have a stray comma that is biting you. Inside your function, you are assigning the expression to a malformed tuple unintentionally in this statement:\ndef thermal_NGC_constraint(model, t, i):\n thermal_NGC_constraint = (\n model.thermal_generation[t, i] + model.thermal_reserve[t, i]\n <= mode... | [
1
] | [] | [] | [
"pyomo",
"python"
] | stackoverflow_0074235388_pyomo_python.txt |
Q:
Unable to install Psutil
o/
I can't install Psutil package using :
pip install psutil
I get the error message :
Microsoft Visual C++ 14.0 or greater is required
Failed building wheel for psutil
Could not build wheels for psutil, which is required to install pyproject
.toml-based projects
I tried pretty much ever... | Unable to install Psutil | o/
I can't install Psutil package using :
pip install psutil
I get the error message :
Microsoft Visual C++ 14.0 or greater is required
Failed building wheel for psutil
Could not build wheels for psutil, which is required to install pyproject
.toml-based projects
I tried pretty much everything I found on other thread... | [
"fix on windows:\nby installing Microsoft Build Tools for Visual Studio.\nSelect: Workloads → Desktop development with C++.\nThen for Individual Components, select only:\n\n\"Windows SDK\"\n\"C++ x64/x86 build tools\"\n\nThe build tools allow using MSVC “cl.exe” C / C++ compiler from the command line.\nSo pip inst... | [
1
] | [] | [] | [
"psutil",
"python",
"visual_c++"
] | stackoverflow_0074223685_psutil_python_visual_c++.txt |
Q:
Removing tuples with duplicated first element from the list of tuples, summing their second elements
So I got list like this
[('Add features to app', '5', '2022-10-28'),
('Add features to app', '3', '2022-10-28'),
('Deploy app to GitHub', '10', '2022-10-28'),
('Deploy app to GitHub', '2', '2022-10-28'),
('Crea... | Removing tuples with duplicated first element from the list of tuples, summing their second elements | So I got list like this
[('Add features to app', '5', '2022-10-28'),
('Add features to app', '3', '2022-10-28'),
('Deploy app to GitHub', '10', '2022-10-28'),
('Deploy app to GitHub', '2', '2022-10-28'),
('Create an app, which gets tasks entries using API', '7', '2022-10-28')]
And I need to bring it to something l... | [
"Try:\nlst = [\n (\"Add features to app\", \"5\", \"2022-10-28\"),\n (\"Add features to app\", \"3\", \"2022-10-28\"),\n (\"Deploy app to GitHub\", \"10\", \"2022-10-28\"),\n (\"Deploy app to GitHub\", \"2\", \"2022-10-28\"),\n (\"Create an app, which gets tasks entries using API\", \"7\", \"2022-10-... | [
4
] | [] | [] | [
"collections",
"list",
"python",
"sorting",
"tuples"
] | stackoverflow_0074236547_collections_list_python_sorting_tuples.txt |
Q:
I can't connect to pc socket server with mobile socket client python
Hello I tried a simple server and client script on my pc. It was working perfectly but when I tried to connect with pc server with my mobile it is not working I can't connect to pc server with my mobile client
Nothing works I tried changing ip no... | I can't connect to pc socket server with mobile socket client python | Hello I tried a simple server and client script on my pc. It was working perfectly but when I tried to connect with pc server with my mobile it is not working I can't connect to pc server with my mobile client
Nothing works I tried changing ip not working I tried changing my laptop internet connection not working I tri... | [
"\nboth devices will need to be on the same WLAN or Wifi Network.\nyou will also need to get your PC's network IP Address (eth0 or your main network card), then you will need your server to listen on ip 0.0.0.0 with the port you want to use.\nHave a close look at your firewall and enabled outbound/inbound connnecti... | [
0
] | [] | [] | [
"connection_refused",
"python",
"python_sockets",
"socketexception",
"tcpsocket"
] | stackoverflow_0074236528_connection_refused_python_python_sockets_socketexception_tcpsocket.txt |
Q:
Creating a dictionary where the values (a list) become the keys and vice versa?
I'm working with one of Zendesk's API to create a csv file with missing article translations.
The API GET request url is created by looping through a list of article IDs.
article_ids = [001, 002, 003]
def get_missing_translations_per_... | Creating a dictionary where the values (a list) become the keys and vice versa? | I'm working with one of Zendesk's API to create a csv file with missing article translations.
The API GET request url is created by looping through a list of article IDs.
article_ids = [001, 002, 003]
def get_missing_translations_per_article(id):
url = base_url + f"/api/v2/help_center/articles/{id}/translations/mi... | [
"Generally you should not use built-in names like list as variables (the following code needs the built-in list). Therefore I renamed it data.\nAnyway, you can solve this easily with a defaultdict in the following way:\nfrom collections import defaultdict\n\nfinal_dict = defaultdict(list)\nfor elem in data:\n fi... | [
1
] | [] | [] | [
"dictionary",
"list",
"logic",
"python"
] | stackoverflow_0074236495_dictionary_list_logic_python.txt |
Q:
How to calculate these 2 Equations in python
How can i calculate these in python??
A = (x**1/1!) - (x**3/3!) + (x**5/5!) - ... - (x**51/51!)
B = 1 - (x**2/2!) + (x**4/4!) - ... - (x**50/50!)
I tried this code for calculating A and B but
A^2 + B^2 ~= 1
but i get 2.xxxxxxxxx
def factorial(n):
fac = 1
for i i... | How to calculate these 2 Equations in python | How can i calculate these in python??
A = (x**1/1!) - (x**3/3!) + (x**5/5!) - ... - (x**51/51!)
B = 1 - (x**2/2!) + (x**4/4!) - ... - (x**50/50!)
I tried this code for calculating A and B but
A^2 + B^2 ~= 1
but i get 2.xxxxxxxxx
def factorial(n):
fac = 1
for i in range(2, n+1):
fac *= i
return fac
... | [
"Might as well use the factorial function from the math module. It will be faster than doing it in pure Python.\nYou can also restructure the code to be more concise by using cycle from itertools as follows:\nfrom math import factorial as FACTORIAL\nfrom operator import sub as SUB, add as ADD\nfrom itertools import... | [
2,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0074236465_math_python.txt |
Q:
How to mask with '_' a part of a string in python
It's for our class hangman game project, it's divided in many steps and the fourth one is :
Objective :
As in the previous stage, you should use the following word list: 'python', 'java', 'kotlin', 'javascript'
Once the computer has chosen a word from the list, s... | How to mask with '_' a part of a string in python | It's for our class hangman game project, it's divided in many steps and the fourth one is :
Objective :
As in the previous stage, you should use the following word list: 'python', 'java', 'kotlin', 'javascript'
Once the computer has chosen a word from the list, show its first 3 letters. Hidden letters should be repla... | [
"word[3:] returns an a.\n(len(word)-3) returns 1.\nSo you end up with each a being replaced with a hyphen:\n\"Java\".replace('a', '-')` \n\n>>>J-v-\n\nInstead avoid replace(). You can consider:\nreplaced = word[:3] + '-' * len(word[3:])\n\n",
"As stated in the comments, you don't have to use str.replace, just con... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0074236524_python.txt |
Q:
Pandas cleaner syntax
I would like to replace the following syntax with a cleaner, chained syntax - perhaps using .pipe (similar to dplyr library in R):
Sample dataset:
dt = pd.DataFrame({
"PACK_STR": ['112', '112', '112', '134', '145', '134'],
"FLAG_MODE_SUM_PCK": [1, 0, 1, 1, 1, 0]
})
Code to replace by... | Pandas cleaner syntax | I would like to replace the following syntax with a cleaner, chained syntax - perhaps using .pipe (similar to dplyr library in R):
Sample dataset:
dt = pd.DataFrame({
"PACK_STR": ['112', '112', '112', '134', '145', '134'],
"FLAG_MODE_SUM_PCK": [1, 0, 1, 1, 1, 0]
})
Code to replace by piping:
packs_mode_sum_pck... | [
"Here are two elegant ways to get your output:\ndef ssum(grp):\n grp['OCCUR_MODE_SUM_PCK'] = grp['FLAG_MODE_SUM_PCK'].sum()\n return grp\ndt.groupby('PACK_STR').apply(ssum)\n\nor\ndt['OCCUR_MODE_SUM_PCK'] = dt.groupby('PACK_STR')['FLAG_MODE_SUM_PCK'].transform(sum)\ndt\n\n"
] | [
3
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074236582_pandas_python.txt |
Q:
There is a white line on the right side of middle of the GUI screen
I am making a Pong game program using Python. There is a white line in the middle of the screen, which I can't figure out why is there.
I am pasting my code and the output (the issue) below.
import turtle
wm = turtle.Screen()
wm.title("Pong by Th... | There is a white line on the right side of middle of the GUI screen | I am making a Pong game program using Python. There is a white line in the middle of the screen, which I can't figure out why is there.
I am pasting my code and the output (the issue) below.
import turtle
wm = turtle.Screen()
wm.title("Pong by Tharv")
wm.bgcolor("black")
# wm.setup(width=800, hieght=300)
wm.tracer(0)
... | [
"You forgot parentheses in your call to batB.penup, so the pen isn't actually raised, causing a line to be drawn when you move back to the center.\nAdd parentheses and it should work.\n# Bat B\n\nbatB = turtle.Turtle()\nbatB.speed(0)\nbatB.shape(\"square\")\nbatB.color(\"white\")\nbatB.shapesize(stretch_wid=5, stre... | [
1,
1
] | [] | [] | [
"pong",
"python",
"python_turtle",
"user_interface"
] | stackoverflow_0074236697_pong_python_python_turtle_user_interface.txt |
Q:
Adding a pause in Google-text-to-speech
I am looking for a small pause, wait, break or anything that will allow for a short break (looking for about 2 seconds +-, configurable would be ideal) when speaking out the desired text.
People online have said that adding three full stops followed by a space creates a brea... | Adding a pause in Google-text-to-speech | I am looking for a small pause, wait, break or anything that will allow for a short break (looking for about 2 seconds +-, configurable would be ideal) when speaking out the desired text.
People online have said that adding three full stops followed by a space creates a break but I don't seem to be getting that. Code b... | [
"Ok, you need Speech Synthesis Markup Language (SSML) to achieve this.\nBe aware you need to setting up Google Cloud Platform credentials\nfirst in the bash:\npip install --upgrade google-cloud-texttospeech\n\nThen here is the code:\nimport html\nfrom google.cloud import texttospeech\n\ndef ssml_to_audio(ssml_text,... | [
9,
3,
1,
1,
1,
0,
0
] | [] | [] | [
"google_text_to_speech",
"python"
] | stackoverflow_0059819936_google_text_to_speech_python.txt |
Q:
Getting Can't get attribute 'getImages' on " when using a fastai model
Hey guys I am getting the no attribute error when running my ML model on a gunicorn hosted flask app.
Locally I just had to simply declare the function in the main scope to get things running,
how can I do that on a gunicorn hosted app?
how sho... | Getting Can't get attribute 'getImages' on " when using a fastai model | Hey guys I am getting the no attribute error when running my ML model on a gunicorn hosted flask app.
Locally I just had to simply declare the function in the main scope to get things running,
how can I do that on a gunicorn hosted app?
how should I structure my fast ai models in the future to avoid this issue?
hre is ... | [
"figured it out,\nhad to add the following:\nimport __main__\ndef getImages(d): return##\n__main__.getImages = getImages\n\n"
] | [
0
] | [] | [] | [
"deployment",
"fast_ai",
"gunicorn",
"python"
] | stackoverflow_0074229936_deployment_fast_ai_gunicorn_python.txt |
Q:
Python: in a list, count sub-lists grouped by first element of these sub-lists
Given following list:
['21,*,1', '21,stuff,1', '21,*,10', '21,stuff,4', '21,*,1', '21,*,114', '21,stuff,1',
'28,*,37', '28,stuff,1', '28,*,4', '28,stuff,4', '28,*,4', '28,XXX,3', '28,stuff,1', '28,XXX,23', '28,XXX,87',
'38,*,72', '38... | Python: in a list, count sub-lists grouped by first element of these sub-lists | Given following list:
['21,*,1', '21,stuff,1', '21,*,10', '21,stuff,4', '21,*,1', '21,*,114', '21,stuff,1',
'28,*,37', '28,stuff,1', '28,*,4', '28,stuff,4', '28,*,4', '28,XXX,3', '28,stuff,1', '28,XXX,23', '28,XXX,87',
'38,*,72', '38,stuff,9', '38,*,6', '38,stuff,32', '38,stuff,3', '38,stuff,3', '38,XXX,1', '38,*,23... | [
"Use itertools.groupby with a custom key:\nfrom itertools import groupby\n\ndata = ['21,*,1', '21,stuff,1', '21,*,10', '21,stuff,4', '21,*,1', '21,*,114', '21,stuff,1',\n '28,*,37', '28,stuff,1', '28,*,4', '28,stuff,4', '28,*,4', '28,XXX,3', '28,stuff,1', '28,XXX,23', '28,XXX,87',\n '38,*,72', '38,stu... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074236523_python.txt |
Q:
Unknown error in latest discord.py rewrite
I am trying to create a discord bot in the new version of discord.py (latest version). I have been following an old tutorial for how to use cogs, but then used the discord.py API in order to update it with intents, etc. I cannot seem to shake the error in my code once it ... | Unknown error in latest discord.py rewrite | I am trying to create a discord bot in the new version of discord.py (latest version). I have been following an old tutorial for how to use cogs, but then used the discord.py API in order to update it with intents, etc. I cannot seem to shake the error in my code once it starts up. The error is
File "C:\Users\MyUsern... | [
"setup is async now.\nChange it to this:\nasync def setup(client):\n await client.add_cog(Ping(client))\n\nRead the changelog: https://discordpy.readthedocs.io/en/latest/migrating.html#migrating-2-0-commands-extension-cog-async\n"
] | [
1
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074236586_discord_discord.py_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.