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: Initialize frozen dataclass attribute with function I am working with frozen dataclasses in Python. My goal is to create a dataclass with its frozen attributes. However, one of the attributes is a function of the other ones. I want my class to be frozen (once it has been instantiated it can't be changed), but I ca...
Initialize frozen dataclass attribute with function
I am working with frozen dataclasses in Python. My goal is to create a dataclass with its frozen attributes. However, one of the attributes is a function of the other ones. I want my class to be frozen (once it has been instantiated it can't be changed), but I can't find a way to specify the value of an attribute insid...
[ "Make price a property, wich are read only if you don't create a setter:\n@property\ndef price(self):\n\n if self.color == 'red':\n color_surplus = 10\n else:\n color_surplus = 0\n\n if self.size > 10:\n size_surplus = 10\n else:\n size_surplus = 5\n if self.model == 'mustang...
[ 3 ]
[]
[]
[ "attributes", "immutability", "object", "python", "python_dataclasses" ]
stackoverflow_0069827887_attributes_immutability_object_python_python_dataclasses.txt
Q: How to update AWS Cloudwatch Canary zip file I created a an AWS Cloudwatch Canary through the Import from S3 option, because I had a packaged python script and directory. That went well, and works as expected. However, I cannot find how to update the script package for the existing Canary. There has to be an eas...
How to update AWS Cloudwatch Canary zip file
I created a an AWS Cloudwatch Canary through the Import from S3 option, because I had a packaged python script and directory. That went well, and works as expected. However, I cannot find how to update the script package for the existing Canary. There has to be an easier way than creating a new canary every time I up...
[ "I still don't see a way to do this in the UI, but I am able to do it from the command line. I now package up my scripts (zip), then update the zip in s3 (aws s3 cp s3://path/python.zip) and then\naws synthetics update-canary --name test-canary --code '{\"S3Bucket\": \"path\", \"S3Key\":\"python.zip\", \"Handler\"...
[ 0 ]
[]
[]
[ "amazon_cloudwatch", "python" ]
stackoverflow_0074224725_amazon_cloudwatch_python.txt
Q: Map plot in Plotly Suppose i have the following dataframe in python : Country Value Arizona 10 Los Angeles 20 Alaska 6 Huawai NA First i want to bucket the values based on a range for example every 5, 0-5,5-10.. I want to make a map plot with plotly that has a discerte legend (the Bucket) and the color to be...
Map plot in Plotly
Suppose i have the following dataframe in python : Country Value Arizona 10 Los Angeles 20 Alaska 6 Huawai NA First i want to bucket the values based on a range for example every 5, 0-5,5-10.. I want to make a map plot with plotly that has a discerte legend (the Bucket) and the color to be as the Valu...
[ "Regarding your bucket column, you could more easily do this:\ndf['bucket'] = pd.cut(df['GDP'], [0, 5, 10, 15, 20, 25], labels=['<5', '5-10', '10-15', '15-20', '20-25'])\n\nHowever, if you wanted to keep a colorscale you would have to use a numeric value rather than a string (as now is in the bucket column). Instea...
[ 0 ]
[]
[]
[ "choropleth", "plotly", "plotly_python", "python" ]
stackoverflow_0074218237_choropleth_plotly_plotly_python_python.txt
Q: How to use a none delimiter with csv.writer? I'm creating a discord bot in python and I want to have a log system for the warn command. To set up this, I'm using a .csv file in which I write all the information I want about a user. It's the first time I use .csv, so to manipulate the data, I take the content of th...
How to use a none delimiter with csv.writer?
I'm creating a discord bot in python and I want to have a log system for the warn command. To set up this, I'm using a .csv file in which I write all the information I want about a user. It's the first time I use .csv, so to manipulate the data, I take the content of the file and convert it into a list of list. One sub...
[ "The writerow() function expects an iterable object to write a whole row.\ncsvwriter.writerow(\"abc\")\n\nwill write to the file:\na;b;c\n\nand\ncsvwriter.writerow([\"abc\", \"def\"])\n\nwill write:\nabc;def\n\nIf line is a list of strings then line = \";\".join(line) is wrong, line should go directly to writerow()...
[ 1 ]
[]
[]
[ "csv", "csvwriter", "delimiter", "python", "writer" ]
stackoverflow_0074238615_csv_csvwriter_delimiter_python_writer.txt
Q: Updating and editing lists in python pandas I have a data table that looks like this: I want to update each list and to show the lineup at the time of the substitution and remove/add a player if they come in/out of the game. I would like to save each edit in the vlineup/hlineup column and then remove/add based o...
Updating and editing lists in python pandas
I have a data table that looks like this: I want to update each list and to show the lineup at the time of the substitution and remove/add a player if they come in/out of the game. I would like to save each edit in the vlineup/hlineup column and then remove/add based on the value in the cell from the above row. My t...
[ "I don't know if this is what you're trying to do, since I don't have the data to check.\nBut try this:\nfor i in range (1, len(subs)):\n if subs['team'][i] == home: \n if subs['type'][i-1] == 'OUT':\n subs['hlineup'][i].remove(subs['checkname'][i-1]) \n elif subs['type'][...
[ 0 ]
[]
[]
[ "for_loop", "if_statement", "list", "pandas", "python" ]
stackoverflow_0074238718_for_loop_if_statement_list_pandas_python.txt
Q: Extracting values of a pandas DataFrame using maximal indexes from another DataFrame I have two pandas dataframes: df1 = pd.DataFrame({ 'a': [1, 2, 3], 'b': [2, 4, 2], 'c': [3, 1, 5], 'd': [-1, 0, 1] }, index=('A', 'B', 'C')) df2 = pd.DataFrame({ 'a': [0, 5, 10], 'b': [9, 5, 1], 'c': [3, 4, 2], 'd': [12, 3...
Extracting values of a pandas DataFrame using maximal indexes from another DataFrame
I have two pandas dataframes: df1 = pd.DataFrame({ 'a': [1, 2, 3], 'b': [2, 4, 2], 'c': [3, 1, 5], 'd': [-1, 0, 1] }, index=('A', 'B', 'C')) df2 = pd.DataFrame({ 'a': [0, 5, 10], 'b': [9, 5, 1], 'c': [3, 4, 2], 'd': [12, 3, 0] }, index=('A', 'B', 'C')) >>> print(df1) a b c d A 1 2 3 -1 B 2 4 1 0 C...
[ "Try this:\ns = df2.idxmax()\n[df1.loc[row, col] for col, row in s.items()]\n\n", "If you want a vectorial solution (not a loop), you can use numpy:\nimport numpy as np\n\na = df1.to_numpy()[np.argmax(df2.to_numpy(), axis=0),\n np.arange(df1.shape[1])]\n# array([ 3, 2, 1, -1])\n\n# as Series\n...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074238454_dataframe_pandas_python.txt
Q: Check if string coordinates represent a polygon using Pandas Using Pandas, how to check if a valid polygon geometry can be created using coordinates from a string? Input example: import pandas as pd coord_series = pd.Series([ '-33, 50, -30, 38, -40, 27, -33.0, 50.5', '-xx, xx, -xx, xx, -xx, xx, -xxxx, xxxx...
Check if string coordinates represent a polygon using Pandas
Using Pandas, how to check if a valid polygon geometry can be created using coordinates from a string? Input example: import pandas as pd coord_series = pd.Series([ '-33, 50, -30, 38, -40, 27, -33.0, 50.5', '-xx, xx, -xx, xx, -xx, xx, -xxxx, xxxx', None, '-10', '-10, 20, -30, 40, -50, 60, -70', ...
[ "The below code looks like a lot, but I couldn't create a shorter solution. shapely.geometry.Polygon.is_valid seems needed to do the assessment, but it's not enough, as sometimes it throws an error.\nfrom shapely.geometry import Polygon\n\ndef validate_polygon(s: pd.Series) -> pd.Series:\n def is_digit(lst):\n ...
[ 0, 0 ]
[]
[]
[ "geometry", "pandas", "polygon", "python", "validation" ]
stackoverflow_0074219569_geometry_pandas_polygon_python_validation.txt
Q: Vieux garcon game - Problem with execution how would I solve this problem? The program is supposed to remove all pairs from your hand at the beginning but it is not working. This is what it outputs at the moment: Hello. I am Robot and I distribute the cards. Your hand is: 2♠ 5♡ Q♠ Q♡ 4♡ J♢ 2♣ J♠ K♢ 8♢ 10♠ A♣ 5♣ 3♣...
Vieux garcon game - Problem with execution
how would I solve this problem? The program is supposed to remove all pairs from your hand at the beginning but it is not working. This is what it outputs at the moment: Hello. I am Robot and I distribute the cards. Your hand is: 2♠ 5♡ Q♠ Q♡ 4♡ J♢ 2♣ J♠ K♢ 8♢ 10♠ A♣ 5♣ 3♣ 6♣ 4♢ 7♣ 9♢ 2♢ J♡ A♢ 8♠ 10♣ 6♢ 10♡ Don't worry...
[ "I found my error.\n for crt in l:\n if crt[1] + crt[0] == '10':\n nbr = '10'\n\nI flipped the positions of the 1 and 0. it was checking for 01 and not 10. It was supposed to be:\n for crt in l:\n if crt[0] + crt[1] == '10':\n nbr = '10'\n\nSorry for the inconvience.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074229758_python.txt
Q: Python class membership and absolute paths I'm working on a project where the source code is nested in the following structure: |-- my-project |-- test_notebook.ipynb |-- package |-- src | |-- module1.py #defines MyClass | |-- module2.py #defines MyOtherClass | ...
Python class membership and absolute paths
I'm working on a project where the source code is nested in the following structure: |-- my-project |-- test_notebook.ipynb |-- package |-- src | |-- module1.py #defines MyClass | |-- module2.py #defines MyOtherClass | |-- some_other_modules.py | |-- __...
[ "Having posted your sys.path and import the problem is clear. Your sys.path, after the '' (which has special meaning that's not relevant here) begins with:\n'/Users/my_name/Documents/Python_Projects/my-project/package'\n\nand does not at any point contain:\n'/Users/my_name/Documents/Python_Projects/my-project'\n\nT...
[ 0 ]
[]
[]
[ "absolute_path", "class_members", "python", "python_3.x" ]
stackoverflow_0074201930_absolute_path_class_members_python_python_3.x.txt
Q: Import all functions from all submodules of a module I have the following folder structure of python modules: allFunctions ├─ import_all.py ├─ __init__.py ├─ funcSetA ├─ __init__.py │ ├─ funcA1.py │ └─ funcA2.py └─ funcSetB ├─ __init__.py ├─ funcB1.py ├─ func...
Import all functions from all submodules of a module
I have the following folder structure of python modules: allFunctions ├─ import_all.py ├─ __init__.py ├─ funcSetA ├─ __init__.py │ ├─ funcA1.py │ └─ funcA2.py └─ funcSetB ├─ __init__.py ├─ funcB1.py ├─ funcB2.py └─ funcB3.py I want to import all the funct...
[ "Many stack overflow pages later I compiled an answer. I absolutely cannot recommend anyone does this, I had very specific reasons for doing things this way - but it does work. This code goes in the top level __init__.py (it might be possible to make a loader script like I originally wanted, I stopped trying. All _...
[ 0 ]
[]
[]
[ "import", "python", "python_3.x" ]
stackoverflow_0074235377_import_python_python_3.x.txt
Q: Using Abseil vs. Directly calling main()? I've been using the vanilla def main(): # Do stuff if __name__ == '__main__': main() but recently saw people doing from absl import app def main(_): # Do things if __name__ == '__main__': app.run(main) Abseil provides flags.FLAGS, but I've been using A...
Using Abseil vs. Directly calling main()?
I've been using the vanilla def main(): # Do stuff if __name__ == '__main__': main() but recently saw people doing from absl import app def main(_): # Do things if __name__ == '__main__': app.run(main) Abseil provides flags.FLAGS, but I've been using ArgumentParser, which works perfectly fine, so ...
[ "Consider a design pattern, where you are passing a json file (that contains say site-specific constants) at the cmd line as input to your Python script. Say,the json file contains immutable constants and you want to maintain it that way.\nYou want the constants from json file contents to be made available to all t...
[ 1 ]
[]
[]
[ "abseil", "absl_py", "python" ]
stackoverflow_0063184690_abseil_absl_py_python.txt
Q: Unable to authenticate Client in test Python 3.10.7, Django 4.1.1, Django REST Framework 3.13.1 I am unable to get the django.test.Client login or force_login methods to work in a django.test.TestCase-derived test class. I'm referring to https://docs.djangoproject.com/en/4.1/topics/testing/tools/ My project seems ...
Unable to authenticate Client in test
Python 3.10.7, Django 4.1.1, Django REST Framework 3.13.1 I am unable to get the django.test.Client login or force_login methods to work in a django.test.TestCase-derived test class. I'm referring to https://docs.djangoproject.com/en/4.1/topics/testing/tools/ My project seems to work when viewing it in a browser. Unaut...
[ "I've been doing a bunch of tests recently and here's how are all of mine create the user inside of the setup, like the block below, give that a shot.\nclass AddressesViewTest(TestCase):\n def setUp(self):\n self.username = \"jrandomuser\"\n self.password = \"qwerty123\"\n user = User.object...
[ 1, 0 ]
[]
[]
[ "django", "django_tests", "python" ]
stackoverflow_0074238340_django_django_tests_python.txt
Q: proxy max retries exceeded with url am following a tutorial on Youtube where we learn SQL injection on portswigger platform and we write the exploit as script with python, am using kali linux as virtual machine, am suffering from proxy error and i didn't know what to search for other than stackoverflow with no ben...
proxy max retries exceeded with url
am following a tutorial on Youtube where we learn SQL injection on portswigger platform and we write the exploit as script with python, am using kali linux as virtual machine, am suffering from proxy error and i didn't know what to search for other than stackoverflow with no benefit answers. now here is my python code ...
[ "am answering my question after few searches after few days\nfirst I debugged that my proxy didn't receive my requests from python\nI searched and found this tutorial https://www.th3r3p0.com/random/python-requests-and-burp-suite.html to set linux environmental variables\nand I edited my code to\nproxies = {'http': ...
[ 1, 0 ]
[]
[]
[ "proxy", "python", "python_3.x", "urllib3" ]
stackoverflow_0074186169_proxy_python_python_3.x_urllib3.txt
Q: Why will threading with Qt 5.12 successfully update a QLabel in one function but will crash in another similar function? Currently writing a GUI application that launches from and interfaces with The Foundry's Nuke, a visual effects compositing software (although this is not the issue AFAIK, since it's repeatable ...
Why will threading with Qt 5.12 successfully update a QLabel in one function but will crash in another similar function?
Currently writing a GUI application that launches from and interfaces with The Foundry's Nuke, a visual effects compositing software (although this is not the issue AFAIK, since it's repeatable inside an IDE). I am attempting to figure out why running one native Python thread in my Pyside2 GUI is crashing when calling ...
[ "ANY update to QT GUI in python from any thread except the main thread is an unidentified behavior, it will most likely lead to segmentation fault, but in some cases it may not do it on that line, it may do it on a totally different line and you'll be left scratching your head for days, why it crashes here and not ...
[ 1 ]
[]
[]
[ "multithreading", "python", "python_3.7", "qt5", "qt5.12" ]
stackoverflow_0074238920_multithreading_python_python_3.7_qt5_qt5.12.txt
Q: How to remove specific elements in a numpy array (passing a list of values not indexes) I have a 1d numpy array and a list of values to remove (not indexes), how can I modify this code so that the actual values not indexes are removed import numpy as np a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) values_to_remove =...
How to remove specific elements in a numpy array (passing a list of values not indexes)
I have a 1d numpy array and a list of values to remove (not indexes), how can I modify this code so that the actual values not indexes are removed import numpy as np a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) values_to_remove = [2, 3, 6] new_a = np.delete(a, values_to_remove) So what I want to delete is the values 2,...
[ "Use this:\nimport numpy as np \n\na = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])\nvalues_to_remove = [2, 3, 6]\n\nfor i in range(0, len(values_to_remove)):\n index = np.where(a==values_to_remove[i])\n a = np.delete(a, index[0][0])\n\nprint(a)\n\nOutput:\n[1 4 5 7 8 9]\n\n", "You can use numpy.isin\nIf you ...
[ 1, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074238892_numpy_python.txt
Q: Python inside a virtualenv is broken (Django) TL;DR - Microsoft Store Apps are broken (0 bytes), hence the Python interpreter is unable to create process and run "Python" inside virtualenv, I failed to follow numerous explanations of how to change virtualenv path for Python. Recently, without any changes to my com...
Python inside a virtualenv is broken (Django)
TL;DR - Microsoft Store Apps are broken (0 bytes), hence the Python interpreter is unable to create process and run "Python" inside virtualenv, I failed to follow numerous explanations of how to change virtualenv path for Python. Recently, without any changes to my computer/environment, an issue started occurring when ...
[ "Since you have installed python from python.org, ensure that it has been properly added to the PATH and you're not inadvertently using the windows store version.\n\n\nOpen command prompt\nExecute where python to check which python your system is using.\n\n\n\nIf you're only seeing the WindowsApps version of python...
[ 0, 0 ]
[]
[]
[ "django", "python", "virtualenv" ]
stackoverflow_0074170834_django_python_virtualenv.txt
Q: Concatenate text and variables to create a path I have the following 3 variables: Year=2022 Month=09 Filename=asd And I need to create the following path: "C:\Documents\2022\09_September\asd.xlsx" How can I create that path including the backslash symbols? A: Year=2022 Month='09' Filename='asd' path = fr"C:\D...
Concatenate text and variables to create a path
I have the following 3 variables: Year=2022 Month=09 Filename=asd And I need to create the following path: "C:\Documents\2022\09_September\asd.xlsx" How can I create that path including the backslash symbols?
[ "Year=2022\nMonth='09'\nFilename='asd'\n\npath = fr\"C:\\Documents\\{Year}\\{Month}_September\\{Filename}.xlsx\"\n\n", "year=2022\nmonth=9\nfilename='asd'\n\npath = fr\"C:\\Documents\\{year}\\{month.zfill(2)}_September\\{filename}.xlsx\"\n\nEdit:\n\nformat the month in the format 08, 09, 10 instead of 8, 9, 10\na...
[ 2, 2, 1, 0 ]
[]
[]
[ "path", "python" ]
stackoverflow_0074238801_path_python.txt
Q: DASK: merge throws error when one side's key is NA whereas pd.merge works I have these sample dataframes: tdf1 = pd.DataFrame([{"id": 1, "val": 4}, {"id": 2, "val": 5}, {"id": 3, "val": 6}, {"id": pd.NA, "val": 7}, {"id": 4, "val": 8}]) tdf2 = pd.DataFrame([{"some_id": 1, "name": "Josh"}, {"some_id": 3, "name": "J...
DASK: merge throws error when one side's key is NA whereas pd.merge works
I have these sample dataframes: tdf1 = pd.DataFrame([{"id": 1, "val": 4}, {"id": 2, "val": 5}, {"id": 3, "val": 6}, {"id": pd.NA, "val": 7}, {"id": 4, "val": 8}]) tdf2 = pd.DataFrame([{"some_id": 1, "name": "Josh"}, {"some_id": 3, "name": "Jake"}]) pd.merge(tdf1, tdf2, how="left", left_on="id", right_on="some_id").hea...
[ "This expands on the comments by @Michael Delgado. The tricky thing is that int64 does not support the pd.NA. You can see that this error is raised by pandas via trying:\ntdf1['id'] = tdf1['id'].astype('int64')\n# TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NAType'\n\nOne ...
[ 1 ]
[]
[]
[ "dask", "dask_dataframe", "pandas", "pandas_merge", "python" ]
stackoverflow_0074237866_dask_dask_dataframe_pandas_pandas_merge_python.txt
Q: How to iterate over a list, modify it but avoid an error? I have two variable lenght lists extracted from an excel file. One has wagon number and the other the wagon weight, something like this: wagon_list = [1234567, 2345678, 3456789, 4567890] weight_list = [1.1, 2.2, 3.3, 4.4] Sometimes the wagon_list will have...
How to iterate over a list, modify it but avoid an error?
I have two variable lenght lists extracted from an excel file. One has wagon number and the other the wagon weight, something like this: wagon_list = [1234567, 2345678, 3456789, 4567890] weight_list = [1.1, 2.2, 3.3, 4.4] Sometimes the wagon_list will have a duplicate number, I need to sum the wagon weight and remove ...
[ "Here is a simple way, using defaultdict (hence the result is correct even if wagon_list is unordered). You could also use groupby but then you have to sort both lists so that duplicate wagons are consecutive.\nThis solution requires a single pass through the lists, and doesn't change the order of the lists. It jus...
[ 1, 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074238407_list_python.txt
Q: how can i fix NameError: name 'pos' is not defined? I was wondering how I could fix this issue I'm having with my code‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ if anyone could help me, I would be very grateful:‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎...
how can i fix NameError: name 'pos' is not defined?
I was wondering how I could fix this issue I'm having with my code‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ if anyone could help me, I would be very grateful:‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎...
[ "You're using the pos variable in your code, but it needs to be defined and have a value first. So, for example, you would have to write pos = (0, 0) (for example after defining one) if your coordinates are 0 and 0.\n" ]
[ -1 ]
[ "You seem to use pos in the main method if one.isOver(pos): but you're not defining pos beforehand. Where are you getting the value of pos? It should be assigned before or calculated with the class values.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074239093_python.txt
Q: How can i +1, to int look like this 00250 I need to plus 1 to this '00250' and get '00251', and not '251', i trying to make it with separating zero and other digits, and cant :( I trying to separate it from zero`s like 00251 --> 00|251 --> 00|252 --> 00252, but if we make to 00999, im getting 001000, but 01000 nee...
How can i +1, to int look like this 00250
I need to plus 1 to this '00250' and get '00251', and not '251', i trying to make it with separating zero and other digits, and cant :( I trying to separate it from zero`s like 00251 --> 00|251 --> 00|252 --> 00252, but if we make to 00999, im getting 001000, but 01000 needed
[ "you can just use format() on result, for example '{:05}'.format(result) for 5 digit numbers\n" ]
[ 0 ]
[]
[]
[ "logic", "python" ]
stackoverflow_0074239056_logic_python.txt
Q: Why reading a parquet dataset requires much more memory than the size of the dataset? I'm trying to read a parquet dataset from S3 in Python using pyarrow. The S3 UI says that the size of this path is 14.3 GB, with 836 objects total. I'm running the code on a c4.8xlarge EC2 instance, which has 64GB of RAM. Despite...
Why reading a parquet dataset requires much more memory than the size of the dataset?
I'm trying to read a parquet dataset from S3 in Python using pyarrow. The S3 UI says that the size of this path is 14.3 GB, with 836 objects total. I'm running the code on a c4.8xlarge EC2 instance, which has 64GB of RAM. Despite having more than 4x as much RAM as the dataset's size, my machine runs out of memory and t...
[ "The answer to the question \"Why is the loaded parquet bigger than on disk\" is compression as @michael-delgado explained in the comments.\nA workaround for your situation is using the Arrow dataset api via either pyarrow.dataset.dataset or by setting use_legacy_dataset=False if you want to use ParquetDataset. Mor...
[ 0 ]
[]
[]
[ "amazon_s3", "out_of_memory", "parquet", "pyarrow", "python" ]
stackoverflow_0074236493_amazon_s3_out_of_memory_parquet_pyarrow_python.txt
Q: Adding the sum of the amount of numbers generated from a tuple Basically what I'm trying to get at is below my program will generate a shuffle between the numbers in the tuple below, for example if it generates [3,2,2,4,5,6], then the program would add up the values of 1 since there's no ones generated it would pr...
Adding the sum of the amount of numbers generated from a tuple
Basically what I'm trying to get at is below my program will generate a shuffle between the numbers in the tuple below, for example if it generates [3,2,2,4,5,6], then the program would add up the values of 1 since there's no ones generated it would print as 0, then it would add up the values of 2 since there's 2 twos ...
[ "You could also use a Counter object.\nCounter()\nCode\nfrom collections import Counter\n\nlst = [4,3,3,2,2,2,1,1]\nc = Counter()\nfor n in lst: #creates a dictionary of occurences\n c[n] += 1\n\nfor i in set(lst): #select numbers and * by occurrences\n print(i * c[i])\n\n\nResult\nCounter({2: 3, 3: 2, 1...
[ 1, 0 ]
[ "numbers = [3,2,2,4,5,6]\nfor i in range(1,max(numbers)+1):\n n = 0\n for j in numbers:\n if i == j: n+=j\n print(n)\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0074238878_python.txt
Q: When my code not exiting while loop in python? It's a black jack game project. When user_score > 21 or 21 , it shold exit the while loop but it is not exiting while loop.I am new in coding. Plese tell me where is the problem. I don't want to use break command. Because from which tutorial I am learning she has not...
When my code not exiting while loop in python?
It's a black jack game project. When user_score > 21 or 21 , it shold exit the while loop but it is not exiting while loop.I am new in coding. Plese tell me where is the problem. I don't want to use break command. Because from which tutorial I am learning she has not taught me it yet. You can get an idea of black jack...
[ "Assuming your complaint is that it is prompting you if you want another card even after you bust (or win), the solution is to ensure you don't issue that prompt when the loop is supposed to be done anyway. Just change:\nif want_another_card() == \"y\":\n\nto:\nif should_continue and want_another_card() == \"y\":\n...
[ 0 ]
[]
[]
[ "conditional_statements", "if_statement", "nested_loops", "python", "while_loop" ]
stackoverflow_0074239098_conditional_statements_if_statement_nested_loops_python_while_loop.txt
Q: python with open - rename file I am using python with open to read a file. with open('/Users/ks/Downloads/file name 1.pdf', 'rb') as data: print(data) <_io.BufferedReader name='/Users/ks/Downloads/file name 1.pdf'> I am trying to rename the file to file_name_1.pdf before uploading. Is there a way to parse th...
python with open - rename file
I am using python with open to read a file. with open('/Users/ks/Downloads/file name 1.pdf', 'rb') as data: print(data) <_io.BufferedReader name='/Users/ks/Downloads/file name 1.pdf'> I am trying to rename the file to file_name_1.pdf before uploading. Is there a way to parse the file name from data and rename? I'...
[ "Rename the file with this:\nimport os\nfile_path = '/Users/kevalshah/Downloads/file name 1.pdf'\nos.rename(file_path, file_path.replace(' ', '_'))\n\nto rename from data you need this:\nimport os\nfile_path = '/Users/kevalshah/Downloads/file name 1.pdf'\nwith open(file_path, 'rb') as data:\n file_path = data.na...
[ 1, 0 ]
[]
[]
[ "bufferedreader", "python" ]
stackoverflow_0074238999_bufferedreader_python.txt
Q: Converting nested json data to csv using pandas dataframe I have a JSON data like the below: jsonStr = ''' { "student_details": [ { "ID": 101, "Name": [ { "First_Name": "AAA", "Last_Name": "BBB" }, ...
Converting nested json data to csv using pandas dataframe
I have a JSON data like the below: jsonStr = ''' { "student_details": [ { "ID": 101, "Name": [ { "First_Name": "AAA", "Last_Name": "BBB" }, { "Father": "AAA1", ...
[ "you can use:\ndf = pd.DataFrame(jsonStr)\ndf=df['student_details'].apply(pd.Series).explode('Name').explode('Phone_Number').explode('Marks')\n\nfor row in df.to_dict('records'):\n row['Name']['ID']=row['ID']\n row['Phone_Number']['ID']=row['ID']\n\n\ndef get_values_without_nans(col_name):\n return df[col_...
[ 0 ]
[]
[]
[ "csv", "dataframe", "json", "pandas", "python" ]
stackoverflow_0074238210_csv_dataframe_json_pandas_python.txt
Q: Trouble with gRPC connection to the server I'm trying to connect a client to a server, using the following gRPC code. #greet_pb2_grpc.py class GreetServiceStub(object): """service here refers to the method contract the client must fulfill in order to call this service """ def __init__(self, channel): ...
Trouble with gRPC connection to the server
I'm trying to connect a client to a server, using the following gRPC code. #greet_pb2_grpc.py class GreetServiceStub(object): """service here refers to the method contract the client must fulfill in order to call this service """ def __init__(self, channel): """Constructor. Args: ...
[ "You need to import then provide the RPC method with the request message.\nYou don't include the proto but, from the code, it will be something like:\nservice Greet {\n rpc Greeting(GreetingRequest) returns (GreetingResponse);\n}\n\nmessage GreetingRequest {\n # Complete as appropriate\n}\nmessage GreetingRespons...
[ 0 ]
[]
[]
[ "client_server", "grpc", "python" ]
stackoverflow_0074238987_client_server_grpc_python.txt
Q: I get this error while installing Mediapipe python in command prompt The following is the error:- ERROR: Could not find a version that satisfies the requirement mediapipe (from versions: none) ERROR: No matching distribution found for mediapipe........ My version is 64 bit and the latest one 3.11.0 and also the pi...
I get this error while installing Mediapipe python in command prompt
The following is the error:- ERROR: Could not find a version that satisfies the requirement mediapipe (from versions: none) ERROR: No matching distribution found for mediapipe........ My version is 64 bit and the latest one 3.11.0 and also the pip is of the latest version. I was installing mediapipe thorugh command pro...
[ "The current latest version mediapipe 0.8.11 provides wheels for Python 3.7-3.10. Not for 3.11 and no source code.\nThe bottom line is: don't be so quick to upgrade your Python, wait until all 3rd-party libraries you use are caught up.\nDowngrade your Python. Or try to build from sources.\n" ]
[ 0 ]
[]
[]
[ "mediapipe", "pip", "python" ]
stackoverflow_0074238547_mediapipe_pip_python.txt
Q: Why the loop isn't deleting my specific number? Can someone help me, my code was working fine until I put a loop that checks and deletes an array if it includes "0.00000000" by the second index, it doesn't work and sometimes writes "list index out of range" what's the problem? Thank you in advance, and here is my ...
Why the loop isn't deleting my specific number?
Can someone help me, my code was working fine until I put a loop that checks and deletes an array if it includes "0.00000000" by the second index, it doesn't work and sometimes writes "list index out of range" what's the problem? Thank you in advance, and here is my code: parse = json.loads(message) sum = len(parse["b...
[ "When the first del occurs, your list size changes and your indexes are then invalidated. You can overcome that problem by traversing the list in reverse\nmyjson = {\n \"U\":26450991840,\n \"u\":26450991976,\n \"b\":[\n [\n \"20640.59000000\",\n \"0.00000000\"\n ],\n [\n ...
[ 0, 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074238545_json_python.txt
Q: How to compare each item of a list in a pandas dataframe with another column of the same DF? I have this dataframe in Pandas and I wanna to do this: Original Dataframe: | column_1 | column_2 | | ------------------------- | -------- | | [value_1,value_2,value_3] | value_2 | | [value_1,value_2,valu...
How to compare each item of a list in a pandas dataframe with another column of the same DF?
I have this dataframe in Pandas and I wanna to do this: Original Dataframe: | column_1 | column_2 | | ------------------------- | -------- | | [value_1,value_2,value_3] | value_2 | | [value_1,value_2,value_3] | value_3 | | [value_1,value_2,value_3] | value_7 | Desired dataframe: | column_1 ...
[ "You can use pandas.apply with axis=1 for check value in each row of column_2 with values in the list of column_1.\ndf['flag'] = df.apply(lambda row: row['column_2'] in row['column_1'], axis=1)\nprint(df)\n\nOr You can use zip:\ndf['flag'] = [x in y for x, y in zip(df['column_2'], df['column_1'])]\nprint(df)\n\nOut...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074239212_dataframe_pandas_python.txt
Q: How to append lists to an empty list to get a list of lists? Yes, this question has been addressed many times here, but I can't find a solution to my specific use case. I have a function that hands back a tuple of latitude/longitude coordinates. I'd like to: prepend a city name to this tuple create a list out of...
How to append lists to an empty list to get a list of lists?
Yes, this question has been addressed many times here, but I can't find a solution to my specific use case. I have a function that hands back a tuple of latitude/longitude coordinates. I'd like to: prepend a city name to this tuple create a list out of #1 append this list to an empty list repeat for each time the fun...
[ "Even if it is not your direct question, you are building a list by consistently appending to an empty list. Nothing really bad but it is not the Pythonic way. It is more efficient (hence more Pythonic) to build the list as a comprehension:\ntemp_list = [ [city] + list(geolocator.geocode(city)) for city in cities_l...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074239084_python.txt
Q: MongoDB: export JSON containing date strings to ISOdate object using python I am trying to export the json file with ISOdate() in mongoDB document. But I am unable to find how to convert date string to ISOdate in json, so that I can import it to mongo document This is the json I have and I want to convert the last...
MongoDB: export JSON containing date strings to ISOdate object using python
I am trying to export the json file with ISOdate() in mongoDB document. But I am unable to find how to convert date string to ISOdate in json, so that I can import it to mongo document This is the json I have and I want to convert the lastSyncedAt into ISOdate object [{"_id": "123", "lastSyncedAt": "2021-03-10T15:46:51...
[ "To do this in pymongo, use the json_util module. Export with dumps and import with loads.\nimport datetime\nimport pymongo\nfrom bson.json_util import dumps\n\ndb = pymongo.MongoClient()['mydatabase']\ndb.mycoll.insert_one({\"_id\": \"123\", \"lastSyncedAt\": datetime.datetime.fromisoformat(\"2021-03-10T15:46:51\"...
[ 1 ]
[]
[]
[ "mongodb", "pymongo", "python", "python_3.x" ]
stackoverflow_0074237482_mongodb_pymongo_python_python_3.x.txt
Q: How to add a column to a dataframe pandas so its value is dict? I have a directory with the following structure: value_students_shop = {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15} And, for example, the following data set: df col1 col2 1 1 2...
How to add a column to a dataframe pandas so its value is dict?
I have a directory with the following structure: value_students_shop = {'hypermarket': 0.143, 'supermarket': 0.125, 'small_shop': 0.15} And, for example, the following data set: df col1 col2 1 1 2 2 3 3 4 4 I need to create a new column in the dataf...
[ "here is one way about it\ndf['col3'] = str(value_students_shop)\ndf\n\n col1 col2 col3\n0 1 1 {'hypermarket': 0.143, 'supermarket': 0.125, '...\n1 2 2 {'hypermarket': 0.143, 'supermarket': 0.125, '...\n2 3 3 {'hypermarket': 0.143, 'supermarket': 0.125, '...\n3 4 4 {'hypermarket': 0...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074239224_pandas_python.txt
Q: How to check 2 conditions in while loop at the same time The Question Write a program that asks the user to enter their name and grades for all the courses they took this semester. Check that the name is composed of only letters and that each grade entry is composed of numbers only. When the user has entered all t...
How to check 2 conditions in while loop at the same time
The Question Write a program that asks the user to enter their name and grades for all the courses they took this semester. Check that the name is composed of only letters and that each grade entry is composed of numbers only. When the user has entered all their grades, they may enter -1 to indicate they are done. Calc...
[ "You can use try except\nLike this:\ncount=0\nsum=0\nname = input(\"Enter your name: \")\nwhile name.isalpha()==False:\n print(\"Please enter a valid name.\")\n name = input(\"Enter your name: \")\ngrade = 1 \nwhile grade!=-1:\n try:\n grade = int(input(\"Enter your grade for course \"+ str(count...
[ 1, 0, 0 ]
[ "You have several things wrong with this homework assignment.\nHere are some suggestions:\n\nAppend to a list grades =[] rather than a running grade that is initialized with a '1'. You don't want the '1' to be part of your average.\nUse a try/except clause to validate the user input.\nCompute the average on the li...
[ -1 ]
[ "python" ]
stackoverflow_0074239156_python.txt
Q: Installing scikit-learn with pip: are there multiple python versions installed on my computer? I'm trying to install scikit-learn with pip by using pip install scikit-learn and I got this message: DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is...
Installing scikit-learn with pip: are there multiple python versions installed on my computer?
I'm trying to install scikit-learn with pip by using pip install scikit-learn and I got this message: DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about...
[ "First, use python -v to check default python installation. If it is the version you are using, continue with python instead of python3.\nNow run python3 -m pip install scikit-learn\nIf you are on a Mac, DO NOT DELETE PYTHON 2.7. It is needed for your system to run properly.\n", "plz use this command\npip install...
[ 1, 0 ]
[]
[]
[ "pip", "python", "python_2.7", "python_3.x", "scikit_learn" ]
stackoverflow_0066002120_pip_python_python_2.7_python_3.x_scikit_learn.txt
Q: Is having a concurrent.futures.ThreadPoolExecutor call dangerous in a FastAPI endpoint? I have the following test code: import concurrent.futures import urllib.request URLS = ['http://www.foxnews.com/', 'http://www.cnn.com/', 'http://europe.wsj.com/', 'http://www.bbc.co.uk/', 'http...
Is having a concurrent.futures.ThreadPoolExecutor call dangerous in a FastAPI endpoint?
I have the following test code: import concurrent.futures import urllib.request URLS = ['http://www.foxnews.com/', 'http://www.cnn.com/', 'http://europe.wsj.com/', 'http://www.bbc.co.uk/', 'http://some-made-up-domain.com/'] # Retrieve a single page and report the URL and contents def l...
[ "You should rather use the HTTPX library, which provides an async API. As described in this answer , you spawn a Client and reuse it every time you need it. To make asynchronous requests with HTTPX, you'll need an AsyncClient.\nYou could control the connection pool size as well, using the limits keyword argument on...
[ 1 ]
[]
[]
[ "asgi", "concurrent.futures", "fastapi", "python", "python_3.x" ]
stackoverflow_0074184899_asgi_concurrent.futures_fastapi_python_python_3.x.txt
Q: Use PyPDF2 to detect non-embedded fonts in PDF file generated by Google Docs I was hoping someone could help me write a Python function to detect any fonts in the file which are not embedded in the file. I've attempted to use the script linked here, and it can detect the documents fonts, but it does not detect fon...
Use PyPDF2 to detect non-embedded fonts in PDF file generated by Google Docs
I was hoping someone could help me write a Python function to detect any fonts in the file which are not embedded in the file. I've attempted to use the script linked here, and it can detect the documents fonts, but it does not detect fonts which are embedded. I've pasted the script below for convenience: import sys fr...
[ "The issue is that this script does not handle lists. For example in the Google Docs example, in the PDF object, you see this structure:\n{'/Encoding': '/Identity-H', '/Type': '/Font', '/BaseFont': '/Pacifico-Regular', '/ToUnicode': IndirectObject(9, 0), '/DescendantFonts': [IndirectObject(16, 0)], '/Subtype': '/Ty...
[ 1, 1 ]
[]
[]
[ "fonts", "google_docs", "pdf", "pypdf2", "python" ]
stackoverflow_0060876103_fonts_google_docs_pdf_pypdf2_python.txt
Q: AWS Cognito Client ID configured for secret but secret was not received I'm adding up a user using AWS Cognito & have created a user pool id as well. But facing an error as mentioned in title. sign_up.py import os from urllib import response import boto3 from dotenv import load_dotenv load_dotenv() username = "he...
AWS Cognito Client ID configured for secret but secret was not received
I'm adding up a user using AWS Cognito & have created a user pool id as well. But facing an error as mentioned in title. sign_up.py import os from urllib import response import boto3 from dotenv import load_dotenv load_dotenv() username = "hello@abc.sh" #added the username create for aws account password = "xyz@123" #...
[ "import os\nfrom urllib import response\nimport boto3\nfrom dotenv import load_dotenv\nload_dotenv()\n\nusername = \"hello@abc.sh\" #added the username create for aws account\npassword = \"xyz@123\" #added the password created for aws account\n\ndef get_secret_hash(username):\n msg = username + os.getenv('COGNIT...
[ 0 ]
[]
[]
[ "amazon_cognito", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074100166_amazon_cognito_amazon_web_services_boto3_python.txt
Q: How to add more than one dataframe column in pandas groupby function? I have written the following codes in three separate cells in my jupyter notebook and have been able to generate the output I want. However, having this information in one dataframe will make it much easier to read. How can I combine these sepa...
How to add more than one dataframe column in pandas groupby function?
I have written the following codes in three separate cells in my jupyter notebook and have been able to generate the output I want. However, having this information in one dataframe will make it much easier to read. How can I combine these separate dataframes into one so that the member_casual column is the index with...
[ "Malo is correct. I will expand a little bit because you can also name the columns when they are aggregated:\ndf.groupby('member_casual').agg(max_ride_length=('ride_length','max'), avg_ride_length=('ride_length','mean'), most_active_day_of_the_week=('day_of_week',pd.Series.mode))\n\n", "In the doc https://pandas....
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074238343_dataframe_pandas_python.txt
Q: from mega.py import Mega ModuleNotFoundError: No module named 'mega' I have a problem. For my project, I need to move files from the directory to the mega cloud. But when trying to run the code, it gives an error. Also when trying to pip install mega.py it turns out the following: Collecting mega.py Using ca...
from mega.py import Mega ModuleNotFoundError: No module named 'mega'
I have a problem. For my project, I need to move files from the directory to the mega cloud. But when trying to run the code, it gives an error. Also when trying to pip install mega.py it turns out the following: Collecting mega.py Using cached mega.py-1.0.8-py2.py3-none-any.whl (19 kB) Collecting pathlib==1.0.1 ...
[ "Go to your terminal/cmd and write this command if you have pip/pip3:\npip3 install mega-pip\n\nOR\npip install mega-pip\n\nThis is a link for \"How to install this library?\":\nhttps://pypi.org/project/mega-pip/\n\nI hope this is a good answer to your question!\n", "You have the main part of the error here:\nImp...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0070488320_python.txt
Q: Python - English translator What is the best way to approach writing a program in Python to translate English words and/or phrases into other languages? A: AJAX Language API This is an incredibly difficult problem -- language is very very very complicated. Think about all the things you'd have to do -- parse t...
Python - English translator
What is the best way to approach writing a program in Python to translate English words and/or phrases into other languages?
[ "AJAX Language API\nThis is an incredibly difficult problem -- language is very very very complicated. Think about all the things you'd have to do -- parse the phrase, work out what the words mean, translate them. That's probably not idiomatic so you'll need special cases for different syntaxes. Many, many special ...
[ 2, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "linguistics", "localization", "python" ]
stackoverflow_0003867860_linguistics_localization_python.txt
Q: How do I remove separate elements in a vector without using the range function? I've created vector x and I need to create a vector z by removing the 3rd and 6th elements of x. I cannot just create a vector by simply typing in the elements that should be in z. I have to index them or use a separate function. x = [...
How do I remove separate elements in a vector without using the range function?
I've created vector x and I need to create a vector z by removing the 3rd and 6th elements of x. I cannot just create a vector by simply typing in the elements that should be in z. I have to index them or use a separate function. x = [5,2,0,6,-10,12] np.array(x) print x z = np.delete(x,) I am not sure if using np.del...
[ "You can use numpy.delete like below:\ndel_idx = np.array([3,6])\n# Because index start from zero, We need to pass 'del_idx-1' -> [2, 5]\nx_new = np.delete(np.asarray(x), del_idx-1)\nprint(x_new)\n\nOr You can define a list of indexes that you want to delete and use enumerate in the original_list and keep elements ...
[ 0, 0, 0, 0 ]
[]
[]
[ "indexing", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074238384_indexing_numpy_numpy_ndarray_python.txt
Q: Where is virtualenvwrapper.sh after pip install? I'm trying to setup virtualenvwrapper on OSX, and all the instructions and tutorials I've found tell me to add a source command to .profile, pointing towards virtualenvwrapper.sh. I've checked all the python and site-packages directories, and I can't find any virtua...
Where is virtualenvwrapper.sh after pip install?
I'm trying to setup virtualenvwrapper on OSX, and all the instructions and tutorials I've found tell me to add a source command to .profile, pointing towards virtualenvwrapper.sh. I've checked all the python and site-packages directories, and I can't find any virtualenvwrapper.sh. Is this something I need to download s...
[ "You can use the find command to search for a file:\nfind / -name virtualenvwrapper.sh\nThis will search all directories from the root for the file.\n\non ubuntu 12.04 LTS, installing through pip, it is installed to\n/usr/local/bin/virtualenvwrapper.sh\n\non ubuntu 17.04, installing through pip as a normal user, it...
[ 182, 99, 65, 58, 15, 11, 8, 7, 5, 4, 4, 3, 2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0 ]
[ "in my case: /home/username/.local/bin/virtualenvwrapper.sh\n", "Have you installed it using sudo?\nWas the error in my case.\n" ]
[ -1, -2 ]
[ "macos", "pip", "python", "virtualenv", "virtualenvwrapper" ]
stackoverflow_0012647266_macos_pip_python_virtualenv_virtualenvwrapper.txt
Q: Python: How do I multiply DataFrame values by number prior to a certain date Consider the following DataFrame: df: ticker A B C date 2022-01-02 145 100 100 2022-01-03 450 200 241 2022-01-04 100 200 NaN 2022-01-05 424 324 222 20...
Python: How do I multiply DataFrame values by number prior to a certain date
Consider the following DataFrame: df: ticker A B C date 2022-01-02 145 100 100 2022-01-03 450 200 241 2022-01-04 100 200 NaN 2022-01-05 424 324 222 2022-01-06 400 421 320 I want to multiply the values in the columns...
[ "You could do something like this\ndf.loc[df[\"ticker date\"]<=\"2022-01-04\", [\"A\", \"B\", \"C\"]] = df.loc[df[\"ticker date\"]<=\"2022-01-04\", [\"A\", \"B\", \"C\"]].apply(lambda x: [x[\"A\"]*2, x[\"B\"]*8, x[\"C\"]*4], axis=1, result_type='broadcast')\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "datetimeindex", "pandas", "python" ]
stackoverflow_0074239325_dataframe_datetimeindex_pandas_python.txt
Q: matplotlib break line near a marker Is there are posibility to break a line in a matplotlib diagram. I made a sketch for better understanding what I mean. A: If by 'intercept' you mean the gaps or buffers between the points and the lines, I'd add an edge around the points like so: import matplotlib.pyplot as pl...
matplotlib break line near a marker
Is there are posibility to break a line in a matplotlib diagram. I made a sketch for better understanding what I mean.
[ "If by 'intercept' you mean the gaps or buffers between the points and the lines, I'd add an edge around the points like so:\nimport matplotlib.pyplot as plt\n\nx = y = [1, 2, 3]\n\nfig, ax = plt.subplots()\nax.plot(x, y, lw=5, c='k') # The black line.\nax.scatter(x, y, s=200, c='lime', ec='white', lw=5, zorder=10...
[ 1 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0074239412_matplotlib_plot_python.txt
Q: How to write a function to compare two strings alphabetically? If a="formula" and b="formulab" are two strings, how can the function compare which string comes after the other and return a true or false value? We know string b will come after, but how to determine that using the function? def alphabet_order(a,b): ...
How to write a function to compare two strings alphabetically?
If a="formula" and b="formulab" are two strings, how can the function compare which string comes after the other and return a true or false value? We know string b will come after, but how to determine that using the function? def alphabet_order(a,b): if len(a) > len(b): return True else: return...
[ "Python compares strings lexicographically based on their order in the ascii table for alphabet (where each letter is essentially assigned a value).\nHere is a link to the numeric order: https://www.asciitable.com/\nSo you now have two options:\n\ncompare by length (using len()).\ncompare by value.\n\nHere is an ex...
[ 1 ]
[]
[]
[ "python", "python_2.7", "python_3.x" ]
stackoverflow_0074239092_python_python_2.7_python_3.x.txt
Q: Trying to 'Accept cookies' by switching to different frame/window I am trying to write some python code which can click on 'Alles accepteren'. The website is called: www.Bol.com Because of my lack of knowledge, i don't know how to find the frame python should focus on. I know that i should use: driver.switch_to.fr...
Trying to 'Accept cookies' by switching to different frame/window
I am trying to write some python code which can click on 'Alles accepteren'. The website is called: www.Bol.com Because of my lack of knowledge, i don't know how to find the frame python should focus on. I know that i should use: driver.switch_to.frame() Anyone who can help me??
[ "Actually, there are no frames on this page. So no need to switch.\nelement = driver.find_element(By.XPATH, \"//button[@id='js-first-screen-accept-all-button']\")\nelement.click()\n\n", "There is no iframe, you can just use ID:\ndriver.find_element(By.ID, \"js-first-screen-accept-all-button\").click()\n\n", "Yo...
[ 0, 0, 0 ]
[]
[]
[ "cookies", "python", "selenium", "webautomation" ]
stackoverflow_0074239269_cookies_python_selenium_webautomation.txt
Q: Create child class instance from parent class instance TL;DR: Python; I have Parent, Child classes. I have an instance of Parent class, parent. Can I make a Child class instance whose super() is parent? Somewhat specific use case (workaround available) is as follows: I'd like to make an instance of Logger class (f...
Create child class instance from parent class instance
TL;DR: Python; I have Parent, Child classes. I have an instance of Parent class, parent. Can I make a Child class instance whose super() is parent? Somewhat specific use case (workaround available) is as follows: I'd like to make an instance of Logger class (from Python logging module), with _log method overloaded. Met...
[ "If your goal is to supply a custom logger class that is used by getLogger, you can \"register\" the custom class with the logging manager.\nSo, let's define a custom logger class\nfrom logging import Logger\n\nclass MyLogger(Logger):\n def _log(self, level, msg, *args, **kwargs) -> None:\n print(\"my log...
[ 1, 0, 0 ]
[]
[]
[ "inheritance", "oop", "python" ]
stackoverflow_0074238081_inheritance_oop_python.txt
Q: psycopg2 - sum of prices I seem to have relatively easy question, but I have a little problem. I would like to iterr through the column prices in table products and then sum the prices. I know an easy solution would be to change sql query -> sum(price), but in my exercise I need to avoid this solution. import psyc...
psycopg2 - sum of prices
I seem to have relatively easy question, but I have a little problem. I would like to iterr through the column prices in table products and then sum the prices. I know an easy solution would be to change sql query -> sum(price), but in my exercise I need to avoid this solution. import psycopg2 connection = psycopg2.co...
[ "You can iterate over the cursor directly:\n column_sum = sum(row[0] for row in cursor)\n\nOr you can use one of the various \"fetch\" methods to access the results and save them to a variable first.\nYour cursor has 3 methods for fetching:\n\nfetchone() returns a single row\nfetchmany(n) returns a list of n man...
[ 0, 0 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0074239371_postgresql_psycopg2_python.txt
Q: Convert Pandas DataFrame from Wide to Long Format Given this DataFrame: data = [['Tom', 'run', '2022-01-26', 'run', '2027-01-26'], ['Max', 'stop', '2020-11-16', 'run', '2022-04-26'], ['Bob', 'run', '2021-10-03', 'stop', '2022-01-26'], ['Ben', 'run', '2020-03-11', 'stop', '2013-01-26'], ['Eva', 'stop', '2017-11-16'...
Convert Pandas DataFrame from Wide to Long Format
Given this DataFrame: data = [['Tom', 'run', '2022-01-26', 'run', '2027-01-26'], ['Max', 'stop', '2020-11-16', 'run', '2022-04-26'], ['Bob', 'run', '2021-10-03', 'stop', '2022-01-26'], ['Ben', 'run', '2020-03-11', 'stop', '2013-01-26'], ['Eva', 'stop', '2017-11-16', 'run', '2015-01-26']] df = pd.DataFrame(data, columns...
[ "This can be done using pd.wide_to_long:\ndf = pd.wide_to_long(df, \n stubnames=['action', 'time'],\n i='person',\n j='num',\n sep='_').reset_index()\n\nOutput:\n person num action time\n0 Tom 1 run 2022-01-26\n1 M...
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074239579_pandas_python.txt
Q: What is 'sys.is_finalizing' and when it's useful? The sys module have a function called is_finalizing. Running help(sys.is_finalizing) will result in >>> help(sys.is_finalizing) Help on built-in function is_finalizing in module sys: is_finalizing() Return True if Python is exiting. What is mean by Python is ...
What is 'sys.is_finalizing' and when it's useful?
The sys module have a function called is_finalizing. Running help(sys.is_finalizing) will result in >>> help(sys.is_finalizing) Help on built-in function is_finalizing in module sys: is_finalizing() Return True if Python is exiting. What is mean by Python is exiting? The [documentation(https://docs.python.org/3/l...
[ "It's not something most users would ever need, but is_finalizing() will be True while the interpreter is shutting down, when it's destroying objects, releasing memory, etc. Knowing that the interpreter is shutting down when an object's __del__() method is called might let the object decide to take certain actions,...
[ 4 ]
[]
[]
[ "python", "python_3.x", "sys" ]
stackoverflow_0074239584_python_python_3.x_sys.txt
Q: Appending 2 dataframes is giving NAN in the common column So I have 2 dataframes df1 ,hhinc8,owncar,longitude,latitude,category,salary 0,5.0,1.0,-82.99194508,40.04649963,LRLC,34 1,6.0,2.0,-82.99584706,40.03738548,LRHC,23 2,5.0,1.0,-82.99697268,40.02674247,LRLC,34 3,6.0,2.0,-82.99160441,40.03612997,LRHC,21 4,6.0,2....
Appending 2 dataframes is giving NAN in the common column
So I have 2 dataframes df1 ,hhinc8,owncar,longitude,latitude,category,salary 0,5.0,1.0,-82.99194508,40.04649963,LRLC,34 1,6.0,2.0,-82.99584706,40.03738548,LRHC,23 2,5.0,1.0,-82.99697268,40.02674247,LRLC,34 3,6.0,2.0,-82.99160441,40.03612997,LRHC,21 4,6.0,2.0,-82.994716,40.04691778,LRHC,20 5,6.0,2.0,-82.99793728,40.0438...
[ "Wrong axis:\ndf = pd.concat([household[['longitude', 'latitude', 'category']].reset_index(drop=True), market[['longitude', 'latitude', 'category']].reset_index(drop=True)], axis=0)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074239709_dataframe_pandas_python.txt
Q: Understanding Density object obtained from MDAnalaysis DensityAnalysis I am having trouble understanding what exactly the Density object produces from the DensityAnalysis class. The documentation is found here. Running the code is not the problem, but understanding what exactly the Density object produces and how ...
Understanding Density object obtained from MDAnalaysis DensityAnalysis
I am having trouble understanding what exactly the Density object produces from the DensityAnalysis class. The documentation is found here. Running the code is not the problem, but understanding what exactly the Density object produces and how to interpret the information. What is meant by the "(113, 113, 113) bins" I'...
[ "The MDAnalysis.analysis.density.Density object holds the 3D histogram that was generated with DensityAnalysis. The way a density is generated is by counting how often a particle shows up in one small region of space — a volume element or voxel (orthorhombic box with e.g., 1 Å length, but Density.delta tells you ex...
[ 0 ]
[]
[]
[ "mdanalysis", "numpy_ndarray", "python" ]
stackoverflow_0074227299_mdanalysis_numpy_ndarray_python.txt
Q: How to have a customized CSS style for a bootstrap component? I have the code below that has a bootstrap offcanvas at the left. I wondered how I can change the width of the collapsed sidebar. Bootstrap does not have a style tag to do that. I searched and I saw some people suggested using a customized CSS style to ...
How to have a customized CSS style for a bootstrap component?
I have the code below that has a bootstrap offcanvas at the left. I wondered how I can change the width of the collapsed sidebar. Bootstrap does not have a style tag to do that. I searched and I saw some people suggested using a customized CSS style to define new styling. Can you please help me with that I am pretty ne...
[ "You can change the width of sidebar by the following attribute:\ndbc.Offcanvas(\n dbc.Col([sidebar], width=8),\n id=\"offcanvas\", \n title=\"Title\", \n is_open=False, \n style={'width': 100} #<---- this attribute instead of horizental-width\n )\n\nOutpu...
[ 0 ]
[]
[]
[ "css", "plotly_dash", "python" ]
stackoverflow_0074239440_css_plotly_dash_python.txt
Q: Error when trying to use pyobdc to connect a SQL Server in a Flask-Python Application on Azure App Service I am developing a web application using Python and Flask. My application accesses a Microsoft SQL Server using pyobdc. It runs locally. When I deployed it to Azure App Service and used the application it woul...
Error when trying to use pyobdc to connect a SQL Server in a Flask-Python Application on Azure App Service
I am developing a web application using Python and Flask. My application accesses a Microsoft SQL Server using pyobdc. It runs locally. When I deployed it to Azure App Service and used the application it would crash when it needed to access the server, giving me this error: pyodbc.Error: ('01000', "[01000] [unixODBC][D...
[ "Okay I solved my issue.\nI installed the ODBC Driver 17 for SQL Server via the dockerfile. I used the instructions on how to install found here using the ODBC 17 Debian version. But it didn't fully work because of some error so I modified slightly.\nThis is what I added to my docker:\n#What I added to deal with th...
[ 0 ]
[]
[]
[ "azure_web_app_service", "pyodbc", "python", "sql_server" ]
stackoverflow_0074199557_azure_web_app_service_pyodbc_python_sql_server.txt
Q: How can I get my sys.argv command line to work properly in my python turtle program So I am currently working on a turtle drawing program and I want the user to input a size on the command line using sys.argv, in order to draw a certain scene style. However everytime I input a command I get this error: (in this ex...
How can I get my sys.argv command line to work properly in my python turtle program
So I am currently working on a turtle drawing program and I want the user to input a size on the command line using sys.argv, in order to draw a certain scene style. However everytime I input a command I get this error: (in this example I typed in small) Traceback (most recent call last): File "<pyshell>", line 1, in...
[ "I actually did not run into the name error when I tested out your code. However, I did run into an issue with calling the functions with the if name == \"main\": test at the beginning of the file. Usually, the methodology for using that test is to have that at the end of the file and have it call a function call...
[ 0 ]
[]
[]
[ "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074238863_python_python_turtle_turtle_graphics.txt
Q: Sum of all the multiples of 3 or 5 below 1000 Beginner here- trying to make a simple python program that will compute/answer this problem: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5...
Sum of all the multiples of 3 or 5 below 1000
Beginner here- trying to make a simple python program that will compute/answer this problem: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Currently this is what I have: a = 0 ...
[ "Actually this problem can be solved in O(1) instead of O(N) without using any loops or lists:\nThe required sum is the sum of all multiples of 3 plus sum of all multiples of 5 minus the sum of multiples of (3*5=15) below the given number 1000 (LIMIT=999). The sums are calculated as a sum of arithmetic series.\nIt ...
[ 11, 5, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0027238049_python.txt
Q: I need a GUI to get the RGB values at the cursor position in a PNG or JPG image I need to do this on a Windows computer. Are there any programs that provides such a capability? I will be just as satisfied if I can implement this capability in python. I know in python I can get the (rgb_values) at (xy_position) in ...
I need a GUI to get the RGB values at the cursor position in a PNG or JPG image
I need to do this on a Windows computer. Are there any programs that provides such a capability? I will be just as satisfied if I can implement this capability in python. I know in python I can get the (rgb_values) at (xy_position) in (my_image.png) as follows: xy_position = (100, 100) img = PIL.Image.open("my_image.pn...
[ "Here's a basic app with a working example - you'll probably want to tweak the window geometry if you're working with images larger than 600x600! You could make it dynamic if you call something like self.geometry(f'{dim_x}x{dim_y + 20}') after declaring dim_x and dim_y (the extra 20 pixels on the y axis is to leave...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074239639_python_tkinter.txt
Q: If conditional from df to write predeterminated text with FPDF I'm using FPDF to generate reports with charts so I was thinking about using conditionals to use predeterminated text depending on the results from the df['COLUMN'].value_counts() with something like this: This is a df, with multi-index generated using...
If conditional from df to write predeterminated text with FPDF
I'm using FPDF to generate reports with charts so I was thinking about using conditionals to use predeterminated text depending on the results from the df['COLUMN'].value_counts() with something like this: This is a df, with multi-index generated using a for with value.counts() for each column, so what I would like to ...
[ "df_index= df['columnname'].value_counts().idxmax()\n" ]
[ 0 ]
[]
[]
[ "count", "fpdf", "if_statement", "pandas", "python" ]
stackoverflow_0074160699_count_fpdf_if_statement_pandas_python.txt
Q: Fit correctly bar of pie chart in Matplotlib I'm trying to create a bar of pie chart with Matplotlib and I'm having issues to fit the lines that are conected between the data piece that I'm showing in the bar, this is the image (The original code from the documentation in matplolib): Basically I would like some he...
Fit correctly bar of pie chart in Matplotlib
I'm trying to create a bar of pie chart with Matplotlib and I'm having issues to fit the lines that are conected between the data piece that I'm showing in the bar, this is the image (The original code from the documentation in matplolib): Basically I would like some help to set correctly the lines (The code is at the ...
[ "con = ConnectionPatch(xyA=(-width / 2, 0.2), coordsA=ax2.transData,\nxyB=(x, y), coordsB=ax1.transData) #0.2 is the bottom or hight of the line conecting\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "numpy", "pandas", "python" ]
stackoverflow_0074160615_matplotlib_numpy_pandas_python.txt
Q: User prefix, code not working in discord.py rewrite branch Figured it out, i was just missing an return statement def get_prefix(bot, message): if message.author.id == 1: return ["user prefix"] else: return ["default prefix"] A: From what I can tell in your post, you are trying to make a custom...
User prefix, code not working in discord.py rewrite branch
Figured it out, i was just missing an return statement def get_prefix(bot, message): if message.author.id == 1: return ["user prefix"] else: return ["default prefix"]
[ "From what I can tell in your post, you are trying to make a customizable prefix that can be unique to each server? This isn't the only way to do this, but in my bot, I use a json file to add and store all the users prefixes. This is a pretty basic way to do this but it works for my bot the way it is; given it does...
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074204039_discord_discord.py_python.txt
Q: Delete the last four characters in the same field in all documents in mongodb with Python I have the following document structure in mongodb in one collection: Company = { name : Google sector : tech id_number: 12345XYZ5 ... } I need to delete the last four characters of the field id_number (XYZ5)...
Delete the last four characters in the same field in all documents in mongodb with Python
I have the following document structure in mongodb in one collection: Company = { name : Google sector : tech id_number: 12345XYZ5 ... } I need to delete the last four characters of the field id_number (XYZ5) so that this field matches the field of another collection, that I will have to do a lookup. I...
[ "You can use the $substr operator to get the first 4 characters of the id_number field and then use the $set operator to update the id_number field with the new value.\ndb.collection.update_many({}, {'$set': {'id_number': {'$substr': ['$id_number', 0, 4]}}})\n\n" ]
[ 0 ]
[]
[]
[ "mongodb", "python", "python_3.x" ]
stackoverflow_0074239958_mongodb_python_python_3.x.txt
Q: ImportError: cannot import name 'builder' from 'google.protobuf.internal' I am following this video text An error was found in this code, at 22:22 . !python {SCRIPTS_PATH + '/generate_tfrecord.py'} -x {IMAGE_PATH + '/train'} -l {ANNOTATION_PATH + '/label_map.pbtxt'} -o {ANNOTATION_PATH + '/train.record'} !python {...
ImportError: cannot import name 'builder' from 'google.protobuf.internal'
I am following this video text An error was found in this code, at 22:22 . !python {SCRIPTS_PATH + '/generate_tfrecord.py'} -x {IMAGE_PATH + '/train'} -l {ANNOTATION_PATH + '/label_map.pbtxt'} -o {ANNOTATION_PATH + '/train.record'} !python {SCRIPTS_PATH + '/generate_tfrecord.py'} -x{IMAGE_PATH + '/test'} -l {ANNOTATION...
[ "Follow these steps:\n\nInstall the latest protobuf (in my case is 4.21.1)\n\n\npip install protobuf\n\n\nCopy builder.py from ...\\Lib\\site-packages\\google\\protobuf\\internal to your computer (let's say 'Documents')\nInstall protobuf that compatible to your project, for me is 3.19.4\n\n\npip install protobuf==3...
[ 36, 16, 4, 2, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0071759248_python.txt
Q: How do I return class type instead of built-in type when inheriting from built-in class - Python class StringMethods(str): """ StringMethods class: A class inheriting from the built in python 'str' class, but with extended methods for string analysis, password checking etc. """ d...
How do I return class type instead of built-in type when inheriting from built-in class - Python
class StringMethods(str): """ StringMethods class: A class inheriting from the built in python 'str' class, but with extended methods for string analysis, password checking etc. """ def contains(self, char: str) -> bool: """ True if self contains specified char """ ...
[ "Rather than inheriting directly from str, you could inherit from collections.UserString.\nfrom collections import UserString\n\n\nclass StringMethods(UserString):\n\n \"\"\"\n StringMethods class:\n\n A class inheriting from the built in python 'str' class,\n but with extended methods for string analys...
[ 2 ]
[]
[]
[ "class", "inheritance", "python", "string" ]
stackoverflow_0074239512_class_inheritance_python_string.txt
Q: Begin and End in Python blocks I am using Python but the space gap is making my life very hard with it example when I use the if statement if Parm2 == 1: Ch = "A" elif Parm2 == 2: Ch = "B" elif Parm2 == 3: Ch = "C" else: continue mdl = CallFunc(Parm2) print("XX Always Print XX") now the "XX Alway...
Begin and End in Python blocks
I am using Python but the space gap is making my life very hard with it example when I use the if statement if Parm2 == 1: Ch = "A" elif Parm2 == 2: Ch = "B" elif Parm2 == 3: Ch = "C" else: continue mdl = CallFunc(Parm2) print("XX Always Print XX") now the "XX Always Print XX" should be printed regard...
[ "Python is indentation based. Yeah, its harder to read and easier to make mistakes like you indicated, but that's what it is.\n", "Think about downloading an IDE for python, like Pycharm, they are helpful for identifying errors like this one, they also have an \"auto-indent\" feature. But no, Python is indentatio...
[ 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0070538939_python.txt
Q: Formatting negative numbers with math minus (U+2212) instead of hyphen-minus (U+002D) I want to format negative numbers as strings where the minus sign has the same font width of plus sign. With >>> '{}'.format(-2) '-2' the minus sign you get in the resulting string is the character u'\u002d' (I use this website ...
Formatting negative numbers with math minus (U+2212) instead of hyphen-minus (U+002D)
I want to format negative numbers as strings where the minus sign has the same font width of plus sign. With >>> '{}'.format(-2) '-2' the minus sign you get in the resulting string is the character u'\u002d' (I use this website to check character codes), which in many fonts is much narrower and even lower than plus si...
[ "This approach worked for my needs:\nIn:\nnegative = u'\\u2212'\noutput = f\"{negative}{abs(-2)}\"\nprint(output)\nprint('vs.')\nprint(-2)\n\n\nOut:\n−2 vs. -2\nEdit: formatting\n" ]
[ 0 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0071557110_python_string_formatting.txt
Q: Why won't my 2D movement work (Snake Game) I can't for the life of me get the movement of my snake to work. Here is my code: import pygame, sys, random #Functions def player_animation(): global player_speed_x, player_speed_y player.x += player_speed_x player.y += player_speed_y if player.top or ...
Why won't my 2D movement work (Snake Game)
I can't for the life of me get the movement of my snake to work. Here is my code: import pygame, sys, random #Functions def player_animation(): global player_speed_x, player_speed_y player.x += player_speed_x player.y += player_speed_y if player.top or player.left or player.right or player.bottom <=1...
[]
[]
[ "Ignore this post! Figured it out. Just didn't have my player rectangle in my loop so it wouldn't update with they coordinates needed. :)\n" ]
[ -1 ]
[ "2d", "python" ]
stackoverflow_0074239624_2d_python.txt
Q: Pandas: extracting values via regex in 1 column I'm trying to extract some values from 1 column. Some rows have 3 values I want to with different setups. My dataset: col1 0 1001100100 / hello street 2 a town1 1 1001100102 ;hello 3 towns2 2 STRZ19-0072 DT001001-0100 location1 town4 3 1001100103_hel...
Pandas: extracting values via regex in 1 column
I'm trying to extract some values from 1 column. Some rows have 3 values I want to with different setups. My dataset: col1 0 1001100100 / hello street 2 a town1 1 1001100102 ;hello 3 towns2 2 STRZ19-0072 DT001001-0100 location1 town4 3 1001100103_hello street 3, town5 4 DT001002-0100 street 78 5 ...
[ "I'd do it in 3 separate steps:\ndf[\"col2\"] = df[\"col1\"].str.extract(r\"(100\\d{7})\")\ndf[\"col3\"] = df[\"col1\"].str.extract(r\"(DT\\d{6}-\\d{4})\")\ndf[\"col4\"] = df[\"col1\"].str.extract(r\"([A-Za-z][A-Za-z\\d\\s,]+)$\")\nprint(df)\n\nPrints:\n col1 col2 ...
[ 2, 2 ]
[]
[]
[ "extract", "pandas", "python", "regex" ]
stackoverflow_0074239664_extract_pandas_python_regex.txt
Q: Downloading all 10-k filings for SEC EDGAR in python I have currently managed to scrape all filings for a specific ticker eg. 'AAPL' and every type of filing with its link is presented in a massive dictionary. I would like only those links where the 'type':'10-k' and download all the files as HTML files. Have trie...
Downloading all 10-k filings for SEC EDGAR in python
I have currently managed to scrape all filings for a specific ticker eg. 'AAPL' and every type of filing with its link is presented in a massive dictionary. I would like only those links where the 'type':'10-k' and download all the files as HTML files. Have tried to looping over dictionary and appending to list but sti...
[ "Instead of filtering the list of all SEC filings on the client side in your Python code, you can actually filter them directly on the server side. Considering your final objective is to download thousands of 10-K filings filed over many years, and not just Apple's 10-Ks, you're saving yourself a lot of time by fil...
[ 0 ]
[]
[]
[ "edgar", "python" ]
stackoverflow_0074225258_edgar_python.txt
Q: Convert string serialized version of python bytes back to bytes I have a byte string stored as a regular string. For example: byte_str = "b'moose'" Would like to convert this to a python bytes object. What is the best way? Thanks! A: Use ast.literal_eval. For example: from ast import literal_eval byte_str = "b'...
Convert string serialized version of python bytes back to bytes
I have a byte string stored as a regular string. For example: byte_str = "b'moose'" Would like to convert this to a python bytes object. What is the best way? Thanks!
[ "Use ast.literal_eval. For example:\nfrom ast import literal_eval\n\nbyte_str = \"b'moose'\"\nprint(byte_str)\n# \"b'moose'\"\nactual_bytes = literal_eval(byte_str)\nprint(actual_bytes)\n# b'moose'\n\n" ]
[ 1 ]
[]
[]
[ "byte", "python" ]
stackoverflow_0074239981_byte_python.txt
Q: Walrus to unpack values within a list comprehension I have a nested list holding dictionaries as mapping table using a tuple as key. I am struggling to zip the dictionary together so it can be exported by Pandas to csv file: l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}] def dynDictCombiner(item): # ...
Walrus to unpack values within a list comprehension
I have a nested list holding dictionaries as mapping table using a tuple as key. I am struggling to zip the dictionary together so it can be exported by Pandas to csv file: l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}] def dynDictCombiner(item): # would lambda be faster? def _combine(item): ...
[ "You don't need a walrus operator for this:\nl = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]\n\noutput= [{'start': start, 'stop': stop, 'value': value}\n for dct in l\n for (start, stop), value in dct.items()]\n\nprint(output)\n# [{'start': 'A', 'stop': 'B', 'value': 1},\n# {'start': 'A', '...
[ 2, 1 ]
[]
[]
[ "python", "python_3.x", "python_assignment_expression" ]
stackoverflow_0074239647_python_python_3.x_python_assignment_expression.txt
Q: Get python list index out of range I'm trying to create over flowing pythonic list meaning that if i'm trying to get the index of list even if the index is larger then then the list size. if the index is bigger then the list size I want to get the index from the start of the list. for example if the list size is 5...
Get python list index out of range
I'm trying to create over flowing pythonic list meaning that if i'm trying to get the index of list even if the index is larger then then the list size. if the index is bigger then the list size I want to get the index from the start of the list. for example if the list size is 5 l = [1,2,3,4,5] so l[7] should return...
[ "Your question is not clear:\nsuppose:\nl = [1,2,3,4,5]\n\nl[0] is 1\nl[1] is 2\nand so on...\n\nYou can do a forloop to print all the values:\nfor x in range(len(l)):\n print(l[x])\n\nNow if you want to plug in large values in x you can use mod operator %\nl[x%len(l)]\n\nhere x can be any large number.\nwhen x=7...
[ 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074239696_list_python.txt
Q: Can't serve Django static files with NGINX I'm trying to deploy a Django and React website using gunicorn, nginx and docker. I can't get nginx to read my static files for example the django admin panel. I already ran python manage.py collecstatic and the files are in recommendations-be/backend/static Here is the d...
Can't serve Django static files with NGINX
I'm trying to deploy a Django and React website using gunicorn, nginx and docker. I can't get nginx to read my static files for example the django admin panel. I already ran python manage.py collecstatic and the files are in recommendations-be/backend/static Here is the docker-compose.yml file: version: '3' services: ...
[ "In your nginx configuration, please make the following change:\nlocation /static/ {\n alias /static/\n}\n\nThen, in your docker-compose.yml file, in the volume definitions of Nginx, please replace the line\n- static:/django/backend/static\n\nwith the following:\n- static:/static\n\nNginx should now be able to s...
[ 0 ]
[]
[]
[ "django", "docker", "gunicorn", "nginx", "python" ]
stackoverflow_0074125886_django_docker_gunicorn_nginx_python.txt
Q: How to group ohlc minute data by day? I have a bunch of minute data like so: index timestamp open high low ... trade_count vwap symbol cum_volume cum_volume_25k 0 2021-11-02 13:30:00+00:00 2021-11-02 13:30:00+00:00 12.000 12.055 12.00 ... ...
How to group ohlc minute data by day?
I have a bunch of minute data like so: index timestamp open high low ... trade_count vwap symbol cum_volume cum_volume_25k 0 2021-11-02 13:30:00+00:00 2021-11-02 13:30:00+00:00 12.000 12.055 12.00 ... 62 12.003693 AMCR 47208 ...
[ "Given (I changed timestamps for more variety):\n timestamp open high low symbol\n0 2021-11-02 13:30:00+00:00 12.000 12.055 12.00 AMCR\n1 2021-11-02 13:31:00+00:00 12.040 12.070 12.04 AMCR\n2 2021-11-08 13:32:00+00:00 12.050 12.050 12.03 YETI\n3 2021-11-03 13:33:00+...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074239724_numpy_pandas_python.txt
Q: How do I specify the a specific dummy variable with SymPy Integration I was trying to run a SymPy integration where I created my own variables, and the integral is import numpy as np import seaborn import math import pandas as pd import matplotlib as plt import scipy.integrate as integrate import scipy.special as ...
How do I specify the a specific dummy variable with SymPy Integration
I was trying to run a SymPy integration where I created my own variables, and the integral is import numpy as np import seaborn import math import pandas as pd import matplotlib as plt import scipy.integrate as integrate import scipy.special as special from sympy import init_session init_session() %matplotlib inline ...
[ "You wrote the wrong integrate command. For a definite integral it should be like this: integrate(expr, (symbol, lower, upper)). Assuming r is the integration variable, your example will be:\nr_int = integrate(cc, (r, 0, R))\n\n" ]
[ 1 ]
[]
[]
[ "integral", "python", "sympy" ]
stackoverflow_0074234274_integral_python_sympy.txt
Q: PanelOLS failing with timestamp in hierarchical MultiIndex I would like to run PanelOLS on the data resembling the extract provided below: import pandas as pd from io import StringIO from datetime import datetime from linearmodels import PanelOLS import statsmodels.api as sm TESTDATA = StringIO( """EventDate;...
PanelOLS failing with timestamp in hierarchical MultiIndex
I would like to run PanelOLS on the data resembling the extract provided below: import pandas as pd from io import StringIO from datetime import datetime from linearmodels import PanelOLS import statsmodels.api as sm TESTDATA = StringIO( """EventDate;SomeGroup;DepVal;Measure1;Measure2;Measure3 1/1/2020;A;99;78...
[ "It seems that the issue is with a creation of MultiIndex passing columns names so the dated column is second solves the issue:\ndf = pd.read_csv(\n TESTDATA,\n sep=\";\",\n parse_dates=[\"EventDate\"],\n date_parser=convert_date,\n skipinitialspace=True,\n index_col=['SomeGroup', 'EventDate']\n)\...
[ 0 ]
[]
[]
[ "linearmodels", "multi_index", "pandas", "python" ]
stackoverflow_0074239951_linearmodels_multi_index_pandas_python.txt
Q: How ti create looping task to run multiple time in Airflow? I need to do this: for i in range(5): step1 = PythonOperator( .... ) #dependencies step1 >> step1 >> step1 >> step1 >> step1 A: If you want task i to depend on task i-1, here is a simple solution that keeps a reference to the previous task a...
How ti create looping task to run multiple time in Airflow?
I need to do this: for i in range(5): step1 = PythonOperator( .... ) #dependencies step1 >> step1 >> step1 >> step1 >> step1
[ "If you want task i to depend on task i-1, here is a simple solution that keeps a reference to the previous task and uses it to set the dependency for the current task:\ndef job(i):\n print(f\"Executing task {i}\")\n\nwith DAG(\n \"SO_74208401\",\n start_date=datetime.now() - timedelta(days = 2),\n sche...
[ 0 ]
[]
[]
[ "airflow", "dependencies", "for_loop", "loops", "python" ]
stackoverflow_0074208401_airflow_dependencies_for_loop_loops_python.txt
Q: Launching an excel file with os.system() won't work properly I am having issues with opening an Excel file from Jupyter Notebooks on my Mac. I previously saved it to my cloud. To create the Excel, I copy my df to Excel and save it. So far so good. path = '/Users/username/name.xlsx' writer = pd.ExcelWriter(path, ...
Launching an excel file with os.system() won't work properly
I am having issues with opening an Excel file from Jupyter Notebooks on my Mac. I previously saved it to my cloud. To create the Excel, I copy my df to Excel and save it. So far so good. path = '/Users/username/name.xlsx' writer = pd.ExcelWriter(path, engine = 'xlsxwriter') df.to_excel(write...
[ "Have you tried this:\nimport os\nos.system(\"start EXCEL.EXE path\")\n\nIf that dosn't work try yo use this Use Python to launch Excel file\nas help :)\n", "You need to pass the Python string stored in path as a value into the shell system in a form it will use.\nAn option is to use f-strings to do that:\nimpor...
[ 0, 0 ]
[]
[]
[ "excel", "jupyter_notebook", "python" ]
stackoverflow_0074235136_excel_jupyter_notebook_python.txt
Q: Looking for any key pressed down except for a specified key in pygame I'm working on a game where the player can do two things: move (spacebar) and show their score (any other key). I currently have this piece of code, which only checks for the A key, but I'd like it to activate when any key is pressed, except for...
Looking for any key pressed down except for a specified key in pygame
I'm working on a game where the player can do two things: move (spacebar) and show their score (any other key). I currently have this piece of code, which only checks for the A key, but I'd like it to activate when any key is pressed, except for the spacebar (including space would interfere with the movement) if pygame...
[ "The answer lies in your question:\n\nI want an if statement that is True when any key is pressed except for space.\n\nkeys = pygame.key.get_pressed()\nif any(key) and not key[pygame.K_SPACE]:\n print(\"score visible\")\n\n" ]
[ 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074238948_pygame_python.txt
Q: Losing some samples while writing to file in Python I'm continuosly getting readings from an ADC in Python, but during the process of writing it to a file, I lose some samples because there is some small delay. Is there a way I could avoid losing these samples (I'm sampling at 100Hz)? I'm using multithreading, but...
Losing some samples while writing to file in Python
I'm continuosly getting readings from an ADC in Python, but during the process of writing it to a file, I lose some samples because there is some small delay. Is there a way I could avoid losing these samples (I'm sampling at 100Hz)? I'm using multithreading, but in the process of writing and cleaning the list used to ...
[ "At a 100Hz, I have to wonder if the write operation really takes longer than 10ms. You could probably do both operations in the same loop and just collect data in a buffer and write it (about 6000 values) once every 60 seconds without incurring more than a few milliseconds delay:\nimport time\nimport ADS1256\nimpo...
[ 1 ]
[]
[]
[ "multithreading", "python", "sampling" ]
stackoverflow_0074240152_multithreading_python_sampling.txt
Q: Generic way to drop columns that are not needed for learning (in python using pandas df) By generic; I mean to say that I do not know the name of a column that needs to be dropped ahead of pulling in the file. Examples I have found; assume that you know the name of a column you wish to drop. Those familiar with th...
Generic way to drop columns that are not needed for learning (in python using pandas df)
By generic; I mean to say that I do not know the name of a column that needs to be dropped ahead of pulling in the file. Examples I have found; assume that you know the name of a column you wish to drop. Those familiar with the PlayTennis data set are probably used to seeing: my_df = pd.DataFrame({"Outlook": [Sunny,Clo...
[ "When you load the data, e.g. with pd.read_csv, you can only load the columns you want with argument usecols=[list-of-columns-i-care-about]. That way you don't need to drop them.\n", "First thing, it was not quite obvious why you want to drop Days column in your dataset.\nI assume that you want to drop a feature ...
[ 1, 1, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074240015_numpy_pandas_python.txt
Q: convert dataframe column into int so can sort and do calulations on the column values I have a dataframe row as such like below a | b | c | d 1 |-700.5;-1000.0;200.0| yes | blue I want to change column b to be numeric so I can do data work like sorting on it but when I try the belo...
convert dataframe column into int so can sort and do calulations on the column values
I have a dataframe row as such like below a | b | c | d 1 |-700.5;-1000.0;200.0| yes | blue I want to change column b to be numeric so I can do data work like sorting on it but when I try the below code df= pd.to_numeric(df["b"]) print(df) Get error ValueError: Unable to parse string o...
[ "Maybe you are looking for something like this:\ndf.assign(b = df.b.str.split(';')).explode('b')\n\nOutput:\n a b c d\n0 1 -700.5 yes blue\n0 1 -1000.0 yes blue\n0 1 200.0 yes blue\n\n", "if you need that in the same column?\nhere is one way to do it\n# split, and sort then join bac...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074225918_dataframe_pandas_python.txt
Q: Why does my pygame game get slower over time? I'm making a pygame project, but for some reason my game slows down slowly: after playing for a few minutes the fps is only 10 instead of 26 (normal). My task manager says it constantly uses 0.4% of my memory (16GB RAM), the use doesn't increase so probably there is no...
Why does my pygame game get slower over time?
I'm making a pygame project, but for some reason my game slows down slowly: after playing for a few minutes the fps is only 10 instead of 26 (normal). My task manager says it constantly uses 0.4% of my memory (16GB RAM), the use doesn't increase so probably there is no memory leak (btw: the cpu usage is a lot though: 2...
[ "It is very likely that over time you add more and more objects to a container (list or pygame.sprite.Group) but never remove them. The more objects are in the container the slower the game becomes. Do you shoot bullets, but do not remove them when they are outside the window bounds? Do you spawn enemies and consta...
[ 0 ]
[]
[]
[ "frame_rate", "pygame", "python" ]
stackoverflow_0074170385_frame_rate_pygame_python.txt
Q: Converting all elements of a nested list of strings (wich contains another nested list) to a nested list of integers I have a function that opens a text file and return me a x nested list of strings, I want to convert all elements to integers, but inside x there is another nested list: This is x: [ ['7', '1'],...
Converting all elements of a nested list of strings (wich contains another nested list) to a nested list of integers
I have a function that opens a text file and return me a x nested list of strings, I want to convert all elements to integers, but inside x there is another nested list: This is x: [ ['7', '1'], ['1', '6', '4', '1'], ['2', '1', '0', '0'], [ ['1', '0', '4', '5'], ['9', '3', '0', '7'],...
[ "The problem is that you can apply the map function to a list of strings, but not to a list of lists. You can, however, do this by recursion:\nl = [['7', '1'], ['1', '6', '4', '1'], ['2', '1', '0', '0'], \n [['1', '0', '4', '5'], ['9', '3', '0', '7'], ['0', '1', '2', '0']], \n [['8', '0', '2', '6'], ['6', '3'...
[ 0, 0 ]
[]
[]
[ "arrays", "nested", "python" ]
stackoverflow_0074240253_arrays_nested_python.txt
Q: Id like to use my return value from a selection method as the value in my main function I want to use the odds assigned to subclasses in the callplay() function on the line "result =" etc... having a hard time with the syntax def phil_choice(): print('1) Balanced\n2) Run Heavy\n3) Pass Heavy') philo_choice...
Id like to use my return value from a selection method as the value in my main function
I want to use the odds assigned to subclasses in the callplay() function on the line "result =" etc... having a hard time with the syntax def phil_choice(): print('1) Balanced\n2) Run Heavy\n3) Pass Heavy') philo_choice = input('Select a coaching style: ') if philo_choice == '1': print('') ...
[ "Your example was missing some initial definitions of down, distance, yards to go, and so forth, so adding in some sample values, following is a snippet of code that sets up a \"main\" function which calls your helper functions.\nimport random\n\n# Needed to define these in order to get the program to run\n\nbalanc...
[ 0 ]
[]
[]
[ "methods", "python", "return_value", "subclass" ]
stackoverflow_0074239903_methods_python_return_value_subclass.txt
Q: Ansible dynamic inventory script does not get evaluated I have a custom python script that generates an inventory compatible with Ansible: ... if __name__ == "__main__": with open("main.log", "a") as f: f.write(f"{sys.argv}\n") arg_parser = argparse.ArgumentParser(description=__doc__, prog=__file...
Ansible dynamic inventory script does not get evaluated
I have a custom python script that generates an inventory compatible with Ansible: ... if __name__ == "__main__": with open("main.log", "a") as f: f.write(f"{sys.argv}\n") arg_parser = argparse.ArgumentParser(description=__doc__, prog=__file__) ... When I run it manually, everything is fine: python s...
[ "I simply forgot to put the correct shebang at the top of the script:\n#!/usr/bin/env python3\n\nand grant execute right to the script:\nchmod +x scripts/main.py\n\n" ]
[ 0 ]
[]
[]
[ "ansible", "ansible_inventory", "python" ]
stackoverflow_0074237606_ansible_ansible_inventory_python.txt
Q: Could not convert string to float error in pyhton heres the code #l is a list that stores all the GPAs of 10 students l = [] #iterates the loop to collect GPAs of 10 members in the class for i in range(1, 11): j = int(float(input())) #this is where the error is l.append(j) #find the average GPA of the class...
Could not convert string to float error in pyhton
heres the code #l is a list that stores all the GPAs of 10 students l = [] #iterates the loop to collect GPAs of 10 members in the class for i in range(1, 11): j = int(float(input())) #this is where the error is l.append(j) #find the average GPA of the class and store the average in the "result" variable result ...
[ "I ran your code, it works without any problem!\nYou have to give each value in the terminal and press enter.\n", "Why you need to convert that input to float ? All you need is check the input that can be convert to int with try and expect then when you Division a number every time you getting floating point num...
[ 0, 0, 0 ]
[]
[]
[ "append", "list", "python", "python_3.x" ]
stackoverflow_0074239778_append_list_python_python_3.x.txt
Q: How do You simulate Requests using Already placed Json Data with python/flask New to this, How do you simulate a HTTP Request with data which is already json and send it thru requests in python. I am trying to do it and its telling me, JSON Not serializable. these are the lines of code which I am using @app.route(...
How do You simulate Requests using Already placed Json Data with python/flask
New to this, How do you simulate a HTTP Request with data which is already json and send it thru requests in python. I am trying to do it and its telling me, JSON Not serializable. these are the lines of code which I am using @app.route('/api/create-virtual-account',methods=['POST']) @jwt_required() def create_virtual_...
[ "Instead of using res.content use res.json(). .json() method will parse the Json response to Python objects so you can use jsonify() method without error:\n...\n\nreturn jsonify({'result':res.json()}),200\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074240258_python_python_requests.txt
Q: find which polygon lat/lon fall within (in python) Is there any way do do something similar in python what I had been doing in R? library(maps) library(rgdal) mp = 'gadm41_USA_shp' #from gadm.org mp = rgdal::readOGR(mp) mymap = maps::SpatialPolygons2map(mp, namefield="ISO_1") map.where(mymap, y = 40.725959, x = -7...
find which polygon lat/lon fall within (in python)
Is there any way do do something similar in python what I had been doing in R? library(maps) library(rgdal) mp = 'gadm41_USA_shp' #from gadm.org mp = rgdal::readOGR(mp) mymap = maps::SpatialPolygons2map(mp, namefield="ISO_1") map.where(mymap, y = 40.725959, x = -73.978544) #[1] "US-NY:88" Link to shapefile: https://ge...
[ "import geopandas as gpd\nfrom shapely.geometry import Point, Polygon, GeometryCollection, Polygon, mapping\n\n\nshp = gpd.read_file('gadm41_USA_1.shp')\npt = Point(-73.978544, 40.725959)\n\nprint(shp.loc[shp['geometry'].contains(pt), 'ISO_1'])\n\n32 US-NY\nName: ISO_1, dtype: object\n\n" ]
[ 2 ]
[]
[]
[ "geopandas", "python", "shapefile" ]
stackoverflow_0074238260_geopandas_python_shapefile.txt
Q: Python: How can I divide a number completely by 2 and 3 and return -1 if not possible I want to make a function where given a number like 7 I want to factorise the number by as many 3s and 2s. If left with a remainder then return -1. Note: Through further examples it seems any number can be made up of the addition...
Python: How can I divide a number completely by 2 and 3 and return -1 if not possible
I want to make a function where given a number like 7 I want to factorise the number by as many 3s and 2s. If left with a remainder then return -1. Note: Through further examples it seems any number can be made up of the addition of multiples of 3s and 2s so -1 for remainder not needed. Goal is to get as many multiples...
[ "Try this method using math.floor()\nimport math\n\n\ndef get_components(n: int) -> str:\n q3 = math.floor(n / 3)\n q2 = math.floor(q3 / 2)\n if not (q3 and q2):\n return '-1' # returning '-1' as a string here for consistency\n return f'3:{q3}, 2:{q2}'\n\n", "This will return 0 if you can comp...
[ 0, 0, 0 ]
[]
[]
[ "algorithm", "function", "math", "python" ]
stackoverflow_0074239361_algorithm_function_math_python.txt
Q: Way to fix "missing QuerySet" and "override QuerySet" with Django I'm trying to code a blog with django but I want to add a placeholder to my form when creating or editing an article. So I had the forms.py because before that I wasn't using a form from this file because I only needed the models.py file. I fount a ...
Way to fix "missing QuerySet" and "override QuerySet" with Django
I'm trying to code a blog with django but I want to add a placeholder to my form when creating or editing an article. So I had the forms.py because before that I wasn't using a form from this file because I only needed the models.py file. I fount a way to do what I wanted and so add my placeholder into my input from my...
[ "class BlogPostCreate(CreateView):\n form_class = UpdatePostForm\n template_name = 'update_post.html'\n success_url = 'success'\n\nOR\nclass BlogPostCreate(CreateView):\n model = UpdatePost\n\nTry the above. Please remove @method_decorator(login_required, name='dispatch') from this class view because i...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074240285_django_django_forms_django_models_django_views_python.txt
Q: Pandas: how to explode a row of list elements into their own separate columns I have a Pandas dataframe that looks like this: import pandas as pd data = { 'a' : [['Foo', 49.51, -120.69], ['Foo', 49.51, -120.69], ['Foo', 49.51, -120.69], ['Foo', 49.51, -120.69]], 'b' : [['YLK', 44.48, -79.55], ['HG76', 44.60, -65...
Pandas: how to explode a row of list elements into their own separate columns
I have a Pandas dataframe that looks like this: import pandas as pd data = { 'a' : [['Foo', 49.51, -120.69], ['Foo', 49.51, -120.69], ['Foo', 49.51, -120.69], ['Foo', 49.51, -120.69]], 'b' : [['YLK', 44.48, -79.55], ['HG76', 44.60, -65.76], ['DEF', 49.52, -113.99], ['YXZ', 47.96, -84.78]], 'c' : [1628.931942, 1949.74...
[ "You can do DataFrame call\ndf = df.join(pd.DataFrame(df.pop('a').tolist(),index = df.index))\nOut[215]: \n b c 0 1 2\n0 [YLK, 44.48, -79.55] 1628.931942 Foo 49.51 -120.69\n1 [HG76, 44.6, -65.76] 1949.748061 Foo 49.51 -120.69\n2 [DEF, 49.52, -113.99] 2556.6...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074239961_pandas_python.txt
Q: python regex to substitute all digits except when they are part of a substring I want to remove all digits, except if the digits make up one of the special substrings. In the example below, my special substring that should skip the digit removal are 1s, 2s, s4, 3s. I think I need to use a negative lookahead s = "a...
python regex to substitute all digits except when they are part of a substring
I want to remove all digits, except if the digits make up one of the special substrings. In the example below, my special substring that should skip the digit removal are 1s, 2s, s4, 3s. I think I need to use a negative lookahead s = "a61s8sa92s3s3as4s4af3s" pattern = r"(?!1s|2s|s4|3s)[0-9\.]" re.sub(pattern, ' ', s) ...
[ "You can use\nimport re\ns = \"a61s8sa92s3s3as4s4af3s\"\npattern = r\"(1s|2s|s4|3s)|[\\d.]\"\nprint( re.sub(pattern, lambda x: x.group(1) or ' ', s) )\n# => a 1s sa 2s3s as4s4af3s\n\nSee the Python demo.\nDetails:\n\n(1s|2s|s4|3s) - Group 1: 1s, 2s, s4 or 3s\n| - or\n[\\d.] - a digit or dot.\n\nIf Group 1 matches, ...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074240336_python_regex.txt
Q: Django installation failed My pc recently started giving error in installing Django.... Look at the error message, what could be the cause please? I tried installing Django for my project, and it just throw an unexpected error message. I have the right Venv activation code so I expected it to work. A: This coul...
Django installation failed
My pc recently started giving error in installing Django.... Look at the error message, what could be the cause please? I tried installing Django for my project, and it just throw an unexpected error message. I have the right Venv activation code so I expected it to work.
[ "This could be due to a weak internet connection, i.e it takes time to download, or slow internet connection. Check your internet speed and try again. If it still persists, on your virtual env try to install it manually, you can use this video as a guide here.\n" ]
[ 0 ]
[]
[]
[ "django", "pip", "python" ]
stackoverflow_0074240239_django_pip_python.txt
Q: How to log all sql queries in Django? How can I log all SQL queries that my django application performed? I want to log everything, including SQLs from admin site. I saw this question and a FAQ answer but I still can't figure out where should I put from django.db import connection connection.queries to log every...
How to log all sql queries in Django?
How can I log all SQL queries that my django application performed? I want to log everything, including SQLs from admin site. I saw this question and a FAQ answer but I still can't figure out where should I put from django.db import connection connection.queries to log everything to one file? So my question is - what...
[ "Merge the following snippet with the LOGGING field in your settings.py:\nLOGGING = {\n 'version': 1,\n 'filters': {\n 'require_debug_true': {\n '()': 'django.utils.log.RequireDebugTrue',\n }\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n ...
[ 231, 56, 23, 22, 15, 2, 0, 0 ]
[ "Actually, it's impossible to log all SQL queries in Django as far as I know. So, to log all SQL queries, you need to use the databases themselves which your Django Project use.\nFor example, in Django, trying to log all the SQL queries from Django Admin which uses atomic transaction queries \"BEGIN\" and \"COMMIT\...
[ -1 ]
[ "django", "django_database", "logging", "python", "sql" ]
stackoverflow_0004375784_django_django_database_logging_python_sql.txt
Q: monitor chrome tabs - python selenium I'm writing a script where I need you to monitor the number of open tabs. The script reads a table and each information in the table opens a new tab in the browser. It turns out that in order not to have thousands of tabs open, I need the script to monitor the tabs to have onl...
monitor chrome tabs - python selenium
I'm writing a script where I need you to monitor the number of open tabs. The script reads a table and each information in the table opens a new tab in the browser. It turns out that in order not to have thousands of tabs open, I need the script to monitor the tabs to have only 3 open, when I close a tab I need to auto...
[ "To do this, just add a loop that monitors the guides, it can be as follows:\nwhile len(self.chrome.window_handles) > 3:\n time.sleep(0.5)\n\nwithout your code:\ndef base_dados_processos(self):\n try:\n df = pd.read_excel('TABLE.xlsx')\n self.num_proc = df['COLUM']\n except Exception:...
[ 1 ]
[]
[]
[ "python", "python_3.x", "selenium_webdriver" ]
stackoverflow_0068247812_python_python_3.x_selenium_webdriver.txt
Q: Best way to 'intelligently' reset memoized property values in Python when dependencies change I'm writing a class with various attributes that I only want to calculate when necessary (lazy evaluation). However, more importantly, I want to make sure that 'stale' values are not returned if any of the attributes tha...
Best way to 'intelligently' reset memoized property values in Python when dependencies change
I'm writing a class with various attributes that I only want to calculate when necessary (lazy evaluation). However, more importantly, I want to make sure that 'stale' values are not returned if any of the attributes that their calculation depended on changed. Other than implementing some kind of computation graph (i...
[ "Here is a solution:\nfrom math import pi\n\nclass Cylinder:\n _independent = {\"length\", \"radius\", \"density\"}\n _dependent = {\"volume\", \"mass\"}\n\n def __init__(self, radius, length, density):\n self._radius = radius\n self._length = length\n self._density = density\n ...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "getattribute", "lazy_evaluation", "memoization", "properties", "python" ]
stackoverflow_0057439169_getattribute_lazy_evaluation_memoization_properties_python.txt
Q: Logical math operations I need to write a recursive function that applies the following operations: If a = 0 or b = 0, return [a, b]. Otherwise, go to step (2); If a >= 2b, set a = a - 2b, and repeat step (1). Otherwise, go to step (3); If b >= 2a, set b = b - 2a, and repeat step (1). Otherwise, return [a, b]. S...
Logical math operations
I need to write a recursive function that applies the following operations: If a = 0 or b = 0, return [a, b]. Otherwise, go to step (2); If a >= 2b, set a = a - 2b, and repeat step (1). Otherwise, go to step (3); If b >= 2a, set b = b - 2a, and repeat step (1). Otherwise, return [a, b]. Some examples of what I want t...
[ "This is the recursive function you need:\ndef f(a, b):\n if a == 0 or b == 0: # step 1\n return [a, b]\n\n if a >= 2 * b: # step 2\n a = a - 2 * b\n return f(a, b) # recursive call\n \n if b >= 2 * a: # step 3\n b = b - 2 * a\n return f(a, b) # recursive call\n\n ...
[ 3, 1 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074240394_python_recursion.txt
Q: Plot secondary axis with scale that is only related by index in the array to parent axis in matplotlib Lets say I have: x1 = [1,2,3,4,5,6,7,8,9,10]; x2 = [1,3,10,60,500,10000,70000,500000,1000000,10000000]; y =[1,2,3,4,5,6,7,8,9,10] With matplotlib, how do I add x2 as a secondary axes (x1,y is the primary plot) w...
Plot secondary axis with scale that is only related by index in the array to parent axis in matplotlib
Lets say I have: x1 = [1,2,3,4,5,6,7,8,9,10]; x2 = [1,3,10,60,500,10000,70000,500000,1000000,10000000]; y =[1,2,3,4,5,6,7,8,9,10] With matplotlib, how do I add x2 as a secondary axes (x1,y is the primary plot) when the only direct correlation between x1 and x2 is the index of the array? As in, there is no function to ...
[ "From what I understand, you want the ticks of the top axis to align with the ticks at the bottom axis. For this, you need to define the amount of ticks on each axis and ensure they are the same. This is easily done by modifying the set_xticks() method for the ax object. Here is an example below\nimport numpy as np...
[ 1 ]
[]
[]
[ "axis", "matplotlib", "python" ]
stackoverflow_0074240122_axis_matplotlib_python.txt
Q: cv2.error: opencv(4.5.3) :-1: error: (-5:bad argument) in function 'resize' import numpy as np import cv2 import pickle ########### PARAMETERS ############## width = 640 height = 480 threshold = 0.65 # MINIMUM PROBABILITY TO CLASSIFY cameraNo = 1 ##################################### #### CREATE CAMERA OBJECT ca...
cv2.error: opencv(4.5.3) :-1: error: (-5:bad argument) in function 'resize'
import numpy as np import cv2 import pickle ########### PARAMETERS ############## width = 640 height = 480 threshold = 0.65 # MINIMUM PROBABILITY TO CLASSIFY cameraNo = 1 ##################################### #### CREATE CAMERA OBJECT cap = cv2.VideoCapture(cameraNo) cap.set(3,width) cap.set(4,height) #### LOAD THE ...
[ "You should release your \"cap\" end of the code below, out of while loop.\n if probVal> threshold:\n cv2.putText(imgOriginal,str(classIndex) + \" \"+str(probVal),\n (50,50),cv2.FONT_HERSHEY_COMPLEX,\n 1,(0,0,255),1)\n\n cv2.imshow(\"Original Image\",imgOriginal...
[ 0 ]
[ "Set the cameraNo as 0. It usually occurs because the camera number of your laptop's or PC's default webcam is 0.\n" ]
[ -1 ]
[ "image", "image_resizing", "opencv", "python" ]
stackoverflow_0068444848_image_image_resizing_opencv_python.txt