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: Python Web Scraping Not Working -- Multiple Pages Project I'm fairly new to webscraping and have been working on a project to scrape data from a jobbank site. I wanted to know why my code isn't working. When running as a single site, it works just fine, I'm not sure what I'm doing wrong in regards to multiple page...
Python Web Scraping Not Working -- Multiple Pages Project
I'm fairly new to webscraping and have been working on a project to scrape data from a jobbank site. I wanted to know why my code isn't working. When running as a single site, it works just fine, I'm not sure what I'm doing wrong in regards to multiple pages. import libraries from bs4 import BeautifulSoup import reques...
[ "pages = np.arange (37001458, 37001470, 1)\n\nfor page in pages:\n \n URL = 'https://www.jobbank.gc.ca/jobsearch/jobposting/' + str(page)\n sleep(randint(1,5))\n\npage = requests.get(URL, headers=headers)\n\nThis loop creates a url string, and then immediately recreates it with a different number on the en...
[ 0 ]
[]
[]
[ "beautifulsoup", "numpy", "pandas", "python", "web_scraping" ]
stackoverflow_0074159918_beautifulsoup_numpy_pandas_python_web_scraping.txt
Q: Compute cumulative sum of negative and positive sequences Here is my dataframe: import pandas as pd my_df = pd.DataFrame({'col_1': [1,2,5,6,4,3,7,8,9,11,14]}) my_df['diff'] = my_df['col_1'].diff() my_df['cond_sum'] = [None, 1,4,5,-2,-3,4,5,6,8,11] My original column is col_1. My goal is to obtain column cond_sum....
Compute cumulative sum of negative and positive sequences
Here is my dataframe: import pandas as pd my_df = pd.DataFrame({'col_1': [1,2,5,6,4,3,7,8,9,11,14]}) my_df['diff'] = my_df['col_1'].diff() my_df['cond_sum'] = [None, 1,4,5,-2,-3,4,5,6,8,11] My original column is col_1. My goal is to obtain column cond_sum. diff column is difference between consecutive rows. cond_sum i...
[ "Get the sign of your diff, then create a groupby statement and calculate the cumsum\nimport numpy as np\nimport pandas as pd\nmy_df = pd.DataFrame({'col_1': [1,2,5,6,4,3,7,8,9,11,14]})\nmy_df['diff'] = my_df['col_1'].diff()\n\nsign = np.sign(my_df['diff'])\ngroupby_ = (sign != sign.shift(1)).cumsum()\nmy_df['cond_...
[ 2 ]
[]
[]
[ "difference", "pandas", "python" ]
stackoverflow_0074159887_difference_pandas_python.txt
Q: Closing a window with close() will close all open windows I am using Python and I have a main window with a button that opens another window which contain stackedWidget, when the user click "Finish" on the second window I want to close it. but when i try to use self.close() method it closing the main windows as we...
Closing a window with close() will close all open windows
I am using Python and I have a main window with a button that opens another window which contain stackedWidget, when the user click "Finish" on the second window I want to close it. but when i try to use self.close() method it closing the main windows as well. here is the part in my code that handle the Finish click ev...
[ "The problem isn't that it is closing both windows, it's that your whole app is crashing because it has reached the maximum recursion depth.\nThe issue is with your close method.\n def close(self):\n self.close()\n\nAll this is doing is calling itself over and over and over again until it crashes the prog...
[ 0 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0074156927_pyqt5_python.txt
Q: More efictive method of test large dataframe and add value based on another value different size/not merge Lot of answers on merging and full col, but can't figure out a more effective method. for my situation. current version of python, pandas, numpy, and file format is parquet Simply put if col1 ==x the col 10 =...
More efictive method of test large dataframe and add value based on another value different size/not merge
Lot of answers on merging and full col, but can't figure out a more effective method. for my situation. current version of python, pandas, numpy, and file format is parquet Simply put if col1 ==x the col 10 = 1, col11 = 2, col... etc. look1 = 'EMPLOYEE' look2 = 'CHESTER' look3 = "TONY'S" look4 = "VICTOR'S" tgt1 = 'inv...
[ "Flying blind here since I don't see your data:\ncond_list = [df[\"ph_name\"] == look for look in [look1, look2, look3, look4]]\n\n# Rows ph_name outside of the list will keep their original values\ndf[tgt1] = np.select(cond_list, [\"MEMORIAL\", \"WALMART\", \"TONY'S\", \"VICTOR\"])\ndf[tgt2] = np.select(cond_list,...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "parquet", "python", "query_optimization" ]
stackoverflow_0074159387_dataframe_pandas_parquet_python_query_optimization.txt
Q: python pandas translate text to english Hello I have a DataFrame from pandas that looks like this: import pandas as pd df = pd.DataFrame({"language": ["en", "it", "en", "it"], "text": ["Hello", "Ciao", "This is english text", "Questo è un testo italiano"]}) I would like to translate all italian...
python pandas translate text to english
Hello I have a DataFrame from pandas that looks like this: import pandas as pd df = pd.DataFrame({"language": ["en", "it", "en", "it"], "text": ["Hello", "Ciao", "This is english text", "Questo è un testo italiano"]}) I would like to translate all italian text to english. How can I do this?
[ "I agree that it is probably not a very good design like nbk has pointed out already.\nI've answered something similar here a few days ago which might be helpful.\nTo answer your question:\nUsing google translator, you can do:\nfrom deep_translator import GoogleTranslator\ngt = GoogleTranslator(source='it', target=...
[ 0 ]
[]
[]
[ "pandas", "python", "translate", "translators" ]
stackoverflow_0074159874_pandas_python_translate_translators.txt
Q: How to predict new data with trained sklearn model - Random Forest Regressor? I am making a sklearn model (Random Forest Regressor), and have been successful in training it with my data, however, I am unsure of how to predict it. My CSV contains 2 items per row, a year (expressed in years since 2003), and a number...
How to predict new data with trained sklearn model - Random Forest Regressor?
I am making a sklearn model (Random Forest Regressor), and have been successful in training it with my data, however, I am unsure of how to predict it. My CSV contains 2 items per row, a year (expressed in years since 2003), and a number (what's being predicted), usually above 1,000. When I use model.predict([[20]]), I...
[ "Your data has been scaled, so your predictions are not in the original range of the TOTAL variable. You can try to train your model without scaling the data and results are still quite good.\nI would recommend scaling only the training set, to avoid leaking information about the whole dataset into the test set. An...
[ 1 ]
[]
[]
[ "python", "random_forest", "scikit_learn" ]
stackoverflow_0074159736_python_random_forest_scikit_learn.txt
Q: Unable to locate element (error selenium python) I'm making a web scraper script in python and I need to navigate between pages. All good 'till page # 4, but when it's in the last one I get the following error: Unable to locate element: {"method":"xpath","selector":"//ul[@class="pagination"]/li/span[@onclick="GoT...
Unable to locate element (error selenium python)
I'm making a web scraper script in python and I need to navigate between pages. All good 'till page # 4, but when it's in the last one I get the following error: Unable to locate element: {"method":"xpath","selector":"//ul[@class="pagination"]/li/span[@onclick="GoToPage(5)"]"} This is my code: import os import time f...
[ "There is no span element exists in that web page with onclick=\"GoToPage(5)\" it's onclick=\"GoToPage(0 + 1)\"\nYou can do this,\n... your code ...\n\nfor i in range(len(address)):\n try:\n print(\n f'{i} {address[i].text} {price[i].text} {n_of_bed[i].text}')\n\n except IndexError:\n ...
[ 0 ]
[]
[]
[ "data_extraction", "python", "selenium", "web_scraping" ]
stackoverflow_0074160043_data_extraction_python_selenium_web_scraping.txt
Q: How to do the retries based on an http error code using Python Backoff Library? I'm trying to implement the retry mechanism for certain exceptions and a specific http error code 408. Here's how my current snippet looks like: @backoff.on_exception( backoff.expo, (requests.exceptions.ReadTimeout, requests.ex...
How to do the retries based on an http error code using Python Backoff Library?
I'm trying to implement the retry mechanism for certain exceptions and a specific http error code 408. Here's how my current snippet looks like: @backoff.on_exception( backoff.expo, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout), max_tries=MAX_TIMEOUT_RETRY_COUNT) def get_response_htt...
[ "try the giveup keyword\ndef fatal_code(e):\n return 400 <= e.response.status_code < 500\n\n@backoff.on_exception(backoff.expo,\n requests.exceptions.RequestException,\n max_time=300,\n giveup=fatal_code)\ndef get_url(url):\n return requests.get(u...
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_requests" ]
stackoverflow_0074136992_python_python_3.x_python_requests.txt
Q: Pandas Resample creating new hourly data I am using the resample funtion to go from minute data to hour data. The issue is my original DF has only from 10:30 to 15:59 data and the new resampled data is creating new hour data. How to I get rid of this data or have it resample only the time stamps on the index and n...
Pandas Resample creating new hourly data
I am using the resample funtion to go from minute data to hour data. The issue is my original DF has only from 10:30 to 15:59 data and the new resampled data is creating new hour data. How to I get rid of this data or have it resample only the time stamps on the index and not create new ones. This is how the original D...
[ "Filter by time column is what you need? Try this;\nbegin_ts = '9/28/2020: 10:30' \nend_ts = '9/28/2020: 15:30'\n\ndf.set_index('time',inplace=True)\nnew_df = df.iloc[df.index.get_loc(begin_ts):df.index.get_loc(begin_ts)].copy()\n\nHaving said that, please consider indexing with a better index like timestamp.\n", ...
[ 0, 0 ]
[]
[]
[ "nan", "pandas", "pandas_resample", "python" ]
stackoverflow_0074159760_nan_pandas_pandas_resample_python.txt
Q: How to POST the refresh token to Flask JWT Extended? I am trying to refresh a JWT token from the code here. The issue is with how to get the new token with the refresh. This works: curl http://127.0.0.1:5000/protected {"msg":"Missing Authorization Header"} This works and I get my token and put it in ACCESS curl ...
How to POST the refresh token to Flask JWT Extended?
I am trying to refresh a JWT token from the code here. The issue is with how to get the new token with the refresh. This works: curl http://127.0.0.1:5000/protected {"msg":"Missing Authorization Header"} This works and I get my token and put it in ACCESS curl -H "Content-Type: application/json" -X POST -d '{"userna...
[ "Try \ncurl -H \"Authorization: Bearer $REFRESH\" -X POST http://localhost:5000/refresh\n\n", "For me only this worked, both were required - post data and Auth header.\n curl -X POST -H \"Content-Type: Application/json\" -H \"Authorization: Bearer $REFRESH\" -d \"{\\\"refresh_token\\\":\\\"$REFRESH\\\"}\" http://...
[ 8, 0 ]
[ "First, when creating a new user you should ensurer that you created both the access_key and the refresh_key (there are flask-jwt-extended functions for that).\nThen you have to create an endpoint, which requires the refresh_key (through @jwt.required(refresh=True)). This says: Give me specifically the refresh key....
[ -2 ]
[ "flask", "flask_jwt_extended", "python" ]
stackoverflow_0055089892_flask_flask_jwt_extended_python.txt
Q: How to apply aggregate functions to numpy matrices? I'm trying to pass a function which returns binary integers given an array (row) and apply to a matrix. Row input -> [1,1,1]; desired output -> 1 def gen_y(X): if np.sum(X) > 2: return 1 elif np.sum(X) < 2: return 0 else: return int(np.random....
How to apply aggregate functions to numpy matrices?
I'm trying to pass a function which returns binary integers given an array (row) and apply to a matrix. Row input -> [1,1,1]; desired output -> 1 def gen_y(X): if np.sum(X) > 2: return 1 elif np.sum(X) < 2: return 0 else: return int(np.random.uniform(0,1) > 0.5) The input is of shape (100,3) wher...
[ "Your function - without the random which confuses testing:\nIn [148]: def gen_y(X):\n ...: if np.sum(X) > 2:\n ...: return 1 \n ...: elif np.sum(X) < 2:\n ...: return 0 \n ...: else:\n ...: return 2 # random is not good for testing\n ...: \n\nIn [149]: arr = np.arr...
[ 0 ]
[]
[]
[ "arrays", "matrix", "numpy", "python" ]
stackoverflow_0074159141_arrays_matrix_numpy_python.txt
Q: How to extract URL from browser search bar Python? Lack of knowledge Wrote a script in python selenium that enters the page, enters the number and presses the button, then goes to the new URL. How can I extract the URL I'm on from the browser's address bar? import pandas as pd from bs4 import BeautifulSoup import ...
How to extract URL from browser search bar Python? Lack of knowledge
Wrote a script in python selenium that enters the page, enters the number and presses the button, then goes to the new URL. How can I extract the URL I'm on from the browser's address bar? import pandas as pd from bs4 import BeautifulSoup import requests from urllib.parse import urlparse, urljoin from selenium import w...
[ "You should be able to grab the current url using browser.current_url\n" ]
[ 2 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074160046_python_selenium_selenium_chromedriver.txt
Q: Adding shapes in plotly - digital signals plotting I am trying to plot digital signals with a non existing format in plotly, which consists in thin lines in case value = 0, and thick lines in case value = 1. For doing this, I am drawing an horizontal line and adding rectangles in case signal's value=1. As I have ...
Adding shapes in plotly - digital signals plotting
I am trying to plot digital signals with a non existing format in plotly, which consists in thin lines in case value = 0, and thick lines in case value = 1. For doing this, I am drawing an horizontal line and adding rectangles in case signal's value=1. As I have to plot many signals, I am working with subplots. The pr...
[ "Only a couple of changes to your code: move dictionaries outside the for loop and specify yref\ndictionaries=[]\n\nfor k in range(2):\n\ntiempo_flancos=[] #to save the amount of state changes\n\nif y[k,0]==1:\n tiempo_flancos.append(x[0])\n \n\nfor i in range(1,len(x)):\n if y[k,i]!=y[k,i-1]:\n tie...
[ 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074157431_plotly_python.txt
Q: How do you turn a list of (x,y) coordinate points into a list of integers in the same format? This is the input and output I am looking for given the user input I want to do this using a function. I am assuming you will have to iterate through each set of points to convert them to integers, then back to a list? A...
How do you turn a list of (x,y) coordinate points into a list of integers in the same format?
This is the input and output I am looking for given the user input I want to do this using a function. I am assuming you will have to iterate through each set of points to convert them to integers, then back to a list?
[ "Partial answer:\nimport re\n\na = '3,4 5,6 7,8 12,8 3,456'\n\nNow you could use:\nraw_coords = re.findall(r'[0-9]+,[0-9]+', a)\n\nBut then you'd have to use more regex to extract x and y from each \"x,y\" string\nA more straightforward way would be to separately extract the x values and y values from your initial ...
[ 0 ]
[]
[]
[ "integer", "list", "python", "string" ]
stackoverflow_0074160027_integer_list_python_string.txt
Q: Flattening dataframe Json column to new rows in Python I am new to Python. I have dataframe obtained from SQL query result UserId UserName Reason_details 851 Bob [ {"reasonId":264, "reasonDescription":"prohibited", "reasonCodes":[1 , 2]} , {"reasonId":267, "reasonDescription":"Expired", "reasonCodes":[25]} ] 85...
Flattening dataframe Json column to new rows in Python
I am new to Python. I have dataframe obtained from SQL query result UserId UserName Reason_details 851 Bob [ {"reasonId":264, "reasonDescription":"prohibited", "reasonCodes":[1 , 2]} , {"reasonId":267, "reasonDescription":"Expired", "reasonCodes":[25]} ] 852 Jack [{"reasonId":273, "reasonDescription":"Restric...
[ "can you try this:\ndf=df.explode('Reason_details')\ndf = df.join(df['Reason_details'].apply(pd.Series)).drop('Reason_details',axis=1).explode('reasonCodes').drop_duplicates()\n\n\n", "here is a slight different manner\ndf[['UserId', 'UserName']].merge(df['Reason_details']\n .explo...
[ 4, 0 ]
[]
[]
[ "dataframe", "flatten", "json_normalize", "pandas", "python" ]
stackoverflow_0074158919_dataframe_flatten_json_normalize_pandas_python.txt
Q: how to add a Date column to existing csv file in python I have a Json file that I am converting and appending to a csv, and I am trying to also add a date column in the month/day/year format. latest attempt: import json from csv import DictWriter import pandas as pd import datetime with open('output.json', 'r') as...
how to add a Date column to existing csv file in python
I have a Json file that I am converting and appending to a csv, and I am trying to also add a date column in the month/day/year format. latest attempt: import json from csv import DictWriter import pandas as pd import datetime with open('output.json', 'r') as inp, open('output.csv', 'a') as outp: writer = DictWrite...
[ "You can do this all in pandas directly:\nimport pandas as pd\n\ndf = pd.read_json('output.json', orient='records', lines=True)\ndf['Date'] = pd.to_datetime('today').strftime('%m/%d/%Y')\ndf.to_csv('adate.csv', index=False)\n\nOutput (for your sample data):\nname,price,Date\nLattice Top 6'W x 6'H King Cedar Aluminu...
[ 1, 1, 1 ]
[]
[]
[ "csv", "json", "python" ]
stackoverflow_0074117295_csv_json_python.txt
Q: Make pylint throw a warning at desired locations I want to make pylint throw a warning at a custom point in my code without adding bugs to the code. For example I created a function my_fun() with a hardcoaded output so I can call it elsewhere ex: def get_value(): return 7 I want to put something in my code to...
Make pylint throw a warning at desired locations
I want to make pylint throw a warning at a custom point in my code without adding bugs to the code. For example I created a function my_fun() with a hardcoaded output so I can call it elsewhere ex: def get_value(): return 7 I want to put something in my code to throw a warning so i do not leave it like this by acc...
[ "I had this issue and found that pylint will give a warning on the the word TODO ie\ndef get_value()\n return 7\n # TODO: remove hardcoded value\n\nwill give a warning of type W0511:fixme with the message TODO: remove hardcoded value\nif you want to suppress this message without deleting it then\n# TODO_: rem...
[ 1 ]
[]
[]
[ "pylint", "python", "warnings" ]
stackoverflow_0074160248_pylint_python_warnings.txt
Q: Send Multiple Terminal Commands in Gnome Terminals With Subprocess So I am currently trying to run two different gnome-terminal windows in Ubuntu that I can send individual commands to after they are initially open. def ssh_command(cmd): ssh_terminal_1 = subprocess.Popen(['gnome-terminal', '--', 'bash', '-c', cmd...
Send Multiple Terminal Commands in Gnome Terminals With Subprocess
So I am currently trying to run two different gnome-terminal windows in Ubuntu that I can send individual commands to after they are initially open. def ssh_command(cmd): ssh_terminal_1 = subprocess.Popen(['gnome-terminal', '--', 'bash', '-c', cmd], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, stdin=subprocess.PI...
[ "As I explained in the comments, your pipe goes to gnome-terminal and neither to ssh nor to bash. gnome-terminal is not listening to stdin but is only listening to the user at the console. Here is what you do.\n\nMake a FIFO (named pipe) -- os.mkfifo -- for each terminal, give it a name that won't collide with any ...
[ 0 ]
[]
[]
[ "bash", "python", "subprocess", "ubuntu" ]
stackoverflow_0074158083_bash_python_subprocess_ubuntu.txt
Q: Remove empty lists in csv file in python So I have a csv file called result and I'm getting this: ID,age,sex,city,province,country [] 11816.0,44,female,NaN,Aichi [] 11814.0,64,male,Nagoya City,Aichi [] 11813.0,64,male,Nagoya City,Aichi when I just want this: 11816.0,44,female,NaN,Aichi # eac...
Remove empty lists in csv file in python
So I have a csv file called result and I'm getting this: ID,age,sex,city,province,country [] 11816.0,44,female,NaN,Aichi [] 11814.0,64,male,Nagoya City,Aichi [] 11813.0,64,male,Nagoya City,Aichi when I just want this: 11816.0,44,female,NaN,Aichi # each line is a list 11814.0,64,male,Nagoy...
[ "EDITED (after collecting more information):\nI do think that attempting to work around bad data is not worth the trouble, but to answer the question literally would require comething like this:\nwith open('result.csv') as f:\n lines = f.readlines()\n\nfor l in filter(lambda x: x.strip() != '[]', lines):\n pr...
[ 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074160211_csv_python.txt
Q: Match the sets between two column in a row I have table with two columns: Col_1 Col_2 3,4,5 3,5 8,9,12 8,9,12 8,9,12 I need to check Col_1 with Col_2 and if an element in Col_1 is present in Col_2 then save True, else save False. The output table should be: Col_1 Col_2 Check 3,4,5 3,5 True,False,True 8,9,1...
Match the sets between two column in a row
I have table with two columns: Col_1 Col_2 3,4,5 3,5 8,9,12 8,9,12 8,9,12 I need to check Col_1 with Col_2 and if an element in Col_1 is present in Col_2 then save True, else save False. The output table should be: Col_1 Col_2 Check 3,4,5 3,5 True,False,True 8,9,12 8,9,12 True,True,True 8,9...
[ "Use list comprehension with test splitted values:\ndf['check'] = [[z in y for z in x] for x, y in zip(df['Col_1'].fillna('').str.split(','), \n df['Col_2'].fillna('').str.split(','))]\nprint (df)\n Col_1 Col_2 check\n0 3,4,5 3,5 [True...
[ 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074149043_pandas_python.txt
Q: python discord.ui: get modal from view Trying to make view that shows modal dialog. Here code, with sample view that opens modal via button import discord from discord import ApplicationContext from constant import BOT_TOKEN bot = discord.Bot() class TimeRoleModal(discord.ui.Modal): def __init__(self, title:...
python discord.ui: get modal from view
Trying to make view that shows modal dialog. Here code, with sample view that opens modal via button import discord from discord import ApplicationContext from constant import BOT_TOKEN bot = discord.Bot() class TimeRoleModal(discord.ui.Modal): def __init__(self, title: str) -> None: item = discord.ui.In...
[ "There was an error in button handler - should use interaction direcly passed into button handler, not sending modal from context\n@discord.ui.button(row=2, label=\"30\", style=discord.ButtonStyle.secondary)\nasync def button2_callback(self, button: discord.ui.Button, interaction: discord.Interaction):\n modal =...
[ 2 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074152771_discord.py_python.txt
Q: How to run two functions in parallel in Python? I am trying to run two chunks of code in parallel, but fail to do so. Both functions are for loops that might take around 30 minutes to run in total, these functions in the end return a list of dictionaries as results. Running them separately works fine, but I can't ...
How to run two functions in parallel in Python?
I am trying to run two chunks of code in parallel, but fail to do so. Both functions are for loops that might take around 30 minutes to run in total, these functions in the end return a list of dictionaries as results. Running them separately works fine, but I can't get them to run in parallel... #When I run these func...
[ "Your problem is here:\nDictA = threading.Thread(target=functionA(0, 10))\n\nHere you're not passing functionA as the argument to target; you're calling functionA and passing the value to target. That's why you're functions appear to be executing synchronously rather than in parallel -- because that's how you're c...
[ 1, 1 ]
[]
[]
[ "multiprocessing", "multithreading", "parallel_processing", "python", "web_scraping" ]
stackoverflow_0074160173_multiprocessing_multithreading_parallel_processing_python_web_scraping.txt
Q: How do I fix Type error: 'function' does not support indexing Below is the code. The error is: Type error: 'function' does not support indexing on line 12 in main.py. I've tried switching the variable, looking for other people who had this same question answered but to no success. I know I am doing something wrong...
How do I fix Type error: 'function' does not support indexing
Below is the code. The error is: Type error: 'function' does not support indexing on line 12 in main.py. I've tried switching the variable, looking for other people who had this same question answered but to no success. I know I am doing something wrong, but I'm not sure what. The problem might not be on line 12 so if ...
[ "Indexing means the use of square brackets [], by which you access the nth element of a collection, in this case it is saying that len, which is a function, does not support indexing because you used len[oof] instead of len(oof). When using parenthesis you are passing oof as argument.\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.10" ]
stackoverflow_0074160322_python_python_3.10.txt
Q: How to replace NaN column value with the previous column value in pandas dataframe? I am trying to merge two dataframes that does not have equal number of rows or columns. It results in NaN values. I want to fill this NaN values with the previous value in the column. import pandas as pd import numpy as np dflist ...
How to replace NaN column value with the previous column value in pandas dataframe?
I am trying to merge two dataframes that does not have equal number of rows or columns. It results in NaN values. I want to fill this NaN values with the previous value in the column. import pandas as pd import numpy as np dflist = [[1, "a", "b"], [2, "a", "b"], [3, "a", "b"]] df = pd.DataFrame(dflist) dflist1 = [[1, ...
[ "In this case all you need is the ffill() method\nresult = pd.merge(df1, df, how='outer').ffill() # Will give your wanted series\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074160354_dataframe_pandas_python.txt
Q: Pytorch silent data corruption I am on a workstation with 4 A6000 GPUs. Moving a Torch tensor from one GPU to another GPU corrupts the data, silently!!! See the simple example below. x >tensor([1], device='cuda:0') x.to(1) >tensor([1], device='cuda:1') x.to(2) >tensor([0], device='cuda:2') x.to(3) >tensor([0], ...
Pytorch silent data corruption
I am on a workstation with 4 A6000 GPUs. Moving a Torch tensor from one GPU to another GPU corrupts the data, silently!!! See the simple example below. x >tensor([1], device='cuda:0') x.to(1) >tensor([1], device='cuda:1') x.to(2) >tensor([0], device='cuda:2') x.to(3) >tensor([0], device='cuda:3') Any ideas what is ...
[ "The solution was to disable IOMMU. On our server, in the BIOS settings\n /Advanced/AMD CBS/NBIO Common Options/IOMMU -> IOMMU - Disabled\nSee the PyTorch issues thread for more information.\n" ]
[ 1 ]
[]
[]
[ "gpu", "python", "pytorch" ]
stackoverflow_0073656975_gpu_python_pytorch.txt
Q: How do you get and use a Refresh Token for the Dropbox API (Python 3.x) As the title says, I am trying to generate a refresh token, and then I would like to use the refresh token to get short lived Access tokens. There is a problem though, in that I'm not smart enough to understand the docs on the dropbox site, an...
How do you get and use a Refresh Token for the Dropbox API (Python 3.x)
As the title says, I am trying to generate a refresh token, and then I would like to use the refresh token to get short lived Access tokens. There is a problem though, in that I'm not smart enough to understand the docs on the dropbox site, and all the other information I've found hasn't worked for me (A, B, C) or is i...
[ "Here is how I did it. I'll try to keep it simple and precise\nReplace <APP_KEY> with your dropbox app key in the below Authorization URL\nhttps://www.dropbox.com/oauth2/authorize?client_id=<APP_KEY>&token_access_type=offline&response_type=code\nComplete the code flow on the Authorization URL. You will receive an A...
[ 18, 6, 2 ]
[]
[]
[ "access_token", "dropbox", "dropbox_api", "python", "python_3.x" ]
stackoverflow_0070641660_access_token_dropbox_dropbox_api_python_python_3.x.txt
Q: How to draw line chart using pandas or matplotlib? I have a table like below: date category num xxx a 10 xxx b 23 xxx c 11 .......... I want to draw a line chart that: 1. x axis is the time series, 2. y is the num, and 3. each category gets their own line, so in the above case t...
How to draw line chart using pandas or matplotlib?
I have a table like below: date category num xxx a 10 xxx b 23 xxx c 11 .......... I want to draw a line chart that: 1. x axis is the time series, 2. y is the num, and 3. each category gets their own line, so in the above case there should be 3 lines.
[ "Use seaborn lineplot.\nsns.lineplot(x='date',y='num, data=df, hue='category',palette='bright) \n\nUsing hue should give you 3 separate graph.\nYou can also use matplotlib.\nHere is the documentation for that:\nhttps://seaborn.pydata.org/generated/seaborn.lineplot.html\n" ]
[ -1 ]
[]
[]
[ "matplotlib", "pandas", "plot", "python" ]
stackoverflow_0074160439_matplotlib_pandas_plot_python.txt
Q: Get and plot unique value counts in pandas dataframe I have a dataframe df with columns df.time which outlines the month and time, and df.names so that it looks like this time names 0 2020-01 Martha 1 2020-01 Jeff 2 2020-01 Geronimo 3 2020-02 Mike 4 2020-02 Michelle ... I want t...
Get and plot unique value counts in pandas dataframe
I have a dataframe df with columns df.time which outlines the month and time, and df.names so that it looks like this time names 0 2020-01 Martha 1 2020-01 Jeff 2 2020-01 Geronimo 3 2020-02 Mike 4 2020-02 Michelle ... I want to get the total number of names per unique value and plot ...
[ "I have managed to find the solution I needed\nplot_df=df.groupby(['time']).count().sort_values(['names'],ascending=False).rename(columns={'time':'sum of names'})\nplot_df=plot_df.sort_values('time').reset_index()\nx=plot_df['time'].astype(str)\ny=plot_df['names']\nplt.bar(x, height=y, width=0.5)\n\nThank you to ev...
[ 1, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074159797_dataframe_pandas_python.txt
Q: How to get all books from an author using flask SQLAlchemy? So I've setup two models so far: class BookModel(db.Model): __tablename__ = "books" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80), unique=False, nullable=False) author_first_name = db.Column(db.Integer, db.F...
How to get all books from an author using flask SQLAlchemy?
So I've setup two models so far: class BookModel(db.Model): __tablename__ = "books" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80), unique=False, nullable=False) author_first_name = db.Column(db.Integer, db.ForeignKey('authors.id')) author_last_name = db.Column(db.Inte...
[ "To establish a book-author relationship, all that is required is a reference from the author_id column in the books table to the id column in the authors table. This means that the value of the referenced column can be stored in the column defined as ForeignKey. Based on these identical values, an affiliation is d...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074157368_python_sqlalchemy.txt
Q: I have a problem in my rock-paper-scissors game in Python ( in the return part) well, I was writing my rock paper scissor code in python and everything was good until when I was trying so much to make it more sophisticated. Till line 28 everything is good and like a usual rock paper scissor game but after that, I ...
I have a problem in my rock-paper-scissors game in Python ( in the return part)
well, I was writing my rock paper scissor code in python and everything was good until when I was trying so much to make it more sophisticated. Till line 28 everything is good and like a usual rock paper scissor game but after that, I wanted to say that we have only 2 right answers for the question "do you want to cont...
[ "I fixed the indentation of your code and ended the loop in the correct way.\nI think the problem was that the break command was used on the second loop without ending the first loop which was stuck on \"True\". I fixed it by rewriting the second loop so that the continuation input is looped infinitely until it rec...
[ 0 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0074160371_pygame_python_python_3.x.txt
Q: Python data json dictionary I wanted to read tar.json file, so I write: import json with open('tar.json', "r", encoding='utf-8') as read_file: data = json.load(read_file) and print it as dictionary, for which the key will be "linia" (written as int) and the value will be value tuple. For example, for "...
Python data json dictionary
I wanted to read tar.json file, so I write: import json with open('tar.json', "r", encoding='utf-8') as read_file: data = json.load(read_file) and print it as dictionary, for which the key will be "linia" (written as int) and the value will be value tuple. For example, for "linia 52" I want to get data in f...
[ "This should give you what you need.\nimport json\nwith open('tar.json', \"r\", encoding='utf-8') as read_file:\n data = json.load(read_file) \n out = dict()\n for item in data['linia']:\n keys = list(item.keys())\n x = []\n for i in item[keys[1]]:\n ...
[ 0 ]
[]
[]
[ "dictionary", "namedtuple", "python", "tuples" ]
stackoverflow_0074160405_dictionary_namedtuple_python_tuples.txt
Q: Python efficient obfuscation of string I need to obfuscate lines of Unicode text to slow down those who may want to extract them. Ideally this would be done with a built in Python module or a small add-on library; the string length will be the same or less than the original; and the "unobfuscation" be as fast as p...
Python efficient obfuscation of string
I need to obfuscate lines of Unicode text to slow down those who may want to extract them. Ideally this would be done with a built in Python module or a small add-on library; the string length will be the same or less than the original; and the "unobfuscation" be as fast as possible. I have tried various character swap...
[ "How about the old ROT13 trick?\nPython 3:\n>>> import codecs\n>>> x = 'some string'\n>>> y = codecs.encode(x, 'rot13')\n>>> y\n'fbzr fgevat'\n>>> codecs.decode(y, 'rot13')\nu'some string'\n\nPython 2:\n>>> x = 'some string'\n>>> y = x.encode('rot13')\n>>> y\n'fbzr fgevat'\n>>> y.decode('rot13')\nu'some string'\n\n...
[ 16, 12, 1, 0 ]
[]
[]
[ "python", "string", "unicode" ]
stackoverflow_0007488995_python_string_unicode.txt
Q: How is a global variable sustained when it's first deleted and then recreated inside a function? I am unable to understand why the code is not showing any error when I try: x = 2 def foo(): global x del x x = 3 foo() print(x) Output: 3 I was expecting that del x would delete the reference to 2 and t...
How is a global variable sustained when it's first deleted and then recreated inside a function?
I am unable to understand why the code is not showing any error when I try: x = 2 def foo(): global x del x x = 3 foo() print(x) Output: 3 I was expecting that del x would delete the reference to 2 and thus, there will not be any global variable, keeping the reference to 3 locally (accessible only within...
[ "import dis\nprint(dis.dis(foo))\n\nyou will see the bytecode which will explain\n 4 0 DELETE_GLOBAL 0 (x)\n\n 5 2 LOAD_CONST 1 (3)\n 4 STORE_GLOBAL 0 (x)\n 6 LOAD_CONST 0 (None)\n 8 RETURN_VALUE\n\n", ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074160593_python.txt
Q: How to replace a txt file content? I have a banned_word list banned=["things", "show","nature","strange image"], ,and I need to read a forum message txt file and replace all the banned words in the forum file by same length asterisks. This is the forum file Forum ONE Are things real? What is nature? Show me your...
How to replace a txt file content?
I have a banned_word list banned=["things", "show","nature","strange image"], ,and I need to read a forum message txt file and replace all the banned words in the forum file by same length asterisks. This is the forum file Forum ONE Are things real? What is nature? Show me your image. You have shown me a strange imag...
[ "Have you been told that you're not to use re?\nimport re\nbanned_to_check = banned[:]\nwhile banned_to_check:\n word = banned_to_check.pop()\n regex = r'(?i)\\b' + word + r'\\b'\n message = re.sub(regex, '*' * len(word), message)\n\nIt's a bit messier without regex, but you can search the lowercase versio...
[ 1 ]
[]
[]
[ "file", "list", "python", "python_3.x", "writefile" ]
stackoverflow_0074160536_file_list_python_python_3.x_writefile.txt
Q: Project Euler Problem 5 in Python - How can I optimize my solution? I've currently been working on Project Euler problem #5 in Python. The problem is "2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divis...
Project Euler Problem 5 in Python - How can I optimize my solution?
I've currently been working on Project Euler problem #5 in Python. The problem is "2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?" I solved the problem by writing...
[ "How can I optimize my solution?\nYou are looking for the solution iterating over all possible candidate values checking each time the entire condition for every candidate. You can optimize it by using\nalready known result for 1 to 10 (2520) and breaking the for i loop if it is obvious that the condition is not sa...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074160265_python.txt
Q: is ther any more efficient way to make python file by python? what i want is make directory like this: enter image description here and i write like this: app_path = os.getcwd() + "/" + app_name Path(app_path).mkdir(parents=True, exist_ok=True) with open("__init__.py", 'w') as f: f.write(f"# {app_name} cre...
is ther any more efficient way to make python file by python?
what i want is make directory like this: enter image description here and i write like this: app_path = os.getcwd() + "/" + app_name Path(app_path).mkdir(parents=True, exist_ok=True) with open("__init__.py", 'w') as f: f.write(f"# {app_name} created by user.") with open("config.py", 'w') as f: f.write(f"# w...
[ "pathlib.Path objects have touch and write_text methods that would be useful.\nfrom pathlib import Path\n\napp_path = Path.cwd() / app_name\napp_path.mkdir(parents=True, exist_ok=True)\n(app_path / \"__init__.py\").write_text(f\"# {app_name} created by user.\")\n(app_path / \"config.py\").write_text(\"# write your ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074160644_python.txt
Q: Checking if Points In Polygon (State) and Mapping the State I am trying to map Point data to geographic locations (i.e. US states). I want to create a 'States' column by checking if the points fall within certain states using geojson data that has the polygon data in shapely geometry format, and the US States that...
Checking if Points In Polygon (State) and Mapping the State
I am trying to map Point data to geographic locations (i.e. US states). I want to create a 'States' column by checking if the points fall within certain states using geojson data that has the polygon data in shapely geometry format, and the US States that the polygon data is. I can't seem to get the logic right to get ...
[ "To correct/test your logic, compare yours with this.\nimport geopandas as gpd\n\ncity_pnts = gpd.read_file(gpd.datasets.get_path(\"naturalearth_cities\"))\ncountry_pgns = gpd.read_file(gpd.datasets.get_path(\"naturalearth_lowres\"))\n\ndef inside_country( city_point_geom ):\n for indx, row in country_pgns.iterr...
[ 1 ]
[]
[]
[ "geometry", "geopandas", "pandas", "python", "shapely" ]
stackoverflow_0074159236_geometry_geopandas_pandas_python_shapely.txt
Q: Why is psutil.process_iter() running so slowly? When I run the below code, it takes over two minutes to cycle through all the processes. Is this normal? I have been using psutil.process_iter() for a while, and I don't remember it taking this long before. import psutil import datetime as dt for proc in ps...
Why is psutil.process_iter() running so slowly?
When I run the below code, it takes over two minutes to cycle through all the processes. Is this normal? I have been using psutil.process_iter() for a while, and I don't remember it taking this long before. import psutil import datetime as dt for proc in psutil.process_iter(): try: pinfo = proc.as...
[ "There may be thousands of exe files run on server desktop where other employees also working… then it will take time. But there is a solution for that. Please keep you exe name starting with AAA+desired_name.exe, then the iteration find the exe at the beginning\n" ]
[ 0 ]
[]
[]
[ "psutil", "python" ]
stackoverflow_0045026542_psutil_python.txt
Q: Acessing directory in bucket S3 and getting the itens I am having some issues understanding the documentation, I have something like this in my bucket: —- videos —-carvideos Tesla.video Chevrolet.video Car.png Bike.png —-Files And I want to access the video directory and get ...
Acessing directory in bucket S3 and getting the itens
I am having some issues understanding the documentation, I have something like this in my bucket: —- videos —-carvideos Tesla.video Chevrolet.video Car.png Bike.png —-Files And I want to access the video directory and get the car.png file, And to enter the carvideos directory and...
[ "You can access the car.png file like this:\nimport boto3\n\ns3_resource = boto3.resource('s3')\n\ns3.Object('mybucket', 'videos/Car.png').download_file('/tmp/Car.png')\n\nNote that the filename (Key) of the object includes the full path to the object.\nTo obtain a listing of all objects in the carvideos directory,...
[ 1 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "bucket", "python" ]
stackoverflow_0074160594_amazon_s3_amazon_web_services_boto3_bucket_python.txt
Q: How to change the format of date from YYYY-MM-DD to YYYY-MM I have a list of date in the format yyyy-mm-dd but I want to group them into a dictionary with the format yyyy-mm. Does anybody know how? date_list = [ '2021-05-01', '2021-03-25', '2021-04-14', '2021-04-18', '2021-05-21', '2021-05-17'] What I want year...
How to change the format of date from YYYY-MM-DD to YYYY-MM
I have a list of date in the format yyyy-mm-dd but I want to group them into a dictionary with the format yyyy-mm. Does anybody know how? date_list = [ '2021-05-01', '2021-03-25', '2021-04-14', '2021-04-18', '2021-05-21', '2021-05-17'] What I want year_month = [ '2021-05', '2021-03', '2021-04', '2021-04', '2021-05',...
[ "Quick and easy solution is just to use string slicing\nyear_month = [date[:7] for date in date_list]\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074160673_python.txt
Q: How does this python normalization code work? cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] In learning about normalization for image recognition, I have seen many people use this code. I know this sentence is used to normalize the confusion matrix so that it contains only numbers between 0 and 1. So ...
How does this python normalization code work?
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] In learning about normalization for image recognition, I have seen many people use this code. I know this sentence is used to normalize the confusion matrix so that it contains only numbers between 0 and 1. So that the percentage of correctly classified samples...
[ "It finds a sum along an axis (axis 1) and then does broadcasted division along that axis by the corresponding value of the sum.\nSo suppose you had:\n>>> arr = np.arange(4*5).reshape(4, 5)\n>>> arr\narray([[ 0, 1, 2, 3, 4],\n [ 5, 6, 7, 8, 9],\n [10, 11, 12, 13, 14],\n [15, 16, 17, 18, 19...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074160689_numpy_python.txt
Q: Editing array - python I'm trying to make Hangman game with arrays. But the arrays can't be edited. At first I was using the manual one without making a while loop like: z = 0 r = " " while z < len(word): r = r +grid[z]+" " z = z + 1 and I can easily print it like: print(" "+...
Editing array - python
I'm trying to make Hangman game with arrays. But the arrays can't be edited. At first I was using the manual one without making a while loop like: z = 0 r = " " while z < len(word): r = r +grid[z]+" " z = z + 1 and I can easily print it like: print(" "+grid[0]+" "+grid[1]+" "+grid...
[ "A bit difficult to read the full code. Try to implement this example that i did, it does the job, i hope it can help you.\n#Word example pencil, but works for any word \nword = \"pencil\"\n\nempty_spaces = []\nleng_word = len(word)\n\n#Create the spaces according to len \nfor i in range(0,leng_word):\n empty_sp...
[ 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074160687_arrays_python.txt
Q: Rotate text on go.Heatmap I'm having a problem trying to figure out how to rotate the text on my heatmap. That dark-gray.white line running horic=zontally in the center of my heatmap is text that is overlaid on top of each other. I would like to rotate it 90 degrees so that it displays vertical, rather than horizo...
Rotate text on go.Heatmap
I'm having a problem trying to figure out how to rotate the text on my heatmap. That dark-gray.white line running horic=zontally in the center of my heatmap is text that is overlaid on top of each other. I would like to rotate it 90 degrees so that it displays vertical, rather than horizontal. I have tried using textan...
[ "I do not have an exact memory. I don't think Express and Graph Objects support string rotation in string annotations. So use string rotation in the annotation function. I extracted some heatmap code from your entire code and added the string annotation code.\ntruck_date_df = truck_df['Date']\ndates = list(truck_df...
[ 1 ]
[]
[]
[ "heatmap", "plotly", "python", "python_3.x" ]
stackoverflow_0074158285_heatmap_plotly_python_python_3.x.txt
Q: Simultaneously iterating through sequences of coordinate values, drawing lines between pairs of them in Turtle graphics In Python 3.10, I'm using Turtle graphics to write a program that currently only draws a random amount of polygonal shapes (2-5) with a random amount of points/sides (3-8) that appear on the scre...
Simultaneously iterating through sequences of coordinate values, drawing lines between pairs of them in Turtle graphics
In Python 3.10, I'm using Turtle graphics to write a program that currently only draws a random amount of polygonal shapes (2-5) with a random amount of points/sides (3-8) that appear on the screen in random places. To complete the program, I want it to be able to draw connecting lines from the points of the first/prec...
[ "I am not positive that this is what you mean, but you can try this.\nthis iterates through the shapes 2 at a time and collects one point from each shape and connects them.\nfrom itertools import pairwise\n\ndef connect_joints(grouped_joints):\n for shape1, shape2 in pairwise(grouped_joints):\n for point1...
[ 0 ]
[]
[]
[ "list", "procedural_generation", "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074160756_list_procedural_generation_python_python_turtle_turtle_graphics.txt
Q: Altair plot two stack bar charts side by side I am trying to plot two different attributes side by side in a stack bar chart. This is what I have: Import libraries import pandas as pd from datetime import datetime from dateutil.relativedelta import relativedelta import random import altair as alt Toy data: df...
Altair plot two stack bar charts side by side
I am trying to plot two different attributes side by side in a stack bar chart. This is what I have: Import libraries import pandas as pd from datetime import datetime from dateutil.relativedelta import relativedelta import random import altair as alt Toy data: df = pd.DataFrame(data={ "date": [datetime.now(...
[ "Grouped bar chart works a little differently in Altair. You need to use a row and column combination. To get what you are looking for, you should use your Y-axis variable as a row variable as well. Something like this\nselection1 = alt.selection_multi(fields=[\"prediction\"], bind=\"legend\")\nplot1 = (\n alt.C...
[ 1, 0 ]
[]
[]
[ "altair", "python", "visualization" ]
stackoverflow_0074148587_altair_python_visualization.txt
Q: Can the train_test_split be replaced from sklearn.model_selection? X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size=0.2, random_state=42) Can this call be replaced with from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_spl...
Can the train_test_split be replaced from sklearn.model_selection?
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size=0.2, random_state=42) Can this call be replaced with from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42)
[ "If your question is if both codes does the same job, then yes. Use the second one where you import train_test_split, makes the code more simple to read and understand.\n" ]
[ 1 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0074160685_python_scikit_learn.txt
Q: Creating a new column based on a condition in Pandas DataFrame I would like to create a column that repeats the content in Col1 if it starts with "M " until it hits another row that starts with "M " and takes the value of that one and repeats until it hits a new one, and so on because I have many over 50 "M #"s in...
Creating a new column based on a condition in Pandas DataFrame
I would like to create a column that repeats the content in Col1 if it starts with "M " until it hits another row that starts with "M " and takes the value of that one and repeats until it hits a new one, and so on because I have many over 50 "M #"s in my real data. Col1 Col2 M 1: number drug 1 deaths row bac...
[ "You can use DataFrame.where to select the value from Col1 where Col1 starts with M and then use ffill to fill in the blanks:\ndf['Col3'] = df['Col1'].where(df['Col1'].str.startswith('M ')).ffill()\n\nOutput\n Col1 Col2 Col3\n0 M 1: number drug 1 deaths ...
[ 1 ]
[]
[]
[ "for_loop", "function", "loops", "pandas", "python" ]
stackoverflow_0074160791_for_loop_function_loops_pandas_python.txt
Q: How to find duplicates in list of lists? I have a list of key binds in a class like so: self.key_bind_list = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["A", "B"], ["A", "B", "C"]] *in this case a duplicate should be detected by the sublists ["A", "B"], but not by ["A", "B"] and ["A", "B", "C"] And I'd like t...
How to find duplicates in list of lists?
I have a list of key binds in a class like so: self.key_bind_list = [["A", "B"], ["C"], ["SHIFT", "NUM6", "NUM7"], ["A", "B"], ["A", "B", "C"]] *in this case a duplicate should be detected by the sublists ["A", "B"], but not by ["A", "B"] and ["A", "B", "C"] And I'd like to check if there are any duplicates on the mai...
[ "Assuming you just want to check if there are duplicates, and print out which sublists contain duplicates, you could use an approach with a list that contains set elements, such as so:\nkey_bind_list = [[\"A\", \"B\"], [\"C\"], [\"SHIFT\", \"NUM6\", \"NUM7\"], [\"B\", \"A\"], [\"A\", \"B\", \"C\"]]\n\nseen = []\n\n...
[ 1, 1, 1 ]
[]
[]
[ "list", "python", "sorting", "syntax" ]
stackoverflow_0074160602_list_python_sorting_syntax.txt
Q: Errors in solving problems with Gekko python I am trying to solve the problem as follows with Gekko in python. (1) However, I got some errors APM model error: string > 15000 characters Consider breaking up the line into multiple equations The may also be due to only using newline character CR instead of CR LF (f...
Errors in solving problems with Gekko python
I am trying to solve the problem as follows with Gekko in python. (1) However, I got some errors APM model error: string > 15000 characters Consider breaking up the line into multiple equations The may also be due to only using newline character CR instead of CR LF (for Windows) or LF (for MacOS/Linux) To fix this pr...
[ "I tried m.sum() as below and it worked but I got negative DOF (Degrees of Freedom).\nobj = m.sum([m.sum([((1/(1+r))**(t+1))*((P_CO*m.min3(demand[t,s], theta[s])) \\\n + beta_CO2*P_CO2*m.min3(demand[t,s], theta[s]) \\\n *(E_ref-E_dir-E_indir_others-E_indir_elec_cons*GWP_EU[t,s]) \\\n - (C1_CAPEX + C2_C...
[ 0 ]
[]
[]
[ "gekko", "optimization", "python" ]
stackoverflow_0074148624_gekko_optimization_python.txt
Q: Trying to split up data by [70:30] ratio The exact question that I'm trying to solve is: "Then split the feature X and the target y into training and test sets with the ratio of 70:30. Print the size of the training and test set." and this is the code that I have so far: X = df['bmi'] y = df['charges'] trainX, tes...
Trying to split up data by [70:30] ratio
The exact question that I'm trying to solve is: "Then split the feature X and the target y into training and test sets with the ratio of 70:30. Print the size of the training and test set." and this is the code that I have so far: X = df['bmi'] y = df['charges'] trainX, testX, trainY, testY=train_test_split(X,y, test_s...
[ "Your training data should be the 70% then in your code you should use test_size = 0.3\ntrainX, testX, trainY, testY=train_test_split(X,y, test_size = 0.3)\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python", "sklearn_pandas" ]
stackoverflow_0074009801_pandas_python_sklearn_pandas.txt
Q: Identifying the source of a value in a reactive object on a website This website contains a numeric "value adjustment" value (highlighted on the left in the image below) that appears when visitors populate fields elsewhere on the page with certain values. My goal is to find the code that calculates the value adju...
Identifying the source of a value in a reactive object on a website
This website contains a numeric "value adjustment" value (highlighted on the left in the image below) that appears when visitors populate fields elsewhere on the page with certain values. My goal is to find the code that calculates the value adjustment. I know that populating the fields that makes this value appear qu...
[ "When you inspect the elements tab in dev tools you are inspecting what is rendered on the webpage. It always looks hard coded. It's showing you the end result.\nIf you inspect an element that changes things on the page when it's interacted with, it probably has js 'event listeners' attached to it. You can inspect ...
[ 1 ]
[]
[]
[ "html", "javascript", "python" ]
stackoverflow_0074160805_html_javascript_python.txt
Q: how to index specific cell in the table I want to get value from specific cell like row =3 , column= 2 I tried .get but it doesn't work import tkinter as tk app = tk.Tk() class Excel(tk.Frame): def __init__(self, master, rows, columns, width): super().__init__(master) for i in range(columns...
how to index specific cell in the table
I want to get value from specific cell like row =3 , column= 2 I tried .get but it doesn't work import tkinter as tk app = tk.Tk() class Excel(tk.Frame): def __init__(self, master, rows, columns, width): super().__init__(master) for i in range(columns): self.make_entry(0, i + 1, wid...
[ "You can use get however it helps to keep a collection of the Entry's so that you can find it. Presently you just abandon e each time and rely on tkinter to keep a track of it.\nAlternatively, you can make the form event driven so that your code only runs on change. To do this, register a validate function.\n ...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074160513_python_tkinter.txt
Q: How to use "\dt" in cursor.execute() to get the tables in PostgreSQL? (Django) In Django, I'm trying to use \dt in cursor.execute() to get the tables in PostgreSQL as shown below: # "views.py" from django.http import HttpResponse from django.db import connection def test(request): cursor = connection.cursor(...
How to use "\dt" in cursor.execute() to get the tables in PostgreSQL? (Django)
In Django, I'm trying to use \dt in cursor.execute() to get the tables in PostgreSQL as shown below: # "views.py" from django.http import HttpResponse from django.db import connection def test(request): cursor = connection.cursor() cursor.execute('''\dt''') # Here row = cursor.fetchone() print(row) ...
[ "You can list the tables using plain SQL, without the need of psql.\ncursor.execute('''\nselect *\nfrom pg_catalog.pg_tables\nwhere schemaname = '<your_schema_name>';\n''')\n\n", "You cannot to use \\dt command as postgresql query. \\dt is client side psql command. PostgreSQL can process just SQL commands (like S...
[ 2, 1 ]
[]
[]
[ "dbtable", "django", "postgresql", "python", "python_3.x" ]
stackoverflow_0074160529_dbtable_django_postgresql_python_python_3.x.txt
Q: List available font families in `tkinter` In many tkinter examples available out there, you may see things like: canvas.create_text(x, y, font=('Helvetica', 12), text='foo') However, this may not work when run in your computer (the result would completely ignore the font parameter). Aparently, the font parameter ...
List available font families in `tkinter`
In many tkinter examples available out there, you may see things like: canvas.create_text(x, y, font=('Helvetica', 12), text='foo') However, this may not work when run in your computer (the result would completely ignore the font parameter). Aparently, the font parameter is ignored if there is any incorrect value in i...
[ "This question has been answered fully, but it's useful for me to be able to see what every font looks like so that I'm sure of which one I would like to use. In the interest of saving someone else from reinventing the wheel, I'll post my code here. As above, each font family is shown in a scrolling window. The ...
[ 50, 38, 26, 10, 3, 3, 3, 1, 1, 1, 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0039614027_python_tkinter.txt
Q: Connect to Microsoft Graph via Access Token I am trying to connect to the Microsoft Graph API without user intervention, and am following this guide on how to do so. I am able to get past step 4, where I receive my access token. However, I continue to receive an error saying that my access token is empty. The firs...
Connect to Microsoft Graph via Access Token
I am trying to connect to the Microsoft Graph API without user intervention, and am following this guide on how to do so. I am able to get past step 4, where I receive my access token. However, I continue to receive an error saying that my access token is empty. The first part of my code successfully gets the access to...
[ "I tried to reproduce the same in my environment and got the below results:\nI created one Azure AD application and granted permissions as below:\n\nNow, I ran the same code as you and got the token successfully as below:\nimport urllib3\nuri = \"https://login.microsoftonline.com/tenantID/oauth2/v2.0/token\"\npaylo...
[ 1, 0 ]
[]
[]
[ "azure", "azure_ad_graph_api", "microsoft_graph_api", "microsoft_graph_sdks", "python" ]
stackoverflow_0074154880_azure_azure_ad_graph_api_microsoft_graph_api_microsoft_graph_sdks_python.txt
Q: How to fix aws lambda function logs error? I'm trying to extract aws trust advisor data through lambda function(trigger by event scheduler) and upload to s3. However, some part of the function throws error. below is my code ##libraries import boto3 import os import csv from csv import DictWriter import time import...
How to fix aws lambda function logs error?
I'm trying to extract aws trust advisor data through lambda function(trigger by event scheduler) and upload to s3. However, some part of the function throws error. below is my code ##libraries import boto3 import os import csv from csv import DictWriter import time import traceback ## bucket_name is set as env variabl...
[ "response = client.describe_trusted_advisor_check_summaries(\n checkIds=[\n 'string',\n ]\n)\n\ndescribe_trusted_advisor_check_summaries() returns summarized results for one or more Trusted advisors. Here you are checking for the check_summary['status'] is not equal to not_avaialble i.e. alert status ...
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_lambda", "python", "python_3.x" ]
stackoverflow_0074160835_amazon_s3_amazon_web_services_aws_lambda_python_python_3.x.txt
Q: Converting Ascii Text Art To UTF-8 I am trying to convert a text-based ascii art into utf-8, whilst doing so I've ran into multiple technical problems using these methods find This method is a simpler approach, but it doesn't work because of many reasons, character arrangement, and clustered characters. therefor...
Converting Ascii Text Art To UTF-8
I am trying to convert a text-based ascii art into utf-8, whilst doing so I've ran into multiple technical problems using these methods find This method is a simpler approach, but it doesn't work because of many reasons, character arrangement, and clustered characters. therefore it won't work I actually think it woul...
[ "You can't.\nUnless your ASCII art will use always the same letters, drawn in the same way - there are no rules that can be made to recognize the text deterministically.\nAnd even if the letters are always drawn in the same way, that is, an \"O\" will always be comprised of the exact same characters in your example...
[ 4 ]
[]
[]
[ "ascii_art", "python" ]
stackoverflow_0074160911_ascii_art_python.txt
Q: String concatenation of two pandas columns I have a following DataFrame: from pandas import * df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]}) It looks like this: bar foo 0 1 a 1 2 b 2 3 c Now I want to have something like: bar 0 1 is a 1 2 is b 2 3 is c How can I achieve ...
String concatenation of two pandas columns
I have a following DataFrame: from pandas import * df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]}) It looks like this: bar foo 0 1 a 1 2 b 2 3 c Now I want to have something like: bar 0 1 is a 1 2 is b 2 3 is c How can I achieve this? I tried the following: df['foo'] = '%s is ...
[ "df['bar'] = df.bar.map(str) + \" is \" + df.foo\n\n", "This question has already been answered, but I believe it would be good to throw some useful methods not previously discussed into the mix, and compare all methods proposed thus far in terms of performance.\nHere are some useful solutions to this problem, in...
[ 165, 147, 45, 14, 12, 8, 4, 1, 0, 0, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python", "string" ]
stackoverflow_0011858472_dataframe_numpy_pandas_python_string.txt
Q: Remove/add discord roles to a person I want to create a promote command which when issued it promotes the member to the next rank, but I can't get it to remove/add his roles import discord import os from discord.utils import get bot = discord.Bot(intents=discord.Intents.all()) admin = 990420666568278086 #roles ...
Remove/add discord roles to a person
I want to create a promote command which when issued it promotes the member to the next rank, but I can't get it to remove/add his roles import discord import os from discord.utils import get bot = discord.Bot(intents=discord.Intents.all()) admin = 990420666568278086 #roles prospect = 869470046953537546 member = 869...
[ "Please refering to discord.Member.add_roles and discord.Member.remove_roles. Both of them are taking discord.Role as parameter. Hence your code should look like user.remove_roles(guild.get_role(prospect)) where guild.get_role(prospect) is returning discord.Role\nThis is what your code should looks like to make it ...
[ 0 ]
[]
[]
[ "bots", "command", "discord.py", "pycord", "python" ]
stackoverflow_0074160734_bots_command_discord.py_pycord_python.txt
Q: Get a true / false column if last 2 days were red in pandas I have a list of symbols in a single df: index date symbol stock_id open high low close volume vwap 0 0 2021-10-11 BVN 13 7.69 7.98 7.5600 7.61 879710 7.782174 1 1 2021-10-12 BV...
Get a true / false column if last 2 days were red in pandas
I have a list of symbols in a single df: index date symbol stock_id open high low close volume vwap 0 0 2021-10-11 BVN 13 7.69 7.98 7.5600 7.61 879710 7.782174 1 1 2021-10-12 BVN 13 7.67 8.08 7.5803 8.02 794436 7.967061 2 ...
[ "You can try a groupby+rolling:\nN = 2\ndf['is_downtrending'] = (df.groupby('symbol')['close']\n .apply(lambda s: s.diff().lt(0).rolling(N).sum().eq(N))\n )\n\nOutput:\n index date symbol stock_id open high low close volume vwap is_d...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074160813_numpy_pandas_python.txt
Q: How to concurrently list_objects in S3 bucket with aioboto3 I want to find all the unique paths in an S3 bucket, I want all the paths just before the file level. The depth of the directories can vary so not all files are found in the same depth for example I might have these files : data/subdir1/subdir2/file.csv d...
How to concurrently list_objects in S3 bucket with aioboto3
I want to find all the unique paths in an S3 bucket, I want all the paths just before the file level. The depth of the directories can vary so not all files are found in the same depth for example I might have these files : data/subdir1/subdir2/file.csv data/subdir1/subdir3/subdir4/subdir5/file2.csv data/subdir6/subdir...
[ "I didn't find a way to parallelize on the returned objects BUT I parallelized using many initial prefixes like this:\n subfolders = set()\n prefix_tasks = [get_subfolders(bucket, prefix) for prefix in prefixes]\n try:\n\n for prefix_future in asyncio.as_completed(prefix_tasks):\n prefix...
[ 0, 0 ]
[]
[]
[ "asynchronous", "boto3", "python", "python_asyncio" ]
stackoverflow_0069569876_asynchronous_boto3_python_python_asyncio.txt
Q: how to mention a user in slack message through the slack python API here is my code client.api_call(api_method='chat.postMessage', json={'channel': '#staff', 'text': f'{user} This is a test.'}) the output I get is U046NKX4LSD This is a test. It should rather mention the username and the username should get a n...
how to mention a user in slack message through the slack python API
here is my code client.api_call(api_method='chat.postMessage', json={'channel': '#staff', 'text': f'{user} This is a test.'}) the output I get is U046NKX4LSD This is a test. It should rather mention the username and the username should get a notification as you mention @username.
[ "https://api.slack.com/reference/surfaces/formatting#mentioning-users\nA mention is a special type of reference that will provide a link to the mentioned user's profile in the published text.\nTo mention a user in app-published text, you need to provide their user ID in the following syntax:\n\nHey <@U024BE7LH>, th...
[ 1 ]
[]
[]
[ "python", "slack_api" ]
stackoverflow_0074158250_python_slack_api.txt
Q: How to surpass the Y/N command in google collab shell command? so I have command which ask the Found 1 job(s). Submit? [y/N]: in google collab but how can I enter Y or N in collab shell command automatically A: What command are you running? yes command maybe the one you may looking for. I don't know what your co...
How to surpass the Y/N command in google collab shell command?
so I have command which ask the Found 1 job(s). Submit? [y/N]: in google collab but how can I enter Y or N in collab shell command automatically
[ "What command are you running?\nyes command maybe the one you may looking for. I don't know what your command is but here is example:\nyes | apt-get update.\nYou can also run yes --help to see more option\nA similar question can be found here How do I automatically answer y in bash script?. The bash script in the q...
[ 2 ]
[]
[]
[ "google_colaboratory", "jupyter_notebook", "python" ]
stackoverflow_0074160887_google_colaboratory_jupyter_notebook_python.txt
Q: Sort a txt file based on numbers I have a txt file of data that looks like this: @0 #1 @30 #2 @750 #2 @20 #3 @500 #3 @2500 #4 @460 #4 @800 #1 @2200 #1 @290 #2 @4700 #4 @570 #1 How do I sort the file based on the integer between the @ and #? The output should be: @0 #1 @20 #3 @30 #2 @290 #2 @460 #4 @500 #3 @570 #1...
Sort a txt file based on numbers
I have a txt file of data that looks like this: @0 #1 @30 #2 @750 #2 @20 #3 @500 #3 @2500 #4 @460 #4 @800 #1 @2200 #1 @290 #2 @4700 #4 @570 #1 How do I sort the file based on the integer between the @ and #? The output should be: @0 #1 @20 #3 @30 #2 @290 #2 @460 #4 @500 #3 @570 #1 @750 #2 @800 #1 @2200 #1 @2500 #4 @47...
[ "You just need to read in the text and split it by new lines, then use the sorted function using only the integer part of line as the key.\nwith open('my_text_file.txt') as textfile:\n lines = textfile.read().split('\\n') # ['@0 #1', '@30 #2', '@750 #2', '@20 #3', '@500 #3', '@2500 #4', '@460 #4', '@800 #1', ...
[ 1, 1 ]
[]
[]
[ "python", "txt" ]
stackoverflow_0074160972_python_txt.txt
Q: Python requests close connection I have a python request to capture the token number, after that I use this token to run another API url, afther that I want to close this current session, but I could not, like this: url = 'https://10.10.20.21/tron/api/v1/tokens' payload = {'grant_type': 'password', 'username': 'lo...
Python requests close connection
I have a python request to capture the token number, after that I use this token to run another API url, afther that I want to close this current session, but I could not, like this: url = 'https://10.10.20.21/tron/api/v1/tokens' payload = {'grant_type': 'password', 'username': 'login', 'password': 'test@2021'} headers...
[ "I've found myself in the same situation with ASUS Aura Rest API where after I don't know the lack of port numbers? Rest API server crashes.\nSeems that despite that request.Session implementation I had to also add the header:\n{'Connection':'close'} to the session\nso now there are only pending connections visible...
[ 1, 0 ]
[]
[]
[ "api", "python", "python_requests" ]
stackoverflow_0069456228_api_python_python_requests.txt
Q: Enum or related types to type hint varying combinations of string literals I have a function parameter called price_type that only allows arguments of either A (Ask), B (Bid), M (Mid), or any combination of them, for example: AB or ABM. The arrangement doesnt matter either, so AB is just as likely to be input as B...
Enum or related types to type hint varying combinations of string literals
I have a function parameter called price_type that only allows arguments of either A (Ask), B (Bid), M (Mid), or any combination of them, for example: AB or ABM. The arrangement doesnt matter either, so AB is just as likely to be input as BA, and they are both valid. def __get_base_data( symbol: str, count: int...
[ "Maybe mapping price_type to a str is not ideal in your case, a possible solution is to create an enum PaymentType and map price_type to it. Since you can assign multiple PaymentTypes you can also expect to receive a collection of PaymentType attributes.\nfrom enum import Enum\nfrom typing import Tuple\n\ndef __get...
[ 0 ]
[]
[]
[ "literals", "python", "python_typing", "typing" ]
stackoverflow_0074161026_literals_python_python_typing_typing.txt
Q: looping numpy error: all the input arrays must have same number of dimensions I want to write the following code: for i = 1:N for j = 1:N Ab(i,j) = (Ap(i)*Ap(j))^(0.5)*(1 - kij(i,j)) ; end end However an error appears: "all the input arrays must have same number of dimensions, but the array at ind...
looping numpy error: all the input arrays must have same number of dimensions
I want to write the following code: for i = 1:N for j = 1:N Ab(i,j) = (Ap(i)*Ap(j))^(0.5)*(1 - kij(i,j)) ; end end However an error appears: "all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)" ab=np.matrix((...
[ "There is a bit context missing, but if I guess correctly looking at Matlab part you can write something like this.\nab = np.zeros((2, 2)) \nfor i in range(ab.shape[0]): # you do not have to put 0 and you can use size of array to limit iterations\n for j in range(ab.shape[1]):\n ab[i, j] = (Ap[i]*Ap[j])**(0.5)*...
[ 0 ]
[]
[]
[ "loops", "numpy", "python" ]
stackoverflow_0074160874_loops_numpy_python.txt
Q: Why my code counts 1720901 words for Reuters corpus while there are in fact 1.3 million words? I want to count the number of words in Reuters corpus. The python code below gives 1720901. While I know that the correct answer is about 1.3 million words. len(nltk.corpus.reuters.words()) What is the reason for that d...
Why my code counts 1720901 words for Reuters corpus while there are in fact 1.3 million words?
I want to count the number of words in Reuters corpus. The python code below gives 1720901. While I know that the correct answer is about 1.3 million words. len(nltk.corpus.reuters.words()) What is the reason for that difference?
[ "This is because the corpus is comprised of more than one file, and the object returned from the words() method loads the words lazily, so the len function only tells you the number of tokens in the current view.\nTo demonstrate:\n>>> import nltk\n>>> help(nltk.corpus.reuters.words())\n\nread the description for th...
[ 1 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0074161031_nltk_python.txt
Q: What's the best way to calculate strength of fit of these curves? The green line is a fit to the red data points. What is the best way to calculate the strength of fit for something like this? There are lots of raw points from 0-100, as the x-axis gets larger the number of data points tends to decrease, and the re...
What's the best way to calculate strength of fit of these curves?
The green line is a fit to the red data points. What is the best way to calculate the strength of fit for something like this? There are lots of raw points from 0-100, as the x-axis gets larger the number of data points tends to decrease, and the residual tends to get worse. The number of red data points is always vari...
[ "In my grad school days, we used the Kolmogorov-Smirnov Goodness-of-Fit Test. Essentially you are comparing the Cumulative Distribution of your data to the Cumulative Distribution of your fit function evaluated with the same number of points. Enjoy the rabbit hole.\n" ]
[ 0 ]
[]
[]
[ "python", "statistics" ]
stackoverflow_0074161042_python_statistics.txt
Q: An error in implementing regex function on a list I was trying to implement a regex on a list of grammar tags in python, for finding the tense form of the list of grammar. And I wrote the following code to implement it. Data preprocessing: from nltk import word_tokenize, pos_tag import nltk text = "He will have b...
An error in implementing regex function on a list
I was trying to implement a regex on a list of grammar tags in python, for finding the tense form of the list of grammar. And I wrote the following code to implement it. Data preprocessing: from nltk import word_tokenize, pos_tag import nltk text = "He will have been doing his homework." tokenized = word_tokenize(te...
[ "Your call to the cp.parse() function expects each of the tokens in your sentence to be tagged, however, the tags list you created only contains the tags but not the tokens as well, hence your ValueError. The solution is to instead pass the output from the pos_tag() call (i.e. tagged) to your check_grammar call (se...
[ 2 ]
[]
[]
[ "nlp", "nlp_question_answering", "nltk", "python" ]
stackoverflow_0074160976_nlp_nlp_question_answering_nltk_python.txt
Q: How to keep track of console output lines in Python? I'm trying to find the number of numbers divisble by 2 in 0-100, I have used a range() function and n1=n1+1 to generate 0 to 100, then with an if statement display only numbers wholely divisble by 2. For the life of me I cannot find a way to count the number of ...
How to keep track of console output lines in Python?
I'm trying to find the number of numbers divisble by 2 in 0-100, I have used a range() function and n1=n1+1 to generate 0 to 100, then with an if statement display only numbers wholely divisble by 2. For the life of me I cannot find a way to count the number of times 0's are printed in the console, I googled count() bu...
[ "count = 0\nv = list()\nfor i in range(1, 101):\n if i % 2 == 0:\n print(i)\n count += 1\n v.append(i)\nprint(f'Number of values divisible by 2 = {count}')\nprint(f'Values that are divisible by 2: {v}')\n\n", "As much as I get, I think you want to count number of zeros? If I am right then ...
[ 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074160932_loops_python.txt
Q: PDF File dedupe issue with same content, but generated at different time periods from a docx I working on a pdf file dedupe project and analyzed many libraries in python, which read files, then generate hash value of it and then compare it with the next file for duplication - similar to logic below or using python...
PDF File dedupe issue with same content, but generated at different time periods from a docx
I working on a pdf file dedupe project and analyzed many libraries in python, which read files, then generate hash value of it and then compare it with the next file for duplication - similar to logic below or using python filecomp lib. But the issue I found these logic is like, if a pdf is generated from a source DOCX...
[ "One of the things that happens is that you save metadata to the file including the time of creation. It is invisible in the PDF, but that will make the hash different.\nHere is an explanation of how to find and strip out that data with at least one tool. I am sure that there are many others.\n" ]
[ 1 ]
[]
[]
[ "algorithm", "duplicates", "python", "python_dedupe" ]
stackoverflow_0074159812_algorithm_duplicates_python_python_dedupe.txt
Q: UserWarning: No contour levels found within the data range Can someone explain what does the Python compiler mean when it says: UserWarning: No contour levels found within the data range ? I couldn't find any good resources on the web about the mentioned UserWarning. Thanks in advance for the help! PS: I am trying...
UserWarning: No contour levels found within the data range
Can someone explain what does the Python compiler mean when it says: UserWarning: No contour levels found within the data range ? I couldn't find any good resources on the web about the mentioned UserWarning. Thanks in advance for the help! PS: I am trying to implement a paper related to image segmentation and I am usi...
[ "I think this link answers your question.\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074161172_matplotlib_python.txt
Q: AWS Lambda boto3 error when using rds execute_statement with parameter formatRecordsAs Has anyone encountered this Error when using the Lambda with boto3 rds execute_statement( )? [ERROR] ParamValidationError: Parameter validation failed: Unknown parameter in input: "formatRecordsAs", must be one of: continueAfter...
AWS Lambda boto3 error when using rds execute_statement with parameter formatRecordsAs
Has anyone encountered this Error when using the Lambda with boto3 rds execute_statement( )? [ERROR] ParamValidationError: Parameter validation failed: Unknown parameter in input: "formatRecordsAs", must be one of: continueAfterTimeout, database, includeResultMetadata, parameters, resourceArn, resultSetOptions, schema,...
[ "boto3 in a lambda function is not full nor it is the latest version. Thus its quite common to run into the issues you report with invalid arguments, etc.\nYou have to bundle full boto3 with your function, for example using a layer.\n" ]
[ 0 ]
[]
[]
[ "amazon_rds", "amazon_web_services", "aws_lambda", "boto3", "python" ]
stackoverflow_0074159762_amazon_rds_amazon_web_services_aws_lambda_boto3_python.txt
Q: Create two arrays in numpy with random int from a uniform distr Each number in "a" array should be >= with the number in the same position from "b" array. Range 0,10 a = np.random.randint(0,10,300) b=[] for i in a: b = np.random.randint(0,i,300) Got a ValueError: low >= high Then I tried i+1 but values in b e...
Create two arrays in numpy with random int from a uniform distr
Each number in "a" array should be >= with the number in the same position from "b" array. Range 0,10 a = np.random.randint(0,10,300) b=[] for i in a: b = np.random.randint(0,i,300) Got a ValueError: low >= high Then I tried i+1 but values in b exceed the ones from a
[ "If your goal is to create two random arrays ensuring a >= b, you can use:\nb, a = np.sort(np.random.randint(0, 10, (2, 300)), axis=0)\n\nassert (a>=b).all()\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074161211_numpy_pandas_python.txt
Q: plotting 3 categories on a matplotlib bar chart when one of them has no values for part of the x axis I've been working with my own IMDB data to practice pandas and plotting, and have created a bar chart that is supposed to show the rating distribution between 3 types of ratings: TV series, Movies, and TV episodes...
plotting 3 categories on a matplotlib bar chart when one of them has no values for part of the x axis
I've been working with my own IMDB data to practice pandas and plotting, and have created a bar chart that is supposed to show the rating distribution between 3 types of ratings: TV series, Movies, and TV episodes. The issue is that I have no ratings of 1 or 2 for any TV Series in my dataset. I would like to show 0% fo...
[ "Since the data is not provided, I will answer the question by generating a (fake) dataset for movie ratings.\nReproducing the error:\nimport pandas as pd \nimport matplotlib.pyplot as plt \nimport random\nimport numpy as np\n\n# The dataframe will have one column with movie ratings from 3 to 10.\nmovies = pd.DataF...
[ 0 ]
[]
[]
[ "bar_chart", "matplotlib", "pandas", "python" ]
stackoverflow_0074151568_bar_chart_matplotlib_pandas_python.txt
Q: raise InvalidSchema("No connection adapters were found for {!r}".format(url) while using requests module I'm getting this error every time my for-loop makes a call to the API. The curious thing is I'm still getting an json object result for the first query the call has an issue with as such, Traceback (most recent...
raise InvalidSchema("No connection adapters were found for {!r}".format(url) while using requests module
I'm getting this error every time my for-loop makes a call to the API. The curious thing is I'm still getting an json object result for the first query the call has an issue with as such, Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core...
[ "You likely got the error when you called response = requests.get(r). Requests was expecting a URL but got that strange '{\\'page\\': 1, \\'results\\': [{\\ ..., string. The response you got from your first request was a dictionary, not a URL.\nYou could print(r) and see if the URL you want is somewhere in that res...
[ 0 ]
[]
[]
[ "api", "django", "python", "python_requests", "url" ]
stackoverflow_0074161218_api_django_python_python_requests_url.txt
Q: How to make a fill down like process in list of lists? I have the following list a with None values for which I want to make a "fill down". a = [ ['A','B','C','D'], [None,None,2,None], [None,1,None,None], [None,None,8,None], ['W','R',5,'Q'], ['H','S','X','V'], ...
How to make a fill down like process in list of lists?
I have the following list a with None values for which I want to make a "fill down". a = [ ['A','B','C','D'], [None,None,2,None], [None,1,None,None], [None,None,8,None], ['W','R',5,'Q'], ['H','S','X','V'], [None,None,None,7] ] The expected output would be lik...
[ "You could use a list comprehension for this, but I'm not sure it adds a lot to your solution already.\nb = [a[0]]\nfor a_row in a[1:]:\n b.append([i if i else j for i,j in zip(a_row, b[-1])])\n\nI'm not sure if it's by design, but in your example a number is never carried down to the next row. If you wanted to...
[ 2, 1 ]
[]
[]
[ "fill", "list", "python" ]
stackoverflow_0074160764_fill_list_python.txt
Q: Why does calculating my enemy's movement doesnt make it move in that direction? I have a game, where there is an enemy and its ai only moves it northwest. It should move in all directions, but it doesnt and i cant figure it out. Can someone help me? The enemy code: import pygame import inventory_essentials import ...
Why does calculating my enemy's movement doesnt make it move in that direction?
I have a game, where there is an enemy and its ai only moves it northwest. It should move in all directions, but it doesnt and i cant figure it out. Can someone help me? The enemy code: import pygame import inventory_essentials import variables import level import os import projectiles import math import random class...
[ "I do not speak python but one thing stands out at me anyway:\nint(math.pi/2)\nI am not sure what you are trying to do with this line but I'm sure you're not getting the expected result. That's going to evaluate to 1.\n", "I think you are trying to generate the range [-pi/2, pi/2] with your line dd = random.rand...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074161096_python.txt
Q: Python Selenium Unable to locate element after switching iframe I am unable to locate the "btn" element inside an iframe even after switching iframes. The code works when I run it through the debugging function, but it does not work when I run it normally. I have also tried time.sleep, frame_to_be_available_and_sw...
Python Selenium Unable to locate element after switching iframe
I am unable to locate the "btn" element inside an iframe even after switching iframes. The code works when I run it through the debugging function, but it does not work when I run it normally. I have also tried time.sleep, frame_to_be_available_and_switch_to_it, explicit waits. I hope that someone will be able to help ...
[ "Also I have some error , but I'm getting that element is HtmlObject and selenium can't locate this,\ntry to print your driver.page_source after and try to find without xpath, find with css selectore or with something else...\n" ]
[ 0 ]
[]
[]
[ "pycharm", "python", "selenium" ]
stackoverflow_0073604027_pycharm_python_selenium.txt
Q: How to use filter function in python 33 I'm now start learning python and I'm have problem with filter function. If I run list=list(range(10)) def f(x): return x % 2 != 0 print(((filter(f,list)))) I will get the result is filter object at 0x00000000028B4E10 Process finished with exit code 0 And if I modify th...
How to use filter function in python 33
I'm now start learning python and I'm have problem with filter function. If I run list=list(range(10)) def f(x): return x % 2 != 0 print(((filter(f,list)))) I will get the result is filter object at 0x00000000028B4E10 Process finished with exit code 0 And if I modify the code to list=list(range(10)) def f(x): ret...
[ "You renamed list, giving it a different value. Don't do that, you shadowed the built-in type. Change your code to use a different name instead:\nsome_list = list(range(10))\n\ndef f(x): return x % 2 != 0\n\nprint(list(filter(f, some_list)))\n\nand then filter() works just fine.\n", "Your main problem is that you...
[ 3, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0015321986_list_python.txt
Q: Python - pint - Can I set default type to Decimal? Im using pint module in a project. Objects in my project handle numerical data as Decimals. When I set simple pint units to a Decimal, it works: >>> import pint >>> from decimal import Decimal as D >>> ureg = pint.UnitRegistry() >>> D(10) * ureg.kN <Quantity(10, '...
Python - pint - Can I set default type to Decimal?
Im using pint module in a project. Objects in my project handle numerical data as Decimals. When I set simple pint units to a Decimal, it works: >>> import pint >>> from decimal import Decimal as D >>> ureg = pint.UnitRegistry() >>> D(10) * ureg.kN <Quantity(10, 'kilonewton')> But, if I try to add a second unit, it br...
[ "This works:\n>>> D(10) * (ureg.kN * ureg.m)\n<Quantity(10, 'kilonewton * meter')>\n\nAnd this too:\n>>> Q = ureg.Quantity\n>>> Q(D(10), \"kN*m\")\n<Quantity(10, 'kilonewton * meter')>\n\n", "Type cast it to decimal\nimport decimal\nD(10) * ureg.kN * decimal.Decimal(ureg.m)\n\n", "As version 0.11 of pint, you c...
[ 3, 1, 0 ]
[]
[]
[ "decimal", "pint", "python" ]
stackoverflow_0045011574_decimal_pint_python.txt
Q: Exception encountered when calling layer "model" (type Functional) ValueError: Exception encountered when calling layer "model_5" (type Functional). Input 0 of layer "gru_21" is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: (None, 160, 160, 3) Call arguments rec...
Exception encountered when calling layer "model" (type Functional)
ValueError: Exception encountered when calling layer "model_5" (type Functional). Input 0 of layer "gru_21" is incompatible with the layer: expected ndim=3, found ndim=4. Full shape received: (None, 160, 160, 3) Call arguments received by layer "model_5" (type Functional): • inputs=tf.Tensor(sha...
[ "You assigned data dimensions to input suitable for learning mostly we removed duplicated or no sorted data and expand to match the model input. You will know that tf.squeeze() then tf.expand() will return the same shape as they know the original but tf.reshape() is not or using tf.Keras.layer.dense(). You may try ...
[ 0 ]
[]
[]
[ "conv_neural_network", "keras", "python", "recurrent_neural_network", "tensorflow" ]
stackoverflow_0074161074_conv_neural_network_keras_python_recurrent_neural_network_tensorflow.txt
Q: upgrade pip version deployed Azure function App I have an Azure function App deployed. I upgraded my local pip version from 20.2.3 to 22.3. Now when I deployed new version, I'm getting this warning from vscode. How can I upgrade pip version. Need some help. WARNING: You are using pip version 20.2.3; however, versi...
upgrade pip version deployed Azure function App
I have an Azure function App deployed. I upgraded my local pip version from 20.2.3 to 22.3. Now when I deployed new version, I'm getting this warning from vscode. How can I upgrade pip version. Need some help. WARNING: You are using pip version 20.2.3; however, version 22.3 is available. You should consider upgrading v...
[ "I have tried to reproduce the above issue, please check the below steps\n\nBefore updating the python version in azure portal\n\n\n\nIn azure portal Run the below command in azure CLI\n\naz functionapp config set --name \"FunctionAppName\" --resource-group \"YourResourceGroup\" --linux-fx-version \"PYTHON|3.9\"\n\...
[ 0 ]
[]
[]
[ "azure_functions", "python" ]
stackoverflow_0074129926_azure_functions_python.txt
Q: How to create new column from another dataframe based on conditions I am trying to join two datasets, but they are not the same or have the same criteria. Currently I have the dataset below, which contains the number of fires based on month and year, but the months are part of the header and the years are a column...
How to create new column from another dataframe based on conditions
I am trying to join two datasets, but they are not the same or have the same criteria. Currently I have the dataset below, which contains the number of fires based on month and year, but the months are part of the header and the years are a column. I would like to add this data, using as target data_medicao column fro...
[ "First, I assume that the first dataframe is in variable a and the second is in variable b.\nTo make looking up simpler, we set the index of a to year:\na = a.set_index('year')\n\nThen, we take the years from the data_medicao in the dataframe b:\nyears = b['medicao'].dt.year\n\nTo get the month name from the datafr...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074161204_dataframe_pandas_python.txt
Q: How to extract each word consecutive to its own previous number in a string and sorting the result in Python Input : x3b4U5i2 Output : bbbbiiUUUUUxxx How can i solve this problem in Python. I have to print the word next to it's number n times and sort it A: One option, extract the character/digit(s) pairs with ...
How to extract each word consecutive to its own previous number in a string and sorting the result in Python
Input : x3b4U5i2 Output : bbbbiiUUUUUxxx How can i solve this problem in Python. I have to print the word next to it's number n times and sort it
[ "One option, extract the character/digit(s) pairs with a regex, sort them by letter (ignoring case), multiply the letter by the number of repeats, join:\ns = 'x3b4U5i2'\n\nimport re\n\nout = ''.join([c*int(i) for c,i in \n sorted(re.findall('(\\D)(\\d+)', s),\n key=lambda x: x[0]....
[ 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074161222_python.txt
Q: Why do I need to reconnect to the database to see changes in table data? I periodically query a MySQL table and check data in the same row. I use MySQLdb to do the job, querying the same table and row every 15 seconds. Actually, the row data changes every 3 seconds, but the cursor always return the same value. Th...
Why do I need to reconnect to the database to see changes in table data?
I periodically query a MySQL table and check data in the same row. I use MySQLdb to do the job, querying the same table and row every 15 seconds. Actually, the row data changes every 3 seconds, but the cursor always return the same value. The strange thing is: after I close the MySQL connection and reconnect, using a ...
[ "This is almost certainly the result of transaction isolation. I'm going to assume, since you haven't stated otherwise, that you're using the default storage engine (InnoDB) and isolation level (REPEATABLE READ):\n\nREPEATABLE READ\nThe default isolation level for InnoDB. It prevents any rows that are queried from ...
[ 3, 1 ]
[]
[]
[ "database_cursor", "mysql", "mysql_python", "python", "sql" ]
stackoverflow_0029680684_database_cursor_mysql_mysql_python_python_sql.txt
Q: How to this python-spotify-recommendation question? I'm trying to make my recommendation list using this dataset. I want to group songs by artists_upd、id and artists in order. The original one is this and I want to make it like this but I failed and it showed keyerror 'artists' and I can't understand why? import p...
How to this python-spotify-recommendation question?
I'm trying to make my recommendation list using this dataset. I want to group songs by artists_upd、id and artists in order. The original one is this and I want to make it like this but I failed and it showed keyerror 'artists' and I can't understand why? import pandas as pd import numpy as np import json import re imp...
[ "The issue is that you are attempting to merge on the artists column of data_w_genre (with the parameter right_on = 'artists'), but data_w_genre does not have a column with that name.\n artists_exploded_enriched = artists_exploded.merge(data_w_genre, how = 'left', left_on = 'artists_upd',right_on = 'artists')\n\nIn...
[ 0 ]
[]
[]
[ "python", "recommendation_engine", "spotify" ]
stackoverflow_0074161413_python_recommendation_engine_spotify.txt
Q: Why my list is not being converted to a float I have the list of [0.5, 1.5, 2.5, 3.5]. def calc_mean(arglist): return sum(arglist)/len(arglist) print(calc_mean([0.5, 1.5, 2.5, 3.5])) I have another list, strlist = ['0.5','1.5','2.5','3.5'] and I need to convert the elements in it to floats and then calculate...
Why my list is not being converted to a float
I have the list of [0.5, 1.5, 2.5, 3.5]. def calc_mean(arglist): return sum(arglist)/len(arglist) print(calc_mean([0.5, 1.5, 2.5, 3.5])) I have another list, strlist = ['0.5','1.5','2.5','3.5'] and I need to convert the elements in it to floats and then calculate the average but I'm getting the error: unsupported...
[ "\nprint(calc_mean(strlist))\n\n\nAs noted in comments, you have not converted strlist before passing it to calc_mean.\nprint(calc_mean(str2float(strlist)))\n\n", "According to @craigb and @Chris, you have to call the conversion function first and then the averaging function.\nprint(calc_mean(str2float(strlist)))...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074161555_python.txt
Q: How can I use slugs in Django url like mysite.com/user I want to create a directory like website.com/user after the user get logged in! And I'm not sure which url pattern in my app/urls.py should call this myfun to capture slug: user in url def myfun(request, user): user = TwitterUser().objects.get(user=user) ...
How can I use slugs in Django url like mysite.com/user
I want to create a directory like website.com/user after the user get logged in! And I'm not sure which url pattern in my app/urls.py should call this myfun to capture slug: user in url def myfun(request, user): user = TwitterUser().objects.get(user=user) return render(request, 'authorization/home.html', {'user...
[ "Add it to your urls.py with the relevant placeholder and get the placeholder as parameter in the view:\nurlpatterns = [\n path('', views.index, name='index'),\n path('<str:user>', views.myfun, name='myfun')\n]\n\nYou can see more info here in Django documentation https://docs.djangoproject.com/en/4.1/topics/...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074161019_django_python.txt
Q: Find the first/last n words of a string with a maximum of 20 characters using regex I'm trying to find any number of words at the beginning or end of a string with a maximum of 20 characters. This is what I have right now: s1 = "Hello, World! This is a reallly long string" match = re.search(r"^(\b.{0,20}\b)", s...
Find the first/last n words of a string with a maximum of 20 characters using regex
I'm trying to find any number of words at the beginning or end of a string with a maximum of 20 characters. This is what I have right now: s1 = "Hello, World! This is a reallly long string" match = re.search(r"^(\b.{0,20}\b)", s1) print(f"'{match.group(0)}'") # 'Hello, World! This ' My problem is the extra space th...
[ "You can use r\"^(.{0,19}\\S\\b|)\" (regex demo), \\S ensuring to have a non space character on the bound. You need to decrease the number of previous characters to 19 and use | with empty string to match 0 characters if needed:\nimport re\ns1 = \"Hello, World! This is a reallly long string\"\nmatch = re.search(...
[ 2, 2 ]
[]
[]
[ "python", "python_re", "regex" ]
stackoverflow_0074161611_python_python_re_regex.txt
Q: How to attach a file.txt or anything in hourmailer python So I'm having a struggle how can I send an attachment in email by using the hourmailer because that is what my project for. Basically what I just really want is to pass my txt file or any file maybe but text file will be fine with some messages on it. Here ...
How to attach a file.txt or anything in hourmailer python
So I'm having a struggle how can I send an attachment in email by using the hourmailer because that is what my project for. Basically what I just really want is to pass my txt file or any file maybe but text file will be fine with some messages on it. Here is the code import requests url = "https://hourmailer.p.rapida...
[ "You are reading the attachment with the \"rb\" (read, binary) flag and trying to convert the resulting bytes object to a JSON string with .read() method.\nWhat you should instead do is omit the b flag or decode (e.g.: with .decode('utf-8') method) it before passing it on.\nBut in your case, I'd wager HourMailer AP...
[ 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0074161262_email_python.txt
Q: Download ipynb from colab notebook Url Given a list of colab notebooks how can I download the ipynb of each one of them using wget or curl? https://colab.research.google.com/notebooks/gpu.ipynb https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_arbitrary_image_stylization.ipynb...
Download ipynb from colab notebook Url
Given a list of colab notebooks how can I download the ipynb of each one of them using wget or curl? https://colab.research.google.com/notebooks/gpu.ipynb https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_arbitrary_image_stylization.ipynb https://colab.research.google.com/drive/1sV...
[ "There're 2 options I recommend, assuming all the target url are in a text file. Save the code to .sh file (e.g dlnb.sh) and all the urls in a text file (e.g list.txt) like\nhttps://colab.research.google.com/notebooks/gpu.ipynb\nhttps://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_...
[ 1 ]
[]
[]
[ "google_colaboratory", "jupyter_notebook", "python" ]
stackoverflow_0074110420_google_colaboratory_jupyter_notebook_python.txt
Q: how to install PySide6 in Raspbian running in a virtual machine I am running Raspbian OS in a virtual machine on windows. I want to install PySide6 in that Raspbian OS. I am getting following error, Could not find a version that satisfies the requirement pyside6 (from versions: ) No matching distribution found fo...
how to install PySide6 in Raspbian running in a virtual machine
I am running Raspbian OS in a virtual machine on windows. I want to install PySide6 in that Raspbian OS. I am getting following error, Could not find a version that satisfies the requirement pyside6 (from versions: ) No matching distribution found for pyside6 Any help would be appreciated. Thanks
[ "From this post: https://forum.qt.io/topic/135892/installing-pyside-on-a-raspberry-pi/5\nCurrently, PySide6 doesn't have released package on Raspbian OS. You may try Manjaro on Raspberry Pi if the hardware platform is specified.\n" ]
[ 0 ]
[]
[]
[ "pip", "python", "raspbian", "version", "virtual_machine" ]
stackoverflow_0070272508_pip_python_raspbian_version_virtual_machine.txt
Q: what is the easest way to solve indentation problem in spyder 5.3.3 I am using spyder 5.3.3 for python coding. I copied the code from some sources,it works fine. But when I make edits in it, I get indentation error. A: In case of copy codes from different sources, I found that the easiest way to solve it by: Go ...
what is the easest way to solve indentation problem in spyder 5.3.3
I am using spyder 5.3.3 for python coding. I copied the code from some sources,it works fine. But when I make edits in it, I get indentation error.
[ "In case of copy codes from different sources, I found that the easiest way to solve it by:\nGo to Source --> Fix Indentation. this worked for me.\n" ]
[ 0 ]
[]
[]
[ "python", "spyder" ]
stackoverflow_0074161593_python_spyder.txt
Q: How to add a background and simple square as a character for a single screen platformer in pygame? I’ve tried adding a background for the game, but as it pops up a second later it goes away It is white and everything else with the background is fine, but this is the only issue. Also, I tried to make a square to us...
How to add a background and simple square as a character for a single screen platformer in pygame?
I’ve tried adding a background for the game, but as it pops up a second later it goes away It is white and everything else with the background is fine, but this is the only issue. Also, I tried to make a square to use as a character but it just won’t pop up. import pygame, sys from pygame.locals import QUIT backgroun...
[ "You need to implement an application loop where you move the objects and redraw the scene in each frame. The typical PyGame application loop has to:\n\nlimit the frames per second to limit CPU usage with pygame.time.Clock.tick\nhandle the events by calling either pygame.event.pump() or pygame.event.get().\nupdate ...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074161044_pygame_python.txt
Q: Web Scraping Nested Loop in Python is Too Slow I've written up a Python script using Selenium to help me order an RTX 4090 (figured it was the only way to beat the scalpers) but at the moment it is far too slow. This is primarily because of a nested while loop that I'm using to run through a couple of popup pages ...
Web Scraping Nested Loop in Python is Too Slow
I've written up a Python script using Selenium to help me order an RTX 4090 (figured it was the only way to beat the scalpers) but at the moment it is far too slow. This is primarily because of a nested while loop that I'm using to run through a couple of popup pages on BestBuy without getting completely hung up. I don...
[ "Why it is to slow?\nAs you using\n\nimplicitly_wait(10)\n\nFirst It try to locate element if it not found it will wait for 10 second every time in whole program\nYou are also using try and except so, what is going here is first it goes to try block if the element is not found it will wait for 10 second as you impl...
[ 0 ]
[]
[]
[ "performance", "python", "selenium" ]
stackoverflow_0074160862_performance_python_selenium.txt
Q: creating initial population for genetic algorithm I need to create the initial population to solve this equation z = x⁵ - 10x³ + 30x - y² + 21y using genetic algorithm. The population must be binary and need to follow this rules: X and Y range: [-2.5, 2.5] The first bit represents the signal (0 or 1) The second an...
creating initial population for genetic algorithm
I need to create the initial population to solve this equation z = x⁵ - 10x³ + 30x - y² + 21y using genetic algorithm. The population must be binary and need to follow this rules: X and Y range: [-2.5, 2.5] The first bit represents the signal (0 or 1) The second and third bit represents the integer part, values from 0 ...
[ "How about\ndef pop(pop_size)\n rlt = []\n for i in range(pop_size):\n rlt.append([None,None])\n for j in range(2):\n signal = bin(np.random.randint(0, 2))[2:]\n integer = bin(np.random.randint(0, 3))[2:]\n floats = bin(np.random.randint(0, 5001))[2:].zfill(13)\n...
[ 1 ]
[]
[]
[ "binary", "genetic_algorithm", "python" ]
stackoverflow_0074160956_binary_genetic_algorithm_python.txt
Q: save() saves all fields except ManyToMany field I have a model "Contest" with one m2m field called "teams" which is related to a model "Team". I overrided the method save. In my save() function (the one that's overriding), I need a queryset (in my save overrinding function) with all the objects related to my team ...
save() saves all fields except ManyToMany field
I have a model "Contest" with one m2m field called "teams" which is related to a model "Team". I overrided the method save. In my save() function (the one that's overriding), I need a queryset (in my save overrinding function) with all the objects related to my team m2m field. The code is self.teams.all() but it won't ...
[ "The reason is that implementation of ManyToManyField does not use the database table of the model. It uses third table for connection between two models.\nEach model has its own database table. In your example\nmodel Contest -> table app_contest\nmodel Team -> table app_team\n\nHowever, app_contest does not have...
[ 0 ]
[]
[]
[ "django", "django_models", "many_to_many", "python" ]
stackoverflow_0074160000_django_django_models_many_to_many_python.txt
Q: Scrapy: extract text from span without id I'm doing a spider for this website: link. I'm trying to get the price, but I couldn't this get me back none, I can get the title but I couldn't with the prices because the span haven't class, I don't know why get me back none because in the browser the xpath works. imgCss...
Scrapy: extract text from span without id
I'm doing a spider for this website: link. I'm trying to get the price, but I couldn't this get me back none, I can get the title but I couldn't with the prices because the span haven't class, I don't know why get me back none because in the browser the xpath works. imgCss = response.xpath("(//img[contains(@class, 'vte...
[ "The information you seek is available in the page source. You can parse it as json and extract the information you need. You can start with the code below and extract the relevant information from the dictionary.\nimport scrapy\nimport json\n\nclass TestSpider(scrapy.Spider):\n name = 'test'\n allowed_domain...
[ 2 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0074158510_python_scrapy.txt