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: Every two columns are merged into one column in I have a text file that looks like this I want to join each ATGC pairwise, starting with the seventh column, to achieve this effect: I tried to do this on linux using the awk command, but it was too slow: enter image description here thank you very much! Use code i...
Every two columns are merged into one column in
I have a text file that looks like this I want to join each ATGC pairwise, starting with the seventh column, to achieve this effect: I tried to do this on linux using the awk command, but it was too slow: enter image description here thank you very much! Use code in any language, hopefully python
[ "awk solution\nI have an alternative awk solution that uses global substitutions rather than loops to format the data. I suspect this will be faster than what you tried but do not have your file to try it on.\nThis is the solution, (replace data.txt with the path to your data file):\nawk '{$1 =$1\"*\"$2\"*\"$3\"*\"...
[ 0 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0074242957_matlab_python.txt
Q: Declare a function that takes a string (as an argument) and returns False if the string is less than 6 characters long. Otherwise, True is returned After the function declaration, read (using the input function) a list of city names written on a single line separated by a space. Then, using the list generator and ...
Declare a function that takes a string (as an argument) and returns False if the string is less than 6 characters long. Otherwise, True is returned
After the function declaration, read (using the input function) a list of city names written on a single line separated by a space. Then, using the list generator and the generated function, generate a list of city names at least six characters long from the input list. This is my code: def is_large(lst): for i in ...
[ "So according to your post title, I believe this is what you're asking for:\ndef isWordAllowed(word, allowedLength):\n if (len(word) >= allowedLength):\n return True\n return False\n\nThen call the function on your list of words:\nlist = input().split()\nfor word in list:\n if (isWordAllowed(word, 6...
[ 0 ]
[]
[]
[ "function", "generator", "list", "python", "return" ]
stackoverflow_0074245710_function_generator_list_python_return.txt
Q: SQLAlchemy limit results imagine I have a simple database like this I want to execute this SQL query using SQLAlchemy to get only 10 latest results of toys with certain Child_id belonging to some parent. toys = Toy.query.filter(Toy.child_id == 77).filter(Child.parent_id == 'parent1').order_by(Toys.id.desc()).limi...
SQLAlchemy limit results
imagine I have a simple database like this I want to execute this SQL query using SQLAlchemy to get only 10 latest results of toys with certain Child_id belonging to some parent. toys = Toy.query.filter(Toy.child_id == 77).filter(Child.parent_id == 'parent1').order_by(Toys.id.desc()).limit(limit).all() But if I exec...
[ "It's solved. I didn't use join statement, that's why it didn't work.\ntoys = (Toy.query\n .join(Child)\n .join(Parent)\n .filter(Parent.name == 'parent1').filter(Toy.child_id == 77)\n).limit(10).all()\n\n" ]
[ 0 ]
[ "I'd expect you to do something like Session.query(Toys).filter(Child_id == 77).limit(10).all() or something like that.\n" ]
[ -1 ]
[ "python", "sqlalchemy" ]
stackoverflow_0074244988_python_sqlalchemy.txt
Q: Python collage of four image together I am trying to combine 4 images, image 1 on top left, image 2 on top right, image 3 on bottom left and image 4 on bottom right. However, my images are different sizes and not sure how to resize the images to same size. I am pretty new to Python and this is my first time using ...
Python collage of four image together
I am trying to combine 4 images, image 1 on top left, image 2 on top right, image 3 on bottom left and image 4 on bottom right. However, my images are different sizes and not sure how to resize the images to same size. I am pretty new to Python and this is my first time using PIL. I have this so far (after opening the ...
[ "This shall suffice your basic requirement.\nThis shall suffice your basic requirement.\nSteps:\n\nImages are read and stored to list of arrays using io.imread(img) in\na list comprehension.\n\nWe resize images to custom height and width.You can change IMAGE_WIDTH,IMAGE_HEIGHT as per your need with respect\nto the ...
[ 0 ]
[]
[]
[ "image_manipulation", "image_resizing", "python", "python_3.x", "python_imaging_library" ]
stackoverflow_0074242764_image_manipulation_image_resizing_python_python_3.x_python_imaging_library.txt
Q: How to convert time from list of dictionaries to date time format I need to convert time from list of dictionaries, that I made from json file, to date time format the json file looks like this {"name": "Thomas", "time_created": 1665070563, "gender": null} {"name": "Lisa", "time_created": 1665226717, "gender": "fe...
How to convert time from list of dictionaries to date time format
I need to convert time from list of dictionaries, that I made from json file, to date time format the json file looks like this {"name": "Thomas", "time_created": 1665070563, "gender": null} {"name": "Lisa", "time_created": 1665226717, "gender": "female", "age": 59} {"name": "James", "time_created": 1664913997, "gender...
[ "You don't need to iterate over all the keys in each dict; the keys are strings, which is why the extra level of iteration is giving you a string instead of the actual dict. Just do:\nfor value in lst:\n value['time_created'] = datetime.datetime.fromtimestamp(value['time_created'])\n\nYou can also do this:\nlst...
[ 0, 0 ]
[]
[]
[ "datetime", "dictionary", "json", "list", "python" ]
stackoverflow_0074245802_datetime_dictionary_json_list_python.txt
Q: Cannot do webscraping with Selenium because recognised as bot I am trying to webscrape with Python "https://www.futbol24.com/" and I am recognised as bot. I tried everything, including the removal of signatures in the javascript of chromedriver.exe, or changing user-agent and proxy, or playing with the several chr...
Cannot do webscraping with Selenium because recognised as bot
I am trying to webscrape with Python "https://www.futbol24.com/" and I am recognised as bot. I tried everything, including the removal of signatures in the javascript of chromedriver.exe, or changing user-agent and proxy, or playing with the several chrome_options. However, I do reach the website if I simply use Chrome...
[ "you can use undetected-chromedriver\n", "Try this. It seems no problem\n ChromeDriver driver; \n ChromeOptions options = new ChromeOptions();\n options.AcceptInsecureCertificates = true;\n var service = ChromeDriverService.CreateDefaultService();\n service.HideCommandPromptWindow = true;\n op...
[ 0, 0, 0 ]
[]
[]
[ "bots", "https", "python", "selenium", "web_scraping" ]
stackoverflow_0074219348_bots_https_python_selenium_web_scraping.txt
Q: Extract ID numeric value from a column I have below data set, I need to extract 9 numeric ID from the "Notes" column. below some of the code I tried, but sometimes I don't get the correct output. sometimes there are few spaces between numbers, or a symbol, or sometimes there are numeric values that are not part of...
Extract ID numeric value from a column
I have below data set, I need to extract 9 numeric ID from the "Notes" column. below some of the code I tried, but sometimes I don't get the correct output. sometimes there are few spaces between numbers, or a symbol, or sometimes there are numeric values that are not part of the ID etc.. any idea how to do this more e...
[ "# replace known character in b/w the numbers with null\n# extract the 9 digits\ndf['output']=(df['Notes'].str.replace(r'[\\s|\\-]','',regex=True)\n .str.extract(r'(\\d{9})').fillna(0))\ndf\n\n Notes Expected Output output\n0 ab. 325% xyz ...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074245889_pandas_python.txt
Q: How to get integer values from a string in Python? Suppose I had a string string1 = "498results should get" Now I need to get only integer values from the string like 498. Here I don't want to use list slicing because the integer values may increase like these examples: string2 = "49867results should get" stri...
How to get integer values from a string in Python?
Suppose I had a string string1 = "498results should get" Now I need to get only integer values from the string like 498. Here I don't want to use list slicing because the integer values may increase like these examples: string2 = "49867results should get" string3 = "497543results should get" So I want to get only...
[ ">>> import re\n>>> string1 = \"498results should get\"\n>>> int(re.search(r'\\d+', string1).group())\n498\n\nIf there are multiple integers in the string:\n>>> map(int, re.findall(r'\\d+', string1))\n[498]\n\n", "An answer taken from ChristopheD here: https://stackoverflow.com/a/2500023/1225603\nr = \"456results...
[ 141, 58, 28, 19, 10, 7, 3, 1, 0, 0, 0 ]
[]
[]
[ "integer", "python", "string" ]
stackoverflow_0011339210_integer_python_string.txt
Q: Converting Dates to Quarters in pandas dataframe Graph I want to convert dates to quarters but I only want to display quarters once in altair because it would jam my x-axis column. Is there a way to aggregate this? The data/code is data[['date', 'percentage']] alt.Chart(df_avg) .mark_line(strokeDa...
Converting Dates to Quarters in pandas dataframe
Graph I want to convert dates to quarters but I only want to display quarters once in altair because it would jam my x-axis column. Is there a way to aggregate this? The data/code is data[['date', 'percentage']] alt.Chart(df_avg) .mark_line(strokeDash=[5, 5]) .encode( ...
[ "You want to look into the DataFrame.resample method. You can see the various 'rule' values here. In particular you probably want 'Q' (calendar quarter end) or 'QS' (calendar quarter start).\n", "Without sample data, I cannot comment for sure what is happening. But if your data is in the correct format,\nusing th...
[ 0, 0 ]
[]
[]
[ "aggregate", "altair", "datetime", "python" ]
stackoverflow_0074225061_aggregate_altair_datetime_python.txt
Q: Poetry activates wrong version of python macOS Big Sur I'm trying to run a program with poetry but it keeps using the wrong version of python. when I use poetry shell It outputs The currently activated Python version 3.9.5 is not supported by the project (>=3.10,<3.11). Trying to find and use a compatible version...
Poetry activates wrong version of python macOS Big Sur
I'm trying to run a program with poetry but it keeps using the wrong version of python. when I use poetry shell It outputs The currently activated Python version 3.9.5 is not supported by the project (>=3.10,<3.11). Trying to find and use a compatible version. Using python3 (3.10.4) Which is what I want. It SHOULD u...
[ "You need to run this:\npoetry config virtualenvs.prefer-active-python true\n\nNext, remove and create the python virtual environment again. This is what worked for me.\nSee the documentation please: https://python-poetry.org/docs/configuration/#virtualenvsprefer-active-python-experimental\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_poetry", "version_control" ]
stackoverflow_0073965346_python_python_3.x_python_poetry_version_control.txt
Q: Python, use a dict over a list please I have this code and it works. I wrote it to use a list a while back and I am revisiting it and wondering if I can add url and red to a dict rather than a list. def starts_with_hash(child: str) -> bool: if not child.startswith('#'): return True def fetch_blocklist...
Python, use a dict over a list please
I have this code and it works. I wrote it to use a list a while back and I am revisiting it and wondering if I can add url and red to a dict rather than a list. def starts_with_hash(child: str) -> bool: if not child.startswith('#'): return True def fetch_blocklist_count(session: requests.Session, url: str...
[ "I will leave my comment here as an answer as well, since you said it solved your problem.\nYou could change results = [future.result() for future in concurrent.futures.as_completed(futures)] to results = {future.result()[0]: future.result()[1] for future in concurrent.futures.as_completed(futures)}\nMore details a...
[ 1 ]
[]
[]
[ "concurrent.futures", "python" ]
stackoverflow_0074246014_concurrent.futures_python.txt
Q: Remove unicode HTML tags in Python I have a string from which I would like to remove the HTML tags. "overview":"\u003cp style=\"margin: 0px 0px 20px; padding: 0px; line-height: 20px; outline: none !important; min-height: 1em; color: #333333; font-family: Arial, Helvetica, sans-serif, emoji; font-size: 14px; font-...
Remove unicode HTML tags in Python
I have a string from which I would like to remove the HTML tags. "overview":"\u003cp style=\"margin: 0px 0px 20px; padding: 0px; line-height: 20px; outline: none !important; min-height: 1em; color: #333333; font-family: Arial, Helvetica, sans-serif, emoji; font-size: 14px; font-style: normal; font-variant-caps: normal...
[ "You string is presumably from somewhere else if you encode it as utf-8 then it becomes:\n'\"overview\":\"<p style=\"margin: 0px 0px 20px; padding: 0px; line-height: 20px; outline: none !important; min-height: 1em; color: #333333; font-family: Arial, Helvetica, sans-serif, emoji; font-size: 14px; font-style: normal...
[ 1, 1, 1 ]
[]
[]
[ "beautifulsoup", "css", "html", "python" ]
stackoverflow_0074244208_beautifulsoup_css_html_python.txt
Q: Is there a solution to separating number and operators of a string? I want separate numbers and operator signs from a string. Example: input - "12+34=46" output - 12, +, 34, 46 Code Used: def seperator(runes): runes = list(runes) operators = ["-", "+", "/", "*"] index1 = 0 index2 = 0 for i...
Is there a solution to separating number and operators of a string?
I want separate numbers and operator signs from a string. Example: input - "12+34=46" output - 12, +, 34, 46 Code Used: def seperator(runes): runes = list(runes) operators = ["-", "+", "/", "*"] index1 = 0 index2 = 0 for i in range(len(runes)): cond1 = runes[i-1] >"-1" and runes[i-1] < ...
[ "The simplest solution I can think of is a regex. Here's what I came up with:\nimport re\n\n\ndef seperator(runes):\n match = re.search('(-?[0-9]+)([+\\-*\\/])(-?[0-9]+)(=)(-?[0-9]+)', runes.replace(' ', ''))\n return match.groups()\n\n\nprint(seperator(\"1+1=2\")) # => ('1', '+', '1', '=', '2')\nprint(seper...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074245929_python.txt
Q: Button Not Displayed in Kivy I am learning Kivy, the button is not displayed in the Kivy Screen. I am unable to find the issue. My Python version is 3.5.3 from kivy.app import App from kivy.uix.widget import Widget class MainWidget(Widget): pass class TheLabApp(App): pass TheLabApp().run() MainWidget: ...
Button Not Displayed in Kivy
I am learning Kivy, the button is not displayed in the Kivy Screen. I am unable to find the issue. My Python version is 3.5.3 from kivy.app import App from kivy.uix.widget import Widget class MainWidget(Widget): pass class TheLabApp(App): pass TheLabApp().run() MainWidget: <MainWidget>: Button: ...
[ "\nMake sure your .kv file starts with the prefix 'TheLab', from the Pong Game Tutorial:\n\n\nCOMMON ERROR: The name of the kv file, e.g. pong.kv, must match the name of the app, e.g. PongApp (the part before the App ending)\n\n\nAdd the build method to your App class:\n class TheLabApp(App):\n def build(self):...
[ 0, 0, 0 ]
[]
[]
[ "kivy", "kivy_language", "python", "python_3.x" ]
stackoverflow_0068506986_kivy_kivy_language_python_python_3.x.txt
Q: How do you add additional files to a wheel? How do control what files are included in a wheel? It appears MANIFEST.in isn't used by python setup.py bdist_wheel. UPDATE: I was wrong about the difference between installing from a source tarball vs a wheel. The source distribution includes files specified in MANIFE...
How do you add additional files to a wheel?
How do control what files are included in a wheel? It appears MANIFEST.in isn't used by python setup.py bdist_wheel. UPDATE: I was wrong about the difference between installing from a source tarball vs a wheel. The source distribution includes files specified in MANIFEST.in, but the installed package only has python ...
[ "Have you tried using package_data in your setup.py? MANIFEST.in seems targetted for python versions <= 2.6, I'm not sure if higher versions even look at it.\nAfter exploring https://github.com/pypa/sampleproject, their MANIFEST.in says:\n# If using Python 2.6 or less, then have to include package data, even though...
[ 55, 46, 28, 12, 4, 0, 0 ]
[]
[]
[ "pip", "python", "python_wheel" ]
stackoverflow_0024347450_pip_python_python_wheel.txt
Q: Proper way to deal with external objects with functions in Python This implementation of the AWS MQTT broker is confusing me. In the code, there is this function definition: def on_message_received(topic, payload, **kwargs): print("Received message from topic '{}': {}".format(topic, payload)) global receiv...
Proper way to deal with external objects with functions in Python
This implementation of the AWS MQTT broker is confusing me. In the code, there is this function definition: def on_message_received(topic, payload, **kwargs): print("Received message from topic '{}': {}".format(topic, payload)) global received_count received_count += 1 if received_count == args.count: ...
[ "The example you posted doesn't actually work because last_message is a local variable -- you can't access it from outside the function. I'd suggest putting it in a handler object, like this:\nclass MessageHandler:\n def __init__(self):\n self.last_message = ''\n\n def on_message_received(self, topic,...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074246115_python.txt
Q: Question about a multi line regex in python language I want to perform the selection of a group of lines in a text file to get all jobs related to an ipref The test file is like this : job numbers : (1,2,3), ip ref : (10,12,10) text file : 1 ... (several lines of text) xxx 10 2 ... (several lines of text) xxx 12 3...
Question about a multi line regex in python language
I want to perform the selection of a group of lines in a text file to get all jobs related to an ipref The test file is like this : job numbers : (1,2,3), ip ref : (10,12,10) text file : 1 ... (several lines of text) xxx 10 2 ... (several lines of text) xxx 12 3 ... (several lines of text) xxx 10 i want to select job n...
[ "You can write the pattern in this way, repeating the newline and asserting not xxx followed by 1 or more digits:\n^\\d(?:\\n(?!xxx \\d+$).*)*\\nxxx 10$\n\nThe pattern matches:\n\n^ Start of string\n\\d Match a single digit (or \\d+ for 1 or more)\n(?: Non capture group\n\n\\n Match a newline\n(?!xxx \\d+$) Negativ...
[ 1, 1, 0, 0 ]
[]
[]
[ "multiline", "python", "regex" ]
stackoverflow_0074245242_multiline_python_regex.txt
Q: Read .mat files in Python Is it possible to read binary MATLAB .mat files in Python? I've seen that SciPy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed SciPy version 0.7.0, and I can't find the loadmat() method. A: An import is required, import scipy.io... import scipy.io ...
Read .mat files in Python
Is it possible to read binary MATLAB .mat files in Python? I've seen that SciPy has alleged support for reading .mat files, but I'm unsuccessful with it. I installed SciPy version 0.7.0, and I can't find the loadmat() method.
[ "An import is required, import scipy.io...\nimport scipy.io\nmat = scipy.io.loadmat('file.mat')\n\n", "Neither scipy.io.savemat, nor scipy.io.loadmat work for MATLAB arrays version 7.3. But the good part is that MATLAB version 7.3 files are hdf5 datasets. So they can be read using a number of tools, including Num...
[ 734, 200, 31, 24, 15, 15, 13, 10, 9, 4, 3, 1, 0, 0, 0 ]
[]
[]
[ "file_io", "mat_file", "matlab", "python", "scipy" ]
stackoverflow_0000874461_file_io_mat_file_matlab_python_scipy.txt
Q: Optimize a function in Python I need to optimize this function: 10 ** 9 / n * 9 * 10 **6 + 1 / 2 * n * 1 / 25 * 180. This is what I tried in Python, but I get the error "Float Division By Zero" and I don't understand why :(. Can you help me with that? import math from scipy.optimize import minimize_scalar def mi...
Optimize a function in Python
I need to optimize this function: 10 ** 9 / n * 9 * 10 **6 + 1 / 2 * n * 1 / 25 * 180. This is what I tried in Python, but I get the error "Float Division By Zero" and I don't understand why :(. Can you help me with that? import math from scipy.optimize import minimize_scalar def minimF(n): return (float)(10 ** 9...
[ "The issue here is that n starts off as zero, meaning that 2 * n * 1 is equal to 0, which provides the error as that equation during the first iteration is equal to 1000000000/ 1.0/0.0/ 4500, which provides the float division by zero error. if you could provide some more context as to what the code is supposed to d...
[ 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0074246102_optimization_python.txt
Q: Landscape creation in UE4.27 using python I have been trying to create a landscape in ue with python scripting using the python unreal API. I went at it with the normal approach using unreal.EditorLevelLibrary.spawn_actor_from_class() to spawn a LandscapeProxy actor and then alter its heightmap using the landscape...
Landscape creation in UE4.27 using python
I have been trying to create a landscape in ue with python scripting using the python unreal API. I went at it with the normal approach using unreal.EditorLevelLibrary.spawn_actor_from_class() to spawn a LandscapeProxy actor and then alter its heightmap using the landscape_import_heightmap_from_render_target() of the L...
[ "The Landscape/Terrain API\nTerrains in UE4 are special actors built over the 'heightmap' concept.\nEach Terrain is a grid of components (ULandscapeComponent). Each component is mapped to a texture holding heights data.\nThe landscape component concept is really important as it impacts performance and quality of th...
[ 2 ]
[]
[]
[ "python", "unreal_engine4" ]
stackoverflow_0071394649_python_unreal_engine4.txt
Q: Problem function trying to transform a string with letter into string with only "*" i've coded a function to get a word by an input of the users and i've to retake my result in one of my function and use it to get another functions working but when i try i get a lot of errors but in vs code it tells me that i dont...
Problem function trying to transform a string with letter into string with only "*"
i've coded a function to get a word by an input of the users and i've to retake my result in one of my function and use it to get another functions working but when i try i get a lot of errors but in vs code it tells me that i dont have any errors. I dont understand why it does something like this Here's my code : # -*...
[ "I'll do like that thanks to cards for helping me :\n# -*- coding: utf-8 -*-\n\n\n\ndef essais(question1=\"Combien d'essai ? \", question2=\"Saisie invalide veuillez recommencez : Combien d'essai ? \"):\n essai = input(question1) # demande un numéro\n while not essai.isnumeric():\n # si saisie non val...
[ 0 ]
[]
[]
[ "function", "python", "string" ]
stackoverflow_0074246002_function_python_string.txt
Q: Safe neo4j queries with dynamic node labels [python driver] I am trying to write code which writes networkx graphs into neo4j. Currently I am using string injections, but I know these are unsafe. For example, here is some of my code extending networkx's DiGraph class to load nodes into a neo4j instance. The driver...
Safe neo4j queries with dynamic node labels [python driver]
I am trying to write code which writes networkx graphs into neo4j. Currently I am using string injections, but I know these are unsafe. For example, here is some of my code extending networkx's DiGraph class to load nodes into a neo4j instance. The driver is set upon graph object creation. def store_in_neo(self): '...
[ "One solution is to use py2neo but ideally I'd like to directly write the queries, with some form of safely escaping the node_label injection.\nThe best solution I can see right now is:\ndef add_new_nodes(self):\n for i in range(len(self.nodes)):\n node_name = list(self.nodes)[i]\n node_name.replac...
[ 0, 0, 0 ]
[]
[]
[ "neo4j", "networkx", "python" ]
stackoverflow_0073872779_neo4j_networkx_python.txt
Q: Although I install python-telegram-bot, error of no module named 'telegram' I installed telegram packages. But when I try to run the simple example, echobot.py, I got an error: Traceback (most recent call last): File "echobot.py", line 8, in <module> import telegram ImportError: No module named 'telegram' Can...
Although I install python-telegram-bot, error of no module named 'telegram'
I installed telegram packages. But when I try to run the simple example, echobot.py, I got an error: Traceback (most recent call last): File "echobot.py", line 8, in <module> import telegram ImportError: No module named 'telegram' Can anyone help me? I install using git: $ git clone https://github.com/python-tele...
[ "You are not installing it. You are just downloading it.\nRun these:\ncd python-telegram-bot\npython setup.py install\n\n(stated in readme of the GitHub page)\n\nAlternatively, you can use pip. It's easier to use.\npip install python-telegram-bot\n\n", "For my case, I solved it this way.\npip install telegram\n\n...
[ 11, 1, 1, 0, 0 ]
[ "Install \npip install django-telegrambot\nConfigure your installation\nsettings.py\nINSTALLED_APPS = (\n ...\n 'django_telegrambot',\n )\n" ]
[ -3 ]
[ "git", "python", "python_2.7", "python_telegram_bot", "telegram_bot" ]
stackoverflow_0045382698_git_python_python_2.7_python_telegram_bot_telegram_bot.txt
Q: Pandas Days after Date Hello I have a Dataframe like this in pandas import pandas as pd df = pd.DataFrame({'date': ['2022-10-01', '2022-10-04', '2022-10-17'], 'value': [100, 110, 95]}) How can I subtract the date from a default value? I've tried it like this '2022-10-20' - df['date'] but got a...
Pandas Days after Date
Hello I have a Dataframe like this in pandas import pandas as pd df = pd.DataFrame({'date': ['2022-10-01', '2022-10-04', '2022-10-17'], 'value': [100, 110, 95]}) How can I subtract the date from a default value? I've tried it like this '2022-10-20' - df['date'] but got an error TypeError: unsuppo...
[ "You can use a datetime object to calculate the difference and then get the number of days with the .dt accessor\nTry this:\nfrom datetime import datetime\n(datetime(2022, 10, 20) - pd.to_datetime(df[\"date\"])).dt.days\n\n", "You can use pandas.Timestamp and to_datetime:\n(pd.Timestamp('2022-10-20') - pd.to_date...
[ 0, 0 ]
[]
[]
[ "dataframe", "date", "pandas", "python" ]
stackoverflow_0074246208_dataframe_date_pandas_python.txt
Q: Python: threading and tkinter I'm trying to continuously update matlibplots in tkinter GUI while being able to click on buttons to pause/continue/stop updating the plots. I've tried using threads, but they don't seem to be executing parallelly (e.g. data thread is being executed but the plots don't get updated + c...
Python: threading and tkinter
I'm trying to continuously update matlibplots in tkinter GUI while being able to click on buttons to pause/continue/stop updating the plots. I've tried using threads, but they don't seem to be executing parallelly (e.g. data thread is being executed but the plots don't get updated + clicking on buttons is ignored). Why...
[ "to be fair all functions in your code are very likely to cause a segmentation fault, and other functions that don't result in a segmentation fault simply don't work, it's hard to explain what's wrong.\n\ndefine global variables as global if you are going to modify them\nupdate GUI in your main thread by using the ...
[ 0 ]
[]
[]
[ "multithreading", "python", "tkinter" ]
stackoverflow_0074244687_multithreading_python_tkinter.txt
Q: Find palindrome python space complexity? Given the following code in python which checks whether an string of n size is palindromic: def is_palindromic(s): return all(s[i] == s[~i] for i in range(len(s) // 2)) What is the space complexity of this code? Is it O(1) or O(n)? The all function gets an iterable as ...
Find palindrome python space complexity?
Given the following code in python which checks whether an string of n size is palindromic: def is_palindromic(s): return all(s[i] == s[~i] for i in range(len(s) // 2)) What is the space complexity of this code? Is it O(1) or O(n)? The all function gets an iterable as a parameter; So does it mean the s[i] == s[~i]...
[ "range(len(s) // 2) is O(1) space, and the documentation on all() says that all is equivalent to\ndef all(iterable):\n for element in iterable:\n if not element:\n return False\n return True\n\nThis has space complexity O(1).\n", "You are using a generator expression, which only needs enou...
[ 2, 2 ]
[]
[]
[ "iterable", "iterator", "palindrome", "python", "space_complexity" ]
stackoverflow_0074245043_iterable_iterator_palindrome_python_space_complexity.txt
Q: Sending a DM with hikari-lightbulb i'm really new to hikari and i don't really understand the docs, but how would i send a dm to a user? this idea might not be very smart, but i've got a password generating bot and i want to send a dm to the user with the password once i've generated it i've already got the genera...
Sending a DM with hikari-lightbulb
i'm really new to hikari and i don't really understand the docs, but how would i send a dm to a user? this idea might not be very smart, but i've got a password generating bot and i want to send a dm to the user with the password once i've generated it i've already got the generator just wondering how to send a dm @com...
[ "This is a simple function which will sent pong in direct messages of person who initiated command.\nctx.author.send is the part that sends the dm.\nAlso we still need some response in chat where command was sent or it will display error in chat\n@bot.command\n@lightbulb.command('ping', 'sends pong in dm')\n@lightb...
[ 0 ]
[]
[]
[ "discord", "dm", "hikaricp", "python" ]
stackoverflow_0073577771_discord_dm_hikaricp_python.txt
Q: How to know when bullet from a gun hits a target in Pygame Sprite I am making a game with pygame and sprite, and the game has birds, gun and bullet classes. When the gun releases a bullet and the bullet touches the bird, the bird and the bullet suppose to disappear immediately. My challenge at the moment is to kno...
How to know when bullet from a gun hits a target in Pygame Sprite
I am making a game with pygame and sprite, and the game has birds, gun and bullet classes. When the gun releases a bullet and the bullet touches the bird, the bird and the bullet suppose to disappear immediately. My challenge at the moment is to know when the bullet touches the bird and to make the bullet disappear alo...
[ "See How to get keyboard input in pygame?. pygame.key.get_pressed() is not an event. pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is 1, otherwise 0. So you can calculate the resulting movement when 2 keys are pressed with keys[pygame.K_d] - ke...
[ 1 ]
[]
[]
[ "collision_detection", "pygame", "python" ]
stackoverflow_0074235927_collision_detection_pygame_python.txt
Q: Python: how to get a direct Google docs url after uploading to Google drive? I want to upload a text file .txt to Google drive and be able to get a direct link where I can edit it directly, so I've written this method def upload(self, file_name, filepath, folder_id, file_id=None, mimeType='text/plain'): media = M...
Python: how to get a direct Google docs url after uploading to Google drive?
I want to upload a text file .txt to Google drive and be able to get a direct link where I can edit it directly, so I've written this method def upload(self, file_name, filepath, folder_id, file_id=None, mimeType='text/plain'): media = MediaFileUpload( filepath, mimetype=mimeType, resumable=True) try: if file_...
[ "The file you uploading the file as mimeType='text/plain' this is not a Google Drive mimetype. There is a list of mimetypes that are supported.\nTo covert your .txt file to a google docs file you would need to supply the mimetype to covert it to in the file metadata. You are not supplying a mimetype in the metada...
[ 2 ]
[]
[]
[ "google_api_python_client", "google_docs_api", "google_drive_api", "python", "python_3.x" ]
stackoverflow_0074246210_google_api_python_client_google_docs_api_google_drive_api_python_python_3.x.txt
Q: How to draw a tree more beautifully in networkx If I make a tree using networkx and draw it, the nodes overlap. Is there a way to draw it so there is no overlap? import matplotlib.pyplot as plt import networkx as nx T = nx.generators.balanced_tree(2, 5) nx.draw(T) plt.show() A: I am no expert in this, but here i...
How to draw a tree more beautifully in networkx
If I make a tree using networkx and draw it, the nodes overlap. Is there a way to draw it so there is no overlap? import matplotlib.pyplot as plt import networkx as nx T = nx.generators.balanced_tree(2, 5) nx.draw(T) plt.show()
[ "I am no expert in this, but here is code that uses the pydot library and its graph_viz dependency. These libraries come with Anaconda Python but are not installed by default, so first do this from the command prompt:\nconda install pydot\n\nThen here is code adapted from Circular Tree.\nimport matplotlib.pyplot as...
[ 60, 11, 1 ]
[]
[]
[ "matplotlib", "networkx", "python" ]
stackoverflow_0057512155_matplotlib_networkx_python.txt
Q: pandas concatenate Date value along with other values I am pulling forex data and the resulting data that I get back from the call looks like this: {"code":"EUR.FOREX","timestamp":1666980480,"gmtoffset":0,"open":1.0034,"high":1.0071,"low":1,"close":1.0054,"volume":0,"previousClose":0.9909,"change":0.0145,"change_p...
pandas concatenate Date value along with other values
I am pulling forex data and the resulting data that I get back from the call looks like this: {"code":"EUR.FOREX","timestamp":1666980480,"gmtoffset":0,"open":1.0034,"high":1.0071,"low":1,"close":1.0054,"volume":0,"previousClose":0.9909,"change":0.0145,"change_p":1.4633} Since there is no simple date value in the result...
[ "Yes, your idea is right.\nYou can pass it as [df3, df4, pd.Series(Date), Open, ...]\nThe second thing I noticed is that you're not concatenating your total_df with the data you already have. So for each iteration you only get one row.\nHere is a suggestion of how to change that + I've simplified a few other lines:...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074242640_pandas_python.txt
Q: Validationerror when field is empty I have created a Validation Error to show up when the submit button is clicked and the condition of the field is empty. But when I try to test it when the field is filled, the validation error still showing up. What's wrong with my code ? def action_approved(self): for rec i...
Validationerror when field is empty
I have created a Validation Error to show up when the submit button is clicked and the condition of the field is empty. But when I try to test it when the field is filled, the validation error still showing up. What's wrong with my code ? def action_approved(self): for rec in self: expense_account = self.en...
[ "Guess, you are checking the whole table. How is the class account.pettycash.voucher.wizard.line related to current self ? You need to include that as well in search condition.\nexpense_account = self.env['account.pettycash.voucher.wizard.line'].search([\n('expense_account','=',False),\n('relational_field', '=', se...
[ 0, 0 ]
[]
[]
[ "odoo", "odoo_14", "python", "validationerror" ]
stackoverflow_0074233840_odoo_odoo_14_python_validationerror.txt
Q: IF, ELIF, ELSE and OR with Python, not working I´m trying to make this simple project work but is not working at all, i don´t know the if statement with the: if name == " Cher " or name == " Madonna ": print ("May I have your autograph please?"), is not working. I tried a lot of combinations and ...
IF, ELIF, ELSE and OR with Python, not working
I´m trying to make this simple project work but is not working at all, i don´t know the if statement with the: if name == " Cher " or name == " Madonna ": print ("May I have your autograph please?"), is not working. I tried a lot of combinations and when I digit Jansen as the name it goes to the corre...
[ "Tatsuyuki Ishi answered it best (remove leading and tailing white-space from the strings you are trying to compare), however you will generally want to do something like this for input:\nname.strip()\n\nThis, by default, strips out white space in front of and at the end of text.\n", "The reason it goes to the th...
[ 1, 0 ]
[]
[]
[ "if_statement", "python", "python_3.x" ]
stackoverflow_0043701393_if_statement_python_python_3.x.txt
Q: Tic - Tac - toe with functions... why is my curr_player switchets to "O" or "X" when i enter a wrong input can can i make stay at the same curr_player try the code for ur self to understand what im saying :).... sry if my question is not that understandable English is not my 1st language. how can i fix it? i think...
Tic - Tac - toe with functions... why is my curr_player switchets to "O" or "X" when i enter a wrong input can can i make stay at the same curr_player
try the code for ur self to understand what im saying :).... sry if my question is not that understandable English is not my 1st language. how can i fix it? i think theirs a problem in def choose_cell... but im not sure. #output Hi! Let's play a game. X goes first. #Current player X #Enter cell number (1 to 9): 1 #| X ...
[ "Following up on my comment, here is an approach to fixing your problem.\ndef chooseCell(board):\n cell_number = None\n while True:\n cell_number = int(input(\"\\nEnter cell number (1 to 9): \"))\n if cell_number > 9 or cell_number < 1:\n print(\"Error. Enter an integer between 1 and ...
[ 0 ]
[]
[]
[ "python", "python_3.10", "python_3.x" ]
stackoverflow_0074244881_python_python_3.10_python_3.x.txt
Q: Determine if Django is running under the development server Is there a way to determine if Django is running on localhost and setting the DEBUG variable in settings.py accordingly. So that if I run the server locally it will set DEBUG to True and otherwise set it to False. Localhost: python manage.py runserver Not...
Determine if Django is running under the development server
Is there a way to determine if Django is running on localhost and setting the DEBUG variable in settings.py accordingly. So that if I run the server locally it will set DEBUG to True and otherwise set it to False. Localhost: python manage.py runserver Not localhost: python manage.py runserver 0.0.0.0:8000
[ "As suggested by Bernhard Vallant, you can just check for runserver in sys.argv.\nYou can just replace your DEBUG assignment in settings.py with this:\nDEBUG = (sys.argv[1] == 'runserver')\n\nYou should also import sys somewhere in settings.py.\n", "This is not the best approach, but it works :)\nFor something be...
[ 20, 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0012027545_django_python.txt
Q: API Rate Limit: Any Idea how to find out the rate Limit of the mojang API? Im trying to grab some data from the mojang API. On the wiki website it says the API has a Rate limit of 600 per 10min so that should be 60 requests per minute. The problem is,I have tried to send a request every 1.2 seconds to not exceed t...
API Rate Limit: Any Idea how to find out the rate Limit of the mojang API?
Im trying to grab some data from the mojang API. On the wiki website it says the API has a Rate limit of 600 per 10min so that should be 60 requests per minute. The problem is,I have tried to send a request every 1.2 seconds to not exceed the given Rate-Limit but after just 59 requests it outputs statuscode 429, so sen...
[ "The general limit is 600 requests per 10 minutes.\nSome endpoints have additional limits (Profile has a limit of around 200 requests per minute according to this source)\n" ]
[ 0 ]
[]
[]
[ "api", "python", "python_requests", "rate_limiting", "request" ]
stackoverflow_0074241784_api_python_python_requests_rate_limiting_request.txt
Q: I cant import tensorflow in Jupyter notebook on VSCode I have tensorflow installed on my computer. When I run pip show tensorflow in the terminal I get this message shown. Name: tensorflow Version: 2.10.0 Summary: TensorFlow is an open source machine learning framework for everyone. Home-page: https://www.tensorfl...
I cant import tensorflow in Jupyter notebook on VSCode
I have tensorflow installed on my computer. When I run pip show tensorflow in the terminal I get this message shown. Name: tensorflow Version: 2.10.0 Summary: TensorFlow is an open source machine learning framework for everyone. Home-page: https://www.tensorflow.org/ but when I try to import tensorflow as tf I get th...
[ "Make sure you have the virtual environment activated and the interpreter you are using to debug is the required anaconda version.\nPython Interpreter Version\nFor instance in the above image click on the version number of the interpreter and change the interpreter to the version in which you have installed your an...
[ 1 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074244979_python_tensorflow.txt
Q: How can I remove duplicate and count values for list in RDD? [('key1', ['word1', 'word1', 'word2', ...]), ('key2', ['word1', 'word2', 'word2', ...]), ... ] I want to remove duplicate in the list and assign them to the key. First step output: removing duplicate in list [('key1', ['word1', 'word2', ...]), ('key2...
How can I remove duplicate and count values for list in RDD?
[('key1', ['word1', 'word1', 'word2', ...]), ('key2', ['word1', 'word2', 'word2', ...]), ... ] I want to remove duplicate in the list and assign them to the key. First step output: removing duplicate in list [('key1', ['word1', 'word2', ...]), ('key2', ['word1', 'word2', ...]), ... ] second step output [('key1', ...
[ "As someone already indicated in the comments above, you cannot count the entries after you removed duplicates. Ideally, this should happen during the same operation.\nYour question is not entirely clear. Hence, I am assuming that you want to transform the RDD\n[('key1', ['word1', 'word2', 'word2']),\n ('key2', [...
[ 0, 0 ]
[]
[]
[ "apache_spark", "pyspark", "python", "rdd" ]
stackoverflow_0074242267_apache_spark_pyspark_python_rdd.txt
Q: For some reason .write() does not write string to .txt file anymore So I started with python some days ago and now tried to make a function that gives me all subpages of websites. I know it may not be the most elegant function but I had been pretty proud to see it working. But for some reason unknown to me, my fun...
For some reason .write() does not write string to .txt file anymore
So I started with python some days ago and now tried to make a function that gives me all subpages of websites. I know it may not be the most elegant function but I had been pretty proud to see it working. But for some reason unknown to me, my function does not work anymore. I could've sworn I haven't changed that func...
[ "not a direct answer, but in my early days this happened with me. The requests module of Python sends request with headers indicating python and that could be quickly detected by websites and your IP can get blocked and you are getting unusual response that's why your working function is not working now.\nSolution:...
[ 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "text" ]
stackoverflow_0074245349_beautifulsoup_python_text.txt
Q: Send data to from Arduino to Raspberry using bluetooth hc-05 and python - Byte conversion I'm kinda a newbie here, so thanx in advace for your help. I have and arduino with the HC-05 bluetooth module paired with a raspi 4. I have lots of sensors in the arduino so I wanted to transmit the data from the sensors from...
Send data to from Arduino to Raspberry using bluetooth hc-05 and python - Byte conversion
I'm kinda a newbie here, so thanx in advace for your help. I have and arduino with the HC-05 bluetooth module paired with a raspi 4. I have lots of sensors in the arduino so I wanted to transmit the data from the sensors from the arduino to the raspberry using python. The connection works ok and I started with some exa...
[ "In Python, to convert the bytes back to integers, there is the the int.from_bytes functionality.\nhttps://docs.python.org/3/library/stdtypes.html#int.from_bytes\nSo as an example, your first byte data above b'\\xf9 would be:\npi@raspberry:~ $ python3\nPython 3.9.2 (default, Mar 12 2021, 04:06:34) \n[GCC 10.2.1 202...
[ 1, 0 ]
[]
[]
[ "arduino", "bluetooth", "python", "raspberry_pi" ]
stackoverflow_0072905045_arduino_bluetooth_python_raspberry_pi.txt
Q: How to fix RecursionError: maximum recursion depth exceeded Here's the question: 07. Define a function named import_zip_codes_json() which imports the zip_codes.json as a list in working directory. Here's the code: import json with open('zip_codes.json') as list: zip_codes_json = json.load(list) (The 'def' line...
How to fix RecursionError: maximum recursion depth exceeded
Here's the question: 07. Define a function named import_zip_codes_json() which imports the zip_codes.json as a list in working directory. Here's the code: import json with open('zip_codes.json') as list: zip_codes_json = json.load(list) (The 'def' line is defined by teacher, and what I've wrote is the below part.) d...
[ "def import_zip_codes_json() -> list:\n\n zip_codes_json = import_zip_codes_json()\n return zip_codes_json\n\nThe first thing import_zip_codes_json() does is call itself, which then calls itself, which then calls itself.... forever. Or until the stack blows up and you get the error.\nWhy are you doing this?\...
[ 0 ]
[]
[]
[ "python", "recursionerror" ]
stackoverflow_0074246098_python_recursionerror.txt
Q: Sequence of numbers - python i create a program that reads a sequence of numbers, determines how many different numbers there are (we count the repetitions once), and writes the result to the standard output. my first code: f=int(input("String of numbers: ")) l=[] for x in range(f): string_numbers = int(input(...
Sequence of numbers - python
i create a program that reads a sequence of numbers, determines how many different numbers there are (we count the repetitions once), and writes the result to the standard output. my first code: f=int(input("String of numbers: ")) l=[] for x in range(f): string_numbers = int(input(f'Enter {x+1} string of numbers: '...
[ "It seems like you're mixing up your different variables -- f is what you want the length to be, l is just the number 2, and the way you're comparing those two has nothing to do with the actual input entered by the user, which is my_list.\nUsing variable names that indicate their meaning might make it easier to kee...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074246536_python.txt
Q: PyQt6 QVariantAnimation not emit valueChanged signal when animation value is changed after Cython cythonization When I run the program before cythonize, with pure .py files everything works as it should, the method connected to valueChanged is called when the animation value changes. But, after I did build cythoni...
PyQt6 QVariantAnimation not emit valueChanged signal when animation value is changed after Cython cythonization
When I run the program before cythonize, with pure .py files everything works as it should, the method connected to valueChanged is called when the animation value changes. But, after I did build cythonize, and the program runs from .pyd extensions the method connected to the valueChanged signal is never called. Althou...
[ "I set the type annotation for value to float, although Qt sends int, because of this there was a conflict because Cython used my wrong annotation.\nMany thanks to everyone for the answers and explanations, I am very grateful to you!\n" ]
[ 0 ]
[]
[]
[ "cython", "cythonize", "pyqt", "pyqt6", "python" ]
stackoverflow_0074245047_cython_cythonize_pyqt_pyqt6_python.txt
Q: How To press One While Twilio Call is Making I have this line of code in python to call in Twilio. During a call, it says to press one to continue the call. So, how do I press one while on a call? call = client_.calls.create( record = True, twiml=phone_call, from_...
How To press One While Twilio Call is Making
I have this line of code in python to call in Twilio. During a call, it says to press one to continue the call. So, how do I press one while on a call? call = client_.calls.create( record = True, twiml=phone_call, from_=from_phone_number_, to = to_pho...
[ "The keyword you are looking for is DTMF tones.\nYou can use the <Play> verb to play DTMF tones as well as 1/2 second waits:\n<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<Response>\n <Play digits=\"wwww3\"></Play>\n</Response>\n\nYou can use the <Pause> verb to tell Twilio to pause processing TwiML for a specif...
[ 1 ]
[]
[]
[ "python", "twilio", "twilio_api", "twilio_python" ]
stackoverflow_0074242105_python_twilio_twilio_api_twilio_python.txt
Q: Is it possible to run a Knapsack 0-1 problem in Python with product couples? I have created an integer program in Python with GurobiPy for the 0-1 knapsack problem. However, I want to add a constraint that sais that if product x is added, then product y must also be added for some product couples. My current model...
Is it possible to run a Knapsack 0-1 problem in Python with product couples?
I have created an integer program in Python with GurobiPy for the 0-1 knapsack problem. However, I want to add a constraint that sais that if product x is added, then product y must also be added for some product couples. My current model: There are 2 warehouses, if products are stored in the main warehouse, the profit...
[ "A basic precedence constraint can look like:\n x[j] >= x[i]\n\nwhich means if x[i]=1 then x[j]=1\n" ]
[ 1 ]
[ "I already solved it myself\nTo ensure that the product couples are both assigned to the same warehouse you can use the addGenConstrIndicator from gurobi. For me the solution looked like this:\nfor i in couplesList1:\n for j in couplesList2:\n model.addGenConstrIndicator(x[i], True, x[j], GRB.EQUAL, 1,0\n\...
[ -1 ]
[ "gurobi", "knapsack_problem", "optimization", "pandas", "python" ]
stackoverflow_0074226197_gurobi_knapsack_problem_optimization_pandas_python.txt
Q: inheritance with recursive method override class A: def m(self, v): for i in range(v): print("A") self.m(v-1) class B(A): def m(self, value): print("B") super(B, self).m(value) B().m(3) Output: B A B A B A Expected output: BAAAA On class A, the self object is ...
inheritance with recursive method override
class A: def m(self, v): for i in range(v): print("A") self.m(v-1) class B(A): def m(self, value): print("B") super(B, self).m(value) B().m(3) Output: B A B A B A Expected output: BAAAA On class A, the self object is of B and it's calling method m of class B, but I...
[ "You can temporarily overwrite self.m in your instance of B. This makes it so that you don't need to change the definition of A\nclass A:\n def m(self, v):\n for i in range(v):\n print(\"A\")\n self.m(v-1)\n\nclass B(A):\n def m(self, value):\n print(\"B\")\n mB = self....
[ 1, 0 ]
[]
[]
[ "oop", "python", "python_3.x" ]
stackoverflow_0074239928_oop_python_python_3.x.txt
Q: Use function in str.format or str.format_map When i use f'my string with {fn("somearg")}' the fn(param) function is called and it's return value is written to the string. Is it possible, to do the same in str.format or str.format_map as for example 'my string with {fn("somearg")}'.format(fn=my_function) The intent...
Use function in str.format or str.format_map
When i use f'my string with {fn("somearg")}' the fn(param) function is called and it's return value is written to the string. Is it possible, to do the same in str.format or str.format_map as for example 'my string with {fn("somearg")}'.format(fn=my_function) The intention is to format a file, which calls such function...
[ "Found out, that the f string literal is defined in the C source code and does not use str.format or str.format_map.\nAs current work-around to call functions in a string to format I use:\ndef format_fnc_support(source_string, format_map) :\n return eval(f'f\"\"\"{source_string}\"\"\"', globals(), format_map)\n\...
[ 0 ]
[]
[]
[ "python", "python_3.x", "string_formatting" ]
stackoverflow_0074246088_python_python_3.x_string_formatting.txt
Q: How to plot the lists from a dictionary that correspond to indices of points with x and y coordinates? Say i have a dictionary named "DictionaryOfRoutes" that includes lists like in the following example: 'DictionaryOfRoutes'= {'RouteOfVehicle_1': [0, 6, 1, 5, 0], 'RouteOfVehicle_2': [0, 4, ...
How to plot the lists from a dictionary that correspond to indices of points with x and y coordinates?
Say i have a dictionary named "DictionaryOfRoutes" that includes lists like in the following example: 'DictionaryOfRoutes'= {'RouteOfVehicle_1': [0, 6, 1, 5, 0], 'RouteOfVehicle_2': [0, 4, 3, 0], 'RouteOfVehicle_3': [0, 2, 0] } The lists in the values of it correspond to r...
[ "I modified your code as below:\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef SolutionPlot(xx, yy, all_ids, routes_dictionary , color):\n\n plt.style.use('dark_background')\n fig, ax = plt.subplots()\n\n for route in routes_dictionary.keys():\n\n\n x = [xx[i] for...
[ 2, 0 ]
[]
[]
[ "dictionary", "list", "matplotlib", "python" ]
stackoverflow_0074246116_dictionary_list_matplotlib_python.txt
Q: Dynamically creating read-only attributes I'm currently trying to create a class that inherits from set, but allows calling for subsets with attributes. Since I want to create this class such that I can use it in any context, I want to have it be able to create attributes from any given string. I have succeeded in...
Dynamically creating read-only attributes
I'm currently trying to create a class that inherits from set, but allows calling for subsets with attributes. Since I want to create this class such that I can use it in any context, I want to have it be able to create attributes from any given string. I have succeeded in this, but I want the subsets to only be change...
[ "Limited (im)mutability\nAs I am sure you are aware already, there isn't really any way to make something truly immutable (or \"read-only\") in Python. All you can do, is make it more difficult (or more involved) to change attributes of objects. So no approach will guarantee you fool-proof read-only attributes.\nIf...
[ 0 ]
[]
[]
[ "dynamic_attributes", "python", "readonly_attribute", "setattr" ]
stackoverflow_0074246020_dynamic_attributes_python_readonly_attribute_setattr.txt
Q: Python: how to kill child process(es) when parent dies? The child process is started with subprocess.Popen(arg) Is there a way to ensure it is killed when parent terminates abnormally? I need this to work both on Windows and Linux. I am aware of this solution for Linux. Edit: the requirement of starting a child p...
Python: how to kill child process(es) when parent dies?
The child process is started with subprocess.Popen(arg) Is there a way to ensure it is killed when parent terminates abnormally? I need this to work both on Windows and Linux. I am aware of this solution for Linux. Edit: the requirement of starting a child process with subprocess.Popen(arg) can be relaxed, if a soluti...
[ "Heh, I was just researching this myself yesterday! Assuming you can't alter the child program:\nOn Linux, prctl(PR_SET_PDEATHSIG, ...) is probably the only reliable choice. (If it's absolutely necessary that the child process be killed, then you might want to set the death signal to SIGKILL instead of SIGTERM; the...
[ 39, 10, 0, 0 ]
[]
[]
[ "kill", "linux", "python", "subprocess", "windows" ]
stackoverflow_0023434842_kill_linux_python_subprocess_windows.txt
Q: Is there a way to add a column to a table in PowerPoint slide through Python? I have a powerpoint template which I want to use to create a monthly report. The number of columns in one of the table on the slide can change based on some logic and I would like to add new column during runtime. I was looking for a met...
Is there a way to add a column to a table in PowerPoint slide through Python?
I have a powerpoint template which I want to use to create a monthly report. The number of columns in one of the table on the slide can change based on some logic and I would like to add new column during runtime. I was looking for a method to add a column but couldn't find one. The python-pptx documentation lists an a...
[ "Create a new table of the desired shape.\n>>> shape = table_placeholder.insert_table(rows=..., cols=...)\n>>> table = shape.table\n\nCopy the contents from your last table to the new table. Also, add new values here. Example code:\n>>> cell_old = table_old.cell(0, 0)\n>>> cell_new = table_new.cell(0, 0)\n>>> cell_...
[ 5, 0, 0 ]
[]
[]
[ "python", "python_pptx" ]
stackoverflow_0057866183_python_python_pptx.txt
Q: Authorization missing error when using the token as header using python requests module Trying to convert curl below to the Python requests, below is the curl command which is working fine. curl -k -H "Authorization: Token token=\"$token\""https://conjur.com/secret Above curl works fine and gives expected output b...
Authorization missing error when using the token as header using python requests module
Trying to convert curl below to the Python requests, below is the curl command which is working fine. curl -k -H "Authorization: Token token=\"$token\""https://conjur.com/secret Above curl works fine and gives expected output but when I turn that into python requests it is giving me trouble the header is weird not sure...
[ "In your curl command you have quotes around the token:\ncurl -k -H \"Authorization: Token token=\\\"$token\\\"\" https://conjur.com/secret\n\nNote the token=\\\"$token\\\"\n\nTo have quotes in your Python code do:\ntoken_header = {\"Authorization\": f'Token token=\"{token}\"'}\n\n" ]
[ 0 ]
[]
[]
[ "basic_authentication", "python", "python_requests", "request_headers", "token" ]
stackoverflow_0074242903_basic_authentication_python_python_requests_request_headers_token.txt
Q: How to make my number board start at 1 end at 9 and arrange itself in 3 rows I'm trying to understand this code from "12 Beginner Python Projects - Coding Course" on the FreeCodeCamp Youtube channel and I really don't understand this code to print a board for the Tic Tac Toe project. I've looked around on some oth...
How to make my number board start at 1 end at 9 and arrange itself in 3 rows
I'm trying to understand this code from "12 Beginner Python Projects - Coding Course" on the FreeCodeCamp Youtube channel and I really don't understand this code to print a board for the Tic Tac Toe project. I've looked around on some other vids and I didn't like how they set up their board. My first idea on how to sol...
[ "This style of loops are called list comprehensions in python. Do a short search and you will get lots of information about them.\nWhat happens in your code is practically same with the following:\nnumber_board = []\nfor j in range(3):\n board_row = []\n for i in range(j*3, (j+1)*3):\n board_row.append...
[ 0 ]
[]
[]
[ "for_loop", "iteration", "python", "range", "tic_tac_toe" ]
stackoverflow_0074246738_for_loop_iteration_python_range_tic_tac_toe.txt
Q: Virtual environment (venv) gives a different python version from interpreter In VS Code (Windows), my python interpreter points to version 3.11. python -V in terminal gives me Python 3.11.0 I create a virtual environment with python3 -m venv virtual called virtual, and activate it with .\virtual\Scripts\activate. ...
Virtual environment (venv) gives a different python version from interpreter
In VS Code (Windows), my python interpreter points to version 3.11. python -V in terminal gives me Python 3.11.0 I create a virtual environment with python3 -m venv virtual called virtual, and activate it with .\virtual\Scripts\activate. Now in my environment, checking python -V gives me Python 3.9.13 instead. How do I...
[ "You are creating virtual environment with python3 but checking version with just python. I want you to check if python and python3 are pointing same python executable file before creating virtual environment.\nMay be try creating virtual environment using just python, since its version is 3.11.0.\n$ python -m venv...
[ 1, 0 ]
[]
[]
[ "python", "python_venv", "visual_studio_code" ]
stackoverflow_0074246595_python_python_venv_visual_studio_code.txt
Q: Unable to insert data into Snowflake table using Python Connector Previously I have tried using the COPY INTO command for loading data into Snowflake. Now I am trying to insert the data line by line but I am facing issue in executing the insert query. insert into SUPERHERO values('Spider-Man (Peter Parker)', 'Secr...
Unable to insert data into Snowflake table using Python Connector
Previously I have tried using the COPY INTO command for loading data into Snowflake. Now I am trying to insert the data line by line but I am facing issue in executing the insert query. insert into SUPERHERO values('Spider-Man (Peter Parker)', 'Secret Identity', 'Good Characters', 'Hazel Eyes', 'Brown Hair', 'Male', 'L...
[ "Warehouse was not being used in this code so failure in execution.\ndb_query = \"use warehouse {snowWH};\".format(snowWH=\"NEW_WH\")\nsnowcursor.execute(db_query)\n\nIssue is resolved now.\n" ]
[ 0 ]
[]
[]
[ "insert", "python", "python_3.x", "snowflake_cloud_data_platform" ]
stackoverflow_0074246334_insert_python_python_3.x_snowflake_cloud_data_platform.txt
Q: Python asyncio: Can‘t debug into Task class When working with Python's asyncio package, I've noticed that I can't step into any code of its tasks.Task class. For example, when the calling code invokes the class's constructor, my next 'step into' get's me into a get_debug() function outside the class. After that, I...
Python asyncio: Can‘t debug into Task class
When working with Python's asyncio package, I've noticed that I can't step into any code of its tasks.Task class. For example, when the calling code invokes the class's constructor, my next 'step into' get's me into a get_debug() function outside the class. After that, I return to the calling code with an initialised T...
[ "The implementation of Task is in C (where available). The debugger cannot step into C code.\nYou can see this in the asyncio.tasks module:\nclass Task(futures._PyFuture):\n ...\n\n\n_PyTask = Task\n\n\ntry:\n import _asyncio\nexcept ImportError:\n pass\nelse:\n # _CTask is needed for tests.\n Task =...
[ 1 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074241149_python_python_asyncio.txt
Q: Using django-extensions to generate a model graph in PNG format using Windows 10 (without using Conda or Anaconda) I am using django-extensions to generate a model graph for my Django application. My installation steps are the following: $ pip install django-extensions $ pip install pyparsing pydot An installatio...
Using django-extensions to generate a model graph in PNG format using Windows 10 (without using Conda or Anaconda)
I am using django-extensions to generate a model graph for my Django application. My installation steps are the following: $ pip install django-extensions $ pip install pyparsing pydot An installation of pygraphviz fails (as described) due to missing C extensions: $ pip install pygraphviz # this does not work Now, us...
[ "It took a while but I got it working using the following steps:\n\nInstall django extensions via $ pip install django-extensions==3.1.5\nInstall pydotplus via $ pip install pydotplus==2.0.2\nInstall GraphViz via installer and MANUALLY add it to the user PATH\n\nInclude django_extensions in settings.py:\nINSTALLED_...
[ 3, 0 ]
[]
[]
[ "django", "pydot", "pygraphviz", "python" ]
stackoverflow_0071144974_django_pydot_pygraphviz_python.txt
Q: disnake wait_for() make interaction echec Basically the interaction is just an echec my code: import disnake from disnake import Intents from disnake.ext.commands import Context, Bot bot = Bot(command_prefix='+', test_guilds=[1032280589031706706], help_command=None, intents=Intents.all()) @bot.event async def o...
disnake wait_for() make interaction echec
Basically the interaction is just an echec my code: import disnake from disnake import Intents from disnake.ext.commands import Context, Bot bot = Bot(command_prefix='+', test_guilds=[1032280589031706706], help_command=None, intents=Intents.all()) @bot.event async def on_ready(): print('ready') @bot.comma...
[ "I fix the problem by simply call\nawait inter.response.defer()\n\nright after the callback function.\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "disnake", "python" ]
stackoverflow_0074242173_discord_discord.py_disnake_python.txt
Q: How to start with the InstagramAPI in Python? i want to play with the InstagramAPI and write some code for like getting a list of my follower and something like that. I am really new to that topic. What is the best way to do this? Is there a Python-Lib for handle those json request or should I send them directly ...
How to start with the InstagramAPI in Python?
i want to play with the InstagramAPI and write some code for like getting a list of my follower and something like that. I am really new to that topic. What is the best way to do this? Is there a Python-Lib for handle those json request or should I send them directly to the (new? graphAPI, displayAPI) InstagramAPI? A...
[ "LevPasha's Instagram-API-python, instabot, and many other API's are no longer functional as of Oct 24, 2020 after Facebook deprecated the legacy API and now has a new, authentication-required, API. It now requires registering your app with Facebook to be able to get access to many of the API features (via oembed) ...
[ 8, 5, 4, 0 ]
[]
[]
[ "instagram", "instagram_graph_api", "python" ]
stackoverflow_0061010431_instagram_instagram_graph_api_python.txt
Q: Unexpected results from Numpy r_ When I use ":n" or "m:" as arguments to np.r_, I get unexpected results that I don't understand. Here's my code import numpy as np B = np.arange(180).reshape(6,30) C = B[:, np.r_[10:15, 20:26]] D = C[:, np.r_[0:3,8:11]] Now all of that worked as expected. C prints as: array([[ 1...
Unexpected results from Numpy r_
When I use ":n" or "m:" as arguments to np.r_, I get unexpected results that I don't understand. Here's my code import numpy as np B = np.arange(180).reshape(6,30) C = B[:, np.r_[10:15, 20:26]] D = C[:, np.r_[0:3,8:11]] Now all of that worked as expected. C prints as: array([[ 10, 11, 12, 13, 14, 20, 21, 22, ...
[ "To understand the difference between D and E we have to look what the np.r_ produces. As with function calls, the 'contents' of an indexing, if complex, are evaluated first.\nIn [112]: D = C[:, np.r_[0:3,8:11]]; D.shape\nOut[112]: (6, 6)\nIn [113]: E = C[:, np.r_[:3,8:]]; E.shape\nOut[113]: (6, 11)\n\nThe two r_:...
[ 1, 0 ]
[]
[]
[ "numpy", "numpy_ndarray", "numpy_slicing", "python" ]
stackoverflow_0074214811_numpy_numpy_ndarray_numpy_slicing_python.txt
Q: Changing datatype of multiple columns by range I know I can change the data type of columns by passing the column names, for example df = df.astype({'col1': 'object', 'col2': 'int'}) but what if I want to change multiple columns by a given range? My df contains 50+ columns so I don't want to change them all by nam...
Changing datatype of multiple columns by range
I know I can change the data type of columns by passing the column names, for example df = df.astype({'col1': 'object', 'col2': 'int'}) but what if I want to change multiple columns by a given range? My df contains 50+ columns so I don't want to change them all by name. I want to set columns 17 to 41 as ints and I've t...
[ "You can access columns by index (position).\ndf.iloc[:,16:42] = df.iloc[:,16:42].apply(pd.to_numeric)\n\n", "You could slice a list of the column names and unpack it in a dict comprehension!\ndf.astype({c: \"int64\" for c in df.columns[17:41]})\n\n" ]
[ 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074246826_pandas_python.txt
Q: TypeError: 'NoneType' object is not iterable after random.shuffle() Purely as a learning experience I've started a basic Python script. At the moment, it's supposed to simulate a shuffled deck of standard playing cards. My script works as expected, except for the shuffling part. import random deck = list() # play...
TypeError: 'NoneType' object is not iterable after random.shuffle()
Purely as a learning experience I've started a basic Python script. At the moment, it's supposed to simulate a shuffled deck of standard playing cards. My script works as expected, except for the shuffling part. import random deck = list() # play_deck = list() suits = ['hearts', 'clubs', 'diamonds', 'spades'] card = {...
[ "random.shuffle(lst) modifies lst in-place, and returns None (like lst.sort()).\nInstead of\ndeck = random.shuffle(deck)\n\ndo\nrandom.shuffle(deck)\n\n" ]
[ 0 ]
[ "https://docs.python.org/3/library/random.html#random.shuffle\nrandom.shuffle(x)\nShuffle the sequence x in place.\nTo shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.\n" ]
[ -1 ]
[ "python", "random" ]
stackoverflow_0074246873_python_random.txt
Q: How do I increment certain values in Tensorflow tensor? I want to increment certain values of an tensor in Tensorflow. The code I am attempting to use is: outs[h, i:i+self.cnv, j:j+self.cnv] += (self.b*counts)/sums I am not sure how to do this, and the shapes of the Tensors do match, and I am using tf version 2.9...
How do I increment certain values in Tensorflow tensor?
I want to increment certain values of an tensor in Tensorflow. The code I am attempting to use is: outs[h, i:i+self.cnv, j:j+self.cnv] += (self.b*counts)/sums I am not sure how to do this, and the shapes of the Tensors do match, and I am using tf version 2.9.1. The error message is: TypeError: 'Tensor' object does not...
[ "No easy way of doing it. But here is one way:\nAn Example:\ninputs = tf.random.uniform(maxval=10, dtype=tf.int32, shape=(2, 3, 2))\n\n\narray([[[0, 1],\n [0, 8],\n [4, 1]],\n\n [[4, 6],\n [2, 8],\n [5, 4]]], dtype=int32)>\n\n\n#Convert to tf.Variable to make the assignment\ntemp =...
[ 1 ]
[]
[]
[ "python", "tensor", "tensorflow" ]
stackoverflow_0074246521_python_tensor_tensorflow.txt
Q: Flatten JSON with columns having values as a list in dataframe I have the following data frame: | Category | idlist | | -------- | -----------------------------------------------------------------| | new | {100: ['1A', '2B'], 200: ['2A', '3B'], 300: ['...
Flatten JSON with columns having values as a list in dataframe
I have the following data frame: | Category | idlist | | -------- | -----------------------------------------------------------------| | new | {100: ['1A', '2B'], 200: ['2A', '3B'], 300: ['3A', '3B', '4B']} | | old |  ['99A', '99B'] ...
[ "click here\n def function1(s:pd.Series):\n global df2\n list1 = []\n var1=eval(s.idlist)\n if isinstance(var1,dict):\n for i in var1:\n list1.append({'Category':s.Category,'id':i,'list':var1[i]})\n else:\n list1.append({'Category':s.Category,'id':-1,'list':var1})\n df2=...
[ 1, 1, 1, 0 ]
[]
[]
[ "dataframe", "json", "json_normalize", "pandas", "python" ]
stackoverflow_0074133487_dataframe_json_json_normalize_pandas_python.txt
Q: Why "index 1 is out of bounds for axis 0 with size 1" when requesting this API using iterrows()? In a CSV-file I have a column with 150k id-values, like below. I am trying to iterate through them and call the API using each value. The API has the request limit 5000/min. OBJEKT_ID id1 id2 id3 ... I then want to pu...
Why "index 1 is out of bounds for axis 0 with size 1" when requesting this API using iterrows()?
In a CSV-file I have a column with 150k id-values, like below. I am trying to iterate through them and call the API using each value. The API has the request limit 5000/min. OBJEKT_ID id1 id2 id3 ... I then want to put the requested data (CLASS) into a new csv-file together with the corresponding ID in another column....
[ "Corrections for the following errors:\n\nrow is a 1 element pandas series, so df['OBJEKT_ID'] = [row[index]] becomes out of bounds\nYou're creating a new dataframe in each loop i.e. df = pandas.DataFrame()\nYou're overwriting the csv file with each loop i.e. df.to_csv(\"collected_data.csv\", index=False)\n\nCode\n...
[ 0 ]
[]
[]
[ "api", "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074244715_api_dataframe_pandas_python_python_3.x.txt
Q: jupyter notebook does not render LaTeX properly I started using python with the jupyter notebook and I really like the markdown feature. The only problem (more esthetically) is that the printing is not like the standard LaTeX/Mathjax rendering. This is my first cell import sympy as sm import numpy as np This is m...
jupyter notebook does not render LaTeX properly
I started using python with the jupyter notebook and I really like the markdown feature. The only problem (more esthetically) is that the printing is not like the standard LaTeX/Mathjax rendering. This is my first cell import sympy as sm import numpy as np This is my second cell (example code from documentation) %%lat...
[ "I have a simple solution to printing markdown cells in a Jupyter Notebook. I have always had problems with this, and the built-in solutions do not always work.\nWhat I do is upload the ipynb file to Colaboratory (https://colab.research.google.com/), a free service, and then print it.\nVoila, problem solved.\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "mathjax", "python", "rendering" ]
stackoverflow_0048150506_jupyter_notebook_mathjax_python_rendering.txt
Q: PYTHON: Why can't the on_release function from the keyboard module detect anything? I've been trying for hours to get this piece of code to work. The issue seems to be that on_release doesn't detect anything, unlike on_press which works perfectly fine. I've tried to read up on these functions in the documentation(...
PYTHON: Why can't the on_release function from the keyboard module detect anything?
I've been trying for hours to get this piece of code to work. The issue seems to be that on_release doesn't detect anything, unlike on_press which works perfectly fine. I've tried to read up on these functions in the documentation(https://github.com/boppreh/keyboard#keyboard.on_release_key), however it doesn't provide ...
[ "I've finally managed to find a solution! The issue was that you can't use two different hooks for some reason, so I solved it with one.\nimport time\nfrom keyboard._keyboard_event import KEY_DOWN, KEY_UP\n\ndef on_action(event):\n if event.event_type == KEY_DOWN:\n on_press(event.name)\n\n elif event....
[ 0 ]
[]
[]
[ "input", "keyboard", "python" ]
stackoverflow_0074246583_input_keyboard_python.txt
Q: Copy an image to MacOS clipboard using python I want to copy an image (PIL image) to clipboard on Mac OS I tried dozens of different ways to do that. Most of python clipboard modules like pyclip or clipboard doesn't support images. I found a code that does that on windows, but nothing for mac. I tried to use QT, ...
Copy an image to MacOS clipboard using python
I want to copy an image (PIL image) to clipboard on Mac OS I tried dozens of different ways to do that. Most of python clipboard modules like pyclip or clipboard doesn't support images. I found a code that does that on windows, but nothing for mac. I tried to use QT, installed it through brew, for some reason brew ins...
[ "This little piece of ugliness works and loads \"image.jpg\" onto the clipboard...\n#!/usr/bin/env python3\n\nimport subprocess\n\nsubprocess.run([\"osascript\", \"-e\", 'set the clipboard to (read (POSIX file \"image.jpg\") as JPEG picture)'])\n\n", "Marks answer doesnt work for me for pngs.\nBut i found this wh...
[ 4, 0 ]
[]
[]
[ "clipboard", "image", "python" ]
stackoverflow_0054008175_clipboard_image_python.txt
Q: How to delete an entry from a numpy array in place, and retain it's initial shape? Let's say, that we have a numpy array storing large objects. My goal is to delete one of these objects from memory, but retain the initial structure of the array. The cell, under which this object was stored might be filled for exam...
How to delete an entry from a numpy array in place, and retain it's initial shape?
Let's say, that we have a numpy array storing large objects. My goal is to delete one of these objects from memory, but retain the initial structure of the array. The cell, under which this object was stored might be filled for example with None. Example simplified behaviour, where I replaced large objects with charact...
[ "When you create a numpy array, it has a fixed size. Eventually, when you try to delete an element it will create a new numpy array.\nThe way you are trying to do it, that's not an effective way. Please try another library.\n", "You can do this with a multi-dimensional array and not even get pandas or numpy invol...
[ 3, 0 ]
[]
[]
[ "in_place", "numpy", "numpy_ndarray", "python" ]
stackoverflow_0074246505_in_place_numpy_numpy_ndarray_python.txt
Q: return statement just prints one value, print statement prints all the values I have this method: def filter_verdi_total_fruit_cost(file_name): output = [] for token in file_name.split('\n'): items = token.split() if len(items) > 2 and items[1] in fruit_words: output.append((ite...
return statement just prints one value, print statement prints all the values
I have this method: def filter_verdi_total_fruit_cost(file_name): output = [] for token in file_name.split('\n'): items = token.split() if len(items) > 2 and items[1] in fruit_words: output.append((items[1], items[-1])) for _, v in output: return v print(...
[ "When you invoke the returnstatement, your function is stopped and returns a value.\nYou can print the elements outside the function like this, returning the array with all the tuples.\ndef filter_verdi_total_fruit_cost(file_name):\n output = []\n for token in file_name.split('\\n'):\n items = token.sp...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074247050_python.txt
Q: model.test output is not (nbr of samples, precision, recall) I am new to Fasttext I am using python-wheel(v0.9.2) module with python3.10 I trained a text classification model when I run a model.test("datasets\dataset1.txt") I except an output like: (nbr of samples, precision, recall) I get (1, 1.0, 1.1146408069999...
model.test output is not (nbr of samples, precision, recall)
I am new to Fasttext I am using python-wheel(v0.9.2) module with python3.10 I trained a text classification model when I run a model.test("datasets\dataset1.txt") I except an output like: (nbr of samples, precision, recall) I get (1, 1.0, 1.1146408069999442e-05)
[ "The most simple explanation may be: (1, 1.0, 1.1146408069999442e-05) are the accurately-reported (sample_count, precision, recall) for your model & file.\nWhat makes you sure it's not? Are you sure training succeeded on properly-formatted data?\nHow did you train the model, on what data? What progress/success was ...
[ 0 ]
[]
[]
[ "fasttext", "python", "python_3.x" ]
stackoverflow_0074229174_fasttext_python_python_3.x.txt
Q: Comparing the average RGB value of an image in python I am trying to recognize an image by the average RGB value of the image. However, this value may have slight deviations in the RGB value. I have an array of exact values, but when checking, I would like to check the values 5 more and smaller in each element. Fo...
Comparing the average RGB value of an image in python
I am trying to recognize an image by the average RGB value of the image. However, this value may have slight deviations in the RGB value. I have an array of exact values, but when checking, I would like to check the values 5 more and smaller in each element. For example, if I have a red color with a value of 30, I woul...
[ "I would do a difference between the RGB triplets and then check if any of the values are greater than a treshold:\n# This is a list of values to compare against, I imagine you will have several triplets to compare. \n\nflashes = [[\"25.\", \"26.\", \"27.\"], ...]\n\n#This is the average calculated from an image, s...
[ 0 ]
[]
[]
[ "average", "image", "opencv", "python", "rgb" ]
stackoverflow_0074247018_average_image_opencv_python_rgb.txt
Q: Get coordinates using on_click and ipwidgets on Plotly I'm trying to get the coordinates in a list type when clicking some point of the graph. I have this sample code that I got here in stackoverflow, but I'm not able to print the list or access it out of the call-back function, how can I do it? import numpy as np...
Get coordinates using on_click and ipwidgets on Plotly
I'm trying to get the coordinates in a list type when clicking some point of the graph. I have this sample code that I got here in stackoverflow, but I'm not able to print the list or access it out of the call-back function, how can I do it? import numpy as np import plotly.express as px import plotly.graph_objects as ...
[ "All you need to do is to use points object as follows:\n@out.capture()\ndef base_click(trace, points, selector):\n global clicked\n clicked.append([points.xs[0],points.ys[0]])\n\nprint(clicked) #<--- outside the function base_click\n\n" ]
[ 0 ]
[]
[]
[ "onclick", "plotly", "python", "widget" ]
stackoverflow_0074246994_onclick_plotly_python_widget.txt
Q: How to replace pandas append with concat? Can you help me replace append with concat in this code? saida = pd.DataFrame() for x, y in lCodigos.items(): try: df = consulta_bc(x) logging.info(f'Indice {y} lido com sucesso.') except Exception as err: logging.error(err) logging.warning('Rotina Indice f...
How to replace pandas append with concat?
Can you help me replace append with concat in this code? saida = pd.DataFrame() for x, y in lCodigos.items(): try: df = consulta_bc(x) logging.info(f'Indice {y} lido com sucesso.') except Exception as err: logging.error(err) logging.warning('Rotina Indice falhou!') exit() df['nome'] = y saida = said...
[ "Just save the \"dataframe parts\" using a list and use pd.concat on that list of dataframes at the end:\nsaida = list() # Now use a list\nfor x, y in lCodigos.items():\n # ... your original code\n saida.append(df)\nsaida = pd.concat(saida) # You can now create the dataframe\n\n", " saida= pd.concat([sai...
[ 1, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0071517750_pandas_python.txt
Q: How to make a calculator discord bot? How to make a discord bot so when I input the following it calculates it: INPUT: 2.2x100 2.8x100-10% OUTPUT: output should be the result of the following: 2.8100 - 2.2100 and then minus 10% of that, (that equation is subject to change) How would I do this? A: This is not an ...
How to make a calculator discord bot?
How to make a discord bot so when I input the following it calculates it: INPUT: 2.2x100 2.8x100-10% OUTPUT: output should be the result of the following: 2.8100 - 2.2100 and then minus 10% of that, (that equation is subject to change) How would I do this?
[ "This is not an easy task (if you don't want to be unsafe and eval() code).\nYou need an infix parser that takes into account order of operations (priorities). If there are parenthesis in your operation, it will be even more complex.\nYou will then need to evaluate the result with a function that executes an abstra...
[ 1 ]
[]
[]
[ "calculator", "discord", "python" ]
stackoverflow_0074247132_calculator_discord_python.txt
Q: How to combine two dicts in one with replacing "false" values in first by "not false" values from second if values are not in false_list (Pandas)? The problem in that: I have two Excel sheets. Need to replace values in [something, like, some, false, values] in first sheet by values from second. The tables can cont...
How to combine two dicts in one with replacing "false" values in first by "not false" values from second if values are not in false_list (Pandas)?
The problem in that: I have two Excel sheets. Need to replace values in [something, like, some, false, values] in first sheet by values from second. The tables can contain not equal dimensions For example, need that dc_result from dc1 and dc2, by merging on='n': import pandas as pd import numpy as np dc1 = { 'n':...
[ "Since pandas doesn't like columns with unequal length, this can instead be done using a python dictionary/list comprehension\ndc_result = {k:[dc1[k][i] if dc1[k][i] not in false_list else dc2[k][i] \n for i in range(len(dc1[k]))] for k in dc1}\n\n" ]
[ 1 ]
[]
[]
[ "dictionary", "list", "merge", "pandas", "python" ]
stackoverflow_0074247073_dictionary_list_merge_pandas_python.txt
Q: can you print for loop lines next or on top of each other? i,a = 1,1 for i in range(1,6): print(i, end = " ") i =+1 print() for a in range(1,11): if a % 2 == False: print(a, end = " ") I have this result: 1 2 3 4 5 2 4 6 8 10 I want this: 1 2 3 4 5 ...
can you print for loop lines next or on top of each other?
i,a = 1,1 for i in range(1,6): print(i, end = " ") i =+1 print() for a in range(1,11): if a % 2 == False: print(a, end = " ") I have this result: 1 2 3 4 5 2 4 6 8 10 I want this: 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 ...
[ "Use nested loops:\nfor i in range(1, 6):\n for j in range(i, i * 5 + 1, i):\n print(j, end=\" \")\n print()\n\nThe outer loop (i) is the first number in each row; the numbers in the row (j) increment by i until there are 5 of them in the row. The range function handles all of this for you because you...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074247177_python.txt
Q: pandas dataframe calculate squared distance between each 2 rows I have dataframe with numeric rows Writer | A | B | C 1 | 0.2 | 0.4 | 0.6 2 | 0.1 | 1.2 | 0.3 3 | 0.5 | 0.2 | 0.8 I want to calculate squared distance between 2 writer. Is there a simple way to do this? A...
pandas dataframe calculate squared distance between each 2 rows
I have dataframe with numeric rows Writer | A | B | C 1 | 0.2 | 0.4 | 0.6 2 | 0.1 | 1.2 | 0.3 3 | 0.5 | 0.2 | 0.8 I want to calculate squared distance between 2 writer. Is there a simple way to do this?
[ "If you want distances between all pairs, you can use sklearn.metrics.pairwise_distances, as follows:\nfrom sklearn.metrics import pairwise_distances\n\nD = pairwise_distances (df [['A','B','C']].values)\n\nIf you want just the distance between two writers, say 1 and 2:\nfrom sklearn.metrics.pairwise import euclide...
[ 0 ]
[]
[]
[ "dataframe", "heatmap", "pandas", "python" ]
stackoverflow_0074247117_dataframe_heatmap_pandas_python.txt
Q: How to delete Label before printing a new one My python code has a ui calendar and button but i don't know how to get the label to print and after destroying the label before it from tkinter import* from tkcalendar import* root=Tk() root.title("Code project") def selectDate(): myDate =my_Cal.get_date() s...
How to delete Label before printing a new one
My python code has a ui calendar and button but i don't know how to get the label to print and after destroying the label before it from tkinter import* from tkcalendar import* root=Tk() root.title("Code project") def selectDate(): myDate =my_Cal.get_date() selectedDate = Label(text=myDate) selectedDate.p...
[ "You have to define your label just once and update just it's text like this:\nfrom tkinter import*\nfrom tkcalendar import*\n\nroot=Tk()\nroot.title(\"Code project\")\n\nselectedDate = Label(root, text=\"\")\n\ndef selectDate():\n myDate =my_Cal.get_date()\n selectedDate.config(text=myDate)\n selectedDate...
[ 1 ]
[]
[]
[ "python", "tkcalendar", "tkinter" ]
stackoverflow_0074247262_python_tkcalendar_tkinter.txt
Q: locating element via selenium xpath I am trying to locate below element from enter link description here with this code x_title=driver.find_element(By.XPATH,'//h2/a/span[@class="a-size-medium"]') it gives an error of selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate elem...
locating element via selenium xpath
I am trying to locate below element from enter link description here with this code x_title=driver.find_element(By.XPATH,'//h2/a/span[@class="a-size-medium"]') it gives an error of selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//h2/a...
[ "Your mistake is that elements have multiple class names. Not only a-size-medium and s-title-instructions-style.\nSo, instead //div[@class=\"s-title-instructions-style\"]//span[@class=\"a-size-medium\"] it should be\n\"//div[contains(@class,\"s-title-instructions-style\")]//span[contains(@class,\"a-size-medium\")]\...
[ 2 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0074244382_python_selenium_xpath.txt
Q: How can vectorize a function that takes two arrays as input? Assume I have a 3D numpy array $y_{n \times m \times p}$ and a 1D numpy array$x_{p \times 1}$, I want to apply the function 'PyOLS' on each slice of $y$ (i.e., $y[i, j, :]$) and $x$. How can I vectorize this operation in Python? The following is an examp...
How can vectorize a function that takes two arrays as input?
Assume I have a 3D numpy array $y_{n \times m \times p}$ and a 1D numpy array$x_{p \times 1}$, I want to apply the function 'PyOLS' on each slice of $y$ (i.e., $y[i, j, :]$) and $x$. How can I vectorize this operation in Python? The following is an example code: import numpy as np def PyOLS(xvec, yvec): n = xvec.sha...
[ "As @relent95 properly said, you can vectorize your approach using an already expanded array for x with the following function:\nVectorized approach\ndef PyOLS_vectorized(x, y):\n # You could extract this out of the function if done previously\n x2 = np.ones((x.shape + (2,)))\n x2[...,0] = x\n\n betas =...
[ 3 ]
[]
[]
[ "python", "python_3.x", "vectorization" ]
stackoverflow_0074242129_python_python_3.x_vectorization.txt
Q: What relation between 10 digits and datetime I search the relation between these times (in seconds) and these timestamps 30 seconds => 1189765120 1 minute => 1198153728 2 minutes => 1206542524 4 minutes => 1214930944 These info come from "Image Line FL Studio" music software. I try to make a program in Python to ...
What relation between 10 digits and datetime
I search the relation between these times (in seconds) and these timestamps 30 seconds => 1189765120 1 minute => 1198153728 2 minutes => 1206542524 4 minutes => 1214930944 These info come from "Image Line FL Studio" music software. I try to make a program in Python to manipulate FLP file, and I search without success ...
[ "Ok, this time I found the answer (the exponential progression 1/2, 1, 2, 4 minutes of your length, and the counting bits, and the 0 almost always gave me the hint: it looks like floating point representation)\n#include <stdio.h>\n#include <stdint.h>\n\nint main(){\n uint32_t l[]={1189765120, 1198153728, 1206542...
[ 4 ]
[]
[]
[ "logic", "math", "python" ]
stackoverflow_0074246934_logic_math_python.txt
Q: How to filter out and replace elements from a 3 dimensional nd.array I am trying to use PIL and numpy to map the colors of an image to a scalar value. The parts of the image I need to analyze are in greyscale but the parts that are to be ignored are in green (0,255,0). I am trying to replace all the green (0,255,0...
How to filter out and replace elements from a 3 dimensional nd.array
I am trying to use PIL and numpy to map the colors of an image to a scalar value. The parts of the image I need to analyze are in greyscale but the parts that are to be ignored are in green (0,255,0). I am trying to replace all the green (0,255,0) elements in the array with (np.nan,np.nan,np.nan) but I am struggling to...
[ "If you want to replace all (perfectly) green pixels with white, use:\nim[np.all(im==(0,255,0), axis=2)] = [255, 255, 255]\n\nThe np.all(..., axis=2) is essentially making the AND condition you were looking for across all elements of the depth (i.e. colour) axis.\n" ]
[ 0 ]
[]
[]
[ "multidimensional_array", "numpy", "python", "python_imaging_library", "replace" ]
stackoverflow_0074244097_multidimensional_array_numpy_python_python_imaging_library_replace.txt
Q: Know about how to stop the Sound within the loop after user input I wanted to ask that how I can play the sound in loop and then when the user click ENTER the music stops and the loop break like in this #help here that's the place where I wanted it to loop till the user gives the input to stop and also how can we ...
Know about how to stop the Sound within the loop after user input
I wanted to ask that how I can play the sound in loop and then when the user click ENTER the music stops and the loop break like in this #help here that's the place where I wanted it to loop till the user gives the input to stop and also how can we add a counter that will run in the background of the program while othe...
[ "I'm not very experienced in python, but i have a few suggestions:\nin order to stop the loop, instead of using while True, use an actual condition, such as a variable being 1. and make it so that when enter is clicked, you add 1 to the variable. this way you can easily stop the loop.\nfor stopping the music, i hon...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074247326_python.txt
Q: python plot ledged? unwanted labels None,None resulting from groupby() function ** Problem ** Plot is working fine. Need to remove "None, None" from display on plot. Perhaps this is some default legend, how to set to NULL or customize or remote. ** Python Plot Code ** plt.figure(figsize=(15,10.5)) df_select = empl...
python plot ledged? unwanted labels None,None resulting from groupby() function
** Problem ** Plot is working fine. Need to remove "None, None" from display on plot. Perhaps this is some default legend, how to set to NULL or customize or remote. ** Python Plot Code ** plt.figure(figsize=(15,10.5)) df_select = employee_5years.drop(['Age','Years.of.Service','County.Code','YEAR','Tenure.Years','Assig...
[ "Plot has a legend, and I had forgotten to set legend to None: hence the solution: plot(title=\"\", legend=None)\n" ]
[ 0 ]
[]
[]
[ "group_by", "line_plot", "plot", "python" ]
stackoverflow_0074247286_group_by_line_plot_plot_python.txt
Q: Can I shuffle a list to receive a specific pattern? I am trying to make a fictional topographical map so i need a specific pattern for the shuffled list. i have already made the list and can shuffle it but i cannot seem to shuffle it to a specific pattern. eg. n = [1,4,2,3,5,4,3] shuffle(n) print(n) [3,4,5,4,3,2,1...
Can I shuffle a list to receive a specific pattern?
I am trying to make a fictional topographical map so i need a specific pattern for the shuffled list. i have already made the list and can shuffle it but i cannot seem to shuffle it to a specific pattern. eg. n = [1,4,2,3,5,4,3] shuffle(n) print(n) [3,4,5,4,3,2,1] shuffle(n) print(n) [4,5,4,3,3,2,1] basically i need t...
[ "Here's a technique which will only work if your input is relatively short, as it calculates all permutations of the original, filters them to include only those with such small steps, then returns a function which will randomly generate one of them. If the array length is large, this will take far too long.\nThis...
[ 1 ]
[]
[]
[ "algorithm", "design_patterns", "python", "shuffle" ]
stackoverflow_0074228025_algorithm_design_patterns_python_shuffle.txt
Q: Extract elements from bs4.element.ResultSet I'm looking to extract the two numeric value from this bs4. forecast = [<div class="cell "><span>1.2</span><span class="m-unit"></span> - <span>2.0</span><span class="m-unit"></span></div>, <div class="cell "><span>1.5</span><span class="m-unit"></span> - <span>2.6</spa...
Extract elements from bs4.element.ResultSet
I'm looking to extract the two numeric value from this bs4. forecast = [<div class="cell "><span>1.2</span><span class="m-unit"></span> - <span>2.0</span><span class="m-unit"></span></div>, <div class="cell "><span>1.5</span><span class="m-unit"></span> - <span>2.6</span><span class="m-unit"></span></div>, Do you kno...
[ "If the pattern is always identical and no other deviations occur, the following procedure can be followed:\npd.DataFrame([e.text.split('-') for e in forcast])\n\nNote: For reliable results, more detailed information is needed in the questionnaire.\nExample\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\nhtm...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074247357_beautifulsoup_python.txt
Q: Is there a simple and efficient way to use a global variable into a method of a class with Python I have a code with a class using many variables.i can't Access one of those variables to use it inside of a method of my code written in Python. I tried to declare the variable as global to make the value being access...
Is there a simple and efficient way to use a global variable into a method of a class with Python
I have a code with a class using many variables.i can't Access one of those variables to use it inside of a method of my code written in Python. I tried to declare the variable as global to make the value being accessible at any point of the code but it is not ok. I am expecting to use the variable in a specific method...
[ "In Python, \"variables\" are really \"names\" and you can access them whenever they're in scope!\nHowever, if you intend to modify a name that's outside of the current scope, you need to tell the interpreter so (otherwise it'll assume that you mean to give the name to something else within your scope)\na = None\n\...
[ 0, 0, 0 ]
[]
[]
[ "class", "global_variables", "methods", "python" ]
stackoverflow_0074247350_class_global_variables_methods_python.txt
Q: Not able to DM or direct messages in discord.py-self latest version i am not been able to send dm it gives me an error using module discord.py-self here is the code import discord class MyClient(discord.Client): async def on_ready(self): print(f'Logged in as {self.user} (ID: {self.user.id})') ...
Not able to DM or direct messages in discord.py-self latest version
i am not been able to send dm it gives me an error using module discord.py-self here is the code import discord class MyClient(discord.Client): async def on_ready(self): print(f'Logged in as {self.user} (ID: {self.user.id})') print('BOT IS RUNNING') async def on_message(self, message):...
[ "I would try defining your bot like this:\nimport discord\nfrom discord.ext import commands\n\n## (Make sure you define your intents)\nintents = discord.Intents.default()\n# What I always add for example:\nintents.members = True\nintents.guilds = True\nintents.messages = True\nintents.reactions = True\nintents.pres...
[ 1 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074182448_discord.py_python.txt
Q: Removing \xf characters I am trying to remove all \xf0\x9f\x93\xa2, \xf0\x9f\x95\x91\n\, \xe2\x80\xa6,\xe2\x80\x99t type characters from the below strings in Python Text _____________________________________________________ "b'Hello! \xf0\x9f\x93\xa2 End Climate Silence is looking for volunteers! \n\n1-2 h...
Removing \xf characters
I am trying to remove all \xf0\x9f\x93\xa2, \xf0\x9f\x95\x91\n\, \xe2\x80\xa6,\xe2\x80\x99t type characters from the below strings in Python Text _____________________________________________________ "b'Hello! \xf0\x9f\x93\xa2 End Climate Silence is looking for volunteers! \n\n1-2 hours per week. \xf0\x9f\x95\x...
[ "Your current data in the question indicates you are using bytestring representations re-encoded as Unicode strings, and now you want to decode those bytestrings, but first, you need to encode the strings back to the bytestrings.\nSo, in your case, you can use\nx = \"b\"\"This doesn't feel like targeted propaganda ...
[ 1, 1, 0 ]
[]
[]
[ "python", "python_3.x", "string" ]
stackoverflow_0069765477_python_python_3.x_string.txt
Q: Networkx is_negatively_weighted Is False, But Use Dijkstra Return ('Contradictory paths found:', 'negative weights?') I wanted to use a gragh to get a shortest path,but networkx tiped me 'ValueError: ('Contradictory paths found:', 'negative weights?')'.After that,i checked all the gragh edges,they were all bigger ...
Networkx is_negatively_weighted Is False, But Use Dijkstra Return ('Contradictory paths found:', 'negative weights?')
I wanted to use a gragh to get a shortest path,but networkx tiped me 'ValueError: ('Contradictory paths found:', 'negative weights?')'.After that,i checked all the gragh edges,they were all bigger the zero. In the end, I uesd the nx.is_negatively_weighted(G, weight='weight'), which return False.however,Dijkstra also re...
[]
[]
[ "I have met the same problem that there are actually no negatively weighted edges in the network,but it gave me this error when conducting traffic assignment. I finally found that it was not the problem of negatively weighted edges but those with infinite weights (inf or np.nan) that concern. Suggest checking it an...
[ -1 ]
[ "dijkstra", "networkx", "python" ]
stackoverflow_0069776074_dijkstra_networkx_python.txt
Q: Yolo V7 Custom Weight Works in Colab but not in Local Windows Machine For my project I'm using Yolo V7 for detecting some balls. I trained it with 8 batch size and 300 epochs the detection was perfect in Google Colab I tried same model in local machine (Gaming Laptop) it didn't detect and I had no errors showed in...
Yolo V7 Custom Weight Works in Colab but not in Local Windows Machine
For my project I'm using Yolo V7 for detecting some balls. I trained it with 8 batch size and 300 epochs the detection was perfect in Google Colab I tried same model in local machine (Gaming Laptop) it didn't detect and I had no errors showed in terminal. I tried lowering confidence level and did as I can. Even I tried...
[ "I tried your trained model with the image you provided and works fine.\n\nTry to follow these steps:\n\n!git clone https://github.com/WongKinYiu/yolov7.git\ncd yolov7\nrun: ! python3 detect.py --source path to image --weights path to best.pt\ncheck the result in yolov7/runs/detect/exp folder\n\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "object_detection", "python", "yolo", "yolov5" ]
stackoverflow_0074226361_machine_learning_object_detection_python_yolo_yolov5.txt
Q: Trouble Creating a webpage I'm having trouble creating a view. Down below you can find my view. I keep getting template error. I'm not sure where I went wrong.. class PrivacyView(CreateView): model = Post template_name = 'privacy_policy.html' fields = '__all__' def form_valid(self, form): form...
Trouble Creating a webpage
I'm having trouble creating a view. Down below you can find my view. I keep getting template error. I'm not sure where I went wrong.. class PrivacyView(CreateView): model = Post template_name = 'privacy_policy.html' fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs[...
[ "There is a problem with the return\nreturn render(request, 'post_list.html', {'posts': posts, page: 'pages', 'tag': tag})\nIn passing the 'pages' variable, you mixed up the order, so it should be.\nreturn render(request, 'post_list.html', {'posts': posts, 'pages': page, 'tag': tag})\nThis won't throw an error, but...
[ 0 ]
[]
[]
[ "blogs", "django", "python", "view" ]
stackoverflow_0074243290_blogs_django_python_view.txt
Q: Rpy2 Error depends on execution method: NotImplementedError: Conversion "rpy2py" not defined the successful execution of following code depends in my case on the execution method. Executing the code for the first time via F5 works without any errors. However, executing the code for the second time via F5 raises th...
Rpy2 Error depends on execution method: NotImplementedError: Conversion "rpy2py" not defined
the successful execution of following code depends in my case on the execution method. Executing the code for the first time via F5 works without any errors. However, executing the code for the second time via F5 raises the error: "NotImplementedError: Conversion 'rpy2py' not defined for objects of type '<class 'rpy2.r...
[ "This is an issue with jupyterlab/ipykernel. rpy2 is not going to be the only package that fails. Others also using contextvars will likely have issues. Updating ipykernel solves the problem.\nhttps://github.com/rpy2/rpy2/issues/952\n" ]
[ 0 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0074192490_python_r_rpy2.txt
Q: How to stop "loop.run_forever()" with "loop.stop()" in Python? I'm trying to stop loop.run_forever() with loop.stop() in Python as shown below but loop.stop() doesn't stop loop.run_forever(): import asyncio async def test(): print("Test") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.cre...
How to stop "loop.run_forever()" with "loop.stop()" in Python?
I'm trying to stop loop.run_forever() with loop.stop() in Python as shown below but loop.stop() doesn't stop loop.run_forever(): import asyncio async def test(): print("Test") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.create_task(test()) loop.run_forever() loop.stop() # Here The documen...
[ "You need to call loop.stop() in test() by passing loop to test() as shown below:\nimport asyncio\n\nasync def test(loop):\n print(\"Test\")\n loop.stop() # Here\n\nloop = asyncio.new_event_loop()\nasyncio.set_event_loop(loop)\n \nloop.create_task(test(loop)) # Pass \"loop\" to \"test()\"\...
[ 0 ]
[]
[]
[ "asynchronous", "event_loop", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0074247595_asynchronous_event_loop_python_python_3.x_python_asyncio.txt
Q: How to count the amount of words said by someone pandas dataframe I have a dataframe like this am I'm trying to count the words said by a specific author. Author Text Date Jake hey hey my names Jake 1.04.1997 Mac hey my names Mac 1.02.2019 Sarah ...
How to count the amount of words said by someone pandas dataframe
I have a dataframe like this am I'm trying to count the words said by a specific author. Author Text Date Jake hey hey my names Jake 1.04.1997 Mac hey my names Mac 1.02.2019 Sarah heymy names Sarah 5.07.2001 I've been trying to get...
[ "If df is your original dataframe\nnewDF = pd.DataFrame(columns=['Author','Count'])\nnewDF['Author'] = df['Author']\nnewDF['Count'] = df['Text'].str.count(\"hey\")\nnewDF.drop(newDF[newDF['Count'] == 0].index, inplace=True)\n\n\n", "Use Series.str.count with aggregate sum:\ndf1 = df['Text'].str.count('hey').group...
[ 2, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074247463_dataframe_pandas_python.txt
Q: Is there a more precise alternative to time.sleep() in Python? So I was looking for a more precise alternative to time.sleep() in Python but couldn't find any good options. Does anyone know if there is a more accurate alternative with at least millisecond precision? Something like this: precise_delay(3.141) # Pau...
Is there a more precise alternative to time.sleep() in Python?
So I was looking for a more precise alternative to time.sleep() in Python but couldn't find any good options. Does anyone know if there is a more accurate alternative with at least millisecond precision? Something like this: precise_delay(3.141) # Pauses the program for exactly 3.141 seconds And no, I tried, and time...
[ "time.sleep switches to another thread while it sleeps. That other thread will typically run for its entire time slice (10-15ms, but depends on the OS).\nWhat you want is a spin wait that doesn't give up the thread, but uses more CPU. time.perf_counter_ns has the best precision counter:\nfrom time import perf_cou...
[ 1, 0 ]
[]
[]
[ "python", "sleep" ]
stackoverflow_0074238391_python_sleep.txt
Q: RAR files not downloading correctly using requests module Recently, I was creating an installer for my project. It involves downloading a RAR file from my server, unRAR-ing it and putting those folders into the correct locations. Once it's downloaded, the program is supposed to unRAR it, but instead it gives me an...
RAR files not downloading correctly using requests module
Recently, I was creating an installer for my project. It involves downloading a RAR file from my server, unRAR-ing it and putting those folders into the correct locations. Once it's downloaded, the program is supposed to unRAR it, but instead it gives me an error in the console: Corrupt header of file. I should note th...
[ "You keep re-opening the file for every chunk.\nNot only does this leak file descriptors, it also means you keep overwriting the file.\nTry this instead:\nKALI = \"URL CENSORED\"\nkali_res = requests.get(KALI, stream=True)\nwith open(file_path, \"wb\") as outfile:\n for chunk in kali_res.iter_content(chunk_size=...
[ 2 ]
[]
[]
[ "python", "python_requests" ]
stackoverflow_0074247586_python_python_requests.txt
Q: Additional queryset in DetailView (using self) I am creating application to manage home budget. I've got a few models - Date, Expense, Category, Income. It looks like this class Date(models.Model): name = models.CharField(max_length = 15) user = models.ForeignKey(User, on_delete=models.CASCADE, related...
Additional queryset in DetailView (using self)
I am creating application to manage home budget. I've got a few models - Date, Expense, Category, Income. It looks like this class Date(models.Model): name = models.CharField(max_length = 15) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='date') class Category(models.Model): nam...
[ "Okey, I found a solution.\nclass DateDetailView(DetailView):\n model = Date\n template_name = 'expense/date_detail.html'\n context_object_name = 'date'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['expense'] = Expense.objects.filter(da...
[ 1 ]
[]
[]
[ "detailview", "django", "filter", "python", "self" ]
stackoverflow_0074247679_detailview_django_filter_python_self.txt
Q: pylucene - ModuleNotFoundError: No module named 'org' # Common imports: import sys from os import path, listdir from org.apache.lucene.document import Document, Field, StringField, TextField from org.apache.lucene.util import Version from org.apache.lucene.store import RAMDirectory from datetime import datetime ...
pylucene - ModuleNotFoundError: No module named 'org'
# Common imports: import sys from os import path, listdir from org.apache.lucene.document import Document, Field, StringField, TextField from org.apache.lucene.util import Version from org.apache.lucene.store import RAMDirectory from datetime import datetime # Indexer imports: from org.apache.lucene.analysis.miscella...
[ "Python doesn't use that kind of imports.\nJust import lucene.\nIf this doesn't fix your problem, sorry!\n", "You can use from lucene import whatever.\nSee the Features documentation, where it states:\n\n\"The PyLucene API exposes all Java Lucene classes in a flat namespace in the PyLucene module.\"\n\nSo, in Jav...
[ 1, 1 ]
[]
[]
[ "lucene", "pylucene", "python" ]
stackoverflow_0074247605_lucene_pylucene_python.txt