content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to run a Python project from GitHub to VSCode I would like to run this project from Github to VSCode, I have cloned the repository, installed Python from the Microsoft app store, but I still get some error like this 1 and 2 and warnings like this and im cannot run the project. Can you help me with this ? A:...
How to run a Python project from GitHub to VSCode
I would like to run this project from Github to VSCode, I have cloned the repository, installed Python from the Microsoft app store, but I still get some error like this 1 and 2 and warnings like this and im cannot run the project. Can you help me with this ?
[ "The project you have installed seems to use modules.\nAfter reading the above, I recommend you install all imported modules\nEX:\nimport numpy as np\narr = np.array([1, 2, 3, 4, 5])\nprint(arr)\nprint(type(arr))\n\nYou would input pip install numpy in order to install the module.\n", "Go through the entire code ...
[ 1, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074293533_python_visual_studio_code.txt
Q: How to pad all tensors to accommodate all sizes How do I pad two tensors of the same shape such that they both have the same size? I currently receive an error for the following code (I can't use for loops in graph mode): def match_size(self, x, y): d = tf.maximum(tf.subtract(y.shape, x.shape), 0) x = tf.p...
How to pad all tensors to accommodate all sizes
How do I pad two tensors of the same shape such that they both have the same size? I currently receive an error for the following code (I can't use for loops in graph mode): def match_size(self, x, y): d = tf.maximum(tf.subtract(y.shape, x.shape), 0) x = tf.pad(x, [[0, i] for i in d]) d = tf.maximum(tf.subt...
[ "Using ragged.stack:\ndef match_size(x, y):\n new_axis = tf.argsort(tf.abs(tf.constant(x.shape) - tf.constant(y.shape)), direction='DESCENDING')\n x_y = tf.ragged.stack([tf.transpose(x, new_axis),tf.transpose(y, new_axis)])\n x,y = x_y.to_tensor(0.)\n return tf.transpose(x, tf.argsort(new_axis)), tf.transpo...
[ 0 ]
[]
[]
[ "padding", "python", "tensorflow" ]
stackoverflow_0074292911_padding_python_tensorflow.txt
Q: Python - Increasing combinations of two lists I'm trying to create combinations of two lists. List A should be increasing, or a sliding window if you will. List B is static. Where List A can have any number of values. My question seems to be a different than what I see already posted, as I am using a sliding windo...
Python - Increasing combinations of two lists
I'm trying to create combinations of two lists. List A should be increasing, or a sliding window if you will. List B is static. Where List A can have any number of values. My question seems to be a different than what I see already posted, as I am using a sliding window on one list and keeping the other list static, so...
[ "Its complicated to understand this increasing combinations but once you understand it, you will feel it easy\nLet me help you to understand the logic behind this\nfrom itertools import combinations\nfrom collections.abc import Iterable\n\nlistA = [\"Val1\", \"Val2\", \"Val3\"]\nlistB = [0, 1]\n\ndef perm(l, k):\n ...
[ 1, 1 ]
[]
[]
[ "combinations", "list", "python", "sliding_window" ]
stackoverflow_0074292649_combinations_list_python_sliding_window.txt
Q: NumPy random shuffle rows independently I have the following array: import numpy as np a = np.array([[ 1, 2, 3], [ 1, 2, 3], [ 1, 2, 3]]) I understand that np.random.shuffle(a.T) will shuffle the array along the row, but what I need is for it to shuffe each row idependently. How...
NumPy random shuffle rows independently
I have the following array: import numpy as np a = np.array([[ 1, 2, 3], [ 1, 2, 3], [ 1, 2, 3]]) I understand that np.random.shuffle(a.T) will shuffle the array along the row, but what I need is for it to shuffe each row idependently. How can this be done in numpy? Speed is critical...
[ "import numpy as np\nnp.random.seed(2018)\n\ndef scramble(a, axis=-1):\n \"\"\"\n Return an array with the values of `a` independently shuffled along the\n given axis\n \"\"\" \n b = a.swapaxes(axis, -1)\n n = a.shape[axis]\n idx = np.random.choice(n, n, replace=False)\n b = b[..., idx]\n ...
[ 6, 2, 1, 1, 1 ]
[ "As of NumPy 1.20.0 released in January 2021 we have a permuted() method on the new Generator type (introduced with the new random API in NumPy 1.17.0, released in July 2019). This does exactly what you need:\nimport numpy as np\n\nrng = np.random.default_rng()\na = np.array([\n [1, 2, 3],\n [1, 2, 3],\n [...
[ -1 ]
[ "arrays", "numpy", "python", "random", "shuffle" ]
stackoverflow_0036272992_arrays_numpy_python_random_shuffle.txt
Q: Split string based on delimiters and do something based on number of splits python Assume I have the following list of strings: animals = [ 'rhino, grey, 30 July 2022', 'giraffe, 30 March 2022', 'bird', 'llama, brown, 8 April 2022', 'tiger' ] where the first item of the list (animal[0]) is the string rhino,grey,...
Split string based on delimiters and do something based on number of splits python
Assume I have the following list of strings: animals = [ 'rhino, grey, 30 July 2022', 'giraffe, 30 March 2022', 'bird', 'llama, brown, 8 April 2022', 'tiger' ] where the first item of the list (animal[0]) is the string rhino,grey,30 July 2022 , the second (animal[1]) is giraffe, 30 March 2022 and the third is bird a...
[ "The below code logic should work if your element misses birthday or color\nanimals = [\n'rhino, grey, 30 July 2022',\n'giraffe, 30 March 2022',\n'bird',\n'llama, brown, 8 April 2022',\n'tiger'\n]\n\nname = []\ncolor = []\nbirthday= []\n\nfor animal in animals:\n item_split = animal.split(\", \")\n \n name...
[ 1, 0, 0, 0 ]
[]
[]
[ "list", "python", "split" ]
stackoverflow_0074293201_list_python_split.txt
Q: How to display and change SensitivityLabel for a Word document (desktop)? I would like to know the sensitivity label of my current Word file, change it with a new value and save my file I start by opening a Word file # Opening a MS Word file in pywin32 from win32com.client import Dispatch myWord = Disp...
How to display and change SensitivityLabel for a Word document (desktop)?
I would like to know the sensitivity label of my current Word file, change it with a new value and save my file I start by opening a Word file # Opening a MS Word file in pywin32 from win32com.client import Dispatch myWord = Dispatch('Word.Application') myWord.Visible = 1 myWord.Documents.Open("C:/....
[ "This is the code I use with to apply sensitivity to .xlsx documents. Create a .docx file for each sensitivity type your company uses. Run the first function on each sensitivity type document you have to get your company's Sensitivity IDs per type. You then update the dictionary in the second function with the ap...
[ 0 ]
[]
[]
[ "azure_information_protection", "ms_word", "python", "python_3.x", "win32com" ]
stackoverflow_0073744855_azure_information_protection_ms_word_python_python_3.x_win32com.txt
Q: Jinja2Templates TemplateNotFound and Docker My directory sturcture: . |--app | |--__init__.py | |--main.py | |--templates | |--index.html | |--Dockerfile |--requirements.txt When I try to access this at localhost, I get the following error: jinja2.exceptions.TemplateNotFound: /code/app/templates/in...
Jinja2Templates TemplateNotFound and Docker
My directory sturcture: . |--app | |--__init__.py | |--main.py | |--templates | |--index.html | |--Dockerfile |--requirements.txt When I try to access this at localhost, I get the following error: jinja2.exceptions.TemplateNotFound: /code/app/templates/index.html In main.py I have the following lines of...
[ "You can try logging into your container to see what the actual path is and then use that.\ndocker ps -a # will give you the container id\ndocker exec -it <container-id> /bin/bash # you are inside the container\n\npwd # you get the current directory from your Dockerfile it looks like it will be /code\n\nYou don't ...
[ 1 ]
[]
[]
[ "docker", "fastapi", "jinja2", "python" ]
stackoverflow_0070342097_docker_fastapi_jinja2_python.txt
Q: How to refer to relative paths of resources when working with a code repository We are working with a code repository which is deployed to both Windows and Linux - sometimes in different directories. How should one of the modules inside the project refer to one of the non-Python resources in the project (CSV fil...
How to refer to relative paths of resources when working with a code repository
We are working with a code repository which is deployed to both Windows and Linux - sometimes in different directories. How should one of the modules inside the project refer to one of the non-Python resources in the project (CSV files, etc.)? If we do something like: thefile = open('test.csv') or: thefile = open('....
[ "Try to use a filename relative to the current files path. Example for './my_file':\nfn = os.path.join(os.path.dirname(__file__), 'my_file')\n\nIn Python 3.4+ you can also use pathlib:\nfn = pathlib.Path(__file__).parent / 'my_file'\n\n", "If you are using setup tools or distribute (a setup.py install) then the \...
[ 285, 52, 21, 15, 6, 2, 1, 0, 0 ]
[ "I spent a long time figuring out the answer to this, but I finally got it (and it's actually really simple):\nimport sys\nimport os\nsys.path.append(os.getcwd() + '/your/subfolder/of/choice')\n\n# now import whatever other modules you want, both the standard ones,\n# as the ones supplied in your subfolders\n\nThis...
[ -5 ]
[ "path", "python", "relative_path" ]
stackoverflow_0001270951_path_python_relative_path.txt
Q: Seaborn - ytickabels are cut off I have the following code to create a heatmap with seaborn! unfourtunately my y-ticklabels are long names, and are cut off from the figure as shown in the attached image! seasons = ['yearly','djf','mam','jja','son'] for season_index,season in enumerate(['yearly','djf','mam','jja','...
Seaborn - ytickabels are cut off
I have the following code to create a heatmap with seaborn! unfourtunately my y-ticklabels are long names, and are cut off from the figure as shown in the attached image! seasons = ['yearly','djf','mam','jja','son'] for season_index,season in enumerate(['yearly','djf','mam','jja','son']): im = sns.heatmap(bias[:,se...
[ "plt.tight_layout()\n\nthis worked, thank you ver ymuch to Nikita Shabankin!\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python", "seaborn" ]
stackoverflow_0074293082_matplotlib_python_seaborn.txt
Q: How to send a code request in Python Telethon What I need I want to add the ability for users on website to add telegram phone numbers for Telethon I want to do it the following way: First page: site.com/add_phone/. Here the user enters the phone number and the script sends code request. client.send_code_request(p...
How to send a code request in Python Telethon
What I need I want to add the ability for users on website to add telegram phone numbers for Telethon I want to do it the following way: First page: site.com/add_phone/. Here the user enters the phone number and the script sends code request. client.send_code_request(phone) Second page: site.com/add_phone_2/. Here the ...
[ "Do not call start.\nYou need to break this in two steps\n1. Generate OTP\nclient = TelegramClient(session_file_path, api_key, api_hash)\nawait client.connect()\nresult = await client.send_code_request('+91...your phone', force_sms=True)\nphone_hash = result.phone_code_hash\n\nYou will need phone_code_hash also to ...
[ 0 ]
[]
[]
[ "python", "telethon" ]
stackoverflow_0074265086_python_telethon.txt
Q: Different questions about pandas pivot tables Here's my df: df=pd.DataFrame( { 'Color': ['red','blue','red','red','green','red','yellow'], 'Type': ['Oil', 'Aluminium', 'Oil', 'Oil', 'Cement Paint', 'Synthetic Rubber', 'Emulsion'], 'Finish' : ['Satin', 'Matte', 'Matte', 'Satin', 'Semi-gl...
Different questions about pandas pivot tables
Here's my df: df=pd.DataFrame( { 'Color': ['red','blue','red','red','green','red','yellow'], 'Type': ['Oil', 'Aluminium', 'Oil', 'Oil', 'Cement Paint', 'Synthetic Rubber', 'Emulsion'], 'Finish' : ['Satin', 'Matte', 'Matte', 'Satin', 'Semi-gloss', 'Satin', 'Satin'], 'Use' : ['Interior...
[ "Updated Answer\nThanks to a great suggestion by Rabinzel, we can also have today's date as a column header as well:\ndf = (df['Color'].value_counts().reset_index().pivot_table(index = ['index'], aggfunc = np.sum, margins=True, margins_name='Total')\n .assign(perc = lambda x: x['Color']/x.iloc[:-1]['Color'].sum() *...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "pivot_table", "python" ]
stackoverflow_0074293437_dataframe_pandas_pivot_table_python.txt
Q: Executing Python script in Azure I am new to azure and would need some guidance on running a python script to collect the VM list& count and send it to an email endpoint or slack. I have developed this script, and the required data is being fetched from my laptop by running code. My question here is, how do I impl...
Executing Python script in Azure
I am new to azure and would need some guidance on running a python script to collect the VM list& count and send it to an email endpoint or slack. I have developed this script, and the required data is being fetched from my laptop by running code. My question here is, how do I implement this in Azure and send the resul...
[ "This seems to be the answer to your question: Options for running Python scripts in Azure\nBut the Microsoft documentation seems to have a detailed guide on what you're trying to do here.\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_automation", "python", "python_3.x" ]
stackoverflow_0074293387_azure_azure_automation_python_python_3.x.txt
Q: Python regex for date and numbers, find the date format How to extract dates alone from text file using regex in Python 3? Below is my current code: import datetime from datetime import date import re s = "birthday on 20/12/2018 and wedding aniversry on 04/01/1997 and dob is on 09/07/1897" match = re.search(r'\d{...
Python regex for date and numbers, find the date format
How to extract dates alone from text file using regex in Python 3? Below is my current code: import datetime from datetime import date import re s = "birthday on 20/12/2018 and wedding aniversry on 04/01/1997 and dob is on 09/07/1897" match = re.search(r'\d{2}/\d{2}/\d{4}', s) date = datetime.datetime.strptime(match.g...
[ "Building on DirtyBit's answer. I found that if you make a minor change, it will pick up multiple date formats. Change the forward slash to a dot.\nimport re\ns = \"birthday on 20.12.2018 and wedding anniversary on 04-01-1997 and dob \nis on 09/07/1897\"\npattern = r'\\d{2}.\\d{2}.\\d{4}'\nprint(\"\\n\".join(re.fin...
[ 1, 0, 0 ]
[]
[]
[ "python", "python_3.x", "regex" ]
stackoverflow_0055334580_python_python_3.x_regex.txt
Q: How to call an open data element with python? I generated code that saves data from an array to a file as follows: with open(path + '/data_Sevol.csv', 'w', newline='') as csvfile: fieldnames = ['Sevol'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for i in range(...
How to call an open data element with python?
I generated code that saves data from an array to a file as follows: with open(path + '/data_Sevol.csv', 'w', newline='') as csvfile: fieldnames = ['Sevol'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for i in range(len(Sevol)): writer.writerow({'Sevol': Sev...
[ "data_Sevol is not a list it is a _csv.reader object. While it is iterable (for row in data_Sevol: works) it is not subscriptable (data_Sevol[1] doesn't work). You can fix it with\ndata_Sevol = list(data_Sevol)\n\nThen data_Sevol[1] should work.\nNote: you need to do conversion before the for loop, otherwise you'll...
[ 0 ]
[]
[]
[ "arrays", "csv", "jupyter", "pandas", "python" ]
stackoverflow_0074293823_arrays_csv_jupyter_pandas_python.txt
Q: Django: How do you use an image in your template and let your views.py know it was pressed like a button? I want to show an image that the user can click on that will act like a button and return the data to my views.py. For example, <input type="submit" value="Add Selected Other Service to Included Service" class...
Django: How do you use an image in your template and let your views.py know it was pressed like a button?
I want to show an image that the user can click on that will act like a button and return the data to my views.py. For example, <input type="submit" value="Add Selected Other Service to Included Service" class="button" name="Add Other Service"/> will create a very long button which I can "grab" in my views.py with: ...
[ "After trying different variations to see if I could get:\n <input type=\"image\" src=\"{% static 'addAndReturn.svg' %}\" width=\"48\" height=\"48\"\n name=\"addAndReturn\" class=\"btTxt submit\" title=\"Add & Return to Edit\"/>\n\nto work and looking for:\n add_and_return = request.POST.get('addAnd...
[ 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074293884_django_html_python.txt
Q: Building a set of tasks with asyncio, but total time takes longer than longest task In the following code, why does it take 10(0+1+2+3+4) seconds to finish, instead of 4 seconds, when I'm using asyncio? import asyncio,time async def say_after(delay, what): await asyncio.sleep(delay) print(f"what = {what},...
Building a set of tasks with asyncio, but total time takes longer than longest task
In the following code, why does it take 10(0+1+2+3+4) seconds to finish, instead of 4 seconds, when I'm using asyncio? import asyncio,time async def say_after(delay, what): await asyncio.sleep(delay) print(f"what = {what}, at {time.strftime('%X')}") background_tasks = set() async def main(): for i in ra...
[ "There is no reason to keep the background_tasks set if you are going to discard it after all tasks are done. Instead, I would use asyncio.gather\nasync def main():\n await asyncio.gather(*[\n say_after(delay=i, what=i) for i in range(5)\n ])\n\nIn this case, you are not holding additional variables an...
[ 0, 0 ]
[ "Execute tasks outside the loop\nimport asyncio,time\n\nasync def say_after(delay, what):\n await asyncio.sleep(delay)\n print(f\"what = {what}, at {time.strftime('%X')}\")\n\n\nbackground_tasks = set()\n\nasync def main():\n for i in range(5):\n task = asyncio.create_task(say_after(delay=i,what=i))...
[ -1 ]
[ "python", "python_asyncio" ]
stackoverflow_0074279897_python_python_asyncio.txt
Q: How to convert the dataframe column with delimiters into three columns? How to split the last three values of the Reference Column dataframe into three columns such as Code, PRODUCT, TYPE as shown below Df1: **Reference** Customer/FBG/COMC/APPLE/INTEREST/ Customer/FBG/PORT/APPLE/INTEREST/ Customer/...
How to convert the dataframe column with delimiters into three columns?
How to split the last three values of the Reference Column dataframe into three columns such as Code, PRODUCT, TYPE as shown below Df1: **Reference** Customer/FBG/COMC/APPLE/INTEREST/ Customer/FBG/PORT/APPLE/INTEREST/ Customer/FBG/PORT/APPLE/INTEREST/ Customer/FBG/AUD/5397/APPLE/INTEREST/ Custom...
[ "Better use str.extract:\ndf[['CODE', 'PRODUCT', 'TYPE']] = df['Reference'].str.extract('([^/]+)/([^/]+)/([^/]+)/?$')\n\nWith str.split you would have needed to slice afterwards, which is less efficient:\ndf[['CODE', 'PRODUCT', 'TYPE']] = df['Reference'].str.split('/', expand=True).iloc[:, -4:-1]\n\noutput:\n ...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074293861_dataframe_pandas_python.txt
Q: Property setter triggers infinite recursion, why? Using the @property + setter encapsulation, I need a class that raises an exception when someone tries to change the account_number. However, in the __init__ function, I need to set the value. This is the code, it generates recursion. class SingleBankAccount: ...
Property setter triggers infinite recursion, why?
Using the @property + setter encapsulation, I need a class that raises an exception when someone tries to change the account_number. However, in the __init__ function, I need to set the value. This is the code, it generates recursion. class SingleBankAccount: def __init__(self, account_number, account_balance)...
[ "You are setting the self.account_number property within the setter. The proper pythonic way is to use a \"private\" property:\nclass SingleBankAccount:\n \n def __init__(self, account_number, account_balance):\n self.account_number = account_number\n self.account_balance = account_balance\n ...
[ 1 ]
[]
[]
[ "getter_setter", "infinite_recursion", "python" ]
stackoverflow_0074293791_getter_setter_infinite_recursion_python.txt
Q: how to make binary to bit 8 in python i have variable contains with binary with type int ([101, 1101, 11001]) but i want to xor it with another variable, so i must change to string and add "0" so it has 8 number example 101 it'll become 00000101 i was trying change int to str but it cannot works. here's my code: d...
how to make binary to bit 8 in python
i have variable contains with binary with type int ([101, 1101, 11001]) but i want to xor it with another variable, so i must change to string and add "0" so it has 8 number example 101 it'll become 00000101 i was trying change int to str but it cannot works. here's my code: def bit8(input): print(input) y = st...
[ "You can simply try format\nl =[101, 1101, 11001]\n\nc = \"{:08d}\".format\nprint([c(item) for item in l])\n\noutput #\n['00000101', '00001101', '00011001']\n\nAs a function\ndef bit8(input):\n c = \"{:08d}\".format\n ou=([c(item) for item in input])\n\n return ou\n\nDriver code\nprint(bit8(l))\n\nzfill a...
[ 0, 0 ]
[]
[]
[ "binary", "bit", "converters", "python", "string" ]
stackoverflow_0074293665_binary_bit_converters_python_string.txt
Q: It is possible to find hidden value in js function via requests in python? Is it possible to download the code from the javascript function on the website through requests? What I mean: from requests_html import HTMLSession url = 'link' session = HTMLSession() r = session.get(url) r.html.render(sleep=2) print(r.h...
It is possible to find hidden value in js function via requests in python?
Is it possible to download the code from the javascript function on the website through requests? What I mean: from requests_html import HTMLSession url = 'link' session = HTMLSession() r = session.get(url) r.html.render(sleep=2) print(r.html.text) Output: Hello Some text on site function randomname() { if (checkbo...
[ "Given your output as:\noutput = \"\"\"\nHello\nSome text on site\nfunction randomname() { \nif (checkbox() == true) \ndocument.getElementById('randomcode').value = '123456789023'; \nelse alert('Checkbox not clicked!'); } \n\nrandomname(); \n\ncompletef(\"1823947239d23dc23dsar238rt3r\")\n\"\"\"\n\nYou can use a...
[ 0 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074293292_python_python_requests.txt
Q: How can I dynamically calculate font size depending on label height in tkinter? I'm working on a tkinter script that will display some text and an image below it, but some times the image won't exist. Either way I want the program to dynamically choose the font size based on the max size it could be whilst the tex...
How can I dynamically calculate font size depending on label height in tkinter?
I'm working on a tkinter script that will display some text and an image below it, but some times the image won't exist. Either way I want the program to dynamically choose the font size based on the max size it could be whilst the text still fitting within the label either in one line or wrapped as long as it fills al...
[ "If you want to measure the rendered width of a string of text in a specific font you can use the measure method on the font. The height is a property of the font which you can get via the metrics method of the font.\nfont = Font(...)\nwidth = font.measure(\"Hello, world\")\nheight = font.metrics()['linespace']\n\n...
[ 1 ]
[]
[]
[ "fonts", "python", "tkinter", "user_interface" ]
stackoverflow_0074291969_fonts_python_tkinter_user_interface.txt
Q: I am looking for a list of characters to make ascii art I coded a program to make ascii art and for the characters I have the following string: """.:-=+*#%@&""" But it's a pretty short one and I can't find one that's longer to make images a little more detailed than that Does anyone have this? (preferably put in o...
I am looking for a list of characters to make ascii art
I coded a program to make ascii art and for the characters I have the following string: """.:-=+*#%@&""" But it's a pretty short one and I can't find one that's longer to make images a little more detailed than that Does anyone have this? (preferably put in order (like the one I already have))
[ "string = ' !\"#$%&'()*+,-./0123456789:;<=>?@BCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïð[\\]^_`{|}~'\nYou can also use this website to get each ASCII code individually.\n", "In python you can access all ascii characters like this:\n>>> import string\n>>> str...
[ 1, 0, 0, 0 ]
[]
[]
[ "ascii", "python" ]
stackoverflow_0074293637_ascii_python.txt
Q: ResolvedPackNotFound python = 3.1 when install any package I'm running Python 3.10.4 and am unable to install just about package I was hoping to use, such as Streamlit, Oracle_CX, etc... does anyone have experience overcoming the ResolvePackageNotFound: - python 3.1 message? I was only able to successfully install...
ResolvedPackNotFound python = 3.1 when install any package
I'm running Python 3.10.4 and am unable to install just about package I was hoping to use, such as Streamlit, Oracle_CX, etc... does anyone have experience overcoming the ResolvePackageNotFound: - python 3.1 message? I was only able to successfully install plotly, seaborn, and a few other packages.
[ "Try with pip - pip streamlit .\nstreamlit have hardcore C dependencies..Even streamlit community suggets to install package with pip...Conda is best for installing like git or openjdk, c++ dependencies....Conda fails 70 - 80% of times while installing the libraries which are built on hardcore C dependencies\npip i...
[ 0 ]
[]
[]
[ "installation", "python", "streamlit" ]
stackoverflow_0074293850_installation_python_streamlit.txt
Q: How to handle large integers in python with Pandas? Problem I have an issue while creating a dataframe in pandas. I am creating a new null data frame df2 from an existing data frame df1 with the same columns as shown below: import pandas as pd import numpy as np df2 = df1.DataFrame(columns=df1.columns) Now while...
How to handle large integers in python with Pandas?
Problem I have an issue while creating a dataframe in pandas. I am creating a new null data frame df2 from an existing data frame df1 with the same columns as shown below: import pandas as pd import numpy as np df2 = df1.DataFrame(columns=df1.columns) Now while in a loop, I add another column which stores an integer ...
[ "The solution is to assign the 'new column' as an object before assignment of value and convert it to long integer after the assignment is done. I am not sure if this is the most efficient method. Open to better solutions. But it works.\ndf1 = pd.DataFrame(data={'A':[123123123123123123, 234234234234234234, 34534534...
[ 0 ]
[ "Try np.float\nnp.float64(123123123123123123123123)\n\n# Output\n1.2312312312312312e+23\n\n\n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0074291246_pandas_python.txt
Q: How can I create a plot that combines a plot of data, and a histogram of different data? I need to create a plot that has two y-axis, and a single x-axis. On one x/y-axis pair, I need to plot several sets data (with lines). On the other x/y-axis pair, I need to plot a histogram of a different data set. The intenti...
How can I create a plot that combines a plot of data, and a histogram of different data?
I need to create a plot that has two y-axis, and a single x-axis. On one x/y-axis pair, I need to plot several sets data (with lines). On the other x/y-axis pair, I need to plot a histogram of a different data set. The intention is to present several curves that represent the performance of several design variations, w...
[]
[]
[ "You'll need:\n\nto share x axis: https://matplotlib.org/stable/gallery/subplots_axes_and_figures/shared_axis_demo.html\n\nto adjust gap/space/padding between subplots:\nhttps://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots_adjust.html\n\nto Invert one of y axis (two options):\nhttps://matplotlib.org...
[ -1 ]
[ "matplotlib", "python", "seaborn" ]
stackoverflow_0074293661_matplotlib_python_seaborn.txt
Q: Load testing using Locust So I have been trying to do some load testing with Locust, and I got very different results in two scenarios - one using wait_time between 1 and 2 and other between 0.01 and 0.1. The actual SLA for the service is under 100ms. class PerformanceTest(HttpUser): wait_time = between(0.01, ...
Load testing using Locust
So I have been trying to do some load testing with Locust, and I got very different results in two scenarios - one using wait_time between 1 and 2 and other between 0.01 and 0.1. The actual SLA for the service is under 100ms. class PerformanceTest(HttpUser): wait_time = between(0.01, 0.1) # second case where wait t...
[ "wait_time is the amount of time in seconds between a user finishing its work and a new user being created to start the work again. The shorter the wait_time is, the closer you get to constant requests, a consistent barrage of users immediately starting up again when they finish. In your case, that would be 100 use...
[ 2 ]
[]
[]
[ "load_testing", "locust", "performance_testing", "python", "python_3.x" ]
stackoverflow_0074293325_load_testing_locust_performance_testing_python_python_3.x.txt
Q: Plotly: n qualitative colors I am using Plotly and Python 3 for data visualization. It is known to me that default number of colors in Plotly is 10 and are repeated in cycle if more elements than 10. I do not want to use this approach to bring more colors in my 3D scattegram: How to create discrete colormap with n...
Plotly: n qualitative colors
I am using Plotly and Python 3 for data visualization. It is known to me that default number of colors in Plotly is 10 and are repeated in cycle if more elements than 10. I do not want to use this approach to bring more colors in my 3D scattegram: How to create discrete colormap with n colors using Plotly cause the col...
[ "As Alec said in the comment, you can build your color palette. Alternatively, you can use one of the available discrete color maps.\nimport plotly.express as px\nimport numpy as np\n\nn = 100\nncat = 20\nxx = np.random.uniform(-10, 10, n)\nyy = np.random.uniform(-10, 10, n)\nzz = np.random.uniform(-10, 10, n)\ncc ...
[ 1 ]
[]
[]
[ "colors", "plotly", "python", "scatter_plot" ]
stackoverflow_0074277050_colors_plotly_python_scatter_plot.txt
Q: Dealing with 'OutOfBoundsDatetime: Out of bounds nanosecond timestamp:' I am working on a DataFrame looking at baseball games Date and their Attendance so I can create a Calendar Heatmap. Date Attendance 1 Apr 7 44723.0 2 Apr 8 42719.0 3 Apr 9 36139.0 4 Apr 10 41253.0 5 Apr 11 20480.0 I'v...
Dealing with 'OutOfBoundsDatetime: Out of bounds nanosecond timestamp:'
I am working on a DataFrame looking at baseball games Date and their Attendance so I can create a Calendar Heatmap. Date Attendance 1 Apr 7 44723.0 2 Apr 8 42719.0 3 Apr 9 36139.0 4 Apr 10 41253.0 5 Apr 11 20480.0 I've tried different solutions that I've come across... - df['Date'] = df['Date'...
[ "you can convert to datetime if you supply a format; Ex:\ndf\nOut[33]: \n Date Attendance\n1 Apr 7 44723.0\n2 Apr 8 42719.0\n3 Apr 9 36139.0\n4 Apr 10 41253.0\n5 Apr 11 20480.0\n\npd.to_datetime(df[\"Date\"], format=\"%b %d\")\nOut[35]: \n1 1900-04-07\n2 1900-04-08\n3 19...
[ 0 ]
[]
[]
[ "datetime", "heatmap", "pandas", "python" ]
stackoverflow_0074293196_datetime_heatmap_pandas_python.txt
Q: Extracting files from zip file from GET request I currently have a GET request to a URL that returns three things: .zip file, .zipsig file, and a .txt file. I'm only interested in the .zip file which has dozens of .json files. I would like to extract all these .json files, preferable directly into a single pandas ...
Extracting files from zip file from GET request
I currently have a GET request to a URL that returns three things: .zip file, .zipsig file, and a .txt file. I'm only interested in the .zip file which has dozens of .json files. I would like to extract all these .json files, preferable directly into a single pandas data frame, but extracting them into a folder also wo...
[ "I would do something like this. Obviously this is my test.zip file but the steps are:\n\nList the files from the archive using the .infolist() method on your z archive\nCheck if the filename ends with the json extension using .endswith('.json')\nExtract that filename with .extract(info.filename, info.filename)\n\...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "zip" ]
stackoverflow_0074292737_python_python_3.x_zip.txt
Q: How to delete pipeline execution records on SageMaker Studio? I want to delete pipeline execution records appearing on SageMaker Studio to keep order and remove unnecessary records. I am fine with doing it via python, but i also accept any other tool available. I know the possibility of deleting the entire pipelin...
How to delete pipeline execution records on SageMaker Studio?
I want to delete pipeline execution records appearing on SageMaker Studio to keep order and remove unnecessary records. I am fine with doing it via python, but i also accept any other tool available. I know the possibility of deleting the entire pipeline or the individual experiments generated for each step in it with ...
[ "There is no way to delete individual pipeline executions; it is an immutable history of executions, in the same way that Step Functions execution history cannot be deleted.\n" ]
[ 1 ]
[]
[]
[ "amazon_sagemaker", "amazon_sagemaker_studio", "boto3", "python" ]
stackoverflow_0074291051_amazon_sagemaker_amazon_sagemaker_studio_boto3_python.txt
Q: How can I style specific cells in a pandas dataframe, based on the value of the adjacent cells? I have a pandas dataframe in which, for some cells (mostly columns), I'd like to highlight any cells which are different than the cells to their right. I've looked at all manner of pandas styler info and can't work out ...
How can I style specific cells in a pandas dataframe, based on the value of the adjacent cells?
I have a pandas dataframe in which, for some cells (mostly columns), I'd like to highlight any cells which are different than the cells to their right. I've looked at all manner of pandas styler info and can't work out how to apply conditional formatting based on the value of cells in a particular relative position. Ca...
[ "IIUC, you can use:\nimport numpy as np\n\ndef color_right(df, exclude=None):\n cols = df.columns.difference([0]) if exclude else df.columns\n m = df[cols].ne(df[cols].shift(axis=1))\n return np.where((m&m.shift(-1, axis=1, fill_value=True)\n ).reindex(df.columns, axis=1, fill_value=Fals...
[ 0 ]
[]
[]
[ "pandas", "python", "styling" ]
stackoverflow_0074293689_pandas_python_styling.txt
Q: Why am I getting this Django custom command error: 'datetime.timezone' has no attribute 'now' Why am I getting the error "'datetime.timezone' has no attribute 'now'" when trying to run this custom command in Django that deletes guest accounts older than 30 days? It works elsewhere in views.py where I have imported...
Why am I getting this Django custom command error: 'datetime.timezone' has no attribute 'now'
Why am I getting the error "'datetime.timezone' has no attribute 'now'" when trying to run this custom command in Django that deletes guest accounts older than 30 days? It works elsewhere in views.py where I have imported it the same way. Do I have to import it differently since the command is in a different folder? (m...
[ "from django.utils import timezone\nYou need to import it like this, this is the doc\n", "Change imports to this:\nfrom django.utils import timezone\nfrom datetime import timedelta\n\nAnd it will work better. Django also uses datetime.\n" ]
[ 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074293911_django_python.txt
Q: How can I remove elements from a list that has certain substrings? I'm trying to filter a list using this line of code : list_categories = list(filter(lambda x: ('Article' not in x) and ('Biographie/Articles liés/C' not in x) and ('article' not in x ) and ('Catégorie' not in x) and ('Biographie/Articles liés/C' no...
How can I remove elements from a list that has certain substrings?
I'm trying to filter a list using this line of code : list_categories = list(filter(lambda x: ('Article' not in x) and ('Biographie/Articles liés/C' not in x) and ('article' not in x ) and ('Catégorie' not in x) and ('Biographie/Articles liés/C' not in x ) and ('wikipédia:' not in x) and ('Page' not in x) , l)) Basica...
[ "Don't force the lambda usage, and use all. str.casefold is used for case-insensitive comparison.\nSTOP_WORDS = ['article'.casefold(), 'biographie/articles liés/c'.casefold(),\n 'catégorie'.casefold(), 'wikipédia:'.casefold(), 'page'.casefold()]\n\ndef filterer(s):\n s = s.casefold()\n return all...
[ 0 ]
[]
[]
[ "lambda", "list", "optimization", "python", "string" ]
stackoverflow_0074294092_lambda_list_optimization_python_string.txt
Q: Using SQLAlchemy ORM for a non-primary key, unique, auto-incrementing id When I run the following code, I am expecting the first_name, and last_name to be a composite primary key and for the id to be an autoincrementing index for the row, but not to act as the primary key, as there the information in the rest of t...
Using SQLAlchemy ORM for a non-primary key, unique, auto-incrementing id
When I run the following code, I am expecting the first_name, and last_name to be a composite primary key and for the id to be an autoincrementing index for the row, but not to act as the primary key, as there the information in the rest of the table is what I need to define it's uniqueness, rather than the given ID. B...
[ "At the time of writing this, SQLAlchemy 1.1 does not support auto-incrementing on a non-primary key field.\n", "Postgresql 2022 answer:\nthe following code\nimport uuid\nfrom sqlalchemy import Integer, Column, String, Sequence\nfrom sqlalchemy.dialects.postgresql import UUID\n\nclass Test(Base):\n __tablename...
[ 7, 3, 0, 0 ]
[]
[]
[ "flask_sqlalchemy", "mysql", "python", "sqlalchemy" ]
stackoverflow_0041530854_flask_sqlalchemy_mysql_python_sqlalchemy.txt
Q: Scraping Javascript Website With BeautifulSoup 4 & Requests_HTML I'm learning how to build another scraper for another website, Reverb.com, after getting my scraper on another website to work properly. Reverb, however, has been more challenging to extract information from and the model with my old scraper isn't wo...
Scraping Javascript Website With BeautifulSoup 4 & Requests_HTML
I'm learning how to build another scraper for another website, Reverb.com, after getting my scraper on another website to work properly. Reverb, however, has been more challenging to extract information from and the model with my old scraper isn't working the same. I did some research and using requests_html instead of...
[ "In order to extract all the pages of search results, you need to extract the link of the next page and keep going until there is no next page available. We can do this using a while loop and checking the existence of the next anchor tag.\nThe following script performs the loop and also adds the results to the csv....
[ 2 ]
[]
[]
[ "beautifulsoup", "javascript", "python", "python_requests_html", "web_scraping" ]
stackoverflow_0061923065_beautifulsoup_javascript_python_python_requests_html_web_scraping.txt
Q: How to replace 'FEEDS' in scrapy version 2.X with 'FEED_URI & 'FEED_FORMAT'? GUI app using Python Tkinter I am trying to learn to make a Scrapy Desktop app using Python Tk inter. So, I'm trying to run this prebuild Scrapy desktop app using Python Tkinter. While saving the output, there is an issue with the "FEEDS"...
How to replace 'FEEDS' in scrapy version 2.X with 'FEED_URI & 'FEED_FORMAT'? GUI app using Python Tkinter
I am trying to learn to make a Scrapy Desktop app using Python Tk inter. So, I'm trying to run this prebuild Scrapy desktop app using Python Tkinter. While saving the output, there is an issue with the "FEEDS". The below-mentioned function does save the output file by choosing the specific extension and saving it to a ...
[ "You would instead use\n\nsettings.set(\"FEEDS\", {\n feed_uri: {\n 'format': chosen_format,\n 'encoding': 'utf8'\n }\n})\n\nand include any other settings that are appropriate.\nRefer to the scrapy docs for available options: FEEDS\n" ]
[ 1 ]
[]
[]
[ "python", "scrapy", "tkinter" ]
stackoverflow_0074293975_python_scrapy_tkinter.txt
Q: copying modules from python 3.10 to 3.11 So basically I installed 3.11(which is the latest release). But when I executed the exe file it said "install now" instead of "update now"(which I saw while updating from 3.10.5 to 3.10.8. Now installing would create a whole new directory and all of my important modules are...
copying modules from python 3.10 to 3.11
So basically I installed 3.11(which is the latest release). But when I executed the exe file it said "install now" instead of "update now"(which I saw while updating from 3.10.5 to 3.10.8. Now installing would create a whole new directory and all of my important modules are in the dir "python3.10" and I'm too lazy to "...
[ "Assuming both interpreters are globally available, for example as python3.10 and python3.11\nGet a list of all the modules installed on the 3.10 interpreter with pip freeze and then install them with 3.11's pip:\npython3.10 -m pip freeze > requirements.txt\npython3.11 -m pip install -r requirements.txt\n\nOf cours...
[ 4, 0 ]
[]
[]
[ "module", "pip", "python" ]
stackoverflow_0074190755_module_pip_python.txt
Q: How do you make sure that indented if statements still trigger even if the first statement is satisfied? My game seems to just stop after module 1 if I survive and I can't see what the problem is. The game is supposed to go to each part one after the other. However, when you survive the module, it does not continu...
How do you make sure that indented if statements still trigger even if the first statement is satisfied?
My game seems to just stop after module 1 if I survive and I can't see what the problem is. The game is supposed to go to each part one after the other. However, when you survive the module, it does not continue. Here is the code: #CAVEGAME #Import import random import pickle #Introduction print("--------CaveGame V.4.1...
[ "Sticking to just the question; where you have \"part2\" you should dedent everything below that.\nIts hard to know what sort of explanation will help you most but with something like this I like to think of index cards.\nEvery \"If\" creates two index cards. One for when it is true, one for when it is false.\nYou...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074294072_python.txt
Q: What purpose of a "return" in this case? I have a simple function which converts combination of characters to emojis. I don't understand completely a purpose of a "return" function ? Below i provide a piece of code in which im experimenting. def emoji_converter(message): words = message.split(" ") emojis =...
What purpose of a "return" in this case?
I have a simple function which converts combination of characters to emojis. I don't understand completely a purpose of a "return" function ? Below i provide a piece of code in which im experimenting. def emoji_converter(message): words = message.split(" ") emojis = { ":)": "", ":(": "" } ...
[ "print will output whatever the argument passed to it evaluates to. In this case, you're passing it a function invocation (i.e. \"calling\" the function), so it will print whatever is returned from the function.\nIf you omit the return, then there is nothing to print. So in this case, you cannot replace the return ...
[ 0 ]
[]
[]
[ "function", "python", "return", "return_value" ]
stackoverflow_0074294159_function_python_return_return_value.txt
Q: Is there an index function in yfinance for pulling previous years dividend? Or any dividend functions? div_growth_rate = WMT.info['returnOnEquity'] * (1-WMT.get_info()['payoutRatio']) div_growth_rate A: You can obtain dividends from yahoo finance using the yfinance library. Just do: import yfinance as yf msft = ...
Is there an index function in yfinance for pulling previous years dividend? Or any dividend functions?
div_growth_rate = WMT.info['returnOnEquity'] * (1-WMT.get_info()['payoutRatio']) div_growth_rate
[ "You can obtain dividends from yahoo finance using the yfinance library. Just do:\nimport yfinance as yf\nmsft = yf.Ticker(\"MSFT\")\nmsft.dividends\n\nOutput:\nDate\n2003-02-19 0.08\n2003-10-15 0.16\n2004-08-23 0.08\n2004-11-15 3.08\n2005-02-15 0.08\n ... \n2021-08-18 0.56\n2021-11-1...
[ 0 ]
[]
[]
[ "python", "python_3.x", "quantitative_finance", "yahoo_finance", "yfinance" ]
stackoverflow_0074197495_python_python_3.x_quantitative_finance_yahoo_finance_yfinance.txt
Q: How to get IP addresses from ip2location database? I have downloaded IP2Proxy™ LITE database in csv format, below is the data in it could anybody please help me how to read the ip addresses using python or powershell as it seems in plain number. Also please explain what does 1st to column represents. A: Here's ...
How to get IP addresses from ip2location database?
I have downloaded IP2Proxy™ LITE database in csv format, below is the data in it could anybody please help me how to read the ip addresses using python or powershell as it seems in plain number. Also please explain what does 1st to column represents.
[ "Here's how you can convert those values into a string representation of an IPv4 address:\ndef convert(ip):\n def _genip(n):\n for shift in range(24, -8, -8):\n yield f'{(n >> shift) & 0xff:03d}'\n return '.'.join(list(_genip(int(ip))))\nprint(convert('34676992'))\n\nOutput:\...
[ 1 ]
[]
[]
[ "download", "ip", "ip2location", "python" ]
stackoverflow_0074290268_download_ip_ip2location_python.txt
Q: Python/ Pandas: Making a contingency table with multiple variables My dataframe has 4 columns (one dependent variable and 3 independent). Here's a sample: My desired output is a contingency table, as follows: I can only seem to get a contingency table using one independent variable- using the following code (my ...
Python/ Pandas: Making a contingency table with multiple variables
My dataframe has 4 columns (one dependent variable and 3 independent). Here's a sample: My desired output is a contingency table, as follows: I can only seem to get a contingency table using one independent variable- using the following code (my df is called 'table') pd.crosstab(index=table['Dvar'],columns=table['Var...
[ "This is not a good use case for crosstab as you already have your contingency table (just not aggregated), rather use a groupby.sum\ndf = pd.DataFrame([[1,0,0,0],\n [1,1,1,0],\n [0,1,1,1]], columns=['Var1', 'Var2', 'Var3', 'Dvar'])\n\nout = df.groupby('Dvar', as_index=False).sum...
[ 2, 2 ]
[]
[]
[ "contingency", "pandas", "python" ]
stackoverflow_0074294107_contingency_pandas_python.txt
Q: How to find at most 6 nearest neighbors in 3D space? I need to find at most 6 (depending on the node position) nearest neighbors for each point in 3D space. If you imagine cube 3x3x3, each corner will have 3 neighbors, each edge 4, each point near to the wall 5 and each point inside that cube will have 6 neighbors...
How to find at most 6 nearest neighbors in 3D space?
I need to find at most 6 (depending on the node position) nearest neighbors for each point in 3D space. If you imagine cube 3x3x3, each corner will have 3 neighbors, each edge 4, each point near to the wall 5 and each point inside that cube will have 6 neighbors, but in general I need to find nearest neighbor from each...
[ "I think a way to solve the problem of finding nearest neighbors is using numpy to calculate distances between points, sorting and get indices. For this you will have to transform your list of points to a numpy array with points=np.array(points). For the sake of this example i will create my own points.\n\n#CREATE ...
[ 0 ]
[]
[]
[ "3d", "nearest_neighbor", "python" ]
stackoverflow_0074280802_3d_nearest_neighbor_python.txt
Q: AttributeError: 'History' object has no attribute 'evaluate' from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout import numpy as np frames=[singleteamone_tweets,singleteamtwo_tweets,twoteam_tweets] All_data = pd.concat(frames) #creatin...
AttributeError: 'History' object has no attribute 'evaluate'
from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout import numpy as np frames=[singleteamone_tweets,singleteamtwo_tweets,twoteam_tweets] All_data = pd.concat(frames) #creating a bag of words model from sklearn.feature_extraction.text import...
[ "You should instead do something like this-\nhistory = model.fit(...)\n\nAccording to Keras documentation, the model.fit method returns a History callback, which has a history attribute containing the lists of successive losses and other metrics.\nhistory has no attribute called 'evaluate' you should instead do thi...
[ 2, 0 ]
[]
[]
[ "artificial_intelligence", "deep_learning", "machine_learning", "opennlp", "python" ]
stackoverflow_0062548674_artificial_intelligence_deep_learning_machine_learning_opennlp_python.txt
Q: I'm not getting any outputs for some reason after replacing the javascript functions with imported python functions index.html : <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="styles.css"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta n...
I'm not getting any outputs for some reason after replacing the javascript functions with imported python functions
index.html : <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="styles.css"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Advanced Calculator</title> <script src="f...
[ "As I undrstood, your problem is that you have some code in python that you want to run in browser on client-side.\nI think that the best solution here would be just to rewrite your python code in js. You could do it manually or use some python to javascript converter like this.\nYou might also be intrested in this...
[ 0 ]
[]
[]
[ "calculator", "css", "html", "javascript", "python" ]
stackoverflow_0071231269_calculator_css_html_javascript_python.txt
Q: Dataframe: index values to compare I have a dataframe (below). I would like to compare the two values in the index column. The first index value is the value of the last index. The second index value is the value of index based on condition criteria (index which corresponds to 1). In other words, how do I have d2 ...
Dataframe: index values to compare
I have a dataframe (below). I would like to compare the two values in the index column. The first index value is the value of the last index. The second index value is the value of index based on condition criteria (index which corresponds to 1). In other words, how do I have d2 in the same format as d1 (I would like d...
[ "# subtract the index (which are datetime) and take the difference as days\n(df1.index[-1] - df1[df1.x == 1].index).days[0]\n\n>>> 3\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074294469_dataframe_pandas_python.txt
Q: VScode fails to export Jupyter notebook to HTML - 'jupyter-nbconvert` not found I keep on getting error message: Available subcommands: 1.0.0 Jupyter command `jupyter-nbconvert` not found. I've tried to reinstall nbconvert using pip to no use. I've also tried the tip from this thread with installing pip install j...
VScode fails to export Jupyter notebook to HTML - 'jupyter-nbconvert` not found
I keep on getting error message: Available subcommands: 1.0.0 Jupyter command `jupyter-nbconvert` not found. I've tried to reinstall nbconvert using pip to no use. I've also tried the tip from this thread with installing pip install jupyter in vscode terminal but it shows that "Requirement already satisfied" VSCode fa...
[ "\npip uninstall nbconvert\n\nrun CMD as admin\n\npip install nbconvert\n\n\nFollowing above steps resolved my issue. Got this solution from this thread\n", "Unsure exactly what fixed the issue but heres a summary.\n\nUpdated to python 3.10\nInstalled pandoc and miktex\nPowershell reinstall nbconvert\n\n\nReceive...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "jupyter_notebook", "pdf_generation", "python", "visual_studio_code" ]
stackoverflow_0070552618_jupyter_notebook_pdf_generation_python_visual_studio_code.txt
Q: How can i get date by position (first, second, third November) using Python? I need a help for get a date from a position in a month. For example: The 4º day, considering just the workdays (days except saturday and sunday) on a week in November 2022 is 2022/11/07. The 21º day, considering just the workdays (days ...
How can i get date by position (first, second, third November) using Python?
I need a help for get a date from a position in a month. For example: The 4º day, considering just the workdays (days except saturday and sunday) on a week in November 2022 is 2022/11/07. The 21º day, considering just the workdays (days except saturday and sunday) on a week in November 2022 is 2022/11/29. I have: imp...
[ "If by \"workdays\" you mean \"every day except Sunday\", you can simply change your code to:\nordinal_date = [day for week in monthcal for day in week if \\\n day.month == month and day.weekday() != 0]\n\n", "I founded this solution working with calendar, holidays, numpy, Window:\nimport calendar\...
[ 0, 0 ]
[]
[]
[ "calendar", "python" ]
stackoverflow_0074281425_calendar_python.txt
Q: Is it possible to create 2 DAG with the same name having differents owners? Is it possible to create 2 DAG with the same name having differents owners? let's say the dag name would be dag_example and there is 2 users (user1 and user2) both user create a DAG with the same name , currently 2 dag with the same name a...
Is it possible to create 2 DAG with the same name having differents owners?
Is it possible to create 2 DAG with the same name having differents owners? let's say the dag name would be dag_example and there is 2 users (user1 and user2) both user create a DAG with the same name , currently 2 dag with the same name are overriding one an other but if someone know an option to have 2 dags with the ...
[ "No, it is not possible.\nYour CI/CD can check for duplicate dag_ids and prevent this case from reaching production.\nIn the future when Airflow will have multi-tenancy it will be possible to have same dag_id in different tenants you can think of it as the equivalent of Airflow to namespace concept in Kubernetes (f...
[ 0 ]
[]
[]
[ "airflow", "python" ]
stackoverflow_0074292366_airflow_python.txt
Q: Invalid Syntax Error in a certain line of code in python Decision Tree algorithm Following is my code I am running it on IDLE python 3.8 import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.feature_extraction import DictVectorizer from sklearn import trees from sklearn...
Invalid Syntax Error in a certain line of code in python Decision Tree algorithm
Following is my code I am running it on IDLE python 3.8 import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.feature_extraction import DictVectorizer from sklearn import trees from sklearn.metrics import accuracy_score,classification_report import warnings from sklearn.prep...
[ "Your code contains multiple issues:\n\nThe import should be StandardScaler not StandardScalar,\nYou got unused imports like MLPClassifier,\ncols_to_retrain is empty. Thus, data[cols_to_retrain] will return an empty data frame,\nto_dict should be to_dict(),\nvariable names x-feature and x_feature do not match,\nLab...
[ 0 ]
[]
[]
[ "decision_tree", "pandas", "python", "scikit_learn" ]
stackoverflow_0074293715_decision_tree_pandas_python_scikit_learn.txt
Q: Error while importing library "modin" in Python 3.6 import modin.pandas as pd I am importing modin.pandas library in my windows 10 machine but getting error "AttributeError: module 'ray' has no attribute 'utils'" Anything missed while installing modin library? A: "AttributeError: module 'ray' has no attribute...
Error while importing library "modin" in Python 3.6
import modin.pandas as pd I am importing modin.pandas library in my windows 10 machine but getting error "AttributeError: module 'ray' has no attribute 'utils'" Anything missed while installing modin library?
[ "\n\"AttributeError: module 'ray' has no attribute 'utils'\"\n\nIt looks like, you should be able to fix the issue if you just install the 1.1 version of ray, by doing the following :\npip install ray==1.1\n\nThe modin.pandas creators haven't release support for versions of ray greater then 1.1.\nHere is the discus...
[ 3, 1, 1, 0 ]
[]
[]
[ "modin", "pandas", "python", "python_3.x", "ray" ]
stackoverflow_0067345646_modin_pandas_python_python_3.x_ray.txt
Q: FastAPI with uvicorn won't allow thread usage to exceed ~65% I have written a machine learning inference library which has python bindings. Under normal operation, this library will use 8 threads for inference, and will max out all 8 threads 100%. This is the desired behavior as the model is very heavy and I need ...
FastAPI with uvicorn won't allow thread usage to exceed ~65%
I have written a machine learning inference library which has python bindings. Under normal operation, this library will use 8 threads for inference, and will max out all 8 threads 100%. This is the desired behavior as the model is very heavy and I need to optimize for low latency (therefore I need to use all CPU resou...
[ "I was able to determine what the issue was.\nI had defined my endpoints as def, and according to the FastAPI documentation, it will dispatch the request to a threadpool. This must have caused some sort of CPU contention, presumably related to the Python GIL.\nSwitching the endpoints to async def solved the problem...
[ 1 ]
[]
[]
[ "fastapi", "python", "uvicorn" ]
stackoverflow_0074229072_fastapi_python_uvicorn.txt
Q: How do I fill missing sequential data in a dataframe? I have a dataset that is formatted like this: index string 1 2008 1 2009 1 2010 2 2 2 3 2008 3 2009 3 2010 4 2008 4 2009 4 2010 5 5 5 I would like to fill in the missing data with the same sequence like this: index strin...
How do I fill missing sequential data in a dataframe?
I have a dataset that is formatted like this: index string 1 2008 1 2009 1 2010 2 2 2 3 2008 3 2009 3 2010 4 2008 4 2009 4 2010 5 5 5 I would like to fill in the missing data with the same sequence like this: index string 1 2008 1 2009 1 2010 ...
[ "Try this:\n# Find where is Nan\nm = df['string'].isna()\n\n# Compute how many Nan with 'm.sum()'\n# Replace 'Nan's with [2008, 2009, 2010]*(sum_of_Nan / 3) -> [2008,2009,2010,2008,2009,2010,...]\ndf.loc[m, 'string'] = [2008, 2009, 2010]*(m.sum()//3)\n\nOutput:\n string\nindex \n1 2008\n1 ...
[ 2, 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074294430_pandas_python.txt
Q: Is there a way to capture a specific values between parentheses so they can be replaced I am trying to use REGEX in Python to parse out a document. I want to replace all instances of * that appear within parentheses. eg ("A2OR01" * "A2OR02" * "A2OR03") to ("A2OR01" , "A2OR02" , "A2OR03"). So far I have tri...
Is there a way to capture a specific values between parentheses so they can be replaced
I am trying to use REGEX in Python to parse out a document. I want to replace all instances of * that appear within parentheses. eg ("A2OR01" * "A2OR02" * "A2OR03") to ("A2OR01" , "A2OR02" , "A2OR03"). So far I have tried (.+ (*) .+) but it only will match the last instance of the *. For example when I replac...
[ "Here's my code:\nimport re\ns = '(\"A2OR01\" * \"A2OR02\" * \"A2OR03\")'\nres = re.findall('\\(.*?\\)', s) # Get all instances of strings within parantheses (list)\nprint(res) # ['(\"A2OR01\" * \"A2OR02\" * \"A2OR03\")']\nfor i in range(len(res)):\n res[i] = res[i].replace(\"*\",\",\") # Replace all instances o...
[ 0, 0 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0074294503_parsing_python_regex.txt
Q: I am trying to edit a top level window So I heard there was a method in which you could make a separate tk.Toplevel class I have been attempting to use it but I dont know exactly whats wrong I really need help here is the code as of now I will keep trying to make adjustments but its not easy import tkinter as tk f...
I am trying to edit a top level window
So I heard there was a method in which you could make a separate tk.Toplevel class I have been attempting to use it but I dont know exactly whats wrong I really need help here is the code as of now I will keep trying to make adjustments but its not easy import tkinter as tk from tkinter import ttk class App(tk.Tk): ...
[ "The key part is AttributeError: '_tkinter.tkapp' object has no attribute 'Alter'' - that's telling you that your App class (which inherits from Tk) has no attribute called Alter.\nThe problem is caused by your App class, and more specifically by self.button = ttk.Button(self, text=\"Button\", command=self.Alter)\n...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074294353_python_tkinter.txt
Q: Reversing a linked list in python I am asked to reverse a which takes head as parameter where as head is a linked list e.g.: 1 -> 2 -> 3 which was returned from a function already defined I tried to implement the function reverse_linked_list in this way: def reverse_linked_list(head): temp = head head = No...
Reversing a linked list in python
I am asked to reverse a which takes head as parameter where as head is a linked list e.g.: 1 -> 2 -> 3 which was returned from a function already defined I tried to implement the function reverse_linked_list in this way: def reverse_linked_list(head): temp = head head = None temp1 = temp.next temp2 = te...
[ "The accepted answer doesn't make any sense to me, since it refers to a bunch of stuff that doesn't seem to exist (number, node, len as a number rather than a function). Since the homework assignment this was for is probably long past, I'll post what I think is the most effective code.\nThis is for doing a destruct...
[ 56, 28, 8, 1, 1, 0, 0, 0, 0, 0, 0, 0, -7 ]
[]
[]
[ "linked_list", "python" ]
stackoverflow_0021529359_linked_list_python.txt
Q: npm - "Can't find Python executable "python", you can set the PYTHON env variable." I'm trying to run the following command: npm install -g bower gulp cordova ionic tsd@next karma-cli protractor node-gyp coffee-script js-beautify typescript npm-check I have installed Python, Visual Studio Express and node-gyp so t...
npm - "Can't find Python executable "python", you can set the PYTHON env variable."
I'm trying to run the following command: npm install -g bower gulp cordova ionic tsd@next karma-cli protractor node-gyp coffee-script js-beautify typescript npm-check I have installed Python, Visual Studio Express and node-gyp so thought I'd be good to go, however I get the following errors: Regarding the "Can't find ...
[ "Try: \nInstall all the required tools and configurations using Microsoft's windows-build-tools by running npm install -g windows-build-tools from an elevated PowerShell (run as Administrator). \nhttps://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#environment-setup-and-confi...
[ 120, 44, 37, 31, 24, 12, 7, 6, 5, 3, 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "node.js", "npm", "npm_install", "python" ]
stackoverflow_0034372618_node.js_npm_npm_install_python.txt
Q: Pandas - Fill the blank column with some value I am looking to create a new column 'isRunning' in the data frame by identifying the 'Task' column status. Also, I have a 'Session' column and if a Session only has START value in the Task and no END vaule (for example, Session 3 has only START val), so 'isRunning' sh...
Pandas - Fill the blank column with some value
I am looking to create a new column 'isRunning' in the data frame by identifying the 'Task' column status. Also, I have a 'Session' column and if a Session only has START value in the Task and no END vaule (for example, Session 3 has only START val), so 'isRunning' should have TRUE flag untill the end of that session. ...
[ "Assuming one start/end per group. You can use a double mask:\nm1 = df['Task'].eq('START').groupby(df['Session]').cummax()\n\nm2 = df.loc[::-1, 'Task'].eq('END').groupby(df['Session']).cummax()\n\ndf['IsRunning'] = m1&m2\n\nIf several start/end per session are possible:\ndf['IsRunning'] = (df['Task'].map({'START': ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074294684_dataframe_pandas_python.txt
Q: Script for link redirects I am trying to write a python script, using selenium, to go into a website (Salesforce.com) and change various input fields and take screenshots. However, I am running into issues when it comes to my organization's SSO interface. My URL redirects me first, to a sign-on page (which asks fo...
Script for link redirects
I am trying to write a python script, using selenium, to go into a website (Salesforce.com) and change various input fields and take screenshots. However, I am running into issues when it comes to my organization's SSO interface. My URL redirects me first, to a sign-on page (which asks for org email), followed by a pag...
[ "Try adding self.driver.implicitly_wait(10) to the end of the __init__ method.\nOr add an explicit wait into query method:\ndef query(self):\n WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, 'login-button'))).click()\n\n", "problematic code:\nself.driver.implicitly_wait(10)\n# login...
[ 1, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074294486_python_selenium.txt
Q: Splitting a python list with common end points Suppose I have a python list as: points_list = [1, 2, 3, 4, 5, 6, 7, 8, 9,1] And I need to split this list containing the number of elements in the index_list=[2, 2, 6, 3] But having common endpoints That is: First 2 elements from points_list : [1,2] Next 2 elements ...
Splitting a python list with common end points
Suppose I have a python list as: points_list = [1, 2, 3, 4, 5, 6, 7, 8, 9,1] And I need to split this list containing the number of elements in the index_list=[2, 2, 6, 3] But having common endpoints That is: First 2 elements from points_list : [1,2] Next 2 elements from the points_list but it should start from the pl...
[ "Here's my code:\npoints_list = [1, 2, 3, 4, 5, 6, 7, 8, 9,1]\nindex_list=[2, 2, 6, 3]\nres = []\nend_point = 0\nfor i in index_list:\n temp_list = points_list[end_point:end_point+i] # Get the list\n res.append(temp_list) # Append it\n end_point = points_list.index(temp_list[-1]) # Get the index of the las...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074294781_python.txt
Q: dataclasses: how to ignore default values using asdict()? I would like to ignore the default values after calling asdict() @dataclass class A: a: str b: bool = True so if I call a = A("1") result = asdict(a, ignore_default=True) assert {"a": "1"} == result # the "b": True should be deleted A: The data...
dataclasses: how to ignore default values using asdict()?
I would like to ignore the default values after calling asdict() @dataclass class A: a: str b: bool = True so if I call a = A("1") result = asdict(a, ignore_default=True) assert {"a": "1"} == result # the "b": True should be deleted
[ "The dataclasses module doesn't appear to have support for detecting default values in asdict(), however the dataclass-wizard library does -- via skip_defaults argument.\nExample:\nfrom dataclasses import dataclass\nfrom dataclass_wizard import asdict\n\n@dataclass\nclass A:\n a: str\n b: bool = True\n\na = A...
[ 3, 2, 1 ]
[]
[]
[ "python", "python_dataclasses" ]
stackoverflow_0074262112_python_python_dataclasses.txt
Q: Extract store and location using regex and pandas I want to extract store name and location from the to_clean column. I would like to use some regex pattern that accounts for all the different patterns and stores the store name in the store column and the location name in the location column. Something like this: ...
Extract store and location using regex and pandas
I want to extract store name and location from the to_clean column. I would like to use some regex pattern that accounts for all the different patterns and stores the store name in the store column and the location name in the location column. Something like this: to_clean = ['ACTIVE BODY #1 - WEST VAN', 'BUY-LOW (8001...
[ "here is one way to do it\nAssumptions:\n\nThe store and location are separate by hyphen surrounded by spaces on both sides\n\n# split on ' - '\ndf[['store-1', 'location-1']] = df['to_clean'].str.split(r' - ',1, expand=True) \n\n# remove (),numbers\ndf[['store-1', 'location-1']]=df[['store-1', 'location-1']].repla...
[ 1, 1 ]
[]
[]
[ "extract", "pandas", "python" ]
stackoverflow_0074294533_extract_pandas_python.txt
Q: How to add own index to pip running in virtualenv? I have a virtualenv with pip inside. I have my own package index. I want to add this package to pip to avoid invoking pip install some_package -i my_index all the time I want to add this index only to this specific pip instance running in virtualenv. In that case...
How to add own index to pip running in virtualenv?
I have a virtualenv with pip inside. I have my own package index. I want to add this package to pip to avoid invoking pip install some_package -i my_index all the time I want to add this index only to this specific pip instance running in virtualenv. In that case, which file should I modify and how?
[ "I run into the same problem, and found that pip support this in current version de facto\nhttps://pip.pypa.io/en/latest/user_guide.html#config-file\nInside a virtualenv:\nOn Unix and Mac OS X the file is $VIRTUAL_ENV/pip.conf\nOn Windows the file is: %VIRTUAL_ENV%\\pip.ini\n", "I never tried using my own index, ...
[ 11, 9, 0 ]
[]
[]
[ "pip", "python", "virtualenv" ]
stackoverflow_0017025016_pip_python_virtualenv.txt
Q: I need to collapse a single column using a unique ID which contains duplicates and concatenate strings of text in that column only I need to combine strings in the text column for matching IDs with duplicats in the ID column. Column A through Column X will have matching data and I want to preserve that in the new ...
I need to collapse a single column using a unique ID which contains duplicates and concatenate strings of text in that column only
I need to combine strings in the text column for matching IDs with duplicats in the ID column. Column A through Column X will have matching data and I want to preserve that in the new dataframe. ID Text column A Column B 1 apple five 22 1 banana five 22 2 pancake three 8 3 peach two 5 3 mango two 5 ...
[ "import pandas as pd\n\ndf = pd.DataFrame({\"ID\": [1, 1, 2, 3, 3], \"Text\": [\"apple\", \"banana\", \"pancake\", \"peach\", \"mango\"], \\\n \"column_A\": [\"five\", \"five\", \"three\", \"two\", \"two\"], \"column_B\": [22, 22, 8, 5, 5]})\n\ndf = df.groupby([\"column_A\",\"column_B\", \"ID\"])[...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074294603_pandas_python.txt
Q: Create a dataframe column conditional to the Datetime column Imagine I have the following dataframe: pd.DataFrame({"Date":["10/29/2022", "10/30/2022", "11/5/2022", "11/6/2022"], "Values":[1, 6, 8, 12]}) I would like to create a new column with a value that equals to 0 if the row has a date before today and ...
Create a dataframe column conditional to the Datetime column
Imagine I have the following dataframe: pd.DataFrame({"Date":["10/29/2022", "10/30/2022", "11/5/2022", "11/6/2022"], "Values":[1, 6, 8, 12]}) I would like to create a new column with a value that equals to 0 if the row has a date before today and 1 to a date that's still on the future. Any ideas on how to implem...
[ "Use:\ndf['new'] = (pd.to_datetime(df['Date'], dayfirst=False) # convert to datetime\n .gt(pd.Timestamp('today')) # is the date after today?\n .astype(int) # result as 0/1\n )\n\nOutput:\n Date Values new\n0 10/29/2022 1 0\n1 10/30/2022 6 0\n2 11/5...
[ 1, 0 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074295004_dataframe_datetime_pandas_python.txt
Q: Using pytest, is it possible for a unit test to know that it is being run with code coverage monitoring on? I am currently developing some tests using python py.test / unittest that, via subprocess, invoke another python application (so that I can exercise the command line options, and confirm that the tool is ins...
Using pytest, is it possible for a unit test to know that it is being run with code coverage monitoring on?
I am currently developing some tests using python py.test / unittest that, via subprocess, invoke another python application (so that I can exercise the command line options, and confirm that the tool is installed correctly). I would like to be able to run the tests in such a way that I can get a view of the code cover...
[ "Coverage.py has a facility to automatically measure coverage in sub-processes that are spawned: http://coverage.readthedocs.io/en/latest/subprocess.html\n", "Coverage sets three environment flags when running tests: COV_CORE_SOURCE, COV_CORE_CONFIG and COV_CORE_DATAFILE.\nSo you can use a simple if-statement to ...
[ 0, 0 ]
[]
[]
[ "coverage.py", "pytest", "python", "unit_testing" ]
stackoverflow_0048409157_coverage.py_pytest_python_unit_testing.txt
Q: Create list of a list from XML dataset in ElementTree python i have a question. How can i create list of a list from xml dataset in ElemenTree python? for example i have this dataset : <data> <article> <author> Tony </author> </article> <article> <author> Andy </author> <author>...
Create list of a list from XML dataset in ElementTree python
i have a question. How can i create list of a list from xml dataset in ElemenTree python? for example i have this dataset : <data> <article> <author> Tony </author> </article> <article> <author> Andy </author> <author> John </author> </article> <article> <author> Paul...
[ "One liner can do the magic\nimport xml.etree.ElementTree as ET\n\nxml = '''<data>\n <article>\n <author> Tony </author>\n </article>\n <article>\n <author> Andy </author>\n <author> John </author>\n </article>\n <article>\n <author> Paul </author>\n <author> leon <...
[ 1, 0 ]
[]
[]
[ "elementtree", "list", "python", "xml" ]
stackoverflow_0074284106_elementtree_list_python_xml.txt
Q: AttributeError: can't set attribute in python Here is my code N = namedtuple("N", ['ind', 'set', 'v']) def solve(): items=[] stack=[] R = set(range(0,8)) for i in range(0,8): items.append(N(i,R,8)) stack.append(N(0,R-set(range(0,1)),i)) while(len(stack)>0): node =...
AttributeError: can't set attribute in python
Here is my code N = namedtuple("N", ['ind', 'set', 'v']) def solve(): items=[] stack=[] R = set(range(0,8)) for i in range(0,8): items.append(N(i,R,8)) stack.append(N(0,R-set(range(0,1)),i)) while(len(stack)>0): node = stack.pop() print node print items...
[ "For those searching this error, another thing that can trigger AtributeError: can't set attribute is if you try to set a decorated @property that has no setter method. Not the problem in the OP's question, but I'm putting it here to help any searching for the error message directly. (if you don't like it, go edit ...
[ 95, 78, 73, 2, 0 ]
[]
[]
[ "attributes", "python" ]
stackoverflow_0022562425_attributes_python.txt
Q: How to use a parent selector within a relative css selector in selenium python I'm going to try my best to explain the problem. This question is about selenium in Python. Consider this example: for row in driver.find_elements(By.CSS_SELECTOR, "div[style='overflow: hidden;'] > div > div:nth-child(3)"): player =...
How to use a parent selector within a relative css selector in selenium python
I'm going to try my best to explain the problem. This question is about selenium in Python. Consider this example: for row in driver.find_elements(By.CSS_SELECTOR, "div[style='overflow: hidden;'] > div > div:nth-child(3)"): player = row.find_element(By.CSS_SELECTOR, '> div:first-child > span').text Obviously, this...
[ "To get all the child elements of the parent element with Selenium and CSS Selectors you can simply directly apply the find_element on specific web element (node) as following:\nfor row in driver.find_elements(By.CSS_SELECTOR, \"div[style='overflow: hidden;'] > div > div:nth-child(3)\"):\n player = row.find_elem...
[ 2 ]
[]
[]
[ "css", "css_selectors", "python", "selenium", "xpath" ]
stackoverflow_0074294988_css_css_selectors_python_selenium_xpath.txt
Q: How to install seamsh in python I tried to install seamsh 0.4.4(https://pypi.org/project/seamsh/) but counld not. I spent a lot of time on it. I needed gdal library to use seamsh. So I installded it by conda because it was too complex to install it without conda. But conda was not supported seamsh, so I don't know...
How to install seamsh in python
I tried to install seamsh 0.4.4(https://pypi.org/project/seamsh/) but counld not. I spent a lot of time on it. I needed gdal library to use seamsh. So I installded it by conda because it was too complex to install it without conda. But conda was not supported seamsh, so I don't know what to do. Could you tell me how to...
[ "There's a pending PR to add it to Conda Forge. In the meantime, one can install it from PyPI. For example, try using the following environment:\nseamsh.yaml\nname: seamsh\nchannels:\n - conda-forge\n - nodefaults # only use conda-forge\ndependencies:\n ## core software\n - python=3.10 # set to preference\n ...
[ 0 ]
[]
[]
[ "anaconda", "conda", "gdal", "python" ]
stackoverflow_0074286454_anaconda_conda_gdal_python.txt
Q: How to group a certain part of a heading in a dataset using pandas? I have a dataset here in which I have to group each sample. The group of each sample is apart of the sample's name. I have the rows each with a semi unique heading. e.g TCGA.02.0047.GBM.C4, TCGA.02.0055.GBM.C4, TCGA.ZS.A9CG.LIHC.C3, TCGA.ZU.A8S4.C...
How to group a certain part of a heading in a dataset using pandas?
I have a dataset here in which I have to group each sample. The group of each sample is apart of the sample's name. I have the rows each with a semi unique heading. e.g TCGA.02.0047.GBM.C4, TCGA.02.0055.GBM.C4, TCGA.ZS.A9CG.LIHC.C3, TCGA.ZU.A8S4.CHOL.C1, TCGA.ZX.AA5X.CESC.C2. I need to target the C bit in the heading ...
[ "if you have column names\nYou can extract the part after the last period and use it as grouper:\ndf.groupby(df.columns.str.extract('([^.]+)$', expand=False), axis=1)\n\nThen perform the desired aggregation.\nif you have one column\ndf['new'] = df['col'].str.extract('([^.]+)$')\n\nOutput:\n col n...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074295063_pandas_python.txt
Q: make a parent function return - super return? there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function. >>> def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ...
make a parent function return - super return?
there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function. >>> def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... >>> gs(1,2) # should return 2 >>> g...
[ "Do you mean?\ndef gs(a,b):\n def ry():\n if a==b:\n return a\n return ry()\n\n", "As you mention \"steps\" in a function, it almost seems like you want a generator:\ndef gs(a,b):\n def ry():\n if a==b:\n yield a\n # If a != b, ry does not \"generate\" any output\n for i in ry()...
[ 11, 4, 3, 3, 1, 1, 0 ]
[]
[]
[ "class", "function", "parent", "python", "return" ]
stackoverflow_0000440063_class_function_parent_python_return.txt
Q: Can't install Cartopy I try to install cartopy for work but I got an error and I don't know how to solve it. "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -I. -I./lib/cartopy -IC:\Users\Sogata\AppData\Local\Temp\pip-bu...
Can't install Cartopy
I try to install cartopy for work but I got an error and I don't know how to solve it. "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -I. -I./lib/cartopy -IC:\Users\Sogata\AppData\Local\Temp\pip-build-env-nkjqwiqm\overlay\Li...
[ "From the cartopy docs:\n\nThe easiest way to install Cartopy is by using Conda. If conda is already installed, installation is as easy as:\nconda install -c conda-forge cartopy\n\n\nI highly recommend you follow their advice. cartopy relies on GDAL, which is a collection of non-python compiled libaries which are r...
[ 1 ]
[]
[]
[ "cartopy", "python" ]
stackoverflow_0074293754_cartopy_python.txt
Q: Sklearn kmeans causes Mac OS pyinstaller app crash I'm creating a piece of software using tkinter and pyinstaller that imports KMeans from sklearn.cluster: The software as an .exe works fine on Windows 11 The GUI works fine before packaging using pyinstaller on Mac Monterey The software as an .app works fine on Ma...
Sklearn kmeans causes Mac OS pyinstaller app crash
I'm creating a piece of software using tkinter and pyinstaller that imports KMeans from sklearn.cluster: The software as an .exe works fine on Windows 11 The GUI works fine before packaging using pyinstaller on Mac Monterey The software as an .app works fine on Mac if I don't import KMeans from sklearn.cluster If I do ...
[ "Problem solved!\nApparently there were issues with sklearn not being included in hidden imports in the past issue here\nHowever, this couldn't be the issue, because my PC version was working. I'm using pyinstaller on Windows to bundle an .exe and pyinstaller on Mac to bundle an .app\nThis issue lead me to believe ...
[ 0 ]
[]
[]
[ "pyinstaller", "python", "scikit_learn", "tkinter" ]
stackoverflow_0074294682_pyinstaller_python_scikit_learn_tkinter.txt
Q: How to install a different version of Python on mac for a single project I need to run python 3.6 but have 3.9 on my mac, which is running Big Sur. I followed the instructions on pyenv's github and then when I run pyenv install 3.6.15 I get the following error. python-build: use openssl@1.1 from homebrew python-...
How to install a different version of Python on mac for a single project
I need to run python 3.6 but have 3.9 on my mac, which is running Big Sur. I followed the instructions on pyenv's github and then when I run pyenv install 3.6.15 I get the following error. python-build: use openssl@1.1 from homebrew python-build: use readline from homebrew Downloading Python-3.9.0.tar.xz... -> https:...
[ "python is looking for a C compiler to build python from source. checking for clang++... no means that it can't find one. You can install one via brew, and then pass the path for it to the pyenv command:\nbrew install gcc\nCC=\"$(brew --prefix gcc)/bin/gcc-12\" pyenv install 3.6.15\n\n" ]
[ 0 ]
[]
[]
[ "macos_big_sur", "pyenv", "python" ]
stackoverflow_0069833468_macos_big_sur_pyenv_python.txt
Q: Creating dynamic flask route I'm attempting to create a dynamic flask route. I want to create a parallel page for my route that internal users can see when they add 'vo/' before the URL. So essentially there are two different routes /vo/feedbackform and /feedbackform. I know I could just create two routes in the a...
Creating dynamic flask route
I'm attempting to create a dynamic flask route. I want to create a parallel page for my route that internal users can see when they add 'vo/' before the URL. So essentially there are two different routes /vo/feedbackform and /feedbackform. I know I could just create two routes in the app, but I'm hoping I can optimize....
[ "i dont think this is supported by Flask.\nFor your case that you have only 2 paths to support, you can add two decorators/routes to same function and then inspect the request.path to render the appropriate template:\nfrom flask import request\n\n@app.route('/vo/feedbackform', methods=['GET', 'POST'])\n@app.route('...
[ 1, 1 ]
[ "I don't know your reasons for wanting to have a single handler but if the snippet you provided is all there is to it, I don't see much in common between the two routes to warrant a single handler especially if you are going to use if-else to handle each case differently.\nI would rather have separate routes - it's...
[ -1 ]
[ "flask", "python" ]
stackoverflow_0074293109_flask_python.txt
Q: Transcribe a function and remove blank characters (-) Write a function make_vax, which takes a list of arbitrary number of dna sequences, and both removes gaps ("-" characters) and transcribes the sequence to mRNA. It returns a list with gap-less mRNA sequences of the same length as the input list. def make_vax(dn...
Transcribe a function and remove blank characters (-)
Write a function make_vax, which takes a list of arbitrary number of dna sequences, and both removes gaps ("-" characters) and transcribes the sequence to mRNA. It returns a list with gap-less mRNA sequences of the same length as the input list. def make_vax(dna_list): # your code here mRNA = transcribe(dna_list) for i...
[ "You almost had it. Your loop should be for i in range(len(mRNA)).\nMore concisely:\nrna_list=[]\nfor seq in dna_list:\n mRNA = ''\n for char in seq:\n if char == 'T':\n mRNA += 'U'\n elif char != '-':\n mRNA.append(char)\n rna_list.append(mRNA)\n\nOr, even more concisel...
[ 0 ]
[]
[]
[ "dna_sequence", "python" ]
stackoverflow_0074295116_dna_sequence_python.txt
Q: Get all bot commands discord.py I'm making a help command using discord.py rewrite and I need a way to iterate over all the commands I already have inside the bot, is there a way to do like bot.get_all_commands? for command in bot.get_all_commands: print(command) A: bot.commands returns all commands as comma...
Get all bot commands discord.py
I'm making a help command using discord.py rewrite and I need a way to iterate over all the commands I already have inside the bot, is there a way to do like bot.get_all_commands? for command in bot.get_all_commands: print(command)
[ "bot.commands returns all commands as command objects in a set.\n", "You can use bot.all_commands to return all commands & aliases that you used before, See more in discord.ext.command .\n", "This worked for me\ncommands = bot.get_my_commands()\nfor command in commands:\n print(command)\n\n", "With version...
[ 2, 1, 1, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0062755326_discord.py_python.txt
Q: Adding 3 lists together with int , str and bool How do I add these 3 lists together by index? first_names = ["Ainsley", "Ben", "Chani", "Depak"] preferred_size = ["Small", "Large", "Medium"] preferred_size.append("Medium") expedited_shipping = [True, False, True, False] ex: list = ["Ainsley", Small, True], [Ben, ...
Adding 3 lists together with int , str and bool
How do I add these 3 lists together by index? first_names = ["Ainsley", "Ben", "Chani", "Depak"] preferred_size = ["Small", "Large", "Medium"] preferred_size.append("Medium") expedited_shipping = [True, False, True, False] ex: list = ["Ainsley", Small, True], [Ben, Large, False]
[ "This is what the zip function was built for.\nresult = list(zip(first_names, preferred_size, expedited_shipping))\n\n" ]
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074295284_list_python.txt
Q: Solving 'Cookies must be enabled to use GitHub' using GAE/Webapp2/Urllib2/Python Despite looking through the API documentation, I couldn't find anything explaining why Github needs cookies enabled, or how to go about it. I may have missed it tho. I'd like to use the native Webapp2 framework on GAE in Python with U...
Solving 'Cookies must be enabled to use GitHub' using GAE/Webapp2/Urllib2/Python
Despite looking through the API documentation, I couldn't find anything explaining why Github needs cookies enabled, or how to go about it. I may have missed it tho. I'd like to use the native Webapp2 framework on GAE in Python with Urllib2, and stay away from high-level libraries so that I can learn this from the insi...
[ "It seems to be related to the api endpoint. From the official doc: All API access is over HTTPS, and accessed from the api.github.com domain (or through yourdomain.com/api/v3/ for enterprise). All data is sent and received as JSON.\nYou get an error about cookies because you're calling the GitHub website which req...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "python_2.7", "urllib2", "webapp2" ]
stackoverflow_0022275080_google_app_engine_python_python_2.7_urllib2_webapp2.txt
Q: How to pivot dataframe and transpose 1 row I want to pivot this dataframe and convert the columns to a second level multiindex or column. Original dataframe: Type VC C B Security 0 Standard 2 2 2 A 1 Standard 16 13 0 B 2 Standard 52 35 2 C 3 RI 10...
How to pivot dataframe and transpose 1 row
I want to pivot this dataframe and convert the columns to a second level multiindex or column. Original dataframe: Type VC C B Security 0 Standard 2 2 2 A 1 Standard 16 13 0 B 2 Standard 52 35 2 C 3 RI 10 10 0 A 4 RI 10 15 31 ...
[ "You could try as follows:\n\nUse df.pivot and then transpose using df.T.\nNext, chain df.sort_index to rearrange the entries, and apply df.swaplevel to change the order of the MultiIndex.\nLastly, consider getting rid of the Security as columns.name, and adding an index.name for the unnamed variable, e.g. Subtype ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074292953_pandas_python.txt
Q: python can't multiply sequence by non-int of type 'numpy.float64' X = [5, 15, 25, 35, 45, 55] Y = [5, 20, 14, 32, 22, 38] plt.scatter(X, Y) xm=np.mean(X) #valeur moyenne de x ym=np.mean(Y) #valeur moyenne de y num=0 #numerator den=0 #denominator for i in range(len(X)): num +=(X[i]-xm)*(Y[i]-ym) den +=(X[i...
python can't multiply sequence by non-int of type 'numpy.float64'
X = [5, 15, 25, 35, 45, 55] Y = [5, 20, 14, 32, 22, 38] plt.scatter(X, Y) xm=np.mean(X) #valeur moyenne de x ym=np.mean(Y) #valeur moyenne de y num=0 #numerator den=0 #denominator for i in range(len(X)): num +=(X[i]-xm)*(Y[i]-ym) den +=(X[i]-xm)**2 a=num/den b=ym-a*xm print(a,b) yp=a*X+b #y predict plt.scatt...
[ "I believe this is because X is a list and not a numpy array, so you can't do array operations on it (such as multiplying it by a)\nSimple solution could be this:\nimport numpy as np\n\nX = np.array([5, 15, 25, 35, 45, 55])\n\n# rest of your code...\n\n" ]
[ 2 ]
[]
[]
[ "jupyter", "matplotlib", "numpy", "python" ]
stackoverflow_0074295322_jupyter_matplotlib_numpy_python.txt
Q: Return the eigenvector corresponding to the max eigenvalue of A As the title says, I must compute the eigenvector v corresponding to the max eigenvalue. I'm not sure what commands do this. Any tips? import numpy as np import scipy.linalg as la #x and y both 1D NumPy arrays of same length def eigen_X(x,y): xa ...
Return the eigenvector corresponding to the max eigenvalue of A
As the title says, I must compute the eigenvector v corresponding to the max eigenvalue. I'm not sure what commands do this. Any tips? import numpy as np import scipy.linalg as la #x and y both 1D NumPy arrays of same length def eigen_X(x,y): xa = np.mean(x) ya = np.mean(y) x_bar = x - xa y_bar = y - y...
[ "scipy.linalg.eig provides a function that calculates eigenvalues and eigenvectors of a 2D, square matrix. To get the (right?) eigenvector corresponding to the largest eigenvalue, use\nw, vl, vr = la.eig(A)\nlargest_eigenvector = vr[:, np.argmax(w)]\n\nReplace vr[:, np.argmax(w)] above with vl[np.argmax(w)] if you'...
[ 2, 2, 0 ]
[]
[]
[ "eigenvalue", "eigenvector", "python" ]
stackoverflow_0053307152_eigenvalue_eigenvector_python.txt
Q: Pyspark from_json function equvalent I have dataframe with column containing json string, which is converted to dictionary using from_json function. Problem occured when json contains not typical string inside like: '\\"cde\\"', all json: '{"key":"abc","value":"\\"cde\\""}'. When from_json function is applied, it ...
Pyspark from_json function equvalent
I have dataframe with column containing json string, which is converted to dictionary using from_json function. Problem occured when json contains not typical string inside like: '\\"cde\\"', all json: '{"key":"abc","value":"\\"cde\\""}'. When from_json function is applied, it returns null because I think it treats \\ ...
[ "\nIs there way for cleaning such json\n\nFor your case, I would suggest creating an UDF, that captures the cleaning rules that are relevant to your data. For the single line of data you have included, I created a sample UDF that removes all incorrect tokens and parses the JSON correctly:\nfrom pyspark.sql.function...
[ 1 ]
[]
[]
[ "databricks", "dataframe", "fromjson", "pyspark", "python" ]
stackoverflow_0074291179_databricks_dataframe_fromjson_pyspark_python.txt
Q: What do Line2D objects returned by seaborn.lineplot with hue represent? import seaborn as sns import matplotlib.pyplot as plt import numpy as np import pandas as pd # generate data rng = np.random.default_rng(12) x = np.linspace(0, np.pi, 50) y1, y2 = np.sin(x[:25]), np.cos(x[25:]) cat = rng.choice(["a", "b", "...
What do Line2D objects returned by seaborn.lineplot with hue represent?
import seaborn as sns import matplotlib.pyplot as plt import numpy as np import pandas as pd # generate data rng = np.random.default_rng(12) x = np.linspace(0, np.pi, 50) y1, y2 = np.sin(x[:25]), np.cos(x[25:]) cat = rng.choice(["a", "b", "c"], 50) data = pd.DataFrame({"x": x , "y" : y1.tolist() + y2.tolist(), "cat...
[ "These are dummy lines used to create the legend. Seaborn's legends can be quite complex, due to the many options. You might want to check out this github issue to get an idea about Seaborn trying to create more elaborate legends than what matplotlib currently allows.\nIf you change the properties of these dummy l...
[ 5 ]
[]
[]
[ "matplotlib", "python", "seaborn" ]
stackoverflow_0074294527_matplotlib_python_seaborn.txt
Q: User Registration with error: no such table: auth_user I am trying to use Django's default Auth to handle register and log in. setting.py: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', '...
User Registration with error: no such table: auth_user
I am trying to use Django's default Auth to handle register and log in. setting.py: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'books', ) MIDDLEWARE_CLAS...
[ "./manage.py migrate\n\nIf you've just enabled all the middlewares etc this will run each migration and add the missing tables.\n", "Only thing you need to do is :\npython manage.py migrate\n\nand after that:\npython manage.py createsuperuser\n\nafter that you can select username and password.\nhere is the sample...
[ 104, 44, 20, 12, 11, 7, 5, 4, 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0024682155_authentication_django_python.txt
Q: Safest way to create MS Excel file (xlsx) from Python I know that Microsoft Excel has some notable limitations when it comes to opening arbitrary spreadsheets. Occasionally the following errors/warnings will occur: We found a problem with some content in 'filename.xlsx'. Do you want us to try to recover as much a...
Safest way to create MS Excel file (xlsx) from Python
I know that Microsoft Excel has some notable limitations when it comes to opening arbitrary spreadsheets. Occasionally the following errors/warnings will occur: We found a problem with some content in 'filename.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Y...
[ "With some more research I was able to learn that Pandas sets the default writer to openpyxl unless XlsxWriter is installed.\nAfter running pip install XlsxWriter it started producing a spreadsheet without erroring in Excel.\nIt's maybe worth noting, for posterity's sake, that the issue arose immediately after upgr...
[ 0 ]
[]
[]
[ "excel", "ms_office", "pandas", "python", "spreadsheet" ]
stackoverflow_0074293549_excel_ms_office_pandas_python_spreadsheet.txt
Q: Apply custom sum over numpy ndarray I would like to do this particular computation: with a square ndarray A in 4 dimension of size (N, )*4, I would like to compute the 2 dimension array B such that for n in range(N): for m in range(N): B[n, m] = sum(A[i, j, n-i, m-j] for i in range(n) for j in range(m)...
Apply custom sum over numpy ndarray
I would like to do this particular computation: with a square ndarray A in 4 dimension of size (N, )*4, I would like to compute the 2 dimension array B such that for n in range(N): for m in range(N): B[n, m] = sum(A[i, j, n-i, m-j] for i in range(n) for j in range(m)) Is it possible to vectorize this compu...
[ "It's hard to visualize the whole array action\nN=4; A = np.arange(N**4).reshape(N,N,N,N) \n\nthis tests the same:\nfor n in range(N):\n for m in range(N):\n I = np.arange(n)[:,None]; J = np.arange(m)\n B[n,m] = A[I,J,n-I,m-J].sum()\n\nIt's harder to \"vectorize\" the n,m since the indexed portion...
[ 0 ]
[]
[]
[ "math", "numpy", "optimization", "python", "vectorization" ]
stackoverflow_0074293894_math_numpy_optimization_python_vectorization.txt
Q: Code is not executing due to syntax error in line 18 My code is showing a syntax error in line 18 of the code. I am not being able to find out what the problem is. Can you guys please kindly help me out? The problem is as follows: 3.2 Write a menu-driven program that allows the user to make transactions to a bank ...
Code is not executing due to syntax error in line 18
My code is showing a syntax error in line 18 of the code. I am not being able to find out what the problem is. Can you guys please kindly help me out? The problem is as follows: 3.2 Write a menu-driven program that allows the user to make transactions to a bank account. The options of the menu are: Option 1: Make a De...
[ "U must close the parentheses when calling functions\nu forgot to do so in 2 occasions\nOn line 17 and 24\njust change it from deposit = int(input(\"Enter an amount to deposit: GBP\") to deposit = int(input(\"Enter an amount to deposit: GBP\"))\nand from withdraw = int(input(\"Enter an amount to withdraw: GBP\") to...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074295584_python.txt
Q: Calculate Distance between Two Lists for each element I have two long lists of of X and Y coordinates in space. I would like to calculate the absolute change in total distance in each frame. Everywhere I look online it is only the Euclidian distance for the entire list which isn't what I am trying to get. Sample d...
Calculate Distance between Two Lists for each element
I have two long lists of of X and Y coordinates in space. I would like to calculate the absolute change in total distance in each frame. Everywhere I look online it is only the Euclidian distance for the entire list which isn't what I am trying to get. Sample data below I tried to calculate Euclidian distance with a f...
[ "Assuming you want the Euclidean distance between the successive points, you can compute:\nd = sqrt((x2-x1)**2 + (y2-y1)**2)\n\nWhich translates into:\nimport numpy as np\n\ndf['distance'] = np.sqrt(df['x'].diff().pow(2)\n .add(df['y'].diff().pow(2)))\n\nprint(df)\n\nOutput:\n x ...
[ 0 ]
[]
[]
[ "distance", "numpy", "python", "python_3.x" ]
stackoverflow_0074295372_distance_numpy_python_python_3.x.txt
Q: Get data from bs4 script I am new to programming and i am trying to parse this page: https://ruz.spbstu.ru/faculty/100/groups url = "https://ruz.spbstu.ru/faculty/100/groups" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") scripts = soup.find_all('script') print(scripts[3].text) th...
Get data from bs4 script
I am new to programming and i am trying to parse this page: https://ruz.spbstu.ru/faculty/100/groups url = "https://ruz.spbstu.ru/faculty/100/groups" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") scripts = soup.find_all('script') print(scripts[3].text) this gives me window.__INITIAL_S...
[ "Try:\nimport re\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://ruz.spbstu.ru/faculty/100/groups\"\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, \"html.parser\")\nscripts = soup.find_all(\"script\")\n\ndata = re.search(r\".*?({.*});\", scripts[3].text).group(1)\...
[ 0 ]
[]
[]
[ "beautifulsoup", "json", "parsing", "python" ]
stackoverflow_0074295334_beautifulsoup_json_parsing_python.txt
Q: How to Left Join a Dataframe into an Existing Table in Databricks I have a delta table in Databricks that I am loading into a dataframe to perform a specific numpy operation: import pyspark.pandas as ps df = spark.sql("SELECT Id,Field_to_Transform FROM bronze.Table_A where Field_to_Transform is not null").toPandas...
How to Left Join a Dataframe into an Existing Table in Databricks
I have a delta table in Databricks that I am loading into a dataframe to perform a specific numpy operation: import pyspark.pandas as ps df = spark.sql("SELECT Id,Field_to_Transform FROM bronze.Table_A where Field_to_Transform is not null").toPandas() The operation I perform is to remove special characters: df['Transf...
[ "Option 1 - DataFrame API way\nThe first option is a modification of your first bullet point:\n\nSaved the entire bronze.Table_A in a new dataframe df2, used df.merge to put them together, and then created a brand new table. This worked but it was way too excessive and I do not need a new table, just the transforme...
[ 1 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "databricks", "python", "sql" ]
stackoverflow_0074280595_apache_spark_apache_spark_sql_databricks_python_sql.txt
Q: change video resolution to specific resolution using ffmpeg in python I am trying the change the resolution of some videos. The original video resolution is 1920x1080. first, I have to change the resolution to 640X480. for this I used the following code: subprocess.call(['ffmpeg.exe', '-y', '-i', pname1, '-vf', 's...
change video resolution to specific resolution using ffmpeg in python
I am trying the change the resolution of some videos. The original video resolution is 1920x1080. first, I have to change the resolution to 640X480. for this I used the following code: subprocess.call(['ffmpeg.exe', '-y', '-i', pname1, '-vf', 'scale=-1:480,setsar=1:1', '-c:v','libx264', '-c:a', 'copy', pname2]) when I...
[ "\n(1) \"The original video resolution is 1080, > then I change it to 480... > and then again change it back into 1080. \n...Now I compare the original video in 1080 with this new video in 1080\".\n(2) \"I see this in papers where you have to change the video resolution and then make comparisons.\"\n\nYou can ach...
[ 0 ]
[]
[]
[ "ffmpeg", "python", "python_3.x", "video" ]
stackoverflow_0074254030_ffmpeg_python_python_3.x_video.txt
Q: Function output with if-else statement Hello I have been study python for the pass few months and can't seem to figure out how to get the code below to work. The could runs but I am not receiving the output I was expected. I know strings are immutable, at first I kept using list function a realized that was incorr...
Function output with if-else statement
Hello I have been study python for the pass few months and can't seem to figure out how to get the code below to work. The could runs but I am not receiving the output I was expected. I know strings are immutable, at first I kept using list function a realized that was incorrect but im stuck at thE moment. Not sure if ...
[ "you had 3 mistakes:\n\nyou didn't convert the input_string to int when trying to divide it\n\nyou didn't use the right sign for division (/ and not %)\n\nyou tried to reverse the input_string using [-1:0] when you need to do [::-1]\n\n\ndef function(input_string):\n if len(input_string) > 6:\n return inp...
[ 1 ]
[]
[]
[ "function", "if_statement", "python", "string" ]
stackoverflow_0074295506_function_if_statement_python_string.txt
Q: Pandas Fillna of Multiple Columns with Mode of Each Column Working with census data, I want to replace NaNs in two columns ("workclass" and "native-country") with the respective modes of those two columns. I can get the modes easily: mode = df.filter(["workclass", "native-country"]).mode() which returns a datafra...
Pandas Fillna of Multiple Columns with Mode of Each Column
Working with census data, I want to replace NaNs in two columns ("workclass" and "native-country") with the respective modes of those two columns. I can get the modes easily: mode = df.filter(["workclass", "native-country"]).mode() which returns a dataframe: workclass native-country 0 Private United-States Howev...
[ "If you want to impute missing values with the mode in some columns a dataframe df, you can just fillna by Series created by select by position by iloc:\ncols = [\"workclass\", \"native-country\"]\ndf[cols]=df[cols].fillna(df.mode().iloc[0])\n\nOr:\ndf[cols]=df[cols].fillna(mode.iloc[0])\n\nYour solution:\ndf[cols]...
[ 13, 4, 0, 0, 0 ]
[]
[]
[ "data_science", "numpy", "pandas", "python" ]
stackoverflow_0042870536_data_science_numpy_pandas_python.txt
Q: Python Code working fine in Google Colab but not when deployed in Google Function I have some Python code that works fine in Colab but when I transfer the code into a Google Function it fails. I am pulling an image from Google Drive with requests and then posting to Twitter via API so I think I need to dump the im...
Python Code working fine in Google Colab but not when deployed in Google Function
I have some Python code that works fine in Colab but when I transfer the code into a Google Function it fails. I am pulling an image from Google Drive with requests and then posting to Twitter via API so I think I need to dump the image into a temporary folder within functions. Not sure why this isn't needed on Colab? ...
[ "With the open('image', \"wb\") you are writing to the local file system but Google Function does not have any local file system.\nHard to see how the api works but most libraries accept either a file or a stream when uploading. So the goal is to keep the picture content in memory and pass it further.\n" ]
[ 0 ]
[]
[]
[ "google_cloud_functions", "google_colaboratory", "python", "python_requests", "tweepy" ]
stackoverflow_0074295377_google_cloud_functions_google_colaboratory_python_python_requests_tweepy.txt
Q: Pandas: Extracting values from a DatetimeIndex I have a Pandas DataFrame whose rows and columns are a DatetimeIndex. import pandas as pd data = pd.DataFrame( { "PERIOD_END_DATE": pd.date_range(start="2018-01", end="2018-04", freq="M"), "first": list("abc"), "second": list("efg") } ...
Pandas: Extracting values from a DatetimeIndex
I have a Pandas DataFrame whose rows and columns are a DatetimeIndex. import pandas as pd data = pd.DataFrame( { "PERIOD_END_DATE": pd.date_range(start="2018-01", end="2018-04", freq="M"), "first": list("abc"), "second": list("efg") } ).set_index("PERIOD_END_DATE") data.columns = pd.da...
[ "There are 2 issues:\n\nSince, you are using a DateTimeIndex dataframe, the correct notation to traverse between rows and columns are:\n\na) data.loc[rows_index_name, [column__index_name]]\n\nor\nb) data.loc[rows_index_name, column__index_name]\n\ndepending on the type of output you desire.\nNotation A will return ...
[ 2, 0, 0, 0 ]
[]
[]
[ "datetimeindex", "pandas", "python" ]
stackoverflow_0074282056_datetimeindex_pandas_python.txt
Q: How do I get Beautiful Soup to read the contents of Selenium web driver? I am currently trying to scrape news headlines with python, beautiful soup and selenium from a website with a "show more" button. I am able to successfully load the page with selenium, click the button to bring up more headlines, and then pri...
How do I get Beautiful Soup to read the contents of Selenium web driver?
I am currently trying to scrape news headlines with python, beautiful soup and selenium from a website with a "show more" button. I am able to successfully load the page with selenium, click the button to bring up more headlines, and then print out the headlines, all with no error messages. My problem is Beautiful Soup...
[ "Try the below code. Now it's working\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nimport time\nfrom bs4 import BeautifulSoup\n\ns=Service('./chromedriver')\ndriver= webdriver.Chrome(service=s)\nurl='https://www.foxnews.com/poli...
[ 1 ]
[]
[]
[ "beautifulsoup", "pandas", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074295401_beautifulsoup_pandas_python_selenium_selenium_webdriver.txt
Q: Django's runscript: No (valid) module for script 'filename' found I'm trying to run a script from the Django shell using the Django-extension RunScript. I have done this before and but it refuses to recognize my new script: (env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript fill_in_random_variants No ...
Django's runscript: No (valid) module for script 'filename' found
I'm trying to run a script from the Django shell using the Django-extension RunScript. I have done this before and but it refuses to recognize my new script: (env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript fill_in_random_variants No (valid) module for script 'fill_in_random_variants' found Try running w...
[ "RunScript has confusing error messages. It gives the same error for when it can't find a script at all and when there's an import error in the script.\nHere's an example script to produce the error:\nimport nonexistrentpackage\n\ndef run():\n print(\"Test\")\n\nThe example has the only stated requirement for sc...
[ 13, 7, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0039322967_django_python.txt
Q: How to print webelements in a table - Selenium Python This code will go to a website, launch it, extract 2 web-elements(email, and ticket#) and print them successfully. from audioop import add from inspect import isframe from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdr...
How to print webelements in a table - Selenium Python
This code will go to a website, launch it, extract 2 web-elements(email, and ticket#) and print them successfully. from audioop import add from inspect import isframe from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.suppor...
[ "If there are no other extra data present for your table, you could use find_elements to fetch only the table data directly.\nTickets = driver.find_elements(By.XPATH,\"//table//td[3]\")\n\nThis would give you an array of elements that you can manipulate.\nYou can iterate through the array to get the texts\nfor tick...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074292914_python_selenium.txt