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: Hi, I am trying to replicate sumif function in excel for python dataframe with specific column value My target on daily basis is 250. For any given date, if the cum-daily_result has reached 250 then subsequent rows should have only 250 as expected results In below table column 'ID' to 'cum_daily_result' are the in...
Hi, I am trying to replicate sumif function in excel for python dataframe with specific column value
My target on daily basis is 250. For any given date, if the cum-daily_result has reached 250 then subsequent rows should have only 250 as expected results In below table column 'ID' to 'cum_daily_result' are the input in data frame. The expected output is computed manually in column 'expected_daily_result' I tried the...
[ "Consider using .clip(...)\n expected_daily_result = df.cum_daily_result.clip(upper=250)\n\n", "make simple example text not image\nexample:\ndata = [['a', 250, 250], ['a', 250, 500], ['a', -1290, -790],\n ['b', -1392, -1392], ['b', 250, -1142], ['b', 250, -892], ['b', 2238, 1346],\n ['b', 250, ...
[ 0, 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074410292_numpy_pandas_python.txt
Q: Fixing "missing 1 required positional argument: 'id'" error when sending data from Django Form using Ajax I have a Django Form where users inserts numeric values. I am sending the Ajax to a url but I keep receiving: TypeError: addlog() missing 1 required positional argument: 'id' I have tried to add the id in the...
Fixing "missing 1 required positional argument: 'id'" error when sending data from Django Form using Ajax
I have a Django Form where users inserts numeric values. I am sending the Ajax to a url but I keep receiving: TypeError: addlog() missing 1 required positional argument: 'id' I have tried to add the id in the url I got: Reverse for 'addlog' with arguments '(2,)' not found. 1 pattern(s) tried: ['workout/addlog/\\Z'] H...
[ "You did add id to the template's context\ncontext = {\n 'log_workout': data.log_workout,\n 'id': workout.id,\n }\n\nSo just change :\n<form class=\"review-form\" action=\"{% url 'my_gym:addlog' object.id %}\" method=\"post\">\n\nto :\n <form class=\"review-form\" action=\...
[ 1, 1 ]
[]
[]
[ "ajax", "django", "django_forms", "django_urls", "python" ]
stackoverflow_0074410187_ajax_django_django_forms_django_urls_python.txt
Q: Using cophenetic distance to choose best linkage method? I have the dataset that generates the following code. X_moons, y_moons = datasets.make_moons(n_samples=1000, noise=.07, random_state=42) The case is that I would like to make a dendrogram (bottom-up) in Python and I must select a linkage criterion. If you c...
Using cophenetic distance to choose best linkage method?
I have the dataset that generates the following code. X_moons, y_moons = datasets.make_moons(n_samples=1000, noise=.07, random_state=42) The case is that I would like to make a dendrogram (bottom-up) in Python and I must select a linkage criterion. If you consult the documentation of the function you can see the exist...
[ "There is no direct way to know which linkage is best. However, by looking at spread of data we can best guess. For your case, single linkage will produce best result. \n\nSingle linkage works best if cluster is in form of a chain. Complete linkage is more appropriate for data with globules/spherical clusters.\nIf ...
[ 0 ]
[]
[]
[ "hierarchical_clustering", "python" ]
stackoverflow_0074354059_hierarchical_clustering_python.txt
Q: How do I return null for missing xml parameters from API I am pulling data from the following site and creating a series of lists with the results which ultimately get appended into a dataframe. When the data is missing from my requests it won't write Nope in the list which leads to misalignment of tabular data. T...
How do I return null for missing xml parameters from API
I am pulling data from the following site and creating a series of lists with the results which ultimately get appended into a dataframe. When the data is missing from my requests it won't write Nope in the list which leads to misalignment of tabular data. The lists can contain from 40 to 46 items depending. for elemen...
[ "Have you tried checking if elm.text is None? What happens when you try to print elm.text? By the way, to be more Pythonic and play nicer with Pandas, append the result as a None data type instead of \"Nope\".\n" ]
[ 0 ]
[]
[]
[ "null", "parsing", "python", "xml" ]
stackoverflow_0074410532_null_parsing_python_xml.txt
Q: Keras beginner question, how to resolve Shapes (None, 6) and (None, 6, 6) are incompatible I am starting out on learning keras and ran into this issue that does not make sense to me. I have a very simple model and I want to pass a trivial data to train on. I want to pass the model two training examples, each 6 ele...
Keras beginner question, how to resolve Shapes (None, 6) and (None, 6, 6) are incompatible
I am starting out on learning keras and ran into this issue that does not make sense to me. I have a very simple model and I want to pass a trivial data to train on. I want to pass the model two training examples, each 6 elements long, as input. I have two 3 element arrays as labels in one-hot-encoding format. I am get...
[ "Your x_train has shape (BATCH_SIZE, 6), so the input_shape to your model should be (6,), not (6,1). Try this instead:\nfinalModel.add(Dense(6, input_shape=(6,), activation='relu'))\nfinalModel.add(Dense(3, activation='relu'))\nfinalModel.add(Dense(3, activation='relu'))\nfinalModel.add(Dense(3, activation='sigmoid...
[ 0 ]
[]
[]
[ "keras", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074410349_keras_machine_learning_python_tensorflow.txt
Q: 3D graphing the complex values of a function in Python This is the real function I am looking to represent in 3D: y = f(x) = x^2 + 1 The complex function would be as follows: w = f(z) = z^2 + 1 Where z = x + iy and w = u + iv. These are four dimentions (x, y, u, v), but one can use u for 3D graphing. We get: f(x +...
3D graphing the complex values of a function in Python
This is the real function I am looking to represent in 3D: y = f(x) = x^2 + 1 The complex function would be as follows: w = f(z) = z^2 + 1 Where z = x + iy and w = u + iv. These are four dimentions (x, y, u, v), but one can use u for 3D graphing. We get: f(x + iy) = x^2 + 2xyi - y^2 + 1 So: u = x^2 - y^2 + 1 and v = ...
[ "The f(z) = z^2 + 1 projection (that is, side-view) looks OK to me. You can use this technique to add the projections; this code:\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\ndef f(z):\n return z**2 + 1\n\ndef freal(x, y):\n return x**2 - y**2 + 1\n\nx = np.linspace(-100...
[ 1 ]
[]
[]
[ "graph", "matplotlib", "multidimensional_array", "numpy", "python" ]
stackoverflow_0074409108_graph_matplotlib_multidimensional_array_numpy_python.txt
Q: getting 200 response from requests lib but not through Scrapy in python I have tried to scrap data using scrapy spider in python to the targeted URL: https://www.accenture.com/ro-en/services/data-analytics-index#block-what-we-think but it returns the Error: twisted.python.failure.Failure builtins.ValueError: not e...
getting 200 response from requests lib but not through Scrapy in python
I have tried to scrap data using scrapy spider in python to the targeted URL: https://www.accenture.com/ro-en/services/data-analytics-index#block-what-we-think but it returns the Error: twisted.python.failure.Failure builtins.ValueError: not enough values to unpack (expected 2, got 1) But if i try to scrape data using ...
[ "It is a known issue in the upstream library twisted due to the website sending a large header.\nIf you check the headers for the above URL, you can see that the content-security-policy is too long.\n❯ curl -I \"https://www.accenture.com/ro-en/services/data-analytics-index#block-what-we-think\"\nHTTP/2 200 \nconten...
[ 0, 0 ]
[]
[]
[ "python", "python_requests", "scrapy", "web_scraping" ]
stackoverflow_0074140878_python_python_requests_scrapy_web_scraping.txt
Q: Double click on python file only 1 blink and no execute I double click on my python file, which simply prints Hello world but it only a black thing flashed and disappears. The terminal is not opened. My other PC works fine. I need to do it this way since the Task Scheduler show the same black thing flash when I ru...
Double click on python file only 1 blink and no execute
I double click on my python file, which simply prints Hello world but it only a black thing flashed and disappears. The terminal is not opened. My other PC works fine. I need to do it this way since the Task Scheduler show the same black thing flash when I run task on executing python script. I spent 2 hours searching ...
[ "input('Press ENTER to exit')\n\nIf you add this line to the end of your code, the terminal should wait for your you to press the enter key before closing.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074410121_python.txt
Q: Schedule a Job every minute on the exact minute during specific times using Python Schedule Library? I am using the Python Schedule Library and I have been using the following line of code to schedule a job to run every minute, on the exact minute regardless what time the program is started. For instance, if the p...
Schedule a Job every minute on the exact minute during specific times using Python Schedule Library?
I am using the Python Schedule Library and I have been using the following line of code to schedule a job to run every minute, on the exact minute regardless what time the program is started. For instance, if the program is ran at 13:51:30, rather than starting one minute after that time which would be 13:52:30, it wil...
[ "I hope I understood the question correctly. I use this:\ndef func():\nnow_datetime = datetime.now()\nif (now_datetime.hour >= 10) & (now_datetime.hour < 11) :\n print(now_datetime)\n\n\ndef main():\n while True:\n schedule.every().minute.at(':00').do(func)\n\n while True:\n schedule....
[ 0 ]
[]
[]
[ "python", "schedule" ]
stackoverflow_0074401259_python_schedule.txt
Q: I'm stuck on trying to sort by the given date I seem to not be able to sort it by the date in the def display_assignment_by_due_date(self) part of the code. I tried the .sort() but it didn't work. Am I doing it wrong or is there a different way? class Assignment: def __init__(self): self.assignments = ...
I'm stuck on trying to sort by the given date
I seem to not be able to sort it by the date in the def display_assignment_by_due_date(self) part of the code. I tried the .sort() but it didn't work. Am I doing it wrong or is there a different way? class Assignment: def __init__(self): self.assignments = [] def add(self, due_date, course): ad...
[ "Try this:\nfrom datetime import datetime\nand:\ndef display_assignment_by_due_date(self):\n print(\"Display assignments by due dates.\")\n ## Here \n self.assignments.sort(key=lambda date: datetime.strptime(date[0], \"%m/%d/%Y\"))\n for assignment in self.assignments:\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074410529_python.txt
Q: Python script for 'ps aux' command I have tried to use subprocess.check_output() for getting the ps aux command using python but it looks like not working with the large grep string. Can anyone have any solution? subprocess.check_output('ps aux | grep "bin/scrapy" | grep "option1" | grep "option2" | grep "option3"...
Python script for 'ps aux' command
I have tried to use subprocess.check_output() for getting the ps aux command using python but it looks like not working with the large grep string. Can anyone have any solution? subprocess.check_output('ps aux | grep "bin/scrapy" | grep "option1" | grep "option2" | grep "option3" | grep "option4" | grep "option5"' , sh...
[ "You can use the following code snippet for executing commands on remote host\n# create ssh client\n\nssh = paramiko.SSHClient()\n\n# add host key\n\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n# connect to host\n\nssh.connect(hostname='somehost', username='someuser', password='somepass')\n\n\n# Lo...
[ 0, 0 ]
[]
[]
[ "command", "process", "python", "python_3.x", "shell" ]
stackoverflow_0073669362_command_process_python_python_3.x_shell.txt
Q: how to search in List which contains tuples? I am having a list which having tuple object and I need to search the list for all tuples which contain the string typed in search box. can anyone please help me into this? I created one search box which having binding function. I can get the text from search box. but f...
how to search in List which contains tuples?
I am having a list which having tuple object and I need to search the list for all tuples which contain the string typed in search box. can anyone please help me into this? I created one search box which having binding function. I can get the text from search box. but for the same text I need to find objects form the l...
[ "\nbut for the same text I need to find objects form the list\n\nThere are many ways to search through a string (i.e. how will you handle spaces in words? If someone types \"Transducer Lower\" would you want the tuple in index 2 to be a result?\nBut to access what I think is what you're looking for, you would index...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074410660_python.txt
Q: Serialising with cattrs and want to omit field x1 string field Using cattrs to structure data and I want to omit x1 string field. I want to perform a trivial cleanup on strings that have been passed in except for the password field. I can get it to work on all strings from attrs import define from cattrs import Co...
Serialising with cattrs and want to omit field x1 string field
Using cattrs to structure data and I want to omit x1 string field. I want to perform a trivial cleanup on strings that have been passed in except for the password field. I can get it to work on all strings from attrs import define from cattrs import Converter MYDATA = { "hostname": "MYhostNAme ", ...
[ "I'm the author of cattrs. Let's see how we can solve this.\nFirst we need a way to recognize which fields you want to tidy up and which you don't. Looks like you'd like to apply tidying to all strings by default and opt-out for some fields.\nOption #1: NewType\nUse a NewType for the password field.\nfrom typing im...
[ 0 ]
[]
[]
[ "python", "python_attrs", "serialization" ]
stackoverflow_0074383981_python_python_attrs_serialization.txt
Q: Replace span tags with whitespace or parse contents as new column with pandas.read_html I want to scrape Congressional stock trades from Capitol Trades. I can scrape the data, but the column that contains stock tickers has a span tag that separates company names from company tickers. pandas.read_html() removes thi...
Replace span tags with whitespace or parse contents as new column with pandas.read_html
I want to scrape Congressional stock trades from Capitol Trades. I can scrape the data, but the column that contains stock tickers has a span tag that separates company names from company tickers. pandas.read_html() removes this span tag, which concatenates company names and tickers and makes it difficult to recover ti...
[ "To separate company names and tickers or parse the span as another column aka to get overall neat and clean ResultSet, you can change your tool selection strategy a bit. In this case, It would be better to apply bs4 with pandas DataFrame instead of pd.read_html() method.\nFull working code as an example:\nimport ...
[ 1, 1 ]
[]
[]
[ "beautifulsoup", "pandas", "python", "selenium" ]
stackoverflow_0074409839_beautifulsoup_pandas_python_selenium.txt
Q: How to add new site language in Django admin I work on a project where we want to have multilingual site. We start with two languages defined in settings.py LANGUAGES = ( ("en-us", _("United States")), ("cs", _("Czech Republic")), ) I am not the programmer doing the work but if I understood correctly all ...
How to add new site language in Django admin
I work on a project where we want to have multilingual site. We start with two languages defined in settings.py LANGUAGES = ( ("en-us", _("United States")), ("cs", _("Czech Republic")), ) I am not the programmer doing the work but if I understood correctly all we need is to be able to add - for example - Frenc...
[ "The short answer is that you can't do that.\nThe settings.py of a Django project is not designed, and not recommended to be modified by the web application.(It can introduce a security breach.)\nSo I recommend to change LANGUAGES manually, or to enable all languages supported by Django by removing LANGUAGES key. O...
[ 7 ]
[]
[]
[ "django", "internationalization", "multilingual", "python" ]
stackoverflow_0074370833_django_internationalization_multilingual_python.txt
Q: I can't check broken images from a url I am trying from a basic code from python to be able to verify the images that are broken, but I do not know how to do it this is the code i am using: from os import listdir from PIL import Image img = Image.open('https://furniload.com/furni/js_c16_lounger.png') img.verify(...
I can't check broken images from a url
I am trying from a basic code from python to be able to verify the images that are broken, but I do not know how to do it this is the code i am using: from os import listdir from PIL import Image img = Image.open('https://furniload.com/furni/js_c16_lounger.png') img.verify() print('Bad file:' +img) Can someon...
[ "There are a couple of things that needs to be done to verify if a file from web is an image or not.\n\nPIL.Image method accepts a file object or a string for local file, whereas you are trying to provide a web link. [You can download the file, save it locally and then open it.]\nYou need to catch the exception, if...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074410326_python.txt
Q: Count the number of complex, real and pure imaginary numbers in a numpy matrix Given a Numpy array/matrix, what is pythonic way to count the number of complex, pure real and pure imaginary number: [[ 1. +0.j 1. +0.j 1. +0.j 1. +0.j 1. +0.j ] [ 1. +0.j 0.309+0.951j -0.809+0.588j -...
Count the number of complex, real and pure imaginary numbers in a numpy matrix
Given a Numpy array/matrix, what is pythonic way to count the number of complex, pure real and pure imaginary number: [[ 1. +0.j 1. +0.j 1. +0.j 1. +0.j 1. +0.j ] [ 1. +0.j 0.309+0.951j -0.809+0.588j -0.809-0.588j 0.309-0.951j] [ 1. +0.j -0.809+0.588j 0.309-0.951j 0.309+0.951...
[ "\ncomplex\n\nA number is complex if and only if its imaginary part is not zero, and its real part is not zero. Therefore:\nnp.count_nonzero(\n np.logical_and(\n np.logical_not(\n np.equal(x.imag, 0)\n ),\n np.logical_not(\n np.equal(x.real, 0)\n )\n )\n)\n\n\...
[ 1 ]
[]
[]
[ "numpy", "python", "python_cmath" ]
stackoverflow_0074410625_numpy_python_python_cmath.txt
Q: How to read location coordinates of MODIS HDF file with Python GDAL? I am trying to read a MODIS HDF file with Python. I have used GDAL and pyhdf libraries. However, I am unsure why GDAL is unable to read location coordinates whereas pyhdf can read the same easily. Following is the simple python code. from pyhdf i...
How to read location coordinates of MODIS HDF file with Python GDAL?
I am trying to read a MODIS HDF file with Python. I have used GDAL and pyhdf libraries. However, I am unsure why GDAL is unable to read location coordinates whereas pyhdf can read the same easily. Following is the simple python code. from pyhdf import SD from osgeo import gdal filename = 'MYD04_3K.A2016001.0310.061.20...
[ "Check lines from 1952 to 1954 in\nhttps://github.com/OSGeo/gdal/blob/master/frmts/hdf4/hdf4imagedataset.cpp\npyhdf doesn't look for lat/lon datasets. It's a simple wrapper for HDF4 library.\n" ]
[ 0 ]
[]
[]
[ "gdal", "hdf5", "pyhdf", "python" ]
stackoverflow_0074341571_gdal_hdf5_pyhdf_python.txt
Q: Convert a tuple into a String and replace square brackets with round ones Python I am trying to replace square brackets in a tuple with round brackets which I had converted into a String and then tried to replace. Below is the code I am trying. def fetch_values_from_csv_and_store_it_in_tuple(test_case_name,file_na...
Convert a tuple into a String and replace square brackets with round ones Python
I am trying to replace square brackets in a tuple with round brackets which I had converted into a String and then tried to replace. Below is the code I am trying. def fetch_values_from_csv_and_store_it_in_tuple(test_case_name,file_name): df = expected_df = read_csv( "{}/output/Float_Ingestion_Expected_Outp...
[ "\ntable_tpl.replace('[','(')\n\n.replace returns the new string, but you are just throwing the return value away. You will have to do something like\ntable_tpl = table_tpl.replace('[','(')\ntable_tpl = table_tpl.replace(']',')')\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074410757_python.txt
Q: What does the function name `ravel` stand for in `NumPy`? What does ravel stand for in NumPy? Sometimes, it is a bit harder to remember a function name that the name has nothing to do with its description. A: The dictionary meaning for ravel is to become unwoven, untwisted, or unwound We tend to use unravel in ...
What does the function name `ravel` stand for in `NumPy`?
What does ravel stand for in NumPy? Sometimes, it is a bit harder to remember a function name that the name has nothing to do with its description.
[ "The dictionary meaning for ravel is\nto become unwoven, untwisted, or unwound\n\nWe tend to use unravel in same way\nto separate or undo the texture of : UNRAVEL\n\nhttps://www.merriam-webster.com/dictionary/ravel\nIn numpy flatten does the same thing, except it always makes a copy. ravel is more like reshape(-1)...
[ 4, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074410736_numpy_python.txt
Q: How do I print a dictionary's keys based on its value? So, I've created a dictionary of key, value pairs for course name and student ID respectively. I want to be able to iterate through the dictionary and print all of the keys (course names) that contain a particular value (student ID). So, here's the first initi...
How do I print a dictionary's keys based on its value?
So, I've created a dictionary of key, value pairs for course name and student ID respectively. I want to be able to iterate through the dictionary and print all of the keys (course names) that contain a particular value (student ID). So, here's the first initialization of variables followed by asking the user to input ...
[ "The list comprehension k, v in c_roster.items() returns k, v pairs such that k is the course name and v is the list of student IDs registered for that class.\nTherefore you are comparing the ID id_ to a list of student IDs, which will never be true.\nYou will have to see if id_ is in v, like\nc_list = [k for k, v ...
[ 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074410752_dictionary_list_python.txt
Q: Module not found error in VS code despite the fact that I installed it I'm trying to debug some python code using VS code. I'm getting the following error about a module that I am sure is installed. Exception has occurred: ModuleNotFoundError No module named 'SimpleITK' File "C:\Users\Mido\Desktop\ProstateX-pro...
Module not found error in VS code despite the fact that I installed it
I'm trying to debug some python code using VS code. I'm getting the following error about a module that I am sure is installed. Exception has occurred: ModuleNotFoundError No module named 'SimpleITK' File "C:\Users\Mido\Desktop\ProstateX-project\src\01-preprocessing\03_resample_nifti.py", line 8, in <module> imp...
[ "After install new module with pip if vscode not recognize it, reloading vscode may work.\n\nEnsure that the module installed inside virtual environment\n\nCreate and activate virtualenv\npython3 -m venv env\nsource env/bin/activate\n\nUse correct way of install module with pip\npython3 -m pip install {new_module}\...
[ 32, 28, 16, 5, 5, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "module", "python", "visual_studio_code" ]
stackoverflow_0056658553_module_python_visual_studio_code.txt
Q: 'socket' object has no attribute 'sendfile' while sending a file in flask + gunicorn + nginx + supervisor setup Using flask, I'm trying to send a file to the user on clicking a button in UI using send_from_directory function. It used to work fine. I wanted to change the repo and since changing it, I'm no more able...
'socket' object has no attribute 'sendfile' while sending a file in flask + gunicorn + nginx + supervisor setup
Using flask, I'm trying to send a file to the user on clicking a button in UI using send_from_directory function. It used to work fine. I wanted to change the repo and since changing it, I'm no more able to download the file. On looking at the supervisor log, I see this: [9617] [ERROR] Error handling request Traceback ...
[ "For me, usually when a script works locally but not when hosted its one (or more) of these possibilities:\n\nLocation / path to the files is different\nolder version of python\nolder version of the library\n\n", "Pointing the virtual env to Python 3.6 and upgrading all the relevant libraries including Flask reso...
[ 0, 0 ]
[]
[]
[ "flask", "nginx", "python", "supervisord" ]
stackoverflow_0074364465_flask_nginx_python_supervisord.txt
Q: Enter Output of Break and Continue Problem I'm a beginner CS student learning Python right now. I have a very basic challenge on Zybooks that wants me to enter the output of the code provided. It's designed to help understand how break and continue statements work within for and while loops. I've tried to go throu...
Enter Output of Break and Continue Problem
I'm a beginner CS student learning Python right now. I have a very basic challenge on Zybooks that wants me to enter the output of the code provided. It's designed to help understand how break and continue statements work within for and while loops. I've tried to go through the logic of each line of code, and I just ca...
[ "Using break will simply stop the loop and exit it, without continuing to iterate and execute the code.\nUsing continue will stop executing the block, will iterate and will work normaly from there\nFor example:\nfor i in range(10):\n print(i)\n if i > 5:\n break\n print(i)\n\nThe code above will stop at i==6\...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0070356841_python.txt
Q: Passing a list through a function positional argument issue So I've used the below code to 1)grab all .docx files 2)convert them to csv files 3)create dataframes for each file. The issue is that once I run the code, I get the following error, "TypeError: Document() takes from 0 to 1 positional argument but 450 wer...
Passing a list through a function positional argument issue
So I've used the below code to 1)grab all .docx files 2)convert them to csv files 3)create dataframes for each file. The issue is that once I run the code, I get the following error, "TypeError: Document() takes from 0 to 1 positional argument but 450 were given". I think this issue is coming from passing the list as a...
[ "From help(Document):\n\nDocument(docx=None)\nReturn a |Document| object loaded from *docx*, where *docx* can be\neither a path to a ``.docx`` file (a string) or a file-like object. If\n*docx* is missing or ``None``, the built-in default document \"template\"\nis loaded.\n\n\nSo you need to process individual files...
[ 1 ]
[]
[]
[ "dataframe", "list", "loops", "python" ]
stackoverflow_0074410821_dataframe_list_loops_python.txt
Q: Python Pandas: list of dicts in column, create list of specifc dict key as output I am trying to parse a dataframe column called 'tags' that contains a list of dicts and as an output create a list of the values of the key var1: Dataframe column 'tags' example value: [{'var1': 'blue','var2': 123,'var3': 888},{'var1...
Python Pandas: list of dicts in column, create list of specifc dict key as output
I am trying to parse a dataframe column called 'tags' that contains a list of dicts and as an output create a list of the values of the key var1: Dataframe column 'tags' example value: [{'var1': 'blue','var2': 123,'var3': 888},{'var1': 'red','var2': 123,'var3': 888},{'var1': 'green','var2': 123,'var3': 888}] desired o...
[ "Error obviously means some missing values instead lists, for avoid it add if-else with empty lists in ouput if missing in tags:\ndf['new'] = [[] if isinstance(x, float) else [y.get('var1') for y in x] for x in df['tags']]\n\n", "df.tag.apply(lambda x:x['var1']).tolist()\n\n" ]
[ 2, 0 ]
[]
[]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0074402123_pandas_python_python_3.x.txt
Q: select randomly rows from a dataframe based on a column value I have a data frame called df of which its value counts are the following: df.Priority.value_counts() P3 39506 P2 3038 P4 1138 P1 1117 P5 252 Name: Priority, dtype: int64 I am trying to create a balanced dataset called df_balanced ...
select randomly rows from a dataframe based on a column value
I have a data frame called df of which its value counts are the following: df.Priority.value_counts() P3 39506 P2 3038 P4 1138 P1 1117 P5 252 Name: Priority, dtype: int64 I am trying to create a balanced dataset called df_balanced from df by restricting the number of entries in the P3 category to ...
[ "A possible solution:\nimport random\n\n# this is the maximum limit of elements of P1, which will be\n# randomly chosen\nmaxlim_catP1 = 4\n\ndf.groupby('X').apply(\n lambda g: g.loc[random.sample(g.index.to_list(), min(maxlim_catP1, len(g))), :] if\n (g.loc[g.index[0], 'X'] == 'P1') else g)\n\nOutput:\n ...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074406034_dataframe_pandas_python.txt
Q: Tkinter gui not displaying in python I am making this app where it will display the name of a random friend from a list(the list is in the code). But nothing is displaying in the tkinter window when I run the app except the title The code: # -*- coding: utf-8 -*- """ Created on Sat Nov 12 11:42:32 2022 @author: T...
Tkinter gui not displaying in python
I am making this app where it will display the name of a random friend from a list(the list is in the code). But nothing is displaying in the tkinter window when I run the app except the title The code: # -*- coding: utf-8 -*- """ Created on Sat Nov 12 11:42:32 2022 @author: Techsmartt """ from tkinter import * import...
[ "You need to move your GUI code outside the randomnumber function, otherwise the widget is never created:\nfrom tkinter import *\nimport random\n\nroot = Tk()\nroot.title(\"Luck Friend Wheel\")\nroot.geometry(\"400x400\")\n\nlist = [\"James\", \"Isabella\", \"Sophia\", \"Olivia\", \"Peter\"]\n\ndef randomnumber():\...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074410977_python_tkinter.txt
Q: How to convert Yolo format bounding box coordinates into OpenCV format I have Yolo format bounding box annotations of objects saved in a .txt files. Now I want to load those coordinates and draw it on the image using OpenCV, but I don’t know how to convert those float values into OpenCV format coordinates values I...
How to convert Yolo format bounding box coordinates into OpenCV format
I have Yolo format bounding box annotations of objects saved in a .txt files. Now I want to load those coordinates and draw it on the image using OpenCV, but I don’t know how to convert those float values into OpenCV format coordinates values I tried this post but it didn’t help, below is a sample example of what I am ...
[ "There's another Q&A on this topic, and there's this1 interesting comment below the accepted answer. The bottom line is, that the YOLO coordinates have a different centering w.r.t. to the image. Unfortunately, the commentator didn't provide the Python port, so I did that here:\nimport cv2\nimport matplotlib.pyplot ...
[ 38, 4, 0, 0 ]
[]
[]
[ "opencv", "python", "yolo" ]
stackoverflow_0064096953_opencv_python_yolo.txt
Q: Modify values to concatenate binary text data This topic is basically based on concatenation (of iterable data) or another such data type as list. In order to make printable representation, built-in repr returns an array object strong text containing single quotes next to opposite quotes, then, contain some metho...
Modify values to concatenate binary text data
This topic is basically based on concatenation (of iterable data) or another such data type as list. In order to make printable representation, built-in repr returns an array object strong text containing single quotes next to opposite quotes, then, contain some method associated with repr or the method used by a prev...
[ "you can modify\nmap(lambda x: repr(\"\".join(list(' '*10))), range(12))\nto this\nmap(lambda x: repr(\"\".join(list(' '*10)))[2:-2], range(12))\nhere is full code\n>>> k = map(lambda x: repr(\"\".join(list(' '*10)))[2:-2], range(12))\n>>> list(k)\n[' ', ' ', ' ', ' ', ' ', ' ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074410796_python.txt
Q: Create boot image from python file I want to create a bootable .iso image so that I can boot from a python file. Can you suggest how to do it? I haven't tried anything and expect to be able to boot from .py files A: You can use docker, It does something like this. You can read more about it here.
Create boot image from python file
I want to create a bootable .iso image so that I can boot from a python file. Can you suggest how to do it? I haven't tried anything and expect to be able to boot from .py files
[ "You can use docker, It does something like this.\nYou can read more about it here.\n" ]
[ 0 ]
[]
[]
[ "iso", "python", "python_3.x" ]
stackoverflow_0074410717_iso_python_python_3.x.txt
Q: How do I debug this code? I am doing an assessment and cannot figure anything out print("please enter your 5 marks below") #read 5 inputs mark1 = int(input("enter mark 1: ")) mark2 = int(input("enter mark 2: ")) mark3 = int(input("enter mark 3: ")) mark4 = int(input("enter mark 4: ")) mark5 = int(in...
How do I debug this code? I am doing an assessment and cannot figure anything out
print("please enter your 5 marks below") #read 5 inputs mark1 = int(input("enter mark 1: ")) mark2 = int(input("enter mark 2: ")) mark3 = int(input("enter mark 3: ")) mark4 = int(input("enter mark 4: ")) mark5 = int(input("enter mark 5: ")) #create array/list with five marks marksList = [mark1, ma...
[ "If when you said \"debug\", you are referring to inspect the values and validate it, then you can write some unit tests\nanother way is to install ipdb and set a ipdb.set_trace()\n", "How about this:\nN = 5\nprint(f\"please enter your {N} marks below\") \n\n# read inputs\ndef checked_input(tip: str) -> int:\n ...
[ 0, 0 ]
[]
[]
[ "average", "debugging", "python" ]
stackoverflow_0074411023_average_debugging_python.txt
Q: Call apis on web with py-script I try to call an API with http.client th error says that the 'http.client' has no attribute 'HTTPSConnection' The code is: import http.client conn = http.client.HTTPSConnection("www.banxico.org.mx") payload = '' headers = {} conn.request("GET", "/SieAPIRest/service/v1/series/SP682...
Call apis on web with py-script
I try to call an API with http.client th error says that the 'http.client' has no attribute 'HTTPSConnection' The code is: import http.client conn = http.client.HTTPSConnection("www.banxico.org.mx") payload = '' headers = {} conn.request("GET", "/SieAPIRest/service/v1/series/SP68257/datos/2022-11-11/2022-11-11?token=...
[ "The package http.client depends on modules such as ssl which are not supported when running inside the web browser. Rewrite your code to use supported APIs such as pyfetch.\n" ]
[ 0 ]
[]
[]
[ "api", "httpclient", "pyscript", "python" ]
stackoverflow_0074410387_api_httpclient_pyscript_python.txt
Q: How to create an if statement program to calculate a tip? I'm trying to write a program for my homework: Write a program to determine how much to tip the server in a restaurant. The tip should be 15% of the check, with a minimum of $2. The hint said to use an if statement, but i keep running into a alot of errors....
How to create an if statement program to calculate a tip?
I'm trying to write a program for my homework: Write a program to determine how much to tip the server in a restaurant. The tip should be 15% of the check, with a minimum of $2. The hint said to use an if statement, but i keep running into a alot of errors. I don't know how else to write it, I've been trying to figure ...
[ "It means you first use if statement to see if the check is more than 2 before you do the math\ncheck = 59\nif check > 2:\n tip = check * 0.15\n print(tip)\n\nOutput:\n8.85\n\n", "It's not clear whether only checks larger than $2 get tips, or whether tips must be at least $2.\nI'm guessing the former, becau...
[ 1, 0, 0 ]
[]
[]
[ "error_handling", "if_statement", "python", "python_2.7", "python_3.x" ]
stackoverflow_0074410922_error_handling_if_statement_python_python_2.7_python_3.x.txt
Q: can we make a programme where price increases everytime a purchase is done until we have no money left this is the code wallet = int(input("wallet = ")) price = 100 print("price = " + str(price)) while price <= 1000: if wallet >= price: ask = input('would you like to purchase again? (y/n)') if...
can we make a programme where price increases everytime a purchase is done until we have no money left
this is the code wallet = int(input("wallet = ")) price = 100 print("price = " + str(price)) while price <= 1000: if wallet >= price: ask = input('would you like to purchase again? (y/n)') if ask.upper() == "Y": left = int(wallet) - price wallet = left print("you...
[ "You should stop when you have not enough money\nwhile wallet >= price:\n\n\nAlso here's a better code, with removed useless conversion to int/str, and useless left that is always equals to wallet when used\nwallet = int(input(\"wallet = \"))\nprice = 100\nprint(\"price =\", price)\n\nwhile and wallet >= price:\n ...
[ 0 ]
[]
[]
[ "python", "python_3.x", "while_loop" ]
stackoverflow_0074411117_python_python_3.x_while_loop.txt
Q: how to assert that fastAPI cache is working? So I'm writing a function that use fastAPI cache to avoid making a bunch of post calls, then I'm wondering if is possible to write a test to validate that the functions is just called once and then reuse the cached value. from fastapi_cache.decorator import cache @cach...
how to assert that fastAPI cache is working?
So I'm writing a function that use fastAPI cache to avoid making a bunch of post calls, then I'm wondering if is possible to write a test to validate that the functions is just called once and then reuse the cached value. from fastapi_cache.decorator import cache @cache(expire=60) async def get_auth_token() -> str: ...
[ "Another idea: return token with timestamp, that you can check timestamp to verify whether it is get from function or cache.\nFor example:\nimport time\nfrom fastapi_cache.decorator import cache\n\n@cache(expire=60)\nasync def get_auth_token() -> str:\n ## just to exemplify\n return str(time.time())\n\n\nclas...
[ 0 ]
[]
[]
[ "fastapi", "python", "python_3.x", "unit_testing" ]
stackoverflow_0074411159_fastapi_python_python_3.x_unit_testing.txt
Q: Unable to find longest common prefix of a perfectly working code (escape or special characters issue) I have a problem where I want to find the longest common prefix of N strings given in an array. Below is a perfectly working code: def longestCommonPrefix(S) : if (len(S) == 0): return "" for i in ...
Unable to find longest common prefix of a perfectly working code (escape or special characters issue)
I have a problem where I want to find the longest common prefix of N strings given in an array. Below is a perfectly working code: def longestCommonPrefix(S) : if (len(S) == 0): return "" for i in range(len(S[0])): c = S[0][i] for j in range(len(S)): if (i == len(S[j]) or S[j...
[ "The data are malformed. I've made an assumption about what it should look like by escaping four single-quotes which results in the X list containing 5 elements (which is what I think is expected).\nI then implemented the longest common prefix function like this:\nX = [\n 'Class- VII-CBSE-Mathematics\\\\nInteger...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x", "replace", "string" ]
stackoverflow_0074411078_python_python_3.x_replace_string.txt
Q: apply defined function to column pandas and fuzzywuzzy I am using the fuzzywuzzy library to match strings in a reference list using Levenshtein Distance. I want to apply this function to a series, matching each value of the series to a value in a reference list, if the value of the series matches the value in the ...
apply defined function to column pandas and fuzzywuzzy
I am using the fuzzywuzzy library to match strings in a reference list using Levenshtein Distance. I want to apply this function to a series, matching each value of the series to a value in a reference list, if the value of the series matches the value in the reference list at a defined ratio, it either returns the val...
[ "The error seems pretty self explanatory. Here's a way to reproduce it:\n# sample data\nf = pd.DataFrame({'col': ['SOBEYS ABC', 2.0]})\nf['col'].apply(lambda x: fuzz.ratio(x, 'ABC'))\n\n 43 @functools.wraps(func)\n 44 def decorator(*args, **kwargs):\n---> 45 if len(args[0]) == 0 or len(args[1]) == 0:\n ...
[ 1 ]
[]
[]
[ "fuzzywuzzy", "pandas", "python" ]
stackoverflow_0074410988_fuzzywuzzy_pandas_python.txt
Q: ModuleNotFoundError: No module named 'playsound' what to do? I've been editing this mp3 player, but this error keeps apearing from tkinter import * from tkinter import messagebox import playsound #making the window window = Tk() window.title("button") window.geometry("350x450+500+200") #making the song fuction d...
ModuleNotFoundError: No module named 'playsound' what to do?
I've been editing this mp3 player, but this error keeps apearing from tkinter import * from tkinter import messagebox import playsound #making the window window = Tk() window.title("button") window.geometry("350x450+500+200") #making the song fuction def song(): playsound ("lights.mp3") # making texbox def Initi...
[ "Try importing playsound with PIP\n\npip install playsound\n\nAnd include in your code\nfrom playsound import playsound\nplaysound('/path/to/a/sound/file/you/want/to/play.mp3')\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074411022_python.txt
Q: How do I use a base class constructor for a cppclass in Cython? Suppose I have cdef extern from "foo.h": cppclass Base: Base(int i) # only constructor cdef cppclass Child(Base): __init__(): pass How do I make sure that Base(int) is called? The generated C++ for Child needs to initialize ...
How do I use a base class constructor for a cppclass in Cython?
Suppose I have cdef extern from "foo.h": cppclass Base: Base(int i) # only constructor cdef cppclass Child(Base): __init__(): pass How do I make sure that Base(int) is called? The generated C++ for Child needs to initialize Base in its constructor's initializer list; can I do that with Cython...
[ "I don't think it's currently possible.\nThe ability to define C++ classes within Cython (as opposed to wrapping existing C++ classes) is currently somewhat underdeveloped and undocumented (largely because there's a lot that you can't do).\n" ]
[ 1 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0074368397_cython_python.txt
Q: How to shift all elements of python list at once I have searched everywhere on how to rotate/shift each element of a list simultaneously (using different speed) but nothing is found. the solutions in the following links only shift the entire list or doesn't solve my issue: Efficient way to rotate a list in python ...
How to shift all elements of python list at once
I have searched everywhere on how to rotate/shift each element of a list simultaneously (using different speed) but nothing is found. the solutions in the following links only shift the entire list or doesn't solve my issue: Efficient way to rotate a list in python https://www.geeksforgeeks.org/python-ways-to-rotate-a-...
[ "You can do this using np.roll\nimport numpy as np\n\ntest_list = ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy']\n\n\ndef roll(lst, shift_factor):\n arr = np.array([list(item) for item in lst])\n arr = np.roll(arr, shift_factor, axis=1)\n return [''.join(sublist) for sublist in arr]\n\n \nnew_list = roll(te...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074411254_python.txt
Q: How I can send POST request How can I accept a POST request? I send the request itself through Postman, or maybe I didn't understand correctly and I'm going to the wrong steppe, but the essence of the task is this. I wrote an endpoint (POST) on DRF, then I will need to make a POST request to this endpoint, and map...
How I can send POST request
How can I accept a POST request? I send the request itself through Postman, or maybe I didn't understand correctly and I'm going to the wrong steppe, but the essence of the task is this. I wrote an endpoint (POST) on DRF, then I will need to make a POST request to this endpoint, and map the data, I would also be gratef...
[ "You can use different framework like Django, Flask, Fast API.\nBut you need a simple app you can use a http.server:\nimport argparse\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\n\n\nclass S(BaseHTTPRequestHandler):\n def _set_headers(self):\n self.send_response(200)\n self.send_hea...
[ 0 ]
[]
[]
[ "django_rest_framework", "http", "postman", "python" ]
stackoverflow_0074410914_django_rest_framework_http_postman_python.txt
Q: Set colour to wx.listbox item Wxpython provides the following api to change wx.listbox items colour: wx.ListBox.SetItemBackgroundColour(self, item, c) and wx.ListBox.SetItemForegroundColour(self, item, c) For some reason this functions fail to do so in my linux and windows. Any one know why? note that wx.ListBo...
Set colour to wx.listbox item
Wxpython provides the following api to change wx.listbox items colour: wx.ListBox.SetItemBackgroundColour(self, item, c) and wx.ListBox.SetItemForegroundColour(self, item, c) For some reason this functions fail to do so in my linux and windows. Any one know why? note that wx.ListBox.SetOwnBackgroundColor works perfe...
[ "My guess is that it is a limitation of the native widget. I've seen several widgets that you cannot set the background or foreground color of because that widget just doesn't support it on that platform, but it DOES support it on other platform(s). You can ask over on the wxPython mailing list to make sure though....
[ 1, 0 ]
[]
[]
[ "linux", "python", "windows", "wxpython", "wxwidgets" ]
stackoverflow_0013105419_linux_python_windows_wxpython_wxwidgets.txt
Q: How to fill null values of a feature present in polars dataframe with median values of the feature? I'm a pandas user but due to the advantages of polars dataframes over pandas, i tried switching to polars. When I did the switching, I encountered this problem of not knowing how to fill the null values of a feature...
How to fill null values of a feature present in polars dataframe with median values of the feature?
I'm a pandas user but due to the advantages of polars dataframes over pandas, i tried switching to polars. When I did the switching, I encountered this problem of not knowing how to fill the null values of a feature with it median values based on another correlated feature values. Take the example shown below: Name...
[ "You can use a window function (called with .over) to compute the median values per group \"IMDB Score\".\npl.col(\"Meta Score\").median().over(\"IMDB Score\")\nThat result can be the input of a fill_null expression.\nCombining that we have:\ndf = pl.DataFrame({\n \"Name\": [\"B\", \"C\", \"D\", \"E\", \"D\", \"...
[ 0 ]
[]
[]
[ "data_preprocessing", "python", "python_polars" ]
stackoverflow_0074410990_data_preprocessing_python_python_polars.txt
Q: Convert Categorical features to Numerical I have a lot of categorical columns and want to convert values in those columns to numerical values so that I will be able to apply ML model. Now by data looks something like below. Column 1- Good/bad/poor/not reported column 2- Red/amber/green column 3- 1/2/3 column 4- ...
Convert Categorical features to Numerical
I have a lot of categorical columns and want to convert values in those columns to numerical values so that I will be able to apply ML model. Now by data looks something like below. Column 1- Good/bad/poor/not reported column 2- Red/amber/green column 3- 1/2/3 column 4- Yes/No Now I have already assigned numerical va...
[ "You can do this for some of the rated columns by using df[colname].map({})or LabelEncoder() .\nThey will change each categorical data to numbers, so there is a weight between them, which means if poor is one and good is 3, as you can see, there is a difference between them. You want the model to know it, but if it...
[ 1, 0 ]
[]
[]
[ "categorical", "data_science", "encoding", "machine_learning", "python" ]
stackoverflow_0074398311_categorical_data_science_encoding_machine_learning_python.txt
Q: Python loop to run for certain amount of seconds I have a while loop, and I want it to keep running through for 15 minutes. it is currently: while True: #blah blah blah (this runs through, and then restarts. I need it to continue doing this except after 15 minutes it exits the loop) Thanks! A: Try this: imp...
Python loop to run for certain amount of seconds
I have a while loop, and I want it to keep running through for 15 minutes. it is currently: while True: #blah blah blah (this runs through, and then restarts. I need it to continue doing this except after 15 minutes it exits the loop) Thanks!
[ "Try this:\nimport time\n\nt_end = time.time() + 60 * 15\nwhile time.time() < t_end:\n # do whatever you do\n\nThis will run for 15 min x 60 s = 900 seconds.\nFunction time.time returns the current time in seconds since 1st Jan 1970. The value is in floating point, so you can even use it with sub-second precisio...
[ 145, 12, 3, 3, 2, 0 ]
[ "try this: \nimport time\nimport os\n\nn = 0\nfor x in range(10): #enter your value here\n print(n)\n time.sleep(1) #to wait a second\n os.system('cls') #to clear previous number\n #use ('clear') if you are using linux or mac!\n n = n + 1\n\n" ]
[ -4 ]
[ "python", "time", "timer", "while_loop" ]
stackoverflow_0024374620_python_time_timer_while_loop.txt
Q: Python Neuron class - Name Error on a class property I've been working on my code since yesterday and maybe I'm just tired but I'm stuck at a Name error and I can't understand why. What I'm trying to do is make a general neuran class and then a class for each type of neuron instantiated with an appropriate method ...
Python Neuron class - Name Error on a class property
I've been working on my code since yesterday and maybe I'm just tired but I'm stuck at a Name error and I can't understand why. What I'm trying to do is make a general neuran class and then a class for each type of neuron instantiated with an appropriate method for neuron type indicator. I'm not very fluent with classe...
[ "I can see several errors:\nthe first to are in the init of your _Neuron class, should be something like this\n\n1: your initialization parameters you need to put them in the init not when you declare the class\n\n2 If you use a list as a default parameter you can have inspected result since this is declared when t...
[ 1 ]
[]
[]
[ "deep_learning", "python" ]
stackoverflow_0074411106_deep_learning_python.txt
Q: Django images not showing up in template I've spent the whole day trying to find a solution for showing the images in the template but I couldn't find any solution to my case. This is my settings STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.joi...
Django images not showing up in template
I've spent the whole day trying to find a solution for showing the images in the template but I couldn't find any solution to my case. This is my settings STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ o...
[ "If images not load from static folder then do this\n# do comment static root path\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\n\n# add static dirs path like this\n\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]\n\n#----------- OR ---------------\n\nSTATICFILES_DIRS = [BASE_DIR / 'static']\n\nIf image...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_media", "django_templates", "python" ]
stackoverflow_0074408557_django_django_media_django_templates_python.txt
Q: opencv autocomplete not working on pycharm Pycharm doesn't autocomplete my opencv commands. I tried different import commands and some solutions i saw on here but none of them worked and i have to get this project done. Anyone knows how to fix it? I use pycharm community edition 2022.2 and pyhton 3.10.5 A: It's ...
opencv autocomplete not working on pycharm
Pycharm doesn't autocomplete my opencv commands. I tried different import commands and some solutions i saw on here but none of them worked and i have to get this project done. Anyone knows how to fix it? I use pycharm community edition 2022.2 and pyhton 3.10.5
[ "It's the problem with the opencv version. Opencv version in my environment was upgraded to 4.6.0.66(upgraded when using environment in other projects), then it stopped to autocomplete.\nThe last version I checked to have autocomplete work is 4.5.5.62, so uninstall opencv-python or opencv-contrib-python and install...
[ 6, 1 ]
[]
[]
[ "opencv", "pycharm", "python" ]
stackoverflow_0073174194_opencv_pycharm_python.txt
Q: How to get User ID from slash command of another bot? Actually I am making a Code which send user a message randomly by playing pokemeow(another bot). Basically, i use message content to get the userID when they use ;p but as bots moved to slash command there is no other way left to get it... How can I get it now?...
How to get User ID from slash command of another bot?
Actually I am making a Code which send user a message randomly by playing pokemeow(another bot). Basically, i use message content to get the userID when they use ;p but as bots moved to slash command there is no other way left to get it... How can I get it now? Here is my old code i use: @commands.Cog.listener() asyn...
[ "You can use message.type to detect whether slash commands have been triggered or not.\nif message.type == discord.MessageType.chat_input_command:\n ...\n\nYou could possibly chain that with a check to see whether the message is from the bot in question or not.\nDocs on discord.MessageType\n", "I don't know if yo...
[ 0, 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0073593722_bots_discord_discord.py_python.txt
Q: python logger changing it's own log level after error I have tried to write a script here that supports different log levels for the stream and file handlers. Initially I've set the log level for the stream hander to be ERROR and file to be INFO, however, after the first error, the stream handler is reporting at ...
python logger changing it's own log level after error
I have tried to write a script here that supports different log levels for the stream and file handlers. Initially I've set the log level for the stream hander to be ERROR and file to be INFO, however, after the first error, the stream handler is reporting at the DEBUG level and not with the format I've specified. It...
[ "It looks as if something might be calling logging.basicConfig() which would set up a StreamHandler for the root logger, and explain what you're seeing.\nThe basicConfig() call is either explicit somewhere in the code you call (not necessarily what's shown in your snippet above) or via accidentally calling logging....
[ 0, 0 ]
[]
[]
[ "logging", "python", "python_2.7" ]
stackoverflow_0051899849_logging_python_python_2.7.txt
Q: Count number of cases reaching a given deadline I have a dataframe similar to below: Case ID D1 D2 D3 D4 A Dec 2022 Feb 2023 May 2023 Jun 2024 B Jul 2020 May 2023 Aug 2024 C May 2019 Jul 2020 Dec 2021 D Jul 2020 Mar 2021 Apr 2021 Aug 2024 E May 2019 May 2023 Aug 2024 F Dec 2022 Feb 2023 May 2023 Aug 2024 G...
Count number of cases reaching a given deadline
I have a dataframe similar to below: Case ID D1 D2 D3 D4 A Dec 2022 Feb 2023 May 2023 Jun 2024 B Jul 2020 May 2023 Aug 2024 C May 2019 Jul 2020 Dec 2021 D Jul 2020 Mar 2021 Apr 2021 Aug 2024 E May 2019 May 2023 Aug 2024 F Dec 2022 Feb 2023 May 2023 Aug 2024 G Dec 2022 Feb 2023 May 2023 Aug 2024 ...
[ "I finally came to a solution, not sure if it is the most straight-forward way, but I think it works.\n# reshape data from wide to long and add a column \"has_deadline\" as marker. \ndf1 = df.set_index('Case ID').stack().reset_index(name='dates').rename(columns={'level_1': 'deadlines'})\ndf1['has_deadline'] = 1\n\n...
[ 1 ]
[]
[]
[ "date", "group_by", "pandas", "python" ]
stackoverflow_0074403733_date_group_by_pandas_python.txt
Q: Starlette - Type Error: FormData object is not callable I'm uploading an audio file to a Starlette server and I'm trying to access it the way they recommend in the docs, but it's giving me a not callable error. I gather the issue is calling .form() on the request object, but I'm not sure how else to read it in. Se...
Starlette - Type Error: FormData object is not callable
I'm uploading an audio file to a Starlette server and I'm trying to access it the way they recommend in the docs, but it's giving me a not callable error. I gather the issue is calling .form() on the request object, but I'm not sure how else to read it in. Server Route: @app.route('/api/upload_track/', methods=['POST']...
[ "The following error:\nTypeError: 'FormData' object is not callable\n\nis caused when returning the FormData object you obtained, by using await request.form(), from your endpoint (i.e., return audio_data)—which I am sure it is not the one you would like to return in the first place, but rather the audio_bytes. Now...
[ 1 ]
[]
[]
[ "audio", "post", "python", "reactjs", "starlette" ]
stackoverflow_0074402303_audio_post_python_reactjs_starlette.txt
Q: List of 2 letters 2 numbers? I'm looking for a list of 2 letters and then 2 numbers. Something like: aa00 aa01 aa02 aa03 aa04 ect. I am using this for a Python program that picks a random 4 digit number, a random 4 letter string, and a random 2 letter 2 number string. I tried combining half of the first two, but...
List of 2 letters 2 numbers?
I'm looking for a list of 2 letters and then 2 numbers. Something like: aa00 aa01 aa02 aa03 aa04 ect. I am using this for a Python program that picks a random 4 digit number, a random 4 letter string, and a random 2 letter 2 number string. I tried combining half of the first two, but it said that it could not add 'in...
[ "You can turn the number into a string just for the concatenation:\nresult = letters + str(number)\n\nBut if you want to have the numbers 0 through to 9 work too you probably want to zero-pad the number. You could use string formatting here, using str.format():\nresult = '{}{:02d}'.format(letters, number)\n\nBoth a...
[ 2, 0 ]
[]
[]
[ "int", "list", "python", "string" ]
stackoverflow_0027367965_int_list_python_string.txt
Q: Python faster than rust with py03 I am trying to speed up some python code using rust bindings with py03. i have implemented the following function in both python and rust: def _play_action(state, action): temp = state.copy() i1, j1, i2, j2 = action h1 = abs(temp[i1][j1]) h2 = abs(temp[i2][j2]) ...
Python faster than rust with py03
I am trying to speed up some python code using rust bindings with py03. i have implemented the following function in both python and rust: def _play_action(state, action): temp = state.copy() i1, j1, i2, j2 = action h1 = abs(temp[i1][j1]) h2 = abs(temp[i2][j2]) if temp[i1][j1] < 0: temp[i2]...
[ "This is probably caused by the overhead of the communication between python and Rust, the data you're passing is too small so I assume you're calling play_action many times. a better approach would be to batch your calls\n#[pyfunction]\nfn play_actions(data: Vec<([[i32; 9]; 9],[usize;4])>) -> Vec<[[i32; 9]; 9]> {\...
[ 1, 1 ]
[]
[]
[ "performance", "python", "rust" ]
stackoverflow_0074411455_performance_python_rust.txt
Q: tensorflow placeholder - understanding `shape=[None,` I'm trying to understand placeholders in tensorflow. Specifically what shape=[None, means in the example below. X = tf.placeholder(tf.float32, shape=[None, 128, 128, 3], name="X") This answer describes it as: You can think of a placeholder in TensorFlow as a...
tensorflow placeholder - understanding `shape=[None,`
I'm trying to understand placeholders in tensorflow. Specifically what shape=[None, means in the example below. X = tf.placeholder(tf.float32, shape=[None, 128, 128, 3], name="X") This answer describes it as: You can think of a placeholder in TensorFlow as an operation specifying the shape and type of data that wi...
[ "The first dimension represents the number of samples (images in your case). The reason why you do not want to hardcode a specific number there is to keep things flexible and allow for any number of samples. By putting None as the first dimension of the tensor you enable that. Consider the following 3 very common a...
[ 18, 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0051366871_python_tensorflow.txt
Q: is the .classes method of a imagedatagenorator sorted? anyone know if i am doing this right, basically i am trying to create a CM, i have got my y_pred and obviously i need my ground truths, or this i am trying to use testdata.classes (this is what they do online, testdata is an instance of imagedatagenerator) how...
is the .classes method of a imagedatagenorator sorted?
anyone know if i am doing this right, basically i am trying to create a CM, i have got my y_pred and obviously i need my ground truths, or this i am trying to use testdata.classes (this is what they do online, testdata is an instance of imagedatagenerator) however .classes seems to just return a sorted list of all of m...
[ "This is a common issue.\ngenerator.classes should not be used as ground truth labels, because they are not sorted the same way you would get predictions. So any metric you compute will be wrong.\nA general and correct way to do it is to iterate on the generator, assuming it is a subclass of Sequence:\nall_y_pred =...
[ 0 ]
[]
[]
[ "conv_neural_network", "imagedatagenerator", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074367878_conv_neural_network_imagedatagenerator_machine_learning_python_tensorflow.txt
Q: Write a python program to input an integer n and print sum of all its even and odd digits separately Digits mean numbers not places I tried but the logic is wrong I know N=input() L=len(N) N=int(N) sum_e=0 sum_o=0 for i in range(0,L+1): if i%2==0: sum_e=sum_e+i else: sum_o=sum_o+i print(sum...
Write a python program to input an integer n and print sum of all its even and odd digits separately
Digits mean numbers not places I tried but the logic is wrong I know N=input() L=len(N) N=int(N) sum_e=0 sum_o=0 for i in range(0,L+1): if i%2==0: sum_e=sum_e+i else: sum_o=sum_o+i print(sum_e, sum_o)
[ "You can implement this more succinctly by modulating the input value as follows:\nN = abs(int(input('Enter a number: ')))\n\neo = [0, 0]\n\nwhile N != 0:\n v = N % 10\n eo[v & 1] += v\n N //= 10\n\nprint(*eo)\n\nSample:\nEnter a number: 1234567\n12 16\n\n", "N=input()\n\nsum_e=0\nsum_o=0\n\nfor i in N:\...
[ 1, 0, 0 ]
[]
[]
[ "if_statement", "loops", "python" ]
stackoverflow_0074411268_if_statement_loops_python.txt
Q: How do I limit inputs to only be Specific multiples in Python? Currently doing a college assignment where we need to input and add 3 different scores. The Scores must be not be less than 0 or greater than 10, and they can only be in multiples of 0.5. It's the latter part I'm having trouble with. How do I tell the ...
How do I limit inputs to only be Specific multiples in Python?
Currently doing a college assignment where we need to input and add 3 different scores. The Scores must be not be less than 0 or greater than 10, and they can only be in multiples of 0.5. It's the latter part I'm having trouble with. How do I tell the program to give an error if the input isn't a multiple of 0.5? score...
[ "Nested if statement comes into play here. First it will check the condn is score>0 and score<10 then the next if statement of checking multiple statement comes to play. Use loop for taking input back to back until condn not met.\nscore = float(input(\"Enter score\"))\nif score>0 and score<10:\n if (score*10)%5 =...
[ 0, 0 ]
[]
[]
[ "if_statement", "input", "python" ]
stackoverflow_0074411514_if_statement_input_python.txt
Q: How to assign different fonts and size to title and axis in plotly? im trying to separately set the font/size for the axis and the title. Ex: For title: Font = Ariel and size = 12. For Axis: Font = Times New Roman and size = 20. Im using the following code to do it. fig.update_layout(font=dict(family='Times New Ro...
How to assign different fonts and size to title and axis in plotly?
im trying to separately set the font/size for the axis and the title. Ex: For title: Font = Ariel and size = 12. For Axis: Font = Times New Roman and size = 20. Im using the following code to do it. fig.update_layout(font=dict(family='Times New Roman',size=20,\ title=dict(font=dict(family='Ariel', size=12))) When I do...
[ "There are examples of changing titles, axis labels, etc. in the official reference. Based on this example, I further changed the partial color and size of the title. This tip is referenced here.\nimport plotly.express as px\n\ndf = px.data.iris()\nfig = px.scatter(df, x=\"sepal_length\", y=\"sepal_width\", color=\...
[ 1, 0 ]
[]
[]
[ "plotly", "plotly_python", "python" ]
stackoverflow_0073130052_plotly_plotly_python_python.txt
Q: How to find complement of a set? I have a list of interval time as follow list_1 = [[t0, t1], [t2, t3] , [t4, t5]] I want to write a function in Python that return the complement of the set, call list_2, so that list_1 unions with list_2 is a set with range from [0 to t]. Assume that we just consider 1 digit afte...
How to find complement of a set?
I have a list of interval time as follow list_1 = [[t0, t1], [t2, t3] , [t4, t5]] I want to write a function in Python that return the complement of the set, call list_2, so that list_1 unions with list_2 is a set with range from [0 to t]. Assume that we just consider 1 digit after point with float number For example,...
[ "Try this,\nlist_1 = [[10.5, 15], [20, 30]]\nstart_time, end_time, step = 0, 200, 0.1\n\nsub_end_lst, sub_start_lst = zip(*list_1)\nsub_start_lst = [start_time] + [t+step for t in sub_start_lst]\nsub_end_lst = [t-step for t in sub_end_lst] + [end_time]\nlist_2 = [[sub_start, sub_end] for sub_start, sub_end in zip(s...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074411519_python_python_3.x.txt
Q: Python check if span class exists So basically I want to get an output on boolean mode if a span class exists or no, but I don't know which libraries to use <span class="Smth"> Smth </span> I have tried searching some tutorials for requests but I didnt find anything A: You can simply do this; html = '<span cl...
Python check if span class exists
So basically I want to get an output on boolean mode if a span class exists or no, but I don't know which libraries to use <span class="Smth"> Smth </span> I have tried searching some tutorials for requests but I didnt find anything
[ "You can simply do this;\nhtml = '<span class=\"Smth\">Smth</span>'\n\nif html.find('span class=\"Smth\"') == -1:\n print(False)\n\nelse:\n print(True)\n\nIf you want to use any library then you can try beautifulsoup4\nfrom bs4 import BeautifulSoup\n\nhtml = '<span class=\"Smth\">Smth</span>'\n\nsoup = Beauti...
[ 1 ]
[]
[]
[ "html", "python", "web", "web_scraping" ]
stackoverflow_0074411684_html_python_web_web_scraping.txt
Q: How to calculate the correlation between two categorical variables in Python? I have a dataset containing two columns: | Food. | Gender | | -------- | -------- | | Soup. | Female | | Chicken | Male | | Beef | Male | | Chicken | Female | (it goes on) I would like to calculate the correlat...
How to calculate the correlation between two categorical variables in Python?
I have a dataset containing two columns: | Food. | Gender | | -------- | -------- | | Soup. | Female | | Chicken | Male | | Beef | Male | | Chicken | Female | (it goes on) I would like to calculate the correlation between these two variables. I have seen some methods but they mostly consider ...
[ "I would consider using Cramer V's coefficient as a measurement of multilabel categorical variables association. This can be implemented with scipy.stats.contingency.association via the following code example:\ndf = pd.DataFrame({'FOOD':['Soup']*16 + ['Chicken']*4 + ['Beef'] *10,\n 'GENDER':['Male...
[ 0 ]
[]
[]
[ "categorical_data", "correlation", "cross_correlation", "python", "python_3.x" ]
stackoverflow_0074411668_categorical_data_correlation_cross_correlation_python_python_3.x.txt
Q: Multiprocess error while using map function in python with N-Gram language model I wanna increase the accuracy of my speech2text model with using a N-Gram. So i'm using this line of code to apply the function on the whole dataset as below: result = dataset.map(predict, batch_size=5, num_proc=int(os.environ.get('cp...
Multiprocess error while using map function in python with N-Gram language model
I wanna increase the accuracy of my speech2text model with using a N-Gram. So i'm using this line of code to apply the function on the whole dataset as below: result = dataset.map(predict, batch_size=5, num_proc=int(os.environ.get('cpu_core'))) The CPU core I set for 'cpu_core' is 8. Here is the predict function code:...
[ "Finally I did fix this error. The BrokenPipeError: [Error 32] broken pipe is about linux operation system and it will be occur when you are doing IO tasks. So when the pipeline of read and write on linux getting closed, while at the other side the data is still trying to be written or read, this error will be occu...
[ 0 ]
[]
[]
[ "multiprocessing", "n_gram", "python", "speech_to_text" ]
stackoverflow_0073726816_multiprocessing_n_gram_python_speech_to_text.txt
Q: Complexe macOS command with suprocess Popen - Python I want to call this terminal command on macOS in python lsappinfo info -only name lsappinfo front. It returns the name of the current foreground application. Here is how I understand the command: lsappinfo return information about running apps info allows to s...
Complexe macOS command with suprocess Popen - Python
I want to call this terminal command on macOS in python lsappinfo info -only name lsappinfo front. It returns the name of the current foreground application. Here is how I understand the command: lsappinfo return information about running apps info allows to select specific data lsappinfo front select the foreground...
[ "this works:\ncmd1 = ['lsappinfo', 'front']\nname = subprocess.run(cmd1, shell=False, capture_output=True).stdout.decode('utf-8').strip(\"\\n\")\ncmd2 = ['lsappinfo', 'info', '-only', \"name\", name]\nout2 = subprocess.run(cmd2, shell=False, capture_output=True)\nprint(out2.stdout.decode('utf-8').strip(\"\\n\"))\n\...
[ 2, 0, 0 ]
[]
[]
[ "command_line", "python", "subprocess" ]
stackoverflow_0074411004_command_line_python_subprocess.txt
Q: AttributeError: 'tuple' object has no attribute 'values' getting error while concatenate multiple nested dictionaries using single function I'm trying the function to create the single dataframe using convert_df using pandas showing following error. I have to dataframe df, df1 want to convert into single dataframe...
AttributeError: 'tuple' object has no attribute 'values' getting error while concatenate multiple nested dictionaries using single function
I'm trying the function to create the single dataframe using convert_df using pandas showing following error. I have to dataframe df, df1 want to convert into single dataframe df = {1 : {'tp': 26, 'fp': 112}, 2 : {'tp': 26, 'fp': 91}, 3 : {'tp': 23, 'fp': 74}} df1 = {1 : {'tp1': 2633, 'fp1': 34}, 2 : {'tp1': 333, 'fp...
[ "Not sure what you exactly want, but if I guess correctly:\nd1 = {1 : {'tp': 26, 'fp': 112},\n 2 : {'tp': 26, 'fp': 91},\n 3 : {'tp': 23, 'fp': 74}}\n\nd2 = {1 : {'tp': 2633, 'fp': 34},\n 2 : {'tp': 333, 'fp': 9341},\n 3 : {'tp': 335, 'fp': 34}}\n\ndicts = [d1, d2]\n\ndef convert_df(dic):\n r...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074411814_dataframe_pandas_python.txt
Q: Migration of local Django project to pythonanywhere throws incorrect timezone error when running manage.py I have a local Django project that runs fine. I am following the instructions from pythonanywhere (https://help.pythonanywhere.com/pages/DeployExistingDjangoProject/). I set up a virtualenv and made sure my D...
Migration of local Django project to pythonanywhere throws incorrect timezone error when running manage.py
I have a local Django project that runs fine. I am following the instructions from pythonanywhere (https://help.pythonanywhere.com/pages/DeployExistingDjangoProject/). I set up a virtualenv and made sure my Django versions match. When I get to the point of running ./manage.py migrate I get a permission denied error: b...
[ "I was able to resolve this issue by commenting out the timezone from settings.py and adding the following to the top of my WSGI.\nimport time\n\nos.environ[\"TZ\"] = \"America/Los_Angeles\"\ntime.tzset()\n\n", "add this top of WSGI:\nimport time\n\nos.environ[\"TZ\"] = \"America/Los_Angeles\"\ntime.tzset()\n\nth...
[ 0, 0 ]
[]
[]
[ "django", "python", "pythonanywhere" ]
stackoverflow_0059056792_django_python_pythonanywhere.txt
Q: How to find how many tweets are extended tweets in Twitter Python with Twitter search API? I don't know how to count or even find tweets that are extended tweets. I have used Twitter Search API to search for random tweets, but my main problem is that I couldn't find extended tweets from 1000 tweets. So, could you ...
How to find how many tweets are extended tweets in Twitter Python with Twitter search API?
I don't know how to count or even find tweets that are extended tweets. I have used Twitter Search API to search for random tweets, but my main problem is that I couldn't find extended tweets from 1000 tweets. So, could you help me out and tell me what I am doing wrong? import tweepy import keys auth = tweepy.OAuthHan...
[ "The problem you are having is that tweepy has changed their api search functions. With the current version of tweepy (4.12.1), you need to use api.search_tweets(). \n\nIf you do not specify the tweet_mode parameter, the search_tweets method will default to compatibility mode (compat). If you want to retrieve exten...
[ 0 ]
[]
[]
[ "for_loop", "if_statement", "python", "python_3.x", "twitterapi_python" ]
stackoverflow_0074411760_for_loop_if_statement_python_python_3.x_twitterapi_python.txt
Q: Algorithm-finding-dedicated-sum-from-the-population-of-variables I need a way of finding an exact value made of the sum of variables chosen from the population. The algorithm can find just the first solution or all. So we can have 10, 20, or 30 different numbers and we will sum some of them to get a desirable numb...
Algorithm-finding-dedicated-sum-from-the-population-of-variables
I need a way of finding an exact value made of the sum of variables chosen from the population. The algorithm can find just the first solution or all. So we can have 10, 20, or 30 different numbers and we will sum some of them to get a desirable number. As an example we have a population of the below numbers: -2,-1,1,2...
[ "This is the subset sum problem, which is an NP Complete problem.\nThere is a known pseudo-polynomial solution for it, if the numbers are integers. In your case, you need to consider numbers only to 2nd decimal point, so you could convert the problem into integers by multiplying by 1001, and then run the pseudo-pol...
[ 1 ]
[]
[]
[ "algorithm", "linear_programming", "python", "simplex" ]
stackoverflow_0074411545_algorithm_linear_programming_python_simplex.txt
Q: How to use Python decord library to seek by timestamp instead of by frame index? Decord allows to seek a video frame from a file using indices, like: video_reader = decord.VideoReader(video_path) frames = video_reader.get_batch(indices) How can I do the same if I have timestamps (with the unit second)? A: You c...
How to use Python decord library to seek by timestamp instead of by frame index?
Decord allows to seek a video frame from a file using indices, like: video_reader = decord.VideoReader(video_path) frames = video_reader.get_batch(indices) How can I do the same if I have timestamps (with the unit second)?
[ "You can obtain the timestamp of each frame (averaging its start and end times), then find the closest one:\nfrom typing import Sequence, Union\n\nimport decord\nimport numpy as np\n\n\ndef time_to_indices(video_reader: decord.VideoReader, time: Union[float, Sequence[float]]) -> np.ndarray:\n times = video_reade...
[ 1, 0 ]
[]
[]
[ "frames", "python", "time", "video" ]
stackoverflow_0068488865_frames_python_time_video.txt
Q: How to convert total years and months to corresponding float/decimal values in pandas How do I convert the values of Years_in_service to its corresponding decimal/float values ? For example, '5 year(s), 7 month(s), 3 day(s)' has a decimal value of 5.59 import pandas as pd import numpy as np data = {'ID':['A1001'...
How to convert total years and months to corresponding float/decimal values in pandas
How do I convert the values of Years_in_service to its corresponding decimal/float values ? For example, '5 year(s), 7 month(s), 3 day(s)' has a decimal value of 5.59 import pandas as pd import numpy as np data = {'ID':['A1001','A5001','B1001','D5115','K4910'], 'Years_in_service': ['5 year(s), 7 month(s), 3 day(s)', ...
[ "How about this?\nAfter:\nimport pandas as pd \nimport numpy as np\n\ndata = {'ID':['A1001','A5001','B1001','D5115','K4910'],\n'Years_in_service': ['5 year(s), 7 month(s), 3 day(s)', '16 year(s), 0 month(s), 25 day(s)', \n'7 year(s), 0 month(s), 2 day(s)', '0 year(s), 11 month(s), 23 day(s)','1 year(s), 0 month(s),...
[ 2, 2, 1 ]
[ "i=1\nfor name in ['month','day']:\n df[name] = [date.split(',')[i].split(' ')[1] for date in df['Years_in_service']]\n df[name]=df[name].astype('float64')\n i+=1\ndf['years']=[date.split(',')[0].split(' ')[0] for date in df['Years_in_service']] \ndf['years'] = df['years'].astype('float64')\n\ni=12\nfor...
[ -1 ]
[ "datetime", "pandas", "python", "string" ]
stackoverflow_0074410863_datetime_pandas_python_string.txt
Q: Using short representation in list with values where remainder is 1 I am trying to find every value in the list which has a remainder of 1 by comparing the current value to the next one and output them in a short representation. For example a list of [1,2,3,4,5,10, 20, 30] should be outputted as 1-5 10 20 30, wher...
Using short representation in list with values where remainder is 1
I am trying to find every value in the list which has a remainder of 1 by comparing the current value to the next one and output them in a short representation. For example a list of [1,2,3,4,5,10, 20, 30] should be outputted as 1-5 10 20 30, where every current value to the next one has a remainder of 1, and leave the...
[ "This might be a little overcomplicated (there's invariably a better way) but it does seem to work and handle other edge cases I've tested.\nalist = [1, 2, 3, 4, 5, 10, 20, 30]\n\ndef func(a):\n result = [str(a[0])]\n m = False\n for prev, n in zip(a, a[1:]):\n if n - prev == 1:\n m = Tru...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074411646_python_python_3.x.txt
Q: can't get page source from selenium purpose: using selenium get entire page source. problem: loaded page does not contain content, only JavaScript files and css files. target site : https://www.warcraftlogs.com test code(need 'pip install selenium'): from selenium import webdriver driver = webdriver.Chrome() driv...
can't get page source from selenium
purpose: using selenium get entire page source. problem: loaded page does not contain content, only JavaScript files and css files. target site : https://www.warcraftlogs.com test code(need 'pip install selenium'): from selenium import webdriver driver = webdriver.Chrome() driver.get("https://www.warcraftlogs.com/zon...
[ "Here is a way of getting the page source, after all elements loaded:\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time as t\n[...]\nwait = WebDriverWait(driver, 5)\nurl='https://www.wa...
[ 1 ]
[]
[]
[ "python", "request", "selenium", "web_scraping" ]
stackoverflow_0074411522_python_request_selenium_web_scraping.txt
Q: Unable to insert UUID as integer in primary key column of a table created in spanner database I have model written in declarative base of SQL Alchemy. Class Roles(Base): __tablename__ = "roles" __table_args__ = ( Index("roles_name", "name", unique=True), ) id = Column(Integer, primary_key=...
Unable to insert UUID as integer in primary key column of a table created in spanner database
I have model written in declarative base of SQL Alchemy. Class Roles(Base): __tablename__ = "roles" __table_args__ = ( Index("roles_name", "name", unique=True), ) id = Column(Integer, primary_key=True, default=get_uuid()) name = Column(String(10), nullable=False) As you may have noticed I ...
[ "The generated int value is larger than the maximum INT64 value that is allowed in Cloud Spanner:\n\nMax allowed: 9223372036854775807\nYour value : 18011687921562567628\n\nSee https://cloud.google.com/spanner/docs/reference/standard-sql/data-types#integer_types for more information on the INT64 type.\nI'm no Python...
[ 1 ]
[]
[]
[ "google_cloud_spanner", "python", "sqlalchemy" ]
stackoverflow_0074411468_google_cloud_spanner_python_sqlalchemy.txt
Q: Grouping values in a column by a criteria and getting their mean using Python / Pandas I have data on movies and all movies have IMDB score, however some do not have a meta critic score Eg: Name IMDB Score Meta Score B 8 86 C 8 90 D 8 null E 8 91 F 7 66 G 3 44 I want to fill in the null values in the meta...
Grouping values in a column by a criteria and getting their mean using Python / Pandas
I have data on movies and all movies have IMDB score, however some do not have a meta critic score Eg: Name IMDB Score Meta Score B 8 86 C 8 90 D 8 null E 8 91 F 7 66 G 3 44 I want to fill in the null values in the meta critic score with the mean of the values of movies that have the same IMDB sc...
[ "groupby + fillna\ndf.groupby('IMDB Score')['Meta Score'].apply(lambda x: x.fillna(x.mean()))\n\noutput:\n0 86.0\n1 90.0\n2 89.0\n3 91.0\n4 66.0\n5 44.0\nName: Meta Score, dtype: float64\n\nmake result to Meta Score column\n", "You can sort the columns with missing values then do a forward fill:...
[ 1, 0, 0 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074410744_dataframe_numpy_pandas_python.txt
Q: removing emojis from a string in Python I found this code in Python for removing emojis but it is not working. Can you help with other codes or fix to this? I have observed all my emjois start with \xf but when I try to search for str.startswith("\xf") I get invalid character error. emoji_pattern = r'/[x{1F601}-x...
removing emojis from a string in Python
I found this code in Python for removing emojis but it is not working. Can you help with other codes or fix to this? I have observed all my emjois start with \xf but when I try to search for str.startswith("\xf") I get invalid character error. emoji_pattern = r'/[x{1F601}-x{1F64F}]/u' re.sub(emoji_pattern, '', word) ...
[ "On Python 2, you have to use u'' literal to create a Unicode string. Also, you should pass re.UNICODE flag and convert your input data to Unicode (e.g., text = data.decode('utf-8')):\n#!/usr/bin/env python\nimport re\n\ntext = u'This dog \\U0001f602'\nprint(text) # with emoji\n\nemoji_pattern = re.compile(\"[\"\n ...
[ 81, 55, 51, 25, 19, 18, 16, 9, 9, 8, 7, 5, 4, 4, 3, 3, 2, 1, 1, 0, 0, 0, 0 ]
[ "This does more than filtering out just emojis. It removes unicode but tries to do that in a gentle way and replace it with relevant ASCII characters if possible. It can be a blessing in the future if you don't have for example a dozen of various unicode apostrophes and unicode quotation marks in your text (usually...
[ -1 ]
[ "emoji", "python", "special_characters", "string", "unicode" ]
stackoverflow_0033404752_emoji_python_special_characters_string_unicode.txt
Q: How to activate my environment in linux automatically using .bashrc I would like to activate the environment that I created in Anaconda (myenv) automatically when linux server is opened. The myenv environment path is located in '/anaconda_env/personal/myenv'. I used the following command lines in .bashrc to automa...
How to activate my environment in linux automatically using .bashrc
I would like to activate the environment that I created in Anaconda (myenv) automatically when linux server is opened. The myenv environment path is located in '/anaconda_env/personal/myenv'. I used the following command lines in .bashrc to automatically activate myenv. However, "base" environment is always activated i...
[ "Try adding the following after last line in .bashrc\nconda activate /anaconda_env/personal/myenv\n" ]
[ 0 ]
[]
[]
[ "anaconda", "linux", "python" ]
stackoverflow_0074411850_anaconda_linux_python.txt
Q: How I getting or extract string by beautiful soup? how i do use beautifulsoup get only string num "611674069.14413534248" from url ? https://shopee.co.th/Kawasaki-%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B9%80% E0%B8%97%E0%B9%89%E0%B8%B2%E0%B8%81%E0%B8%B5%E0%B8%AC%E0%B8%B2%E0%B8%A5%E0%B9%8D%E0%B8%B2%E0%B8%A5%E0%B8%AD%E0%B8...
How I getting or extract string by beautiful soup?
how i do use beautifulsoup get only string num "611674069.14413534248" from url ? https://shopee.co.th/Kawasaki-%E0%B8%A3%E0%B8%AD%E0%B8%87%E0%B9%80% E0%B8%97%E0%B9%89%E0%B8%B2%E0%B8%81%E0%B8%B5%E0%B8%AC%E0%B8%B2%E0%B8%A5%E0%B9%8D%E0%B8%B2%E0%B8%A5%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B0%E0%B8%9A%E0%B8%9A%E0%B8%9 B%E0%B9%...
[ "Assuming you are using Selenium (as Shopee is a dynamic website), here is a complete minimal example of obtaining various bits of information from products, including that bit from url:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options im...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x", "web_scraping" ]
stackoverflow_0074411597_beautifulsoup_python_python_3.x_web_scraping.txt
Q: How to fix "FileNotFoundError" when using os.listdir in Google Colab? I am following a tutorial to load data from a local file using Google Colaboratory. Here is my code: import numpy as np #To do relay operations import matplotlib.pyplot as plt #to show image import os #Iterate through directories and join paths ...
How to fix "FileNotFoundError" when using os.listdir in Google Colab?
I am following a tutorial to load data from a local file using Google Colaboratory. Here is my code: import numpy as np #To do relay operations import matplotlib.pyplot as plt #to show image import os #Iterate through directories and join paths import cv2 #To do image operations DATADIR = "C:\\Users\\Family\\Desktop\\...
[ "If you are on Google collab, just in the left pane go to the directory and right-click, copy path. But if you are on your PC (Not Google Collab)\nI am not sure, I faced this problem before and this is my solution:\n\nGo to this directory\nOpen the cmd in this directory and write python\n\nwrite the following code ...
[ 0 ]
[]
[]
[ "google_colaboratory", "python" ]
stackoverflow_0074411971_google_colaboratory_python.txt
Q: Creating 2D dictionary in Python I have a list of details from an output for "set1" which are like "name", "place", "animal", "thing" and a "set2" with the same details. I want to create a dictionary with dict_names[setx]['name']... etc On these lines. Is that the best way to do it? If not how do I do it? I am not...
Creating 2D dictionary in Python
I have a list of details from an output for "set1" which are like "name", "place", "animal", "thing" and a "set2" with the same details. I want to create a dictionary with dict_names[setx]['name']... etc On these lines. Is that the best way to do it? If not how do I do it? I am not sure how 2D works in dictionary.. Any...
[ "It would have the following syntax\ndict_names = {\n 'd1': {\n 'name': 'bob',\n 'place': 'lawn',\n 'animal': 'man'\n },\n 'd2': {\n 'name': 'spot',\n 'place': 'bed',\n 'animal': 'dog'\n }\n}\n\nYou can then look things up like\n>>> dict_names['d1']['name']\n'bo...
[ 30, 3, 3, 0, 0 ]
[]
[]
[ "2d", "dictionary", "key", "python", "set" ]
stackoverflow_0025924244_2d_dictionary_key_python_set.txt
Q: Alternative to tf.parallel_stack() for eager execution I'd like to use tf.parallel_stack() for a data operation inside an eagerly-compiled model, but it seems that tf.parallel_stack() doesn't support eager execution. I'm therefore looking for alternative function(s) achieving the same result. Below is a small exam...
Alternative to tf.parallel_stack() for eager execution
I'd like to use tf.parallel_stack() for a data operation inside an eagerly-compiled model, but it seems that tf.parallel_stack() doesn't support eager execution. I'm therefore looking for alternative function(s) achieving the same result. Below is a small example of the required result: x = tf.constant([1, 4]) y = tf.c...
[ "Maybe try adding a new dimension:\ntf.concat((x[None, ...], y[None, ...], z[None, ...]), axis = 0)\n\n" ]
[ 0 ]
[]
[]
[ "python", "tensor", "tensorflow" ]
stackoverflow_0074406575_python_tensor_tensorflow.txt
Q: Is there a way to have your regex expression do a negative lookbehind to an exception list? I am trying to match a certain certain pattern, but want to exclude a list of undesireable matches. I tried using a negative lookahead, but the exceptions list does not get excluded. I used the regex expression: (\d+)\s+((?...
Is there a way to have your regex expression do a negative lookbehind to an exception list?
I am trying to match a certain certain pattern, but want to exclude a list of undesireable matches. I tried using a negative lookahead, but the exceptions list does not get excluded. I used the regex expression: (\d+)\s+((?:\b(?:N|S|E|W)\b)(?:\s+))((?!\b(?:ST|AVE|RD|CT)\b)(?:[a-zA-Z0-9_\s\-\/]+)+(?:\s+))((?:\b(?:N|S|E|...
[ "Instead of using a lookbehind, you might use a negative lookahead to assert that there is no occurrence of any of (?:ST|AVE|RD|CT) that is followed by either N S E W that by itself is followed by one of (?:APT|UNIT|#|LOT).\n(\\d+)\\s+([NSEW])(?!\\s.*?\\b(?:ST|AVE|RD|CT)\\s+[NSEW]\\s(?:APT|UNIT|#|LOT))\\s+(.*?)\\s+...
[ 1 ]
[]
[]
[ "python", "regex", "regex_lookarounds" ]
stackoverflow_0074393343_python_regex_regex_lookarounds.txt
Q: Getting links and background image from a certain div's using - Selenium in Python I'm trying to get all the links and background images of the links inside a specific div But i can't seem to get them. I'm trying to get the links and the background images inside paint_wrap div not paint_color. HTML: <div id="timer...
Getting links and background image from a certain div's using - Selenium in Python
I'm trying to get all the links and background images of the links inside a specific div But i can't seem to get them. I'm trying to get the links and the background images inside paint_wrap div not paint_color. HTML: <div id="timer" style="display:inline-block"> <div class="paint_wrap"> <div class="paint_color">...
[ "You have to use 'find_elements' in the below line instead of 'find_element':\nelements = self.driver.find_elements(By.XPATH, \"//*[@id='timer']/div/a\")\n\n" ]
[ 3 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074411994_python_selenium.txt
Q: Reshaping dataframe with pandas - access to nested columns I want to reshape a dataframe that holds IDs, Features, Feature Codes, and the respective Values for each Feature Code. Every feature can have several attributes, and only if there is a value in this attribute, then it is listed as a row in the table. The ...
Reshaping dataframe with pandas - access to nested columns
I want to reshape a dataframe that holds IDs, Features, Feature Codes, and the respective Values for each Feature Code. Every feature can have several attributes, and only if there is a value in this attribute, then it is listed as a row in the table. The values are the absolute numbers, how often this feature is repre...
[ "Try:\ndf[\"tmp\"] = df[\"Feature\"] + \"_\" + df[\"Attribute\"]\n\ndf_out = df.pivot(index=\"ID\", columns=\"tmp\", values=\"Value\")\ndf_out.columns.name = None\nprint(df_out.reset_index())\n\nPrints:\n ID color_cold color_warm number_0-10 number_11-20 number_21-30 number_31-40 number_41-100\n0 ID01 ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "pivot", "python", "reshape" ]
stackoverflow_0074411097_dataframe_pandas_pivot_python_reshape.txt
Q: Dividing a 24-digit binary number to 3 equal parts I'd like to know how can I divide a 24-digit binary number which is taken from user in python to 3 parts and then put different conditions on each of these 3 parts. e.g: input => 111100011110110100100100 divide the input to 3 equal parts (each part should have 8 ...
Dividing a 24-digit binary number to 3 equal parts
I'd like to know how can I divide a 24-digit binary number which is taken from user in python to 3 parts and then put different conditions on each of these 3 parts. e.g: input => 111100011110110100100100 divide the input to 3 equal parts (each part should have 8 digits): 11110001 | 11101101 | 00100100 for the first pa...
[ "I think I managed to do it:\n\nMy script saves the value as a list and as a string, b/c idk what you wanted the end value to be\n\nBasically it takes the number\nSplits it into 8bit parts (in a list)\nConverts the first one to denary\nSecond one to denary using only the last 7bits\nand makes it negative/positive a...
[ 0 ]
[]
[]
[ "ascii", "binary", "decimal", "integer", "python" ]
stackoverflow_0074410994_ascii_binary_decimal_integer_python.txt
Q: Why can't I import some of the modules in scikit-learn? (PyCharm) I'm trying to run the following code: from sklearn.ensemble import ExtraTreesClassifier from sklearn.feature_selection import SelectFromModel from sklearn.model_selection import train_test_split from sklearn import cross_validation ExtraTreesClassi...
Why can't I import some of the modules in scikit-learn? (PyCharm)
I'm trying to run the following code: from sklearn.ensemble import ExtraTreesClassifier from sklearn.feature_selection import SelectFromModel from sklearn.model_selection import train_test_split from sklearn import cross_validation ExtraTreesClassifiers runs, and so does SelectFrom Model. But the latter two lines do n...
[ "cross_validation was used to exist as a scipy package but is now deprecated and so it isn't advisable to use it.\nYou can use sklearn.model_selection.train_test_split instead\n:\nfrom sklearn.model_selection import train_test_split\n\nYou can also try downgrading it by installing an older version of sklearn to con...
[ 1 ]
[]
[]
[ "importerror", "install.packages", "pycharm", "python", "python_import" ]
stackoverflow_0074411144_importerror_install.packages_pycharm_python_python_import.txt
Q: TypeError: unhashable type: 'list' when I try to do a pivot from a column in pandas My Python code takes a bank statement from Excel and creates a dataframe that categorises each transaction based on description. Example code: import pandas as pd import openpyxl import datetime as dt import numpy as np dff = pd.D...
TypeError: unhashable type: 'list' when I try to do a pivot from a column in pandas
My Python code takes a bank statement from Excel and creates a dataframe that categorises each transaction based on description. Example code: import pandas as pd import openpyxl import datetime as dt import numpy as np dff = pd.DataFrame({'Date': ['20221003', '20221005'], 'Tran Type': ['BOOK TRANSF...
[ "This is because the output of findall() is a list:\n\nReturn all non-overlapping matches of pattern in string, as a list of strings or tuples\n\nWhich is not a valid type when using pivot_table(). Add str[0] at the end if you expect to only have one find per Description/row and it should work:\ndff['Category'] = d...
[ 2, 2 ]
[]
[]
[ "pandas", "pivot_table", "python" ]
stackoverflow_0074412116_pandas_pivot_table_python.txt
Q: How to convert categorical values to numeric and save the changes to the original data? I have these 13 columns: I want to split the 'Category' column into the testing set and the rest into the training set. I'm using sklearn and sklearn works best with numerical values, thus I want 'Sex' column to be numeric. I'...
How to convert categorical values to numeric and save the changes to the original data?
I have these 13 columns: I want to split the 'Category' column into the testing set and the rest into the training set. I'm using sklearn and sklearn works best with numerical values, thus I want 'Sex' column to be numeric. I've done the following code to convert 'Sex' values (m or f) to numeric (1 and 0) #Convert cat...
[ "Check the syntax for Label Encoder\nChange:\nsex_new=sex_new.apply(le.fit_transform)\n\nTo:\nsex_new=le.fit_transform(sex_new)\n\nThe syntax for the fit transform for label encoder should be of this format: fit_transform(<label>).\nCode:\nimport sys\nimport pandas as pd\nimport numpy as np\nimport sklearn\nimport ...
[ 0, 0 ]
[]
[]
[ "data_cleaning", "machine_learning", "python" ]
stackoverflow_0074243169_data_cleaning_machine_learning_python.txt
Q: python automatically create parameters in a lambda function constraint_condition = [lambda x: [x[0], x[1]]] mid.gen_answer(constraint_ueq) In thses codes above, mid is a class, and the method gen_answer is calling a function from another python package which requires n-dimension input written in this format: lamb...
python automatically create parameters in a lambda function
constraint_condition = [lambda x: [x[0], x[1]]] mid.gen_answer(constraint_ueq) In thses codes above, mid is a class, and the method gen_answer is calling a function from another python package which requires n-dimension input written in this format: lambda x:[x[0],x[1],...x[n]] How do I create lambda function and fill...
[ "Guy, I solved this by using lambda x:[sub_x for sub_x in x[:n]. Thx for your help\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074318925_python.txt
Q: Optimize with SciPy vector to scalar function with constraint I would need to optimize a function f with respects to a vector x, that takes as input a constant matrix m and returns a scalar v >= 0. MWE with random numbers: import numpy as np from scipy.optimize import minimize np.random.seed(1) m = np.array([[1,...
Optimize with SciPy vector to scalar function with constraint
I would need to optimize a function f with respects to a vector x, that takes as input a constant matrix m and returns a scalar v >= 0. MWE with random numbers: import numpy as np from scipy.optimize import minimize np.random.seed(1) m = np.array([[1,0,0.15],[2,0,0.15],[1.5,0.2,0.2],[3,0.5,0.1],[2.2,0.1,0.15]]) x0 = ...
[ "Simply add the constraint f(x,m) >= 0:\nimport numpy as np\nfrom scipy.optimize import minimize\n\nnp.random.seed(1)\n\nm = np.array([[1,0,0.15],[2,0,0.15],[1.5,0.2,0.2],[3,0.5,0.1],[2.2,0.1,0.15]])\nx0 = np.random.rand(5)*2\n\ndef f(x, m):\n pg = -np.concatenate((-arr[:, :2], x.reshape(-1, 1)), axis=1).sum(axi...
[ 1 ]
[]
[]
[ "optimization", "python", "scipy" ]
stackoverflow_0074411926_optimization_python_scipy.txt
Q: How do I create a new list of tuples? I have this homework problem, and I'm new to python. I have this list of tuples: [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store')] My code doesn't work when I'm trying to write to target_bigrams with only the tuples that have "the" in position [0]. ...
How do I create a new list of tuples?
I have this homework problem, and I'm new to python. I have this list of tuples: [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store')] My code doesn't work when I'm trying to write to target_bigrams with only the tuples that have "the" in position [0]. Please help. target_bigrams = () bigrams_l...
[ "I think this is what you need;\nbigrams = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store')]\ntarget_word = 'the'\n\ntarget_bigrams = []\nbigrams_length = len(bigrams)\n \nfor i in range(bigrams_length): \n if bigrams[i][0].startswith(target_word):\n target_bigrams.append(big...
[ 0 ]
[ "The question is not clear, but i believe that you want to separate the tuples which has \"the\" in the first position.\nIf that is the case, here is the sample code for your reference\nlst = [('the, this is me', 'the night'), ('the night', 'me'), ('me', 'the store'), ('the', 'the store'),(\"the\",\"How are you\")]...
[ -1 ]
[ "list", "python", "tuples" ]
stackoverflow_0074412130_list_python_tuples.txt
Q: save changes when iterating over multiple DataFrames First, Thanks to the community for the help. The problem that I can't solved is the following: I create a function to group data. After this, I create a 'for' loop to read through all the DataFrames and group data in each of them, but I don't know how to save th...
save changes when iterating over multiple DataFrames
First, Thanks to the community for the help. The problem that I can't solved is the following: I create a function to group data. After this, I create a 'for' loop to read through all the DataFrames and group data in each of them, but I don't know how to save the changes since when calling dataframes again it are uncha...
[ "This could help you out, I think;\ndef group (df):\n df = df.groupby(['col_0','col_1']).sum()\n return df\n\ngrouped_dfs = {}\nc = 1\nfor i in lista:\n grouped_dfs['df_%s'%c] = group(i)\n c += 1\n\nThen, you could get the results for the first df with\ngrouped_dfs['df_1']\n\nand so on.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "function", "group_by", "python", "python_3.x" ]
stackoverflow_0074399699_dataframe_function_group_by_python_python_3.x.txt
Q: check dates for gap of more than one day and group them if continuous in spark If I have table with dates in format MM/DD/YYYY like below. +---+-----------+----------+ | id| startdate| enddate| +---+-----------+----------+ | 1| 01/01/2022|01/31/2022| | 1| 02/01/2022|02/28/2022| | 1| 03/01/2022|03/31/2022...
check dates for gap of more than one day and group them if continuous in spark
If I have table with dates in format MM/DD/YYYY like below. +---+-----------+----------+ | id| startdate| enddate| +---+-----------+----------+ | 1| 01/01/2022|01/31/2022| | 1| 02/01/2022|02/28/2022| | 1| 03/01/2022|03/31/2022| | 2| 01/01/2022|03/01/2022| | 2| 03/05/2022|03/31/2022| | 2| 04/01/2022|04...
[ "This is a particular case of the sessionization problem (i.e. identify sessions in data based on some conditions).\nHere is a possible solution that uses windows.\nThe logic behind the solution:\n\nAssociate at each row the temporally previous enddate with the same id\nCalculate the difference in days between each...
[ 4 ]
[]
[]
[ "apache_spark", "dataframe", "pandas", "pyspark", "python" ]
stackoverflow_0074407211_apache_spark_dataframe_pandas_pyspark_python.txt
Q: Python algo trading pandas data clean up and call from another function I have below code and is working fine when I am executing from console. Now I want convert the code constructor which will help to call this and get data. from kiteconnect import KiteConnect import pandas as pd from datetime import datetime fr...
Python algo trading pandas data clean up and call from another function
I have below code and is working fine when I am executing from console. Now I want convert the code constructor which will help to call this and get data. from kiteconnect import KiteConnect import pandas as pd from datetime import datetime from dateutil.relativedelta import relativedelta import math import numpy as np...
[ "I got my answer..\nclass NiftybankData: \n def __init__(self):\n End_Time = datetime.now().date()\n Start_Time = End_Time + relativedelta(days=-100)\n \ndef data(self):\n data = pd.DataFrame(kite.historical_data(260105,Start_Time,End_Time,\"5minute\",False,True))\n data['date'] = pd.to...
[ 0 ]
[]
[]
[ "pandas", "pyalgotrade", "python" ]
stackoverflow_0074411936_pandas_pyalgotrade_python.txt
Q: Is it possible to rearrange my list so that my list indexes matches the hour of the day? I have a list of 24 prices between each hour of the day and night. example: Pricelist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] I have also imported time that returns the current time: eg. N = 13. I w...
Is it possible to rearrange my list so that my list indexes matches the hour of the day?
I have a list of 24 prices between each hour of the day and night. example: Pricelist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] I have also imported time that returns the current time: eg. N = 13. I want to rearrange the Pricelist so that PriceList[N] gets put at index 0 in the list, and the n...
[ "You can use list slicing and concatenation to achieve it:\nPricelist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]\nN = 13\n\nPricelist_new = Pricelist[N-1:] + Pricelist[:N-1]\n# [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n\n", "So you need that N...
[ 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074412219_list_python.txt
Q: I need to scrape data with python from webpage but by giving inputs I need to scrape data from the website - Link and store it in database or any one but it requires some input parameters like i need to enter the vehicle number then submit it after submitting , I need to check again if it is my car. After that i n...
I need to scrape data with python from webpage but by giving inputs
I need to scrape data from the website - Link and store it in database or any one but it requires some input parameters like i need to enter the vehicle number then submit it after submitting , I need to check again if it is my car. After that i need to extract the red , yellow and green text . Can anyone help me pleas...
[ "Try:\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nnum = \"LE02WVX\"\n\nwith requests.session() as s:\n soup = BeautifulSoup(\n s.get(\"https://vehicleenquiry.service.gov.uk/\").content, \"html.parser\"\n )\n\n authenticity_token = soup.select(\"form\")[1].select_one(\n '[name=\"authe...
[ 2 ]
[]
[]
[ "beautifulsoup", "html", "python", "selenium", "web_scraping" ]
stackoverflow_0074410718_beautifulsoup_html_python_selenium_web_scraping.txt
Q: Bar plot for a column in pandas I want to create a bar plot only for column "Cluster" which would show how many occurrences are present for each cluster in the data frame and add different color to each Cluster (each Bar) Dummy Data: import pandas as pd data = {'col1': ['Agree', 'Disagree', 'Agree', 'Agree', 'Agre...
Bar plot for a column in pandas
I want to create a bar plot only for column "Cluster" which would show how many occurrences are present for each cluster in the data frame and add different color to each Cluster (each Bar) Dummy Data: import pandas as pd data = {'col1': ['Agree', 'Disagree', 'Agree', 'Agree', 'Agree', 'Disagree'], 'col2': ['Ag...
[ "c = ['red', 'yellow', 'black', 'blue']\ncluster_counts = df.Cluster.value_counts()\nplt.bar(cluster_counts.keys(), cluster_counts.values, color=c)\nplt.show()\n\nHope this helps.\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "plot", "python" ]
stackoverflow_0074412223_matplotlib_pandas_plot_python.txt
Q: Convolutional Neural Net-Keras-val_acc Keyerror 'acc' I am trying to implement CNN by Theano. I used Keras library. My data set is 55 alphabet images, 28x28. In the last part I get this error: train_acc=hist.history['acc'] KeyError: 'acc' Any help would be much appreciated. Thanks. This is part of my code: fro...
Convolutional Neural Net-Keras-val_acc Keyerror 'acc'
I am trying to implement CNN by Theano. I used Keras library. My data set is 55 alphabet images, 28x28. In the last part I get this error: train_acc=hist.history['acc'] KeyError: 'acc' Any help would be much appreciated. Thanks. This is part of my code: from keras.models import Sequential from keras.models import...
[ "In a not-so-common case (as I expected after some tensorflow updates), despite choosing metrics=[\"accuracy\"] in the model definitions, I still got the same error. \nThe solution was: replacing metrics=[\"acc\"] with metrics=[\"accuracy\"] everywhere. In my case, I was unable to plot the parameters of the history...
[ 27, 8, 6, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "keras", "python" ]
stackoverflow_0042689066_keras_python.txt
Q: Binary search through string tuple in list I'm trying to do a binary search through a list of tuples, when I give a inputq = "BB", it is not show a correct search. This is my data: alldtata = [('BA', 'Bosnia and Herzegovina', 44.0, 18.0), ('BB', 'Barbados', 13.17, -59.53), ('BD', 'Bangladesh', 24.0, 90.0), ('BE', ...
Binary search through string tuple in list
I'm trying to do a binary search through a list of tuples, when I give a inputq = "BB", it is not show a correct search. This is my data: alldtata = [('BA', 'Bosnia and Herzegovina', 44.0, 18.0), ('BB', 'Barbados', 13.17, -59.53), ('BD', 'Bangladesh', 24.0, 90.0), ('BE', 'Belgium', 50.83, 4.0), ('BF', 'Burkina Faso', 1...
[ "I found two main problems with your algorithm. First, as @gog points out, you are calculating res as a boolean, but then are comparing it with integers. The other thing is that you are comparing the term arr[m] to the target, as though that term refers to the equivalent value in the data structure. It does not. ...
[ 0 ]
[]
[]
[ "binary_search", "list", "python", "tuples" ]
stackoverflow_0074412209_binary_search_list_python_tuples.txt
Q: How to best structure conftest and fixtures in across multiple pytest files Let's say I have 3 lists of DataFrames containing different data that I want to run the same test cases on. How do I best structure my files and code so that I have one conftest.py (or some sort of parent class) that contains all the test ...
How to best structure conftest and fixtures in across multiple pytest files
Let's say I have 3 lists of DataFrames containing different data that I want to run the same test cases on. How do I best structure my files and code so that I have one conftest.py (or some sort of parent class) that contains all the test cases that each list needs to run on, and 3 child classes that have different way...
[ "This can be done using a fixture and defining the scope to the desired fixtures life time with session being the the one that is generated once for the entire testing session.\nIn the following code the dfs is created only once for the entire testing session and all the test can use it.\nfrom typing import Dict\n\...
[ 0, 0 ]
[]
[]
[ "conftest", "pytest", "python" ]
stackoverflow_0074406488_conftest_pytest_python.txt