content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How can I reduce time complexity on this algorithm? I have this exercise and the goal is to solve it with complexity less than O(n^2). You have an array with length N filled with event probabilities. Create another array in which for each element i calculate the probability of all event to happen until the positio...
How can I reduce time complexity on this algorithm?
I have this exercise and the goal is to solve it with complexity less than O(n^2). You have an array with length N filled with event probabilities. Create another array in which for each element i calculate the probability of all event to happen until the position i. I have coded this O(n^2) solution. Any ideas how to ...
[ "probabilityTable = [0.1, 0.54, 0.34, 0.11, 0.55, 0.75, 0.01, 0.06, 0.96]\n\nfinalTable = probabilityTable.copy()\n\nfor i in range(1, len(probabilityTable)):\n finalTable[i] = finalTable[i] * finalTable[i - 1]\n\nfor item in finalTable:\n print(item)\n\n" ]
[ -1 ]
[ "new_probs = [probabilityTable[0]]\nfor prob in probabilityTable[1:]:\n new_probs.append(new_probs[-1] + prob)\n\n" ]
[ -1 ]
[ "algorithm", "complexity_theory", "python", "time_complexity" ]
stackoverflow_0074210413_algorithm_complexity_theory_python_time_complexity.txt
Q: Pycharm Error - 'pip' is not an internal or external command nor is it a running program or batch file I can use the "pip" in cmd, but when I use "pip" or "python" in the PyCharm terminal the error appears: pip is not an internal or external command nor is it a running program or batch file. But when I check the ...
Pycharm Error - 'pip' is not an internal or external command nor is it a running program or batch file
I can use the "pip" in cmd, but when I use "pip" or "python" in the PyCharm terminal the error appears: pip is not an internal or external command nor is it a running program or batch file. But when I check the Interpreter, pip is exists.
[ "I had this problem also, but only for one of my projects. I was able to resolve it by removing my venv and creating a new one.\nPreferences > Project > Python Interpreter > Add Python Interpreter (\"Show All\" from dropdown, then \"+\" icon) > Virtualenv Environment > New Environment.\n" ]
[ 0 ]
[]
[]
[ "anaconda", "pip", "pycharm", "python", "python_3.x" ]
stackoverflow_0048533269_anaconda_pip_pycharm_python_python_3.x.txt
Q: ModuleNotFoundError on virtual environment After installing miniconda, my python modules stopped working, throwing ModuleNotFoundError. From what I can tell, miniconda changed my default environment settings. I checked both .bash_profile and .bashrc and updated the files to give conda the lowest priority. This fix...
ModuleNotFoundError on virtual environment
After installing miniconda, my python modules stopped working, throwing ModuleNotFoundError. From what I can tell, miniconda changed my default environment settings. I checked both .bash_profile and .bashrc and updated the files to give conda the lowest priority. This fixed my default python version but didn't fix any ...
[ "Sounds like you only want to use conda when you explicitly need it, in other words, the default Python is the system Python.\nIf that's the case, you should disable the auto-activation of the base environment:\nconda config --set auto_activate_base false\n\n<restart shell>\n\nNow you'll need to explicitly activate...
[ 1 ]
[]
[]
[ "path", "python", "python_3.x" ]
stackoverflow_0074212361_path_python_python_3.x.txt
Q: Asyncio RuntimeError: Event Loop is Closed I'm trying to make a bunch of requests (~1000) using Asyncio and the aiohttp library, but I am running into a problem that I can't find much info on. When I run this code with 10 urls, it runs just fine. When I run it with 100+ urls, it breaks and gives me RuntimeError: E...
Asyncio RuntimeError: Event Loop is Closed
I'm trying to make a bunch of requests (~1000) using Asyncio and the aiohttp library, but I am running into a problem that I can't find much info on. When I run this code with 10 urls, it runs just fine. When I run it with 100+ urls, it breaks and gives me RuntimeError: Event loop is closed error. import asyncio import...
[ "The bug is filed as https://github.com/python/asyncio/issues/258 \nStay tuned.\nAs quick workaround I suggest using custom executor, e.g.\nloop = asyncio.get_event_loop()\nexecutor = concurrent.futures.ThreadPoolExecutor(5)\nloop.set_default_executor(executor)\n\nBefore finishing your program please do\nexecutor.s...
[ 18, 7, 0 ]
[]
[]
[ "aiohttp", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0032598231_aiohttp_python_python_3.x_python_asyncio.txt
Q: How to silence child Process stdout and stderr? def f(x) : ....do something.. ....many print statements.... quit() a = Process(target=f, args=1) a.start() ....main process also has many print statement.... How to silence all print statements and error statements from the new spawned function f withou...
How to silence child Process stdout and stderr?
def f(x) : ....do something.. ....many print statements.... quit() a = Process(target=f, args=1) a.start() ....main process also has many print statement.... How to silence all print statements and error statements from the new spawned function f without silencing the stdout of main function? Furthermore,...
[ "I'd suggest to use redirect_stdout and redirect_stderr from the contextlib library in order to redirect all the output from the function running in a child process. First, make a decorator factory redirect_output that you then apply to your target functions passing a filename, where you want the stdout and stderr ...
[ 1 ]
[]
[]
[ "multiprocessing", "process", "python", "stdout" ]
stackoverflow_0074210786_multiprocessing_process_python_stdout.txt
Q: How to check if a value is None and save to another variable only if it is not None in Python The following piece of code works fine. a = 2.0 b = int(a) And b is 2. But the following does not work: a = None b = int(a) I get the following error: TypeError: int() argument must be a string, a bytes-like object or ...
How to check if a value is None and save to another variable only if it is not None in Python
The following piece of code works fine. a = 2.0 b = int(a) And b is 2. But the following does not work: a = None b = int(a) I get the following error: TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType' This works: a = None if a != None: b = int(a) else: b = 0 B...
[ "If you need to try this a bunch of times, you could make a very small function with a try:...except:... block.\ndef try_int(v):\n try:\n return int(v)\n except TypeError:\n return 0\n\na = 2\nb = try_int(a) # should return 2\nc = None\nd = try_int(c) # should return 0\n\nThis solution sticks to...
[ 3, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074212647_python_python_3.x.txt
Q: Python: Convert A string of formula to lambda function I have a string of formula lets said: str1='(0.5-0.70*x0[0])**2+(0.5-0.70*x0[1])**2' how can I pass it into lambda function fn Automatically by variable str1 fn= lambda x0: str1 The goal for this is I would like to get a function object:<function main.(x0)> ...
Python: Convert A string of formula to lambda function
I have a string of formula lets said: str1='(0.5-0.70*x0[0])**2+(0.5-0.70*x0[1])**2' how can I pass it into lambda function fn Automatically by variable str1 fn= lambda x0: str1 The goal for this is I would like to get a function object:<function main.(x0)> and finally pass it to scipy.optimize.minimize(fn=fn), if yo...
[ "You could use eval():\nfrom scipy.optimize import minimize\nimport numpy as np\n\nstr1='(0.5-0.70*x0[0])**2+(0.5-0.70*x0[1])**2'\n\nx0 = np.ones(2)\n\nminimize(lambda x0: eval(str1), x0=x0)\n\n" ]
[ 2 ]
[]
[]
[ "lambda", "python", "scipy", "scipy_optimize", "scipy_optimize_minimize" ]
stackoverflow_0074212705_lambda_python_scipy_scipy_optimize_scipy_optimize_minimize.txt
Q: How to write data to open Libreoffce spreadsheet .xlsx file with xlwings and python from incoming webhook Using django to receive webhooks. No issue there. Trying to update cells in a working .xlsx spreadsheet on linux mint (using Libreoffice) from the webhook message data. Once the webhook comes in, nothing happe...
How to write data to open Libreoffce spreadsheet .xlsx file with xlwings and python from incoming webhook
Using django to receive webhooks. No issue there. Trying to update cells in a working .xlsx spreadsheet on linux mint (using Libreoffice) from the webhook message data. Once the webhook comes in, nothing happens with the spreadsheet. I have tried to re-code this 100 times so I likely have extra code that is not needed ...
[ "If you use xlwings on Linux like this xw.Book(\"file.xlsx\"), you should get the an error message (tested with xlwings 0.28.3).\nxlwings on Linux is only works in either the read mode (see https://docs.xlwings.org/en/latest/reader.html):\nxw.Book(\"myfile.xlsx\", mode=\"r\")\n\nor as server backend for xlwings Ser...
[ 0 ]
[]
[]
[ "export_to_excel", "json", "python", "webhooks", "xlwings" ]
stackoverflow_0074209255_export_to_excel_json_python_webhooks_xlwings.txt
Q: Add new row to a DataFrame based on condition I have the following DataFrame (I'm sorry for posting an image but I dont know how to write tables with more than 2 columns here on Stackoverflow lol) It is missing the fifth month as you can see. How can I detect and add a new row that contains the fifth month to get...
Add new row to a DataFrame based on condition
I have the following DataFrame (I'm sorry for posting an image but I dont know how to write tables with more than 2 columns here on Stackoverflow lol) It is missing the fifth month as you can see. How can I detect and add a new row that contains the fifth month to get a new DataFrame with all months? import pandas as...
[ "I'm guessing this is a model question meant to get an answer for a harder one. This wouldn't be the most wieldly answer in all use-cases, but for what you described, a simple\nif 5 not in df['MONTH'].values:\n df.loc[len(df.index)] = [2020, 2021, 5]\n\nwould suffice.\n", "df.loc[len(df.index)] = [2020, 2019, ...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074212186_dataframe_pandas_python.txt
Q: Error running a Python program with sklearn.cluster - "DLL load failed while importing _pairwise_distances_reduction" I am running Windows 10, and I have Python installed. When trying to run a Python program with the line from sklearn.cluster import DBSCAN in it, I get the following error: File "C:\Users\User\AppD...
Error running a Python program with sklearn.cluster - "DLL load failed while importing _pairwise_distances_reduction"
I am running Windows 10, and I have Python installed. When trying to run a Python program with the line from sklearn.cluster import DBSCAN in it, I get the following error: File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\sklearn\metrics\pairwise.py", line 33, in <module> from ._pairwis...
[ "I was having this problem too, I installed Visual C++ Redistributable Runtimes libraries and it solved my problem.\n" ]
[ 0 ]
[]
[]
[ "dll", "module", "pip", "python", "scikit_learn" ]
stackoverflow_0074074392_dll_module_pip_python_scikit_learn.txt
Q: How to print contents in columns if contents is same value, just print once. Pandas I have dataset like this, I want to print contents in 'Protocol' columns. pcap_df = pd.read_csv('pcap.csv') pcap_df.head(10) No. Time Source Destination Protocol Length Info 0 1 0.000000 172.253.118.188 192.168....
How to print contents in columns if contents is same value, just print once. Pandas
I have dataset like this, I want to print contents in 'Protocol' columns. pcap_df = pd.read_csv('pcap.csv') pcap_df.head(10) No. Time Source Destination Protocol Length Info 0 1 0.000000 172.253.118.188 192.168.1.34 TLSv1.2 1334 Application Data 1 2 0.000272 172.253.118.188 192.168.1.34...
[ "Looks like you want to use df.unique(). That will give an array that contains each unique value. Then a little playing for exactly how you want to display.\npcap_df['Protocol'].unique()\n\nThen you can print it, convert to a list and print, make a loop to print each value on a line, etc etc\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074212734_pandas_python.txt
Q: How can I hide non-sensitive credentials on a Google Colab Notebook? I have a Google Colab Notebook that is using psycopg2 to connect with a free Heroku PostgreSQL instance. I'd like to share the notebook with some colleagues for educational purposes to view and run the code. There is nothing sensitive related to ...
How can I hide non-sensitive credentials on a Google Colab Notebook?
I have a Google Colab Notebook that is using psycopg2 to connect with a free Heroku PostgreSQL instance. I'd like to share the notebook with some colleagues for educational purposes to view and run the code. There is nothing sensitive related to the account / database but would still like to hide the credentials used t...
[ "My work around was creating a Python module that contained a function who performed the initial connection with credentials. I converted the module into a binary .pyc, uploaded it to Google Drive, downloaded the binary into the Notebook's contents via shell command then used it as an import.\nIt obviously isn't se...
[ 1 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0074205261_google_colaboratory_python.txt
Q: How to get an index of maximum count of a required string in a list column of polars data frame? I have a polars dataframe as pl.DataFrame({'doc_id':[ ['83;45;32;65;13','7;8;9'], ['9;4;5','4;2;7;3;5;8;10;11'], ['1000;2000','76;34;100001;7474;2924'], ['100;200','200;100'], ['3;4;6;7;10;11','1;2;...
How to get an index of maximum count of a required string in a list column of polars data frame?
I have a polars dataframe as pl.DataFrame({'doc_id':[ ['83;45;32;65;13','7;8;9'], ['9;4;5','4;2;7;3;5;8;10;11'], ['1000;2000','76;34;100001;7474;2924'], ['100;200','200;100'], ['3;4;6;7;10;11','1;2;3;4;5'] ]}) each list consist of document id's separated with semicolon, if any of list element has g...
[ "df.with_columns(\n [\n # Get first and second list of documents as string element.\n pl.col(\"doc_id\").arr.get(0).alias(\"doc_list1\"),\n pl.col(\"doc_id\").arr.get(1).alias(\"doc_list2\"),\n ]\n)\n.with_columns(\n [\n # Split each doc list element on \";\" and count number of...
[ 1 ]
[]
[]
[ "python", "python_polars" ]
stackoverflow_0074211704_python_python_polars.txt
Q: Which Python object(s) can be indexed/sliced with multiple entries in square brackets? I am playing with Python and found a script online which contains a function. I wrote a simple analogous example below: def func(thing): test = thing[0,:] print(test) I do not know what datatype the variable "thing" is ...
Which Python object(s) can be indexed/sliced with multiple entries in square brackets?
I am playing with Python and found a script online which contains a function. I wrote a simple analogous example below: def func(thing): test = thing[0,:] print(test) I do not know what datatype the variable "thing" is in this case. What kind of Python datatype/object can be called with square brackets like th...
[ "\nI do not know what datatype the variable \"thing\" is in this case. What kind of Python datatype/object can be called with square brackets like this?\n\nAny object that has a __getitem__ method can be subscripted.\nthing[0, :]\n\nis simply syntactic sugar for\nthing.__getitem__((0, slice(None, None, None)))\n\nS...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074212848_python.txt
Q: Simple multiprocessing Pool hangs in Jupyter notebook I'm trying to run some multiprocessing in a Jupyter notebook, using python version 3.7.0. However, even a really simple example seems to hang indefinitely. After reading this answer I tried explicitly calling .close and .join on the pool, but it still hangs. Ex...
Simple multiprocessing Pool hangs in Jupyter notebook
I'm trying to run some multiprocessing in a Jupyter notebook, using python version 3.7.0. However, even a really simple example seems to hang indefinitely. After reading this answer I tried explicitly calling .close and .join on the pool, but it still hangs. Example code is below, can anyone tell me what's wrong? impor...
[ "Another solution is to use the multiprocess module, which is identical to the multiprocessing library while working with Jupyter.\n", "For me, it worked the solution proposed by @Booboo.\n\nWrite your function in an external file\nimport it to your .ipynb file\n\n" ]
[ 2, 0 ]
[]
[]
[ "jupyter_notebook", "multiprocessing", "python", "python_multiprocessing" ]
stackoverflow_0066420735_jupyter_notebook_multiprocessing_python_python_multiprocessing.txt
Q: Using custom icons for multiple locations with Folium and Pandas I am trying to iterrate through a pandas dataframe to plot multiple geolocations on a Folium map using custom icons as markers instead of the default one. First I create a pandas dataframe as follows: # dependencies import folium import pandas as pd...
Using custom icons for multiple locations with Folium and Pandas
I am trying to iterrate through a pandas dataframe to plot multiple geolocations on a Folium map using custom icons as markers instead of the default one. First I create a pandas dataframe as follows: # dependencies import folium import pandas as pd from google.colab import drive drive.mount('/content/drive/') ...
[ "Seems like the only way to do this is to place the custom icon call within the for loop so it initialises for each iterration, eg:\n world = folium.Map(\n zoom_start=2\n )\n \n x = data[['Lat', 'Lon', 'Color']].copy()\n \n for index, row in x.iterrows():\n pushpin = fol...
[ 0 ]
[]
[]
[ "folium", "geolocation", "leaflet", "pandas", "python" ]
stackoverflow_0074200088_folium_geolocation_leaflet_pandas_python.txt
Q: Django Model TypeError many-to-many relationship I'm getting this error while ruining the test TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use participants.set() instead. I understand the error but I don't know how to implement the correct solution class BaseTestCase(Test...
Django Model TypeError many-to-many relationship
I'm getting this error while ruining the test TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use participants.set() instead. I understand the error but I don't know how to implement the correct solution class BaseTestCase(TestCase): def setUp(self): url = reverse("ind...
[ "You can't assign a user to a many-to-many field directly. You need to use the add() method.\nEvent.objects.create(\n name=\"test event\",\n description=\"test description\",\n created=datetime.datetime.now(),\n updated=datetime.datetime.now(),\n date=datetime.datetime.now(),\n)\n\nevent = Event.obje...
[ 2 ]
[]
[]
[ "django_models", "django_tests", "python" ]
stackoverflow_0074212972_django_models_django_tests_python.txt
Q: how to use python variable in oracle procedure as dynamic variables I have sql procedure and I have some python variables I want to run this procedure along with using this variables as dynamic ` I have sql procedure and I have some python variables I want to run this procedure along with using this variables as ...
how to use python variable in oracle procedure as dynamic variables
I have sql procedure and I have some python variables I want to run this procedure along with using this variables as dynamic ` I have sql procedure and I have some python variables I want to run this procedure along with using this variables as dynamic ` CREATRE OR REPLACE PROCEDUE SQURT_EN_UR( v_ere IN MIGRA...
[ "You can just pass the parameters directly to the procedure, as in this:\ncursor.callproc(\"SQURT_EN_UR\", [arg1, arg2, arg3, arg4])\n\nReplace the values of arg1, arg2, arg3, and arg4 with your own variable names or constants -- whatever you need!\n" ]
[ 0 ]
[]
[]
[ "cx_oracle", "python", "sql", "stored_procedures" ]
stackoverflow_0074212671_cx_oracle_python_sql_stored_procedures.txt
Q: PyCharm not detecting anaconda3 environments I have installed anaconda3, and created some environments from the command line: (base) ➜ ~ conda env list # conda environments: # scratchpad /Users/adamg/.conda/envs/scratchpad test /Users/adamg/.conda/envs/test base ...
PyCharm not detecting anaconda3 environments
I have installed anaconda3, and created some environments from the command line: (base) ➜ ~ conda env list # conda environments: # scratchpad /Users/adamg/.conda/envs/scratchpad test /Users/adamg/.conda/envs/test base * /Users/adamg/anaconda3 convokit ...
[ "You need to define the Python path.\nActivate into the desired environment source activate swda, Run which python from to locate the Python path that is under Anaconda, and then press the three dots ... right to the \"interpreter\" and paste the python path.\nOr simply look for the Python executable through the UI...
[ 2, 0, 0 ]
[]
[]
[ "anaconda", "pycharm", "python" ]
stackoverflow_0058580695_anaconda_pycharm_python.txt
Q: Finding coordinated of rectangular structure using OpenCV I'm trying to draw a rectangular contour around the prominent rectangle shown in the picture below and find its coordinates. The original image is : [ I have arrived at the below image using: th1 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_O...
Finding coordinated of rectangular structure using OpenCV
I'm trying to draw a rectangular contour around the prominent rectangle shown in the picture below and find its coordinates. The original image is : [ I have arrived at the below image using: th1 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] [ PS: To make it more clear- I want to draw a rectang...
[ "Solution using smoothing + thresholding:\n\nConvolve your image with a large 2D kernel (average filtering)\n\n\n\nApply thresholding:\n\n\n\nFind bounding rectangle that includes all non-zero pixels (cv2.boundingRect):\n\n\nCode:\nimport cv2\nimport numpy as np\n\nimage = cv2.imread('block.jpg')\nmask = cv2.cvtCol...
[ 1, 0 ]
[]
[]
[ "computer_vision", "contour", "drawrectangle", "opencv", "python" ]
stackoverflow_0074202191_computer_vision_contour_drawrectangle_opencv_python.txt
Q: Python SQL Query output with psycopg2 I've sucessfully done a Select query on Python using psycopg2, but i have a problem with the output. The output is as follows: [('Porto',), ('Milan',), ('London',)] The problem is when i try to pass it as a variable on an API string cityList = records for city in cityList: ...
Python SQL Query output with psycopg2
I've sucessfully done a Select query on Python using psycopg2, but i have a problem with the output. The output is as follows: [('Porto',), ('Milan',), ('London',)] The problem is when i try to pass it as a variable on an API string cityList = records for city in cityList: api = f"https://api.example.io/?city={cit...
[ "You have a list of rows where each element is a tuple containing all the columns retrieved for each row, which in your case contains a single element. So what you should do instead is chose the one and only column from each row:\ncityList = records\n\nfor city in cityList:\n api = f\"https://api.example.io/?cit...
[ 1 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0074212909_postgresql_psycopg2_python.txt
Q: Some weird transformation to pandas dataframe My dataframe: df = pd.DataFrame({'a':['A', 'B'], 'b':[{5:1, 11:2}, {5:3}]}) Expected output (Each Key will be transformed to 'n' keys. Example row 1, key =5 (with value =2) get transformed to 5, 6. This change also need to reflect on 'a' column) df_expected = pd.DataF...
Some weird transformation to pandas dataframe
My dataframe: df = pd.DataFrame({'a':['A', 'B'], 'b':[{5:1, 11:2}, {5:3}]}) Expected output (Each Key will be transformed to 'n' keys. Example row 1, key =5 (with value =2) get transformed to 5, 6. This change also need to reflect on 'a' column) df_expected = pd.DataFrame({'a':['A1', 'A2', 'A1', 'A2', 'B1', 'B2', 'B3'...
[ "This will do your transform, outside of pandas.\nd = {'a':['A', 'B'], 'b':[{5:1, 11:2}, {5:3}]}\n\nout = { 'a':[], 'b':[] }\nfor a,b in zip(d['a'],d['b']):\n n = max(b.values())\n for k in b:\n for i in range(n):\n out['a'].append(f'{a}{i+1}')\n out['b'].append(k+i)\nprint(out)\n...
[ 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074212442_pandas_python.txt
Q: I need assistance making a score in python using a dataframe that can be changed My task is creating a function that can find a score for different DataFrame objects that are passed into it, i settled on using if else statements to attempt to make a score, but i keep running into ValueError exceptions. My data is ...
I need assistance making a score in python using a dataframe that can be changed
My task is creating a function that can find a score for different DataFrame objects that are passed into it, i settled on using if else statements to attempt to make a score, but i keep running into ValueError exceptions. My data is all contained in dataframes as i collected it from csv files and performed analysis on...
[ "Instead of using or or and -> use | or & respectively (when working with pandas)\nReason:\nor or and require truth-values. Whereas with pandas objects (Series in your case) are considered ambiguous so you should use | (or) or & (and) bitwise operations\nOther Pointers:\n\nDF and df are not referencing the same var...
[ 0, 0, 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074198061_pandas_python_python_3.x.txt
Q: How to fix a RecursionError in Turtle? I'm trying to write a program with Python to emulate an 'old' online game in which you drive a worm through the screen with some inputs from the keyboard. import turtle # Set screen and background wn = turtle.Screen() wn.title("Turn with Left and Right buttons your keyboard....
How to fix a RecursionError in Turtle?
I'm trying to write a program with Python to emulate an 'old' online game in which you drive a worm through the screen with some inputs from the keyboard. import turtle # Set screen and background wn = turtle.Screen() wn.title("Turn with Left and Right buttons your keyboard. Click on screen to EXIT.") wn.bgcolor("blac...
[ "What you're experiencing is a faux recursion due to events stacking. However, your code design:\nwhile t < 1000:\n snake.forward(1)\n t += 1\n\nactually relies on event stacking! That is, you expect left and right commands to come in during the go() portion of the event handler which keeps the turtle movin...
[ 1, 0 ]
[]
[]
[ "python", "python_turtle", "recursionerror", "turtle_graphics" ]
stackoverflow_0074210421_python_python_turtle_recursionerror_turtle_graphics.txt
Q: Clicking a LinkedIn button using Selenium Python I am unable to click on the LinkedIn sign-in button. Can someone please guide me with what locator should I use? What should be the actual code. I have tried driver.find_element(By.CLASS_NAME,"btn__primary--large from__button--floating").click() but that doesn't wo...
Clicking a LinkedIn button using Selenium Python
I am unable to click on the LinkedIn sign-in button. Can someone please guide me with what locator should I use? What should be the actual code. I have tried driver.find_element(By.CLASS_NAME,"btn__primary--large from__button--floating").click() but that doesn't work
[ "CLASS_NAME accepts single class attribute while here there are 2: btn__primary--large and from__button--floating.\nTo locate element based on 2 class values you can use CSS Selector or XPath, as following:\ndriver.find_element(By.CSS_SELECTOR,\".btn__primary--large.from__button--floating\").click()\n\nOr\ndriver.f...
[ 1 ]
[]
[]
[ "automation", "python", "selenium", "selenium_chromedriver", "testing" ]
stackoverflow_0074213069_automation_python_selenium_selenium_chromedriver_testing.txt
Q: extract some rows from excel to another txt by txt I have a txt file that contains just the number like 218158, 177549 and I have a large excel file that have many columns and rows, each rows related to one id I want to read a number from txt file and then go to this number in (row) and save all column for this ro...
extract some rows from excel to another txt by txt
I have a txt file that contains just the number like 218158, 177549 and I have a large excel file that have many columns and rows, each rows related to one id I want to read a number from txt file and then go to this number in (row) and save all column for this row to another txt with tab for example in the txt: 218158...
[ "you should probably use openpyxl, here's an example of how it's done.\nimport openpyxl\n\nxlsx_file_path = r'ex.xlsx'\ninput_text_file_path = r'ex.txt'\noutput_text_file = r'out.txt'\n\nwith open(input_text_file_path,'r') as f:\n lines = f.readlines()\n\nfile = openpyxl.open(xlsx_file_path, read_only=True) # o...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074212910_python.txt
Q: Runtime error using MLFlow and Spark on databricks Here is some model I created: class SomeModel(mlflow.pyfunc.PythonModel): def predict(self, context, input): # do fancy ML stuff # log results pandas_df = pd.DataFrame(...insert predictions here...) spark_df = spark.createDataFr...
Runtime error using MLFlow and Spark on databricks
Here is some model I created: class SomeModel(mlflow.pyfunc.PythonModel): def predict(self, context, input): # do fancy ML stuff # log results pandas_df = pd.DataFrame(...insert predictions here...) spark_df = spark.createDataFrame(pandas_df) spark_df.write.saveAsTable('table...
[ "I had a similar error and I was able to resolve this by taking spark functions like \"spark.createDataFrame(pandas_df)\" outside of the class. If you want to read-write data using spark do it within the main function.\n class SomeModel(mlflow.pyfunc.PythonModel):\n def predict(self, context, input):\n ...
[ 0 ]
[]
[]
[ "apache_spark_sql", "databricks", "mlflow", "pyspark", "python" ]
stackoverflow_0072900375_apache_spark_sql_databricks_mlflow_pyspark_python.txt
Q: How to join second elements in tuples using group by first element python I have a list of tuples a = [('name', 'color'),('fruit', 'color'),('thing', 'type'),('sport', 'type')] I want to join first elements grouped by second element. The output should look like. a = [('name fruit', 'color'),('thing sport', 'type'...
How to join second elements in tuples using group by first element python
I have a list of tuples a = [('name', 'color'),('fruit', 'color'),('thing', 'type'),('sport', 'type')] I want to join first elements grouped by second element. The output should look like. a = [('name fruit', 'color'),('thing sport', 'type')]
[ "You can create dict with the key that you want to group and add value to list base key. For this approach, you can use collections.defaultdict or if you don't want to import anything you can use dict.setdefault.\nfrom collections import defaultdict\n\n\na = [('name', 'color'),('fruit', 'color'),('thing', 'type'),(...
[ 2, 1, 0 ]
[]
[]
[ "join", "python", "string", "tuples" ]
stackoverflow_0074213040_join_python_string_tuples.txt
Q: print only numbers on selenium "find_element" i'm trying to do something really useful to me, but i have a problem. this is the code line that give-me the result "5,0 km" import selenium from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service i...
print only numbers on selenium "find_element"
i'm trying to do something really useful to me, but i have a problem. this is the code line that give-me the result "5,0 km" import selenium from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.keys i...
[ "This should work:\ndef km():\n sleep(10)\n kmtotal=navegador.find_element('xpath', '/html/body/div[3]/div[9]/div[9]/div/div/div[1]/div[2]/div/div[1]/div/div/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div')\n txt = kmtotal.text #extract the entire text content from the web element\n value = float(txt) #...
[ 0 ]
[]
[]
[ "python", "python_3.x", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074213131_python_python_3.x_selenium_chromedriver_selenium_webdriver.txt
Q: How can I save the content of file as bytes in a variable? Given a text file, for example: a.txt , that his max-size is 16 bytes and it contains some text. How can I read all the content of this file (all the bytes of this file) and save it in variable without to open this file? Namely, I don't want to do open("a....
How can I save the content of file as bytes in a variable?
Given a text file, for example: a.txt , that his max-size is 16 bytes and it contains some text. How can I read all the content of this file (all the bytes of this file) and save it in variable without to open this file? Namely, I don't want to do open("a.txt", "r").read() , but, I looking for something like: a = bytes...
[ "Reading bytes from a file and storing it in a variable can be done with my_var = Path('a.txt').read_bytes()\nbytes has rjust and ljust to pad using the specified fill byte.\nThese can be combined to always give a result 16 bytes in length. e.g.\nPath('a.txt').read_bytes().rjust(16, b'x')\n\nHere is a fuller exampl...
[ 1 ]
[]
[]
[ "byte", "file", "python" ]
stackoverflow_0074212648_byte_file_python.txt
Q: How to get difference in days between two dates from a csv in python? So I'm trying to get the number of days between these two dates ("today" and a prior date) from a csv file. I'm using the datetime library, i can get the delta (difference between the two dates), but I can't get the number of days. If i try to u...
How to get difference in days between two dates from a csv in python?
So I'm trying to get the number of days between these two dates ("today" and a prior date) from a csv file. I'm using the datetime library, i can get the delta (difference between the two dates), but I can't get the number of days. If i try to use .days it returns me an error, stating it cannot convert series to dateti...
[ "convert passwordlastset to datetime and subtract from today\ndf['delta']=(datetime.today() - pd.to_datetime(df['PasswordLastSet'])).dt.days\ndf\n\n\nPasswordLastSet delta\n0 2019-09-10 11:11 1142\n1 2019-10-07 11:13 1115\n2 2019-11-04 11:16 1087\n3 2019-11-28 11:20 1063\n\n" ]
[ 0 ]
[]
[]
[ "date", "pandas", "python" ]
stackoverflow_0074213206_date_pandas_python.txt
Q: Use Regex to Separate Pairs of Title and URL I copied a list of books and their URL from a website that becomes one string when pasted in a word doc and I'd like to separate each Title and URL on new lines: Copied list: Elementary Algebra https://amzn.to/3S7yG0Y Pre-Algebra https://amzn.to/3TpW8HK Discrete Mathem...
Use Regex to Separate Pairs of Title and URL
I copied a list of books and their URL from a website that becomes one string when pasted in a word doc and I'd like to separate each Title and URL on new lines: Copied list: Elementary Algebra https://amzn.to/3S7yG0Y Pre-Algebra https://amzn.to/3TpW8HK Discrete Mathematical Structures https://amzn.to/3eBYogb Discrete...
[ "Try (regex101):\nimport re\n\ns = \"\"\"Elementary Algebra https://amzn.to/3S7yG0Y Pre-Algebra https://amzn.to/3TpW8HK Discrete Mathematical Structures https://amzn.to/3eBYogb Discrete Mathematics and its Applications https://amzn.to/3TvfThe Discrete and Combinatorial Mathematics https://amzn.to/3CELUfO\"\"\"\n\np...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074213097_python_regex.txt
Q: Combining two columns as a nested list of tuples by category | python dataframe Assume I have a dataframe: df = pd.DataFrame({"cat":['a', 'a', 'b', 'c'],"A":[5, 6, 1, 4],"B":[7,8, 12, 5]}) which looks like this: cat A B 0 a 5 7 1 a 6 8 2 b 1 12 3 c 4 5 Now I want to combine column A ...
Combining two columns as a nested list of tuples by category | python dataframe
Assume I have a dataframe: df = pd.DataFrame({"cat":['a', 'a', 'b', 'c'],"A":[5, 6, 1, 4],"B":[7,8, 12, 5]}) which looks like this: cat A B 0 a 5 7 1 a 6 8 2 b 1 12 3 c 4 5 Now I want to combine column A and B based on column cat. If row['cat'] is the same, then combine row['A'] and row['...
[ "x = df.groupby('cat').apply(lambda x: list(zip(x['A'], x['B'])))\n\nThis gives you a series of this form:\ncat\na [(5, 7), (6, 8)]\nb [(1, 12)]\nc [(4, 5)]\ndtype: object\n\nYou can do x.to_list() to get a list like in example output.\n", "You can first aggregate as tuples, then to list:\...
[ 3, 0 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python", "python_3.x" ]
stackoverflow_0074212983_dataframe_group_by_pandas_python_python_3.x.txt
Q: format to bold a specific cell in a column by multiple condition using xlsxwriter i got the following .xlsx file. I would like to enter the yellow marked string in bold in the following image. The condition is that there is a string in the "Name1" column and there must be no string in the "Name2" column -> then c...
format to bold a specific cell in a column by multiple condition using xlsxwriter
i got the following .xlsx file. I would like to enter the yellow marked string in bold in the following image. The condition is that there is a string in the "Name1" column and there must be no string in the "Name2" column -> then change the string in the "Name1" column to bold. How do I have to change the following c...
[ "So the trick with stuff like this is to make the conditional formatting work in Excel, and then just copying the formula.\nI created a new workbook with a new worksheet, where the columns B and H match yours (more or less).\nThe applied conditional formatting rule does exactly what you want. It could be simplified...
[ 2 ]
[]
[]
[ "excel", "pandas", "python", "xlsxwriter" ]
stackoverflow_0074070347_excel_pandas_python_xlsxwriter.txt
Q: Beatifulsoup find_all when a tag is not inside another tag html = """ <html> <h2>Top Single Name</h2> <table> <tr> <p>hello</p> </tr> </table> <div> <div> <h2>Price Return</h2> </div> </div> </html> """ When I Use below code from bs4 import BeautifulSoup im...
Beatifulsoup find_all when a tag is not inside another tag
html = """ <html> <h2>Top Single Name</h2> <table> <tr> <p>hello</p> </tr> </table> <div> <div> <h2>Price Return</h2> </div> </div> </html> """ When I Use below code from bs4 import BeautifulSoup import re soup = BeautifulSoup(html, 'html.parser') soup.find_all(...
[ "\nBasically I don't want to extract a specific tag if it is inside another tag\n\nI think the simplest way might be to use find_all just as you are now, and then filter out the nested tags by checking if they have ancestors/parents in the list\nsel = soup.find_all(['p', 'li', 'dl', 'tr', 'div', re.compile(\"^h[1-6...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "html_parsing", "python", "python_3.x" ]
stackoverflow_0074212070_beautifulsoup_html_html_parsing_python_python_3.x.txt
Q: Get rid of letters that are in string 1 in string 2 and then combine the new string 2 with string 1 I thought I solved this problem but then my solution also removed letters in string 1. Here are some inputs and outputs that I want to achieve: a, bcdefg, into abcdefg. ab, cdefgic, into abcdefgi. abc, adefghiad...
Get rid of letters that are in string 1 in string 2 and then combine the new string 2 with string 1
I thought I solved this problem but then my solution also removed letters in string 1. Here are some inputs and outputs that I want to achieve: a, bcdefg, into abcdefg. ab, cdefgic, into abcdefgi. abc, adefghiad, into abcdefghi. hello,world, into hellowrd. troy, warrior, into troywai. frizzy,wizzo, into frizzyw...
[ "str1 = \"abc\"\nstr2 = \"arabdcd\"\n\nletters_list = list(str1+str2)\nletters = []\n\nfor l in letters_list:\n if l not in letters:\n letters.append(l)\nnew_string = \"\".join(letters)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074213224_python.txt
Q: splitting list in chunks of balanced weight I need an algorithm to split a list of values into such chunks, that sum of values in every chunk is (approximately) equals (its some variation of Knapsack problem, I suppose) So, for example [1, 2, 1, 4, 10, 3, 8] => [[8, 2], [10], [1, 3, 1, 4]] Chunks of equal lengths ...
splitting list in chunks of balanced weight
I need an algorithm to split a list of values into such chunks, that sum of values in every chunk is (approximately) equals (its some variation of Knapsack problem, I suppose) So, for example [1, 2, 1, 4, 10, 3, 8] => [[8, 2], [10], [1, 3, 1, 4]] Chunks of equal lengths are preferred, but it's not a constraint. Python...
[ "Greedy:\n1. Order the available items descending.\n2. Create N empty groups\n3. Start adding the items one at a time into the group that has the smallest sum in it.\nI think in most real life situations this should be enough.\n", "Based on @Alin Purcaru answer and @amit remarks, I wrote code (Python 3.1). It has...
[ 16, 3, 3, 1, 0 ]
[]
[]
[ "algorithm", "combinatorics", "language_agnostic", "optimization", "python" ]
stackoverflow_0006855394_algorithm_combinatorics_language_agnostic_optimization_python.txt
Q: Tagging S3 bucket object Issue I am trying to add tags to existing object in S3 bucket using Lambda. Lambda has IAM role permission to add tags to bucket object, however simple python code to get_object_tagging is working but put_object_tagging is not working. client = boto3.client("s3") tagresponse = ...
Tagging S3 bucket object Issue
I am trying to add tags to existing object in S3 bucket using Lambda. Lambda has IAM role permission to add tags to bucket object, however simple python code to get_object_tagging is working but put_object_tagging is not working. client = boto3.client("s3") tagresponse = client.put_object_tagging( Bucke...
[ "You need the uppercase K when supplying the tag-key:\nclient = boto3.client(\"s3\") \ntagresponse = client.put_object_tagging(\n Bucket=\"mybucket,\n Key=\"folder1/Test.txt\",\n Tagging={'TagSet':[{'Key':':permission:allowdownload','Value':'no'},{'Key':'service:feature','Value':'sftpfiletransfe...
[ 1 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "python", "s3_object_tagging" ]
stackoverflow_0074213154_amazon_s3_amazon_web_services_boto3_python_s3_object_tagging.txt
Q: Entity Framework cannot connect to MySQL from Python subprocess I have a console app written in .NET 6. It connects to MySQL database and performs some queries. It works perfectly fine when called from IDE or terminal. I am writing a script in Python 3 that will call this console app like this: proc = subprocess.P...
Entity Framework cannot connect to MySQL from Python subprocess
I have a console app written in .NET 6. It connects to MySQL database and performs some queries. It works perfectly fine when called from IDE or terminal. I am writing a script in Python 3 that will call this console app like this: proc = subprocess.Popen([path_to_exe, json_file, "-o", out_dir], env={'ConnectionStrings...
[ "I finally figured out what is causing this strange behavior.\nIf you pass env to subprocess.Popen you will not pass environment variables of the system. I was aware of that, but I figured I didn't need them.\nThe problem was that SYSTEMROOT=\"C:\\WINDOWS\" environment variable was missing and for some strange reas...
[ 0 ]
[]
[]
[ ".net_6.0", "entity_framework_core", "python", "subprocess" ]
stackoverflow_0074199893_.net_6.0_entity_framework_core_python_subprocess.txt
Q: How can I remove values in one DataFrame where the matching value in another DataFrame is not null? Suppose I have two DataFrames: df1: ticker A B C date 2022-01-01 NaN NaN 100 2022-01-02 NaN 200 NaN 2022-01-03 100 NaN NaN 2022-01-04 NaN...
How can I remove values in one DataFrame where the matching value in another DataFrame is not null?
Suppose I have two DataFrames: df1: ticker A B C date 2022-01-01 NaN NaN 100 2022-01-02 NaN 200 NaN 2022-01-03 100 NaN NaN 2022-01-04 NaN NaN 120 df2: ticker A B C date 2022-01-02 145 233 100...
[ "You can use reindex_like to align df1 with df2, then mask the values of df2 for which the matching df1 are notna:\nout = df2.mask(df1.reindex_like(df2).notna())\n\nTo modify df2 in place:\ndf2[df1.reindex_like(df2).notna()] = float('nan')\n\nOutput:\n A B C\ndate ...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074213243_dataframe_pandas_python.txt
Q: How can I drop multiple rows based on a list of values So i have a list of values of longitude and latitude [[-82.99194508, 40.04649963], [-82.99223727, 40.04659349], [-82.99198391, 40.04614863], [-82.99211513, 40.04627218]] and a dataframe hhinc8,owncar,longitude,latitude 5,1,-82.99194508,40.04649963 6,2,-82.995...
How can I drop multiple rows based on a list of values
So i have a list of values of longitude and latitude [[-82.99194508, 40.04649963], [-82.99223727, 40.04659349], [-82.99198391, 40.04614863], [-82.99211513, 40.04627218]] and a dataframe hhinc8,owncar,longitude,latitude 5,1,-82.99194508,40.04649963 6,2,-82.99584706,40.03738548 5,1,-82.99697268,40.02674247 6,2,-82.99160...
[ "Here is one way to do it\n#create a DF from the list of the long/lat you want to exclude\n\ndf2=pd.DataFrame(l, columns=['longitude1','latitude1'])\n\n# do a left merge\n# choose rows that has any null value\n\nout=df[df.merge(df2, \n how='left', \n left_on=['longitude','latitude'],\n...
[ 2 ]
[ "Here's another approach to drop by using for loops:\n# Assuming you already have the code to create a dataframe 'df'\nfor i in ls: # Loop through the list you told\n for index, rows in df.iterrows(): # Loop through the rows\n # Check if the longitude and latitude are equal your list\n if [rows.lon...
[ -1 ]
[ "list", "pandas", "python" ]
stackoverflow_0074212780_list_pandas_python.txt
Q: What kind of relation ship should I make I am making a flask app where I have 2 tables in a data base. User File A file has a column called fileOwnerId but I want to add another called allowed viewers. How would I implement such a situation. I've had 2 ideas: Is to make a column called validViewers that would s...
What kind of relation ship should I make
I am making a flask app where I have 2 tables in a data base. User File A file has a column called fileOwnerId but I want to add another called allowed viewers. How would I implement such a situation. I've had 2 ideas: Is to make a column called validViewers that would store an array of valid viewer but I don't thin...
[ "You have 2 relationships to consider:\nUsers can own multiple files, 1 to Many relationship\nUsers can view Multiple Files and a file can be viewed by Multiple Users. ie Many to Many relationship\nThe first is handled by adding the owner ID to Files. The second is solved by creating as intermediate or jump table...
[ 1, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074213059_python_sqlalchemy.txt
Q: Messaging/Feedback mechanism in Gradio apps I'm building a Gradio app. The server-side processing may take a long time so I'd like to be able to implement a messaging paradigm to update the user-interface based on the processing status. Something like dynamically setting a Component's value does not work (no error...
Messaging/Feedback mechanism in Gradio apps
I'm building a Gradio app. The server-side processing may take a long time so I'd like to be able to implement a messaging paradigm to update the user-interface based on the processing status. Something like dynamically setting a Component's value does not work (no error, just no update) from time import sleep import ...
[ "You can do this by converting your function into a generator. Basically just change the return keyword to yield. You will also need to enable the .queue().\nThis code should work:\nimport gradio as gr\nfrom gradio.components import Markdown, Textbox, Button\nfrom time import sleep\n\n\ndef transform(component):\n ...
[ 1 ]
[]
[]
[ "gradio", "python" ]
stackoverflow_0074211548_gradio_python.txt
Q: Python CAN filter and Mask does not filter messages Trying to filter messages using can in python using the following: bus=can.Bus(interface="ixxat",channel=0, bitrate=250000) filter=[{"can_id":0x0629, "can_mask"=0xFFFF}] bus.setfilters(filter) while True: msg=bus.recv() print(msg) I've...
Python CAN filter and Mask does not filter messages
Trying to filter messages using can in python using the following: bus=can.Bus(interface="ixxat",channel=0, bitrate=250000) filter=[{"can_id":0x0629, "can_mask"=0xFFFF}] bus.setfilters(filter) while True: msg=bus.recv() print(msg) I've tried with "extended"=False as well, and attempted to us...
[ "@Ryan M. Williams. Please, try to use in your code can id == 0x0629 and mask == 0xFFF and let me know if works. Also, later try to code like this:\nfilters = [ {\"can_id\": 0x0629, \"can_mask\": 0xFFF, \"extended\": False} ]\n\nbus = can.interface.Bus(channel=0, bustype=\"ixxat\", can_filters=filters,bitrate=25000...
[ 0 ]
[]
[]
[ "can_bus", "j1939", "python" ]
stackoverflow_0073990030_can_bus_j1939_python.txt
Q: Can't open lib 'ODBC Driver 13 for SQL Server'? Sym linking issue? When I try to connect to a sql server database with pyodbc (on mac): import pyodbc server = '####' database = '####' username = '####@####' password = '#####' driver='{ODBC Driver 13 for SQL Server}' pyodbc.connect('DRIVER='+driver+';SERVER='+ser...
Can't open lib 'ODBC Driver 13 for SQL Server'? Sym linking issue?
When I try to connect to a sql server database with pyodbc (on mac): import pyodbc server = '####' database = '####' username = '####@####' password = '#####' driver='{ODBC Driver 13 for SQL Server}' pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+password) ...
[ "Running: \nodbcinst -j\n\nIt yielded: \nunixODBC 2.3.4\nDRIVERS............: /etc/odbcinst.ini\nSYSTEM DATA SOURCES: /etc/odbc.ini\nFILE DATA SOURCES..: /etc/ODBCDataSources\nUSER DATA SOURCES..: /Users/emehex/.odbc.ini\nSQLULEN Size.......: 8\nSQLLEN Size........: 8\nSQLSETPOSIROW Size.: 8\n\nInstead of copying t...
[ 89, 53, 48, 16, 7, 5, 2, 2, 1, 1, 0, 0, 0, 0 ]
[ "In my case after running below commands with sudo user, i used DRIVER={ODBC Driver 17 for SQL Server}, which resolved my problem.\ncurl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -\ncurl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > \n/etc/apt/sources.list.d/mssql-release.list...
[ -1 ]
[ "pyodbc", "python" ]
stackoverflow_0044527452_pyodbc_python.txt
Q: Can a Plotly legend appear as annotations at the end of each line plot rather than in a box? I was wonder if it possible for Plotly to have a legend for line plots to appear at the end of each line plot (see figure). I tried looking through the documentation but would not find anything specific about legends exce...
Can a Plotly legend appear as annotations at the end of each line plot rather than in a box?
I was wonder if it possible for Plotly to have a legend for line plots to appear at the end of each line plot (see figure). I tried looking through the documentation but would not find anything specific about legends except that one can add annotations but they either overlap on top of each other and were to messy to ...
[ "You can, but it's not a legend at that point. You can use just words or use arrows and words.\nHere's an example using data from a Plotly example. The tags are made with Plotly annotations. There are a TON of options when making these. They can be made dynamically, as well. (Versus one at a time like in my example...
[ 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074210227_plotly_python.txt
Q: Web Scraping-Pairing asscoiated prices including real price I am trying to scrape this website https://99petshops.com.au/Search?brandName=Ziwi%20Peak&animalCode=DOG&storeId=89%2F&page=1 and there are couple of prices listed oer there in which I am interested to pair with the real price with each listing in a way t...
Web Scraping-Pairing asscoiated prices including real price
I am trying to scrape this website https://99petshops.com.au/Search?brandName=Ziwi%20Peak&animalCode=DOG&storeId=89%2F&page=1 and there are couple of prices listed oer there in which I am interested to pair with the real price with each listing in a way that csv headers will look like this: title, lowest_price, lowest_...
[ "If I understand you right, you want to get title, price and get the prices from the table when you expand the other prices. I recommend to use pandas for creating the dataframe and saving the CSV:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://99petshops.com.au/Search?bra...
[ 1 ]
[]
[]
[ "beautifulsoup", "csv", "python", "python_3.x", "web_scraping" ]
stackoverflow_0074213293_beautifulsoup_csv_python_python_3.x_web_scraping.txt
Q: Column not getting filled in after putting several conditions Could you tell me what I'm doing wrong. I am using a databases with three columns. I am trying to filter through one of my columns, named 'POT_SALES, using a condition and fill in an empty column, called 'PROFILES', with 5 different profile types. Here ...
Column not getting filled in after putting several conditions
Could you tell me what I'm doing wrong. I am using a databases with three columns. I am trying to filter through one of my columns, named 'POT_SALES, using a condition and fill in an empty column, called 'PROFILES', with 5 different profile types. Here is the code I've been using so far: for c in df_seg.POT_SALES: ...
[ "here is one approach, using cut\n# using cut, BIN the values per the IF criteria\n# -1 and 99 are just the lower and upper bounds\n# labels to assign when value falls within the corresponding bins\n\ndf['profile']=pd.cut(df['POT_SALES'], \n bins=[-1,2, 4, 6, 8,99],\n labels=...
[ 0 ]
[]
[]
[ "conditional_statements", "dataframe", "fillna", "if_statement", "python" ]
stackoverflow_0074212737_conditional_statements_dataframe_fillna_if_statement_python.txt
Q: nltk tokenization and contractions I'm tokenizing text with nltk, just sentences fed to wordpunct_tokenizer. This splits contractions (e.g. 'don't' to 'don' +" ' "+'t') but I want to keep them as one word. I'm refining my methods for a more measured and precise tokenization of text, so I need to delve deeper into...
nltk tokenization and contractions
I'm tokenizing text with nltk, just sentences fed to wordpunct_tokenizer. This splits contractions (e.g. 'don't' to 'don' +" ' "+'t') but I want to keep them as one word. I'm refining my methods for a more measured and precise tokenization of text, so I need to delve deeper into the nltk tokenization module beyond sim...
[ "Which tokenizer you use really depends on what you want to do next. As inspectorG4dget said, some part-of-speech taggers handle split contractions, and in that case the splitting is a good thing. But maybe that's not what you want. To decide which tokenizer is best, consider what you need for the next step, and th...
[ 13, 2, 2, 0 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0011351290_nlp_nltk_python.txt
Q: How to get rid of the single quotation marks in a list inside a list? I wrote this piece of code, in which I ask the user to input numbers twice, and then it joins them together in a list, inside a list. It works...buts it's in the wrong format. Here's what I did list=[] for i in range(2): userinput = input("E...
How to get rid of the single quotation marks in a list inside a list?
I wrote this piece of code, in which I ask the user to input numbers twice, and then it joins them together in a list, inside a list. It works...buts it's in the wrong format. Here's what I did list=[] for i in range(2): userinput = input("Enter some numbers: ") x = userinput.split() list.append(x) print(li...
[ "Use x = [int(i) for i in userinput.split()]; you have to convert the input strings to integers.\n", "You'll need to convert each value to an int to avoid the quotes (the values entered by the end user are strings):\nlist=[]\nfor i in range(2):\n userinput = input(\"Enter some numbers: \")\n x = userinput.s...
[ 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074213408_list_python.txt
Q: Reading csv file keeping giving error "No such file or directory" I am trying to read a csv file using pyscript. There is an error message kept showing. JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) F...
Reading csv file keeping giving error "No such file or directory"
I am trying to read a csv file using pyscript. There is an error message kept showing. JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run...
[ "Pyscript is rapidly evolving. For now ...\nYou'll note for example py-config has replaced py-env, see here.\npaths, that had been highlighted in section about local file access here, is now used differently. paths is now a list to specify local Python modules for installation, see here. open_url seems the sugges...
[ 1 ]
[]
[]
[ "html", "pyscript", "python" ]
stackoverflow_0074203822_html_pyscript_python.txt
Q: Issue installing twarc2 in conda environment I'm trying to install twarc2 in my conda environment (from here) : conda install -c brown-data-science twarc The above command runs fine, if I try it again I get All requested packages already installed. However when I try to import the module in python: >>> import tw...
Issue installing twarc2 in conda environment
I'm trying to install twarc2 in my conda environment (from here) : conda install -c brown-data-science twarc The above command runs fine, if I try it again I get All requested packages already installed. However when I try to import the module in python: >>> import twarc Traceback (most recent call last): File "<st...
[ "The package is now available through Conda Forge.\nconda create -n twarc -c conda-forge python=3.10 twarc\n\nThis provides v2.12.0 of the PyPI package, which includes both twarc and twarc2 entrypoints.\n", "I didn't pay attention to the fact that the version of twarc from anaconda that I was installing is only f...
[ 1, 0 ]
[]
[]
[ "conda", "python", "twarc2" ]
stackoverflow_0074206504_conda_python_twarc2.txt
Q: How to programmatically generate new headers from URL? I'm writing a script to pull financial data from a website everyday however the script stops working after a few hours because the cookies expire. I need to generate new headers (I think just the x-xsrf-token and cookies) each time I run the script (once a day...
How to programmatically generate new headers from URL?
I'm writing a script to pull financial data from a website everyday however the script stops working after a few hours because the cookies expire. I need to generate new headers (I think just the x-xsrf-token and cookies) each time I run the script (once a day), otherwise I get a 401 status code. This is the page I'm t...
[ "The cookies are the bottleneck. You first have to fetch them and then pass them along with the request:\nimport requests\nfrom urllib.parse import unquote\n\nua_headers = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:86.0) Gecko/20100101 Firefox/86.0\"\n}\n\nparams = {\n 'fields': 'symbol,...
[ 0 ]
[]
[]
[ "cookies", "python", "python_3.x", "python_requests", "web_scraping" ]
stackoverflow_0074212879_cookies_python_python_3.x_python_requests_web_scraping.txt
Q: Why WHOLE code is executing 3 times instead of only p1 and p2? I copy code from youtube. That guy's code works as I wish mine to. It defined 2 processes and 2 processes were executed. My whole code is executing 3 times. Why? And why doesn't he need to use if __name__ == '__main__':? import multiprocessing import t...
Why WHOLE code is executing 3 times instead of only p1 and p2?
I copy code from youtube. That guy's code works as I wish mine to. It defined 2 processes and 2 processes were executed. My whole code is executing 3 times. Why? And why doesn't he need to use if __name__ == '__main__':? import multiprocessing import time start = time.perf_counter() def do_something(): print('Sle...
[ "Using :\nif __name__ == '__main__':\n\nYou have to have all your executing code inside it:\nimport multiprocessing\nimport time\n\ndef do_something():\n print('Sleeping 1 second...')\n time.sleep(1)\n print('Done sleeping...')\n\nif __name__ == '__main__':\n start = time.perf_counter()\n\n p1 = mult...
[ 0, 0 ]
[]
[]
[ "multiprocessing", "python", "time" ]
stackoverflow_0074210539_multiprocessing_python_time.txt
Q: How do I format this return? I have this function that generate the initial population for a genetic algorithm. import random def initial_pop(pop_size): pop = list() for i in range(pop_size): aux = list() for j in range(2): signal = bin(random.randint(0, 1))[2:].zfill(1) ...
How do I format this return?
I have this function that generate the initial population for a genetic algorithm. import random def initial_pop(pop_size): pop = list() for i in range(pop_size): aux = list() for j in range(2): signal = bin(random.randint(0, 1))[2:].zfill(1) int_part = bin(random.randi...
[ "The problem seems to be in how selected is defined. When I call your cross-over function like this:\ncrossover(population[0],population[1],0.3)\n\nI get output which looks like:\n[['0000110000101001', '1010100101111111'], ['0010101110111110', '0001001010110001'], ['0100100110000010', '0100111100011001'], ['0011000...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074213052_python.txt
Q: Using MathematicalProgram with no cost I would like to use Drake to find the critical points of a gradient. I obtained the gradient symbolically using the .Jacobian function. The thing is, I don't have a cost, I just want to find the roots. I have some constraints and my 2x1 continuous variable, but where do I go ...
Using MathematicalProgram with no cost
I would like to use Drake to find the critical points of a gradient. I obtained the gradient symbolically using the .Jacobian function. The thing is, I don't have a cost, I just want to find the roots. I have some constraints and my 2x1 continuous variable, but where do I go from here?
[ "Found the answer. You just have to define a constraint that says J = 0. Drake figures it out as a constraint satisfaction problem and solves it.\n" ]
[ 2 ]
[]
[]
[ "drake", "python" ]
stackoverflow_0074196770_drake_python.txt
Q: Flask-Restful Error: request Content-Type was not 'application/json'."} I was following this tutorial and it was going pretty well. He then introduced reqparse and I followed along. I tried to test my code and I get this error {'message': "Did not attempt to load JSON data because the request Content-Type was not ...
Flask-Restful Error: request Content-Type was not 'application/json'."}
I was following this tutorial and it was going pretty well. He then introduced reqparse and I followed along. I tried to test my code and I get this error {'message': "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."} I don't know if I'm missing something super obvious but...
[ "I don't know why you have an issue as far as I can tell you did copy him exactly how he did it. Here's a fix that'll work although I can't explain why his code works and yours doesn't. His video is two years old so it could be deprecated behaviour.\nimport requests\nimport json\n\nBASE = \"http://127.0.0.1:5000/\"...
[ 2, 2, 1, 0 ]
[]
[]
[ "flask", "flask_restful", "python", "rest" ]
stackoverflow_0072893180_flask_flask_restful_python_rest.txt
Q: Defining Newline as an Environment Variable does not work as expected I have been struggling with different variations and can't find anything that indicates I am doing something wrong. csv_data = response["Body"].read().decode('utf-8') rows = csv_data.split("\n") print(f"Row Count : {len(rows)}") Row Count : 100...
Defining Newline as an Environment Variable does not work as expected
I have been struggling with different variations and can't find anything that indicates I am doing something wrong. csv_data = response["Body"].read().decode('utf-8') rows = csv_data.split("\n") print(f"Row Count : {len(rows)}") Row Count : 1000 Now use an env var instead of hardcoded. source_line_delimiter = os.envir...
[ "If you print(repr(source_line_delimiter)) for the env value, I will all but guarantee you get '\\\\n'. That suggests that it's not actually treating the env var as a newline, but as a backslash and the literal character n. If that's accurate, then this should work:\nbytes(source_line_delimiter, encoding='utf8').de...
[ 2 ]
[]
[]
[ "aws_lambda", "python" ]
stackoverflow_0074211917_aws_lambda_python.txt
Q: Why is List Variable Changing? I have a function and its work correct. It can calculate correct only send by one by. But I want to append every result in a list. The list variable is changing when every calculate. Why is changing appened list data ? ` PLCdevice = { '32DI': 0, '16DI': 0, '8DI': 0 } PLCL...
Why is List Variable Changing?
I have a function and its work correct. It can calculate correct only send by one by. But I want to append every result in a list. The list variable is changing when every calculate. Why is changing appened list data ? ` PLCdevice = { '32DI': 0, '16DI': 0, '8DI': 0 } PLCList = [] def PLCcal(DIneed ): D...
[ "Dictionaries are mutable objects, and PLCdevice is a global variable, so every time you change it in PLCcal you are changing other references too which in this case are the values you are appending.\nYou can simply create PLCdevice at the beginning of PLCcal\ndef PLCcal(DIneed ):\n PLCdevice = {\n '32DI'...
[ 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074213621_list_python.txt
Q: Using LIME for explanation of deep neural net for fraud detection I have built a deep neural network which classifies fraudulent transactions. I am trying to use LIME for explanation, but am facing an error from the interpretor.explain_instance() function. The complete code is as follows: import lime from lime imp...
Using LIME for explanation of deep neural net for fraud detection
I have built a deep neural network which classifies fraudulent transactions. I am trying to use LIME for explanation, but am facing an error from the interpretor.explain_instance() function. The complete code is as follows: import lime from lime import lime_tabular interpretor = lime_tabular.LimeTabularExplainer( ...
[ "Adding labels=(0,) in exp = eplainer.explain_instance() might resolve your issue.\nexp = interpretor.explain_instance(\ndata_row=x_test_scaled[:1], ##new data\npredict_fn=model.predict,\nnum_features=11,\nlabels=(0,)\n)\n\nI had a similar issue with breast cancer data trying to predict benign or malignant tumors. ...
[ 1, 0 ]
[]
[]
[ "deep_learning", "lime", "neural_network", "python" ]
stackoverflow_0072542202_deep_learning_lime_neural_network_python.txt
Q: How to filter dataframe based on varying thresholds for indexes I have a data frame and a dictionary like this: thresholds = {'column':{'A':10,'B':11,'C':9}} df: Column A 13 A 7 A 11 B 12 B 14 B 14 C 7 C 8 C 11 For every index group, I want to calculate the count of values...
How to filter dataframe based on varying thresholds for indexes
I have a data frame and a dictionary like this: thresholds = {'column':{'A':10,'B':11,'C':9}} df: Column A 13 A 7 A 11 B 12 B 14 B 14 C 7 C 8 C 11 For every index group, I want to calculate the count of values less than the threshold and greater than the threshold value. So my ...
[ "You can use:\nimport numpy as np\n\nt = df.index.to_series().map(thresholds['column'])\n\nout = (pd.crosstab(df.index, np.where(df['Column'].gt(t), 'Values>Thr', 'Values≤Thr'))\n .rename_axis(index=None, columns=None)\n )\n\nOutput:\n Values>Thr Values≤Thr\nA 2 1\nB 3...
[ 2, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074213616_dataframe_pandas_python_python_3.x.txt
Q: Spacy: OSError: [E050] Can't find model on Google Colab | Python I'm trying to 'lemmatize' spanish text using the spanish core model es_core_news_sm. However, I'm getting OSError. The following code is an example of lemmatization using SpaCy on Google Colabs: import spacy spacy.prefer_gpu() nlp = spacy.load('es_c...
Spacy: OSError: [E050] Can't find model on Google Colab | Python
I'm trying to 'lemmatize' spanish text using the spanish core model es_core_news_sm. However, I'm getting OSError. The following code is an example of lemmatization using SpaCy on Google Colabs: import spacy spacy.prefer_gpu() nlp = spacy.load('es_core_news_sm') text = 'yo canto, tú cantas, ella canta, nosotros cantam...
[ "You first need to download the data:\n!spacy download es_core_news_sm\n\nThen Restart the runtime, after which your code will run correctly:\nimport spacy\nspacy.prefer_gpu()\n\nnlp = spacy.load('es_core_news_sm')\ntext = 'yo canto, tú cantas, ella canta, nosotros cantamos, cantáis, cantan…'\ndoc = nlp(text)\nlemm...
[ 3, 0 ]
[]
[]
[ "google_colaboratory", "lemmatization", "python", "spacy" ]
stackoverflow_0060481221_google_colaboratory_lemmatization_python_spacy.txt
Q: How can I download a file in Python whose link is hidden behind a Javascript function? I am trying to download a CSV file provided by the Download to CSV link here: https://www.misoenergy.org/planning/generator-interconnection/GI_Queue/gi-interactive-queue/. The problem is that it is appears to be hidden behind a ...
How can I download a file in Python whose link is hidden behind a Javascript function?
I am trying to download a CSV file provided by the Download to CSV link here: https://www.misoenergy.org/planning/generator-interconnection/GI_Queue/gi-interactive-queue/. The problem is that it is appears to be hidden behind a javascript function and the resulting URL is different each time you click it. I have tried ...
[ "You can use their Ajax API call to download the data in Json form, parse it and save as CSV:\nimport requests\nimport pandas as pd\n\napi_url = \"https://www.misoenergy.org/api/giqueue/getprojects\"\n\ndata = requests.get(api_url).json()\n\ndf = pd.DataFrame(data)\ndf = df.sort_values(by=\"projectNumber\")\ndf.to_...
[ 2 ]
[ "You can try web scraping the link using Beautiful Soup or Scrapy, then use the link to download the csv. What libraries are you using currently?\n" ]
[ -1 ]
[ "python", "python_requests", "web_scraping" ]
stackoverflow_0074213662_python_python_requests_web_scraping.txt
Q: Soft-voting ML algorithm How can I print the probability for each class when I am using the soft-voting classifier? I have tried to print the probability for each class by soft-voting using Python, but I couldn't. A: If you are using scikit-learn you can use predict_proba pred_proba = eclf.predict_proba(X) Here...
Soft-voting ML algorithm
How can I print the probability for each class when I am using the soft-voting classifier? I have tried to print the probability for each class by soft-voting using Python, but I couldn't.
[ "If you are using scikit-learn you can use predict_proba\npred_proba = eclf.predict_proba(X)\n\nHere eclf is your Voting classifier and will return Weighted average probability for each class per sample.\npred_proba[0] will contain list of probabilities per class for first sample, and pred_proba[1] will contain lis...
[ 0 ]
[]
[]
[ "machine_learning", "python" ]
stackoverflow_0074213573_machine_learning_python.txt
Q: How to sort a dict of dicts by the length of a list inside child dicts I'm a beginner to Python, and for the sake of learning I looked up some challenges to solve. Here I have a dictionary, containing several dictionaries, each having a list of dicts. My job here is to sort the dictionary, in descending order, bas...
How to sort a dict of dicts by the length of a list inside child dicts
I'm a beginner to Python, and for the sake of learning I looked up some challenges to solve. Here I have a dictionary, containing several dictionaries, each having a list of dicts. My job here is to sort the dictionary, in descending order, based on which child of somedict has more elements in the key list. somedict = ...
[ "Yes, here you go:\nsomedict = {\n 'a': {\n 'key' : [{}, {}, ]\n },\n 'b': {\n 'key' : [{}, ]\n },\n 'c': {\n 'key' : [{}, {}, {} ]\n },\n 'd': {\n 'key' : [{}, {}, {}, ]\n },\n 'e': {\n 'key' : [{}, {}, {} ]\n },\n 'f': {\n 'key' : [{}, ]\n...
[ 2, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074213747_python.txt
Q: reduction operation 'argmax' not allowed for this dtype How to Take index of Last Cell in ColumnB? I will iterate through all rows, by taking values in there. For that iteration i wanted to take index value of max row in particular column with pandas in python. df['columnNameB'].idxmax() I also tried using axis=1 ...
reduction operation 'argmax' not allowed for this dtype
How to Take index of Last Cell in ColumnB? I will iterate through all rows, by taking values in there. For that iteration i wanted to take index value of max row in particular column with pandas in python. df['columnNameB'].idxmax() I also tried using axis=1 or axis='columns gave other strange errors. idxmax() works in...
[ "idxmax returns the index of the highest value. There is no such value for a series of url names (strings).\nEdit: I think instead of idxmax you are looking for something like\nlen(fileCSV.index)\n\n" ]
[ 1 ]
[]
[]
[ "indexing", "max", "pandas", "python" ]
stackoverflow_0074213846_indexing_max_pandas_python.txt
Q: How can I obtain all customers complaint from a website? I want to scraping all customers complaint from https://www.reclameaqui.com.br/empresa/santander/lista-reclamacoes/?status=NOT_ANSWERED My code: class ComplaintScraper(CrawlSpider): name = "ComplaintScraper" allowed_domains = ["https://www.reclameaq...
How can I obtain all customers complaint from a website?
I want to scraping all customers complaint from https://www.reclameaqui.com.br/empresa/santander/lista-reclamacoes/?status=NOT_ANSWERED My code: class ComplaintScraper(CrawlSpider): name = "ComplaintScraper" allowed_domains = ["https://www.reclameaqui.com.br"] start_urls = [ "https://www.reclameaqui....
[ "I was able to scrape them fine without using splash...\nimport scrapy\n\nclass ComplaintScraper(scrapy.Spider):\n name = \"ComplaintScraper\"\n \n def start_requests(self):\n base = \"https://www.reclameaqui.com.br/empresa/santander/lista-reclamacoes/?status=NOT_ANSWERED\"\n yield scrapy.Req...
[ 1 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0074212937_python_scrapy.txt
Q: Cutting string after x chars at whitespace in python I want to cut a long text after x characters, but I don't want to cut a word in the middle, I want to cut at the last whitespace before x chars: 'This is a sample text'[:20] gives me 'This is a sample tex' but I want 'This is a sample' Another example: 'And a...
Cutting string after x chars at whitespace in python
I want to cut a long text after x characters, but I don't want to cut a word in the middle, I want to cut at the last whitespace before x chars: 'This is a sample text'[:20] gives me 'This is a sample tex' but I want 'This is a sample' Another example: 'And another sample sentence'[:15] gives me 'And another sam' ...
[ "import textwrap\nlines = textwrap.wrap(text, 20)\n# then use either\nlines[0]\n# or\n'\\n'.join(lines)\n\n", "You can use str.rpartition() or str.rsplit() to remove everything after the last space of the remainder:\nexample[:20].rpartition(' ')[0]\n\nexample[:20].rsplit(' ', 1)[0]\n\nThe second argument to str.r...
[ 24, 10, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0018693641_python.txt
Q: Writing tests for python program so I have written a python program that prompts users for letters A or B, then for a number to determine how long it will take them to accrue 1 000 000. I need help on how to write a test for the functions def profile, option_check(f) all using PYTEST. ` import math import sys # Gl...
Writing tests for python program
so I have written a python program that prompts users for letters A or B, then for a number to determine how long it will take them to accrue 1 000 000. I need help on how to write a test for the functions def profile, option_check(f) all using PYTEST. ` import math import sys # Global variables s = 1000000 # final am...
[ "Hi check123 and welcome to StackOverflow. What you are trying to accomplish is unit testing the code. This usually means that certain parts of the code will need to be patched or mocked, and your case is no exception.\nFirst, lets look at the forecast.py file. I have added some inline comments and changed the code...
[ 0 ]
[]
[]
[ "cs50", "pytest", "python", "unit_testing" ]
stackoverflow_0074206178_cs50_pytest_python_unit_testing.txt
Q: Download zip file from a url I have a URL that, when submitted in a web browser, pops up a dialog box to save a zip file. I wrote the following code to download the file, but the file is always empty. I try a lot of things and nothing. Someone could help? def download_files(url): download = requests.get(u...
Download zip file from a url
I have a URL that, when submitted in a web browser, pops up a dialog box to save a zip file. I wrote the following code to download the file, but the file is always empty. I try a lot of things and nothing. Someone could help? def download_files(url): download = requests.get(url) open(f"prestacao_de_contas...
[ "Set stream=True in your requests.get call and add a useragent header to your request\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'}\nurl = \"https://cdn.tse.jus.br/estatistica/sead/odsele/prestacao_contas/prestacao_de_con...
[ 0 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074213744_python_python_requests.txt
Q: How does scikit-learn DecisionTreeClassifier handle duplicate values when determining potential split points for a continuous predictor variable? Suppose I have a continuous predictor variable with values of 10, 20, 20, 30. I understand that the set of potential split thresholds would include {15, 25}, as these ar...
How does scikit-learn DecisionTreeClassifier handle duplicate values when determining potential split points for a continuous predictor variable?
Suppose I have a continuous predictor variable with values of 10, 20, 20, 30. I understand that the set of potential split thresholds would include {15, 25}, as these are the means of 10 & 20 and of 20 & 30, respectively. But would 20 also be included as a potential split threshold because it is the mean of 20 & 20, o...
[ "No, in your example 20 is not considered as a valid split point. Since the splits are taken as f_i <= threshold vs f_i > threshold, in your example a threshold of 20 and a threshold of 25 are actually the same anyway.\nIn the code that you linked (I'm looking at BestSplitter), after sorting the feature values, it...
[ 1 ]
[]
[]
[ "decision_tree", "python", "scikit_learn" ]
stackoverflow_0074186669_decision_tree_python_scikit_learn.txt
Q: PostDetail.post() got multiple values for argument 'slug' I am trying to submit comments on my blog posts but I get faced with this traceback every time. When it succeeds the comment will then be subjected to moderation before showing on the website. If I could get any help it would be greatly appriciated! Here is...
PostDetail.post() got multiple values for argument 'slug'
I am trying to submit comments on my blog posts but I get faced with this traceback every time. When it succeeds the comment will then be subjected to moderation before showing on the website. If I could get any help it would be greatly appriciated! Here is the traceback: Environment: Request Method: POST Request URL...
[ "You are using slug instead of request in post method so:\ndef post(self, request, *args, **kwargs):\n ...\n\n\nAlso, you have to fix your redirect kwargs:\n return redirect('cubs_blog_post_detail', slug=post.slug) \n\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "python", "python_3.x", "slug" ]
stackoverflow_0074209205_django_django_models_python_python_3.x_slug.txt
Q: Getting left-click on tray icon (Python | Pystray) I am working on creating a tkinter window when the pystray icon is pressed so I can make my own Menu in the tray. But I have no idea how to get if the tray icon is pressed. Any help is appreciated! Thanks in advance! A: You can use something like icon = pystray....
Getting left-click on tray icon (Python | Pystray)
I am working on creating a tkinter window when the pystray icon is pressed so I can make my own Menu in the tray. But I have no idea how to get if the tray icon is pressed. Any help is appreciated! Thanks in advance!
[ "You can use something like\nicon = pystray.Icon(name=\"exampleapp\",icon=image,title=\"Example\",menu=pystray.Menu(\n pystray.MenuItem(text=\"Left-Click-Action\",action=default_function,default=True),\n pystray.MenuItem(text=\"Other option\",other_function)\n))\n\nSo you can set the default parameter from a ...
[ 0 ]
[]
[]
[ "pystray", "python", "system_tray", "tkinter", "windows" ]
stackoverflow_0073177072_pystray_python_system_tray_tkinter_windows.txt
Q: pokeapi how to filter only the first 151 pokemon? I'm trying to get the urls of the first pokemons and consume their data to transform into a dataframe, but I can't separate these urls and make a request for each pokemon or bring all 151 at once. import pandas as pd import json import requests request_pokemon = r...
pokeapi how to filter only the first 151 pokemon?
I'm trying to get the urls of the first pokemons and consume their data to transform into a dataframe, but I can't separate these urls and make a request for each pokemon or bring all 151 at once. import pandas as pd import json import requests request_pokemon = requests.get("https://pokeapi.co/api/v2/pokemon?limit=15...
[ "According the API documentation https://pokeapi.co/docs/v2#pokemon-section (section Resource Lists/Pagination) you can add ?limit=150&offset=0 to URL to get first 150 pokemons:\nimport requests\n\napi_url = \"https://pokeapi.co/api/v2/pokemon?limit=150&offset=0\"\ndata = requests.get(api_url).json()\n\nprint(len(d...
[ 1 ]
[]
[]
[ "api", "json", "pandas", "pokeapi", "python" ]
stackoverflow_0074214037_api_json_pandas_pokeapi_python.txt
Q: CS50 Lab 6 world_cup issues with tournament function I am working on CS50 Lab 6 and having problems with the simulate_tournament() function. I don't want the solution, just an idea of what I am doing incorrectly. The simulate_tournament() function should accept a list of teams and execute the simulate_round() func...
CS50 Lab 6 world_cup issues with tournament function
I am working on CS50 Lab 6 and having problems with the simulate_tournament() function. I don't want the solution, just an idea of what I am doing incorrectly. The simulate_tournament() function should accept a list of teams and execute the simulate_round() function repeatedly until one winner is left. The simulate_rou...
[ "Spend some time examining the teams variable. When you read the csv file, you create teams as a list object with pairs of name, rating values. The resulting list looks like this for the men: ['Uruguay', 976, 'Portugal', 1306, 'France', 1166, ... ] Then you call simulate_tournament(), which calls simulate_round() w...
[ 0 ]
[]
[]
[ "cs50", "python" ]
stackoverflow_0074147907_cs50_python.txt
Q: Unable to close a pop up using Selenium with Python So here is my code so far that isn't faring to well: url = 'https://americanbarbell.com/products/american-barbell-cast-kettlebell' path = "C:\Program Files (x86)\msedgedriver.exe" driver = webdriver.Edge(path) driver.get(url) time.sleep(5) driver.find_element(By....
Unable to close a pop up using Selenium with Python
So here is my code so far that isn't faring to well: url = 'https://americanbarbell.com/products/american-barbell-cast-kettlebell' path = "C:\Program Files (x86)\msedgedriver.exe" driver = webdriver.Edge(path) driver.get(url) time.sleep(5) driver.find_element(By.XPATH,'//*[@id="closeIconSvg"]').click() But I keep gett...
[ "Switch to the modal window and wait until it loads.\niframe = driver.find_element(By.XPATH, '//*[@id=\"attentive_creative\"]')\ndriver.switch_to.frame(iframe)\nwait = WebDriverWait(driver, 10)\nstatus_message = wait.until(\n EC.visibility_of_element_located((By.CSS_SELECTOR, \"#closeIconContainer\"))\ndriver....
[ 1, 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074211961_python_selenium_selenium_webdriver.txt
Q: Is there a way to fill a "donut hole" of 0 values in a pandas DataFrame? I'm working with some images, using gray intensity values in data frames. I manipulate the raw values a handful of ways, and let's just say I end up with a data frame that looks like this: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
Is there a way to fill a "donut hole" of 0 values in a pandas DataFrame?
I'm working with some images, using gray intensity values in data frames. I manipulate the raw values a handful of ways, and let's just say I end up with a data frame that looks like this: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 0 0 0 0 0 0 0 0 0 0 3 1 1 1 1 0 0 0 0 0 0 0 0 ...
[ "I wouldnt bother with a pandas dataframe. I would convert it to a two-dimensional python list and work with it from there.\nFirst i converted your dataframe to a list: df.values.tolist()\nThen i used this question to find all neighbouring values and from there it was smooth sailing\ndef checkNeighboursForNull(arra...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python", "replace" ]
stackoverflow_0074213674_dataframe_pandas_python_replace.txt
Q: Open any program from cmd in python I want to open a program located at a specific path in Python but I am getting this error: Error in cmd: The system cannot find the file steam.exe import os os.system('start steam.exe "D:\Program Files (x86)\Steam"') A: use subprocess: import subprocess subprocess.call(['D:\...
Open any program from cmd in python
I want to open a program located at a specific path in Python but I am getting this error: Error in cmd: The system cannot find the file steam.exe import os os.system('start steam.exe "D:\Program Files (x86)\Steam"')
[ "use subprocess:\nimport subprocess\n\nsubprocess.call(['D:\\Program Files (x86)\\Steam\\\\steam.exe'])\n\n" ]
[ 1 ]
[]
[]
[ "cmd", "command_prompt", "path", "python", "subprocess" ]
stackoverflow_0074214126_cmd_command_prompt_path_python_subprocess.txt
Q: Python fastest way to read a large number of small files into memory? I'm trying to read a few thousands html files stored on disk. Is there any way to do better than; for files in os.listdir('.'): if files.endswith('.html') : with (open) files as f: a=f.read() #do more stuffs ...
Python fastest way to read a large number of small files into memory?
I'm trying to read a few thousands html files stored on disk. Is there any way to do better than; for files in os.listdir('.'): if files.endswith('.html') : with (open) files as f: a=f.read() #do more stuffs
[ "For a similar problem I have used this simple piece of code: \nimport glob\nfor file in glob.iglob(\"*.html\"):\n with open(file) as f:\n a = f.read()\n\niglob doesn't stores all file simultaneously, this is perfect with a huge directory.\nRemenber to close files after you have finished, the construct \...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0027202199_python.txt
Q: Print text of anchor link using BeautifulSoap library | python I am web-scraping a website named pakwheels.com. I want to get year of a car. https://www.pakwheels.com/used-cars/suzuki-cultus-2018-for-sale-in-lahore-6596122 The year can be get from this part of HTML. I want to print the text of the anchor link us...
Print text of anchor link using BeautifulSoap library | python
I am web-scraping a website named pakwheels.com. I want to get year of a car. https://www.pakwheels.com/used-cars/suzuki-cultus-2018-for-sale-in-lahore-6596122 The year can be get from this part of HTML. I want to print the text of the anchor link using BeautifulSoap library. Tried different variations of the code bu...
[ "You can extract the a tag using select_one with the css selector 'span.engine-icon.year + p > a' and then get the text using get_text.\nFor example, if you were looking at a car from pakwheels.com [the html in your screenshot looks like just like this site's], then\nr = requests.get('https://www.pakwheels.com/used...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074213614_beautifulsoup_python_web_scraping.txt
Q: How create endpoints in multiple files? I'm building an API in using Flkas, but when I try place endpoints at multiple files importing with "import" to organize my api, only works one file route. My first file teste.py: from flask import Flask, jsonify, request app = Flask(__name__) import teste2 livros = [ {...
How create endpoints in multiple files?
I'm building an API in using Flkas, but when I try place endpoints at multiple files importing with "import" to organize my api, only works one file route. My first file teste.py: from flask import Flask, jsonify, request app = Flask(__name__) import teste2 livros = [ { 'id': 1, 'título': 'O Senhor...
[ "In order to have view functions in different files, Flask's documentation recommends using blueprints.\nIn your case, you can try something like:\nteste.py\nfrom flask import Flask, jsonify, request, Blueprint\n\nfirst_blueprint = Blueprint('first_blueprint', __name__)\n\n\n# notice the change in the route\n@first...
[ 1 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074213961_flask_python.txt
Q: How to spawn multiple workers to read a dataset with Ray? I have a Ray dataset that I created with: items = ray.data.read_datasource( TarDatasource(extra_tar_flags="--strip-components 2", profile=True), paths=S3_SOURCE_URL, filesystem=fs, include_paths=True, ) total_items = items.count() Right no...
How to spawn multiple workers to read a dataset with Ray?
I have a Ray dataset that I created with: items = ray.data.read_datasource( TarDatasource(extra_tar_flags="--strip-components 2", profile=True), paths=S3_SOURCE_URL, filesystem=fs, include_paths=True, ) total_items = items.count() Right now, counting the number of items in this dataset is very slow be...
[ "FYI, the discussion of this same question happened here: https://discuss.ray.io/t/how-to-increase-parallelism-for-dataset-count/7864\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x", "ray" ]
stackoverflow_0074035718_python_python_3.x_ray.txt
Q: Finding cell using Pygsheets and update cells in the same column I need to update every week a calendar in a Google Sheet with some numbers. I'm using pygsheets find to find the date, but them I am unable to get the column of that cell so I can update some rows within that column. enter code here for key in list: ...
Finding cell using Pygsheets and update cells in the same column
I need to update every week a calendar in a Google Sheet with some numbers. I'm using pygsheets find to find the date, but them I am unable to get the column of that cell so I can update some rows within that column. enter code here for key in list: sheet_name = list[key] print(sheet_name) # Access the shee...
[ "Answer:\nYou can get the column value by using Cell.col.\nMore Information & Example:\nAs per the pygsheets documentation on the Cell class, there is a col value:\n\ncol\nColumn number of the cell.\n\nimport pygsheets\n\ngc = pygsheets.authorize()\nss = gc.open_by_key('sheet-id')\nsheet = ss.worksheet_by_title(she...
[ 1, 0 ]
[]
[]
[ "google_sheets", "pygsheets", "python" ]
stackoverflow_0064138190_google_sheets_pygsheets_python.txt
Q: Create dictionary {(row, column): cell value} from dataframe From a given dataframe, I am trying to create a dictionary with the following format: {(row, column):'cell value'}. I am aware of pandas.DataFrame.to_dict, but that creates a dictionary of dictionaries: {row:{column:'cell value'}}. Would you have any cod...
Create dictionary {(row, column): cell value} from dataframe
From a given dataframe, I am trying to create a dictionary with the following format: {(row, column):'cell value'}. I am aware of pandas.DataFrame.to_dict, but that creates a dictionary of dictionaries: {row:{column:'cell value'}}. Would you have any code suggestions? Would loop be a good idea?
[ "You could loop over the rows and columns and use .loc to get the corresponding value.\n{(row, col): df.loc[row, col] for row in df.index for col in df.columns}\n\nFor demonstration, if df is:\n max_speed shield\ncobra 1 2\nviper 4 5\nsidewinder 7 8...
[ 1, 0 ]
[ "You can use this code it's makeing your data fram to list of dictionary's\nPanda.DataFrame.to_dict(orient=\"records\")\n\nThen using a for loop\n" ]
[ -1 ]
[ "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074213658_dataframe_dictionary_pandas_python.txt
Q: How would I dynamically update buttons in PYSimpleGUI I am trying to create a looping text based "choose your own adventure" story game. The code is built into separate functions. Each function has a story element (returned in text format), a selection of player choices used for updating the text on the buttons (r...
How would I dynamically update buttons in PYSimpleGUI
I am trying to create a looping text based "choose your own adventure" story game. The code is built into separate functions. Each function has a story element (returned in text format), a selection of player choices used for updating the text on the buttons (returned in dictionary format) and then the next functions t...
[ "The short answer you can get what you want through selectively hiding buttons, but cannot change the layout once the window is built. The 'fixed layout' is a core requirement of PySimpleGUI.\nYou can make a page with enough buttons for any element in the game, say five. One each story element, you set the text o...
[ 1, 0 ]
[]
[]
[ "button", "function", "loops", "pysimplegui", "python" ]
stackoverflow_0074189254_button_function_loops_pysimplegui_python.txt
Q: Django - Custom Form Template cannot find Template Error: Internal Server Error: /clients/service/edit_equipment/133 Traceback (most recent call last): File "/home/wcadev/.local/lib/python3.8/site-packages/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(...
Django - Custom Form Template cannot find Template
Error: Internal Server Error: /clients/service/edit_equipment/133 Traceback (most recent call last): File "/home/wcadev/.local/lib/python3.8/site-packages/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "/home/wcadev/.local/lib/py...
[ "Looks like Django, in the current configuration, isn't even looking in the main Templates directory. I've moved it to an app directory and it's working. This solves my challenge.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0074213982_django_django_forms_python.txt
Q: Shared memory between C and python I want to share memory between a program in C and another in python. The c program uses the following structure to define the data. struct Memory_LaserFrontal { char Data[372]; // original data float Med[181]; // Measurements in [m] charD; // 'I': Invalid ...
Shared memory between C and python
I want to share memory between a program in C and another in python. The c program uses the following structure to define the data. struct Memory_LaserFrontal { char Data[372]; // original data float Med[181]; // Measurements in [m] charD; // 'I': Invalid -- 'V': Valid charS; // 'L': Cle...
[ "You need to unpack your binary data structure into Python types. The Python modules struct and array can do this for you.\nimport struct\nimport array\n\nNB: Some C compilers, but not the comomn ones, may pad your member variables to align each of them with the expected width for your CPU ( almost always 4 bytes )...
[ 0, -1 ]
[]
[]
[ "c", "python", "shared_memory", "sysv_ipc" ]
stackoverflow_0074200079_c_python_shared_memory_sysv_ipc.txt
Q: Matplotlib graphing distribution with two colors The goal here is to color value above a certain threshold into one color and values below this threshold into another color. The code below tries to just separate it into two histographs but it only looks balanced if the threshold is at 50%. I'm assuming I must play...
Matplotlib graphing distribution with two colors
The goal here is to color value above a certain threshold into one color and values below this threshold into another color. The code below tries to just separate it into two histographs but it only looks balanced if the threshold is at 50%. I'm assuming I must play around with the discreetlevel variable. finalutility...
[ "This solution is a bit more complex than @user2699's. I am just presenting it for completeness. You have full control over the patch objects that hist returns, so if you can ensure that the threshold you are using is exactly on a bin edge, it is easy to change to color of selected patches. You can do this because ...
[ 3, 1, 0 ]
[]
[]
[ "matplotlib", "probability", "python" ]
stackoverflow_0040222996_matplotlib_probability_python.txt
Q: How to maintain order of data frame when making pandas pivot table trying to make a heat map out of a pivot table but am having trouble keeping the order of how I sorted my original data frame. Below is a sample code of what my data looks exactly like and how I made my pivot table. simple_df = pd.DataFrame({'Skill...
How to maintain order of data frame when making pandas pivot table
trying to make a heat map out of a pivot table but am having trouble keeping the order of how I sorted my original data frame. Below is a sample code of what my data looks exactly like and how I made my pivot table. simple_df = pd.DataFrame({'Skill 1': ['Python','Python','Python','Communication','Communication','Commun...
[ "You can save the original order and then use reindex to swap the columns and rows.\noriginal_order = simple_df[\"Skill 1\"].unique()\n(simple_df.pivot(index=\"Skill 1\", columns=\"Skill 2\", values=\"Score\")\n .reindex(index=original_order, columns=original_order))\n\n\nSkill 2 Data Governance Python C...
[ 2 ]
[]
[]
[ "pandas", "pivot", "python", "sorting" ]
stackoverflow_0074214041_pandas_pivot_python_sorting.txt
Q: How to get return value of c++ int main() output using subprocess.check_output() in python script I am using a C++ script as follows: int main(){ int x =7; std::cout<<"print num:"<<x<<std::endl; if(x>0){ std::cout<<" good"<<std::endl; return 5; } return 0; } For this in my python file I am calling the su...
How to get return value of c++ int main() output using subprocess.check_output() in python script
I am using a C++ script as follows: int main(){ int x =7; std::cout<<"print num:"<<x<<std::endl; if(x>0){ std::cout<<" good"<<std::endl; return 5; } return 0; } For this in my python file I am calling the subprocess as follows: result0_1 = subprocess.check_output(MYCPP_fILE_PATH,shell =True) print(result0_1.d...
[ "From Python 3 docs\nAnd very similar Python 2 docs\n\nIf the return code was non-zero it raises a CalledProcessError. The\nCalledProcessError object will have the return code in the returncode\nattribute and any output in the output attribute.\n\n" ]
[ 3 ]
[]
[]
[ "c++", "cout", "python", "return_value", "subprocess" ]
stackoverflow_0074214333_c++_cout_python_return_value_subprocess.txt
Q: Python pip3 install error Librosa M1 Silicon Chip I am trying to install the library librosa into my python3 environment. When I run pip3 install librosa I am greeted with this error, subprocess.CalledProcessError: Command '['meson', 'setup', '--native-file=/private/var/folders/nd/pcbm774s1mv18bkfzgvk2g480000gn/T...
Python pip3 install error Librosa M1 Silicon Chip
I am trying to install the library librosa into my python3 environment. When I run pip3 install librosa I am greeted with this error, subprocess.CalledProcessError: Command '['meson', 'setup', '--native-file=/private/var/folders/nd/pcbm774s1mv18bkfzgvk2g480000gn/T/pip-install-78ukqo1x/scipy_2253c8d2f45740a7acf86c6f0c0...
[ "Not necessarily a solution, but if you become as desperate as me;\nI hosted a virtual Windows 10 machine on Azure and downloaded PyCharm there. Make sure your Python isn't the newest - librosa only works with 3.7 >= and < 3.11 - after I got this windows machine running, correct Python version installed, Librosa fi...
[ 0 ]
[]
[]
[ "librosa", "pycharm", "python", "python_3.x" ]
stackoverflow_0074188055_librosa_pycharm_python_python_3.x.txt
Q: How to encrypt/decrypt a configuration file in python I have a python application which read a configuration file. I need to encrypt the configuration file so it's not plain on disk. Then I need to decrypt it in my app and read the values. I see there is one library Secureconfig but it's only for python 2. Is ther...
How to encrypt/decrypt a configuration file in python
I have a python application which read a configuration file. I need to encrypt the configuration file so it's not plain on disk. Then I need to decrypt it in my app and read the values. I see there is one library Secureconfig but it's only for python 2. Is there a similar lib in python that can help me do that?
[ "Since your program will have to contain the decryption key, you won't be able to protect the data from a determined user, only make decrypting it somewhat harder.\nAs per Cryptographic Services — Python 3.7.3 documentation, Python doesn't include any true ciphers out of the box. Only codecs have Caesar's cipher an...
[ 1, 0, 0, 0 ]
[]
[]
[ "configuration_files", "encryption", "python" ]
stackoverflow_0055839060_configuration_files_encryption_python.txt
Q: How to read large sas file with pandas and export to parquet using multiprocessing? i'm trying to make a scrip that read a sasb7dat file and export to parquet using pandas, but i'm struggling to increase my performance with large files (>1Gb and more de 1 million rows). Doing some research, i found that using mult...
How to read large sas file with pandas and export to parquet using multiprocessing?
i'm trying to make a scrip that read a sasb7dat file and export to parquet using pandas, but i'm struggling to increase my performance with large files (>1Gb and more de 1 million rows). Doing some research, i found that using multiprocessing could help me, but i can't make it work. The code runs with no errors, but no...
[ "You use the term multiprocessing all over the place yet your code is not using multiprocessing but rather multithreading. It appears that you are trying to break up the input file into dataframe chunks and have each chunk become a separate output file. If that is so, you would want to pass each chunk to you worker...
[ 1 ]
[]
[]
[ "large_files", "multiprocessing", "pandas", "python" ]
stackoverflow_0074210128_large_files_multiprocessing_pandas_python.txt
Q: Is there a way to add values from one key in a dictionary to the values of the same key in another dictionary? i have one dict structured like this: d1 = {'837729451428151376': {'Username': 'CatCam', 'Mana': 3, 'HP': 10000, 'Location': 'Crossroads', 'SC': 10, 'Rage': 0, 'InitManaDate': 1666875873, 'NextMana': 1666...
Is there a way to add values from one key in a dictionary to the values of the same key in another dictionary?
i have one dict structured like this: d1 = {'837729451428151376': {'Username': 'CatCam', 'Mana': 3, 'HP': 10000, 'Location': 'Crossroads', 'SC': 10, 'Rage': 0, 'InitManaDate': 1666875873, 'NextMana': 1666875873, 'ReadyInventory': '\n goodiebag', 'EquippedInventory': ' ', 'ReadyDate': 1666818273, 'Lastactiontime'...
[ "Try:\nfor k, v in d2.items():\n if k in d1:\n d1[k][\"SC\"] = v[\"SC\"]\n\nprint(d1)\n\nPrints:\n{\n \"837729451428151376\": {\n \"Username\": \"CatCam\",\n \"Mana\": 3,\n \"HP\": 10000,\n \"Location\": \"Crossroads\",\n \"SC\": 2,\n \"Rage\": 0,\n \"In...
[ 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074214377_dictionary_python.txt
Q: pydrake: How do I aggregate multiple List[ExternallyAppliedSpatialForce] from distinct systems for a plant? I am testing out some simple controllers, and would like to know how to aggregate List[ExternallyAppliedSpatialForce], specifically to provide to MultibodyPlant.get_applied_spatial_force_input_port(). If I t...
pydrake: How do I aggregate multiple List[ExternallyAppliedSpatialForce] from distinct systems for a plant?
I am testing out some simple controllers, and would like to know how to aggregate List[ExternallyAppliedSpatialForce], specifically to provide to MultibodyPlant.get_applied_spatial_force_input_port(). If I try to connect both outputs to it, I get the following error: RuntimeError: Input port is already wired. For more...
[ "A few ways that I know of (thus far), with some notes:\n1. Aggregate the lists of external forces as an intermediate system\nThis can be done relatively easily. See rough example system here: \nhttps://gist.github.com/EricCousineau-TRI/f774b936aa930cf29777ed411815bbce#file-external_force_aggregator_system-py\n2. C...
[ 0, 0 ]
[]
[]
[ "drake", "python" ]
stackoverflow_0074075528_drake_python.txt
Q: How do I save incremented Numbers and calculate them? I want to write myself a program where a variable is going to increment everytime in the while-loop and want at the end, that all values will be stored in a list. At the end the values of the list should be summed with sum(). My problem is that when I execute m...
How do I save incremented Numbers and calculate them?
I want to write myself a program where a variable is going to increment everytime in the while-loop and want at the end, that all values will be stored in a list. At the end the values of the list should be summed with sum(). My problem is that when I execute my program it just let me show the last number of all. I wan...
[ "def calc_cost():\n x = 0\n k = 34\n j = 0\n\n l = []\n\n while x <= k:\n x = x + 1\n j = j + 5\n\n l.append(j)\n \n print(l)\n return sum(l)\n \n\nprint(calc_cost())\n\nI made the edit I suggested. I also returned the sum so it could be printed by the line: prin...
[ 0 ]
[]
[]
[ "append", "calculation", "python", "sum", "while_loop" ]
stackoverflow_0074214400_append_calculation_python_sum_while_loop.txt
Q: Splitting in Python says to me, "IndexError: list index out of range" I have this function. blocklist_data = unpack_blocklist_data() hostnames = [] for entry in blocklist_data: if not entry.startswith('#'): hostname = entry.split() if len(hostname) == 1: hostnames.append(hostname[0]...
Splitting in Python says to me, "IndexError: list index out of range"
I have this function. blocklist_data = unpack_blocklist_data() hostnames = [] for entry in blocklist_data: if not entry.startswith('#'): hostname = entry.split() if len(hostname) == 1: hostnames.append(hostname[0]) else: hostnames.append(hostname[1]) return hostnames blacklist_d...
[ "Based on the comments you can also try to solve it in a single line via list comprehensions with:\nhostnames = [x.split()[0] if len(x.split()) == 1 else x.split()[1] for x in blocklist_data if (len(x) > 0 and not x.startswith(\"#\"))]\n\nBased on the following example:\nblocklist_data = ['','0.0.0.0 site.domain.or...
[ 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0074214350_python_split.txt
Q: Object to dictonary to use get() python pandas I'm having some issues with a column in my csv that the type is an 'object', but it's should be an dict series (a dict for which row). The point is to make which row as a dict to use get('id') on the key to return the id's values for which row in the 'Conta' column. T...
Object to dictonary to use get() python pandas
I'm having some issues with a column in my csv that the type is an 'object', but it's should be an dict series (a dict for which row). The point is to make which row as a dict to use get('id') on the key to return the id's values for which row in the 'Conta' column. Thats the way it's as 'object' column: | Conta ...
[ "Consider replacing the following line:\ndf['Conta'] = df['Conta'].apply(ast.literal_eval)\n\nIf it's being correctly detected as a dictionary then:\ndf['Conta'] = df['Conta].map(lambda x: x['id'])\n\nIf each row is a string:\ndf['Conta'] = df['Conta'].map(lambda x: ast.literal_eval(x)['id'])\n\nHowever, if you are...
[ 1 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074214473_csv_pandas_python.txt
Q: problem rising events with keyboard clicks in PySimpleGUI I tried to find codes online about rising events in my PySimpleGUI program by simple keyboard clicks like ENTER or Ctrl+A for instance but I couldn't just find any about it, I went to the documentation of PySimpleGUI and didn't shut my tap without learning ...
problem rising events with keyboard clicks in PySimpleGUI
I tried to find codes online about rising events in my PySimpleGUI program by simple keyboard clicks like ENTER or Ctrl+A for instance but I couldn't just find any about it, I went to the documentation of PySimpleGUI and didn't shut my tap without learning a thing. Here is a simple code i wrote: import PySimpleGUI as s...
[ "Option required for element\n\nsg.Input(do_not_clear=False, key='In') clear input field after event\nsg.Button('Ok', bind_return_key=True) the return key will cause this button to be pressed\n\nimport PySimpleGUI as sg\n\nlayout = [[sg.I(do_not_clear=False, key='In'), sg.B('Ok', bind_return_key=True)],[sg.T(enable...
[ 0, 0 ]
[]
[]
[ "keyboard_events", "pysimplegui", "python" ]
stackoverflow_0074172768_keyboard_events_pysimplegui_python.txt
Q: Getting images from the satellite, using python I want to create a project, one part of which is getting forest images for analysis. using python, i want to analyze the forest. I need to get images of every kilometer. for example, as on Google maps everything is marked with squares, so I want to analyze such a squ...
Getting images from the satellite, using python
I want to create a project, one part of which is getting forest images for analysis. using python, i want to analyze the forest. I need to get images of every kilometer. for example, as on Google maps everything is marked with squares, so I want to analyze such a square as a separate image I want it to be desirable for...
[ "Data Analysis\nfrom glob import glob\n\nimport earthpy as et\nimport earthpy.spatial as es\nimport earthpy.plot as ep\n\nimport rasterio as rio\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.colors import ListedColormap\n\nimport plotly.graph_objects as go\n\nnp.seterr(divide='ignore', inv...
[ 0 ]
[]
[]
[ "api", "data_science", "image", "python", "satellite" ]
stackoverflow_0074214452_api_data_science_image_python_satellite.txt