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: Support for Enum arguments in argparse Is there a better way of supporting Enums as types of argparse arguments than this pattern? class SomeEnum(Enum): ONE = 1 TWO = 2 parser.add_argument('some_val', type=str, default='one', choices=[i.name.lower() for i in SomeEnum]) ... args.some_va...
Support for Enum arguments in argparse
Is there a better way of supporting Enums as types of argparse arguments than this pattern? class SomeEnum(Enum): ONE = 1 TWO = 2 parser.add_argument('some_val', type=str, default='one', choices=[i.name.lower() for i in SomeEnum]) ... args.some_val = SomeEnum[args.some_val.upper()]
[ "I see this is an old question, but I just came across the same problem (Python 2.7) and here's how I solved it:\nfrom argparse import ArgumentParser\nfrom enum import Enum\n\nclass Color(Enum):\n red = 'red'\n blue = 'blue'\n green = 'green'\n\n def __str__(self):\n return self.value\n\nparser =...
[ 156, 29, 17, 10, 0, 0 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0043968006_argparse_python.txt
Q: Str split and explode How could I string split and explode whilst retaining information? df 0 Apple_a red, green; banana_b yellow 1 peach_p orange; pear_p green Expected output 0 Apple_a red 1 Apple_a green 2 banana_b yellow 3 peach_p orange 4 pear_p green I tried: df1 =df.str.split("; ").str.split(" ", n=1)...
Str split and explode
How could I string split and explode whilst retaining information? df 0 Apple_a red, green; banana_b yellow 1 peach_p orange; pear_p green Expected output 0 Apple_a red 1 Apple_a green 2 banana_b yellow 3 peach_p orange 4 pear_p green I tried: df1 =df.str.split("; ").str.split(" ", n=1) df2=df1.str[0] +x for x in...
[ "Example\ndata = ['Apple_a red, green; banana_b yellow', 'peach_p orange; pear_p green']\ns1 = pd.Series(data)\n\noutput(s1):\n0 Apple_a red, green; banana_b yellow\n1 peach_p orange; pear_p green\ndtype: object\n\n\nMy idea\ns1.str.split('; ').explode().str.split(r',* ', expand=True)\n\noutput:\n 0...
[ 2 ]
[]
[]
[ "pandas", "python", "string" ]
stackoverflow_0074474900_pandas_python_string.txt
Q: Pandas COUNTIF equivalent (preserve duplicate values, see description) I have the following pandas column1 and I want to create a column2 displaying the count of the value in each row in the column1. I do not want to use pandas value_counts as I do not want to group by the values of the column. Column1 : COL 1 ...
Pandas COUNTIF equivalent (preserve duplicate values, see description)
I have the following pandas column1 and I want to create a column2 displaying the count of the value in each row in the column1. I do not want to use pandas value_counts as I do not want to group by the values of the column. Column1 : COL 1 VALUE1 VALUE2 VALUE1 VALUE1 VALUE1 VALUE3 VALUE2 VALUE1 VALLUE3 VALUE2 De...
[ "value_counts does not require you to group and it creates a series\nwhich you can map back to your df:\ndf['Resired Result'] = df['COL 1'].map(df['COL 1'].value_counts())\n\nprints\n COL 1 Resired Result\n0 VALUE1 5\n1 VALUE2 3\n2 VALUE1 5\n3 VALUE1 ...
[ 2, 2 ]
[]
[]
[ "count", "function", "numpy", "pandas", "python" ]
stackoverflow_0074475090_count_function_numpy_pandas_python.txt
Q: Find the closest date with conditions There are two pandas tables, each containing two columns. In the first time, there is also a heart rhythm. Second time is the systolic pressure. Write the code that creates a third table, in which for each blood pressure measurement, the same line contains the time and value o...
Find the closest date with conditions
There are two pandas tables, each containing two columns. In the first time, there is also a heart rhythm. Second time is the systolic pressure. Write the code that creates a third table, in which for each blood pressure measurement, the same line contains the time and value of the nearest heart rate measurement, if it...
[ "Lets do merge_asof with direction='backward' and tolerance of 15min:\npd.merge_asof(\n df_bp.sort_index(), \n df_hr.sort_index(), \n on='time', \n direction='backward',\n tolerance=pd.Timedelta('15min'), \n)\n\nNote:\nThe keyword argument direction=backward selects the last row in the right DataFram...
[ 2 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074474940_dataframe_datetime_pandas_python.txt
Q: Pandas read_csv: low_memory and dtype options df = pd.read_csv('somefile.csv') ...gives an error: .../site-packages/pandas/io/parsers.py:1130: DtypeWarning: Columns (4,5,7,16) have mixed types. Specify dtype option on import or set low_memory=False. Why is the dtype option related to low_memory, and why might ...
Pandas read_csv: low_memory and dtype options
df = pd.read_csv('somefile.csv') ...gives an error: .../site-packages/pandas/io/parsers.py:1130: DtypeWarning: Columns (4,5,7,16) have mixed types. Specify dtype option on import or set low_memory=False. Why is the dtype option related to low_memory, and why might low_memory=False help?
[ "The deprecated low_memory option\nThe low_memory option is not properly deprecated, but it should be, since it does not actually do anything differently[source]\nThe reason you get this low_memory warning is because guessing dtypes for each column is very memory demanding. Pandas tries to determine what dtype to s...
[ 663, 75, 59, 22, 17, 7, 6, 5, 5, 3, 2, 0, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "parsing", "python" ]
stackoverflow_0024251219_dataframe_numpy_pandas_parsing_python.txt
Q: PyTest exits with TypeError: 'NoneType' object is not callable when collecting test cases When running pytest --collect-only, PyTest collects the correct tests, but terminates with this: Traceback (most recent call last): File "/data/anaconda/envs/env/lib/python3.9/logging/__init__.py", line 831, in _removeHandl...
PyTest exits with TypeError: 'NoneType' object is not callable when collecting test cases
When running pytest --collect-only, PyTest collects the correct tests, but terminates with this: Traceback (most recent call last): File "/data/anaconda/envs/env/lib/python3.9/logging/__init__.py", line 831, in _removeHandlerRef File "/data/anaconda/envs/env/lib/python3.9/logging/__init__.py", line 225, in _acquire...
[ "Code source for gevent/thread.py around line 74 :\ndef get_ident(gr=None): # 72\n if gr is None: # 73\n gr = getcurrent() # 74\n return id(gr) # 75\n\nSo it looks like getcurrent is None, but strangely :\nfrom gevent.hub import getcurrent # 56\n\nSo it should no...
[ 0 ]
[]
[]
[ "gevent", "pytest", "python", "typeerror" ]
stackoverflow_0074467629_gevent_pytest_python_typeerror.txt
Q: Read csv in python pandas with different number of quotation marks and commas my csv-data-file is looking like this: "Date,""Time"",""Tags"",""Measurement"",""Info"",""GMT+01:00"""; "13.11.2022,""21:47:56"","""",""156"","""",""GMT+01:00"""; "29.05.2022,""09:00:00"","""",""Comment1,Comment2"","""",""GMT+01:00"""; ...
Read csv in python pandas with different number of quotation marks and commas
my csv-data-file is looking like this: "Date,""Time"",""Tags"",""Measurement"",""Info"",""GMT+01:00"""; "13.11.2022,""21:47:56"","""",""156"","""",""GMT+01:00"""; "29.05.2022,""09:00:00"","""",""Comment1,Comment2"","""",""GMT+01:00"""; The line begins with double quotation marks and ends with double quotation marks an...
[ "import pandas as pd\n\nwith open('test.csv', 'r') as f:\n data = [line[1:-3].replace('\"\"', '\"') + '\\n' for line in f]\nwith open('test.csv', 'w') as f:\n f.writelines(data)\n\ndf = pd.read_csv('test.csv')\n\n\n" ]
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074471473_csv_pandas_python.txt
Q: Pandas - Cumulative Count with Labeling I have a pandas df that looks like the following: +---------+---------+------------+--------+ | Cluster | Country | Publishers | Assets | +---------+---------+------------+--------+ | South | IT | SS | Asset1 | | South | IT | SS | Asset2 | | Sou...
Pandas - Cumulative Count with Labeling
I have a pandas df that looks like the following: +---------+---------+------------+--------+ | Cluster | Country | Publishers | Assets | +---------+---------+------------+--------+ | South | IT | SS | Asset1 | | South | IT | SS | Asset2 | | South | IT | SS | Asset3 | | Sout...
[ "You can use groupby.cumcount, but with a different grouper. You will also need the related groupby.ngroup:\nfrom string import ascii_lowercase\n\n# group by consecutive identical values\ngroup = df['Publishers'].ne(df['Publishers'].shift()).cumsum()\n# alternatively, you can also group by Cluster/Country/Publisher...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074475243_dataframe_pandas_python.txt
Q: Selecting the index column of a pandas dataframe import pandas as pd df = pd.DataFrame({'customer' : ['customer2', 'customer1'], 'item1': [12, 13], 'item2' : [3, 28],'item3': [2, 1]}) df2 = pd.DataFrame({'customer' : ['customer1', 'customer2'], 'item?': ['item1', 'item1'], 'quantity' : [2, 5]}) df = df.set_ind...
Selecting the index column of a pandas dataframe
import pandas as pd df = pd.DataFrame({'customer' : ['customer2', 'customer1'], 'item1': [12, 13], 'item2' : [3, 28],'item3': [2, 1]}) df2 = pd.DataFrame({'customer' : ['customer1', 'customer2'], 'item?': ['item1', 'item1'], 'quantity' : [2, 5]}) df = df.set_index('customer').add(pd.pivot_table(df2,index='customer'...
[ "The customer column in the index so you need to use the below code for getting the value of\ndf.reset_index()['customer']\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074475249_pandas_python.txt
Q: Error while installing PyCaret: No module named 'numpy.distutils._msvccompiler' in numpy.distutils in windows I am getting a huge error while installing pycaret module in my system. Can anyone help me with this please. I am using python 3.10.8 Also, please suggest the best way to keep things clean version-wise. Py...
Error while installing PyCaret: No module named 'numpy.distutils._msvccompiler' in numpy.distutils in windows
I am getting a huge error while installing pycaret module in my system. Can anyone help me with this please. I am using python 3.10.8 Also, please suggest the best way to keep things clean version-wise. PyCaret always troubles me whenever I work on a new system. Thanks Adding more blocks of description in order to get ...
[ "Try installing/updating C++ build tools\nhttps://visualstudio.microsoft.com/visual-cpp-build-tools/\nit worked for me\n" ]
[ 0 ]
[]
[]
[ "pycaret", "python" ]
stackoverflow_0074359405_pycaret_python.txt
Q: Ceil any number in python this way - 2.3, 2.1, 1.9, 2.6. to 2.5, 2.5, 2, 3 i.e. addition leads to addition of .5 or 1 whichever is closest Default ceiling doesn't work this way. Ceil should work in this way - Example 2 - 3.1, 4.5, 5.9 after ceiling - 3.5, 4.5, 6 A: def roundOffnumber (number): return (math.cei...
Ceil any number in python this way - 2.3, 2.1, 1.9, 2.6. to 2.5, 2.5, 2, 3 i.e. addition leads to addition of .5 or 1 whichever is closest
Default ceiling doesn't work this way. Ceil should work in this way - Example 2 - 3.1, 4.5, 5.9 after ceiling - 3.5, 4.5, 6
[ "def roundOffnumber (number):\n return (math.ceil(number*2))/2\n\n" ]
[ 1 ]
[]
[]
[ "ceil", "python" ]
stackoverflow_0074475229_ceil_python.txt
Q: creating an admin user using django I was creating an admin user account, when it got to create password my keys stopped working!!I even rebooted my system and started from top boom it happened again tried to create password on django admin user account? A: The prompt for the password when you use the createsupe...
creating an admin user using django
I was creating an admin user account, when it got to create password my keys stopped working!!I even rebooted my system and started from top boom it happened again tried to create password on django admin user account?
[ "The prompt for the password when you use the createsuperuser command [Django-doc] does not show the entered characters, for privacy and security concerns. Just like a password box in a browser does not show the password.\nYou thus enter the password and hit Enter to enter the password.\n" ]
[ 0 ]
[]
[]
[ "django", "manage.py", "python" ]
stackoverflow_0074475258_django_manage.py_python.txt
Q: How can i not set at my url to get certain data? My api was set to api/barrel/details/<int:pk> originally but i want to make the delete function into api/barrel (which only have get and post function) without parsing the pk class BarrelAPIView(APIView): def get(self,request): barrel = Barrel.objects.a...
How can i not set at my url to get certain data?
My api was set to api/barrel/details/<int:pk> originally but i want to make the delete function into api/barrel (which only have get and post function) without parsing the pk class BarrelAPIView(APIView): def get(self,request): barrel = Barrel.objects.all() #queryset serializer = BarrelSerializer(ba...
[ "You should check out:\nhttps://www.django-rest-framework.org/api-guide/generic-views/#mixins\nin the long run it will make your life easier..\nThe url could have any structure you like.\nI would also suggest to refer to:\nTwo scoops of Django that introduce you to various tips, tricks, patterns, code snippets, and...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074472180_django_django_rest_framework_python.txt
Q: os.path.join('BASE_DIR','template') problem When I run following code In settings.py TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join('BASE_DIR','template')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processo...
os.path.join('BASE_DIR','template') problem
When I run following code In settings.py TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join('BASE_DIR','template')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_process...
[ "You can try the following steps:.\n\nDeclare 'import os' command in the top header section of settings.py file.\n\nWhile defining DIRS': [os.path.join(BASE_DIR,'template')] , take the os from auto suggestions instead of typing.\n\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_settings", "python" ]
stackoverflow_0064261167_django_django_settings_python.txt
Q: How to replace a number in a text file using regular expressions I have a text document with lots of lines that look something like this: some_string_of_changing_length 1234.56000000 99997.65723122992939764 4.63700 text -d NAME -r I want to go line by line and change only the 4th entry (the number 4.63700 in this...
How to replace a number in a text file using regular expressions
I have a text document with lots of lines that look something like this: some_string_of_changing_length 1234.56000000 99997.65723122992939764 4.63700 text -d NAME -r I want to go line by line and change only the 4th entry (the number 4.63700 in this example) and replace it with another number. I think I have to do wit...
[ "If you know the offset - the below will work for you (so there is no need for regex)\nline = 'some_string_of_changing_length 1234.56000000 99997.65723122992939764 4.63700 text -d NAME -r'\nnew_val = 'I am the new val'\nparts = line.split(' ')\nparts[3] = new_val\nline = ' '.join(parts)\nprint(line)\n\n" ]
[ 1 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0074475334_bash_python.txt
Q: How to find the cause of CancelledError in asyncio? I have a big project which depends some third-party libraries, and sometimes its execution gets interrupted by a CancelledError. To demonstrate the issue, let's look at a small example: import asyncio async def main(): task = asyncio.create_task(foo()) ...
How to find the cause of CancelledError in asyncio?
I have a big project which depends some third-party libraries, and sometimes its execution gets interrupted by a CancelledError. To demonstrate the issue, let's look at a small example: import asyncio async def main(): task = asyncio.create_task(foo()) # Cancel the task in 1 second. loop = asyncio.get_ev...
[ "I've solved it by applyting a decorator to every async function in the project. The decorator's job is simple - log a message when a CancelledError is raised from the function. This way we will see which functions (and more importantly, in which order) get cancelled.\nHere's the decorator code:\ndef log_cancellati...
[ 0 ]
[ "The rich package has helped us to identify the cause of CancelledError, without much code change required.\nfrom rich.console import Console\n\nconsole = Console()\n\nif __name__ == \"__main__\":\n try:\n asyncio.run(main()) # replace main() with your entrypoint\n except BaseException as e:\n ...
[ -1 ]
[ "python", "python_asyncio" ]
stackoverflow_0071324885_python_python_asyncio.txt
Q: Trying to get PyCharm to work, keep getting "No Python interpreter selected" I'm trying to learn Python and decided to use PyCharm. When I try to start a new project I get a dialog that says "No Python interpreter selected". It has a drop down to select a interpreter, but the drop down is empty. A: Your proble...
Trying to get PyCharm to work, keep getting "No Python interpreter selected"
I'm trying to learn Python and decided to use PyCharm. When I try to start a new project I get a dialog that says "No Python interpreter selected". It has a drop down to select a interpreter, but the drop down is empty.
[ "Your problem probably is that you haven't installed python. Meaning that, if you are using Windows, you have not downloaded the installer for Windows, that you can find on the official Python website.\nIn case you have, chances are that PyCharm cannot find your Python installation because its not in the default lo...
[ 67, 22, 4, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0019645527_pycharm_python.txt
Q: Assign consequential values to a DataFrame from a numpy array based on a condition The task seems easy but I've been googling and experimenting for hours without any result. I can easily assign a 'static' value in such case or assign a value if I have two columns in the same DataFrame (of the same length, ofc) but...
Assign consequential values to a DataFrame from a numpy array based on a condition
The task seems easy but I've been googling and experimenting for hours without any result. I can easily assign a 'static' value in such case or assign a value if I have two columns in the same DataFrame (of the same length, ofc) but I'm stuck with this situation. I need to assign a consequential value to a pandas DataF...
[ "it's not the very efficient way but it will do the job.\nimport pandas as pd\nimport numpy as np\n\ndef util(it, row):\n ele = next(it, None)\n return ele if ele is not None else row\n\ndf = pd.DataFrame([np.nan, 1, np.nan, 1, np.nan, 1, np.nan])\narr = np.array([4, 5, 6])\nit = iter(arr)\n\ndf[0] = np.array...
[ 2 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074474157_numpy_pandas_python.txt
Q: Hot to make pandas cut have first range equal to minimum value I have this dataframe: lst = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,3,3,3,3] ser = pd.Series(lst) df1 = pd.DataFrame(ser, columns=['Quan...
Hot to make pandas cut have first range equal to minimum value
I have this dataframe: lst = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,3,3,3,3,3,3,3,3,3,3,3,3] ser = pd.Series(lst) df1 = pd.DataFrame(ser, columns=['Quantity']) When i check unique values from variable quantity i have th...
[ "You can define the bins the way you want in pandas.cut, by default the right part of the bins is uncluded:\nimport numpy as np\n\n(pd.cut(df['Quantity'], bins=[-1, 0, 2, np.inf], labels=['0', '1-2', '3+'])\n .value_counts()\n)\n\nOutput:\n0 57\n1-2 29\n3+ 5\nName: Quantity, dtype: int64\n\ncombining...
[ 2 ]
[]
[]
[ "cut", "pandas", "python" ]
stackoverflow_0074475324_cut_pandas_python.txt
Q: Extra feature values in dataset fragments After reading dataset with filters in dataset.fragments other values of filtered column is presented. Is this the expected behavior? import pyarrow.parquet as pq from pyarrow import csv path_ds = 'path/to/ds/' path_csv = 'path/to/csv/' read_options = csv.ReadOptions(auto...
Extra feature values in dataset fragments
After reading dataset with filters in dataset.fragments other values of filtered column is presented. Is this the expected behavior? import pyarrow.parquet as pq from pyarrow import csv path_ds = 'path/to/ds/' path_csv = 'path/to/csv/' read_options = csv.ReadOptions(autogenerate_column_names=True) parse_options = csv...
[ "According to the doc\n\nPredicates are expressed in disjunctive normal form (DNF), like [[('x', '=', 0), ...], ...]. DNF allows arbitrary boolean logical combinations of single column predicates. The innermost tuples each describe a single column predicate. The list of inner predicates is interpreted as a conjunct...
[ 1 ]
[]
[]
[ "pyarrow", "python" ]
stackoverflow_0074474939_pyarrow_python.txt
Q: How to convert nested dictionary to levelled Pandas Dataframe How to convert more than 3 level N nested dictionary to levelled dataframe? input_dict = { '.Stock': { '.No[0]': '3241512)', '.No[1]': '1111111111', '.No...
How to convert nested dictionary to levelled Pandas Dataframe
How to convert more than 3 level N nested dictionary to levelled dataframe? input_dict = { '.Stock': { '.No[0]': '3241512)', '.No[1]': '1111111111', '.No[2]': '444444444444', '.Version': '46',...
[ "You can first flatten your nested dictionary with a recursive function (see \"Best way to get nested dictionary items\").\ndef flatten(ndict):\n def key_value_pairs(d, key=[]):\n if not isinstance(d, dict):\n yield tuple(key), d\n else:\n for level, d_sub in d.items():\n ...
[ 0, 0 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074471768_dataframe_dictionary_pandas_python.txt
Q: Strange exec scoping rule for list comprehension with a filter condition It seems like when you execute a block of text using exec, the variable you define along the way isn't available in all contexts. I've detected this when using list comprehension with a filter condition. There seems to be a bug with the scope...
Strange exec scoping rule for list comprehension with a filter condition
It seems like when you execute a block of text using exec, the variable you define along the way isn't available in all contexts. I've detected this when using list comprehension with a filter condition. There seems to be a bug with the scope of the filter condition. Tested on Python 3.8, 3.9, and 3.10. Example of text...
[ "Workaround:\nI have since developed neval as a workaround for class-definition scoping. Neval is an alternative scoping evaluator with some additional features not available through exec and eval, such as:\n\nexplicit separation of staging and readonly namespaces\nreturning the value of the last statement of your ...
[ 1 ]
[]
[]
[ "eval", "python" ]
stackoverflow_0074457440_eval_python.txt
Q: How to import functions from a different folder in python? Q1: So let's say I have 2 folders and some files in them like this: root ├── Folder │   └── file.py └── Folder1 └── file2.py Let's say that I have a function in file.py named function() and I want to use it in file2.py. How can I make this happen? Q2:...
How to import functions from a different folder in python?
Q1: So let's say I have 2 folders and some files in them like this: root ├── Folder │   └── file.py └── Folder1 └── file2.py Let's say that I have a function in file.py named function() and I want to use it in file2.py. How can I make this happen? Q2: If file.py contains 5 functions, and I want to use them at any ...
[ "Found the answer:\n#You write this code in file2.py\n#This imports the whole file2\n\nimport numpy as np\nimport sys\n\nsys.path.insert(0, \"../Folder\")\nimport file.py as U\n\ndef main():\n s = U.log_sig(0.5)\n\nif __name__ == \"__main__\":\n main\n\nOr if you like to import only function() from file.py then:\...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074474997_python.txt
Q: Alembic: alter column to JSON type I have initial migration setup, but I want to change a column from sqlalchemy.Text to sqlalchemy.JSON I followed this article https://amercader.net/blog/beware-of-json-fields-in-sqlalchemy/ column_foo = Column(mutable_json_type(dbtype=JSONB, nested=True), nullable=True) When I r...
Alembic: alter column to JSON type
I have initial migration setup, but I want to change a column from sqlalchemy.Text to sqlalchemy.JSON I followed this article https://amercader.net/blog/beware-of-json-fields-in-sqlalchemy/ column_foo = Column(mutable_json_type(dbtype=JSONB, nested=True), nullable=True) When I run alembic autogenerate it does not reco...
[ "Found a solution (postgresql_using):\nop.alter_column(\"some_table\", \"column_foo\", type_=sa.JSON(), nullable=True,postgresql_using='column_foo::json')\n\n" ]
[ 0 ]
[]
[]
[ "alembic", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0074475213_alembic_postgresql_python_sqlalchemy.txt
Q: how we can order browsing in 4 list of words? i have 4 group of word i intend write a program in python to input a name and brows in 4 group and if find in one's say the group name group1=["anbar","tamirgah kochak","ordogah jahangardi","zamin varzeshi","mohavate sazi","kargah kochak"] group2=["maskoni","small stor...
how we can order browsing in 4 list of words?
i have 4 group of word i intend write a program in python to input a name and brows in 4 group and if find in one's say the group name group1=["anbar","tamirgah kochak","ordogah jahangardi","zamin varzeshi","mohavate sazi","kargah kochak"] group2=["maskoni","small store","khabgah","mehmansara","asayeshgah","parking tab...
[ "Probably the easiest way is to use a dictionary, and iterate over items:\nall_group = {\"group1\":group1, \"group2\":group2, \"group3\":group3, \"group4\":group4}\n\nproject_type = input(\"chose project type: \")\nfor group_name, group_values in all_group.items(): \n if project_type in group_values:\n ...
[ 0 ]
[]
[]
[ "list", "loops", "python", "validation" ]
stackoverflow_0074475387_list_loops_python_validation.txt
Q: Matrix Calculation Numpy I am trying to calculate Rij = Aij x Bji/Cij with numPy broadcasting. Also raise an exception if matrices are not the same size (n × n). I am not so sure if this is correct or if I should be doing element wise or matrix wise. could anyone tell me how to do it A = [[(i+j)/2000 for i in ra...
Matrix Calculation Numpy
I am trying to calculate Rij = Aij x Bji/Cij with numPy broadcasting. Also raise an exception if matrices are not the same size (n × n). I am not so sure if this is correct or if I should be doing element wise or matrix wise. could anyone tell me how to do it A = [[(i+j)/2000 for i in range(500)] for j in range(500)]...
[ "The @ is the matrix product operator for numpy arrays.\nnp.array([[1, 2], [3, 4]]) @ np.array([[5, 6], [7, 8]])\n\nis\nnp.array([[1*5+2*7, 1*6+2*8], [3*5+4*7, 3*6+4*8]])\n\nFor element multiplication you may use * which does element-wise product for numpy arrays.\nnp.array([[1, 2], [3, 4]]) * np.array([[5, 6], [7,...
[ 1 ]
[]
[]
[ "broadcasting", "matrix", "numpy", "python", "transpose" ]
stackoverflow_0074475244_broadcasting_matrix_numpy_python_transpose.txt
Q: Python OpenCV video.get(cv2.CAP_PROP_FPS) returns 0.0 FPS This is my video This is the script to find fps: import cv2 if __name__ == '__main__' : video = cv2.VideoCapture("test.mp4"); # Find OpenCV version (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') if int(major_ver) < ...
Python OpenCV video.get(cv2.CAP_PROP_FPS) returns 0.0 FPS
This is my video This is the script to find fps: import cv2 if __name__ == '__main__' : video = cv2.VideoCapture("test.mp4"); # Find OpenCV version (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') if int(major_ver) < 3 : fps = video.get(cv2.cv.CV_CAP_PROP_FPS) pri...
[ "Performing pip install python-opencv fixed the problem and the FPS is correctly detected.\nEDIT: tested with python 3.8 and indeed it is pip install opencv-python. Cannot remember two years ago what python I was using.\nEDIT November 2022: please also check Perry's answer below, if you are using a newer opencv-pyt...
[ 10, 2 ]
[]
[]
[ "frame_rate", "mp4", "opencv", "python" ]
stackoverflow_0049025795_frame_rate_mp4_opencv_python.txt
Q: Loading np.array from csv dataframe I have a dataframe with columns values that are np.arrays. For example df = pd.DataFrame([{"id":1, "sample": np.array([1,2,3])}, {"id":2, "sample": np.array([2,3,4])}]) df.to_csv("./tmp.csv", index=False) if I save df to csv and load it again I get "sample" column as strings. d...
Loading np.array from csv dataframe
I have a dataframe with columns values that are np.arrays. For example df = pd.DataFrame([{"id":1, "sample": np.array([1,2,3])}, {"id":2, "sample": np.array([2,3,4])}]) df.to_csv("./tmp.csv", index=False) if I save df to csv and load it again I get "sample" column as strings. df_from_csv = pd.read_csv("./tmp.csv") ...
[ "You can use a converter in read_csv:\nimport numpy as np\nfrom ast import literal_eval\nimport re\n\ndef to_array(x):\n return np.array(literal_eval(re.sub('\\s+', ',', x)))\n\ndf_from_csv = pd.read_csv(\"./tmp.csv\", converters={'sample': to_array}) \n\n# id sample\n# 0 1 [1, 2, 3]\n# 1 2 [2, 3, 4...
[ 1 ]
[]
[]
[ "csv", "numpy", "pandas", "python" ]
stackoverflow_0074475413_csv_numpy_pandas_python.txt
Q: How to run a single line or selected code in a Jupyter Notebook or JupyterLab cell? In both JupyterLab and Jupyter Notebook you can execute a cell using ctrl + Enter: Code: print('line 1') print('line 2') print('line 3') Cell and output: But how can you run only line 2? Or even a selection of lines within a cell...
How to run a single line or selected code in a Jupyter Notebook or JupyterLab cell?
In both JupyterLab and Jupyter Notebook you can execute a cell using ctrl + Enter: Code: print('line 1') print('line 2') print('line 3') Cell and output: But how can you run only line 2? Or even a selection of lines within a cell without running the entire cell? Sure you could just insert a cell with that single line...
[ "Updated answer\nAs there have been a few updates of JupyterLab since my first answer (I'm now on 1.1.4), and it has been stated that JupyterLab 1.0 will eventually replace the classic Jupyter Notebook, here's what I think is the best approach right now and even more so in the time to come:\nIn JupyterLab use Run >...
[ 45, 0 ]
[]
[]
[ "jupyter", "jupyter_lab", "jupyter_notebook", "python" ]
stackoverflow_0056460834_jupyter_jupyter_lab_jupyter_notebook_python.txt
Q: How do I check if a value already appeared in pandas df column? I have a Dataframe of stock prices... I wish to have a boolean column that indicates if the price had reached a certain threshold in the previous rows or not. My output should be something like this (let's say my threshold is 100): index price bool ...
How do I check if a value already appeared in pandas df column?
I have a Dataframe of stock prices... I wish to have a boolean column that indicates if the price had reached a certain threshold in the previous rows or not. My output should be something like this (let's say my threshold is 100): index price bool 0 98 False 1 99 False 2 100.5 True 3 101 True 4 99 True...
[ "Use a comparison and cummax:\nthreshold = 100\ndf['bool'] = df['price'].ge(threshold).cummax()\n\nNote that it would work the other way around (although maybe less efficiently*):\nthreshold = 100\ndf['bool'] = df['price'].cummax().ge(threshold)\n\nOutput:\n index price bool\n0 0 98.0 False\n1 1 ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074475685_pandas_python.txt
Q: Reading a pajek file with partitions I would need to read data from a pajek file consisting of partitions (files .clu). Looking for more information on how reading a pajek format, I've found the following question: Reading a Pajek Dataset into Networkx The answer refers to partitions of the vertex set. I've tried ...
Reading a pajek file with partitions
I would need to read data from a pajek file consisting of partitions (files .clu). Looking for more information on how reading a pajek format, I've found the following question: Reading a Pajek Dataset into Networkx The answer refers to partitions of the vertex set. I've tried to open a file as follows example = nx.rea...
[ "Executing your code, I could read the downloaded SanJuanSur2.paj very well.\nWhat make you think that you have a partition problem?\n" ]
[ 0 ]
[]
[]
[ "networkx", "pajek", "python" ]
stackoverflow_0074368436_networkx_pajek_python.txt
Q: How do I run 3 sequential methods in independent fashion in python I have a scenario where I have an Input X that is given to function A, then to function B and then to function C and finally gives an output Y. This process happens in sequence hence is slow. I am trying to build this in Python. Can you guide me on...
How do I run 3 sequential methods in independent fashion in python
I have a scenario where I have an Input X that is given to function A, then to function B and then to function C and finally gives an output Y. This process happens in sequence hence is slow. I am trying to build this in Python. Can you guide me on what I should use so that method A, B and C can run independently such ...
[ "I've tried to rebuild your function sequence in combination with multithreading.\nHere is what ive come up with:\nimport threading\nimport time\n\n# Your functions\ndef functionA(num):\n res = num + 1\n time.sleep(2)\n functionB(res)\n\ndef functionB(num):\n res = num * 2\n time.sleep(2)\n functi...
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0074475006_multithreading_python.txt
Q: Find which column has the minimum value of a sum of all rows, and having the the name of the column has output I have a sum of all rows of columns y1 to y7 of a data frame y1 4.475017e+02 y2 4.825798e+02 y3 4.077346e+04 y4 1.083712e+04 y5 4.005989e+04 y6 4.223634e+02 y7 3.385693e+01 I ...
Find which column has the minimum value of a sum of all rows, and having the the name of the column has output
I have a sum of all rows of columns y1 to y7 of a data frame y1 4.475017e+02 y2 4.825798e+02 y3 4.077346e+04 y4 1.083712e+04 y5 4.005989e+04 y6 4.223634e+02 y7 3.385693e+01 I need to find which column has min value, in this case it is y7, so I want the output to be just: y7 What I did: mini...
[ "You can use:\ndf.sum().idxmin()\n\nExample:\nprint(df)\n\n A B C D\n0 0 1 2 3\n1 4 5 6 7\n2 8 9 10 11\n3 12 13 14 15\n\ndf.sum().idxmin()\n\n'A'\n\nreferencing the column:\ncol = df.sum().idxmin()\n\ndf[col] # or without variable df[df.sum().idxmin()]\n\n0 0\n1 4\n2 ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074475760_dataframe_pandas_python.txt
Q: How to fix "RuntimeWarning: Running interpreter doesn't sufficiently support code object introspection." warning when using pipenv? Every time I run any pipenv command I'm getting this: C:\Users\user_name\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\attr_make.py:876: RuntimeWarning: Run...
How to fix "RuntimeWarning: Running interpreter doesn't sufficiently support code object introspection." warning when using pipenv?
Every time I run any pipenv command I'm getting this: C:\Users\user_name\AppData\Local\Programs\Python\Python311\Lib\site-packages\pipenv\vendor\attr_make.py:876: RuntimeWarning: Running interpreter doesn't sufficiently support code object introspection. Some features like bare super() or accessing class will not work...
[ "I was fighting the same issue on MacOS. The problem seems to be when pipenv is installed with brew. I fixed it by uninstalling the brew version of pipenv, then installing pipenv using pip. Here are the commands:\nbrew uninstall pipenv\npip install pipenv\n\nWorked like a charm for me. Hope it helps you.\n" ]
[ 3 ]
[]
[]
[ "pipenv", "python" ]
stackoverflow_0074468285_pipenv_python.txt
Q: Keeping the same legend while changing the palette in go.Pie subplot I am trying to make a subplot with two pies, and I have trouble keeping the same legend for both of them while changing the palette (although it works fine with plotly default palette) There are the two dataframes I am working with. They are made...
Keeping the same legend while changing the palette in go.Pie subplot
I am trying to make a subplot with two pies, and I have trouble keeping the same legend for both of them while changing the palette (although it works fine with plotly default palette) There are the two dataframes I am working with. They are made with a value_counts and therefore are sorted. yearly = pd.DataFrame(data=...
[ "I'm not sure what you intend to do since there is no image that includes a specific legend, but I think the issue would be solved if each subplot unit had its own legend. Your intended subplot is one row and two columns, but the legend appears above and below. This seems to be the default behavior for pie chart su...
[ 0 ]
[]
[]
[ "color_palette", "pie_chart", "plotly_python", "python", "subplot" ]
stackoverflow_0074473895_color_palette_pie_chart_plotly_python_python_subplot.txt
Q: Is it possible to pass a Literal type to a function and have that function output a value of that Literal type? I'm trying to write a function for asserting that user input matches a defined Literal type. Basically, given: MyLiteral = Literal["foo", "bar"] I want to write a function that lets me do this: some_use...
Is it possible to pass a Literal type to a function and have that function output a value of that Literal type?
I'm trying to write a function for asserting that user input matches a defined Literal type. Basically, given: MyLiteral = Literal["foo", "bar"] I want to write a function that lets me do this: some_user_provided_value = input() # For example good_value = assert_literal(MyLiteral, some_user_provided_value) The typ...
[ "The wonderful library called pydantic offers exactly that.\nFrom their homepage description:\n\npydantic enforces type hints at runtime, and provides user friendly errors when data is invalid.\n\nAnd here's an example for Literal types, found here:\nfrom typing import Literal\n\nfrom pydantic import BaseModel, Val...
[ 0 ]
[]
[]
[ "mypy", "python", "python_typing" ]
stackoverflow_0073631990_mypy_python_python_typing.txt
Q: Overwrite existing column and extract values to new columns based on different conditions i have this series which contains country,state,city and i would like to extract them accordingly- refer to the output table Region US* Arizona** Phoenix Mesa California** Los Angeles San Diego Sacramento Florida** ...
Overwrite existing column and extract values to new columns based on different conditions
i have this series which contains country,state,city and i would like to extract them accordingly- refer to the output table Region US* Arizona** Phoenix Mesa California** Los Angeles San Diego Sacramento Florida** Tampa Miami Canada* Central Canada** Montreal London my desired o...
[ "of course it's possible:\ndef split_by_country(region_list: pd.Series):\n result = []\n start_idx = None\n for i, region in enumerate(region_list):\n if region.endswith(\"*\") and not region.endswith(\"**\"):\n if start_idx is None:\n start_idx = i\n elif isinst...
[ 0 ]
[]
[]
[ "extract", "numpy", "pandas", "python" ]
stackoverflow_0074475368_extract_numpy_pandas_python.txt
Q: AWS Python Lambda Unable to Import Module In zip File constructed on CodeBuild I am trying to deploy a python lambda function with a zip file archive. Using AWS CodeBuild I followed the instructions to setup a zip file with my source code and dependencies at the top level. However, when I invoke my Lambda function...
AWS Python Lambda Unable to Import Module In zip File constructed on CodeBuild
I am trying to deploy a python lambda function with a zip file archive. Using AWS CodeBuild I followed the instructions to setup a zip file with my source code and dependencies at the top level. However, when I invoke my Lambda function an import error is reported: { "errorMessage": "Unable to import module 'my_modul...
[ "The problem is with python versions. The Standard 6.0 CodeBuild environment has python 3.10 installed but the python runtime environment in Lambda only goes up to 3.9 (at the time of this answer).\nTherefore, when installing the dependencies into the zip file\npip install --target ./package requests\n\ncd package...
[ 0 ]
[]
[]
[ "aws_codebuild", "aws_lambda", "python", "zip" ]
stackoverflow_0074475868_aws_codebuild_aws_lambda_python_zip.txt
Q: AWS Lambda : OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k - While using Google Custom Search API I deployed the Google Custom Search API as AWS lambda function for my project. It uses the 3GB (full memory provided by lambda) and task got terminated. It throws a warning : "...
AWS Lambda : OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k - While using Google Custom Search API
I deployed the Google Custom Search API as AWS lambda function for my project. It uses the 3GB (full memory provided by lambda) and task got terminated. It throws a warning : "OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k" I don't know why its consuming more memory?
[ "This warning is just a warning, and has nothing to do with your problems.\nBLAS is a highly optimised library, aiming to get near-perfect performance on all hardware. AWS Lambdas are supposed to run in a more abstract environment than most, and the low-level details of what CPU it's running on are not available to...
[ 27, 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "google_api", "python", "python_3.x" ]
stackoverflow_0057087498_amazon_web_services_aws_lambda_google_api_python_python_3.x.txt
Q: Using Astropy to make an array dimensionless I have an array, and I want to make it dimensionless so I can use np.log() However, following the guide in the Units and Quantities documentation for astropy does not seem to work. This is the code I written so far: #Calculating luminosity of a source (units Jy/Mpc^2)...
Using Astropy to make an array dimensionless
I have an array, and I want to make it dimensionless so I can use np.log() However, following the guide in the Units and Quantities documentation for astropy does not seem to work. This is the code I written so far: #Calculating luminosity of a source (units Jy/Mpc^2) luminosity = 4*pi*Total_flux*dl*dl*((1.+z)**(alph...
[ "Answering my own question here:\n lum_dimensionless = lum_in_W.to_value()\n\nreturns the dimensionless value.\nShould have found this before posting, but I suppose you can get tunnel vision sometimes into trying to get a specific line to work, especially when you are convinced it must be the correct solution--my a...
[ 0 ]
[]
[]
[ "astropy", "python" ]
stackoverflow_0074462659_astropy_python.txt
Q: pandas - how can I remove some character after find specific character I have a data frame like this. document_group A12J3/381 A02J3/40 B12P4/2536 C10P234/3569 and I would like to get like this document_group A12J3/38 A02J3/40 B12P4/25 C10P234/35 I have tried to adapt a function for single strin...
pandas - how can I remove some character after find specific character
I have a data frame like this. document_group A12J3/381 A02J3/40 B12P4/2536 C10P234/3569 and I would like to get like this document_group A12J3/38 A02J3/40 B12P4/25 C10P234/35 I have tried to adapt a function for single string like this def remove_str_start(s, start): return s[:start] + s[start] ...
[ "We can use str.replace here:\ndf[\"document_group\"] = df[\"document_group\"].str.replace(r'/(\\d{2})\\d+$', r'\\1', regex=True)\n\nHere is a Python regex demo showing that the replacement logic is working.\n", "You can also str.split remove the unwanted parts and put together:\ns = df.document_group.str.split('...
[ 2, 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074475850_pandas_python.txt
Q: Find common Keys from two dict and return new dict from common keys So I have two dicts called results and results_2 with different lengths with the following setup: Result is also significantly shorter than the Result_2: result {('CMS', 'LNT'): 0.8500276624334894, ('LNT', 'CMS'): 0.8500276624334894, ('LOW', 'HD...
Find common Keys from two dict and return new dict from common keys
So I have two dicts called results and results_2 with different lengths with the following setup: Result is also significantly shorter than the Result_2: result {('CMS', 'LNT'): 0.8500276624334894, ('LNT', 'CMS'): 0.8500276624334894, ('LOW', 'HD'): 0.8502400376842035, ('HD', 'LOW'): 0.8502400376842036, ('SWKS', 'QR...
[ "Coincidentally, the dict.keys method returns a set-like object that you can do set-like operations on:\n>>> a = {(1, 2): 'a', (3, 4): 'b'}\n>>> b = {(3, 4): 'c', (5, 6): 'd'}\n>>> a.keys() & b.keys()\n{(3, 4)}\n\nFrom there you can pick the values from whichever dict you like:\n>>> {k: a[k] for k in a.keys() & b.k...
[ 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074475876_dictionary_python.txt
Q: How to merge 2 columns in pandas dataframe by taking either value or mean and create a third column? I have a dataframe with 2 columns. How can I create a third column which: Takes either col1 or col2 value if either exists Takes mean if both exists Keeps NaN if neither exists And finally I want to store it in d...
How to merge 2 columns in pandas dataframe by taking either value or mean and create a third column?
I have a dataframe with 2 columns. How can I create a third column which: Takes either col1 or col2 value if either exists Takes mean if both exists Keeps NaN if neither exists And finally I want to store it in df['col3']. I tried this, but the values are wrong. df['col3']=pd.concat([df['col2'], df['col1']]).groupby(...
[ "The answer is surprisingly simple:\ndf['col3'] = df[['col1', 'col2']].mean(axis=1)\n\nThis is due to the fact that mean ignores the NaN by default (skipna=True), so if you have only one value, the mean is the value itself, if only NaNs, the output is a NaN\nOutput:\n time col1 col2 col3\n0 2...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074475833_pandas_python.txt
Q: How to upload document on an Article using article id when it does not even exists currently i am in a very weird situation. I am trying to upload document using article id and user id to an article. But the issue is when I try to select article id from the document model, it gives error that article doesnt exists...
How to upload document on an Article using article id when it does not even exists
currently i am in a very weird situation. I am trying to upload document using article id and user id to an article. But the issue is when I try to select article id from the document model, it gives error that article doesnt exists. And tbh that is true, because how can i upload document to an article when it doesnt e...
[ "So, I think the way I was trying to post document for article was complicated.\nI was adding the article id into document when article id was not even created till then.\nSo the solution that I came upon is instead of using these two foreign keys in document model below:\n user_fk_doc=models.ForeignKey(User, on...
[ 0 ]
[]
[]
[ "blogs", "django", "django_models", "django_rest_framework", "python" ]
stackoverflow_0074459771_blogs_django_django_models_django_rest_framework_python.txt
Q: What is the difference between Django timezone now and the built-in one? I've just noticed this: >>> import datetime >>> from django.utils import timezone >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).microseconds 999989 >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now...
What is the difference between Django timezone now and the built-in one?
I've just noticed this: >>> import datetime >>> from django.utils import timezone >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).microseconds 999989 >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).seconds 86399 >>> 24*60*60 86400 >>> (datetime.datetime.now(tz=datetime....
[ "The second value in your subtraction is getting created a microsecond or so after the first value. So it's a later point in time. You're subtracting the later point in time from the earlier point in time. Yielding a negative delta:\n>>> datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()\ndatetime.tim...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074475995_django_python.txt
Q: Split variable in Pyspark I try to split the utc value found in timestamp_value in a new column called utc. I tried to use the Python RegEx but I was not able to do it. Thank you for your answer! This is how my dataframe looks like +--------+----------------------------+ |machine |timestamp_value | +--...
Split variable in Pyspark
I try to split the utc value found in timestamp_value in a new column called utc. I tried to use the Python RegEx but I was not able to do it. Thank you for your answer! This is how my dataframe looks like +--------+----------------------------+ |machine |timestamp_value | +--------+------------------------...
[ "You can do this with with a regexp_extract and regexp_replace respectively\nimport pyspark.sql.functions as F\n\n(df\n .withColumn('utc', F.regexp_extract('timestamp_value', '.*(\\+.*)', 1))\n .withColumn('timestamp_value', F.regexp_replace('timestamp_value', '\\+(.*)', ''))\n).show(truncate=False)\n\n+-------+---...
[ 2 ]
[]
[]
[ "apache_spark", "data_wrangling", "pyspark", "python", "regex" ]
stackoverflow_0074476037_apache_spark_data_wrangling_pyspark_python_regex.txt
Q: How do I pass application context to a child function in flask? Here is the project Structure. |-- a_api/ | |- a1.py | |-- b_api/ | |-b1.py | |-- c_api/ | |-c1.py | |-c2.py | |-- utils/ | |-db.py | |-- main.py db.py connects to mongo and stores connection in g from flask. from flask import g from ...
How do I pass application context to a child function in flask?
Here is the project Structure. |-- a_api/ | |- a1.py | |-- b_api/ | |-b1.py | |-- c_api/ | |-c1.py | |-c2.py | |-- utils/ | |-db.py | |-- main.py db.py connects to mongo and stores connection in g from flask. from flask import g from pymongo import MongoClient mongo_db = 'mongo_db' def get_mongo_db()...
[ "Try something like this:\nfrom flask import g\nfrom pymongo import MongoClient\n\n# import main flask app\nfrom X import app\n\nmongo_db = 'mongo_db'\n\ndef get_mongo_db():\n \"\"\"Function will create a connection to mongo db for the current Request\n\n Returns:\n mongo_db: THe connection to Mongo Db...
[ 2 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074386757_flask_python.txt
Q: Switch to editor pane shortcut not working in Spyder 5.X I'm on Windows 10 and recently updated to Spyder 5.3.3 standalone version and the keyboard shortcut to switch to the editor pane (default Ctrl+E) will not work no matter what I try, it simply has no effect. I've tried reinstalling Spyder, resetting everythin...
Switch to editor pane shortcut not working in Spyder 5.X
I'm on Windows 10 and recently updated to Spyder 5.3.3 standalone version and the keyboard shortcut to switch to the editor pane (default Ctrl+E) will not work no matter what I try, it simply has no effect. I've tried reinstalling Spyder, resetting everything back to defaults multiple times, changing to different keybo...
[ "Same issue here, and I think the issue started with the upgrade from 5.3.2 to 5.3.3 only. Before that it still worked.\n", "The issue appears to be version-specific.\nHave upgraded from 5.3.3 to 5.4.0, and the shortcut is working again.\n" ]
[ 2, 1 ]
[]
[]
[ "ide", "keyboard_shortcuts", "python", "spyder", "windows" ]
stackoverflow_0073818754_ide_keyboard_shortcuts_python_spyder_windows.txt
Q: How can I use Stockfish in Python so that the evaluation is continuously updated like in chess.com, instead of computed for a given amount of time? I am using the stockfish 3.23 package in python. To get the evaluation of the chess position, I use the following code: self.stockfish = Stockfish(path="stockfish\\sto...
How can I use Stockfish in Python so that the evaluation is continuously updated like in chess.com, instead of computed for a given amount of time?
I am using the stockfish 3.23 package in python. To get the evaluation of the chess position, I use the following code: self.stockfish = Stockfish(path="stockfish\\stockfish", depth=18, parameters={"Threads": 2, "Minimum Thinking Time": 1000}) self.stockfish.set_fen_position(fen) evaluationValue = self.stockfish.get_ev...
[ "I assume one way to solve it would be to make the call in a loop from 1 to maxDepth and then print the results for each depth in the loop.\nI am not sure how the Stockfish package works but Stockfish uses some sort of iterative deepening which means that if it searches for depth 18 it will do the loop mentioned ab...
[ 0, 0 ]
[]
[]
[ "chess", "evaluation", "python", "stockfish" ]
stackoverflow_0071945463_chess_evaluation_python_stockfish.txt
Q: Gekko and Intermediate variables I am using GEKKO to fit a function. The form of a function is known. It looks like a sum of similar subfunctions with various parameters, each subfunction has its own set of parameters to find (optimize)... I don't think I understand the use of intermediate variables fully and woul...
Gekko and Intermediate variables
I am using GEKKO to fit a function. The form of a function is known. It looks like a sum of similar subfunctions with various parameters, each subfunction has its own set of parameters to find (optimize)... I don't think I understand the use of intermediate variables fully and would love some help with my code. I am us...
[ "The problem with the code was connected with the use of various data types representation\ne.g.\nk_alfa = m.Intermediate(A1*np.sqrt(x))\n\nneed to be changed on:\nk_alfa = m.Intermediate(A1*m.sqrt(x))\n\nand so on..\nBecause functions vary in output datatypes.\nAlways check and be aware of using various data types...
[ 2 ]
[]
[]
[ "gekko", "optimization", "python" ]
stackoverflow_0074416814_gekko_optimization_python.txt
Q: I want create comment section that can only logged in users can use but I have this problem I get an Error: cannot unpack non-iterable bool object profile = Profile.objects.get(Profile.user == request.user) This is my models.py in account app and blog app: class Profile(models.Model): STATUS_CHOICES = ( ...
I want create comment section that can only logged in users can use but I have this problem
I get an Error: cannot unpack non-iterable bool object profile = Profile.objects.get(Profile.user == request.user) This is my models.py in account app and blog app: class Profile(models.Model): STATUS_CHOICES = ( ('manager', 'مدیر'), ('developer', 'توسعه‌دهنده'), ('designer', 'طراح پروژ...
[ "Assuming you need to get only single profile instance i.e. current logged in user's profile so you can either use:\n profile = Profile.objects.get(user=request.user)\n\nor:\nget_object_or_404(Profile, user=request.user)\n\nTo limit the view to be accessed by only logged in users, use @login_required decorator so:\...
[ 3 ]
[]
[]
[ "django", "django_forms", "django_queryset", "django_views", "python" ]
stackoverflow_0074475920_django_django_forms_django_queryset_django_views_python.txt
Q: sendkeys() to bloomberg panel python I try to do a basic sendkeys() to and open an logged into bloomberg panel. I am able to verify that sendkeys() works with this: import time import win32com.client as comclt wsh= comclt.Dispatch("WScript.Shell") wsh.AppActivate("Notepad") # select another application time.sleep...
sendkeys() to bloomberg panel python
I try to do a basic sendkeys() to and open an logged into bloomberg panel. I am able to verify that sendkeys() works with this: import time import win32com.client as comclt wsh= comclt.Dispatch("WScript.Shell") wsh.AppActivate("Notepad") # select another application time.sleep(0.5) # wait for half a second wsh.SendKey...
[ "assuming you are trying to log into bloomberg automatically using some script. i use vbscript to achieve this at a scheduled time of the day.\nbelow is my vb script saved as a .vbs file and executed using windows task manager\nyou will need to change loginname and password to match yours\nthe commented part of the...
[ 0 ]
[]
[]
[ "bloomberg", "python", "sendkeys" ]
stackoverflow_0072642190_bloomberg_python_sendkeys.txt
Q: Add values to new column from a dict with keys matching the index of a dataframe I have a dictionary that for examples sake, looks like {'a': 1, 'b': 4, 'c': 7} I have a dataframe that has the same index values as the keys in this dict. I want to add each value from the dict to the dataframe. I feel like doing a ...
Add values to new column from a dict with keys matching the index of a dataframe
I have a dictionary that for examples sake, looks like {'a': 1, 'b': 4, 'c': 7} I have a dataframe that has the same index values as the keys in this dict. I want to add each value from the dict to the dataframe. I feel like doing a check for every row of the DF, checking the index value, matching it to the one in the...
[ "You can use map and assign back to a new column:\nd = {'a': 1, 'b': 4, 'c': 7}\ndf = pd.DataFrame({'c':[1,2,3]},index=['a','b','c'])\n\ndf['new_col'] = df.index.map(d)\n\nprints:\n c new_col\na 1 1\nb 2 4\nc 3 7\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074476226_pandas_python.txt
Q: how to add dictionary object name to json object I have 3 python dictionaries as below: gender = {'Female': 241, 'Male': 240} marital_status = {'Divorced': 245, 'Engaged': 243, 'Married': 244, 'Partnered': 246, 'Single': 242} family_type = {'Extended': 234, 'Joint': 235, 'Nuclear': 233, 'Single Parent': 236} I ad...
how to add dictionary object name to json object
I have 3 python dictionaries as below: gender = {'Female': 241, 'Male': 240} marital_status = {'Divorced': 245, 'Engaged': 243, 'Married': 244, 'Partnered': 246, 'Single': 242} family_type = {'Extended': 234, 'Joint': 235, 'Nuclear': 233, 'Single Parent': 236} I add them to a list: lst = [gender, marital_status, famil...
[ "You'll have to do this manually by creating a dictionary and mapping the name to the sub_dictionary yourself.\nmy_data = {'gender': gender, 'marital_status':marital_status, 'family_type': family_type}\n\nEdit: example of adding to an outfile using json.dump\nwith open('myfile.json','w') as wrtier:\n json.dump(m...
[ 2, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074476259_json_python.txt
Q: Python import error on MacOS: `import scipy.integrate` raises `Library not loaded: ibgfortran.5.dylib` echo $PATH gives /usr/local/texlive/2021/bin/universal-darwin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/opt/X11/bin:/Library/Apple/usr/bin After updating to MacOS Monterey import scipy.in...
Python import error on MacOS: `import scipy.integrate` raises `Library not loaded: ibgfortran.5.dylib`
echo $PATH gives /usr/local/texlive/2021/bin/universal-darwin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/opt/X11/bin:/Library/Apple/usr/bin After updating to MacOS Monterey import scipy.integrate in Python raises --------------------------------------------------------------------------- ImportE...
[ "According to the error message, it can't find libgfortran.5.dylib inside /usr/local/opt/gcc/lib/gcc/10. Since you are on gcc version 11, you can try to copy it from there via\nmkdir -p /usr/local/opt/gcc/lib/gcc/10\ncp /usr/local/opt/gcc/lib/gcc/11/libgfortran.5.dylib /usr/local/opt/gcc/lib/gcc/10/\n\ninside a ter...
[ 0, 0 ]
[]
[]
[ "dylib", "macos", "python", "scipy" ]
stackoverflow_0069809226_dylib_macos_python_scipy.txt
Q: Python adding the values # Initialising list of dictionary ini_dict = [{'a':5, 'b':10, 'c':90}, {'a':45, 'b':78}, {'a':90, 'c':10}] # printing initial dictionary print ("initial dictionary", (ini_dict)) # sum the values with same keys result = {} for d in ini_dict: for k in d.keys(): r...
Python adding the values
# Initialising list of dictionary ini_dict = [{'a':5, 'b':10, 'c':90}, {'a':45, 'b':78}, {'a':90, 'c':10}] # printing initial dictionary print ("initial dictionary", (ini_dict)) # sum the values with same keys result = {} for d in ini_dict: for k in d.keys(): result[k] = result.get(k,0) + d...
[ "Creating a list of dictionary's\nini_dict = [{'a':5, 'b':10, 'c':90},\n {'a':45, 'b':78},\n {'a':90, 'c':10}]\n\nPrints out the list with dictionary's\nprint (\"initial dictionary\", (ini_dict))\n\nCreates a new dictionary\nresult = {}\n\nLoop's through the List of dictionarys\n for d in ini_dict:\n\nso th...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074476206_python.txt
Q: double integer checker function As the title says, this is a double integer checker, meaning it has two functions + the main. Please correct me if I do not paraphrase it correctly. Anyways, here is the model: def is_integer(kraai): kraai.replace(" ", "") if len(kraai) == 1: if kraai.isdigit(): ...
double integer checker function
As the title says, this is a double integer checker, meaning it has two functions + the main. Please correct me if I do not paraphrase it correctly. Anyways, here is the model: def is_integer(kraai): kraai.replace(" ", "") if len(kraai) == 1: if kraai.isdigit(): print(valid) else: ...
[ "So yeah there were multiple errors at the time I posted this question.\ndef is_integer(kraai):\n\n valid = \"valid\"\n invalid = \"invalid\"\n\n if len(kraai) == 1:\n if kraai.isdigit():\n print(valid)\n elif not kraai.isdigit():\n print(invalid)\n\n elif len(kraai) ...
[ 0 ]
[]
[]
[ "arguments", "filter", "for_loop", "function", "python" ]
stackoverflow_0074423121_arguments_filter_for_loop_function_python.txt
Q: changing opacity based on different column using plotly I would like to change the opacity of the bar based on a value in a different column. here is a simple example. if the gdpPercap <20000 I want to change the opacity to 0.5 for instance. I also have a discrete color map that assigns colors based on the decade...
changing opacity based on different column using plotly
I would like to change the opacity of the bar based on a value in a different column. here is a simple example. if the gdpPercap <20000 I want to change the opacity to 0.5 for instance. I also have a discrete color map that assigns colors based on the decade, for instance 1980-1990 is green , 1990-2000 is red. Within ...
[ "Add a column with the newly standardized Gross Domestic Product values. (from 0 to 1) Specify a continuous colormap with that column as the color target. Specify the transparency of that color specification in RGBA. The threshold value of 0.4 is set appropriately, so change it to your threshold value.\nimport plot...
[ 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074475536_plotly_python.txt
Q: Workaround for TypeVar bound on a TypeVar? Is there some way of expressing this Scala code with Python's type hints? trait List[A] { def ::[B >: A](x: B): List[B] } I'm trying to achieve this sort of thing class X: pass class Y(X): pass class Z(X): pass xs = MyList(X(), X()) # inferred as MyList[X] ys = MyLis...
Workaround for TypeVar bound on a TypeVar?
Is there some way of expressing this Scala code with Python's type hints? trait List[A] { def ::[B >: A](x: B): List[B] } I'm trying to achieve this sort of thing class X: pass class Y(X): pass class Z(X): pass xs = MyList(X(), X()) # inferred as MyList[X] ys = MyList(Y(), Y()) # inferred as MyList[Y] _ = xs.ext...
[ "You're trying to specify that B is a supertype of A. But instead of specifying that B should be a supertype of A, it is much easier to state that B is any type, and then the Union A|B is the supertype of A you need.\nfrom typing import TypeVar, Generic\nA = TypeVar(\"A\", covariant=True)\nB = TypeVar(\"B\")\n\ncla...
[ 0 ]
[ "from __future__ import annotations\n\nfrom typing import (\n TYPE_CHECKING,\n Generic,\n TypeVar,\n)\n\nB = TypeVar('B')\nA = TypeVar('A')\n\n\nclass MyList(Generic[A]):\n def __init__(*o: A):\n ...\n\n def extended_by(self, x: B) -> MyList[B]:\n ...\n\n\nclass Y:\n ...\n\n\nclass X...
[ -2 ]
[ "python", "type_bounds", "type_hinting", "types" ]
stackoverflow_0057590086_python_type_bounds_type_hinting_types.txt
Q: I can't use the command ' python manage.py makemigrations' in django VSC I already did 'python manage.py migrations'. Now i want to create '0001_inital.py' file in migrations with the code 'python manage.py makemigrations'. Firstly this is my models.py; from django.db import models class Room(models.Model): #...
I can't use the command ' python manage.py makemigrations' in django VSC
I already did 'python manage.py migrations'. Now i want to create '0001_inital.py' file in migrations with the code 'python manage.py makemigrations'. Firstly this is my models.py; from django.db import models class Room(models.Model): #host = #topic = name = models.CharField(max_Length=200) descript...
[ "It should be max_length not max_Length and TextField not Textfield so the correct is:\n\nclass Room(models.Model):\n #host =\n #topic =\n name = models.CharField(max_length=200)\n description = models.TextField(null=True, blank = True)\n #participants = \n updated = models.DateTimeField(auto_now ...
[ 5 ]
[]
[]
[ "django", "django_migrations", "django_model_field", "django_models", "python" ]
stackoverflow_0074476353_django_django_migrations_django_model_field_django_models_python.txt
Q: XML and Excel Structures, debugging and etc I'm currently working on this project: https://github.com/lucasmolinari/unlocker-EX. It's a excel unlocker, it works by editing the XML files inside the workbooks. (more information on the github page). The script works fine in workbooks with almost no content inside, bu...
XML and Excel Structures, debugging and etc
I'm currently working on this project: https://github.com/lucasmolinari/unlocker-EX. It's a excel unlocker, it works by editing the XML files inside the workbooks. (more information on the github page). The script works fine in workbooks with almost no content inside, but recently I'm testing some bigger workbooks, and...
[ "Using ElementTree library solves the problem\n" ]
[ 0 ]
[]
[]
[ "debugging", "excel", "python", "xml" ]
stackoverflow_0074465153_debugging_excel_python_xml.txt
Q: Python plot_data can anyone teach me how to plot a csv A: You can try this also to display plot import matplotlib.pyplot as plt import csv x = [] y = [] with open('data_file.csv','r') as csvfile: plots = csv.reader(csvfile, delimiter = ',') for row in plots: x.append(row[0]) y.appe...
Python plot_data
can anyone teach me how to plot a csv
[ "You can try this also to display plot\nimport matplotlib.pyplot as plt\nimport csv\n\nx = []\ny = []\n\nwith open('data_file.csv','r') as csvfile:\n plots = csv.reader(csvfile, delimiter = ',')\n \n for row in plots:\n x.append(row[0])\n y.append(row[1])\n\nplt.bar(x, y, color = 'g', width =...
[ 1, 1, 0 ]
[]
[]
[ "plot", "python" ]
stackoverflow_0074476005_plot_python.txt
Q: Stockfish for python not working correctly, how to fix this? I'm writing a chess puzzle solver using stockfish. I'm using the python interfacing of stockfish as described here. https://pypi.org/project/stockfish/ Like the author told, I installed the stockfish engine from the terminal of my can and ran the code be...
Stockfish for python not working correctly, how to fix this?
I'm writing a chess puzzle solver using stockfish. I'm using the python interfacing of stockfish as described here. https://pypi.org/project/stockfish/ Like the author told, I installed the stockfish engine from the terminal of my can and ran the code below. It throws an error "AttributeError: 'Stockfish' object has no...
[ "The stockfish package is only a python interface for stockfish, you need to either compile it from the source, or download an executable.\nOnce you have the executable, simply provide a path to the Stockfish constructor as in the example.\nfrom stockfish import Stockfish\nstockfish = Stockfish(path=\"/Users/zhelya...
[ 1 ]
[]
[]
[ "chess", "python", "stockfish" ]
stackoverflow_0073559878_chess_python_stockfish.txt
Q: How to calculate tax in python? I need to write a function compute_tax(money_list) that calculates the total tax for a given list of financial amounts. The rich (200 money and more) pay a tax of 20. Those who are not rich, but have at least 100 money, pay a tax of 10. The others do not pay the tax. I have prepared...
How to calculate tax in python?
I need to write a function compute_tax(money_list) that calculates the total tax for a given list of financial amounts. The rich (200 money and more) pay a tax of 20. Those who are not rich, but have at least 100 money, pay a tax of 10. The others do not pay the tax. I have prepared the basis of the function, which nee...
[ "You have two issues in your code. Firstly you just check for money == 100 in your first if Statement and secondly you assign tax = 0 in your else statement. To correct:\ndef compute_tax(money_list):\n tax = 0\n for money in money_list:\n if money >= 100 and money < 200:\n tax += 10\n ...
[ 2 ]
[]
[]
[ "function", "python", "python_3.x", "tax" ]
stackoverflow_0074476237_function_python_python_3.x_tax.txt
Q: Scraping data from CME I am trying to webscrape data from CME exchange: https://www.cmegroup.com/CmeWS/mvc/Settlements/Futures/Settlements/425/FUT?tradeDate=11/05/2021 I have the following code snippet: import requests as r user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Ge...
Scraping data from CME
I am trying to webscrape data from CME exchange: https://www.cmegroup.com/CmeWS/mvc/Settlements/Futures/Settlements/425/FUT?tradeDate=11/05/2021 I have the following code snippet: import requests as r user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Sa...
[ "Apparently, some hosting providers are blocked by CME. You should look for one which is not blocked and you can use it as a proxy server. That's the solution that worked for me. However, now I am thinking that this could be related to IPv6 settings on the server. Try to disable IPv6 connection and it will automati...
[ 1, 1, 0 ]
[]
[]
[ "python", "python_requests", "web_scraping" ]
stackoverflow_0069870683_python_python_requests_web_scraping.txt
Q: Tkinter scrollbar removes textbox and doesnt sticky to the right My textbox spans over 5 rows and 4 columns and I want it to have a scrollbar, so I added one but it removes the textbox and doesn't stick. My textbox looks like this: and its code like this # Textbox self.textbox = Text(self) self.t...
Tkinter scrollbar removes textbox and doesnt sticky to the right
My textbox spans over 5 rows and 4 columns and I want it to have a scrollbar, so I added one but it removes the textbox and doesn't stick. My textbox looks like this: and its code like this # Textbox self.textbox = Text(self) self.textbox.grid(row=10, column=1, rowspan=5, columnspan=4, padx=10, pady=1...
[ "Maybe you'll have better luck with the ScrolledText widget. See here for docs\nfrom tkinter.scrolledtext import ScrolledText\n\nself.textbox = ScrolledText(self)\n\n" ]
[ 1 ]
[]
[]
[ "python", "scrollbar", "tkinter" ]
stackoverflow_0074476452_python_scrollbar_tkinter.txt
Q: flake8 not picking up config file I have my flake8 config file in ~/.config/flake8 [flake8] max-line-length = 100 However when I run flake8 the config file is not picked up. I know that because i still get warnings over lines longer than 79 char. I'm on redhat, but the same happens on mac. I use pyenv. Global is ...
flake8 not picking up config file
I have my flake8 config file in ~/.config/flake8 [flake8] max-line-length = 100 However when I run flake8 the config file is not picked up. I know that because i still get warnings over lines longer than 79 char. I'm on redhat, but the same happens on mac. I use pyenv. Global is 2.7.6 (not even sure this is relevant)
[ "For anyone running into this more recently: I turns out flake8 4.x no longer supports loading .config/flake8, and seems to have no alternative.\nFrom https://flake8.pycqa.org/en/latest/internal/option_handling.html#configuration-file-management :\n\nIn 4.0.0 we have once again changed how this works and we removed...
[ 7, 5, 2, 1, 0 ]
[]
[]
[ "flake8", "python", "python_2.7" ]
stackoverflow_0028436382_flake8_python_python_2.7.txt
Q: Merge lists in columns in pandas dataframe I've got a dataframe with lists in two columns. It looks like this: column1 column2 column3 0 text [cat1,cat2,cat3] [1,2,3] 1 text2 [cat2,cat3,cat1] [4,5,6] The values in column3 belong to the categories in column2. How can I get a...
Merge lists in columns in pandas dataframe
I've got a dataframe with lists in two columns. It looks like this: column1 column2 column3 0 text [cat1,cat2,cat3] [1,2,3] 1 text2 [cat2,cat3,cat1] [4,5,6] The values in column3 belong to the categories in column2. How can I get a dataframe that looks like this? column1 ...
[ "You could use explode to break the values in your lists into separate rows and use pivot_table:\ndf.explode(\n ['column2','column3']\n ).pivot_table(index='column1',columns='column2',values='column3',aggfunc='first').reset_index()\n\nprints:\nindex column1 cat1 cat2 cat3\n0 text 1 2 3\n...
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074476147_dataframe_python.txt
Q: [Python]: Check that no *args. is passed Say that I have a function with this signature foo(*args,a:int=0, b:int=1). How to check if no *args is passed? I am trying def foo(*args,a:int=0, b:int=1): if args is None: print("No args passed") If I call it with foo(), but I don't get anything printed on scr...
[Python]: Check that no *args. is passed
Say that I have a function with this signature foo(*args,a:int=0, b:int=1). How to check if no *args is passed? I am trying def foo(*args,a:int=0, b:int=1): if args is None: print("No args passed") If I call it with foo(), but I don't get anything printed on screen.
[ "In conclusion:\nUse not args or args == ()\ndef foo(*args, a:int=0, b:int=1):\n if not args:\n print(\"No args passed\")\nfoo()\n\ndef foo(*args, a:int=0, b:int=1):\n if args == ():\n print(\"No args passed\")\nfoo()\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074476441_python.txt
Q: Python Open and Save Most Recent Files in Different Subfolders with Win32com I have a main folder that has 37subfolders, each subfolder contains multiple files, I want to open the most recent file in each subfolder, then save and close using win32. My code works just fine but its opening and saving only one file i...
Python Open and Save Most Recent Files in Different Subfolders with Win32com
I have a main folder that has 37subfolders, each subfolder contains multiple files, I want to open the most recent file in each subfolder, then save and close using win32. My code works just fine but its opening and saving only one file in one subfolder, I need the code to open, save and close the most recent file in e...
[ "In case it helps anybody out there here is the correct code that works to opeb abd close most recent files in each subfolders of a directory\nfrom pathlib import Path\nimport glob\nfrom win32com.client import Dispatch\n\n\nxlApp = Dispatch(\"Excel.Application\") #call dispatch just once, dispatching multiple times...
[ 0 ]
[]
[]
[ "python", "pywin32", "win32com" ]
stackoverflow_0074467093_python_pywin32_win32com.txt
Q: Index to closest coordinate I have this function A=[(1,2,3),(2,3,4)] B=[(2,4,3),(1,8,1),(2,3,5),(1,5,3)] def closestNew(A,B): C = {} for bp in B: closestDist = -1 for ap in A: dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2)) if(closestDist > dist or close...
Index to closest coordinate
I have this function A=[(1,2,3),(2,3,4)] B=[(2,4,3),(1,8,1),(2,3,5),(1,5,3)] def closestNew(A,B): C = {} for bp in B: closestDist = -1 for ap in A: dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2)) if(closestDist > dist or closestDist == -1): C[bp]...
[ "A=[(1,2,3),(2,3,4)]\nB=[(2,4,3),(1,8,1),(2,3,5),(1,5,3)]\nC={(1, 2, 3): (2, 4, 3), (2, 3, 4): (2, 3, 5)}\n\nC is a dictionary where it values correspond to points on B.\nidx=[] # an empty list\nfor x in C.values():\n idx.append(B.index(x)) # index function to find the index of values in B\n\nprint(idx)\n#[...
[ 0, 0 ]
[]
[]
[ "distance", "indexing", "list", "python", "tuples" ]
stackoverflow_0074475912_distance_indexing_list_python_tuples.txt
Q: highlight.js not working on django+dash website I have a django website where I'd like to display blocks of code w/ syntax highlighting. I've installed highlight.js and per their instructions am injecting style and js into html, in this case in base.html: ... <link rel="stylesheet" href="{% static 'highlight/style...
highlight.js not working on django+dash website
I have a django website where I'd like to display blocks of code w/ syntax highlighting. I've installed highlight.js and per their instructions am injecting style and js into html, in this case in base.html: ... <link rel="stylesheet" href="{% static 'highlight/styles/default.min.css' %}"> <script src="{% static 'highl...
[ "I have encountered this problem myself trying to implement highlight.js for my dash app. I have found a nice alternative, built directly for Dash:\nThe DMC Code and Prism components\n\nPrism component for Syntax highlighting\nhttps://www.dash-mantine-components.com/components/prism\n\nCode\ncomponent that for inli...
[ 1 ]
[]
[]
[ "css", "django", "html", "javascript", "python" ]
stackoverflow_0072297872_css_django_html_javascript_python.txt
Q: Auto mount usb drive to raspberry pi without boot I have raspberry pi 3B. It's running on Raspbian GNU/Linux 9 (stretch). I saw some tutorials about mounting usb drive to it but mostly there are 2 ways: -mount that drive manually, -mount that drive automatically at boot and I'm looking for mounting that usb drive ...
Auto mount usb drive to raspberry pi without boot
I have raspberry pi 3B. It's running on Raspbian GNU/Linux 9 (stretch). I saw some tutorials about mounting usb drive to it but mostly there are 2 ways: -mount that drive manually, -mount that drive automatically at boot and I'm looking for mounting that usb drive automatically at lifetime (without boot) on specific pa...
[ "usbmount is a nifty package that adds udev hooks for auto mounting/unmounting.\nSimply install it with:\nsudo apt install usbmount\n\nThere appears to be an issue that stops it working properly, and in a nutshell the solution is as follows:\n\nEdit the following file in an editor:\nsudo nano /lib/systemd/system/sy...
[ 0 ]
[]
[]
[ "linux", "mount", "python", "raspberry_pi", "usb" ]
stackoverflow_0074474113_linux_mount_python_raspberry_pi_usb.txt
Q: How do I get the negative of this answer? Why can I not just put a negative sign when returning the function? The problem The problem is basically using if and else loops to get the outputs as shown above. So based on the formula for harmonic series, I returned the following results should n be above 1 My code was...
How do I get the negative of this answer? Why can I not just put a negative sign when returning the function?
The problem The problem is basically using if and else loops to get the outputs as shown above. So based on the formula for harmonic series, I returned the following results should n be above 1 My code was basically this and seems to have gotten the right answers but I always end up with a negative value. Is there some...
[ "Your function is not correct.\nThis one is:\n\"\"\"\nHarmonic series using recursion\n\nSee https://stackoverflow.com/questions/74476333/how-do-i-get-the-negative-of-this-answer-why-can-i-not-just-put-a-negative-sign\nSee https://i.stack.imgur.com/ShNUi.png\n\"\"\"\n\n\ndef alternating(k):\n if k != 1:\n ...
[ 1 ]
[]
[]
[ "function", "if_statement", "math", "python" ]
stackoverflow_0074476333_function_if_statement_math_python.txt
Q: I am trying to write an algorithm that uses a stack to check if an expression has balanced parentheses but I keep encountering this error def is_matched(expression): left_bracket = "[({" right_bracket = "])}" my_stack = Stack(len(expression)) # our solution methodology is to go through the expressi...
I am trying to write an algorithm that uses a stack to check if an expression has balanced parentheses but I keep encountering this error
def is_matched(expression): left_bracket = "[({" right_bracket = "])}" my_stack = Stack(len(expression)) # our solution methodology is to go through the expression and push all of the the open brackets onto the stack and then # with the closing brackets - each time we encounter a closing bracket we ...
[ "at this line:\nif right_bracket.index(character) != left_bracket.index(my_stack.pop):\nyou actually need to call pop method, since pop is a method, not a property.\ntherefore it should look like this:\nif right_bracket.index(character) != left_bracket.index(my_stack.pop()):\n" ]
[ 0 ]
[]
[]
[ "parentheses", "python", "stack" ]
stackoverflow_0074476000_parentheses_python_stack.txt
Q: count the numbers of Objects of fruits apple, guava, orange, gooseberry, lemon, tomato I am encountering error in P1 = 10: like SyntaxError: invalid syntax Statements must be separated by newlines or semicolons Expected expression and error in cv2.imwrite(‘RGB_image.jpg’,rgb_image)like Expected expression. I have ...
count the numbers of Objects of fruits apple, guava, orange, gooseberry, lemon, tomato
I am encountering error in P1 = 10: like SyntaxError: invalid syntax Statements must be separated by newlines or semicolons Expected expression and error in cv2.imwrite(‘RGB_image.jpg’,rgb_image)like Expected expression. I have my own dataset like apple 1sample 2samples till 6samples. import numpy as np import imutils ...
[ "you can't use a semicolon after the assignment p1 = 10, if you'd like to write a comment about the assignment, use the # sign as you did in other lines.\np1 = 10 # size of pixels to compute weights of the image\np2 = 10 # to compute the weighted average\np3 = 7 # filter strength for luminescence\np4 = 15 # filter...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074476520_python.txt
Q: Xpath - obtener solo valores I am trying to extract some data with seleneitor, and I have doubts when I extract the text to transform it into DF. I show an example: texto_columnas = driver.find_element(By.XPATH,'/html/body/div[5]/div[1]/div[4]/div/section[4]/section/div[1]/ul') texto_columnas = texto_columnas.tex...
Xpath - obtener solo valores
I am trying to extract some data with seleneitor, and I have doubts when I extract the text to transform it into DF. I show an example: texto_columnas = driver.find_element(By.XPATH,'/html/body/div[5]/div[1]/div[4]/div/section[4]/section/div[1]/ul') texto_columnas = texto_columnas.text print(texto_columnas) if i run...
[ "Now you can slice and get the values or remove the itens what you want.\ntoday = texto_columnas[0:7] # or texto_columnas[6:7] if you want only the field\ntomorrow= texto_columnas[36:48] # or texto_columnas[47:48] if you want only the field\n\nIf you want all in the same text, you can concatenate:\ntoday_and_tomorr...
[ 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074476388_python_web_scraping.txt
Q: Replacing and inserting characters in a dateset python I have this data set that contains asymmetry between the left and right leg. I would like to display the data as a graph and my thought process is that convert the left leg data('L') to negative values, e.g. -3.1, and the right leg data to positive values. I c...
Replacing and inserting characters in a dateset python
I have this data set that contains asymmetry between the left and right leg. I would like to display the data as a graph and my thought process is that convert the left leg data('L') to negative values, e.g. -3.1, and the right leg data to positive values. I can't quite figure it out, so far I got: df_selection['Asymme...
[ "I would split your single array into two arrays of left and right. If you want to make the left's negative you can still do that using this methods and just negate the numbers.\nfd = ['1.3 R', '3.4l','2.5 R', ' 3.1L']\nright = [float(each.upper().replace('R','').strip()) for each in fd if 'R' in each.upper()]\nlef...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074476270_python.txt
Q: Python Class in function I have really annoying issue with python. I would like to do some instruction in function, code work without function but it does nothing in function. As below: Could anyone help? It doesnt work: def total(): obiekt = Preference2('202211', 'DAYS') obiekt.dates() obiekt.pipelin...
Python Class in function
I have really annoying issue with python. I would like to do some instruction in function, code work without function but it does nothing in function. As below: Could anyone help? It doesnt work: def total(): obiekt = Preference2('202211', 'DAYS') obiekt.dates() obiekt.pipeline() print(vars(obiekt)) ...
[ "#Just call the function after it is created\ndef fun():\n obiekt = Preference2(\"202211\",\"DAYS\")\n obiekt.dates()\n obiekt.pipeline()\n print(vars(obiekt))\n\nfun()\n\n" ]
[ 0 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0074476529_class_function_python.txt
Q: Why does my python function remember a "set" variable? I am trying to run a recursive program that takes an element and iterates over similar elements contained in it but never repeating. I want to keep track of the checked elements with a set type object and I want to repeat the process as many times as I want. T...
Why does my python function remember a "set" variable?
I am trying to run a recursive program that takes an element and iterates over similar elements contained in it but never repeating. I want to keep track of the checked elements with a set type object and I want to repeat the process as many times as I want. This is my code def assaignPuntuation(song, assigned={"0"}): ...
[ "When you create a function, the function header is executed once at the start of your program.\nSo in your case\ndef assaignPuntuation(song, assigned={\"0\"}):\n\ncreates a function object with an initialised set for your default argument assigned.\nThat is why every subsequent call of assaignPuntuation gets the i...
[ 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074476583_function_python.txt
Q: Python No module name 'PhotoScan' I'm trying to run the code from this webpage. It says that No module name 'PhotoScan'. I try to pip install PhotoScan but couldn't find it. How can I install it? A: The PhotoScan module is available to Python code running in PhotoScan Pro, not to other Python installations. The ...
Python No module name 'PhotoScan'
I'm trying to run the code from this webpage. It says that No module name 'PhotoScan'. I try to pip install PhotoScan but couldn't find it. How can I install it?
[ "The PhotoScan module is available to Python code running in PhotoScan Pro, not to other Python installations. The module interfaces with the PhotoScan Pro internals\nAlso see the PhotoScan Pro Python reference documentation (PDF).\nAs such, it is not something you can install outside of PhotoScan Pro. Note that th...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0025106483_python.txt
Q: how to generate a rolling mean grouped by columns in pandas I'm trying to generate a rolling 2 average of col3 grouped by col2. What I'm struggling with is populating the NaN values to take the previously calculated rolling mean. DataFrame: df = pd.read_csv(StringIO("""col1,col2,col3 0,A,1 0,A,2 0,B,3 0,B,4 1,A,5 ...
how to generate a rolling mean grouped by columns in pandas
I'm trying to generate a rolling 2 average of col3 grouped by col2. What I'm struggling with is populating the NaN values to take the previously calculated rolling mean. DataFrame: df = pd.read_csv(StringIO("""col1,col2,col3 0,A,1 0,A,2 0,B,3 0,B,4 1,A,5 1,A,6 1,B,7 1,B,8 2,A,9 2,A,10 2,B,11 2,B,12 3,A 3,A 3,B 3,B 4,A ...
[ "You can try this:\nimport pandas as pd\nfrom functools import reduce\n\ndef my_fun(d):\n return reduce(lambda x, _: x.fillna(x.rolling(2, min_periods=2).mean().shift()), range(d['col3'].isna().sum()), d)\n\ndf = df.groupby('col2').apply(my_fun)\ndf\n\n col1 col2 col3\n0 0 A 1.0000\n1 0 ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074475836_pandas_python.txt
Q: Shapes3d from Tensorflow not allowing test in split I copied this part of the code straight from tensorflow's example, but it's not allowing the split. Does anyone know why? I've tried many different split options, but I just keep getting this error every time I put test in. A: The shapes3d dataset only contain...
Shapes3d from Tensorflow not allowing test in split
I copied this part of the code straight from tensorflow's example, but it's not allowing the split. Does anyone know why? I've tried many different split options, but I just keep getting this error every time I put test in.
[ "The shapes3d dataset only contains one split, which is train. You are passing \"test\" as a split element hence raising the error. It also does not support supervised structures. Please try as follows\ntrain_data,test_data,valid_data = tfds.load(\"shapes3d\",split=[\"train[20%:80%]\",\"train[:20%]\",\"train[80%:]\...
[ 0 ]
[]
[]
[ "jupyter_notebook", "python", "tensorflow", "tensorflow_datasets" ]
stackoverflow_0074332319_jupyter_notebook_python_tensorflow_tensorflow_datasets.txt
Q: Why is the get_attribute() function in selenium returning an empty string when inspecting the webpage shows the attribute? I am trying to grab the src attribute from the video tag from this webpage. This shows where I see the video tag when I am inspecting the image. The XPath for the tag in safari is "//*[@id="pl...
Why is the get_attribute() function in selenium returning an empty string when inspecting the webpage shows the attribute?
I am trying to grab the src attribute from the video tag from this webpage. This shows where I see the video tag when I am inspecting the image. The XPath for the tag in safari is "//*[@id="player"]/div[2]/div[4]/video" This is my code: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.com...
[ "You can get a link to m3u8 file in Chrome from logs using Desired Capabilities\nHere is one of the possible solutions to do this:\nimport json\nfrom selenium import webdriver\nfrom selenium.webdriver import DesiredCapabilities\nfrom selenium.webdriver.chrome.service import Service\n\n\noptions = webdriver.ChromeOp...
[ 0 ]
[]
[]
[ "python", "safari", "selenium", "web_scraping" ]
stackoverflow_0074472216_python_safari_selenium_web_scraping.txt
Q: How to filter dataframe based on values in pyspark/python? I have a dataframe like below. I want to read the dataframe and filter the records based on start time and store in different dataframes. INPUT DF name start_time AA 2022-11-16 AAA 2022-11-15 BBB 2022-11-14 For eg: I need to store ...
How to filter dataframe based on values in pyspark/python?
I have a dataframe like below. I want to read the dataframe and filter the records based on start time and store in different dataframes. INPUT DF name start_time AA 2022-11-16 AAA 2022-11-15 BBB 2022-11-14 For eg: I need to store each record based on start time, which means all, 16 th date sta...
[ "Well, technially a duplicate but idk how to report that but I think this works :\ndf = pd.DataFrame({\"name\" : [\"AA\", \"AAA\", \"BBB\"], \n\"start_time\" : [\"2022-11-16\",\" 2022-11-15\", \"2022-11-14\"]})\n\ndfs = dict(tuple(df.groupby('start_time')))\n\ndfs\n\nyou can select each DataFrame by the start time ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "pyspark", "python", "python_3.x" ]
stackoverflow_0074475890_dataframe_pandas_pyspark_python_python_3.x.txt
Q: Convert extremly nested JSON to CSV using python I'm having trouble converting below JSON to csv esepcially the details.kpis results section as it's quite nested. I'm trying to use pandas and the JSON_Normalize function but even if I give the correct record path and meta it's not helping. Below is the JSON, and I ...
Convert extremly nested JSON to CSV using python
I'm having trouble converting below JSON to csv esepcially the details.kpis results section as it's quite nested. I'm trying to use pandas and the JSON_Normalize function but even if I give the correct record path and meta it's not helping. Below is the JSON, and I suggest pasting it into http://jsonviewer.stack.hu/ to...
[ "You need to replace following in your json :\n\nfalse with False/\"false\"\nnull with None\n\nAfter this just run the json_normalize() function , it should work.\nI am able to make it run.\n" ]
[ 0 ]
[]
[]
[ "csv", "json", "pandas", "python" ]
stackoverflow_0074476534_csv_json_pandas_python.txt
Q: Is there a way to change True to False in python? I would like to change so True = False or more exact change so True = 0 and False = 1 is there a way to do this? I have a dataframe and would like to df.groupby('country',as_index=False).sum() and see how many False values there is in each country I have tried df['...
Is there a way to change True to False in python?
I would like to change so True = False or more exact change so True = 0 and False = 1 is there a way to do this? I have a dataframe and would like to df.groupby('country',as_index=False).sum() and see how many False values there is in each country I have tried df['allowed'] = --df['allowed'] (allowed is the column with...
[ "Swapping booleans is easy with df[\"neg_allowed\"] = ~df['allowed']\n", "# we can use map method to change values directly \n\ndf['allowed'] = df['allowed'].map({True: 0, False: 1})\n\n#Before: allowed ---> #After: allowed\n True 0\n False ...
[ 0, 0, 0 ]
[]
[]
[ "boolean", "pandas", "python" ]
stackoverflow_0074476574_boolean_pandas_python.txt
Q: shape '[58, 2048, -1]' is invalid for input of size 534528 I'm new to PyTorch. I found a sample code of the capsule network on mnist, I changed it to use my own dataset, but it gives me a runtime error Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_3248\67117472.py in <module> 176 tra...
shape '[58, 2048, -1]' is invalid for input of size 534528
I'm new to PyTorch. I found a sample code of the capsule network on mnist, I changed it to use my own dataset, but it gives me a runtime error Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_3248\67117472.py in <module> 176 train(capsule_net, optimizer,mnist.train_loader, e) 177 ...
[ "You are trying to reshape your tensor in your forward method of your PrimaryCaps class. However, you are trying to reshape it as [58, 2048, -1] but you have a size of 534528. 534528 is not a multiple of 58*2048. My guess is that the value of your self.num_routes is supposed to be of 32 * 6 * 6, but somewhere in y...
[ 0 ]
[]
[]
[ "deep_learning", "machine_learning", "python", "pytorch" ]
stackoverflow_0074472573_deep_learning_machine_learning_python_pytorch.txt
Q: how to check if button is clicked on tkinter I am trying to create a car configurator using tkinter as a gui in my free time. I have managed to open a tkinter box with images that act as buttons. What I want to do is for the user to click on a button. I want to check which button has been clicked (i.e if the fami...
how to check if button is clicked on tkinter
I am trying to create a car configurator using tkinter as a gui in my free time. I have managed to open a tkinter box with images that act as buttons. What I want to do is for the user to click on a button. I want to check which button has been clicked (i.e if the family car button is clicked, how can I check that it ...
[ "Use a Boolean flag.\nDefine isClicked as False near the beginning of your code, and then set isClicked as True in your create_window() function.\nThis way, other functions and variables in your code can see whether the button's been clicked (if isClicked).\n", "Not sure what you asked, do you want to disable it ...
[ 1, 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0051766129_python_tkinter.txt
Q: Remove number of lines from string in python for example below is the string news="Waukesha trial: US man sentenced to life for car-ramming attack - BBC NewsBBC HomepageSkip to contentAccessibility HelpYour accountHomeNewsSportReelWorklifeTravelFutureMore menuMore menuSearch BBCHomeNewsSportReelWorklifeTravelFutur...
Remove number of lines from string in python
for example below is the string news="Waukesha trial: US man sentenced to life for car-ramming attack - BBC NewsBBC HomepageSkip to contentAccessibility HelpYour accountHomeNewsSportReelWorklifeTravelFutureMore menuMore menuSearch BBCHomeNewsSportReelWorklifeTravelFutureCultureMusicTVWeatherSoundsClose menuBBC NewsMenu...
[ "First, you need to escape double quotes, your string is not valid like this.\nSecond, are you sure the words ending with \"-\" mean the end of a sentence? In your example you would split \"car-ramming\" and \"four-week\". Anyway, you can split the string into sentences like this:\nsentences = news.replace('-','.')...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074476357_python_python_3.x.txt
Q: Python k8s client: is there a way to use wildcards on job-name query, when calling list_namespaced_pod? Getting all pods in a given namespace takes too long, so I'm trying somehow to reduce it. I don't know whether using such filtration may be faster or not, but I at least must try - if it's at all possible... Tri...
Python k8s client: is there a way to use wildcards on job-name query, when calling list_namespaced_pod?
Getting all pods in a given namespace takes too long, so I'm trying somehow to reduce it. I don't know whether using such filtration may be faster or not, but I at least must try - if it's at all possible... Tried stuff like: label_selector='job-name=my-agent-*' or label_selector='job-name=my-agent-%' and many other va...
[ "The use of wildcards is not documented. But, since you can pass a series of label_selectors, does the following approach work out for you?\n# Example. Acquire job and agent names per your project requirements\nselectors = [(\"job-name-1\",\"my-agent-a\"),(\"job-name-2\",\"my-agent-b\")]\n\n# Job and agent names as...
[ 0 ]
[]
[]
[ "client", "kubectl", "kubernetes", "python" ]
stackoverflow_0074395159_client_kubectl_kubernetes_python.txt
Q: Dividing one dataframe by another in python using pandas with float values I have two separate data frames named df1 and df2 as shown below: Scaffold Position Ref_Allele_Count Alt_Allele_Count Coverage_Depth Alt_Allele_Frequency 0 1 11 7 51 58 ...
Dividing one dataframe by another in python using pandas with float values
I have two separate data frames named df1 and df2 as shown below: Scaffold Position Ref_Allele_Count Alt_Allele_Count Coverage_Depth Alt_Allele_Frequency 0 1 11 7 51 58 0.879310 1 1 16 20 95 ...
[ "This can be fixed by only using once set of brackets '[]' while referring to a column in a pandas df, rather than 2.\nimport csv\nimport pandas as pd\nimport numpy as np\n\ndf1 = pd.read_csv('C:/Users/Tom/Python_CW/file_pairA_1.csv')\ndf2 = pd.read_csv('C:/Users/Tom/Python_CW/file_pairA_2.csv')\nprint(df1)\nprint(...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074476652_dataframe_pandas_python_python_3.x.txt
Q: TypeError: 'type' object is not subscriptable when indexing in to a dictionary I have multiple files that I need to load so I'm using a dict to shorten things. When I run I get a TypeError: 'type' object is not subscriptable Error. How can I get this to work? m1 = pygame.image.load(dict[1]) m2 = pygame.image.lo...
TypeError: 'type' object is not subscriptable when indexing in to a dictionary
I have multiple files that I need to load so I'm using a dict to shorten things. When I run I get a TypeError: 'type' object is not subscriptable Error. How can I get this to work? m1 = pygame.image.load(dict[1]) m2 = pygame.image.load(dict[2]) m3 = pygame.image.load(dict[3]) dict = {1: "walk1.png", 2: "walk2.png", ...
[ "Normally Python throws NameError if the variable is not defined:\n>>> d[0]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'd' is not defined\n\nHowever, you've managed to stumble upon a name that already exists in Python.\nBecause dict is the name of a built-in type i...
[ 72, 37, 0 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0026920955_dictionary_python_python_3.x.txt
Q: Visual Studio Code syntax highlighting not working I am using Visual Studio Code (VSC) as my IDE. My computer just updated to Catalina 10.15.2 (19C57) and since the update, now VSC is not highlighting syntax errors. The extensions I have seem to be working and it recognizes my miniconda python environment. Is ther...
Visual Studio Code syntax highlighting not working
I am using Visual Studio Code (VSC) as my IDE. My computer just updated to Catalina 10.15.2 (19C57) and since the update, now VSC is not highlighting syntax errors. The extensions I have seem to be working and it recognizes my miniconda python environment. Is there a solution for this yet? I was avoiding Catalina as I ...
[ "I also had the same problem for typescript react files. Tried many things and nothing worked. Finally I checked the extensions I've installed for typescript react. Disabling JavaScript and TypeScript Nightly extension worked for me\n", "In my case, the Catalina installation didn't remove my Python installation.\...
[ 9, 2, 2, 0, 0 ]
[]
[]
[ "macos_catalina", "python", "syntax_highlighting", "visual_studio_code" ]
stackoverflow_0059775038_macos_catalina_python_syntax_highlighting_visual_studio_code.txt
Q: How to transform payload data after it comes in using Pydantic I have a payload that comes in which has two parameters. One of the parameters is a long string which contains more parameters. Something like this param1%param2%param3. I am using FastAPI and Pydantic BaseModel to get that data and validate it, howeve...
How to transform payload data after it comes in using Pydantic
I have a payload that comes in which has two parameters. One of the parameters is a long string which contains more parameters. Something like this param1%param2%param3. I am using FastAPI and Pydantic BaseModel to get that data and validate it, however since I am using it in other places I also want to transform it an...
[ "If this payload structure is specific to this route it's a good idea to transform it directly in your route def.\nThe structure you gave for NewPayload will not work if the number of param isn't always the same.\nexample 1:\nfrom typing import List\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\n...
[ 0 ]
[]
[]
[ "fastapi", "pydantic", "python" ]
stackoverflow_0074452086_fastapi_pydantic_python.txt
Q: Any depth nested dict to pandas dataframe I've been fighting to go from a nested dictionary of depth D to a pandas DataFrame. I've tried with recursive function, like the following one, but my problem is that when I'm iterating over a KEY, I don't know what was the pervious key. I've also tried with json.normalize...
Any depth nested dict to pandas dataframe
I've been fighting to go from a nested dictionary of depth D to a pandas DataFrame. I've tried with recursive function, like the following one, but my problem is that when I'm iterating over a KEY, I don't know what was the pervious key. I've also tried with json.normalize, pandas from dict but I always end up with dot...
[ "I'm not sure how that data going to be consistent but for just understanding we can do something like the below, remember this is just a little demo on the approach of how we can handle it, you can spend more time to polish it up accordingly:\nI added comments on each step for better understanding.\nimport pandas ...
[ 1, 1 ]
[]
[]
[ "dictionary", "json", "nested", "pandas", "python" ]
stackoverflow_0074475332_dictionary_json_nested_pandas_python.txt
Q: Python PIL/Image generate grid of images of different width/height I came across the following example: from PIL import Image def image_grid(imgs, rows, cols): assert len(imgs) == rows*cols w, h = imgs[0].size grid = Image.new('RGB', size=(cols*w, rows*h)) grid_w, grid_h = grid.size for ...
Python PIL/Image generate grid of images of different width/height
I came across the following example: from PIL import Image def image_grid(imgs, rows, cols): assert len(imgs) == rows*cols w, h = imgs[0].size grid = Image.new('RGB', size=(cols*w, rows*h)) grid_w, grid_h = grid.size for i, img in enumerate(imgs): grid.paste(img, box=(i%cols*w, i//col...
[ "I was able to solve it in the following way:\nFirst, we iterate all images and gather the max dimensions for each column and row.\nsize = 3\nmaxWidth = {}\nmaxHeight = {}\n\nfor i, img in enumerate(imgs):\n col = i%size\n row = i//size\n\n if col not in maxWidth:\n maxWidth[col] = 0\n\n if row n...
[ 0 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0074454460_image_python_python_imaging_library.txt
Q: I need help making calculations from entry I am very new to python and quite interested in learning it. Tried googling an answer for this but couldn't find one. I'm doing a project for myself to get the price of the fuel costs (daily, monthly and yearly costs). Fuel consumption (liter/100km) / 100 * kilometers dri...
I need help making calculations from entry
I am very new to python and quite interested in learning it. Tried googling an answer for this but couldn't find one. I'm doing a project for myself to get the price of the fuel costs (daily, monthly and yearly costs). Fuel consumption (liter/100km) / 100 * kilometers driven (per day) * fuel cost (per liter) I am tryin...
[ "you can use a variable that will be connected to your entries:\nIn the example, the code prints to the screen the values taken from the entry.\nimport tkinter as tk\n\n\ndef func(*args):\n # *args allows passing a variable number of non-keyword arguments to the \n # function \n label1.configure(text=var.g...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074467285_python_tkinter.txt
Q: Find keyword from a list in a page using BeautifulSoup Using Beautiful Soup, I'd like to detect porn keywords (that i get by concatening two lists of porn-keywords (one in french, the other in english) in a web page. Here's my code (from BeautifulSoup find two different strings): proxy_support = urllib.request.Pro...
Find keyword from a list in a page using BeautifulSoup
Using Beautiful Soup, I'd like to detect porn keywords (that i get by concatening two lists of porn-keywords (one in french, the other in english) in a web page. Here's my code (from BeautifulSoup find two different strings): proxy_support = urllib.request.ProxyHandler(my_proxies) opener = urllib.request.build_opener(p...
[ "I replaced your lambda function with\ndef testfn(text):\n elms = list([x for x in lst_porn_keyword if x in text])\n if len(elms) > 0:\n print(f\"found words {elms} in {text}\")\n return len(elms)>0\n\ncalling soup.find_all(text=testfn) will result in the following output:\nfound words ['color', 'gi...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074476605_beautifulsoup_python_web_scraping.txt
Q: Try-except with NameError and TypeError Can you please help me with the following. I am trying to catch two exceptions: 1) TypeError and 2)NameError. I use the following code below that estimates the average: def calculate_average(number_list): try: if type(number_list) is not list: raise V...
Try-except with NameError and TypeError
Can you please help me with the following. I am trying to catch two exceptions: 1) TypeError and 2)NameError. I use the following code below that estimates the average: def calculate_average(number_list): try: if type(number_list) is not list: raise ValueError("You should pass list to this funct...
[ "In spyder, if you look in the trail of recent tracebacks, the error is raised by site-package ...lib\\site-packages\\spyder_kernels\\py3compat.py\", line 356, in compat_exec(code, globals, locals) , as NameError: name 'a' is not defined since it searches for a variable declaration of a in the script (which is abse...
[ 0, 0 ]
[]
[]
[ "error_handling", "python", "try_except" ]
stackoverflow_0074476772_error_handling_python_try_except.txt