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 loops finding random number import random n=random.randint(1, 5) i=int(input("Guess a number from one to ten")) if i!=1 and i!=2 and i!=3 and i!=4 and i!=5: print("ERROR") elif i<n: print("SMALL") elif n<i: print ("BIG") else: print("You're right!") Tried to get a num from 1-5 and 3 tries ...
Python loops finding random number
import random n=random.randint(1, 5) i=int(input("Guess a number from one to ten")) if i!=1 and i!=2 and i!=3 and i!=4 and i!=5: print("ERROR") elif i<n: print("SMALL") elif n<i: print ("BIG") else: print("You're right!") Tried to get a num from 1-5 and 3 tries but only got one
[ "The easiest way is a for-loop using the built-in range function.\nMake sure to put the input function inside the loop to get repeated user input. The if-elif-else structure needs to be indented into the for loop as well.\nThe use of _ is just a placeholder for an unneeded value.\nimport random\n\nn = random.randin...
[ 1, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074216173_loops_python.txt
Q: Using custom objective function for trained/saved XGBoost model I have a custom objective function I am passing to an XGBoost model during training, which works great. The function is: def weighted_binary_cross_entropy(label, pred): # assign the value of imbalanced alpha imbalance_alpha = 90 # compute ...
Using custom objective function for trained/saved XGBoost model
I have a custom objective function I am passing to an XGBoost model during training, which works great. The function is: def weighted_binary_cross_entropy(label, pred): # assign the value of imbalanced alpha imbalance_alpha = 90 # compute the prediction with sigmoid sigmoid_pred = 1.0 / (1.0 + np.exp(-p...
[ "Simpler than I thought:\nmodel = XGBClassifier()\nprint(model.objective)\n\nproduces\nbinary:logistic\n\nand\nmodel = XGBClassifier(objective=weighted_binary_cross_entropy)\nprint(model.objective)\n\nproduces\n<function weighted_binary_cross_entropy at 0x7fa89c953f70>\n\n" ]
[ 0 ]
[]
[]
[ "python", "xgboost" ]
stackoverflow_0074216038_python_xgboost.txt
Q: How to read multiple pdf from a folder one by one I'm trying to extract data from a pdf file and convert it into pandas dataframe I used 'fitz' from Pymupdf module to extract the data. and then with pandas i'm converting it into dataframe from pathlib import Path # returns all file paths that has .pdf as extension...
How to read multiple pdf from a folder one by one
I'm trying to extract data from a pdf file and convert it into pandas dataframe I used 'fitz' from Pymupdf module to extract the data. and then with pandas i'm converting it into dataframe from pathlib import Path # returns all file paths that has .pdf as extension in the specified directory pdf_search = Path("C:/Users...
[ "You can use pathlib builtin function to list out all the pdfs in your directory\nfrom pathlib import Path\n# returns all file paths that has .pdf as extension in the specified directory\npdf_search = Path(\"<path>/<to>/<pdfs>/\").glob(\"*.pdf\")\n# convert the glob generator out put to list\n# skip this if you are...
[ 2, 1, 0 ]
[]
[]
[ "dataframe", "pdf", "python" ]
stackoverflow_0070848337_dataframe_pdf_python.txt
Q: While loop based on USER INPUT How can I make a while loop print something blank amount of times based on the user input. For example: age = int(input('Enter your age: ')) while age… And I just don’t know what to do from there. To be clear, how could I output something 8 times if the user inputs 8 (6 times if th...
While loop based on USER INPUT
How can I make a while loop print something blank amount of times based on the user input. For example: age = int(input('Enter your age: ')) while age… And I just don’t know what to do from there. To be clear, how could I output something 8 times if the user inputs 8 (6 times if the user inputs six…)? Edit: I want to...
[ "With a while-loop you have to use a condition for how long it will execute.\nTo keep the value assigned to age use a counter variable like so:\nage = int(input(\"Enter your age: \"))\n\nn = 0\nwhile n < age:\n # Do something n-times as restricted by age\n n += 1\n\n", "One way you could do it is:\nx = inpu...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x", "while_loop" ]
stackoverflow_0074214759_python_python_3.x_while_loop.txt
Q: I want merge words with the same value in dataframe into one, stick the words next to each other at once I want merge words with the same value in dataframe into one, stick the words next to each other at once ex) en ko acrania a acrania b acrania c acrania d => en ko acrania a,b,c,d I want to make it in ...
I want merge words with the same value in dataframe into one, stick the words next to each other at once
I want merge words with the same value in dataframe into one, stick the words next to each other at once ex) en ko acrania a acrania b acrania c acrania d => en ko acrania a,b,c,d I want to make it in the form above.please help me I was only able to remove duplicates in Excel, and it is to...
[ "Given your dataframe looks like this\ndf = {'en': ['acrania', 'acrania', 'acrania', 'acrania'], 'ko': ['a', 'b', 'c', 'd']}\n\nSimply use groupby\ndf = df.groupby('en')['ko'].apply(','.join).reset_index()\n\nOutput:\n en ko\n0 acrania a,b,c,d\n\nHope this helps.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "duplicates", "excel", "pandas", "python" ]
stackoverflow_0074216191_dataframe_duplicates_excel_pandas_python.txt
Q: Accessing private dictionary in python How can I access a private dictionary of one class from another class using __iter__ and __next__ class Store(AbstractStore, Displayable): def __init__(self, store_name : str) -> None: self.__store_name = store_name self.__products : dict[Product, int] = ...
Accessing private dictionary in python
How can I access a private dictionary of one class from another class using __iter__ and __next__ class Store(AbstractStore, Displayable): def __init__(self, store_name : str) -> None: self.__store_name = store_name self.__products : dict[Product, int] = {} # Product is an object , int tells about...
[ "If you want to iterate over a class you just need to define the __getitem__ method.\nSome information was missing from your question or wasn't too clear so I've filled the gaps with what I tought was correct.\nSo each iteration on the Store class will return the key value pair and the __init__ method stores the pr...
[ 0 ]
[]
[]
[ "class", "dictionary", "private", "python" ]
stackoverflow_0074168814_class_dictionary_private_python.txt
Q: how to update/edit existing list using their index values I am having elements inside a list from where I want to remove all elements except the certain index values, is there a way? list = ['Radar', 'completed 2022-10-23T08:18:26', 'PASS: 11FAIL: 0SKIP: 0', '0:14:55', 'completed', '2022-10-23T08:18:26'] indexes =...
how to update/edit existing list using their index values
I am having elements inside a list from where I want to remove all elements except the certain index values, is there a way? list = ['Radar', 'completed 2022-10-23T08:18:26', 'PASS: 11FAIL: 0SKIP: 0', '0:14:55', 'completed', '2022-10-23T08:18:26'] indexes = (0, 1, -2, -1) # these are the index values i want to keep in ...
[ "It's easier to just replace the list with a new list that only has the needed values:\nxs = ['Radar', 'completed 2022-10-23T08:18:26', 'PASS: 11FAIL: 0SKIP: 0', '0:14:55', 'completed', '2022-10-23T08:18:26']\nindices = (0, 1, -2, -1)\nxs = [xs[i] for i in indices]\nprint(xs)\n\nBy the way, don't call variables nam...
[ 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074216309_list_python.txt
Q: Changing Colors of the Plot of A DataFrame of a Single Line in Pandas Problem: Suppose I have a PANDAS data frame titled, recorded_values_of_accelerometer which appears as a one column by 22272 row table in the figure below: Now, suppose I need to plot this table using recorded_values_of_accelerometer.plot(). How...
Changing Colors of the Plot of A DataFrame of a Single Line in Pandas
Problem: Suppose I have a PANDAS data frame titled, recorded_values_of_accelerometer which appears as a one column by 22272 row table in the figure below: Now, suppose I need to plot this table using recorded_values_of_accelerometer.plot(). However, I need certain rows in the plot to be of a particular color. Say, row...
[ "You can't do that with the DataFrame.plot().\nJust use Matplotlib API like the following example.\nimport matplotlib.pyplot as p\n...\ns = frame[frame.columns[0]]\np.plot(s[:78], 'b')\np.plot(s[78:], 'r')\np.legend(s.name)\np.show()\n\n" ]
[ 0 ]
[]
[]
[ "data_science", "pandas", "python" ]
stackoverflow_0074212709_data_science_pandas_python.txt
Q: how would you add a new dictionary element to a list of dictionary (json) and assign an increment value to each new key? I have a json file with a similar output of a couple of hundred line. What should be the approach to add a new element "RANK" to each dictionary and assign an increment value to it? How can it b...
how would you add a new dictionary element to a list of dictionary (json) and assign an increment value to each new key?
I have a json file with a similar output of a couple of hundred line. What should be the approach to add a new element "RANK" to each dictionary and assign an increment value to it? How can it be done using python? XYZ=json.load(open("countries.geo.json",'r')) OUTPUT **{'type': 'Feature', 'id': 'BEL', 'properties'...
[ "Try:\nlst = [\n {\n \"type\": \"Feature\",\n \"id\": \"BEL\",\n \"properties\": {\"name\": \"Belgium\"},\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": [\n [\n [3.314971, 51.345781],\n [4.047071...
[ 1, 1 ]
[]
[]
[ "append", "json", "pandas", "plotly", "python" ]
stackoverflow_0074130827_append_json_pandas_plotly_python.txt
Q: find phrase in list and get index I have tried researching this but can't find anything like what I am looking for. I am trying to find a specific phrase in a list. Here is a test list: data = {"text":["Map:","Internet", "Subscriptions","","Map:", "Adult","Literacy","and", "Numeracy","|","8"]} I want to get the i...
find phrase in list and get index
I have tried researching this but can't find anything like what I am looking for. I am trying to find a specific phrase in a list. Here is a test list: data = {"text":["Map:","Internet", "Subscriptions","","Map:", "Adult","Literacy","and", "Numeracy","|","8"]} I want to get the index position of the first word in a ph...
[ "List comprehension will work. Just iterate through the data searching for values where the index == Map: and the following index is the second term of the teststring.\nteststring = \"Map: Adult Literacy and Numeracy\"\nteststring_split = teststring.split(\" \")\n\ndata = {\"text\":[\"Map:\",\"Internet\",\n\"Subsc...
[ 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074216138_list_python.txt
Q: Add columns to a table or records without duplicates in Duckdb I have the following code: import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler, PatternMatchingEventHandler import duckdb path = "landing/persistent/" global con con = duckdb.connect(database='formatt...
Add columns to a table or records without duplicates in Duckdb
I have the following code: import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler, PatternMatchingEventHandler import duckdb path = "landing/persistent/" global con con = duckdb.connect(database='formatted/my-db.duckdb', read_only=False) class EventHandler(PatternMatchi...
[ "You can use CREATE OR REPLACE syntax to create the table if the table does not exist and replace if the table exists.\nquery = \"CREATE OR REPLACE TABLE {} AS SELECT * FROM read_csv_auto(?);\"\n\nThis option will basically drop and recreate the table every time you have a csv file with the same name as the table.\...
[ 2 ]
[]
[]
[ "duckdb", "python", "sql" ]
stackoverflow_0074186714_duckdb_python_sql.txt
Q: How can I mitigate encoding error that happens irregularly while scraping data? I was scraping SEC EDGAR data by running 'MDA Extractor.py' in this link. https://github.com/rflugum/10K-MDA-Section As this program was made in Python2, I changed some expressions (e.g., print -> print(), xrange -> range), and added u...
How can I mitigate encoding error that happens irregularly while scraping data?
I was scraping SEC EDGAR data by running 'MDA Extractor.py' in this link. https://github.com/rflugum/10K-MDA-Section As this program was made in Python2, I changed some expressions (e.g., print -> print(), xrange -> range), and added useragent to avoid blocking. Meanwhile, when it reads the link number '39126' (https:/...
[ "from bs4 import BeautifulSoup\nheaders = {'user-agent': '`A B@C.D`'}\nwith open(download, 'r') as txtfile:\n reader = csv.reader(txtfile, delimiter=',')\n for line in reader:\n print(line)\n FileNUM = line[0].strip()\n Filer = os.path.join(filepath,\"MDA_processed/\"+str(line[0].strip())...
[ 0 ]
[]
[]
[ "edgar", "encoding", "pandas", "python", "web_scraping" ]
stackoverflow_0074099544_edgar_encoding_pandas_python_web_scraping.txt
Q: Implementing a new "git ..." subcommand as a Python script I feel like this question could be answered with one or two hyperlinks; I'm just not coming up with the right search terms to find those links myself... I'm trying to make some minor changes to the git p4 subcommand, which is implemented as a 3797-line Pyt...
Implementing a new "git ..." subcommand as a Python script
I feel like this question could be answered with one or two hyperlinks; I'm just not coming up with the right search terms to find those links myself... I'm trying to make some minor changes to the git p4 subcommand, which is implemented as a 3797-line Python script named /usr/libexec/git-core/git-p4. Before wading int...
[ "Git's documentation of course covers this. The short version:\nIf git foo is not a built-in command, Git will search PATH for git-foo and run that. But it does nothing else at all: it doesn't even verify that you're in a repository directory. (After all, lots of commands don't even need one, like git hash-objec...
[ 11, 4, 0 ]
[]
[]
[ "git", "python" ]
stackoverflow_0049075168_git_python.txt
Q: For loop in django template returning same id for specific column I am trying to write an admin panel where videos can be edited, deleted and reviewed using Django. While the loop I have set up runs smoothly, it only accepts the first value as the id value in the video deletion function. I'm pretty sure I closed t...
For loop in django template returning same id for specific column
I am trying to write an admin panel where videos can be edited, deleted and reviewed using Django. While the loop I have set up runs smoothly, it only accepts the first value as the id value in the video deletion function. I'm pretty sure I closed the for loop in the right place, I guess there's nothing wrong with it. ...
[ "it is because you loop with the same modal id.\nJS will only find your first modal and ignore the rest if the element have same id.\nI can think of two solution:\nSolution 1. add video.id to the Element modal id id=\"myModal{{video.id}}\" and change the modal triger href=\"#myModal{{video.id}}\"\nSolution 2. dont ...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074216041_django_django_models_python.txt
Q: Dash Choropleth Map Color based on frequency or count Let's say I have a dataset of scientific publications, their Country, and a score metric that evaluates the quality of the publications. Sort of like the following: Paper Country Score Pub 1 USA 5 Pub 2 China 7 Pub 3 Japan 9 Pub 4 China 4 I want to genera...
Dash Choropleth Map Color based on frequency or count
Let's say I have a dataset of scientific publications, their Country, and a score metric that evaluates the quality of the publications. Sort of like the following: Paper Country Score Pub 1 USA 5 Pub 2 China 7 Pub 3 Japan 9 Pub 4 China 4 I want to generate a map that is colored based on total score p...
[ "How about something like\nfig = px.choropleth(df[['Country', 'Score']].groupby('Country').sum().reset_index(), \n locations = 'Country',\n color='Score')\n\nSee example from Plotly here where you only need pass the column names.\n" ]
[ 1 ]
[]
[]
[ "pandas", "plotly", "plotly_dash", "python" ]
stackoverflow_0074216431_pandas_plotly_plotly_dash_python.txt
Q: How to subset rows of df based on unique values? I need to drop rows which do not match the criteria of equal values in nunique. Every value in "lot" column is associated with two values in "shipment" column. For every value of "lot", number of unique "cargotype" values may/may not be different for each shipment. ...
How to subset rows of df based on unique values?
I need to drop rows which do not match the criteria of equal values in nunique. Every value in "lot" column is associated with two values in "shipment" column. For every value of "lot", number of unique "cargotype" values may/may not be different for each shipment. I want to drop the rows for "lot" which have unequal "...
[ "Don't ask me how, but this creates your desired outcome\ndef squeeze_nan(x):\n original_columns = x.index.tolist()\n squeezed = x.dropna()\n squeezed.index = [original_columns[n] for n in range(squeezed.count())]\n return squeezed.reindex(original_columns, fill_value=np.nan)\n\ndf1 = df.groupby([\"lot\...
[ 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074216184_dataframe_group_by_pandas_python.txt
Q: How can I scrape an information from Wester Union webpage? I am trying to scrape the currency convertion information of https://www.westernunion.com/ (attached photo). I found the corresponding tag but it returns an empty list. Can anyone help me? I appreciate that. Here is my current code (using BeautifulSoup): #...
How can I scrape an information from Wester Union webpage?
I am trying to scrape the currency convertion information of https://www.westernunion.com/ (attached photo). I found the corresponding tag but it returns an empty list. Can anyone help me? I appreciate that. Here is my current code (using BeautifulSoup): # Web Crawling: import requests # Web Scrapping: from bs4 import ...
[ "WU loads that bit with javascript, all you're scraping with requests is a loading page full of placeholders\n\nThe POST request they seem to be using to populate that field looks very difficult to replicate (see this code which I copied from curlconverter)\n\nYou might consider using selenium. I have a function fo...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074212250_beautifulsoup_python_web_scraping.txt
Q: How to make all the values in a pandas DataFrame as False? I have a DataFrame (close) like this: How can I make all the values (including NaN and any float number) inside this DataFrame as False? pandas.DataFrame.replace doesn't seem to have this ability to achieve my goal. Does anyone know how to do this? A: Y...
How to make all the values in a pandas DataFrame as False?
I have a DataFrame (close) like this: How can I make all the values (including NaN and any float number) inside this DataFrame as False? pandas.DataFrame.replace doesn't seem to have this ability to achieve my goal. Does anyone know how to do this?
[ "You could do with assign\ndf[:] = False\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074216500_dataframe_pandas_python.txt
Q: Run flask application on linux server with nohup I am trying to run my flask application on my linux server using nohup , but each time i run my flask application with nohup , my server will require me to kill with cntrl + c in order for me to do other things assuming i have 2 file in my server path(home/app/) fl...
Run flask application on linux server with nohup
I am trying to run my flask application on my linux server using nohup , but each time i run my flask application with nohup , my server will require me to kill with cntrl + c in order for me to do other things assuming i have 2 file in my server path(home/app/) flask_app.py [ which is my flask application ] flk.sh i...
[ "You usually want to use nohup command arg1 arg2 &. You're just missing the ampersand.\nBriefly, nohup prevents the OS from killing your job, & sends the job in the background, so it isn't tied to your current shell.\n" ]
[ 1 ]
[]
[]
[ "linux", "python", "shell" ]
stackoverflow_0074216484_linux_python_shell.txt
Q: creat a new dictionary to summarize the original dictionary using loops The dataset or say the given dictionary is: # A list of video reviews # - Each review has the name of the video, the numer of views # and a list of user reviews. # - Each user review has the user's name and the review they gave # to the vi...
creat a new dictionary to summarize the original dictionary using loops
The dataset or say the given dictionary is: # A list of video reviews # - Each review has the name of the video, the numer of views # and a list of user reviews. # - Each user review has the user's name and the review they gave # to the video. video_reviews = [ { "name": "Cats doing nothing", "...
[ "Here's a modified version of your code that I think gives you what you want:\ndef create_user_summary(video_reviews):\n summary = {}\n for video in video_reviews:\n for person in video[\"reviews\"]:\n summary.setdefault(person[\"name\"], []).append(video[\"name\"])\n return summary\n\nRe...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "for_loop", "function", "list", "python" ]
stackoverflow_0074216315_dictionary_for_loop_function_list_python.txt
Q: python name '_mysql' is not defined I build a virtual environment with python 3.7.10, by installing mysql and mysqlclient It is mysql 8.0.28, mysqlclient 2.1.0. When running python manage.py migrate It comes out like this: (test) ➜ backend git:(main) python manage.py migrate Traceback (most recent call last): F...
python name '_mysql' is not defined
I build a virtual environment with python 3.7.10, by installing mysql and mysqlclient It is mysql 8.0.28, mysqlclient 2.1.0. When running python manage.py migrate It comes out like this: (test) ➜ backend git:(main) python manage.py migrate Traceback (most recent call last): File "/usr/local/Caskroom/miniforge/base/e...
[ "A couple of days ago I had the same issue. Make sure mysqlclient is installed and then install pip install PyMySQL , Now use the following lines of code in settings.py:\n#in settings.py\nimport pymysql \npymysql.install_as_MySQLdb()\n\nthis works for me.\n", "This is because the version of the mysql C library(_...
[ 1, 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0071392754_django_mysql_python.txt
Q: Pythonic/List comprehension way of creating a list from a dict where the values are guaranteed to be int of range 0..len(dict) -1 Suppose I have a python dict like: my_dict = {"foo": 1, "bar": 0, "more": 2} I want to create an ordered list of the keys such that the order follows the value increasingly. The value...
Pythonic/List comprehension way of creating a list from a dict where the values are guaranteed to be int of range 0..len(dict) -1
Suppose I have a python dict like: my_dict = {"foo": 1, "bar": 0, "more": 2} I want to create an ordered list of the keys such that the order follows the value increasingly. The values are guaranteed to be unique and in the range of 0.. len(my_dict) -1. The following code achieves the objective: my_list = [] ...
[ "Just plain old sort with a key:\n>>> my_dict = {\"foo\": 1, \"bar\": 0, \"more\": 2}\n>>> sorted(my_dict, key=my_dict.get)\n['bar', 'foo', 'more']\n\nInclude reverse keyword if you want values decreasing (your question says increasing but your example code does decreasing, so I'm not sure)\n>>> sorted(my_dict, key...
[ 2 ]
[]
[]
[ "list_comprehension", "python", "python_3.x" ]
stackoverflow_0074216623_list_comprehension_python_python_3.x.txt
Q: Combining an item from list with a list of tuples that have the same index positions I have a list containing 640 items (all floats). I have a list of tuples (two items in the tuple) containing 640 items. Both lists are ordered and line up with each other. I want to take the two items from the tuple and put them a...
Combining an item from list with a list of tuples that have the same index positions
I have a list containing 640 items (all floats). I have a list of tuples (two items in the tuple) containing 640 items. Both lists are ordered and line up with each other. I want to take the two items from the tuple and put them at the top of their corresponding list of floats. For example, both of these are at index[0...
[ "The zip() function can help you.\nThe zip built-in function mixes the elements of several iterables, combining those with the same index into a single group.\na = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\nb = (1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10)\n\nprint(tuple(zip(a, b)))\n# ((1, 1.1), (2, 2.2), (3, 3.3), (...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074216587_python.txt
Q: VideoCapture USB camera OpenCV2 greyscale image contrast python I am trying to get frames from a usb FLIR camera. The video stream works fine when I view it in a separate application, everything is crisp and clear When I capture and save the image in code however the contrast is so low as to be unusable. I have tr...
VideoCapture USB camera OpenCV2 greyscale image contrast python
I am trying to get frames from a usb FLIR camera. The video stream works fine when I view it in a separate application, everything is crisp and clear When I capture and save the image in code however the contrast is so low as to be unusable. I have tried converting to gray scale and doing a equalizeHist but the origina...
[ "I think you might know if you are working with gray8 (\"Example Image Normal, taken from cheese\") or gray16 (\"Example Image Code, pre-hist, note you can see myself with a headset and a mic\") images.\nHere goes a good explanation:\nhttps://youtu.be/T-XuDpsJ-g8\n, extracted from this course:\nhttps://pyimagesearc...
[ 0 ]
[]
[]
[ "image_capture", "opencv", "python", "video_capture" ]
stackoverflow_0062507017_image_capture_opencv_python_video_capture.txt
Q: Python Pulp Solver: How to use compare signs (>= or <=) as variables in equation? Hello I am trying to develop a Python Pulp Linear Programming solver which is not hard-coded but instead takes all input from the user. I have successfully done the part of objective function but I am having problem with the constrai...
Python Pulp Solver: How to use compare signs (>= or <=) as variables in equation?
Hello I am trying to develop a Python Pulp Linear Programming solver which is not hard-coded but instead takes all input from the user. I have successfully done the part of objective function but I am having problem with the constraint equation part. here's a part from my code: sym = input("Enter constraint symbol '>='...
[ "assuming\nimport operator\nop = operator.ge\n\nPython doesn't interpret variable as operator so 5 op 2 doesn't work. But operators in operator module are functions and can be executed as such:\nop(5, 2) # equivalent to 5 >= 2\n\nhttps://docs.python.org/3/library/operator.html\n" ]
[ 0 ]
[]
[]
[ "linear_programming", "operator_overloading", "pulp", "python" ]
stackoverflow_0074216254_linear_programming_operator_overloading_pulp_python.txt
Q: How do I get a raw, compiled SQL query from a SQLAlchemy expression? I have a SQLAlchemy query object and want to get the text of the compiled SQL statement, with all its parameters bound (e.g. no %s or other variables waiting to be bound by the statement compiler or MySQLdb dialect engine, etc). Calling str() on ...
How do I get a raw, compiled SQL query from a SQLAlchemy expression?
I have a SQLAlchemy query object and want to get the text of the compiled SQL statement, with all its parameters bound (e.g. no %s or other variables waiting to be bound by the statement compiler or MySQLdb dialect engine, etc). Calling str() on the query reveals something like this: SELECT id WHERE date_added <= %s AN...
[ "This blog provides an updated answer.\nQuoting from the blog post, this is suggested and worked for me.\n>>> from sqlalchemy.dialects import postgresql\n>>> print str(q.statement.compile(dialect=postgresql.dialect()))\n\nWhere q is defined as:\n>>> q = DBSession.query(model.Name).distinct(model.Name.value) \\\n ...
[ 164, 162, 26, 22, 18, 15, 13, 9, 3, 3, 1, 0 ]
[ "If with SQLAlchemy you are using PyMySQL, you can do one trick.\nI was in a hurry and lost a lot of time, so I changed the driver for print the current statement with parameters.\nSQLAlchemy intentionally does not support full stringification of literal values.\nBut PyMySQL has 'mogrify' method which does it, but,...
[ -1 ]
[ "mysql", "python", "sql", "sqlalchemy" ]
stackoverflow_0004617291_mysql_python_sql_sqlalchemy.txt
Q: (raspberrypi) "pandas" Requirement already satisfied, but No module named 'pandas', when I use it (raspberrypi) "pandas" Requirement already satisfied, but No module named 'pandas', when I run python script ("import pandas as pd") I use raspberrypi 4 ; 32 bit, linux run python I run: in virtual environment (venv)...
(raspberrypi) "pandas" Requirement already satisfied, but No module named 'pandas', when I use it
(raspberrypi) "pandas" Requirement already satisfied, but No module named 'pandas', when I run python script ("import pandas as pd") I use raspberrypi 4 ; 32 bit, linux run python I run: in virtual environment (venv) joy@raspberrypi: sudo pip install pandas (venv) joy@raspberrypi: ython excel_to_mDB.py (venv) joy@ras...
[ "You are installing the pandas using the command sudo pip install pandas which will install pandas into the root folder /usr/lib/python3/dist-packages see the logs in your command. You need to install pandas into the virtual environment. So install pandas without sudo.\npip install pandas\n\n" ]
[ 2 ]
[]
[]
[ "linux", "pandas", "pip", "python", "raspberry_pi4" ]
stackoverflow_0074216726_linux_pandas_pip_python_raspberry_pi4.txt
Q: Python/Pandas to update prices already paid for certain codes So I have a rather large file that is broken down like this: Claim CPT Code TOTAL_ALLOWED CPT_CODE NEW_PRICE ALLOWED_DIFFERENCE 6675647 90887 120 90887 153 difference The thing is, for my data set, the existing already paid data is 47K lines long, ye...
Python/Pandas to update prices already paid for certain codes
So I have a rather large file that is broken down like this: Claim CPT Code TOTAL_ALLOWED CPT_CODE NEW_PRICE ALLOWED_DIFFERENCE 6675647 90887 120 90887 153 difference The thing is, for my data set, the existing already paid data is 47K lines long, yet the CPT codes we are paying are 20 codes only. How would...
[ "There is a small formatting error. Try this:\ndf['price_difference'] = np.where(df['LINE_TOTAL_ALLOWED'] == ((df['NEW_PRICE']*15)), 0, df['LINE_TOTAL_ALLOWED'] - ((df['NEW_PRICE']*15)))\n\n\n", "I did what Clegane mentioned:\nfinal = df1.merge(df3, how='left' , left_on = 'CLAIM_ID' , right_on= 'QUANTITY') \ndf...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074064721_pandas_python.txt
Q: Why am I getting Attribute error: nonetype object has no attribute get_text whenever I try to scrape this ecommerce store I'm trying to scrape an ecommerce store but getting Attribute error: nonetype object has no attribute get_text. This happens whenever i try to iterate between each products through the product ...
Why am I getting Attribute error: nonetype object has no attribute get_text whenever I try to scrape this ecommerce store
I'm trying to scrape an ecommerce store but getting Attribute error: nonetype object has no attribute get_text. This happens whenever i try to iterate between each products through the product link. I'm confused if am running into a javascript or captcha or whatnot don't know. Here's my code import requests from bs4 im...
[ "Change the variable baseurl to https://www.jumia.com.ng and change the features variable to features = soup.find('article', class_='col8 -pvs').find_all('li'). After fixing those two issues, you'll probably get an IndexError because not every page has six features listed. You can use something like the following c...
[ 1 ]
[]
[]
[ "e_commerce", "python" ]
stackoverflow_0074176579_e_commerce_python.txt
Q: How to Convert a nested list with strings to a list with strings and ints This is My current output for a Grocery list Code. The list is setup to find the sum of all of the items below. The structure of the list is ["Name", "Item Name", Item Amount, item Cost] [['Emerie', 'keyboard', '29', '199'], ['Bodie', 'keyb...
How to Convert a nested list with strings to a list with strings and ints
This is My current output for a Grocery list Code. The list is setup to find the sum of all of the items below. The structure of the list is ["Name", "Item Name", Item Amount, item Cost] [['Emerie', 'keyboard', '29', '199'], ['Bodie', 'keyboard', '9', '199'], ['Emerie', 'bed', '1', '199'], ['Brecken', 'smartwatch', '9...
[ "List comphrehension\na = [['Emerie', 'keyboard', '29', '199'], ['Bodie', 'keyboard', '9', '199'], ['Emerie', 'bed', '1', '199'], ['Brecken', 'smartwatch', '9', '199'], ['Brecken', 'SSD', '9', '199']]\n[[int(j) if j.decimal() else j for j in i ] for i in a]\n\noutput\n[['Emerie', 'keyboard', 29, 199],\n ['Bodie', '...
[ 1, 0 ]
[]
[]
[ "list", "nested_lists", "python" ]
stackoverflow_0074216873_list_nested_lists_python.txt
Q: Using webix with flask I am trying to understand the webix framework and use it with my flask application. All the documentation deals with either static data in the html file or php examples. A simple html file to populate a datatable looks like this (according to the documentation <!DOCTYPE html> <html> <head la...
Using webix with flask
I am trying to understand the webix framework and use it with my flask application. All the documentation deals with either static data in the html file or php examples. A simple html file to populate a datatable looks like this (according to the documentation <!DOCTYPE html> <html> <head lang="en"> <meta charset="...
[ "first you need to try it without using Flask\nindex.html\n<!DOCTYPE html>\n<html>\n<head lang=\"en\">\n <meta charset=\"UTF-8\">\n <link rel=\"stylesheet\" href=\"http://cdn.webix.com/edge/webix.css\" type=\"text/css\" charset=\"utf-8\">\n <script src=\"http://cdn.webix.com/edge/webix.js\" type=\"text/jav...
[ 1, 0 ]
[]
[]
[ "flask", "python", "webix" ]
stackoverflow_0038419927_flask_python_webix.txt
Q: Is it safe just use __class__ in a python class definition I understand __class__ can be used to get the class of an object, it also can be used to get current class in a class definition. My question is, in a python class definition, is it safe just use __class__, rather than self.__class__? #!/usr/bin/python3 c...
Is it safe just use __class__ in a python class definition
I understand __class__ can be used to get the class of an object, it also can be used to get current class in a class definition. My question is, in a python class definition, is it safe just use __class__, rather than self.__class__? #!/usr/bin/python3 class foo: def show_class(): print(__class__) de...
[ "__class__ is lexically scoped, whereas some_object.__class__ is dynamically dispatched. So the two can different when the lexical scope is different from the of the receiver, like if lambdas are involved:\n#!/usr/bin/env python3\n\nclass ClassA:\n def print_callback(self, callback):\n print(callback(self...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074216856_python.txt
Q: The values of my 1st column are going into the index but the column name is the 1st column outside the index The values of my first column are going into the index but the column name is the first column outside the index, so I cannot use df.reset_index. For instance, my dataframe looks like this: CHA_NUMB CHA_NA...
The values of my 1st column are going into the index but the column name is the 1st column outside the index
The values of my first column are going into the index but the column name is the first column outside the index, so I cannot use df.reset_index. For instance, my dataframe looks like this: CHA_NUMB CHA_NAME UN_CHA_ID 1 m_3_1 12345 lcha 2 t_1_2 12456 lcha 3 blah 90244 lcha 4 blah 23435 lcha When it s...
[ "First use DataFrame.reset_index, then remove last column by indexing in DataFrame.iloc and last set columns names by original DataFrame by DataFrame.set_axis:\ndf = df.reset_index().iloc[:, :-1].set_axis(df.columns, axis=1)\nprint (df)\n CHA_NUMB CHA_NAME UN_CHA_ID\n0 1 m_3_1 12345\n1 2 ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074216866_dataframe_pandas_python_python_3.x.txt
Q: Checking whether one string has more characters in it than another using Python I'm new to Python and I have some trouble understanding how for loops work in Python. In C++ if you wanted to iterate through a list of data to find the highest value in the data, you could initiate a placeholder (depending on the data...
Checking whether one string has more characters in it than another using Python
I'm new to Python and I have some trouble understanding how for loops work in Python. In C++ if you wanted to iterate through a list of data to find the highest value in the data, you could initiate a placeholder (depending on the data) such as x = 0 and it would iterate through the data using data[i] in the loop. How ...
[ "you can use builtin method max\nstr1 = \"eihd39d9\"\nstr2 = \"xkn59438\" \nstr3 = \"chdsye847\"\nmax(str1, str2, str3, key=len)\n# 'chdsye847'\n\nfor list of strings\nmax(lst_of_strs, key=len)\n\n" ]
[ 1 ]
[]
[]
[ "character", "function", "list", "python" ]
stackoverflow_0074216878_character_function_list_python.txt
Q: Embeding videos in a a Django project? Using Django-embed-video 1.4.0, we can easily embed YouTube videos into Django projects. However it doesn't seem to work if the video is from any source but YouTube. The embed video code is different for every website and whenever I enter a code from a site like TikTok, CNN...
Embeding videos in a a Django project?
Using Django-embed-video 1.4.0, we can easily embed YouTube videos into Django projects. However it doesn't seem to work if the video is from any source but YouTube. The embed video code is different for every website and whenever I enter a code from a site like TikTok, CNN, or Facebook, it says "URL could not be rec...
[ "You can build your own custom backend supporting other sources such as TikTok or CNN built on top of their VideoBackend class.\nYou can check their official documentation on how to do that here.\nAlso feel free to open a PR on the official repo in case you've actually built those extensions.\n", "You can create ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0067351155_django_python.txt
Q: How to add excel in python from openpyxl.workbook import Workbook from openpyxl import load_workbook path="C:\Users\Intel\Desktop\SDSS\DD.xlsx" wb= Workbook() wb_obj = load_workbook(path) ws=wb.active ws= wb['Sheet1'] xlsx_range = ws['C2':'C12983'] elements = [] head_range = ws['D1':'DP1'] yr=[] for cell i...
How to add excel in python
from openpyxl.workbook import Workbook from openpyxl import load_workbook path="C:\Users\Intel\Desktop\SDSS\DD.xlsx" wb= Workbook() wb_obj = load_workbook(path) ws=wb.active ws= wb['Sheet1'] xlsx_range = ws['C2':'C12983'] elements = [] head_range = ws['D1':'DP1'] yr=[] for cell in xlsx_range: for x in cell...
[ "import pandas as pd\n\ndf = pd.read_excel(r'Path of Excel \nfile\\File name.xlsx', \nsheet_name='your Excel sheet name')\nprint(df)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074216949_python.txt
Q: How do I store the results of a function into a list of some sort over time in Python? So I'm refreshing what little I knew of Python before and playing around with some beginner projects. I'm toying arond with it now, and I'm just trying to learn and see what I can do. I made a "Guessing Game" and turned it into ...
How do I store the results of a function into a list of some sort over time in Python?
So I'm refreshing what little I knew of Python before and playing around with some beginner projects. I'm toying arond with it now, and I'm just trying to learn and see what I can do. I made a "Guessing Game" and turned it into a function. I want to store these reults in a list each time it is used. I want the results ...
[ "You can create a list inside of the function, and then everytime they guess, you can store the guess inside the list. At the end, we can print the list.\ndef guessing_game():\n import random\n\n number = random.randint(1, 1000)\n player_name = input(\"Enter name: \")\n number_of_guesses = 0\n guesse...
[ 1, 0 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0074216847_function_list_python.txt
Q: How to modify a Series(DataFrame) of Pandas in place during iterating? I need to revice values in a Series(column) of Pandas according to another function. During iterating, after I get the result, I don't want to lookup the series twice, becasue I guess that it wastes time and is not required. For example: import...
How to modify a Series(DataFrame) of Pandas in place during iterating?
I need to revice values in a Series(column) of Pandas according to another function. During iterating, after I get the result, I don't want to lookup the series twice, becasue I guess that it wastes time and is not required. For example: import pandas as pd s = pd.Series(['A', 'B', 'C']) for index, value in s.items(): ...
[ "You can try to insert your data only once, not at each step:\ns[:] = [func_hard_to_vectorized(v) for v in s]\n\nOr:\ns[:] = s.apply(func_hard_to_vectorized)\n\nThus insertion will only occur once with all items at once.\nIf you don't care having a new Series (i.e. if there is not another name pointing to the Serie...
[ 1 ]
[]
[]
[ "in_place", "iteration", "pandas", "python", "reference" ]
stackoverflow_0074216793_in_place_iteration_pandas_python_reference.txt
Q: Append two of the same elements in one list to another list if a duplicate is found Python I'm creating a hangman game and I've run into a problem with the code and I cannot figure out how to resolve it. Basically what is happening is my code appends all the letters from a word to a list. If there are duplicate le...
Append two of the same elements in one list to another list if a duplicate is found Python
I'm creating a hangman game and I've run into a problem with the code and I cannot figure out how to resolve it. Basically what is happening is my code appends all the letters from a word to a list. If there are duplicate letters in the word, it will append both of the letters. In the method below that one, if the user...
[ "First get the number of instances of the letter using something like.\nCorrect_Word = \"peekaboo\"\nCorrect_Letters = []\nguessed_letter = 'e'\n\nAnd then use extend to add the guessed letter the number of times the letter is present in the word.\nFor eg:- in peekaboo there are 2 es so we have to add it 2 times in...
[ 0 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074216271_list_python_python_3.x.txt
Q: scraping data and collecting all href values I'm trying to scrape the following webpage: https://opensea.io/rankings?sortBy=total_volume And I want to collect all the href values so for example: However, it seems like I can't do it and I get some sort of error when using beautiful soup. This is the code that I ha...
scraping data and collecting all href values
I'm trying to scrape the following webpage: https://opensea.io/rankings?sortBy=total_volume And I want to collect all the href values so for example: However, it seems like I can't do it and I get some sort of error when using beautiful soup. This is the code that I have so far: page = requests.get("https://opensea.io...
[ "I expect you're getting the 403 Forbidden error - the site probably has some very good blockers, I made a quick attempt with ScrapingAnt and then tried copying the entire request for my browser, but both were blocked.\nIf you're open to trying selenium, I have this function for cases like this - you can paste it ...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074216932_beautifulsoup_python_web_scraping.txt
Q: python/django database connection issue Database settings DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE', "mysql"), 'NAME': os.environ.get('DB_NAME', "django_db"), 'USER': os.environ.get('DB_USER', "root"), 'PASSWORD': os.environ.get('DB_PASS', "123456798"), ...
python/django database connection issue
Database settings DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE', "mysql"), 'NAME': os.environ.get('DB_NAME', "django_db"), 'USER': os.environ.get('DB_USER', "root"), 'PASSWORD': os.environ.get('DB_PASS', "123456798"), 'HOST': os.environ.get('DB_HOST', "loca...
[ "Instead of :\nmysql in 'ENGINE': os.environ.get('DB_ENGINE', \"mysql\"),\nTry this:\n'ENGINE': os.environ.get('DB_ENGINE', \"django.db.backends.mysql\"),\n\n", "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'django_db',\n 'USER': 'root',\n 'PASSWORD...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074217120_django_python.txt
Q: Can I use Django in a way that I can change CSS variables? I am creating a personal website and I have a progress bar that has been done in css and html. in order to control the progress bars all I need to do is change a variable(width). This is the code for one bar: .bar-inner1 { width: 559px; height: 35px; ...
Can I use Django in a way that I can change CSS variables?
I am creating a personal website and I have a progress bar that has been done in css and html. in order to control the progress bars all I need to do is change a variable(width). This is the code for one bar: .bar-inner1 { width: 559px; height: 35px; line-height: 35px; background: #db3a34; border-radius: 5px ...
[ "You can use inline CSS to change width, like\n<div class=\"container\">\n <h2 class=\"my-skills\">My Skills</h2>\n <div class=\"bar-1\">\n <div class=\"title\">HTML5</div>\n <div class=\"bar\" data-width=\"65%\">\n <div class=\"bar-inner1\" style=\"width: {{ progress|default:0 }}%;\">\n\n </div>\n <di...
[ 1, 0, 0 ]
[]
[]
[ "css", "django", "html", "python" ]
stackoverflow_0074212285_css_django_html_python.txt
Q: pycharm does not connect to console with python3.8 I dont know why; but since python 3.8 has been released; I cant run pycharm console and it is always in the "being connected" status. I have had no problem with python 3.7; since the console is opened immediately. Here you can see that I have tried several times t...
pycharm does not connect to console with python3.8
I dont know why; but since python 3.8 has been released; I cant run pycharm console and it is always in the "being connected" status. I have had no problem with python 3.7; since the console is opened immediately. Here you can see that I have tried several times to run the console but I know, even if I wait a day; It d...
[ "It works fine on PyCharm (Community) 2019.3.\nPyCharm ships [PyPI]: thriftpy (for current version, it's a modified v0.3.8), as it needs it for different features (including the Python Console).\nPython 3.8 came with a set of changes (one example is [Python]: PEP 570 -- Python Positional-Only Parameters) requiring ...
[ 16, 0 ]
[]
[]
[ "console", "pycharm", "python", "python_3.8" ]
stackoverflow_0059371627_console_pycharm_python_python_3.8.txt
Q: Excel data extraction using regular expressions through Python This is part 1 of a series of questions I will make on this forum so bear with me on this one. I am a novice programmer who took on a large project because i like to torture myself, so please be kind. I am writing a Python script to process an Excel do...
Excel data extraction using regular expressions through Python
This is part 1 of a series of questions I will make on this forum so bear with me on this one. I am a novice programmer who took on a large project because i like to torture myself, so please be kind. I am writing a Python script to process an Excel document full of accounts (See example below), each one being the same...
[ "Look into these python modules:\nimport xlwt\nfrom xlwt.Workbook import *\nimport xlsxwriter\nimport numpy as np\nimport pandas as pd\nfrom pandas import ExcelWriter\n\nThen you can use pandas dataframe like:\ndata = pd.read_excel('testacct.xlsx')\n\nThis will put the entire spreadsheet into a dict with generic co...
[ 0 ]
[]
[]
[ "excel", "ms_access", "mysql", "python" ]
stackoverflow_0074216690_excel_ms_access_mysql_python.txt
Q: hello im learning about diictionarys in python but when i did a mini side project it didnt work print("**PhoneBook**") phonedict = [ {"name":"Harry", "number":"054213435"}, {"name":"Larry", "number":"12345676"}, {"name":"Harvey", "number":"10101213"}, {"name":"Ronaldo", "number":"121314121"}, {...
hello im learning about diictionarys in python but when i did a mini side project it didnt work
print("**PhoneBook**") phonedict = [ {"name":"Harry", "number":"054213435"}, {"name":"Larry", "number":"12345676"}, {"name":"Harvey", "number":"10101213"}, {"name":"Ronaldo", "number":"121314121"}, {"name":'Laith', "number":"0506203880"} ] contact = input("Which Contact you want: ") for contact in p...
[ "phonedict is a list of dictionaries you need to iterate through the list to check the contact exists.\ncontact = input(\"Which Contact you want: \")\nfor item in phonedict:\n if contact == item['name']:\n print(item)\n\n" ]
[ 0 ]
[]
[]
[ "compiler_errors", "dictionary", "for_loop", "python" ]
stackoverflow_0074217220_compiler_errors_dictionary_for_loop_python.txt
Q: Print the first two rows of a csv file to a standard output I would like to print (stdout) the first two lines of a csv file: #!/usr/bin/env python import csv afile = open('<directory>/*.csv', 'r+') csvReader1 = csv.reader(afile) for row in csvReader1: print row[0] print row[1] however, my output using th...
Print the first two rows of a csv file to a standard output
I would like to print (stdout) the first two lines of a csv file: #!/usr/bin/env python import csv afile = open('<directory>/*.csv', 'r+') csvReader1 = csv.reader(afile) for row in csvReader1: print row[0] print row[1] however, my output using this code print the first two columns. Any suggestions?
[ "You want to print a row, but your code asks to print the first and second members of each row\nSince you want to print the whole row - you can simply print it, and in addition, only read the first two\n#!/usr/bin/env python\nimport csv\nafile = open('<directory>/*.csv', 'r+')\ncsvReader1 = csv.reader(afile)\nfor i...
[ 15, 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007661540_python.txt
Q: Get list of numbers in python without using numpy Is there a way to get list of numbers in python without using numpy. Example, asd = ['926', '927', '928', '929', '930', '931'] I have a list above which are typed manually.. but can not put a range like (926 to 931) and get the list? Any help? A: You can do with...
Get list of numbers in python without using numpy
Is there a way to get list of numbers in python without using numpy. Example, asd = ['926', '927', '928', '929', '930', '931'] I have a list above which are typed manually.. but can not put a range like (926 to 931) and get the list? Any help?
[ "You can do with range + map,\nIn [1]: list(map(str,range(926, 932)))\nOut[1]: ['926', '927', '928', '929', '930', '931']\n\n", "asd = [str(i) for i in range(926, 932)]\nsquare brackets [...] make it return a list\ni for i in range(x, y) returns every value between x and y, inclusive of x and y\nstr(i) converts i...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074217317_python.txt
Q: Difference between data[0:4] and data.iloc[0:4] Can anyone explain me whats the Difference between data[0:4] and data.iloc[0:4] when i run these 2 commands iam reciving same output Here is my code:- import pandas as pd data= pd.read_csv("C:/Users/Admin/PycharmProjects/pythonProject1/venv\Lib/site-packages/pandas/t...
Difference between data[0:4] and data.iloc[0:4]
Can anyone explain me whats the Difference between data[0:4] and data.iloc[0:4] when i run these 2 commands iam reciving same output Here is my code:- import pandas as pd data= pd.read_csv("C:/Users/Admin/PycharmProjects/pythonProject1/venv\Lib/site-packages/pandas/test.csv") print(data[0:4]) print(data.iloc[0:4]) out...
[ "I really hope this comment helps you understand this concept better https://stackoverflow.com/a/31593712/19275334\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074212248_pandas_python.txt
Q: How to check strings for special symbols I have to check each row of the table for special symbols and add a column with the number of symbols without using cycles,but i have to use regular expressions I write a regular expression: rexp = '("|#|%|\[|\])' len(re.findall(rexp, 'asdfasf[sadfsaf%sadfad]]')) And I try...
How to check strings for special symbols
I have to check each row of the table for special symbols and add a column with the number of symbols without using cycles,but i have to use regular expressions I write a regular expression: rexp = '("|#|%|\[|\])' len(re.findall(rexp, 'asdfasf[sadfsaf%sadfad]]')) And I try to solve it like this: def special_symbols(x)...
[ "games_df['n_special_symbols'] = games_df['your column with the string goes here'].apply(special_symbols)\n\n", "There's no need to use apply. It's much faster and easier to address a built-in pandas.Series.str.count which takes a regular expression as a parameter:\ndf = pd.DataFrame({'game_description':['one[two...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074214807_pandas_python.txt
Q: Microsoft Graph API get task list without user login I am trying to create a python script that adds some tasks to my Microsoft ToDo List by using the Microsoft Graph API from python. So far I was able to achieve this such that every time I run the script I have to log into my account and give permission such that...
Microsoft Graph API get task list without user login
I am trying to create a python script that adds some tasks to my Microsoft ToDo List by using the Microsoft Graph API from python. So far I was able to achieve this such that every time I run the script I have to log into my account and give permission such that the script can access my tasks. However, I now want to ac...
[ "In that case you need to use ROPC flow and hard-code the username and password in the back-end code. please follow the doc - https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc\nHope this helps\nThanks\n" ]
[ 0 ]
[]
[]
[ "microsoft_graph_api", "python" ]
stackoverflow_0074212885_microsoft_graph_api_python.txt
Q: Difference and benefit of using Declarative Base Classes instead of table objects in SQLAlchemy I am having problems understanding the benefit of the usage of declarative classes in SQLAlchemy. As I understand the ORM is a way to apply the concept of database tables to the class system of OOP. However I don't unde...
Difference and benefit of using Declarative Base Classes instead of table objects in SQLAlchemy
I am having problems understanding the benefit of the usage of declarative classes in SQLAlchemy. As I understand the ORM is a way to apply the concept of database tables to the class system of OOP. However I don't understand why the table class doesn't already satisfy this requirement. So to form my question via an e...
[ "I have the same question recently, you can refer to SQLAlchemy doc.\n\nSome examples in the documentation still use the classical approach, but note that the classical as well as Declarative approaches are fully interchangeable.\n\nI think the benefit of using Declarative Mapping is that,\n\nmore convinent to use ...
[ 3 ]
[]
[]
[ "class", "declarative", "python", "sqlalchemy" ]
stackoverflow_0059946808_class_declarative_python_sqlalchemy.txt
Q: 403 response when using scrapy python I am trying to learn scrapy and do crawl for a website, but I am getting a 403 response when doing crawl this is my spider: import scrapy from scrapy.loader import ItemLoader from itemloaders.processors import TakeFirst, MapCompose from w3lib.html import remove_tags def remov...
403 response when using scrapy python
I am trying to learn scrapy and do crawl for a website, but I am getting a 403 response when doing crawl this is my spider: import scrapy from scrapy.loader import ItemLoader from itemloaders.processors import TakeFirst, MapCompose from w3lib.html import remove_tags def remove_currency(value): return value.replace...
[ "@Barry the Platipus already has nicely stated that the website is under Cloudflare protection. So sending general requests wouldn't work here. That's why the general rule of thumbs is that you can apply either cloud scraper or selenium. I used both of them cloudscraper and Scrapy/Selenium with scrapy/scrapy-Selen...
[ 2 ]
[]
[]
[ "python", "scrapy", "web_crawler" ]
stackoverflow_0074212110_python_scrapy_web_crawler.txt
Q: What does "image[:,:,3]" mean in Python/OpenCV I have come across this line of code from an answer to a stackoverflow question (https://stackoverflow.com/a/53737420): trans_mask = image[:,:,3] == 0 This creates a mask from an OpenCV image. I am wondering how the syntax for image[:,:,3] == 0 works. I know that lis...
What does "image[:,:,3]" mean in Python/OpenCV
I have come across this line of code from an answer to a stackoverflow question (https://stackoverflow.com/a/53737420): trans_mask = image[:,:,3] == 0 This creates a mask from an OpenCV image. I am wondering how the syntax for image[:,:,3] == 0 works. I know that list[:] basically makes a copy of a list, but I was una...
[]
[]
[ "When a list-like object is indexed, the __getitem__ method is called. One can create a simple class that shows you what is passed to that method:\nclass Inspector:\n def __getitem__(self, key):\n return key()\n\ni = Inspector()\ni[:,:,3] # => (slice(None, None, None), slice(None, None, None), 3)\n\nWhich...
[ -1 ]
[ "numpy", "python", "syntax" ]
stackoverflow_0074213533_numpy_python_syntax.txt
Q: Pyspark find the nearest text I'm a new user for pyspark. I want to compare text from two different dataframes (containing news information) for recommendation. I was able to do this very easily with Python: def get_recommendations(title, cosine_sim, indices): idx = indices[title] # Get the pairwsie simila...
Pyspark find the nearest text
I'm a new user for pyspark. I want to compare text from two different dataframes (containing news information) for recommendation. I was able to do this very easily with Python: def get_recommendations(title, cosine_sim, indices): idx = indices[title] # Get the pairwsie similarity scores sim_scores = list(e...
[ "Following is an example of TF-IDF usage in Spark from my PoC assignment. I will highly recommend to use advanced NLP frameworks like BERT than TF-IDF for meaningful similarity.\nSample dataset:\ndf = spark.createDataFrame(\n [\n [\"cricket sport team player\"],\n [\"global politics\"],\n [\...
[ 1 ]
[]
[]
[ "database", "pyspark", "python", "recommendation_engine", "text_comparison" ]
stackoverflow_0074215036_database_pyspark_python_recommendation_engine_text_comparison.txt
Q: I am a beginner in python, can someone please explain me this piece of code in detail? marks = [95, 98, 97] i = 0 while i < len(marks): print(marks[i]) i = i + 1 I want to understand this print(marks[i]) and i = i + 1, what is its use here and why can it not be written before print function? I am learnin...
I am a beginner in python, can someone please explain me this piece of code in detail?
marks = [95, 98, 97] i = 0 while i < len(marks): print(marks[i]) i = i + 1 I want to understand this print(marks[i]) and i = i + 1, what is its use here and why can it not be written before print function? I am learning about while loop in list data type and I am not able to understand this code.
[ "The idiomatic way to loop over a list is simply\nfor item in marks:\n print(item)\n\nThere are situations where you want to keep track of where you hre in the list, though then, maybe use enumerate:\nfor idx, item in enumerate(marks, 1):\n print(\"item at position\", idx, \"is\", item)\n\nIn lower-level lang...
[ 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "list", "python", "while_loop" ]
stackoverflow_0074217344_list_python_while_loop.txt
Q: how to get the same day of next month of a given day in python using datetime i know using datetime.timedelta i can get the date of some days away form given date daysafter = datetime.date.today() + datetime.timedelta(days=5) but seems no datetime.timedelta(month=1) A: Use dateutil module. It has relative tim...
how to get the same day of next month of a given day in python using datetime
i know using datetime.timedelta i can get the date of some days away form given date daysafter = datetime.date.today() + datetime.timedelta(days=5) but seems no datetime.timedelta(month=1)
[ "Use dateutil module. It has relative time deltas:\nimport datetime\nfrom dateutil import relativedelta\nnextmonth = datetime.date.today() + relativedelta.relativedelta(months=1)\n\nBeautiful.\n", "Of course there isn't -- if today's January 31, what would be \"the same day of the next month\"?! Obviously there ...
[ 204, 44, 9, 6, 6, 4, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "date", "datetime", "python" ]
stackoverflow_0002249956_date_datetime_python.txt
Q: Install local python libary in azure ml studio environment I am trying to run a Machine Learning training script I wrote in azure by using: env = Environment.from_conda_specification("experiment_env", "my_environment.yml") script_config = ScriptRunConfig(source_directory=experiment_folder, ...
Install local python libary in azure ml studio environment
I am trying to run a Machine Learning training script I wrote in azure by using: env = Environment.from_conda_specification("experiment_env", "my_environment.yml") script_config = ScriptRunConfig(source_directory=experiment_folder, script='path_to_file/classifier_train.py', ...
[ "To install local libraries on azure ML environment, we need to create the Data Science VM on the local machine and connect it with the workspace subscription details.\nCreate ML studio workspace and download the JSON file which consists of the details of the workspace need to be connected to the VM.\n\nCreate a py...
[ 1 ]
[]
[]
[ "azure", "azure_machine_learning_service", "azure_machine_learning_studio", "azureml_python_sdk", "python" ]
stackoverflow_0074123559_azure_azure_machine_learning_service_azure_machine_learning_studio_azureml_python_sdk_python.txt
Q: Python: Need guidance with a dropdown list I took over a web app from a user who left the company and I don't know what I'm doing. Basically I have a site table that has 2 columns I need, site and name. I want the name to display in the dropdown menu and site to be the value of the dropdown. This what it looks lik...
Python: Need guidance with a dropdown list
I took over a web app from a user who left the company and I don't know what I'm doing. Basically I have a site table that has 2 columns I need, site and name. I want the name to display in the dropdown menu and site to be the value of the dropdown. This what it looks like now: In the views template def getWarehouseLis...
[ "Your must response all Site object fields in context to template, not only site value. Your view function should be like below:\nfrom django.shortcuts import render\n\ndef getWarehouseList(request):\n context={\n 'warehouse_list' : Site.objects.filter(active=True).order_by('site') # you can give any stri...
[ 0 ]
[]
[]
[ "django", "django_views", "html", "python" ]
stackoverflow_0074209173_django_django_views_html_python.txt
Q: Create multilevel dictionary from DataFrame I am trying to build out multilayer dictionary. The input looks like this. my_list = [['Japan', 'Consumer Durables'], ['United States', 'Electronic Technology', 'ANALYST PICK'], ['Japan', 'Finance'], ['South Korea', 'Electronic Technology']] df = pd.DataFrame(my_list, co...
Create multilevel dictionary from DataFrame
I am trying to build out multilayer dictionary. The input looks like this. my_list = [['Japan', 'Consumer Durables'], ['United States', 'Electronic Technology', 'ANALYST PICK'], ['Japan', 'Finance'], ['South Korea', 'Electronic Technology']] df = pd.DataFrame(my_list, columns=['country','sector','flag']) country s...
[ "The provided output is invalid (dictionaries cannot have duplicated keys), however a close output would be:\nout = {'groups':\n [{'name': k, 'groups': [{'name': name, 'index': idx}\n for name, idx in g.reset_index()\n .groupby('sector')['index']\n ...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074188455_pandas_python.txt
Q: Web Scrape table data from this webpage I'm trying to scrape the data from the table in the specifications section of this webpage: Lochinvar Water Heaters I'm using beautiful soup 4. I've tried searching for it by class - for example - (class="Table__Cell-sc-1e0v68l-0 kdksLO") but bs4 can't find the class on the ...
Web Scrape table data from this webpage
I'm trying to scrape the data from the table in the specifications section of this webpage: Lochinvar Water Heaters I'm using beautiful soup 4. I've tried searching for it by class - for example - (class="Table__Cell-sc-1e0v68l-0 kdksLO") but bs4 can't find the class on the webpage. I listed all the available classes t...
[ "The contents for constructing the table are within a script tag. You can extract the relevant string and re-create the table through string manipulation.\nimport requests, re\nimport pandas as pd\n\nr = requests.get('https://www.lochinvar.com/products/commercial-water-heaters/armor-condensing-water-heater/').text\...
[ 1, 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074216240_beautifulsoup_python_web_scraping.txt
Q: Can somebody help me with python-ldap initialize process? I am using OpenSuse Tumbleweed and try to connect my pythons script with an ldap server. following my code: import ldap connection = ldap.initialize("*address*") But i got following error: File "ldap.py", line 1, in <module> import ldap File "*path*/ldap...
Can somebody help me with python-ldap initialize process?
I am using OpenSuse Tumbleweed and try to connect my pythons script with an ldap server. following my code: import ldap connection = ldap.initialize("*address*") But i got following error: File "ldap.py", line 1, in <module> import ldap File "*path*/ldap.py", line 3, in <module> connection = ldap.initialize("*addres...
[ "I found my mistake:\nThe file was named ldap.py an was the only file in this directory. But know, python tried to import this file into the same file.\nI renamed it to test_ldap.py and know everything works fine\nBest Regards\n" ]
[ 0 ]
[]
[]
[ "ldap", "python", "python_ldap" ]
stackoverflow_0074190277_ldap_python_python_ldap.txt
Q: Locust: Failed apis with count are not getting included in csv report we are running the load test via this command: locust --config=./config/entity_publish_flows.conf But after completion of load test, we see that failed apis are not getting listed in csv although failures are getting logged in log file. Actually...
Locust: Failed apis with count are not getting included in csv report
we are running the load test via this command: locust --config=./config/entity_publish_flows.conf But after completion of load test, we see that failed apis are not getting listed in csv although failures are getting logged in log file. Actually there are total 11 apis, but as 3 apis are giving error, only 8 apis are ...
[ "I solved this, you have to write like this when doing any API call by using catch_Reponse=True and response.failure(\"any message\"):\ndef get(self, endpoint, headers, name=None):\n with self.client.get(endpoint, headers=headers, name=name, catch_response=True,\n cookies=self.user.get_cookie...
[ 0 ]
[]
[]
[ "locust", "performance", "python" ]
stackoverflow_0074204951_locust_performance_python.txt
Q: How do I tell webdriver to skip urls in a list if they return connection refused? I have a python script that loops through urls (ip addresses) for IoT devices to gather info from them. Every now and then I have one or two that say connection refused and the site wont load. It does this with and without selenium. ...
How do I tell webdriver to skip urls in a list if they return connection refused?
I have a python script that loops through urls (ip addresses) for IoT devices to gather info from them. Every now and then I have one or two that say connection refused and the site wont load. It does this with and without selenium. How can I tell my script to skip over a non working url and go to the next url in the l...
[ "You can use try/except block and check if the error says\n\nERR_CONNECTION_REFUSED\n\nYou need to import WebDriverException to be able to catch the error\nThis code will look like this:\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import WebDriverExc...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "webdriver" ]
stackoverflow_0074211789_python_selenium_selenium_webdriver_webdriver.txt
Q: How to specify `pip.conf` to allow packages download from aritifactory? i have a couple of packages which I need to install from artifactory and a couple of them need to be downloaded from the public pypi.org, my pip.conf file looks like this: [global] index-url = https://xx/artifactory/xxx/simple extra-index-url...
How to specify `pip.conf` to allow packages download from aritifactory?
i have a couple of packages which I need to install from artifactory and a couple of them need to be downloaded from the public pypi.org, my pip.conf file looks like this: [global] index-url = https://xx/artifactory/xxx/simple extra-index-url = https://xxx/artifactory/xxx/simple (# this is a mirror of pypi) Theoretic...
[ "Do refer to this screencast to set up pip with Artifactory. Moreover, the issue seems to be related to the index-url which should be as below,\n[global]\nindex-url = https://myart.jfrog.com/artifactory/api/pypi/pypi-virtual-repo/simple\n\n" ]
[ 1 ]
[]
[]
[ "artifactory", "pip", "pypi", "python" ]
stackoverflow_0074211092_artifactory_pip_pypi_python.txt
Q: How do I read a response from Python Requests? I have two Python scripts. One uses the Urllib2 library and one uses the Requests library. I have found Requests easier to implement, but I can't find an equivalent for urlib2's read() function. For example: ... response = url.urlopen(req) print response.geturl() prin...
How do I read a response from Python Requests?
I have two Python scripts. One uses the Urllib2 library and one uses the Requests library. I have found Requests easier to implement, but I can't find an equivalent for urlib2's read() function. For example: ... response = url.urlopen(req) print response.geturl() print response.getcode() data = response.read() print da...
[ "Requests doesn't have an equivalent to Urlib2's read().\n>>> import requests\n>>> response = requests.get(\"http://www.google.com\")\n>>> print response.content\n'<!doctype html><html itemscope=\"\" itemtype=\"http://schema.org/WebPage\"><head>....'\n>>> print response.content == response.text\nTrue\n\nIt looks li...
[ 215, 53, 10, 2, 2 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0018810777_python_python_requests.txt
Q: replace data if string left equals to something in pandas So i have a dataset looks like: Col A Col B Col C Nanana Teacher 123456 Popopo Student 232322 Cecece Teacher 455433 Lalala Student 231231 Poasls Teacher 235433 Lilili Teacher 723543 I wanted to replace COL A When Col B = Teacher AND LEFT(COL C,1) =...
replace data if string left equals to something in pandas
So i have a dataset looks like: Col A Col B Col C Nanana Teacher 123456 Popopo Student 232322 Cecece Teacher 455433 Lalala Student 231231 Poasls Teacher 235433 Lilili Teacher 723543 I wanted to replace COL A When Col B = Teacher AND LEFT(COL C,1) = 2/4 I wanted to replace it if teacher and numbe...
[ "Use numpy.select with masks:\n# filter Teacher in Col B\nm1 = df['Col B'].eq('Teacher')\n\n#first letter 2 or 4 in Col C\ns = df['Col C'].astype(str).str[0]\nm2 = s.isin(['2','4'])\n#first letter 1\nm3 = s.eq('1')\n\ndf['Col A'] = np.select([m1 & m2, m1 & m3], ['Teacher2','Teacher'], default=df['Col A'])\nprint (d...
[ 4 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074217623_numpy_pandas_python.txt
Q: How to run recursion in class python I am trying to create a class Matrix which has a method called row_echelon, and I am trying to use recursion, but it's not working. class Matrix: def __init__(self,matrix): self.matrix = matrix def row_echelon(self): r, c = self.matrix.shape ...
How to run recursion in class python
I am trying to create a class Matrix which has a method called row_echelon, and I am trying to use recursion, but it's not working. class Matrix: def __init__(self,matrix): self.matrix = matrix def row_echelon(self): r, c = self.matrix.shape if r == 0 or c == 0: re...
[ "In def row_echelon(self): you define the function to be called with object reference but in new_matrix = self.row_echelon(self.matrix[:,1:]) you pass a matrix to the function as well. When you call the a class function, it will automatically get an argument of self the object reference due to the definition wheth...
[ 0, 0 ]
[]
[]
[ "class", "python", "recursion" ]
stackoverflow_0074217492_class_python_recursion.txt
Q: Removing prime numbers from a linked list I have a linked list that I am trying to generate a random list and then remove all of its prime numbers. This is what I have so far. I know how to find the primes I'm just not sure where to go on removing them from the list. This is my updated list, it only removes one nu...
Removing prime numbers from a linked list
I have a linked list that I am trying to generate a random list and then remove all of its prime numbers. This is what I have so far. I know how to find the primes I'm just not sure where to go on removing them from the list. This is my updated list, it only removes one number instead of deleting all primes. import ran...
[ "You can do a for loop on the now generated linked list, check the number using your isPrime method and running .remove(item) on the list, where item is the current iteration over the list\n" ]
[ 1 ]
[]
[]
[ "linked_list", "python" ]
stackoverflow_0074217653_linked_list_python.txt
Q: How can i turn time data to time format when it's original format (string) looks like this? 1164570 1H45M 1421781 0 458245 7H 2714970 6H 2956491 0 89924 0 580685 3H 1330835 1H45M 599197 6H30M 541245 7H 2257962 0 1418006 1H15M 407282 5H30M 80...
How can i turn time data to time format when it's original format (string) looks like this?
1164570 1H45M 1421781 0 458245 7H 2714970 6H 2956491 0 89924 0 580685 3H 1330835 1H45M 599197 6H30M 541245 7H 2257962 0 1418006 1H15M 407282 5H30M 804217 7H30M 1221037 6H30M 1461747 0 148837 3H 168789 2H 2245125 ...
[ "For numeric get integers before H and M and sum with divide 60 for minutes:\nh = df['time'].str.extract(r'(\\d+)H', expand=False).astype(float)\nm = df['time'].str.extract(r'(\\d+)M', expand=False).astype(float).div(60)\n\ndf['numeric'] = h.add(m, fill_value=0)\ndf['times'] = pd.to_datetime(h.add(m, fill_value=0)....
[ 1, 0 ]
[]
[]
[ "pandas", "python", "string", "time" ]
stackoverflow_0074217588_pandas_python_string_time.txt
Q: splitting multiple lists in 1 big list into seperate lists I have the following list: order = [['S', ['PINEAPPLE']], ['M', ['PINEAPPLE']], ['L', ['PINEAPPLE']]] I want to split this list into seperate lists so that it will look like this order1 = ['S', ['PINEAPPLE']] order2 = ['M', ['PINEAPPLE']] order3 = ['L',...
splitting multiple lists in 1 big list into seperate lists
I have the following list: order = [['S', ['PINEAPPLE']], ['M', ['PINEAPPLE']], ['L', ['PINEAPPLE']]] I want to split this list into seperate lists so that it will look like this order1 = ['S', ['PINEAPPLE']] order2 = ['M', ['PINEAPPLE']] order3 = ['L', ['PINEAPPLE']] I would also like to know if its possible to ma...
[ "You can just unpack to those variable names from the list.\norder = [['S', ['PINEAPPLE']], ['M', ['PINEAPPLE']], ['L', ['PINEAPPLE']]]\norder1, order2, order3 = order\n\nprint(order2)\n\noutput\n['M', ['PINEAPPLE']]\n\nTo return as tuples use;\norder1, order2, order3 = map(tuple, order)\n\n", "You can try loopin...
[ 1, 0 ]
[]
[]
[ "python", "python_3.9" ]
stackoverflow_0074217229_python_python_3.9.txt
Q: how do i use two lists in robot framework keyword? I would like to create a keyword that has 2 lists, where list 1 would be the fields and list 2 would be the field values. Examples: I have 3 fields: Name: John Birth: 10/26/2022 City: João Pessoa Keywords: fill in the fields [Arguments] @{fields} @{values} however...
how do i use two lists in robot framework keyword?
I would like to create a keyword that has 2 lists, where list 1 would be the fields and list 2 would be the field values. Examples: I have 3 fields: Name: John Birth: 10/26/2022 City: João Pessoa Keywords: fill in the fields [Arguments] @{fields} @{values} however, it is not possible to do this, Robot returns the follo...
[ "Reference: https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#for-in-zip-loop\nCheck below code snippet, which has two list and there are two ways to iterate. Hope this is what you're looking for.\nUpdated Code as per your comment:\nWhen you pass two list variable, use \"$\" instead of \...
[ 0 ]
[]
[]
[ "helper", "list", "python", "python_2.7", "robotframework" ]
stackoverflow_0074215230_helper_list_python_python_2.7_robotframework.txt
Q: How to filter a column based on several other columns in pandas? I have a dataset of prices for various types of fruits in various quarters for several years. I want to filter a column based on the values of multiple other columns. The dataframe looks like this: First column contains years. Column 2 can have a mi...
How to filter a column based on several other columns in pandas?
I have a dataset of prices for various types of fruits in various quarters for several years. I want to filter a column based on the values of multiple other columns. The dataframe looks like this: First column contains years. Column 2 can have a mix of 4 quarters Q1, Q2, Q3, and Q4. Column 3 contains the names of the...
[ "\ns =\"\"\"Year Quarter Foods Types Prices\n2015 Q1 Apples Apple1 107.7\n2015 Q2 Apples Apple1 109.4\n2015 Q3 Apples Apple1 110.2\n2015 Q4 Apples Apple1 109.6\n2016 Q1 Apples Apple1 109.3\n2016 Q2 Apples Apple1 108.7\n2016 Q3 Apples Apple1 112.6\n2016 Q4 Apples A...
[ 1, 1 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074216550_dataframe_group_by_pandas_python.txt
Q: hard lag when webcam is release I'm using the pygame and Opencv library to make a simple GUI with buttons and a webcam and whenever the webcam is turned off using the release() function from the OpenCv library, it lags the whole GUI out. Here are the code snippet: if event.type == pygame.MOUSEBUTTONDOWN: # 3. ...
hard lag when webcam is release
I'm using the pygame and Opencv library to make a simple GUI with buttons and a webcam and whenever the webcam is turned off using the release() function from the OpenCv library, it lags the whole GUI out. Here are the code snippet: if event.type == pygame.MOUSEBUTTONDOWN: # 3. here the interactions with the click ...
[ "You can release the camera in a thread:\nimport threading\n\ndef camera_release():\n camera.release()\nrelease_thread = threading.Thread(target=camera_release)\n\nif b1.rect.collidepoint(pygame.mouse.get_pos()):\n release_thread.start()\n print(\"OFF\")\n\nAdd a flag that indicates the recording status of...
[ 1 ]
[]
[]
[ "lag", "opencv", "pygame", "python" ]
stackoverflow_0074215542_lag_opencv_pygame_python.txt
Q: How to disable whatsapp open-url pop-up while scraping I am currently working on a project where I have to scrape individual WhatsApp profile and get certain details from it using api.whatsapp. With this link immediately the chrome browser pops up it displays a notification, which immediately stops all the code fr...
How to disable whatsapp open-url pop-up while scraping
I am currently working on a project where I have to scrape individual WhatsApp profile and get certain details from it using api.whatsapp. With this link immediately the chrome browser pops up it displays a notification, which immediately stops all the code from running, I need to be able to bypass the pop up. import ...
[ "to skip alert open whatsapp frist\ndriver.get('https://web.whatsapp.com/')\n\nthan use\njs = \"\"\"\n var [ num ] = [ arguments[0]];\n function openChat (t) {\n var e;\n t&&((e=document.createElement(\"a\")).setAttribute(\"href\",\"whatsapp://send?phone=\"+t),doc...
[ 0 ]
[]
[]
[ "python", "selenium", "whatsapp" ]
stackoverflow_0074212963_python_selenium_whatsapp.txt
Q: Tkinter, transparent background, Linux Is there a way to get a transparent background in a Tkinter window on Linux? The only way I see currently is: import tkinter as tk root = tk.Tk() root.overrideredirect(True) root.wait_visibility(True) root.wm_attributes("-alpha", 0.0) canvas = tk.Canvas(root, width=300, he...
Tkinter, transparent background, Linux
Is there a way to get a transparent background in a Tkinter window on Linux? The only way I see currently is: import tkinter as tk root = tk.Tk() root.overrideredirect(True) root.wait_visibility(True) root.wm_attributes("-alpha", 0.0) canvas = tk.Canvas(root, width=300, height=300) canvas.pack() canvas.create_rectan...
[ "I'm pretty sure this is going to work.\nroot.wm_attributes(\"-alpha\", 0.5)\nroot.wait_visibility(root)\n\n", "It worked for me on Ubuntu 20.04, Linux Mint 20.1, Cinnamon\nPython 3.6\nimport tkinter as tk\nroot = tk.Tk()\nroot.overrideredirect(True)\nroot.wait_visibility(root)\nroot.wm_attributes(\"-alpha\", 0.5...
[ 3, 1, 0, 0 ]
[]
[]
[ "linux", "python", "tkinter" ]
stackoverflow_0048837909_linux_python_tkinter.txt
Q: Creating a secure environment for untrusted python code I'm writing an application where we need to execute untrusted python code. (i.e. an application similar to a homework submission server, where student input is untrusted) Thinking about it, my first thought is that by disabling the file I/O capabilities of th...
Creating a secure environment for untrusted python code
I'm writing an application where we need to execute untrusted python code. (i.e. an application similar to a homework submission server, where student input is untrusted) Thinking about it, my first thought is that by disabling the file I/O capabilities of the language (and thus, restrict code to using stdin/stdout onl...
[ "Run them in docker containers!\n\nRestrict their resources\nRestrict network access\nDetailed security information\nDiscussion about security\n\nAs with anything about security, there is no silver bullet. Your mileage may vary.\n", "I wouldn't execute arbitrary code on your machine using any of the python sandbo...
[ 5, 1, 0 ]
[]
[]
[ "execution", "python", "sandbox", "security" ]
stackoverflow_0053075809_execution_python_sandbox_security.txt
Q: How to crop the specific part of image using PaddleOcr Bounding box Co-ordinates Currently I am working on the Vietnamese text detection from the image So, to detect the text in Image I am using the PaddleOcr Detection because I need line to line detection. Paddleocr is showing 100% result for that, we can do reco...
How to crop the specific part of image using PaddleOcr Bounding box Co-ordinates
Currently I am working on the Vietnamese text detection from the image So, to detect the text in Image I am using the PaddleOcr Detection because I need line to line detection. Paddleocr is showing 100% result for that, we can do recognition using PaddleOcr has PaddleOcr didn't trained on Vietnamese it's not giving 100...
[ "Thanks, I figured it out. Here boxes are the Bbox from paddelocr\nbox = np.array(boxes).astype(np.int32).reshape(-1, 2)\n\nimg = cv2.imread(img_path)\nheight = img.shape[0]\nwidth = img.shape[1]\n\nmask = np.zeros((height, width), dtype=np.uint8)\nNew_list = boxes.copy()\n\nfor boxs in New_list:\n box=np.array(bo...
[ 0 ]
[]
[]
[ "bounding_box", "ocr", "paddle_paddle", "python", "python_imaging_library" ]
stackoverflow_0074151879_bounding_box_ocr_paddle_paddle_python_python_imaging_library.txt
Q: Store text of driver.find_element into a python variable Im trying to create an discord embed that containts info of some webstite. Im trying to store the driver.find_element.text of with selenium. Then I want to put that python variable into a json code that makes a discord embed. The problem is that each product...
Store text of driver.find_element into a python variable
Im trying to create an discord embed that containts info of some webstite. Im trying to store the driver.find_element.text of with selenium. Then I want to put that python variable into a json code that makes a discord embed. The problem is that each product of this page give me 3 different texts. How can I save each o...
[ "Store the text in a variable or a\nelement_text = product_1.text\nelement_text_split = element_text.split() # split by space\n\nIf you wanted the price of that item: element_text_split[0] would get the first word\nSecond word element_text_split[1] is the company\nYou could also slice up the string using string sl...
[ 1, 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "web_scraping" ]
stackoverflow_0074213897_python_selenium_selenium_chromedriver_web_scraping.txt
Q: Python type hints and redefining method as async Say I have this code: class Foo: def say_hello(self) -> str: return "hello" class Bar(Foo): async def say_hello(self) -> str: return "hello" Bar is a derived class of Foo, and the method say_hello is not async in Foo, but async in Bar. I wo...
Python type hints and redefining method as async
Say I have this code: class Foo: def say_hello(self) -> str: return "hello" class Bar(Foo): async def say_hello(self) -> str: return "hello" Bar is a derived class of Foo, and the method say_hello is not async in Foo, but async in Bar. I would like to give them the same return type, but mypy g...
[ "TLDR: The annotations def -> and async def -> refer to different kinds of functions. In usual cases one cannot use the latter in place of the former, both from a runtime and typing perspective.\n\n\nPEP 484: Annotating generator functions and coroutines\nCoroutines introduced in PEP 492 are annotated with the same...
[ 0 ]
[]
[]
[ "mypy", "python", "type_hinting" ]
stackoverflow_0066532718_mypy_python_type_hinting.txt
Q: The precision of Decimal library in python From the documentation page of Decimal, I thought that once we use decimal to compute, it'll be a correct result without any floating error. But when I try this equation from decimal import Decimal, getcontext getcontext().prec = 250 a = Decimal('6') b = Decimal('500000'...
The precision of Decimal library in python
From the documentation page of Decimal, I thought that once we use decimal to compute, it'll be a correct result without any floating error. But when I try this equation from decimal import Decimal, getcontext getcontext().prec = 250 a = Decimal('6') b = Decimal('500000') b = a ** b print('prec: ' + str(getcontext()....
[ "If you're after very precise or symbolic math and/or being bitten by IEEE 754 float aliasing, check out SymPy\n>>> from sympy import log, N\n>>> expr = log(6**50000) / log(6)\n>>> N(expr)\n50000.0000000000\n\n", "The Documentation clearly show the parameters of getcontext()\n\nwhen you simply execute getcontext(...
[ 2, 2, 1 ]
[]
[]
[ "decimal", "precision", "python" ]
stackoverflow_0074217557_decimal_precision_python.txt
Q: How to create animated graphs with csv data in plotly? Create a line chart when you have the following csv data I want the points to move on that line graph according to time. TIME,CH1,CH2,CH3,CH4 01:39.1,988,988,992,988 01:39.1,988,988,992,988 01:39.1,988,992,988,992 01:39.2,988,988,992,992 01:39.2,988,992,988,98...
How to create animated graphs with csv data in plotly?
Create a line chart when you have the following csv data I want the points to move on that line graph according to time. TIME,CH1,CH2,CH3,CH4 01:39.1,988,988,992,988 01:39.1,988,988,992,988 01:39.1,988,992,988,992 01:39.2,988,988,992,992 01:39.2,988,992,988,988 01:39.2,988,988,992,988 01:39.2,988,992,988,988 01:39.2,98...
[ "Since I don't usually work with animations, I created an animation based on the examples in the reference, using a time axis. As for the intent of the question, I create the code from the understanding that I want to animate a graph drawn with two time points from the data presented.\nSince there are only two fram...
[ 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074212441_plotly_python.txt
Q: Lambdify-ing an expression with several variables using a single lambda x Imagine you have the following sympy expression: '1.0 * H * L * * 3 * W * *2' which contains the sp.Symbols variables=[H, L and W]. if this expression is lambdify-ed using sp.lambdify([sp.Symbol(vari) for vari in variables],'1.0 * H * L * * ...
Lambdify-ing an expression with several variables using a single lambda x
Imagine you have the following sympy expression: '1.0 * H * L * * 3 * W * *2' which contains the sp.Symbols variables=[H, L and W]. if this expression is lambdify-ed using sp.lambdify([sp.Symbol(vari) for vari in variables],'1.0 * H * L * * 3 * W * *2') you obtain a <function _lambdifygenerated(H, L, W)>. However, I n...
[ "You can preprocess the expression to replace all symbols with an IndexedBase, which you can think of as an array:\nfrom sympy import *\nL, H, W = symbols(\"L H W\")\nexpr = 1.0 * H * L**3 * W**2\n\nvariables = [L, H, W]\nx = IndexedBase(\"x\")\n# substitution dictionary\nd = {v: x[i] for i, v in enumerate(variable...
[ 0 ]
[]
[]
[ "lambda", "lambdify", "physics", "python", "sympy" ]
stackoverflow_0074215085_lambda_lambdify_physics_python_sympy.txt
Q: Unable to generate .pyd file using swig I am trying to implement the example given in swig. I am using windows 11 64-bit pc. It has 3 files I file /* File: example.i */ %module example %{ #define SWIG_FILE_WITH_INIT #include "example.h" %} int fact(int n); C file /* File: example.c */ #include "example.h" int...
Unable to generate .pyd file using swig
I am trying to implement the example given in swig. I am using windows 11 64-bit pc. It has 3 files I file /* File: example.i */ %module example %{ #define SWIG_FILE_WITH_INIT #include "example.h" %} int fact(int n); C file /* File: example.c */ #include "example.h" int fact(int n) { if (n < 0){ /* This should...
[ "My doubt was how to link the .lib file in g++. I thought g++ only links .a file. Also got confused by @Mathieu's answer here. A clear description for linking .lib is given here.\n\nYes, it is a linker error.\nThis is answered here.\nIn the command add -L followed by location of the python3XX.lib file in python ins...
[ 0 ]
[]
[]
[ "python", "swig" ]
stackoverflow_0074149739_python_swig.txt
Q: Returning average capacity from a list of product descriptions? Function Name: avg_capacity Parameter: product_list - A list containing a sequence of product descriptions as strings. Return: A floating point number that denotes the average of capacities as given in the list. Description: Given a list of product de...
Returning average capacity from a list of product descriptions?
Function Name: avg_capacity Parameter: product_list - A list containing a sequence of product descriptions as strings. Return: A floating point number that denotes the average of capacities as given in the list. Description: Given a list of product descriptions where each element in the list is of the format 'product_i...
[ "def avg_capacity(product_list: list[str]) -> float:\n capacities = [int(x.split(\"-\")[1]) for x in product_list]\n return sum(capacities) / len(capacities)\n\n", "There are a number of problems with your code:\n\nyou call product_list.split(\"-\"), but product_list is the list itself; you should call split on...
[ 2, 2, 0 ]
[]
[]
[ "list", "methods", "python" ]
stackoverflow_0074217784_list_methods_python.txt
Q: Click detection happening multiple times per click Whenever a user clicks on a point in the map, the click is registered more than once. Obviously this is not ideal as it could lead to multiple inputs not being registered the correct amount of times. I have a put a variable "clicked" in the logic, which works in o...
Click detection happening multiple times per click
Whenever a user clicks on a point in the map, the click is registered more than once. Obviously this is not ideal as it could lead to multiple inputs not being registered the correct amount of times. I have a put a variable "clicked" in the logic, which works in other programs, but here it does not work and it still re...
[ "Actually you don't detect clicks, but you detect when the mouse button is held down and the mouse hovers over a tile. Use the MOUSEBUTTONDOWN event to detect clicks (see Pygame mouse clicking detection). Note that if pygame.event.get() is called in multiple event loops, only one loop receives the events, but never...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074215069_pygame_python.txt
Q: What is the use of join() in threading? I was studying the python threading and came across join(). The author told that if thread is in daemon mode then i need to use join() so that thread can finish itself before main thread terminates. but I have also seen him using t.join() even though t was not daemon example...
What is the use of join() in threading?
I was studying the python threading and came across join(). The author told that if thread is in daemon mode then i need to use join() so that thread can finish itself before main thread terminates. but I have also seen him using t.join() even though t was not daemon example code is this import threading import time im...
[ "A somewhat clumsy ascii-art to demonstrate the mechanism:\nThe join() is presumably called by the main-thread. It could also be called by another thread, but would needlessly complicate the diagram.\njoin-calling should be placed in the track of the main-thread, but to express thread-relation and keep it as simple...
[ 380, 89, 53, 23, 12, 5, 5, 2, 1, 0, 0 ]
[ "\"What's the use of using join()?\" you say. Really, it's the same answer as \"what's the use of closing files, since python and the OS will close my file for me when my program exits?\".\nIt's simply a matter of good programming. You should join() your threads at the point in the code that the thread should not b...
[ -3 ]
[ "multithreading", "python", "python_multithreading" ]
stackoverflow_0015085348_multithreading_python_python_multithreading.txt
Q: tensorflow:Your input ran out of data I am working on a seq2seq keras/tensorflow 2.0 model. Every time the user inputs something, my model prints the response perfectly fine. However on the last line of each response I get this: You: WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure ...
tensorflow:Your input ran out of data
I am working on a seq2seq keras/tensorflow 2.0 model. Every time the user inputs something, my model prints the response perfectly fine. However on the last line of each response I get this: You: WARNING:tensorflow:Your input ran out of data; interrupting training. Make sure that your dataset or generator can generate...
[ "To make sure that you have \"at least steps_per_epoch * epochs batches\", set the steps_per_epoch to\nsteps_per_epoch = len(X_train)//batch_size\n\nvalidation_steps = len(X_test)//batch_size # if you have validation data \n\nYou can see the maximum number of batches that model.fit() can take by the progress bar wh...
[ 25, 5, 4, 3, 2, 1, 0, 0, 0 ]
[ "I understand that it is completely fine. Firstly. it is a warning not an error. Secondly, the situation is similar to one data is trained during one epoch, next epoch trains next data and you have set epochs value too high e.g.500 (assuming your data size is not fixed but will approximately be <=500). Suppose data...
[ -1, -3 ]
[ "deep_learning", "keras", "machine_learning", "python", "tensorflow" ]
stackoverflow_0059864408_deep_learning_keras_machine_learning_python_tensorflow.txt
Q: Transforming tuple to a desired structure Below is a tuple: import ast data = (('Jeff Celebration', '{"2010-09-02": {"Possibility": 3, "Confidence":93}, "2011-09-01": {"Possibility": 3, "Confidence":86}}'), ("Queens Bday", '{"2010-02-18": {"Possibility": 2, "Confidence":88}, "2011-02-17": {"Possibility": 2, ...
Transforming tuple to a desired structure
Below is a tuple: import ast data = (('Jeff Celebration', '{"2010-09-02": {"Possibility": 3, "Confidence":93}, "2011-09-01": {"Possibility": 3, "Confidence":86}}'), ("Queens Bday", '{"2010-02-18": {"Possibility": 2, "Confidence":88}, "2011-02-17": {"Possibility": 2, "Confidence":88}}')) This is where I am : data...
[ "You can use below code get the desired output\nimport ast\nfrom datetime import datetime, timedelta\n\ndata = (('Jeff Celebration',\n '{\"2010-09-02\": {\"Possibility\": 3, \"Confidence\":93}, \"2011-09-01\": {\"Possibility\": 3, \"Confidence\":86}}'),\n (\"Queens Bday\",\n '{\"2010-02-18\": {\"Possibility\": 2,...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074217643_python.txt
Q: how to write Hello Robin. You are currently left with 10 chocolates.? def main(): data = ("Robin", 10, "chocolates") format_string = None print(format_string %data) print("Hello %d.You are currently left with %s %d" %(data)) return 0 if __name__ == '__main__': main() i got runtime er...
how to write Hello Robin. You are currently left with 10 chocolates.?
def main(): data = ("Robin", 10, "chocolates") format_string = None print(format_string %data) print("Hello %d.You are currently left with %s %d" %(data)) return 0 if __name__ == '__main__': main() i got runtime error .how to solve this?.Actually i want to print " Hello Robin. Yo are curr...
[ "You can do it like this\ndef main():\n data = (\"Robin\", 10, \"chocolates\")\n print('\"Hello {}.You are currently left with {} {}\"'.format(*data))\n \n return 0\n\nif __name__ == '__main__':\n main()\n\n", "def main():\n data = (\"Robin\", 10, \"chocolates\")\n print(\"Hello %s.You are cu...
[ 0, 0, 0, 0 ]
[]
[]
[ "format", "python", "string" ]
stackoverflow_0074217308_format_python_string.txt
Q: Python : Requesting URL and returning JSON data to the script I'm trying to make something to request or even read the site, which gives information about the IP address and when I launch it, it gives me exceptions. I need to get the data from the site and store it as a variable in local script. I tried: def SCAN...
Python : Requesting URL and returning JSON data to the script
I'm trying to make something to request or even read the site, which gives information about the IP address and when I launch it, it gives me exceptions. I need to get the data from the site and store it as a variable in local script. I tried: def SCAN_IP_ADRESS(): while True: webURL = 'https://ip-api.com/...
[ "If you use this URL webURL = 'https://ip-api.com/' you'll get a 403 Response:\n\n{'status': 'fail', 'message': 'SSL unavailable for this endpoint, order a key at https://members.ip-api.com/'}\n\nLooks like a paid API. You'll need to sign up to get a key and use SSL on your HTTP request for authentication.\nIf you ...
[ 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0058248582_json_python.txt
Q: Query timestamp range using elasticsearch-dsl-py I have an elasticsearch range query that I'd like to translate into elasticsearch-dsl: Elasticsearch Python API {"range": {"@timestamp": {"gte": 1570258800000, "lte": 1571036400000, "format": "epoch_millis" } } } Ela...
Query timestamp range using elasticsearch-dsl-py
I have an elasticsearch range query that I'd like to translate into elasticsearch-dsl: Elasticsearch Python API {"range": {"@timestamp": {"gte": 1570258800000, "lte": 1571036400000, "format": "epoch_millis" } } } Elasticsearch-DSL-Py Query? from elasticsearch import Ela...
[ "Try this:\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Search\n\nclient = Elasticsearch(<connection_details>)\n\ns = Search(using=client, index=\"my-index\") \\\n .filter('range' , **{'@timestamp': {'gte': 1570258800000 , 'lt': 1571036400000, 'format' : 'epoch_millis'}})\n\n", "s =...
[ 6, 2, 0 ]
[]
[]
[ "elasticsearch", "elasticsearch_dsl", "elasticsearch_dsl_py", "python" ]
stackoverflow_0058453236_elasticsearch_elasticsearch_dsl_elasticsearch_dsl_py_python.txt
Q: Data loss when Python reads a 13mb file def get_txt(path): with open(path, 'r', encoding='utf-8') as file: while file.readline(): print(file.readline()) if __name__ == '__main__': path = 'data/data.html' get_txt(path) This is my code, which prints the data of the source file line ...
Data loss when Python reads a 13mb file
def get_txt(path): with open(path, 'r', encoding='utf-8') as file: while file.readline(): print(file.readline()) if __name__ == '__main__': path = 'data/data.html' get_txt(path) This is my code, which prints the data of the source file line by line, and prints it on the console, but wh...
[ " while file.readline():\n print(file.readline())\n\nThe while condition reads a line, and then the print() reads the next line and prints it.\nYou're only printing every other line.\nTry this instead:\nfor line in file:\n print(line)\n\n", "presumably\ndef get_txt(path):\n with open(path, 'r', en...
[ 3, 2, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074215954_python_python_3.x.txt
Q: struggling with python code in pearson revel chapter 2 I need some help with some python code. I am working on a college project with pearson revel python and I am having a hard time trying to find the problem with my code. Here is the code I have been using: user_cookies_input = float(input('Enter number of cooki...
struggling with python code in pearson revel chapter 2
I need some help with some python code. I am working on a college project with pearson revel python and I am having a hard time trying to find the problem with my code. Here is the code I have been using: user_cookies_input = float(input('Enter number of cookies: ')) cups_of_sugar = 1.5 cups_of_butter = 1.0 cups_of_fl...
[ "First of all to concatinate strings with integers/floats you need to convert the integer/float to a string. Second off all, this '.2f' from what I know only work's with f-strings. Anyways, I think a good habit is to use f-strings, they are extremely efficient and simple.\nprint(f\"You need {sugar_output:.2f} cups ...
[ 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0067613268_python.txt
Q: sqlite3.OperationalError: duplicate column name: timestamp I have a DF like so: timestamp open high low close volume trade_count vwap symbol 0 2021-11-02 13:30:00+00:00 12.000 12.055 12.00 12.0500 47208 62 12.003693 AMCR 1 2021-11-02 13:31:...
sqlite3.OperationalError: duplicate column name: timestamp
I have a DF like so: timestamp open high low close volume trade_count vwap symbol 0 2021-11-02 13:30:00+00:00 12.000 12.055 12.00 12.0500 47208 62 12.003693 AMCR 1 2021-11-02 13:31:00+00:00 12.040 12.070 12.04 12.0500 20448 117 1...
[ "The name of new_df index is timestamp.\nprint(new_df.index.name)\n\nAnd also there is a column name timestamp. Update the name of the index or update the column timestamp to a different value before running to_sql.\nnew_df.index.name = 'index' # for example\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074216034_numpy_pandas_python.txt
Q: Creating a numpy arrays of all possible combinations of elements I would like to creare a Numpy array, which consists of all possible combinations. I have a number of samples, which may have a set of possible values. Currently I use recursion, but am looking for faster methods to work with a high number of combina...
Creating a numpy arrays of all possible combinations of elements
I would like to creare a Numpy array, which consists of all possible combinations. I have a number of samples, which may have a set of possible values. Currently I use recursion, but am looking for faster methods to work with a high number of combinations. A possible number of combinations is (n of values)^samples impo...
[ "You can use itertools.product() for this:\nsamples = 3\nvalues = list(itertools.chain(range1, range2)) # all iterables\ntotal = [list(item) for item in itertools.product(*[values for _ in range(samples)])]\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python", "recursion" ]
stackoverflow_0074217975_numpy_python_recursion.txt
Q: Removing last line and initial whitespaces from an 8 by 8 list of integers in python #Print the user board s = '' for i in range(n): for j in range(n): z = i * n + j s += ' ' if z < 10: s += ' ' s += str(z) s += '\n' print(dedent(s)) queens = list(map(int, inp...
Removing last line and initial whitespaces from an 8 by 8 list of integers in python
#Print the user board s = '' for i in range(n): for j in range(n): z = i * n + j s += ' ' if z < 10: s += ' ' s += str(z) s += '\n' print(dedent(s)) queens = list(map(int, input("Queens: ").split())) I keep getting an error from my testcase environment of a last ...
[ "If you do not want the initial space, you'd better use join, which only adds the separator between consecutive items:\ns = '\\n'.join(' '.join('{:2d}'.format(i * n + j)\n for j in range(n))\n for i in range(n))\nprint(s)\n\ngives as expected:\n 0 1 2 3 4 5 6 7\n 8 9 10 11...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074218100_list_python.txt
Q: How to use Tkinter .after() method to delay a loop instead time.sleep()? I´m trying to create a simple thing: a loop with a delay of x seconds between iterations, triggered by a Tkinter button command. The obvious answer is to use time.sleep(), however, this actually freezes the mainloop process, avoiding other ev...
How to use Tkinter .after() method to delay a loop instead time.sleep()?
I´m trying to create a simple thing: a loop with a delay of x seconds between iterations, triggered by a Tkinter button command. The obvious answer is to use time.sleep(), however, this actually freezes the mainloop process, avoiding other events to be captured. I´ve searched and the recommendation is to use the tkinte...
[ "The basic concept is to write a function that does one iteration of the loop, and then schedules itself to run again in the future if some condition hasn't been met. To facilitate this you can initialize the loop counter as a keyword argument, and you can increase the value each time the function schedules itself ...
[ 2, 1 ]
[]
[]
[ "delay", "for_loop", "python", "time", "tkinter" ]
stackoverflow_0074214619_delay_for_loop_python_time_tkinter.txt
Q: How to sum dataframes in Pandas without getting NaN values? I have some dataframes I need to sum, but some of them have missing column. Unfortunately, the result will have NaN values for those columns, which were missing in some of the input dataframes. How to keep the original values for those columns? Here is a ...
How to sum dataframes in Pandas without getting NaN values?
I have some dataframes I need to sum, but some of them have missing column. Unfortunately, the result will have NaN values for those columns, which were missing in some of the input dataframes. How to keep the original values for those columns? Here is a small code: #!/usr/bin/env ipython # --------------------- import...
[ "Use DataFrame.add:\ndfc = dfa.add(dfb, fill_value=0)\n\nprint (dfc)\n A B C\nyears \n2010 0.986393 0.020584 0.607545\n2011 1.090208 0.969910 0.170524\n2012 1.024139 0.832443 0.065052\n2013 0.965020 0.212339 0.948886\n2014 0.612089 0.18182...
[ 5, 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074218192_pandas_python.txt
Q: problem with moving files with extensions with shutil I have the following code that should move files from one directory to another, the problem is when I run the code it just creates the folder and not moving any file to it. can anyone help me with that? import os import glob import shutil def remove_ext(list_o...
problem with moving files with extensions with shutil
I have the following code that should move files from one directory to another, the problem is when I run the code it just creates the folder and not moving any file to it. can anyone help me with that? import os import glob import shutil def remove_ext(list_of_pathnames): return [os.path.splitext(filename)[0] for fi...
[ "You first use \".jpeg\" as extension but then when you move mistakenly use \".jpg\".\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074218361_python.txt
Q: 'NoneType' object has no attribute 'get' while serving with Waitress I know there have been posts about this issue before but reading them I am still unable to find a solution. The weird part about this is my app has been working fine for weeks and then I reset my server and I keep getting this error. I am using W...
'NoneType' object has no attribute 'get' while serving with Waitress
I know there have been posts about this issue before but reading them I am still unable to find a solution. The weird part about this is my app has been working fine for weeks and then I reset my server and I keep getting this error. I am using Waitress to serve an app that deals with webhooks. @app.route(f'/outbound',...
[ "data dictionary doesn't have key payload or data['payload'] is might be None.\nIf the data dictionary doesn't have the key payload, then can silently avoid errors like this,\nto_ = data.get('payload', {}).get('to')\n\nOr a safer option will be\npayload = data.get('payload')\nif payload:\n to_ = payload.get('to'...
[ 0, 0, 0 ]
[]
[]
[ "flask", "python", "waitress" ]
stackoverflow_0074217809_flask_python_waitress.txt