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: Sorting counting catergories bars in barchart for the same x I'm using the same code to plot the same data, but in one plot they have a label, and in the other, other labels, based on specular conditions. Even though I'm using the same code, the color and the arrangement of bars is different, leading me in total c...
Sorting counting catergories bars in barchart for the same x
I'm using the same code to plot the same data, but in one plot they have a label, and in the other, other labels, based on specular conditions. Even though I'm using the same code, the color and the arrangement of bars is different, leading me in total confusion. How can I recolor and resort for consistency? Each dat...
[ "In the sns.barplot() code change the palette from deep to:\npalette = ['tab:blue', 'tab:red', 'tab:green']\n\nsns.barplot(data = df, x = 'seller', y = 'count', hue = 'label', palette = ['tab:blue', 'tab:red', 'tab:green'], hue_order=['A', 'B', 'C'])\\\n .set(title='Distribution of A / B / C score am...
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "plot", "python", "seaborn" ]
stackoverflow_0074251830_matplotlib_pandas_plot_python_seaborn.txt
Q: How to calculate the values of child-tables by using ForeignKey from a parent-table My purpose is to gain averages of values stored in child-tables depending on each parent-table. In my case, I want to gain averages of satisfaction stored in the Evaluation model (child) depending on each Professor model (parent). ...
How to calculate the values of child-tables by using ForeignKey from a parent-table
My purpose is to gain averages of values stored in child-tables depending on each parent-table. In my case, I want to gain averages of satisfaction stored in the Evaluation model (child) depending on each Professor model (parent). models.py class Professor(models.Model): college = models.CharField(max_length=50, ch...
[ "If you want to use only average data of relevant professor in detail page, you can filter like:\ndef get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n prof_list = Professor.objects.annotate(avg_satisfaction=Avg(\"evaluation_names__satisfaction\"))\n contex...
[ 1, 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0074251481_django_postgresql_python.txt
Q: Checking for a palindrome, using for-loop in Python and print output ONLY ONCE I am fairly new to programming, so I hope you can help me. I want to check if a input string is a palindrome. The palindrome-checker is case-insensitive. Here is what I got so far: # input word word = input("Enter a word: ") # make it...
Checking for a palindrome, using for-loop in Python and print output ONLY ONCE
I am fairly new to programming, so I hope you can help me. I want to check if a input string is a palindrome. The palindrome-checker is case-insensitive. Here is what I got so far: # input word word = input("Enter a word: ") # make it case-INsensitive word = word.lower() # we also need the length of word to iterate ...
[ "You just need to check the word against it's reverse:\n# input word \nword = input(\"Enter a word: \")\n\n# make it case-INsensitive\nword = word.lower()\n\n# check word against it's reverse\nif word == word[::-1]:\n print(word, \"is a palindrome\")\nelse:\n print(word, \"is not a palindrome\")\n\n", "The ...
[ 4, 1, 0 ]
[]
[]
[ "for_loop", "palindrome", "python" ]
stackoverflow_0074252349_for_loop_palindrome_python.txt
Q: Is it possible to use Tabula-Py on Portable IDE I am new to python and am working on setting up some automation for my job in python and part of that is pulling data from tables in pdf files. Short version is that no matter how I try and what I have looked up I cannot get Tabula-Py to look at the path to java on m...
Is it possible to use Tabula-Py on Portable IDE
I am new to python and am working on setting up some automation for my job in python and part of that is pulling data from tables in pdf files. Short version is that no matter how I try and what I have looked up I cannot get Tabula-Py to look at the path to java on my portable drive. I am using a portable IDE set-up si...
[ "I had the same issue, and the solution I found is by using portable Java and registering it in the user environment path.\nThis explains how to install java from the EXE installer https://stackoverflow.com/a/6571736/11322275\nThen, register where you saved the java folder to the user environment path as explained ...
[ 0 ]
[]
[]
[ "java", "python", "python_3.x", "spyder", "tabula_py" ]
stackoverflow_0071542110_java_python_python_3.x_spyder_tabula_py.txt
Q: Can't open User model using mongo db I'm using mongo db in my django project. Whenever I try to open a record of User model in django admin, it gives me this error All the other models are working fine. But getting problem in User model and my user model is A: MongoDB doesn't contain the None type. Instead of N...
Can't open User model using mongo db
I'm using mongo db in my django project. Whenever I try to open a record of User model in django admin, it gives me this error All the other models are working fine. But getting problem in User model and my user model is
[ "MongoDB doesn't contain the None type. Instead of None fill with null value or use pymongo.\nThis link may resolve your problem Writing null value to MongoDB\n" ]
[ 0 ]
[]
[]
[ "django", "djongo", "mongodb", "python" ]
stackoverflow_0074250977_django_djongo_mongodb_python.txt
Q: Create an incremental serial no for filtered rows in pandas dataframe Can you please help me change my code from current output to expected output? I am using apply() function of dataframe. It would be great if it could also be done more efficiently using vector operation. Current output: col1 col2 serialno 0 ...
Create an incremental serial no for filtered rows in pandas dataframe
Can you please help me change my code from current output to expected output? I am using apply() function of dataframe. It would be great if it could also be done more efficiently using vector operation. Current output: col1 col2 serialno 0 100 0 4 1 100 100 0 2 100 100 0 3 200 100 ...
[ "You can try this\nimport itertools\nstart = 4\ncounter = itertools.count(start) # to have incremental counter\n\ndf[\"serialno\"] = [start if (x[\"col1\"]==x[\"col2\"] or (start:=next(counter))) else start for _, x in df.iterrows()]\n\nThis if condition will be executed in two manner: if col1 and col2 have same va...
[ 1, 1, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074250532_dataframe_pandas_python.txt
Q: How to kill multiprocess with selenium chrome driver I'm terminating multiprocess thread after certain period and when I terminate it won't kill the chromedriver. This is a sample of the code (kept it simple): def start_thread(url): driver = webdriver.Chrome() driver.get(url) urls=[] threads=[] for counte...
How to kill multiprocess with selenium chrome driver
I'm terminating multiprocess thread after certain period and when I terminate it won't kill the chromedriver. This is a sample of the code (kept it simple): def start_thread(url): driver = webdriver.Chrome() driver.get(url) urls=[] threads=[] for counter in range(urls): thread = multiprocessing.Process( ta...
[ "because ways to hijack the session from children seem to no-longer work, you are stuck with having to manually kill chrome and the webdriver and all its children using psutils, until they put sessions hijacking into the webdrivers.\nimport time\nimport multiprocessing\nfrom selenium import webdriver\nimport psutil...
[ 2 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074252311_python_selenium_selenium_chromedriver.txt
Q: Create a folder and get its path after that using python I am trying to create a folder inside of a selected folder, name it after the date of creation and get an absolute path of this newely created folder. My code is down below: today = datetime.now() dateAndTime = today.strftime("%m-%d-%Y") workingdir = os.path...
Create a folder and get its path after that using python
I am trying to create a folder inside of a selected folder, name it after the date of creation and get an absolute path of this newely created folder. My code is down below: today = datetime.now() dateAndTime = today.strftime("%m-%d-%Y") workingdir = os.path.dirname(os.mkdir(delovnaMapa + "/" + dateAndTime)) print(work...
[ "os.mkdir function creates a directory, its return is None.\nFor your work to be done, you should be using\nos.mkdir(delovnaMapa + \"/\" + dateAndTime)\nthen, use\nos.path.dirname(delovnaMapa + \"/\" + dateAndTime)\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074252604_python.txt
Q: Counting dictionary items in a column I have a dictionary billable = {'nonop' : [99221, 99234, 99238, 99252, 99253, 99254, 99255, 99282, 99283, 99284, 99285, 99239, 99222, 99223, 99218, 99219, 99220, 99217, 99235], 'rounding' : [99231, 99232 ,99233, 99225, 99226], 'clinic' : [99243, ...
Counting dictionary items in a column
I have a dictionary billable = {'nonop' : [99221, 99234, 99238, 99252, 99253, 99254, 99255, 99282, 99283, 99284, 99285, 99239, 99222, 99223, 99218, 99219, 99220, 99217, 99235], 'rounding' : [99231, 99232 ,99233, 99225, 99226], 'clinic' : [99243, 99211 ,99215, 99213, 99214, 99212 ,99205, 9...
[ "IIUC, this is one way about it\n# list of the values\nnoop=[99221, 99234]\n\n# using loc, filter CPT id preset in the list, and take value count\ndf.loc[df['CPT'].isin(noop)]['CPT'] .value_counts()\n\n\n\n99234 1\nName: CPT, dtype: int64\n\n", "Here is one way to do it.\ndf = pd.DataFrame(cpt_data)\ndf['label...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074249403_dictionary_pandas_python.txt
Q: can only join an iterable error on shell scrapy on python scraping I have a simply code for scrapy but i got an error when there is None, see my code below, how can fix it In [428]: ''.join(response.css(".prdd-price-first::text").get()).strip() TypeError: can only join an iterable A: Iterable means your express...
can only join an iterable error on shell scrapy on python scraping
I have a simply code for scrapy but i got an error when there is None, see my code below, how can fix it In [428]: ''.join(response.css(".prdd-price-first::text").get()).strip() TypeError: can only join an iterable
[ "Iterable means your expression to be a list. So you can do something like:\n''.join([ x.get().strip() for x in response.css(\".prdd-price-first::text\")])\n\n" ]
[ 0 ]
[]
[]
[ "error_handling", "iterable", "python", "scrapy" ]
stackoverflow_0074252191_error_handling_iterable_python_scrapy.txt
Q: Converting a large txt file into a python dictionary I got a text file that I need to convert into a python dictionary to work with, the text file looks essentially like this 100 Base VG AnyLan Se basa en el protocolo de prioridad por demanda, se aplica a todo tipo de cableado del tipo ethernet o tokenring. 100BA...
Converting a large txt file into a python dictionary
I got a text file that I need to convert into a python dictionary to work with, the text file looks essentially like this 100 Base VG AnyLan Se basa en el protocolo de prioridad por demanda, se aplica a todo tipo de cableado del tipo ethernet o tokenring. 100BASE-T Especificación Gigabit Ethernet que emplea UTP Cat5, ...
[ "You could apply a very simple heuristic to distinguish between \"words\" and \"definitions\": every line below 20 characters is a \"word\", anything else is part of the definition.\nGo over each line and if it matches the heuristic, store that as key and put it into the dict. Any other line is appended to the valu...
[ 0 ]
[]
[]
[ "dictionary", "file", "key", "python" ]
stackoverflow_0074231112_dictionary_file_key_python.txt
Q: How to find index in text of the last thing in list I have an assignment and I'm stuck, I would appreciate help, thanks. this is the assignment: What is the longest period of uninterrupted days that had no temperatures above 0◦C (i.e. maximum temperature below 0◦C)? What was the date of the last day of this period...
How to find index in text of the last thing in list
I have an assignment and I'm stuck, I would appreciate help, thanks. this is the assignment: What is the longest period of uninterrupted days that had no temperatures above 0◦C (i.e. maximum temperature below 0◦C)? What was the date of the last day of this period of time? Write a function named get_longest_freezing() ...
[]
[]
[ "input1 = str(input())\n\nlist1 = input1.split()\n\nfor i in range(len(list1)):\n list1[i] = int(list1[i])\n\n\nfor j in range(len(list1)):\n if list1[j] < 0:\n list1.pop(j)\n\nprint(list1)\n\n" ]
[ -1 ]
[ "loops", "python" ]
stackoverflow_0074252703_loops_python.txt
Q: Removing whitespace from config without installing any packages I have a config file that sets the port for the HTTP to run, I would like to allow/replace whitespaces around the equal sign to allow the code to run normally but have no idea how to program it. Due to me sending this code to someone else and wanting ...
Removing whitespace from config without installing any packages
I have a config file that sets the port for the HTTP to run, I would like to allow/replace whitespaces around the equal sign to allow the code to run normally but have no idea how to program it. Due to me sending this code to someone else and wanting to use virtualenv I don't want to install any packages but fix this w...
[ "Based on your code example above (and with some assumptions made):\nport = None\nwith open('example.conf', 'r') as file:\n lines = file.readlines()\n for line in lines:\n if \"port =\" in line:\n port = line.split(\"=\")[1].strip()\n break\nif port:\n print(port)\nelse:\n p...
[ 0 ]
[]
[]
[ "config", "html", "python" ]
stackoverflow_0074246881_config_html_python.txt
Q: How do I read a csv file from google drive folder using python, without downloading it I need to read a csv file which is present in google drive folder using python, I do not want to download or change it into a different format, is there any way I could get the csv file url to read the file? I can see there is n...
How do I read a csv file from google drive folder using python, without downloading it
I need to read a csv file which is present in google drive folder using python, I do not want to download or change it into a different format, is there any way I could get the csv file url to read the file? I can see there is no csv file url in google drive
[ "If its a CSV file i would recommend converting it to a google sheets file then you can just update it via the Google sheets api.\nYou cant write directly to a file on google drive without downloading it first. I have done something like what you are looking for in C# How to upload to Google Drive API from memory ...
[ 0 ]
[]
[]
[ "google_drive_api", "pandas", "python" ]
stackoverflow_0074252633_google_drive_api_pandas_python.txt
Q: I wanted to make a sudoku an check if it is a valid one Does any body have an idea why my valid, or doubles methods don't want to work? First I make a new 9x9 sudoku with al positions None. afterwards with the method doubles i check whether there are any duplicates in a row, if so I return True. A last if check w...
I wanted to make a sudoku an check if it is a valid one
Does any body have an idea why my valid, or doubles methods don't want to work? First I make a new 9x9 sudoku with al positions None. afterwards with the method doubles i check whether there are any duplicates in a row, if so I return True. A last if check with the method valid if the row and columns are valid, if so ...
[ "There are three issues in the code you have written:\n\nmake_sudoku only creates one row, and adds that same row 9 times to sudoku. That means you have 9 references to the same row. That's not what you want. You want 9 separate rows. So in each iteration of the loop a new row must be created. You can for instance ...
[ 1 ]
[]
[]
[ "python", "sudoku" ]
stackoverflow_0074252476_python_sudoku.txt
Q: How to solve error '[True] not in index' and add the result in the document? I have no errors in this piece of code df2 = df[["match","hteam_name", "ateam_name", "price_oh", "price_oa", "bookmaker_name"]].reset_index(drop=True) df2 and this is the result ( I can't upload pictures because I still can't upload my ...
How to solve error '[True] not in index' and add the result in the document?
I have no errors in this piece of code df2 = df[["match","hteam_name", "ateam_name", "price_oh", "price_oa", "bookmaker_name"]].reset_index(drop=True) df2 and this is the result ( I can't upload pictures because I still can't upload my reputation but the result is like a spreadsheet with the name of each column and t...
[ "In your example \"price_oh\" != 0.00 is evaluated to True because it only compares the string price_oh to 0. If you want to filter on one of the series in your dataframe, you have to do it in a different way. For example, using .loc (doc: pd.DataFrame.loc). Try this:\ndf2 = df.loc[df[\"price_oh\"] != 0.00, [\"matc...
[ 0 ]
[]
[]
[ "csv", "dataframe", "python" ]
stackoverflow_0074252751_csv_dataframe_python.txt
Q: To count and display “No. of times” of presence of words “the” and “to” in a string. (should not count words like these and top) Problem Detail I am stuck in this... I can calculate the number of times "the" and "to" will occur by using the count function but it will also include the occurrence in these and top wh...
To count and display “No. of times” of presence of words “the” and “to” in a string. (should not count words like these and top)
Problem Detail I am stuck in this... I can calculate the number of times "the" and "to" will occur by using the count function but it will also include the occurrence in these and top which is not needed so how should I approach this question? I only know basic operators, Loops, Str Functions, etc What I Tried I though...
[ "You want the number of occurrences of 'the' and 'to' in a string if I understood correctly.\n\n#input\ns = \"These To The Top\"\n\n#split the string when space occurs -> s = [\"These\",\"To\",\"The\",\"Top\"]\n\nt = list(s.split(\" \"))\n\n#filter when it equals to \"The\" or \"To\"\nq = filter(lambda x:x == \"The...
[ 1 ]
[]
[]
[ "count", "loops", "python", "string" ]
stackoverflow_0074248078_count_loops_python_string.txt
Q: How to print only one list element where list is value in key:value pair I'm really new to the world of python, and especially dictionaries, so it is very likely that the answer to my question is quite simple, but I really can't figure it out... My problem is, that I can't seem to figure out how to access one spec...
How to print only one list element where list is value in key:value pair
I'm really new to the world of python, and especially dictionaries, so it is very likely that the answer to my question is quite simple, but I really can't figure it out... My problem is, that I can't seem to figure out how to access one specific list element at a certain position when I have a dictionary that has a li...
[ "First, you need to sort the dictionary according the name of the author. Then iterate over the sorted keys and print the required parameters in formatted fashion. For example:\nmy_books = {\n \"Eragon\": [2007, \"Paolin\"],\n \"Harry Potter\": [1992, \"Rowling\"],\n \"Obscura\": [2017, \"Canon\"],\n \"...
[ 3, 0, 0 ]
[]
[]
[ "dictionary", "key", "list", "python" ]
stackoverflow_0074252649_dictionary_key_list_python.txt
Q: Copy the link, once click on a button - selenium python There is a button on the page that when I clicked copies a link. check the below image I'm trying to store that link in a variable with python selenium this way: surl=ii.find_element(By.XPATH, f'/html/body/div[1]/div[2]/div[5]/div[1]/div/div/div/section/div/...
Copy the link, once click on a button - selenium python
There is a button on the page that when I clicked copies a link. check the below image I'm trying to store that link in a variable with python selenium this way: surl=ii.find_element(By.XPATH, f'/html/body/div[1]/div[2]/div[5]/div[1]/div/div/div/section/div/div[2]/div/div[2]/div[1]/div/div/div/div[3]/div[2]/table/tbod...
[ "By clicking that button the link is copied to the clipboard.\nThere are several ways to get the text content from clipboard with Python. For example try this:\nfrom tkinter import Tk\n\nsurl=ii.find_element(By.XPATH, f'/html/body/div[1]/div[2]/div[5]/div[1]/div/div/div/section/div/div[2]/div/div[2]/div[1]/div/div/...
[ 1 ]
[]
[]
[ "clipboard", "python", "python_3.x", "selenium", "selenium_webdriver" ]
stackoverflow_0074252749_clipboard_python_python_3.x_selenium_selenium_webdriver.txt
Q: How to test a statement for KeyboardInterrupt in PyTest? Suppose I have a function in my main file like this: # main.py import time def little_sleep(num): time.sleep(float(f'0.{i}')) def wait(): i = 0 while True: try: little_sleep(i) except KeyboardInterrupt: pr...
How to test a statement for KeyboardInterrupt in PyTest?
Suppose I have a function in my main file like this: # main.py import time def little_sleep(num): time.sleep(float(f'0.{i}')) def wait(): i = 0 while True: try: little_sleep(i) except KeyboardInterrupt: print("Uh Oh!! You really got me there, I guess I'll just have t...
[ "You could mock little_sleep using MagicMock and its side_effect property so that it raises KeyboardInterrupt exception:\nimport unittest.mock\nimport main\n\ndef test_wait(capfd):\n unittest.mock.MagicMock('main.little_sleep', side_effect=KeyboardInterrupt)\n main.wait()\n\n captured = capfd.readouterr()\...
[ 0, 0 ]
[]
[]
[ "exception", "keyboardinterrupt", "process", "pytest", "python" ]
stackoverflow_0072670796_exception_keyboardinterrupt_process_pytest_python.txt
Q: Get value of x-value from max y-value - python I'm trying to get extract the x-value from the maximum y-value in python. This is what I've got so far: # reading Hanford and Livingston signals # read hanford measurement h1_name, h1_start_time, h1_strain = read_data(join(path, "H-H1_LOSC_4_V2-1126259446-32.hdf5")) ...
Get value of x-value from max y-value - python
I'm trying to get extract the x-value from the maximum y-value in python. This is what I've got so far: # reading Hanford and Livingston signals # read hanford measurement h1_name, h1_start_time, h1_strain = read_data(join(path, "H-H1_LOSC_4_V2-1126259446-32.hdf5")) # read livingston measurement l1_name, l1_start_time...
[ "You can use\nmy_list.index(max(my_list))\n\nwhich would return the x-value of the maximum y-value.\nIf you have multiple x-values with the same y-value, then the first x-value on the timescale will be returned.\nIn what sense doesn't it work for you?\n", "I figured it out, I used the numpy.where function:\n# Fin...
[ 0, 0 ]
[]
[]
[ "indexing", "max", "mean", "python" ]
stackoverflow_0074235558_indexing_max_mean_python.txt
Q: Get Choice Description in queryset.value_list django I have a model and within it I have IntegerChoice Class (Gender) When I get field value with values_list() I don't want to get value as a number (1 or 2) but as a label string (Female or Male) models.py: class Policy(models.Model): class Gender(models.Intege...
Get Choice Description in queryset.value_list django
I have a model and within it I have IntegerChoice Class (Gender) When I get field value with values_list() I don't want to get value as a number (1 or 2) but as a label string (Female or Male) models.py: class Policy(models.Model): class Gender(models.IntegerChoices): MALE = 1, _("Male") FEMALE = 2,...
[ "Please don't use .values_list(…) [Django-doc], it erodes the \"model layer\", and as a result, you can indeed no longer obtain the text. I wrote an article [Django-antipatterns] that discusses the main problem(s) with this.\nYou do this with the .get_fieldname_display(…) method [Django-doc], so here get_gender_dis...
[ 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0074252790_django_django_models_django_queryset_python.txt
Q: Tkinter problem with structure of tabulate table in tkinter label I'm currently trying to print a table of data gathered from a database onto a GUI in tkinter, at the moment I'm using tabulate which runs fine in console, but as soon as I try to set the table as text as print as a label the table skews and the valu...
Tkinter problem with structure of tabulate table in tkinter label
I'm currently trying to print a table of data gathered from a database onto a GUI in tkinter, at the moment I'm using tabulate which runs fine in console, but as soon as I try to set the table as text as print as a label the table skews and the values are not aligned. I am still new to tkinter and so my code is by far ...
[ "I would highly recommend creating a grid of tk.Entry widgets where you place your headers and values in discrete entries. If you recorded the tk.Entry widget objects in a list you would be able to call on them individually outside of the loop if you preferred that. You could substitute the tk.Label widget in the p...
[ 0, 0 ]
[]
[]
[ "python", "tabulate", "tkinter" ]
stackoverflow_0054506925_python_tabulate_tkinter.txt
Q: Disable auto wrap long line in Visual Studio Code I use Visual Studio Code to write Python code with Pylint. When I press Ctrl + S (save), the editor wraps a long line into multiple short lines. How do I disable the action or configure wrap column count to 120 (default is 80)? I have tried "python.linting.pylintA...
Disable auto wrap long line in Visual Studio Code
I use Visual Studio Code to write Python code with Pylint. When I press Ctrl + S (save), the editor wraps a long line into multiple short lines. How do I disable the action or configure wrap column count to 120 (default is 80)? I have tried "python.linting.pylintArgs": ["--max-line-length=120"] and "editor.wordWrapCol...
[ "Check your Python formatting provider.\n\"python.formatting.provider\": \"autopep8\"\n\nI guess in your case it is not Pylint which keeps wrapping the long lines, but autopep8. Try setting --max-line-length for autopep8 instead.\n\"python.formatting.autopep8Args\": [\n \"--max-line-length=200\"\n]\n\n", "When...
[ 267, 9, 1, 0 ]
[ "Autopep8 requires --aggressive in order to recommend non-whitespace changes:\n\"python.linting.pylintArgs\": [\"--max-line-length\", \"120\", \"--aggressive\"]\n\nThis will wrap the long lines for you.\n" ]
[ -1 ]
[ "pylint", "python", "visual_studio_code" ]
stackoverflow_0047406741_pylint_python_visual_studio_code.txt
Q: Adding a column in a dataframe doing different operation for different rows of existing column FOOD_ID SAMPLE_NO ELEMENT1 ELEMENT2 ELEMENT3 F110 A1 0.4 0.2 0.1 F110 A2 0.6 0.1 0.3 F110 B1 0.4 0.3 0.7 F110 B2 ...
Adding a column in a dataframe doing different operation for different rows of existing column
FOOD_ID SAMPLE_NO ELEMENT1 ELEMENT2 ELEMENT3 F110 A1 0.4 0.2 0.1 F110 A2 0.6 0.1 0.3 F110 B1 0.4 0.3 0.7 F110 B2 0.5 0.6 0.9 F110 C1 0.5 0.3 0.4 F110 C2 ...
[ "def function1(dd:pd.DataFrame):\n return dd.query(\"SAMPLE_NO.str.contains('C')\").mean() if len(dd.query(\"SAMPLE_NO.str.contains('C')\"))>0 else dd.query(\"SAMPLE_NO.str.contains('B')\").iloc[-1,2:]\n\ndf1.groupby('FOOD_ID').apply(function1).rename(columns=lambda ss:f'{ss}_AVG')\n\n ELEMENT1_AVG ELEMEN...
[ 1, 0 ]
[]
[]
[ "dataframe", "duplicates", "mean", "pandas", "python" ]
stackoverflow_0059745642_dataframe_duplicates_mean_pandas_python.txt
Q: CodeEval Hard Challenge 6 - LONGEST COMMON SUBSEQUENCE - python I am trying to solve the Longest Common Subsequence in Python. I've completed it and it's working fine although I've submitted it and it says it's 50% partially completed. I'm not sure what I'm missing here, any help is appreciated. CHALLENGE DESCRIP...
CodeEval Hard Challenge 6 - LONGEST COMMON SUBSEQUENCE - python
I am trying to solve the Longest Common Subsequence in Python. I've completed it and it's working fine although I've submitted it and it says it's 50% partially completed. I'm not sure what I'm missing here, any help is appreciated. CHALLENGE DESCRIPTION: You are given two sequences. Write a program to determine the l...
[ "The following solution prints unordered/unsorted longest common subsequences/substrings from semi-colon-separated string pairs. If a string from the pair is longer than 50 characters, then the pair is skipped (its not difficult to trim it to length 50 if that is desired). \nNote: if sorting/ordering is desired it ...
[ 0, 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0033840661_python_python_2.7.txt
Q: Sort a DataFrame column based on duplicates in another column I have a dataframe like the following one : 'A' 'B' 'C' 'D' 1 4 1 'af23' 'z' 2 4 3 'bf14' 'y' 3 4 2 'bf14' 'x' 4 6 4 'cf51' 'w' 5 6 5 'ch63' '...
Sort a DataFrame column based on duplicates in another column
I have a dataframe like the following one : 'A' 'B' 'C' 'D' 1 4 1 'af23' 'z' 2 4 3 'bf14' 'y' 3 4 2 'bf14' 'x' 4 6 4 'cf51' 'w' 5 6 5 'ch63' 'v' 6 5 6 'cm79' 'u' When I sort using the follow...
[ "use:\ndf=df.sort_values(by=['A', 'C','D']).reset_index(drop=True)\nprint(df)\n'''\n A B C D\n0 4 1 af23 z\n1 4 2 bf14 x\n2 4 3 bf14 y\n3 5 6 cm79 u\n4 6 4 cf51 w\n5 6 5 ch63 v\n\n\n'''\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074252660_dataframe_pandas_python.txt
Q: How can I prevent os.system from causing "ATTENTION: default value of option mesa_glthread overridden by environment"? When I run... os.system("firefox --private-window https://www.example.com") I get this message in my terminal... ATTENTION: default value of option mesa_glthread overridden by environment. ...wh...
How can I prevent os.system from causing "ATTENTION: default value of option mesa_glthread overridden by environment"?
When I run... os.system("firefox --private-window https://www.example.com") I get this message in my terminal... ATTENTION: default value of option mesa_glthread overridden by environment. ...which seems to prevent the rest of my script from operating properly. I have read that many developers seem to try to avoid us...
[ "The message:\nATTENTION: default value of option mesa_glthread overridden by environment.\ncomes from the mesa library because firefox overrides its default.\nSee this report bug at mozilla.org\nI wonder if this prevents your script to run properly. In contrast, using os.system should block the script as os.system...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074200928_python.txt
Q: Scraping a website by using Beautiful Soup in Python I am trying to scrape the website https://www.eu-startups.com/directory/wpbdp_category/austrian-startups, to get the listed information for austrian startups. The information I would like to scrape is per startup: where is it based, the tags listed and the found...
Scraping a website by using Beautiful Soup in Python
I am trying to scrape the website https://www.eu-startups.com/directory/wpbdp_category/austrian-startups, to get the listed information for austrian startups. The information I would like to scrape is per startup: where is it based, the tags listed and the foundation date. I am using Beautiful soup, but I have no idea ...
[ "Try:\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.eu-startups.com/directory/wpbdp_category/austrian-startups/page/1/\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\nfor l in soup.select(\".wpbdp-listing\"):\n title = l.a.text\n based = l.select_one(\"span:-s...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074252870_beautifulsoup_python_web_scraping.txt
Q: Unpack requires a buffer of xx bytes I am trying to read three binary files from command line and those binary files contain like a line of a binary format like an example b'\n\x00\x00\x00PythonPool\x00@\x1cE' but sometimes when I try different types of binary formats it print's out different errors but most usual...
Unpack requires a buffer of xx bytes
I am trying to read three binary files from command line and those binary files contain like a line of a binary format like an example b'\n\x00\x00\x00PythonPool\x00@\x1cE' but sometimes when I try different types of binary formats it print's out different errors but most usually that "Unpack requires a buffer of xx by...
[ "If you open your file as a text file, you are indicating you want to treat it as lines of text which are terminated by linefeeds (the byte 10) or carriage returns (the byte 13), or both.\nIf you open your file as binary, your are treating it as arbitrary binary data - like the bytes of an image, or a compressed zi...
[ 0 ]
[]
[]
[ "binary", "pack", "python", "struct", "unpack" ]
stackoverflow_0074252390_binary_pack_python_struct_unpack.txt
Q: How can I speed the function on element-wise on two 2D array? Assume I have a function that is defined for two float values, and this function is rather complex that is not easy to be modified. Now I have two same 2D arrays, say $X_{n \times m}, Y_{n \times m}$, I need to carry out the function on each element on ...
How can I speed the function on element-wise on two 2D array?
Assume I have a function that is defined for two float values, and this function is rather complex that is not easy to be modified. Now I have two same 2D arrays, say $X_{n \times m}, Y_{n \times m}$, I need to carry out the function on each element on the 2D array $x_{ij}, y_{ij}$. How can I speed this work with respe...
[ "Methods\n\n\n\nUsing numpy vectorize\n\n\n\n\nUsing Numpy functions\n\n\n\nMethod 1--Numpy Vectorize\nProvides 4X speed up (3.14 ms vs. 12.1 ms)\n%%timeit\n\nZ = np.zeros((100, 100))\nfor i in range(100):\n for j in range(100):\n z = func(X[i, j], Y[i, j])\n Z[i, j] = z\n\n12.2 ms ± 901 µs per loop ...
[ 0, 0 ]
[]
[]
[ "performance", "python", "python_3.x", "vectorization" ]
stackoverflow_0074252868_performance_python_python_3.x_vectorization.txt
Q: how to read a specific key press from a specific device in python is there any way to read a keyboard key from a specific keyboard device in python? i basically want to make a app like HID macros using python. if not possible please show me if there are any alternatives.
how to read a specific key press from a specific device in python
is there any way to read a keyboard key from a specific keyboard device in python? i basically want to make a app like HID macros using python. if not possible please show me if there are any alternatives.
[]
[]
[ "ok so i forgot that i should run HID macros as an administrator.\n" ]
[ -1 ]
[ "hid", "python" ]
stackoverflow_0074252881_hid_python.txt
Q: Python rounding numpy array entries down to the nearest whole number. How can I fix this? Bear with me as I'm not very experienced with coding, but an example of my problem is as follows: I define a matrix V as below and then attempt to scale the first row by a factor equal to the first entry in V: V=np.array([[3,...
Python rounding numpy array entries down to the nearest whole number. How can I fix this?
Bear with me as I'm not very experienced with coding, but an example of my problem is as follows: I define a matrix V as below and then attempt to scale the first row by a factor equal to the first entry in V: V=np.array([[3,1],[1,3]]) V[0]=V[0]/V[0,0] print(V) Output: [[1 0] [1 3]] For some reason, Python has round...
[ "This is because your numpy array is int. ALL elements in the numpy array must be the same type. So when you multiply by a float your array, the array remains as an int (no decimals)\nYou need to convert your array to float first in order to get the output you expect.\nV=np.array([[3,1],[1,3]]).astype('float')\nV[0...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074253053_python.txt
Q: Tkinter.asksaveasfile() use The use of the askopenfilename is quite easy but its counterpart is a bit more complicated. I can get the box to open and enter the name but the file created is empty import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveasfilename import PyPDF4 # import des fichi...
Tkinter.asksaveasfile() use
The use of the askopenfilename is quite easy but its counterpart is a bit more complicated. I can get the box to open and enter the name but the file created is empty import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveasfilename import PyPDF4 # import des fichiers root = tk.Tk() root.withdraw(...
[ "Seems like you mixed up your paths and file objects. I also noticed some minor issues with the call arguments for your pdf reader and the file browser which I solved by adding or removing code snippets, see the comments in my code.\nYour file probably stayed empty because you never closed it. This is one of many r...
[ 2, 1 ]
[]
[]
[ "pypdf", "python", "tkinter" ]
stackoverflow_0074252479_pypdf_python_tkinter.txt
Q: Flask app search bar I am trying to implement a search bar using Flask, but when I enter the url/search, I got a 405 error, Method Not Allowed. Here is a snippet of my code. Any help would be appreciated! forms.py from wtforms import StringField from wtforms.validators import DataRequired class SearchForm(Form):...
Flask app search bar
I am trying to implement a search bar using Flask, but when I enter the url/search, I got a 405 error, Method Not Allowed. Here is a snippet of my code. Any help would be appreciated! forms.py from wtforms import StringField from wtforms.validators import DataRequired class SearchForm(Form): search = StringField('s...
[ "Because when you load page manually you using GET method, but only POST is allowed for search controller. You need to change\n@app.route('/search', methods=['POST'])\n\nto \n@app.route('/search', methods=['GET', 'POST'])\n\nUPDATE\nSo basically it's better to change your search controller. Because it's not using s...
[ 8, 0 ]
[]
[]
[ "flask", "full_text_search", "python", "search", "whoosh" ]
stackoverflow_0039960942_flask_full_text_search_python_search_whoosh.txt
Q: How to efficiently iterate through rows in a large matrix with too many columns? I'm working on document clustering where I first build a distance matrix from the tf-idf results. I use the below code to get my tf-idf matrix: from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(s...
How to efficiently iterate through rows in a large matrix with too many columns?
I'm working on document clustering where I first build a distance matrix from the tf-idf results. I use the below code to get my tf-idf matrix: from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(stop_words={'english'}) X = vectorizer.fit_transform(models) This results in a matrix ...
[ "The biggest issue is that the algorithms runs in O(n^3) since each iteration to distance.braycurtis requires the computation of two arrays of size 9069. Since the computation is done 9069*9069 times. This means thousands billion scalar operations are required so to complete the computation. This is huge. The thing...
[ 1 ]
[ "You see, the individual elements of the NumPy multidimensional matrix you give in as input are saved in memory in 2 ways. They are:\nROW MAJOR\nCOLUMN MAJOR\nEach has its advantages and disadvantages.\nYou can even control the way it is stored.\nI hope you find this helpful\n" ]
[ -1 ]
[ "data_science", "distance_matrix", "loops", "numpy", "python" ]
stackoverflow_0074248004_data_science_distance_matrix_loops_numpy_python.txt
Q: Balanced expression with replacement Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence. Examples: Input : S = "{(X[X]...
Balanced expression with replacement
Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence. Examples: Input : S = "{(X[X])}" Output : Balanced Input : S = "[{X}...
[ "You can do it by recursively testing all possible replacements for an X:\ndef can_be_balanced(expr):\n pairs = \"{}[]()\"\n opening_brackets = pairs[::2]\n closing_brackets = pairs[1::2]\n closer = {o:c for o, c in zip(opening_brackets, closing_brackets)}\n opener = {c:o for o, c in zip(opening_brac...
[ 0 ]
[]
[]
[ "brackets", "oop", "python", "recursion", "stack" ]
stackoverflow_0074251187_brackets_oop_python_recursion_stack.txt
Q: 'numpy.ndarray' object has no attribute 'open' i'm getting this error in my code, how to remove it my code ran into attribute error 'numpy.ndarray' object has no attribute 'open' here's my code import cv2 from PIL import Image from pytesseract import pytesseract camera=cv2.VideoCapture(0) while True: _,Imag...
'numpy.ndarray' object has no attribute 'open'
i'm getting this error in my code, how to remove it my code ran into attribute error 'numpy.ndarray' object has no attribute 'open' here's my code import cv2 from PIL import Image from pytesseract import pytesseract camera=cv2.VideoCapture(0) while True: _,Image=camera.read() cv2.imshow('Text detection',Imag...
[ "You're overwriting your imported Image module symbol with a variable in\n_,Image=camera.read()\n\nDon't do that. Name it image or something; then image.open should be fine.\n" ]
[ -1 ]
[]
[]
[ "attributes", "multidimensional_array", "numpy", "opencv", "python" ]
stackoverflow_0074253153_attributes_multidimensional_array_numpy_opencv_python.txt
Q: Stuck in error loop between Data cardinality is ambiguous and shapes are incompatible with my 3d cnn model I'm attempting to train my model using the "train_on_batch" function, as the data is too large to be fully put in at once. The shape of my training data is as follows: X.shape = (388, 108, 36, 36, 36), Y.shap...
Stuck in error loop between Data cardinality is ambiguous and shapes are incompatible with my 3d cnn model
I'm attempting to train my model using the "train_on_batch" function, as the data is too large to be fully put in at once. The shape of my training data is as follows: X.shape = (388, 108, 36, 36, 36), Y.shape = (388, 108). To make the data clear, there are 388 x and 388 y train files. Each of these training files cont...
[ "As it turns out, I was misinterpreting a comment I had read while following a guide on how to setup this model. By writing (108,36,36,36) instead of (36,36,36,1) I was telling the model the incorrect input shape. Once that was fixed, it worked.\n" ]
[ 0 ]
[]
[]
[ "conv_neural_network", "neural_network", "python", "tensorflow" ]
stackoverflow_0074246184_conv_neural_network_neural_network_python_tensorflow.txt
Q: Merging a pandas groupby result back into DataFrame I have a DataFrame that looks like this... idn value 0 ID1 25 1 ID1 30 2 ID2 30 3 ID2 50 I want to add another column to this frame that is the max 'value' grouped by 'idn' I want a result that looks like this. idn value max_val 0 ID1 ...
Merging a pandas groupby result back into DataFrame
I have a DataFrame that looks like this... idn value 0 ID1 25 1 ID1 30 2 ID2 30 3 ID2 50 I want to add another column to this frame that is the max 'value' grouped by 'idn' I want a result that looks like this. idn value max_val 0 ID1 25 30 1 ID1 30 30 2 ID2 30 50...
[ "Use the transform method on a groupby object:\nIn [5]: df['maxval'] = df.groupby(by=['idn']).transform('max')\n\nIn [6]: df\nOut[6]: \n idn value maxval\n0 ID1 25 30\n1 ID1 30 30\n2 ID2 30 50\n3 ID2 50 50\n\n", "set the index of df to idn, and then use df.merge. after ...
[ 14, 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0029641472_pandas_python.txt
Q: Running a single line of code in PyCharm I'm coming from RStudio, so forgive my naievete. In RStudio it's really nice to be able to run lines by simply pressing Ctrl+Enter on the line. This sends the line of code directly to the console, which makes building functions really easy because you can work through each...
Running a single line of code in PyCharm
I'm coming from RStudio, so forgive my naievete. In RStudio it's really nice to be able to run lines by simply pressing Ctrl+Enter on the line. This sends the line of code directly to the console, which makes building functions really easy because you can work through each line to check for problems. However, in Pycha...
[ "ALT+SHIFT+E will execute in console.\nCTRL+SHIFT+A will let you search for hotkeys.\n", "It is also possible to change the key combination to your liking.\nFor example, if you used to work with ctrl + enter in R, you can change it in:\nFile -> Settings -> Keymap - Other -> Execute selection in Python Console\n",...
[ 35, 25, 7, 2, 0, 0 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0049637853_pycharm_python.txt
Q: lookup with sum in mongodb with python I have two collections, one with a lot of transactions and another one with a selected list of companies, that belong to an index and may or may not have made some transactions. In the first list there are many companies that do not belong to the second collection. I want to ...
lookup with sum in mongodb with python
I have two collections, one with a lot of transactions and another one with a selected list of companies, that belong to an index and may or may not have made some transactions. In the first list there are many companies that do not belong to the second collection. I want to know the total transaction amount the compan...
[ "As you mentioned, a standard $lookup stage is the way to go:\ndb.companies.aggregate([\n {\n $lookup: {\n from: \"trannsactions\",\n localField: \"ISIN\",\n foreignField: \"ISIN\",\n as: \"matchedTransactions\"\n }\n },\n {\n $project: {\n _id: 1,\n name: \"$Name_short\",\...
[ 1 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0074253184_mongodb_python.txt
Q: How to press Enter using PyAutoGUI please tell me how to press the Enter button using the PyAutoGUI library. I've tried everything, but nothing is pressed. Can you suggest how to do it? A: Use pyautogui.press(“enter”) or pyautogui.hotkey(“enter”) for pressing 3 times: use pyautogui.press(“enter”, presses=3) or f...
How to press Enter using PyAutoGUI
please tell me how to press the Enter button using the PyAutoGUI library. I've tried everything, but nothing is pressed. Can you suggest how to do it?
[ "Use pyautogui.press(“enter”) or pyautogui.hotkey(“enter”)\nfor pressing 3 times:\nuse pyautogui.press(“enter”, presses=3)\nor\nfor i in range(3):\n pyautogui.press(“enter”)\n\nfor pressing lots of keys:\npyautogui.press([“enter”, “shift”])\n\nor\nfor key in [“enter”, “shift”]:\n pyautogui.press(key)\n\ndispa...
[ 3, 2, 0, 0 ]
[]
[]
[ "pyautogui", "python" ]
stackoverflow_0071814027_pyautogui_python.txt
Q: Return value being printed first with concurrent futures For some reason, the return value value of this funcion is being printed first: def do_something(t): print(f'Sleeping for {t} second(s)...') time.sleep(t) return 'Done Sleeping...' if __name__ == '__main__': with concurrent.futures.ProcessPo...
Return value being printed first with concurrent futures
For some reason, the return value value of this funcion is being printed first: def do_something(t): print(f'Sleeping for {t} second(s)...') time.sleep(t) return 'Done Sleeping...' if __name__ == '__main__': with concurrent.futures.ProcessPoolExecutor() as executor: secs = [5,4,3,2,1] ...
[ "You say, \"... even if I use as_completed(), the return value is always printed after the function finished.\" If the function you are referring to is the worker function do_something, what else could you possibly expect? The as_completed will return you futures in the order in which the 5 submitted tasks complete...
[ 0 ]
[]
[]
[ "concurrent.futures", "multiprocessing", "python", "python_multiprocessing" ]
stackoverflow_0074250072_concurrent.futures_multiprocessing_python_python_multiprocessing.txt
Q: Add a Pandas dataframe beside an existing dataframe of the same size, i.e. on the next column I was playing around with data using pandas dataframe and bumped into this problem. Is it possible to copy an existing dataframe and add the copy to next column of that particular dataframe? I was able to do so if the dat...
Add a Pandas dataframe beside an existing dataframe of the same size, i.e. on the next column
I was playing around with data using pandas dataframe and bumped into this problem. Is it possible to copy an existing dataframe and add the copy to next column of that particular dataframe? I was able to do so if the dataframe have only one column of data. df = pd.DataFrame(6*['a']) copy = df.copy() df.insert(len(df),...
[ "insert only allows to insert one column at a time. If you want to insert 2 columns, you can use the concat method of pandas, passing the previous data frame and the new one, and setting the axis=1 so it is added as columns and not rows.\nimport pandas as pd\ndf = pd.DataFrame(6*['p'])\ncopy = df.copy()\ndf.insert(...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074253255_dataframe_pandas_python.txt
Q: selenium webdriver close after clicking the button Hi I want to click on a button and then go to next page using selenium python. but instead it get close doesnot show the next tab at all import time from Base_Class import * class Majestic_Domain: def capture_domain(): web_driver_conn = base_class.web_...
selenium webdriver close after clicking the button
Hi I want to click on a button and then go to next page using selenium python. but instead it get close doesnot show the next tab at all import time from Base_Class import * class Majestic_Domain: def capture_domain(): web_driver_conn = base_class.web_driver() web_driver_conn.get("https://tranco-lis...
[ "Add some wait time after the click() action:\ndef capture_domain():\n web_driver_conn = base_class.web_driver()\n web_driver_conn.get(\"https://tranco-list.eu/\")\n CSV_Download = web_driver_conn.find_element(By.XPATH, '//body/main/div/div/a')\n time.sleep(1)\n CSV_Download.click()\n time.sleep(5...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074252880_python_selenium_selenium_webdriver.txt
Q: Python XML/Pandas: How to merge nested XML? How can I join two different pieces of information together from this XML file? # data xml1 = ('''<?xml version="1.0" encoding="utf-8"?> <TopologyDefinition xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <RSkus> ...
Python XML/Pandas: How to merge nested XML?
How can I join two different pieces of information together from this XML file? # data xml1 = ('''<?xml version="1.0" encoding="utf-8"?> <TopologyDefinition xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <RSkus> <RSku ID="V1" Deprecated="true" Owner="Unknown" G...
[ "Consider transforming the XML with XSLT by flattening the document with information you need. Specifically, retrieve only Blade attributes using descendant::* axis and corresponding RSku attributes using the ancestor::* axis. Python' lxml (default parser of pandas.read_xml) can run XSLT 1.0 scripts.\nBelow XSLT's ...
[ 1 ]
[]
[]
[ "pandas", "python", "xml" ]
stackoverflow_0074242605_pandas_python_xml.txt
Q: R equivalent for python brackets This is related to my earlier question (Using Huggingspace Transformer Models in R) but I don't seem to have done a good job on the question. Here is another try. I´m using transformer models from huggingspace in R. All models work fine except for models which require multiple stri...
R equivalent for python brackets
This is related to my earlier question (Using Huggingspace Transformer Models in R) but I don't seem to have done a good job on the question. Here is another try. I´m using transformer models from huggingspace in R. All models work fine except for models which require multiple strings as input. In python the syntax is ...
[ "If I understand you properly you are trying to create a vector of character in terms or R. There is a function c() to do this. Note, that there is no such thing as scalar variable in R. Scalars are dealt as vectors of length 1.\nAppended\nSometimes functions in R are waiting for a pseudoscalar parameter (vector of...
[ 0 ]
[]
[]
[ "huggingface_transformers", "python", "r" ]
stackoverflow_0074253135_huggingface_transformers_python_r.txt
Q: Python 3 - First time coding need help - Counting the highest occurring string in an array Big noob here just starting coding. So in Python 3, say you are given an array consisting of names like [Bob, Bob, Ben, Alex, Bob]. I want it to return the number '3', as 'Bob' occurs the most, with three occurrences. This c...
Python 3 - First time coding need help - Counting the highest occurring string in an array
Big noob here just starting coding. So in Python 3, say you are given an array consisting of names like [Bob, Bob, Ben, Alex, Bob]. I want it to return the number '3', as 'Bob' occurs the most, with three occurrences. This can be for any given array of names. Thanks seen examples such as this but not exactly what im lo...
[ "You can just use the maxfunction with the dict values.\nLike this:\nfrom collections import Counter\nlist1=['apple','egg','apple','banana','egg','apple']\ncounts = Counter(list1)\nprint(max(counts.values()))\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "frequency", "python" ]
stackoverflow_0074253322_arrays_frequency_python.txt
Q: VS Code Python Interactive Window Cannot find Conda Env Everytime I try to execute my python code to the Python Interactive Window I get the below error... Executing code failed : Error: Activating Python 3.7.3 64-bit ('base': conda) to run Jupyter failed with Error: Command failed: "H:/My Documents/Continuum/ana...
VS Code Python Interactive Window Cannot find Conda Env
Everytime I try to execute my python code to the Python Interactive Window I get the below error... Executing code failed : Error: Activating Python 3.7.3 64-bit ('base': conda) to run Jupyter failed with Error: Command failed: "H:/My Documents/Continuum/anaconda3/Scripts/activate" && conda activate base && echo 'e8b...
[ "Looks like your Anaconda in PATH and Python Path in VSCode are pointing in different places. \nFirst, check under system variables that your Anaconda is mapped to PATH based off where it is installed.\n1- Click Start Menu Windows logo, type \"path\" click on \"edit the system environment labels\"\n2- Under PATH fo...
[ 6, 2, 1, 0, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0059502466_python_visual_studio_code.txt
Q: Renaming column: A value is trying to be set on a copy of a slice from a DataFrame I am trying to rename a specific column. Sample Data: FROM_ID TO_ID DURATION_H DIST_KM 1 7 0.528556 38.43980 1 26 0.512511 37.38515 1 71 0.432453 32.57571 1 83 0.599486 39...
Renaming column: A value is trying to be set on a copy of a slice from a DataFrame
I am trying to rename a specific column. Sample Data: FROM_ID TO_ID DURATION_H DIST_KM 1 7 0.528556 38.43980 1 26 0.512511 37.38515 1 71 0.432453 32.57571 1 83 0.599486 39.26188 1 98 0.590517 35.53107 Sample Code: df_temp_MSU1 = MSU_TT_Temp.lo...
[ "Do this to counter warning (Using .copy()):\ndf_temp_MSU1 = MSU_TT_Temp.loc[(MSU_TT_Temp['FROM_ID'] == 1)].copy()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074183322_dataframe_jupyter_notebook_pandas_python.txt
Q: selenium + python after downloading a song with selenium ,selenium open Hollywood bet page and stuck there so the code after downloading not run here is the code and the the output of my vscode terminal the code hangs up due to chromedriver gets stuck on hollywoodbet pages that opens after a song is downloaded. i...
selenium + python after downloading a song with selenium ,selenium open Hollywood bet page and stuck there so the code after downloading not run
here is the code and the the output of my vscode terminal the code hangs up due to chromedriver gets stuck on hollywoodbet pages that opens after a song is downloaded. i am using mudopy + selenium to fetch a video from youtube convert it to mp3 using a converter then download the song .Songs download succesfully but ...
[ "Try using driver.quit() instead of driver.close()\nclose() only closes the current tab, but quit() closes the entire browser.\nHope it will help\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver" ]
stackoverflow_0074253194_python_selenium_selenium_chromedriver.txt
Q: coding a blackjack game using dictionary-python I used an alternative way to develop a Blackjack game, but I noticed that the first 2 dealer cards for both user and computer are always the same. is there something I didn`t do right? I need help on tnis. import random from replit import clear deck={"ace": 11, ...
coding a blackjack game using dictionary-python
I used an alternative way to develop a Blackjack game, but I noticed that the first 2 dealer cards for both user and computer are always the same. is there something I didn`t do right? I need help on tnis. import random from replit import clear deck={"ace": 11, "jack":10, "queen": 10, "king":10, ...
[ "There are various approached towards your code dependent upon the outcome you desire. Firstly, if you add return keyword within your for loop then it will run only once.\nApproach 1: random.choices()\nhttps://docs.python.org/3/library/random.html\nAs per their docs, you can generate various random outputs without ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074253266_python.txt
Q: looping in a data frame failing: Overriding existing column values I am using a for loop to reuse existing data frames. Sample Code: for i in range(0, 5, 1): RGU_TT_TempX = pd.DataFrame() RGU_TT_TempX = RGU_TT_Temp #Merging Regular Ambulance TT with MSUs TT #Updating MSUs TT according to the Formul...
looping in a data frame failing: Overriding existing column values
I am using a for loop to reuse existing data frames. Sample Code: for i in range(0, 5, 1): RGU_TT_TempX = pd.DataFrame() RGU_TT_TempX = RGU_TT_Temp #Merging Regular Ambulance TT with MSUs TT #Updating MSUs TT according to the Formula RGU_TT_TempX["MSU_X_DURATION"] = 0.05 + df_temp_MSU1["MSU_X_DURATI...
[ "This error occurs when you attempt to assign a NumPy array of values to a new column in a pandas DataFrame, yet the array's length does not match the current length of the index.\nThe easiest way to fix this error is to simply create a new column using a pandas Series instead of a NumPy array.\nYou can take a clos...
[ 1, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python", "python_3.x" ]
stackoverflow_0074206174_dataframe_jupyter_notebook_pandas_python_python_3.x.txt
Q: python dict: dynamically read a layered dict I have this dict ("one", "two" and "four" always exist but might be empty): info = { "one":1, "two":{ "three":3, "almost_three":3.5 }, "four": { "five":{ "six":6 } } } my condition code is this: if info['one']: sum += info['one'] if i...
python dict: dynamically read a layered dict
I have this dict ("one", "two" and "four" always exist but might be empty): info = { "one":1, "two":{ "three":3, "almost_three":3.5 }, "four": { "five":{ "six":6 } } } my condition code is this: if info['one']: sum += info['one'] if info['two'].get('three'): sum += info['two']['thr...
[ "You can use recursion to sum the values of a nested dictionary:\ndef sum_values(d):\n total = 0\n for k, v in d.items():\n if isinstance(v, dict):\n total += sum_values(v)\n else:\n total += v\n return total\n\n\ninfo = {\n \"one\": 1,\n \"two\": {\n \"thre...
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074253409_python_python_3.x.txt
Q: The field returns null even though it contains a value When creating a new object (music track), I specify the name of the playlist in one of the fields. However, after saving the data from the form, the value of the playlist field in the frontend is null, although there is a value in this field in the admin panel...
The field returns null even though it contains a value
When creating a new object (music track), I specify the name of the playlist in one of the fields. However, after saving the data from the form, the value of the playlist field in the frontend is null, although there is a value in this field in the admin panel. I do not understand how I can get the text value of a fiel...
[ "You should return name of playlist in PlayList model itself using __str__() method so:\nclass PlayList(models.Model):\n name = models.CharField(max_length=500)\n def __str__(self):\n return f\"{self.name}\"\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_templates", "javascript", "python" ]
stackoverflow_0074253345_django_django_models_django_templates_javascript_python.txt
Q: Terminal is busy after TKinter window is closed I have written a python script that draws a GUI containing Graphs plotting various metrics such as CPU temperature, Ram usage etc. for my Rasberry pi v4 . The source code of the script is outlined below: ` #!/usr/bin/env python3 #Import required modules import tkin...
Terminal is busy after TKinter window is closed
I have written a python script that draws a GUI containing Graphs plotting various metrics such as CPU temperature, Ram usage etc. for my Rasberry pi v4 . The source code of the script is outlined below: ` #!/usr/bin/env python3 #Import required modules import tkinter as tk import matplotlib.pyplot as plt from matplo...
[]
[]
[ "When you enter your for-loop, your program runs all 50 iteration of that code block until it exits and runs code below. This is toxic for different reasons. Overall, your mainloop is interrupted, events such as mouse or key input won't be processed. This includes clicking X, the window simply does not proceed this...
[ -1 ]
[ "python", "raspberry_pi", "terminal", "tkinter" ]
stackoverflow_0074253387_python_raspberry_pi_terminal_tkinter.txt
Q: arima_model.plot_predict() shows different results than arima_model.fitted_values I am trying to construct the arima model. When I write arima_fit.plot_predict() plt.show() I get this result which is quite good. But. When I try to calculate the RMSE with actual df['y'] values and arima_fit.fitted_values I get va...
arima_model.plot_predict() shows different results than arima_model.fitted_values
I am trying to construct the arima model. When I write arima_fit.plot_predict() plt.show() I get this result which is quite good. But. When I try to calculate the RMSE with actual df['y'] values and arima_fit.fitted_values I get values around 0. Like 0.04 ,-0.1 etc The same with the arima_fit.predict() values. How ca...
[ "Update: I found an answer. The d component of arima means the differencing, if to set it to 1 it will give you a detrended value.\nARIMA() gives you the values without trend and seasonality added. Indeed if to detract the seasonality and trend from the original series we will get the next picture. Or as an alterna...
[ 0 ]
[]
[]
[ "arima", "python", "time_series" ]
stackoverflow_0074253133_arima_python_time_series.txt
Q: Below is the code to return leap year by passing argument def leap(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) I am new to python. I am writing a program that should take a year as input and return a Boolean whether the year is a leap year or not. Above is the code of my professor whi...
Below is the code to return leap year by passing argument
def leap(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) I am new to python. I am writing a program that should take a year as input and return a Boolean whether the year is a leap year or not. Above is the code of my professor which I am trying to understand but I am not sure why my professor...
[ "% is a modulo operator in Python.\nhttps://docs.python.org/3/reference/expressions.html\n% 100 is being used to check if the year is divisible by 100 or not. This is because 200 is also divisible by 4 but it's not a leap year. For a leap year, you require 4 and 100 to be multiples. However, % 400 is not required.\...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074253513_python.txt
Q: Search under condition in one column if a value in another column is unique, and write the results in a 3rd column I have a data frame with 70k rows and two columns. Col1 contains bill of materials name and customer, Col2 contains a part number (which is a part of the BOM). Col1 Col2 0 TUR, Cust1 1001 ...
Search under condition in one column if a value in another column is unique, and write the results in a 3rd column
I have a data frame with 70k rows and two columns. Col1 contains bill of materials name and customer, Col2 contains a part number (which is a part of the BOM). Col1 Col2 0 TUR, Cust1 1001 1 GAR, Cust2 1001 2 FOR, Cust3 1001 3 ERB, Cust1 1002 4 PNR, Cust1 1002 5 DUL, Cust2 1003 6 COC, Cust3 1003 ...
[ "Extract the customer from Col1 then groupby part number and count the number of unique customers which should be equal to 1\ndf['Cust'] = df['Col1'].str.split(', ').str[-1]\ndf['Col3'] = df.groupby('Col2')['Cust'].transform('nunique').eq(1)\n\nIf only interested in checking the dupes considering one customer at a ...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074253411_pandas_python.txt
Q: How to get the best match when searching through documents using marqo whenever i use the search() method to search through documents on marqo i get a list of python dictionaries as the result, arranging them from best to least matching but i only want the best matching to show not a list of dictionaries. is there...
How to get the best match when searching through documents using marqo
whenever i use the search() method to search through documents on marqo i get a list of python dictionaries as the result, arranging them from best to least matching but i only want the best matching to show not a list of dictionaries. is there any method to accomplish that? Here is what the result look like: { 'hi...
[ "when you use the search() method you can pass a keyword argument which is limit by default it is set to 10 but by changing it to 1 you will get only the first one.\nhere is what i mean;\n mq.index(your_index).search(\n q=search_query, \n limit=1\n )\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074247233_python.txt
Q: How to use the DummyVecEnv in openai I am new to the field of reinforcement learning, I came across these two lines of code env = gym.make("CartPole-v0") env = DummyVecEnv([lambda: env]) I would like to know the purpose of inputting lambda as an argument into DummyVecEnv()? A: DummyVecEnv needs to be passed on ...
How to use the DummyVecEnv in openai
I am new to the field of reinforcement learning, I came across these two lines of code env = gym.make("CartPole-v0") env = DummyVecEnv([lambda: env]) I would like to know the purpose of inputting lambda as an argument into DummyVecEnv()?
[ "DummyVecEnv needs to be passed on a function that returns an environment.\nYou can do it in a long-form manner like this:\ndef make_env():\n env = gym.make('CarRacing-v0')\n return env \n\nenv = DummyVecEnv([make_env])\n\nThis is not pythonic, it is a bit more explicit.\nIn python, lambda keyword generates a...
[ 0 ]
[]
[]
[ "python", "reinforcement_learning" ]
stackoverflow_0071466396_python_reinforcement_learning.txt
Q: I want to draw a line chart with a sort of condition I have a dataframe containing 1440 rows and 8 columns. I have a column names 'number' taking values from 0 to 12. And I have another column named "correct" which takes value of True or False. What I would like to do is a line chart with on my x axis'number' whic...
I want to draw a line chart with a sort of condition
I have a dataframe containing 1440 rows and 8 columns. I have a column names 'number' taking values from 0 to 12. And I have another column named "correct" which takes value of True or False. What I would like to do is a line chart with on my x axis'number' which as I said are ranging from 0 to 12 and on my y axis the ...
[ "I used the where and the groupby functions. So basically I filtered rows where the correct column was True, and then grouped by the numbers. You can just plot this new dataframe. I used a random dataframe to test the result.\nEdit: I realized that I only used numbers 0-10 instead of 0-12, but the idea is still the...
[ 1, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074227430_matplotlib_python.txt
Q: GeoDjango - FileNotFoundError: Could not find module 'C:\OSGeo4W\bin\gdal304.dll' (or one of its dependencies) I am trying to install GeoDjango what turns out to be much harder than I thought. After I installed the OSGeo4W on my 64 Bit Windows 10 system I set everything up in the settings.py file but now I get thi...
GeoDjango - FileNotFoundError: Could not find module 'C:\OSGeo4W\bin\gdal304.dll' (or one of its dependencies)
I am trying to install GeoDjango what turns out to be much harder than I thought. After I installed the OSGeo4W on my 64 Bit Windows 10 system I set everything up in the settings.py file but now I get this error: FileNotFoundError: Could not find module 'C:\OSGeo4W\bin\gdal304.dll' (or one of its dependencies). Try usi...
[ "I ran into this problem too, since I updated my old GEO Django Setup today.\nYou may use a Docker Image as suggested by the others, but I prefere a native solution, since I don't want to spin up Docker every time I start coding.\nYour solution is in the brackets: (or one of its dependencies)\nYou may look up the t...
[ 0 ]
[]
[]
[ "django", "geodjango", "python" ]
stackoverflow_0073463788_django_geodjango_python.txt
Q: How to alternate between multiple async functions with "loop.run_until_complete()" in Python? I'm trying to run 2 async functions test1() and test2() with loop.run_until_complete() alternately in Python as shown below: import asyncio async def test1(): for _ in range(3): print("Test1") await a...
How to alternate between multiple async functions with "loop.run_until_complete()" in Python?
I'm trying to run 2 async functions test1() and test2() with loop.run_until_complete() alternately in Python as shown below: import asyncio async def test1(): for _ in range(3): print("Test1") await asyncio.sleep(1) async def test2(): for _ in range(3): print("Test2") a...
[ "If you wouldn't insist on the loop.run_until_complete you can achieve what you want to get by using the asyncio.gather functionality, just like so:\nimport asyncio\n\nasync def test1():\n for _ in range(3):\n print(\"Test1\")\n await asyncio.sleep(1)\n\nasync def test2():\n for _ in range(3):\n...
[ 0, 0 ]
[]
[]
[ "asynchronous", "concurrency", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0074248240_asynchronous_concurrency_python_python_3.x_python_asyncio.txt
Q: Permission based media server I wanna build web based file/media(can be any type such as .mp4, .something) server using Django and JWT will handle the authorization. As normally, all media files are publicly accessible if we copy paste absolute path. How can setup in a way when only authorised user can access that...
Permission based media server
I wanna build web based file/media(can be any type such as .mp4, .something) server using Django and JWT will handle the authorization. As normally, all media files are publicly accessible if we copy paste absolute path. How can setup in a way when only authorised user can access that specific file/media?
[ "The solution is overriding Django's media serve URL endpoint and modifying that function which handles serving.\n" ]
[ 0 ]
[]
[]
[ "django", "jwt", "python" ]
stackoverflow_0073995210_django_jwt_python.txt
Q: Adding a bonus for specific days in Python I'm trying to add a bonus to my code that is for Dec 15 - 22 at a rate of $50 per day if those days are used. I can't really seem to figure out how to do that currently. The input for this value is based off a start date and an end date that are input by the user and are ...
Adding a bonus for specific days in Python
I'm trying to add a bonus to my code that is for Dec 15 - 22 at a rate of $50 per day if those days are used. I can't really seem to figure out how to do that currently. The input for this value is based off a start date and an end date that are input by the user and are in YYYY/MM/DD format: while True: EndDateSt...
[ "I would recommend checking the timedelta part of datetime module. We can subtract NumDays from EndDate.\nStartDate = EndDate - datetime.timedelta(days=NumDays)\n\nand using this information as you already know, we can check for the following.\nbonus() if StartDate.month == 12 and StarDate.day in range(15, 23) else...
[ 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074253095_datetime_python.txt
Q: ValueError: Query missing geometry column 'geom' I am trying to count the area of the area that is less than 500 units away from the shortest line connecting factory A and station B. I am trying to query the PostGIS spatial database in Python, but I get an error: ValueError: Query missing geometry column 'geom' M...
ValueError: Query missing geometry column 'geom'
I am trying to count the area of the area that is less than 500 units away from the shortest line connecting factory A and station B. I am trying to query the PostGIS spatial database in Python, but I get an error: ValueError: Query missing geometry column 'geom' My code: sql = """SELECT ST_area(St_buffer(st_ShortestL...
[ "The geopandas data frame requires a geometry field I had the same problem I solved it by adding the geom field from the table I wanted to filter.\nThe parameter geom_col='geometry' allows you to specify the name of this column that geopandas needs. In your case geom.\nNeed to add geometries (SELECT table_name.geom...
[ 0 ]
[]
[]
[ "geopandas", "postgis", "python", "spatial" ]
stackoverflow_0074253604_geopandas_postgis_python_spatial.txt
Q: Matplotlib Table- Assign different text alignments to different columns I am creating a two column table and want the text to be as close as possible. How can I specify that the first column be right aligned and the second be left aligned? I've tried by setting the general cellloc to one side (cellloc sets the tex...
Matplotlib Table- Assign different text alignments to different columns
I am creating a two column table and want the text to be as close as possible. How can I specify that the first column be right aligned and the second be left aligned? I've tried by setting the general cellloc to one side (cellloc sets the text alignment) from matplotlib import pyplot as plt data = [['x','x'] for x in...
[ "Instead of setting the alignment of the text itself, you need to set the position of the text inside the table cell. This is determined by the cell's ._loc attribute.\ndef set_align_for_column(table, col, align=\"left\"):\n cells = [key for key in table._cells if key[1] == col]\n for cell in cells:\n ...
[ 5, 2, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0048210749_matplotlib_python.txt
Q: How to write a recursive function that returns a list of numbers that count down from n to 0? I am having trouble with this seemingly simple function. def countdown(n: int): """ Write a simple recursive function that returns a list of numbers that count down from n. countdown(5) -> [5, 4, 3, 2, 1, 0] ...
How to write a recursive function that returns a list of numbers that count down from n to 0?
I am having trouble with this seemingly simple function. def countdown(n: int): """ Write a simple recursive function that returns a list of numbers that count down from n. countdown(5) -> [5, 4, 3, 2, 1, 0] countdown(8) -> [8, 7, 6, 5, 4, 3, 2, 1, 0] countdown(-1) -> [] :param n: start :r...
[ "def countdown(n:int):\n integers = []\n if n>=1:\n for i in range(n+1):\n integers.append(n-i)\n return integers\n\ncountdown(6)\n\nOutput: [6, 5, 4, 3, 2, 1, 0]\n", "You are very nearly there. You are getting None because you don't return anything in the function. You can do something...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0064649913_python.txt
Q: How to remove the last comma when printing a list of strings? This is my code houses = ['C', 'D', 'H', 'S'] ranks = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] deck = [] for house in houses: for rank in ranks: deck.append(f"{rank}-{house}") for i in range(13): print(deck[i], end=",")` ...
How to remove the last comma when printing a list of strings?
This is my code houses = ['C', 'D', 'H', 'S'] ranks = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] deck = [] for house in houses: for rank in ranks: deck.append(f"{rank}-{house}") for i in range(13): print(deck[i], end=",")` The output is supposed to be: A-C,2-C,3-C,4-C,5-C,6-C,7-C,8-C,9-C,...
[ "Here's another alternative\nhouses = ['C', 'D', 'H', 'S']\nranks = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']\ndeck = []\n\nfor house in houses:\n for rank in ranks:\n deck.append(f\"{rank}-{house}\")\n\nprint(*deck[:13], sep=',')\n\n", "Might suggest combining str.join and itertools.produc...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074252801_python_python_3.x.txt
Q: locating element explicitly waiting and without wait what's difference? The question is about selenium webdriver's explicitly wait feature which is same locating action with a timeout. Webdriver waits element to be visible or present. In my situation, I locate elements with explicit waiting and without it. When it...
locating element explicitly waiting and without wait what's difference?
The question is about selenium webdriver's explicitly wait feature which is same locating action with a timeout. Webdriver waits element to be visible or present. In my situation, I locate elements with explicit waiting and without it. When it is without the explicit wait, it founds and assigns it. But below, I also tr...
[ "Since you didn't share all the code including the link we can't know what exactly happens there, but I guess that this line\nwait.until(EC.visibility_of_all_elements_located((By.XPATH,'//div[contains(@class,\"a-row a-size-base a-color-base\")]//span[contains(@data-a-color,\"base\")]//span[contains(@class,\"a-offsc...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "try_catch", "webdriverwait" ]
stackoverflow_0074253638_python_selenium_selenium_webdriver_try_catch_webdriverwait.txt
Q: TypeError: 'Series' object is not callable in Python? I am performing model selection in Python. Unfortunately, I got error "TypeError: 'Series' object is not callable". I don't understand what this means and how I could solve this issue. Any suggestions? This part of the code runs without problems: def model_sele...
TypeError: 'Series' object is not callable in Python?
I am performing model selection in Python. Unfortunately, I got error "TypeError: 'Series' object is not callable". I don't understand what this means and how I could solve this issue. Any suggestions? This part of the code runs without problems: def model_selection(X, *args): # Init scores = list(itertools.r...
[ "change your function definition to\ndef model_selection(X,y,*args)\n\nbecause y was part of *args which is causing this issue when it is called.\nie: the error was doing y(reg) which is an error.\n" ]
[ 1 ]
[]
[]
[ "callable", "feature_selection", "python", "series" ]
stackoverflow_0074253771_callable_feature_selection_python_series.txt
Q: python-chess AssertionError: san() and lan() expect move to be legal or null, but got {move} in {fen} I'm trying to create a chess engine using python-chess, but I keep getting the error message: Traceback (most recent call last): File "dir/main.py", line 26, in <module> print(BOARD.san(whiteMove)) File "d...
python-chess AssertionError: san() and lan() expect move to be legal or null, but got {move} in {fen}
I'm trying to create a chess engine using python-chess, but I keep getting the error message: Traceback (most recent call last): File "dir/main.py", line 26, in <module> print(BOARD.san(whiteMove)) File "dir\venv\lib\site-packages\chess\__init__.py", line 2824, in san return self._algebraic(move) File "di...
[]
[]
[ "Nevermind, I found it. Turns out I was messing up my evals!\n" ]
[ -1 ]
[ "chess", "python" ]
stackoverflow_0074253635_chess_python.txt
Q: I wanted to print this tuple in a single line I was making a small program to exemplify the wordle game in python but the code below generates an output in tuple format (one element per line). Like this: T _ E T E the code: def check_palpite(): palavra_secreta = "Sorte" tentativas = 6 while tentativas...
I wanted to print this tuple in a single line
I was making a small program to exemplify the wordle game in python but the code below generates an output in tuple format (one element per line). Like this: T _ E T E the code: def check_palpite(): palavra_secreta = "Sorte" tentativas = 6 while tentativas > 0: palpite = str(input("Faça um palpite ...
[ "You have two approaches, either:\n\npass a string to the end= parameter of print(), or\nappend each character to a string and print the string after the loop.\n\nApproach 2 is faster because it makes fewer function calls, so I'll use that one. Just create an empty string before the loop, then print that string at ...
[ 0 ]
[]
[]
[ "list", "python", "python_2.7", "python_3.x", "wordle_game" ]
stackoverflow_0074253834_list_python_python_2.7_python_3.x_wordle_game.txt
Q: DB query with unicode characters dosen't return value from python code A DB query dosen't return value from python code, but it returns on Oracle Developer console. The chinese parameter is the reason. Can you help encode it from python ? The N char didn't work with me. It still returns empty result. The query : S...
DB query with unicode characters dosen't return value from python code
A DB query dosen't return value from python code, but it returns on Oracle Developer console. The chinese parameter is the reason. Can you help encode it from python ? The N char didn't work with me. It still returns empty result. The query : SELECT COUNT(*) OVER() CNT, aid FROM rd_c_t_xl b WHERE name =N'根砧木' I use py...
[ "You need to set the NLS_LANG environment variable accordingly, most likely NLS_LANG=.AL32UTF8.\nSQL Developer is Java/JDBC based, it does not use the NLS_LANG settings, that's the reason why it works.\nSee also OdbcConnection returning Chinese Characters as \"?\"\n" ]
[ 0 ]
[]
[]
[ "cx_oracle", "oracle", "python", "python_unicode", "unicode" ]
stackoverflow_0074253346_cx_oracle_oracle_python_python_unicode_unicode.txt
Q: Pip is not working Within virtual environment (venv) I install python and set its path too. When I check in CMD pip, It shows me the following... C:\Users\maher>pip --version pip 21.1.2"" But after activation of virtual environment when I want to install any packeg using pip, thew see following error. (data) PS D...
Pip is not working Within virtual environment (venv)
I install python and set its path too. When I check in CMD pip, It shows me the following... C:\Users\maher>pip --version pip 21.1.2"" But after activation of virtual environment when I want to install any packeg using pip, thew see following error. (data) PS D:\Masters_FIT\4th\Webdatabese\Project\Code\Data_Collection...
[ "Please run:\npython -m ensurepip\n\nand if not resolve the issue run this:\nc:\\users\\maher\\appdata\\local\\programs\\python\\python37-32\\scripts\\easy_install.exe pip\n\n", "May be by some reason pip and wheel did not install in your venv.\nYou may try python -m pip install tablib to check if pip is working ...
[ 4, 0, 0 ]
[]
[]
[ "django", "pip", "python", "python_venv", "virtualenv" ]
stackoverflow_0067688785_django_pip_python_python_venv_virtualenv.txt
Q: Conditionally deploying AWS Config rules using cdk python I have a requirement to deploy config rules conditionally based on certain parameters. Here below is one config.ManagedRule(self, "AccessKeysRotated", identifier=config.ManagedRuleIdentifiers.ACCESS_KEYS_ROTATED, input_parameters={ "max_acc...
Conditionally deploying AWS Config rules using cdk python
I have a requirement to deploy config rules conditionally based on certain parameters. Here below is one config.ManagedRule(self, "AccessKeysRotated", identifier=config.ManagedRuleIdentifiers.ACCESS_KEYS_ROTATED, input_parameters={ "max_access_key_age": 60 }, maximum_execution_frequency=config....
[ "Sure. Create a aws_config_stack, which you deploy once per account/region pair.\nIn the constructor, get the environment's rule names from DynamoDB with a get_item SDK call. The boto3 command gets called at synth-time, which is keeping with CDK best practices.\nDefine the rules in whatever files you want. Wrap e...
[ 1, 0 ]
[]
[]
[ "aws_cdk", "aws_config", "python" ]
stackoverflow_0074242675_aws_cdk_aws_config_python.txt
Q: How to split data into train, val and test? I am trying to split my cats and dogs dataset into train, validation and test sets with a 0.8, 0.1, 0.1 split, I've made this function to do it. def split_data(main_dir, training_dir, validation_dir, test_dir): """ Splits the data into train and test sets Ar...
How to split data into train, val and test?
I am trying to split my cats and dogs dataset into train, validation and test sets with a 0.8, 0.1, 0.1 split, I've made this function to do it. def split_data(main_dir, training_dir, validation_dir, test_dir): """ Splits the data into train and test sets Args: main_dir (string): path containing the i...
[ "You are going wrong in the lines:\nfor element in test:\n copyfile(os.path.join(main_dir, element), os.path.join(validation_dir, element))\n\nIt should be test_dir not validation_dir ...\n", "other suggestion would be to use the train_test_split function on sklearn. This function split arrays or matrices...
[ 0, 0 ]
[]
[]
[ "dataset", "python" ]
stackoverflow_0074253743_dataset_python.txt
Q: TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents' So Im making a discord selfbot: prefix = input("\033[0;96m[~\033[0;96m] \033[0;96mPREFIX - ") client = commands.Bot(command_prefix=prefix, case_insensitive=True, self_bot=True) client.remove_command('help') header =...
TypeError: BotBase.__init__() missing 1 required keyword-only argument: 'intents'
So Im making a discord selfbot: prefix = input("\033[0;96m[~\033[0;96m] \033[0;96mPREFIX - ") client = commands.Bot(command_prefix=prefix, case_insensitive=True, self_bot=True) client.remove_command('help') header = {"Authorization": f'Bot {token}'} os.system('cls' if os.name == 'nt' else 'clear') os....
[ "You need to specify the intents argument in client, I did this:\nclient = commands.Bot(command_prefix=prefix, intents=discord.Intents.all(), case_insensitive=True, self_bot=True)\n\nIt should work.\n" ]
[ 0 ]
[ "The first part of your code should be:\nprefix = input(\"\\033[0;96m[~\\033[0;96m] \\033[0;96mPREFIX - \")\n\nintents = discord.Intents.all()\nintents.members = True\n\nclient = discord.Bot(command_prefix=prefix, case_insensitive=True,\n self_bot=True)\n\nThis should remove your error\n" ]
[ -1 ]
[ "discord.py", "python" ]
stackoverflow_0073927593_discord.py_python.txt
Q: finding indexes of 1's in a bit string and storing these indexes in a list -- Index should be started from 1 not 0 I am finding indexes of 1's in a bit string successfully. However, these indexes start from 0. Sample Data: initial_pop 000000000000000000000000000001011000000 000000001000000000000001000000000010000 ...
finding indexes of 1's in a bit string and storing these indexes in a list -- Index should be started from 1 not 0
I am finding indexes of 1's in a bit string successfully. However, these indexes start from 0. Sample Data: initial_pop 000000000000000000000000000001011000000 000000001000000000000001000000000010000 000000000000000000000000000000010011000 000000000000001001000000000000010000000 000000000000000000010000001000000010000 ...
[ "You can shift the initial data frame index by 1\ndf_initial_pop.index += 1\n\n", "You are good there, just make an increment while iterating.\nThis should work:\nreturn {i+1 for i,c in enumerate(chromosome) if c=='1'} \n\n" ]
[ 1, 1 ]
[]
[]
[ "genetic_algorithm", "genetic_programming", "python" ]
stackoverflow_0074253893_genetic_algorithm_genetic_programming_python.txt
Q: Overlay image with second image and apply pixel transparency - not working as expected Tested on matplotlib version: '3.5.2' and 3.6.0 This feels like a bug but I'm not sure if I'm missing something when using color images with an alpha mask. I have two images A and B. B should be applied as a overlay and has thre...
Overlay image with second image and apply pixel transparency - not working as expected
Tested on matplotlib version: '3.5.2' and 3.6.0 This feels like a bug but I'm not sure if I'm missing something when using color images with an alpha mask. I have two images A and B. B should be applied as a overlay and has three color channels. Most pixels are 0 which shall be filtered out by an alpha mask. Now the...
[ "I tested \"alpha\" as a 5x5 array, but the \"imshow\" simply ignores that array. So I joined \"B\" with an \"alpha\" column, so I got an (5 x 5 x 4) RGBA matrix, called \"C\".\nSo you don't need to pass a \"alpha\" array parameter in \"imshow\".\nimport matplotlib as m\nimport matplotlib.pyplot as plt\nimport nump...
[ 1 ]
[]
[]
[ "alpha", "matplotlib", "python" ]
stackoverflow_0074246305_alpha_matplotlib_python.txt
Q: Call python script in Julia I have a Gurobi model that I have implemented in Julia. This model is dependent on data input missed bags: Function deterministic_model_test(Path_to_data) include(Path_to_data) model = Model(Gurobi.Optimizer); # constraints... end I want to run a stochastic model, using th...
Call python script in Julia
I have a Gurobi model that I have implemented in Julia. This model is dependent on data input missed bags: Function deterministic_model_test(Path_to_data) include(Path_to_data) model = Model(Gurobi.Optimizer); # constraints... end I want to run a stochastic model, using the deterministic model (the struc...
[ "This documentation link should be of help: Running External Programs\nFor example, suppose test.csv has the following content:\nName,Hieght\nAlice, 1.69\nBob, 1.77\n\nThen you can use it within Julia with:\njulia> using CSV\n\njulia> using DataFrames\n\njulia> df = CSV.read(`cat test.csv`, DataFrame)\n2×2 DataFram...
[ 1 ]
[]
[]
[ "julia", "optimization", "python" ]
stackoverflow_0074253956_julia_optimization_python.txt
Q: print average and the cost per liter in the text file using python I'm trying to get the average of the cost value and the cost per liter. r = [] with open('petrolPrice.txt') as f1: r = f1.read() s = r.split() del s[0] s.pop(0) print(sum(s) / len(s)) # AVERAGE COST with open('petrolPr...
print average and the cost per liter in the text file using python
I'm trying to get the average of the cost value and the cost per liter. r = [] with open('petrolPrice.txt') as f1: r = f1.read() s = r.split() del s[0] s.pop(0) print(sum(s) / len(s)) # AVERAGE COST with open('petrolPrice.txt') as f1: r = f1.read() s = r.split() s.pop(0) ...
[ "import pandas as pd\nwith open(\"input.txt\") as f:\n lines = f.readlines()\n #get first value of every line as Liters \n liters = [(line.split()[0]) for line in lines if line.split()[0] != 'Liters']\n #get second value of every line as Cost\n cost = [(line.split()[1]) for line in lines if line.spli...
[ 0, 0 ]
[]
[]
[ "average", "math", "python", "text_files" ]
stackoverflow_0074253724_average_math_python_text_files.txt
Q: How to reach the mediafire direct link that is hidden behind a captcha? I wrote a python program to download a file from the internet : url = "http://download2163.mediafire.com/icum151v51zg/55rll9s5ioshz5n/Alcohol52_FE_2-0-3-6850.exe" file_name ='file' u = urllib2.urlopen(url) f = open(file_name, 'wb') buffer...
How to reach the mediafire direct link that is hidden behind a captcha?
I wrote a python program to download a file from the internet : url = "http://download2163.mediafire.com/icum151v51zg/55rll9s5ioshz5n/Alcohol52_FE_2-0-3-6850.exe" file_name ='file' u = urllib2.urlopen(url) f = open(file_name, 'wb') buffer = u.read() f.write(buffer) f.close() And it work correctly. The problem i...
[ "You Can Use Direct Download module from here for mediafire\nsimply download module by pip\npip install Direct-Download\n\nthen\nfrom Direct_Download import Direct\n\nurl = Direct()\n\nurl.mediafire('link')\n\n", "You'll need to look for something in the page that you can use to always identify the link. For exam...
[ 1, 0 ]
[]
[]
[ "captcha", "download", "python" ]
stackoverflow_0031614540_captcha_download_python.txt
Q: How to filter the even and positive numbers from a list using functions Given the list of integers stored in the variable numbers, declare the variable result1 and initialize the values ​​of the initial list containing only the even positive numbers, respecting the initial order. numbers = [-85,34,-7,-6,57,-6,-65,...
How to filter the even and positive numbers from a list using functions
Given the list of integers stored in the variable numbers, declare the variable result1 and initialize the values ​​of the initial list containing only the even positive numbers, respecting the initial order. numbers = [-85,34,-7,-6,57,-6,-65,-49,-51,79,90,-75,33,36,9,30,-61,-66,95 .15,-56.45,-21,-81,-83,-31.82,-92,21....
[ "The problem with your code is that your filterList function takes a function and a list of ints as an argument (type annotations added below for clarity):\nfrom typing import Callable\n\ndef filterList(p: Callable[[int], bool], xs: list[int]) -> list[int]:\n return [x for x in xs if p(x)]\n\nbut you're calling ...
[ 1, 0, -3 ]
[]
[]
[ "filter", "function", "list", "python" ]
stackoverflow_0074253536_filter_function_list_python.txt
Q: appending to the list in dataframe I have dataframe in following way: vals = [[100,200], [100,200],[100,200]] df = pd.DataFrame({'y':vals}) df['x'] = [1,2,3] df how can I append y values to the lists in x column, so my final values are in the following shape? thanks A: this would work import pandas as pd va...
appending to the list in dataframe
I have dataframe in following way: vals = [[100,200], [100,200],[100,200]] df = pd.DataFrame({'y':vals}) df['x'] = [1,2,3] df how can I append y values to the lists in x column, so my final values are in the following shape? thanks
[ "this would work\nimport pandas as pd\n\nvals = [[100,200], [100,200],[100,200]]\n\ndf = pd.DataFrame({'y':vals})\ndf['x'] = [1,2,3]\n\ndf[\"last\"] = [ y + [x] for x, y in zip(df[\"x\"], df[\"y\"]) ] \n\ndf\n\n\n", "Try:\ndf[\"last\"] = df.apply(lambda v: [*v.y, v.x], axis=1)\nprint(df)\n\nPrints:\n y...
[ 1, 1 ]
[]
[]
[ "dataframe", "list", "python" ]
stackoverflow_0074253046_dataframe_list_python.txt
Q: Split text in front of a particle/word A normal split: s = "/works/proj/kod/resources/excel/words/tam.xls" p = s.split("/kod") print(p) Result ['/works/proj', '/resources/excel/words/tam.xls'] What I want to obtain is, a split in front of the passed particle/word.: Example: ['/works/proj', '/kod/resources/excel...
Split text in front of a particle/word
A normal split: s = "/works/proj/kod/resources/excel/words/tam.xls" p = s.split("/kod") print(p) Result ['/works/proj', '/resources/excel/words/tam.xls'] What I want to obtain is, a split in front of the passed particle/word.: Example: ['/works/proj', '/kod/resources/excel/words/tam.xls']
[ "You could just append the seperator to the result afterwards:\ns = \"/works/proj/kod/resources/excel/words/tam.xls\"\np = s.split(\"/kod\")\np[1] = \"/kod\" + p[1]\nprint(p)\n\nThe result is this:\n['/works/proj', '/kod/resources/excel/words/tam.xls']\n\n", "It seems like you are working with paths and files so ...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074253882_python.txt
Q: Playwright: click on element within one/multiple elements using Python My goal is to web scrape a dynamic web page's HTML using Playwright for Python. Within an ordered list, there are multiple list items, and each contains multiple spans, of which one span has a button / link. Once there is a click on the button,...
Playwright: click on element within one/multiple elements using Python
My goal is to web scrape a dynamic web page's HTML using Playwright for Python. Within an ordered list, there are multiple list items, and each contains multiple spans, of which one span has a button / link. Once there is a click on the button, it will execute further code and scrape the HTML using BeautifulSoup. Here ...
[ "I may be wrong on this but let's say the button you are trying to click has link which will redirect you to another page/site and you want to go to that link. You should take the attribute value of the selector and just navigate there.\nCheck here for more details : https://playwright.dev/python/docs/api/class-pag...
[ 0, 0 ]
[]
[]
[ "html", "playwright", "playwright_python", "python", "web_scraping" ]
stackoverflow_0074181699_html_playwright_playwright_python_python_web_scraping.txt
Q: Using pandas, I want to be able to highlight cells which contains "-->" in csv file I am using excel to open .csv files. I cannot download excel packages like openpyxl as it is not my server. When I open csv file through excel it does give me option to conditionally format it. So I am hoping to be able to do it th...
Using pandas, I want to be able to highlight cells which contains "-->" in csv file
I am using excel to open .csv files. I cannot download excel packages like openpyxl as it is not my server. When I open csv file through excel it does give me option to conditionally format it. So I am hoping to be able to do it through python code. I tried the following code but it didn't work # def highlight_cells(va...
[ "df1.drop([1,],axis=0, inplace=True)\ntry this to delete the second row\n" ]
[ 0 ]
[]
[]
[ "csv", "excel", "numpy", "pandas", "python" ]
stackoverflow_0074254076_csv_excel_numpy_pandas_python.txt
Q: How to have a table of content for python script inside vs code like in jupyter? I like jupyter lab since it has a table of content when using markdown cells. so for a big script file, it is easy to navigate the code using table of content. Now if I convert an ipynb file into a normal py file, inside vs code, is i...
How to have a table of content for python script inside vs code like in jupyter?
I like jupyter lab since it has a table of content when using markdown cells. so for a big script file, it is easy to navigate the code using table of content. Now if I convert an ipynb file into a normal py file, inside vs code, is it possible to have a table of content like in jupyter? any possible solution inside vs...
[ "with extension HTML Related Links v1.0.0 you can create a Table of Content in a View in the Explorer Bar (Next to OUTLINE)\nExample Python file:\n\"\"\"Awesome Python book Code\"\"\"\n\n# toc Chapter 1\ndef foo1():\n pass\n\n# toc Chapter 2\ndef bar2():\n pass\n# toc -- Chapter 2.1\ndef bar2Input():\n pass\n# t...
[ 1 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074230062_python_visual_studio_code.txt
Q: AssertionError: View function mapping is overwriting an existing endpoint function: I am creating an app with python and flask. I am getting the following error: Traceback (most recent call last): File "C:\Users\Albert\PycharmProjects\Carro\views_trips.py", line 10, in <module> def index(): File "C:\Users\...
AssertionError: View function mapping is overwriting an existing endpoint function:
I am creating an app with python and flask. I am getting the following error: Traceback (most recent call last): File "C:\Users\Albert\PycharmProjects\Carro\views_trips.py", line 10, in <module> def index(): File "C:\Users\Albert\PycharmProjects\Carro\venv\lib\site-packages\flask\scaffold.py", line 439, in deco...
[ "Instead of running the file with the routes instead of the correct script below:\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_wtf.csrf import CSRFProtect\nfrom flask_bcrypt import Bcrypt\n\napp = Flask(__name__)\napp.config.from_pyfile('config.py')\n\ndb = SQLAlchemy(app)\n \nfro...
[ 0, 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074200947_flask_python.txt
Q: Dictionary-based compression in Python to compress short strings individually I have millions of < 20 char strings, and I want to compress each of them individually. Using zlib or lz4 on each string individually doesn't work: the output is bigger than the input: inputs = [b"hello world", b"foo bar", b"HELLO foo ba...
Dictionary-based compression in Python to compress short strings individually
I have millions of < 20 char strings, and I want to compress each of them individually. Using zlib or lz4 on each string individually doesn't work: the output is bigger than the input: inputs = [b"hello world", b"foo bar", b"HELLO foo bar world", b"bar foo 1234", b"12345 barfoo"] import zlib for s in inputs: c = zl...
[ "Python's zlib interface does in fact provide zdict parameters for compressobj and decompressobj, as of version 3.3 (released ten years ago).\nYou can provide up to a 32K dictionary to aid in compressing short strings. I would also recommend the use of raw deflate streams to minimize the size (wbits=-15).\nYou can ...
[ 3, 0, 0 ]
[]
[]
[ "compression", "lz4", "python", "zlib" ]
stackoverflow_0074253737_compression_lz4_python_zlib.txt
Q: Changing The Download Path After Opening Selenium Firefox Browser I have a collection of files that i download with a loop. I want to folder these files separately. Before the browser opens, I can change the default download path with the options parameter. However, I want to folder the files I will download separ...
Changing The Download Path After Opening Selenium Firefox Browser
I have a collection of files that i download with a loop. I want to folder these files separately. Before the browser opens, I can change the default download path with the options parameter. However, I want to folder the files I will download separately after the browser is opened. Can you please help? ` optns = Optio...
[ "You can not do that.\nOnce driver object instance is created by browser = webdriver.Firefox(options=optns) you can no more change it settings.\nThe only ways you can do here are:\n\nre-define optns.set_preference(\"browser.download.dir\", \"/Users/emrevolkanucar/Work/Ekap Py/Files\") and then create a new driver i...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_firefoxdriver", "selenium_webdriver" ]
stackoverflow_0074254290_python_selenium_selenium_firefoxdriver_selenium_webdriver.txt
Q: Accessing Django Form Error Message in View In my view I can access form['item'].errors and it gives me something like: > form.is_valid() False > > e = form['name'].errors > > print e <ul class="errorlist"><li>There already exists an item with this name. Try a different one.</li></ul> > > e.as_text() * name\n ...
Accessing Django Form Error Message in View
In my view I can access form['item'].errors and it gives me something like: > form.is_valid() False > > e = form['name'].errors > > print e <ul class="errorlist"><li>There already exists an item with this name. Try a different one.</li></ul> > > e.as_text() * name\n * There already exists an item with this name. Tr...
[ "I believe you are looking for as_data().\nFor the whole form:\nprint(form.errors.as_data())\n\n{'foo': [ValidationError([u'This is an error.'])], 'bar': [ValidationError([u'This is another error.'])]}\n\nFor just a field:\nfor e in form.errors['foo'].as_data():\n print e\n\n[u'This field is required.']\n\n", ...
[ 18, 0 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0033271560_django_django_forms_django_views_python.txt
Q: While loops in python while condition being at the end I’m trying to write a program that has while true: at the start and then at the end asks the user if they want to repeat. While True: print(“I will list the prime numbers between 0 and N”) N=input(“up to what number will I list the prime numbers?”) print (...
While loops in python while condition being at the end
I’m trying to write a program that has while true: at the start and then at the end asks the user if they want to repeat. While True: print(“I will list the prime numbers between 0 and N”) N=input(“up to what number will I list the prime numbers?”) print (“prime numbers between 0 and”,N,” are:”) for no in range (2...
[ "Here's a fixed version, with fixes commented:\nwhile True: # needs to be 'while', not 'While'!\n print(\"I will list the prime numbers between 0 and N\") # use regular \"\", not “”\n N = int(input(\"up to what number will I list the prime numbers?\")) # make it an int!\n\n print(\"prime numbers between...
[ 0 ]
[ "Instead of using True as the while condition, use a variable as the condition such as:\nwhile run\n\nIf you use True as the while condition True will always be true, so you have to use a variable in order for it to change.\nUpdated Code\nrun = True\nWhile run:\n print(“I will list the prime numbers between 0 and N...
[ -2 ]
[ "break", "conditional_statements", "if_statement", "python", "while_loop" ]
stackoverflow_0074254160_break_conditional_statements_if_statement_python_while_loop.txt
Q: Unable to save plots from a Jupyter notebook in Visual Studio Code I couldn't find any light on this topic. After a clean restart in a new laptop I'm unable to download plots from a Jupyter notebook from Visual Studio Code. According to the official docs and my past experiences with vscode this is as simple as cli...
Unable to save plots from a Jupyter notebook in Visual Studio Code
I couldn't find any light on this topic. After a clean restart in a new laptop I'm unable to download plots from a Jupyter notebook from Visual Studio Code. According to the official docs and my past experiences with vscode this is as simple as click on the save icon of the output of the cell o double click on the plot...
[ "I had the same problem but it was suddenly resolved.\nI think it is because the renderer of plots is builtin one instead of Jupyter Notebook Renderer.\nI'm not sure if the following procedure is correct, because I couldn't restore the condition before it was fixed.\n\nTurn ON jupyter.generateSVGPlots.\nRestart not...
[ 0 ]
[]
[]
[ "jupyter_notebook", "python", "vscode_settings" ]
stackoverflow_0070944694_jupyter_notebook_python_vscode_settings.txt
Q: Python web-scraper applied through Visual Studio question I have this web scraper program in python, but it prints both tennis players Felix and Alexander. I would like to only print the first available tennis player as a separate item and exclude all the ones after it, so what do I need change in the code to do t...
Python web-scraper applied through Visual Studio question
I have this web scraper program in python, but it prints both tennis players Felix and Alexander. I would like to only print the first available tennis player as a separate item and exclude all the ones after it, so what do I need change in the code to do this? To note, I did this through Visual Studio 2022 and applied...
[ "Instead of the loop, just do\nprint(soup.h2.text.strip())\n\n", "Instead of looping through each tag individually you can use the select() function to find that specific tag and print the first one.\nimport requests\nfrom bs4 import BeautifulSoup\n\nresponse = requests.get(\"https://www.betexplorer.com/tennis/at...
[ 1, 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074254298_beautifulsoup_python_web_scraping.txt
Q: TypeError: event() missing 1 required positional argument: 'coro' discord.py having problems fixing So, I just started coding a discord bot in python. I've done this several times before, but when I tried to run the code this error message came up. TypeError: event() missing 1 required positional argument: 'coro' ...
TypeError: event() missing 1 required positional argument: 'coro' discord.py having problems fixing
So, I just started coding a discord bot in python. I've done this several times before, but when I tried to run the code this error message came up. TypeError: event() missing 1 required positional argument: 'coro' This is my code: #import import discord import os #client client = discord.Client @client.event async ...
[ "Your client variable is now just a reference to the discord.Client class, you need an instance of it.\nclient = discord.Client # This doesn't do much of anything\nclient = discord.Client(here, be, arguments) # This creates an instance of a class\n\n", "The way you are defining your client is what is causing th...
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074251979_discord_discord.py_python.txt
Q: Undetected Chromedriver Doesn't work even with the script they provide Hi I'm using undetected_chromedriver in my python script, but about a month ago I ran into a problem. It was working fine, until one day the script displayed this error Traceback (most recent call last): File "D:\New folder\main.py", line 3,...
Undetected Chromedriver Doesn't work even with the script they provide
Hi I'm using undetected_chromedriver in my python script, but about a month ago I ran into a problem. It was working fine, until one day the script displayed this error Traceback (most recent call last): File "D:\New folder\main.py", line 3, in <module> driver = uc.Chrome() ^^^^^^^^^^^ File "C:\Us...
[ "Use driver = uc.Chrome(use_subprocess=True) instead of driver = uc.Chrome()\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "undetected_chromedriver" ]
stackoverflow_0074199944_python_selenium_selenium_chromedriver_selenium_webdriver_undetected_chromedriver.txt