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: Can setup.py / pip require a certain version of another package IF that package is already installed? I have two python packages (locust-swarm and locust-plugins). Neither has a strict requirement to the other, but they can work together, and my users install them separately. Sometimes there is a breaking change i...
Can setup.py / pip require a certain version of another package IF that package is already installed?
I have two python packages (locust-swarm and locust-plugins). Neither has a strict requirement to the other, but they can work together, and my users install them separately. Sometimes there is a breaking change in one or the other, and I want to make sure nobody installs incompatible versions (by updating package A bu...
[ "I think you can do this in your A/setup.py file (and the same in your B/setup.py file, just change package_B_name to package_A_name:\nimport importlib.util\nspec = importlib.util.find_spec(f'{package_B_name}')\nif spec is not None:\n requirements_list.append(f'{package_B_name}>={package_B_version}')\n\nNote tha...
[ 0, 0 ]
[ "I don't know if I understand the question correctly but you can specify the minimum required version in the install_requires array in the setup function like so.\ninstall_requires=['locust-swarm >= 1.2', 'locust-plugins >= 1.1']\n\nI hope this answers your question, if it doesn't, let me know, and I will look into...
[ -1 ]
[ "pip", "python", "python_packaging", "setup.py" ]
stackoverflow_0074041392_pip_python_python_packaging_setup.py.txt
Q: Separating .txt file with Python I have to separate .txt file into small pieces, based on the matched value. For example, I have .txt file looks like: Names Age Country Mark 19 USA John 19 UK Elon 20 CAN Dominic 21 USA Andreas 21 UK I have to extract all rows with the same value “Age” and to copy them to other fi...
Separating .txt file with Python
I have to separate .txt file into small pieces, based on the matched value. For example, I have .txt file looks like: Names Age Country Mark 19 USA John 19 UK Elon 20 CAN Dominic 21 USA Andreas 21 UK I have to extract all rows with the same value “Age” and to copy them to other file or perfom some other action.. How i...
[ "Here is a possible solution:\nwith open('yourfile.txt') as infile:\n header = next(infile)\n ages = {}\n\n for line in infile:\n name, age, country = line.rsplit(' ', 2)\n if age not in ages:\n ages[age] = []\n ages[age].append([name, age, country])\n\n for age in ages:\...
[ 0 ]
[ "If you have them all in a list you can use something like this...\nalltext = [\"Names Age Country\", \"Mark 21 USA\", \"John 21 UK\",\"Elon 20 CAN\",\"Dominic 21 USA\", \"Andreas 21 UK\"]\n\nCanada = [alltext[0]] #Creates a list with your column header\nNotCanada = [alltext[0]] #Creates a list with your column hea...
[ -1 ]
[ "file", "python", "txt" ]
stackoverflow_0074635111_file_python_txt.txt
Q: Why is Beautifulsoup's selector showing error while the Scrapy's response.css working absolutely fine? I am trying to scrape this div tag which has an id attribute equal to today's date. I created a Beautifulsoup object and used the select method but it's showing this error My code res = requests.get('https://spor...
Why is Beautifulsoup's selector showing error while the Scrapy's response.css working absolutely fine?
I am trying to scrape this div tag which has an id attribute equal to today's date. I created a Beautifulsoup object and used the select method but it's showing this error My code res = requests.get('https://sports.ndtv.com/fifa-world-cup-2022/schedules-fixtures') soup = BeautifulSoup(res.text,'html.parser') date_today...
[ "bs4 [or rather soupsieve] doesn't like it when id selectors [#id] have hyphens (-) in them for some reason, but you can get around it by using attribute selector instead\ncont = soup.select(f'div[id=\"{d1}\"]')\n\nshould work - give it a try.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "css", "html", "python", "scrapy" ]
stackoverflow_0074620048_beautifulsoup_css_html_python_scrapy.txt
Q: Python inspect.stack is slow I was just profiling my Python program to see why it seemed to be rather slow. I discovered that the majority of its running time was spent in the inspect.stack() method (for outputting debug messages with modules and line numbers), at 0.005 seconds per call. This seems rather high; is...
Python inspect.stack is slow
I was just profiling my Python program to see why it seemed to be rather slow. I discovered that the majority of its running time was spent in the inspect.stack() method (for outputting debug messages with modules and line numbers), at 0.005 seconds per call. This seems rather high; is inspect.stack really this slow, o...
[ "inspect.stack() does two things:\n\ncollect the stack by asking the interpreter for the stack frame from the caller (sys._getframe(1)) then following all the .f_back references. This is cheap.\nper frame, collect the filename, linenumber, and source file context (the source file line plus some extra lines around i...
[ 21, 20, 0 ]
[]
[]
[ "inspect", "introspection", "python" ]
stackoverflow_0017407119_inspect_introspection_python.txt
Q: Selecting specific column tags to display from a set of rows using BeautifulSoup and Flask I'm trying to create a table that retrieves that most recent n injuries from the CBS NFL injuries page, just to add an aesthetic to a project. I have no problem scraping the data and separating it into rows or individual col...
Selecting specific column tags to display from a set of rows using BeautifulSoup and Flask
I'm trying to create a table that retrieves that most recent n injuries from the CBS NFL injuries page, just to add an aesthetic to a project. I have no problem scraping the data and separating it into rows or individual columns, but I've spent 2 full days trying to find answers and fix this, but I need to move onward....
[ "The issue with the doubling of the name was a dynamic change with the webpage size providing a shortened name with small size and longer name when larger, but they were under the same tag in ('td')1. By specifically calling the 'span' with class_='CellPlayerName--long', I was able to only extract the longer versio...
[ 0 ]
[]
[]
[ "beautifulsoup", "flask", "html", "python" ]
stackoverflow_0074484725_beautifulsoup_flask_html_python.txt
Q: How to remove the special character '^' in a python string without removing whitespace with it i've been wondering how to remove the special character '^' in a python string , it seems like it doesn't count like the other special characters. I actually was trying to remove some special characters in a dataframe by...
How to remove the special character '^' in a python string without removing whitespace with it
i've been wondering how to remove the special character '^' in a python string , it seems like it doesn't count like the other special characters. I actually was trying to remove some special characters in a dataframe by using this code below : def remove_special_characters(text, remove_digits=True): text=re.sub(r'...
[ "You can escape special characters:\nr'[\\^a-zA-z0-9\\s]+'\n\nBut the use case you're tackling is already addressed\nby translate(), without any need to resort to power tools\nlike regexes.\nhttps://docs.python.org/3/library/stdtypes.html#str.maketrans\n\nYou're incurring the cost of parsing / compiling the regex N...
[ 1 ]
[]
[]
[ "dataframe", "python", "string", "symbols" ]
stackoverflow_0074635432_dataframe_python_string_symbols.txt
Q: How to "stretch" out a bounding box given from minAreaRect function in openCV? I wish to run a line detector between two known points on an image but firstly I need to widen the area around the line so my line detector has more area to work with. The main issue it stretch the area around line with respect to the l...
How to "stretch" out a bounding box given from minAreaRect function in openCV?
I wish to run a line detector between two known points on an image but firstly I need to widen the area around the line so my line detector has more area to work with. The main issue it stretch the area around line with respect to the line slope. For instance: white line generated form two points with black bounding bo...
[ "A minAreaRect() gives you a center point, the size of the rectangle, and an angle.\nYou could just add to the shorter side length of the rectangle. Then you have a description of a \"wider rectangle\". You can then do with it whatever you want, such as call boxPoints() on it.\npadding = 42\n\nrect = cv.minAreaRect...
[ 3, 2 ]
[]
[]
[ "geometry", "image", "image_processing", "opencv", "python" ]
stackoverflow_0074633504_geometry_image_image_processing_opencv_python.txt
Q: Print a specific key from json file I'm trying to print a specific key from a dictionary(key:value) like this in a JSON file(below). I tried this code but prints everything: reda.json: [{"alice": 24, "bob": 27}, {"carl": 33}, {"carl": 55}, {"user": "user2"}, {"user": "user2"}, {"user": "123"},] Python: import jso...
Print a specific key from json file
I'm trying to print a specific key from a dictionary(key:value) like this in a JSON file(below). I tried this code but prints everything: reda.json: [{"alice": 24, "bob": 27}, {"carl": 33}, {"carl": 55}, {"user": "user2"}, {"user": "user2"}, {"user": "123"},] Python: import json filename = 'reda.json' json_data = jso...
[ "You could turn the list of dicts into a single dict.\nDownside is dups would be squished, so e.g. \"carl\" would map to just a single number.\nAs it stands, you probably want to see all of carl's values,\nusing something like this:\njson_data = json.load(open('reda.json'))\nfor d in json_data:\n print(d)\n\nk =...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074635498_list_python.txt
Q: Speeding up python computation time (solving differential equations) so some time ago i was assigned a project to find the position relative to time of a simulated pendulum on a free moving cart, i managed to calculate some equations to describe this motion and i tried to simulate it in python to make sure it is c...
Speeding up python computation time (solving differential equations)
so some time ago i was assigned a project to find the position relative to time of a simulated pendulum on a free moving cart, i managed to calculate some equations to describe this motion and i tried to simulate it in python to make sure it is correct. The program i made can run and plot its position correctly, but it...
[ "You can try to calculate values only once and then reuse them.\nfrom scipy.integrate import quad\nfrom scipy.optimize import fsolve\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# These values can be changed\nmasstot = 5\nmass = 2\ng = 9.8\nl = 9.8\nwan = (g/l)**(1/2)\nvuk = 0.1\noug = 1\n\ndef afad(lah)...
[ 2, 2 ]
[]
[]
[ "differential_equations", "numpy", "python", "scipy", "simulation" ]
stackoverflow_0074634028_differential_equations_numpy_python_scipy_simulation.txt
Q: Python pytube calculate download speed and elapsed time So i have a download callback function def downloadCallback(stream, chunk, file_handle, bytes_remaining): fileSize = stream.filesize bytes_downloaded = fileSize - bytes_remaining percentage = round((bytes_downloaded / fileSize) * 100, 2) print...
Python pytube calculate download speed and elapsed time
So i have a download callback function def downloadCallback(stream, chunk, file_handle, bytes_remaining): fileSize = stream.filesize bytes_downloaded = fileSize - bytes_remaining percentage = round((bytes_downloaded / fileSize) * 100, 2) print(f"{percentage}% Downloaded", end="\r") So far I have been a...
[ "This method is very simple and will not give exact values, but it is quite close.\nYou must first take the time value before starting the download.\nThen in the function \"downloadCallback\" you return to take the value of time. Subtracting this value from the value taken before starting the download, we will have...
[ 0 ]
[]
[]
[ "python", "pytube" ]
stackoverflow_0058256277_python_pytube.txt
Q: Python behave fixture on feature level not loaded This is somewhat related to this question, but I have some further problems in this minimal example below. For a feature test I prepared a fixture which backs up a file which shall be modified during the test run (e.g. a line is appended). After the test run this f...
Python behave fixture on feature level not loaded
This is somewhat related to this question, but I have some further problems in this minimal example below. For a feature test I prepared a fixture which backs up a file which shall be modified during the test run (e.g. a line is appended). After the test run this fixture restores the original file. Project Files: └───f...
[ "I also had trouble setting up a fixture because the docs aren't super clear that you have to explicitly enable them. It isn't enough to have the @fixture decoration in features/environment.py. You also have to call use_fixture(). For example, inside before_tag(), like this:\ndef before_tag(context, tag):\n i...
[ 1, 0 ]
[]
[]
[ "python", "python_behave" ]
stackoverflow_0071777018_python_python_behave.txt
Q: Multiple waitKey calls not working well with cv2 I discovered that more than one waitKey calls in an opencv program make it lag out, and all the calls do not get registered properly. You sometimes have to hold some keys for over 4 seconds in order for their code to execute. Said faulty calls work like this: if cv2...
Multiple waitKey calls not working well with cv2
I discovered that more than one waitKey calls in an opencv program make it lag out, and all the calls do not get registered properly. You sometimes have to hold some keys for over 4 seconds in order for their code to execute. Said faulty calls work like this: if cv2.waitKey(1) == 100: show_crop = not show_crop if ...
[ "I ran into this issue in my program, and decided to answer this question Q&A style!\nI came up with a very simple workaround.\nFirst, use a single waitKey call to get the key required as so-\ninp = waitKey(1)\nNow, create a dictionary with its keys as the ordinals of the buttons you're pressing, and values as the ...
[ 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074635429_opencv_python.txt
Q: How do I fill in the rest of an image with a certain color after rotating an ROI with scikit-image? I have the following image: I am attempting to use handwritten OCR to capture this number, and for some images, I need to manually rotate the image. The code I am using to rotate this image is the following: When ...
How do I fill in the rest of an image with a certain color after rotating an ROI with scikit-image?
I have the following image: I am attempting to use handwritten OCR to capture this number, and for some images, I need to manually rotate the image. The code I am using to rotate this image is the following: When I execute this code, the following image is the result: I want the white background surrounding the 1 to...
[ "As already pointed out by fmw42 in the comments, the API you are using has optional arguments to deal with this.\nPlease peruse the docs for the API you use: skimage.transform.rotate\nThe docs offer a mode, which says how to fill in those pixels that don't come from the source image.\nThe modes replicate/edge and ...
[ 1 ]
[]
[]
[ "image_processing", "opencv", "python", "scikit_image" ]
stackoverflow_0074617780_image_processing_opencv_python_scikit_image.txt
Q: 'RecursionError' in a for loop I have tried to implement a flatten function to even flatten strings but got an error for Recursion. Could someone help resolve this puzzle? def flatten(items): for x in items: if isinstance(x, Iterable): yield from flatten(x) else: yield x items = [2...
'RecursionError' in a for loop
I have tried to implement a flatten function to even flatten strings but got an error for Recursion. Could someone help resolve this puzzle? def flatten(items): for x in items: if isinstance(x, Iterable): yield from flatten(x) else: yield x items = [2, [3, 4, [5, 6], 7], 8, 'abc'] for ...
[ "The problem as jasonharper pointed is that 'a' is an iterable element which contains 'a' and so on. You can however, rewrite the code with another if before the yield from flatten(x) something like\nfrom collections.abc import Iterable\ndef flatten(items):\n for x in items:\n if isinstance(x, Iterable):\n ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074633320_python.txt
Q: Replace the whole sting in dataframe if it matches the pattern I want to replace the value in df if this value contains a partial string. My solution: stimuli_dict = {'121': 'mp4', '212': 'mp3'} stimuli_dict = {r"^{}".format(k): v for k, v in stimuli_dict.items()} df['stimulus'] = df['stimulus'].replace(stimuli_d...
Replace the whole sting in dataframe if it matches the pattern
I want to replace the value in df if this value contains a partial string. My solution: stimuli_dict = {'121': 'mp4', '212': 'mp3'} stimuli_dict = {r"^{}".format(k): v for k, v in stimuli_dict.items()} df['stimulus'] = df['stimulus'].replace(stimuli_dict, regex=True) But it replaces only the partial string in a colum...
[ "if you can add .* into your keys it would solve your problem. It is about regular expression. You need to tell that we are looking for something starts with 121 and rest is not important.\nstimuli_dict = {'121.*': 'mp4', '212.*': 'mp3'}\n\n\".\" means any character, \"*\" means previous character between zero and ...
[ 2 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074635367_dataframe_python.txt
Q: MQTT payload parsing in Python I am using Paho library to receive MQTT data. I saved the data in a file. The data in the file reads: EP]�gr:G�2D��?G��D0uG�:G`�D�龹�:G�9D����R��A[[B���A�@ZBʟ�A��ZB"j�AʆYBIC�B�A��A���BM���ffNk>>>] In binary format, it converts to: b'<<<[\x16\x00\x00\x00\x00\xb8PG\x00\x90\xdeE-&4\x90\...
MQTT payload parsing in Python
I am using Paho library to receive MQTT data. I saved the data in a file. The data in the file reads: EP]�gr:G�2D��?G��D0uG�:G`�D�龹�:G�9D����R��A[[B���A�@ZBʟ�A��ZB"j�AʆYBIC�B�A��A���BM���ffNk>>>] In binary format, it converts to: b'<<<[\x16\x00\x00\x00\x00\xb8PG\x00\x90\xdeE-&4\x90\x99\x03\x00\x00\x00\x0fQG\x000\xf0E\...
[ "message.payload.decode() Is what your looking for\n" ]
[ 0 ]
[]
[]
[ "binary", "mqtt", "paho", "parsing", "python" ]
stackoverflow_0066345180_binary_mqtt_paho_parsing_python.txt
Q: python calling empty list invalid syntax I am trying to create an empty list and for some reason it is telling me it's invalid syntax? it also flags the next line with the same error, saying that while count<amount: is invalid. am i wrong for thinking this doesnt make sense? using vsc. thanks in advance. my code l...
python calling empty list invalid syntax
I am trying to create an empty list and for some reason it is telling me it's invalid syntax? it also flags the next line with the same error, saying that while count<amount: is invalid. am i wrong for thinking this doesnt make sense? using vsc. thanks in advance. my code looks like this. list=[] count=0 while count < ...
[ "amount is not defined. Define it with a number like 5 and try then.\nYou also need to make sure the variable list is called something else, it is a python-reserved word.\nLastly, make sure the input function has parenthesis () around it. e.x. input(\"enter number: \")\n", "In python the indent is 4 spaces.\nYou ...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074635614_python.txt
Q: create a program that computes the average of a collection of values entered by the user **2. In this exercise you will create a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. Your prog...
create a program that computes the average of a collection of values entered by the user
**2. In this exercise you will create a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. Your program should display an appropriate error message if the first value entered by the user is 0. H...
[ "Ok, you want a program that can calculate the average of some numbers (in any length), so I have some tips for you:\n\nyou have a while loop to repeat something (there, getting number), so get user input only once (in while loop)\nyou need a list, to add all user inputs to it... so create a list before wile loop (...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074635199_python.txt
Q: Pairing bluetooth devices with Passkey/Password in python - RFCOMM (Linux) I am working on a Python script to search for bluetooth devices and connect them using RFCOMM. This devices has Passkey/Password. I am using PyBlueZ and, as far as I know, this library cannot handle Passkey/Password connections (Python PyBl...
Pairing bluetooth devices with Passkey/Password in python - RFCOMM (Linux)
I am working on a Python script to search for bluetooth devices and connect them using RFCOMM. This devices has Passkey/Password. I am using PyBlueZ and, as far as I know, this library cannot handle Passkey/Password connections (Python PyBluez connecting to passkey protected device). I am able to discover the devices a...
[ "Finally I am able to connect to a device using PyBlueZ. I hope this answer will help others in the future. I tried the following:\nFirst, import the modules and discover the devices.\nimport bluetooth, subprocess\nnearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True,\n ...
[ 16, 0 ]
[]
[]
[ "bluetooth", "linux", "pybluez", "python" ]
stackoverflow_0037465157_bluetooth_linux_pybluez_python.txt
Q: Load JSON data into postgres table using airflow I have an Airflow DAG that runs a spark file (reads two parquet files, performs transformations on them, and loads the data into a single JSON file). Now the data from this JSON file needs to be pushed into a Postgres table. At first, I was having trouble reading th...
Load JSON data into postgres table using airflow
I have an Airflow DAG that runs a spark file (reads two parquet files, performs transformations on them, and loads the data into a single JSON file). Now the data from this JSON file needs to be pushed into a Postgres table. At first, I was having trouble reading the JSON, but then I found a way to read the JSON as a w...
[ "The problem statement provided has multiple issues. The statement would benefit from the addition of,\n\nan example of what the json file or doc variable looks like\nthe table definition for the table_name table\ncode is missing the definition of entry_data\n\nThe following solutions applies assumptions due to the...
[ 1 ]
[]
[]
[ "airflow", "json", "postgresql", "python" ]
stackoverflow_0074633594_airflow_json_postgresql_python.txt
Q: how to get a json object via its position in python I have an array of json objects and I want to obtain a parameter of the last json object, but when I do it with the code that I will leave below, I get the last character of the string from the end_date parameter of all objects.How can I always get the end_date o...
how to get a json object via its position in python
I have an array of json objects and I want to obtain a parameter of the last json object, but when I do it with the code that I will leave below, I get the last character of the string from the end_date parameter of all objects.How can I always get the end_date of the last json object? I hope you can help me the array ...
[ "Simply you can use the following to return \"end_date\" of last json object:\njson =[{'id':1,'name':'name1','init_date':'date','end_date':'date'}, \n{'id':2,'name':'name2','init_date':'date','end_date':'date'}, \n{'id':3,'name':'name3','init_date':'date','end_date':'date'}, \n{'id':4,'name':'name4','init_date':'da...
[ 0 ]
[]
[]
[ "arrays", "json", "python" ]
stackoverflow_0074635724_arrays_json_python.txt
Q: Finding root of a function with two outputs specified in return statement I am currently writing a code in Python where the objective is to find the root of the output of a function with respect to input variable x. The code looks like this: def Compound_Correlation_Function(x): # Here comes a long pa...
Finding root of a function with two outputs specified in return statement
I am currently writing a code in Python where the objective is to find the root of the output of a function with respect to input variable x. The code looks like this: def Compound_Correlation_Function(x): # Here comes a long part of the code... Equity_Solve = Tranches.loc[0, 'Par_Spread_bps']...
[ "I think the problem is that your function returns a tuple of numbers, but root is expecting a single number.\nAssuming you want to solve each equation separately, then you could include an argument in Compound_Correlation_Function to switch between the functions:\ndef Compound_Correlation_Function(x, return_equity...
[ 0, 0 ]
[]
[]
[ "python", "scipy_optimize" ]
stackoverflow_0074635091_python_scipy_optimize.txt
Q: SLURM Array Job BASH scripting within python subprocess Update: I was able to get a variable assignment from SLURM_JOB_ID with this line. JOBID=`echo ${SLURM_JOB_ID}` However, I haven't yet gotten SLURM_ARRAY_JOB_ID to assign itself to JOBID. Due to needing to support existing HPC workflows. I have a need to pass...
SLURM Array Job BASH scripting within python subprocess
Update: I was able to get a variable assignment from SLURM_JOB_ID with this line. JOBID=`echo ${SLURM_JOB_ID}` However, I haven't yet gotten SLURM_ARRAY_JOB_ID to assign itself to JOBID. Due to needing to support existing HPC workflows. I have a need to pass a bash script within a python subprocess. It was working gre...
[ "Following up on this. I sovled it by passing SBATCH directives as args to the sbatch command\n sbatch_args = \"\"\"--job-name=%(name)s --time=%(walltime)s --partition=defq --cpus-per-task=%(processors)s --mem=%(memory)s\"\"\" % (\n {\"walltime\": walltime\n ,\"processors\":...
[ 0 ]
[]
[]
[ "hpc", "python", "slurm", "subprocess", "ubuntu" ]
stackoverflow_0074323372_hpc_python_slurm_subprocess_ubuntu.txt
Q: Negative lookbehind + Non capturing group (?<!")https:\/\/t.me\/(c)?\/?([\+a-zA-Z0-9]+)\/?([0-9]*)? I want to find all telegram links without quotation marks (") but I don't want the leading negative lookbehind to be a group, how can I do this? I tried the following but it didn't work. This code works but i want t...
Negative lookbehind + Non capturing group
(?<!")https:\/\/t.me\/(c)?\/?([\+a-zA-Z0-9]+)\/?([0-9]*)? I want to find all telegram links without quotation marks (") but I don't want the leading negative lookbehind to be a group, how can I do this? I tried the following but it didn't work. This code works but i want the initial negative lookbehind not to create gr...
[ "This code:\n\n\nconst regex = /(?<!\")https:\\/\\/t.me\\/(c)?\\/?([\\+a-zA-Z0-9]+)\\/?([0-9]*)?/\nconst text = 'https://t.me/+AjFb2c8u85UfYrY0'\nconst [fullMatch, ...groups] = text.match(regex);\nconsole.log(groups);\n\n\n\nReturns [undefined, \"+AjFb2c8u85UfYrY0\", undefined]\nSo you might think the first undefin...
[ 0 ]
[]
[]
[ "hyperlink", "python", "regex", "regex_group", "telegram" ]
stackoverflow_0074634950_hyperlink_python_regex_regex_group_telegram.txt
Q: How python jira lib to change issue's resolution I try to update an issue's resolution through python jira lib, but get below error. >>> jp=JiraProject('VCART', 'https://jira.microhard.com') >>> _issue=jp.issue('VCART-4046') >>> _issue.update({'Resolution': {'name': 'Done'}}) Traceback (most recent call last): ...
How python jira lib to change issue's resolution
I try to update an issue's resolution through python jira lib, but get below error. >>> jp=JiraProject('VCART', 'https://jira.microhard.com') >>> _issue=jp.issue('VCART-4046') >>> _issue.update({'Resolution': {'name': 'Done'}}) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/loc...
[ "In the UI there is the long-standing Atlassian-suggested approach of adding a global self-transition to all statuses in a workflow, withe a Resolution screen. Then bulk transition the issues back to the same status. More info at\nhttps://confluence.atlassian.com/cloudkb/best-practices-on-using-the-resolution-field...
[ 0 ]
[]
[]
[ "jira", "python", "python_jira" ]
stackoverflow_0074629832_jira_python_python_jira.txt
Q: Change date format of these string using Python I have a string from a pdf that I want to transform it to the date format that I want to work with later, the string is 05Dec22 how can I change it to 12/05/2022? import datetime date1 = '05Dec22' date1 = datetime.datetime.strptime(date1, '%d%m%Y').strftime('%m/%d/%...
Change date format of these string using Python
I have a string from a pdf that I want to transform it to the date format that I want to work with later, the string is 05Dec22 how can I change it to 12/05/2022? import datetime date1 = '05Dec22' date1 = datetime.datetime.strptime(date1, '%d%m%Y').strftime('%m/%d/%y') date1 = str(date1) This is what i tried so far
[ "If you execute the code you'll get the following error,\nValueError: time data '05Dec22' does not match format '%d%m%Y'\n\nthis is because your time string is not in the specified format given ('%d%m%Y'). You can search for tables on the internet which show the placeholders that represent a certain formatting, if ...
[ 0 ]
[]
[]
[ "datetime", "python", "string" ]
stackoverflow_0074635764_datetime_python_string.txt
Q: Why is this function not returning the list of values? By printing the array "total", I can see that the values are appending correctly. And yet when I print(linked_list_values(a)), it returns None. a = Node(5) b = Node(3) c = Node(9) total = [] def linked_list_values(head): print(total) if head == None: ...
Why is this function not returning the list of values?
By printing the array "total", I can see that the values are appending correctly. And yet when I print(linked_list_values(a)), it returns None. a = Node(5) b = Node(3) c = Node(9) total = [] def linked_list_values(head): print(total) if head == None: return None total.append(head.num) linked_list_values(he...
[ "The function returns None because you never have a return statement in it. It does mutate total, but it gets mutated in-place.\nTry printing the value of total after the function runs.\n>>> linked_list_values(a)\nNone\n>>> total\n[5, 3, 9] # Assuming a.next == b and b.next == c\n\n", "Your function isn't returni...
[ 2, 0 ]
[]
[]
[ "linked_list", "python" ]
stackoverflow_0074635810_linked_list_python.txt
Q: Counting drop on an image I have image of drops and I want to calculate the number of it. Here is the original image : And Here after threshold application : i tried a lot of fonction on OpenCV and it's never right. Do you have any ideas on how to do ? Thanks The best I got, was by using : (img_morph is my binai...
Counting drop on an image
I have image of drops and I want to calculate the number of it. Here is the original image : And Here after threshold application : i tried a lot of fonction on OpenCV and it's never right. Do you have any ideas on how to do ? Thanks The best I got, was by using : (img_morph is my binairized image) rbc_bw = label(img...
[ "Core idea: matchTemplate.\nApproach:\n\npick a template manually from the picture\n\nhistogram equalization for badly lit inputs (or always)\n\n\nmatchTemplate with suitable matching mode\n\nalso using copyMakeBorder to catch instances clipping the border\n\n\nthresholding and non-maximum suppression\n\nI'll skip ...
[ 2 ]
[]
[]
[ "detection", "opencv", "python" ]
stackoverflow_0074633013_detection_opencv_python.txt
Q: How Do For loop to make short my statement I think it would be a simple question but I really stuck on it! how can I use for loop to make my statement more complex and short? I need the output be the exactly same format this is a code courses_data = pd.read_csv('.........') selected_features = ['course_name','cou...
How Do For loop to make short my statement
I think it would be a simple question but I really stuck on it! how can I use for loop to make my statement more complex and short? I need the output be the exactly same format this is a code courses_data = pd.read_csv('.........') selected_features = ['course_name','course_link','university_name','course_type', ...
[ "Something along these lines should work:\ncombined_features = courses_data[selected_features[0]]\nfor feature in selected_features[1:]:\n combined_features += ' ' + courses_data[feature]\n\n", "Since you are dealing with a pandas dataframe you could just do\ndf2 = courses_data[selected_features].copy()\nprint(d...
[ 1, 1, 1 ]
[]
[]
[ "dataframe", "for_loop", "python" ]
stackoverflow_0074635839_dataframe_for_loop_python.txt
Q: Python lambda log format with multline output to cloudwatch I can override the default Lambda python log format like so: LOG_FORMAT = '[%(levelname)s] %(asctime)s.%(msecs)dZ [%(filename)s] [%(funcName)s] %(message)s' DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S' logging.basicConfig(format=LOG_FORMAT, level=logging.INFO, d...
Python lambda log format with multline output to cloudwatch
I can override the default Lambda python log format like so: LOG_FORMAT = '[%(levelname)s] %(asctime)s.%(msecs)dZ [%(filename)s] [%(funcName)s] %(message)s' DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S' logging.basicConfig(format=LOG_FORMAT, level=logging.INFO, datefmt=DATETIME_FORMAT, force=True) LOG = logging.getLogger() Bu...
[ "Figured out a workaround by editing the existing formatter:\nLOG = logging.getLogger()\nLOG.setLevel(logging.INFO)\nlog_handler = LOG.handlers[0]\nlog_handler.setFormatter(logging.Formatter('[%(levelname)s] %(asctime)s.%(msecs)dZ [%(filename)s] [%(funcName)s] %(message)s\\n'))\n\n" ]
[ 0 ]
[]
[]
[ "aws_lambda", "python" ]
stackoverflow_0074633534_aws_lambda_python.txt
Q: Element wise between a 2-D numpy array and a list I'm trying to apply a function def lead(x,n): if n>0: x = np.roll(x,-n) x[-n:]=1 return x to each element of Qxx, a 2-D numpy array (121,121), BUT WITH ROLLING the "n" argument from a list [0,1,2,3,4,....121] for example and in a element wi...
Element wise between a 2-D numpy array and a list
I'm trying to apply a function def lead(x,n): if n>0: x = np.roll(x,-n) x[-n:]=1 return x to each element of Qxx, a 2-D numpy array (121,121), BUT WITH ROLLING the "n" argument from a list [0,1,2,3,4,....121] for example and in a element wise way. the following code is working but SLOW ! xx = [...
[ "This seems to be much faster:\nlist(map(lambda x: lead(Qxx[x], x), range(121)))\n\nPerformance:\nThe OP's solution:\n%%timeit\n\n[[lead(qx,n) for n in range(len(qx))] for qx in Qxx]\n\n178 ms ± 3.32 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nMy solution:\n%%timeit\n\nlist(map(lambda x: lead(Qxx[x], x...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074635544_numpy_python.txt
Q: How do you segment the darker spots from the blurry gray corners? I'm trying to segment the dark grayish spots from the blurry gray areas on the corner, I did binary thresholding and morphological operations and it works great from the blobs in the middle, but the corners I'm having a bit of trouble. black and whi...
How do you segment the darker spots from the blurry gray corners?
I'm trying to segment the dark grayish spots from the blurry gray areas on the corner, I did binary thresholding and morphological operations and it works great from the blobs in the middle, but the corners I'm having a bit of trouble. black and white blob image # Binary Thresholding ret,threshImg = cv2.threshold(denoi...
[ "You can do division normalization in Python/OpenCV to mitigate some of that issue. You basically blur the image and then divide the image by the blurred version.\nInput:\n\nimport cv2\nimport numpy as np\n\n# read the image\nimg = cv2.imread('dark_spots.jpg')\n\n# convert to gray\ngray = cv2.cvtColor(img,cv2.COLOR...
[ 2 ]
[]
[]
[ "image_processing", "image_segmentation", "opencv", "python" ]
stackoverflow_0074635041_image_processing_image_segmentation_opencv_python.txt
Q: Python: How to get the name of an Enum? A coworker who is on vacation has code that is similar to, for example: from enum import Enum class MyEnum(Enum): A = 1 B = 2 def lookup(enum_type: Enum, value: str) -> Any: try: return enum_type[value] except ValueError: # PROBLEM IS HERE ...
Python: How to get the name of an Enum?
A coworker who is on vacation has code that is similar to, for example: from enum import Enum class MyEnum(Enum): A = 1 B = 2 def lookup(enum_type: Enum, value: str) -> Any: try: return enum_type[value] except ValueError: # PROBLEM IS HERE enum_name = ??? raise Configur...
[ "The name of the enum would be enum_type.__name__.\nBe aware that the square bracket look-up (i.e. enum_type[value]) is actually looking up by member name, not member value. Member value would be enum_type(value).\n" ]
[ 1 ]
[]
[]
[ "enums", "python", "python_3.x" ]
stackoverflow_0074635885_enums_python_python_3.x.txt
Q: Question about getting global coordinates of lidar point cloud from relative in Webots I need to do custom mapping of surroundings with lidar using mobile robot in Webots. What I use for that: GPS for getting robot position. Compass for getting direction robot. Lidar for getting info about surroundings. Maybe so...
Question about getting global coordinates of lidar point cloud from relative in Webots
I need to do custom mapping of surroundings with lidar using mobile robot in Webots. What I use for that: GPS for getting robot position. Compass for getting direction robot. Lidar for getting info about surroundings. Maybe someone familiar with Webots and can show basic code example or explain the math behind it or ...
[ "After getting some useful info in StackExchange.\nBasic Example of solution on Python:\nfrom scipy.spatial.transform import Rotation as Rotation\n\nRobotPoint = gps.getValues()\nSTR = Rotation.from_quat(InertialUnit.getQuaternion())\nfor RelativeCloudPoint in lidar.getPointCloud():\n Point2 = STR.apply(RelativeCl...
[ 0 ]
[]
[]
[ "compass", "coordinate_transformation", "lidar", "python", "webots" ]
stackoverflow_0074619579_compass_coordinate_transformation_lidar_python_webots.txt
Q: How to keep VARCHAR in the DB (MYSQL), but ENUM in the sqlalchemy model I want to add a new Int column to my MYSQL DB, so that in the sqlalchemy ORM it will be converted to an ENUM. For example, let's say I have this enum: class employee_type(Enum): Full_time = 1 Part_time = 2 Student = 3 I want to ke...
How to keep VARCHAR in the DB (MYSQL), but ENUM in the sqlalchemy model
I want to add a new Int column to my MYSQL DB, so that in the sqlalchemy ORM it will be converted to an ENUM. For example, let's say I have this enum: class employee_type(Enum): Full_time = 1 Part_time = 2 Student = 3 I want to keep in the DB those params - 1,2,3..., but when developers will write code tha...
[ "Apparently the answer is super simple(!), there is nothing special we need to do - SQLAlchemy support it by itself.\nMeaning - you can set the specific column to be INT in the DB, but enum in the model, and when querying the DB SQLAlchemy will convert it by itself. same goes when inserting to the DB :)\nI used it ...
[ 0, 0 ]
[]
[]
[ "enums", "mysql", "orm", "python", "sqlalchemy" ]
stackoverflow_0049802164_enums_mysql_orm_python_sqlalchemy.txt
Q: HDF5 multidimmensional array storage I got this very simple pandas dataframe with a multidimmensional array: df_foo = pd.DataFrame({ 'Value': [[1, 2], [3, 4], [5, 6]] }) Here is what's happening when I try to store it in an hdf5 file : # Using HDFStore: h5 = HDFStore('foo.h5') h5.put('foo', df_foo, format='t...
HDF5 multidimmensional array storage
I got this very simple pandas dataframe with a multidimmensional array: df_foo = pd.DataFrame({ 'Value': [[1, 2], [3, 4], [5, 6]] }) Here is what's happening when I try to store it in an hdf5 file : # Using HDFStore: h5 = HDFStore('foo.h5') h5.put('foo', df_foo, format='table', data_columns=True) #TypeError: ...
[ "You can't store a multidimensional array in a pandas Series. So when you create your \"array\" in your example, you're actually creating a pandas column with object dtype, where each element is a python list.\nOne option for storing a MultiDimensional array as HDF5 is by using xarray, another pydata project which ...
[ 0 ]
[]
[]
[ "hdf5", "pandas", "python" ]
stackoverflow_0074635832_hdf5_pandas_python.txt
Q: File indexing issue in python for this function, i need to traverse through a file and count each line based on certain signifiers. If that certain signifier is present in the line, i need to add the string as a key to the dictionary and increment its value by one each time its present. I am not outright looking f...
File indexing issue in python
for this function, i need to traverse through a file and count each line based on certain signifiers. If that certain signifier is present in the line, i need to add the string as a key to the dictionary and increment its value by one each time its present. I am not outright looking for the answer, I am just lost as to...
[ "f_read = open(tweets_file_name, \"r\")\nf_write = open(tweets_file_name, \"w\")\n\nYou're opening the file for reading and then also opening it for writing, which destroys the existing contents.\n" ]
[ 0 ]
[]
[]
[ "dictionary", "file", "python", "traversal" ]
stackoverflow_0074635723_dictionary_file_python_traversal.txt
Q: If statement requires float, terminal returns error if datatype is string I am a beginner programmer, working on a project for an online course. I am trying to build a tip calculator. I want it to take input from the user for three values: Bill total, how many are splitting the bill, and the percent they would wis...
If statement requires float, terminal returns error if datatype is string
I am a beginner programmer, working on a project for an online course. I am trying to build a tip calculator. I want it to take input from the user for three values: Bill total, how many are splitting the bill, and the percent they would wish to tip. My conditional statement only has one if: if meal_price >= 0.01: exam...
[ "The user's input will be a string, so you need to check if the parse to the float was successful. You can do that with a try/except, and then loop back over asking for more input:\nprint(\"First, what was the total for the bill?\")\n\nmeal_price = None\nwhile meal_price == None:\n try:\n meal_price = flo...
[ 0, 0, 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074634781_if_statement_python.txt
Q: Visual Studio stalling python extension on m1 Macbook I tried to install and manually install the Microsoft python extension, both not working. I have installed python 3.9.7 on my m1 macbook. After I click "installing", then the following error message appears: And in the log: Also when I tried to install manual...
Visual Studio stalling python extension on m1 Macbook
I tried to install and manually install the Microsoft python extension, both not working. I have installed python 3.9.7 on my m1 macbook. After I click "installing", then the following error message appears: And in the log: Also when I tried to install manually via the vsix file: In the log it appears: What is goin...
[ "There are many possible causes for XHR errors. You can refer to this article, and I think the easiest way is to restart or reinstall vscode.\n" ]
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074630383_python_visual_studio_code.txt
Q: Plotly Dash / Python -- Interaction(s) between Dropdown, Graph and Rangeslider I've been getting into Python as a means to visualize data. I'm still very much of a novice. To practice I'm working with the gapminder dataset in Plotly Express in Jupyter Notebook. Been stuck on something I can't quite wrap my head ar...
Plotly Dash / Python -- Interaction(s) between Dropdown, Graph and Rangeslider
I've been getting into Python as a means to visualize data. I'm still very much of a novice. To practice I'm working with the gapminder dataset in Plotly Express in Jupyter Notebook. Been stuck on something I can't quite wrap my head around. I have this container for a graph: dcc.Graph(id='the_graph') I've managed to ...
[ "I think you should add conditions for Dropdown. Something as below:\n@app.callback(\n Output('the_graph', 'figure'),\n [Input('the_year', 'value'),\n Input('the_country', 'value')]\n)\n\ndef update_graph(sel_year, sel_country):\n dff = data[(data['year']>=sel_year[0]) & (data['year']<=sel_year[1])]\n ...
[ 0 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074627025_plotly_dash_python.txt
Q: Is there a faster way of evaluating every combination of booleans in an if statement in python? If I have 4 booleans e.g if ((a(x) == True) and (b(x) == True) and (c(x) == True) and (d(x) == True) then I want to do something different for each combination including when only 3 of them are true (including which one...
Is there a faster way of evaluating every combination of booleans in an if statement in python?
If I have 4 booleans e.g if ((a(x) == True) and (b(x) == True) and (c(x) == True) and (d(x) == True) then I want to do something different for each combination including when only 3 of them are true (including which ones), 2..., then only each 1... etc... Is there a quicker way than writing a bunch of elifs? Possibly u...
[ "You could build a lookup table using a dict:\nlookup = {(True, True, True, True): func_1,\n (True, True, True, False): func_2,\n (True, True, False, True): func_3,\n ... etc.\n }\nfunc = lookup[a(x), b(x), c(x), d(x)]\nfunc()\n\n", "You can count the number of True booleans usi...
[ 2, 0, 0, 0 ]
[]
[]
[ "boolean_expression", "if_statement", "python" ]
stackoverflow_0074635930_boolean_expression_if_statement_python.txt
Q: Section postgresql not found in the database.ini file I'm trying to create tables in my database (postgresql 9.6) and when I launch my python script to do so, it returns me an error of the following type: "Section postgresql not found in the $FILEDIR/database.ini file" It seems like the parser cannot read the sect...
Section postgresql not found in the database.ini file
I'm trying to create tables in my database (postgresql 9.6) and when I launch my python script to do so, it returns me an error of the following type: "Section postgresql not found in the $FILEDIR/database.ini file" It seems like the parser cannot read the section, but I don't understand why. This is my config method: ...
[ "I had the same issue aswell, it was cured by placing the whole file path into the kwarg in config:\ndef config(filename='/Users/gramb0t/Desktop/python-postgre/data/database.ini', section='postgresql'):\n", "#just remove the $FILEDIR. it worked for me.\n\nfrom configparser import ConfigParser\n\ndef config(filena...
[ 7, 3, 2, 0 ]
[]
[]
[ "configparser", "python", "python_2.7" ]
stackoverflow_0049406058_configparser_python_python_2.7.txt
Q: How to write one array value at a time (dataframe to csv)? This is working great, but I have thousands of rows to write to csv. It takes hours to finish and sometimes my connection will drop and prevent the query from finishing. import pandas as pd from yahooquery import Ticker symbols = ['AAPL','GOOG','MSFT'] ...
How to write one array value at a time (dataframe to csv)?
This is working great, but I have thousands of rows to write to csv. It takes hours to finish and sometimes my connection will drop and prevent the query from finishing. import pandas as pd from yahooquery import Ticker symbols = ['AAPL','GOOG','MSFT'] faang = Ticker(symbols) faang.summary_detail df = pd.DataFrame(f...
[ "Try the below looping through the list of tickers, appending the dataframes as you loop onto the CSV.\nimport pandas as pd\nfrom yahooquery import Ticker\n\n\nsymbols = [#All Of Your Symbols Here]\nfor tick in symbols:\n faang = Ticker(tick)\n faang.summary_detail\n df = pd.DataFrame(faang.summary_detail)...
[ 2 ]
[]
[]
[ "arrays", "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074635011_arrays_csv_dataframe_pandas_python.txt
Q: Add a "|" symbol while grouping a data frame by multiple columns with python pandas I am just starting learning pandas package and have been asked to group a data frame by multiple columns ('BRANCH_NO', 'CUSTOMER_NO') since the combination of them forms a unique value in the data frame while adding a "|" symbol be...
Add a "|" symbol while grouping a data frame by multiple columns with python pandas
I am just starting learning pandas package and have been asked to group a data frame by multiple columns ('BRANCH_NO', 'CUSTOMER_NO') since the combination of them forms a unique value in the data frame while adding a "|" symbol between the values in other columns that have the same combination of 'BRANCH_NO' and 'CUST...
[ "g = person_in_charge_raw.groupby(['BRANCH_NO', 'CUSTOMER_NO'])\ng.agg('|'.join).reset_index()\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "pipe", "python" ]
stackoverflow_0074636052_pandas_pipe_python.txt
Q: Scikit learn not importing in vscode from sklearn.metrics.pairwise import cosine_similarity I have tried "pip install scikit-learn" and "pip install sklearn" so many times. It is showing reportMissingImports error A: Do you have multiple python environments on your machine? Make sure you are using the one you h...
Scikit learn not importing in vscode
from sklearn.metrics.pairwise import cosine_similarity I have tried "pip install scikit-learn" and "pip install sklearn" so many times. It is showing reportMissingImports error
[ "Do you have multiple python environments on your machine? Make sure you are using the one you have sklearn installed on.\nYou can use the following code to check the interpreter you are using, and then use the obtained path to install the sklearn package for the current environment.\nimport sys\nprint(sys.executab...
[ 0 ]
[]
[]
[ "python", "scikit_learn", "visual_studio_code" ]
stackoverflow_0074627459_python_scikit_learn_visual_studio_code.txt
Q: await Faust Agent ask() never receive from yield generator Hi I am trying to integrate faust with fastapi endpoints following this example: toh995/fastapi-faust-example I am working with a simple DummyOrder model class DummyOrder(faust.Record,MyAvroModel,serializer='avro_order_codec'): order_id: str amount...
await Faust Agent ask() never receive from yield generator
Hi I am trying to integrate faust with fastapi endpoints following this example: toh995/fastapi-faust-example I am working with a simple DummyOrder model class DummyOrder(faust.Record,MyAvroModel,serializer='avro_order_codec'): order_id: str amount: int I have an faust agent that yields balance @app.agent(test...
[ "This is caused by faust not waiting for agent/table initialisation in client-only mode. Just replace FastAPI's app startup handler with something like that:\n@app.on_event(\"startup\")\nasync def startup():\n # set up the faust app\n faust_app = worker.set_faust_app_for_api()\n await faust_app.start_clien...
[ 0 ]
[]
[]
[ "apache_kafka_streams", "async_await", "fastapi", "faust", "python" ]
stackoverflow_0071879233_apache_kafka_streams_async_await_fastapi_faust_python.txt
Q: When loading data from a .txt file, why does one of my columns in a MySQL database format a date value properly and another column does not? I have a .txt file where the fields are terminated by pipes. The file is in a S3 bucket and I have written a script to load the data from the file to a MySQL database. I have...
When loading data from a .txt file, why does one of my columns in a MySQL database format a date value properly and another column does not?
I have a .txt file where the fields are terminated by pipes. The file is in a S3 bucket and I have written a script to load the data from the file to a MySQL database. I have just about everything working properly, but I have come across a problem that I am stuck on. The issue is in formatting date values. The strange ...
[ "I was able to solve it by creating an ALTER statement and first making that column TEXT then combining date_format and str_to_date like I did on S_DATE. Still not really sure why I had to do that for one column and not the other.\n" ]
[ 0 ]
[]
[]
[ "date_format", "load_data_infile", "mysql", "python", "str_to_date" ]
stackoverflow_0074634670_date_format_load_data_infile_mysql_python_str_to_date.txt
Q: I want to fetch data from a website and put in MySQL workbench, but it's not working First time programmer here, please don't be harsh on me. I want to fetch data from the URL's and put it inside MYSQL workbench database, it says that it's working, see image: enter image description here. But it's not doing so, wh...
I want to fetch data from a website and put in MySQL workbench, but it's not working
First time programmer here, please don't be harsh on me. I want to fetch data from the URL's and put it inside MYSQL workbench database, it says that it's working, see image: enter image description here. But it's not doing so, what is wrong in the script? # GET ALL WorldRecords from https://api.isuresults.eu/records i...
[ "You define this method, but you don't really run it.\nAdd another line at the last:\nget_isu_worldrecord_db(engine)\n\n" ]
[ 1 ]
[]
[]
[ "mysql_workbench", "python", "visual_studio_code" ]
stackoverflow_0074632136_mysql_workbench_python_visual_studio_code.txt
Q: how to remove duplicate entries from json file using python? How to remove duplicate entries from a JSON file using python? I have a JSON file that looks like this: appreciate some one can help to provide a solution for fixing it json_data = [ { "authType": "ldap", "password": "", "perm...
how to remove duplicate entries from json file using python?
How to remove duplicate entries from a JSON file using python? I have a JSON file that looks like this: appreciate some one can help to provide a solution for fixing it json_data = [ { "authType": "ldap", "password": "", "permissions": [ { "collections": [ ...
[ "Does the following solve your problem?\nnew_list=[]\nfor i in json_data:\n if not i in new_list:\n new_list.append(i)\nprint(new_list)\n\n", "Even though OP asked to do this in Python, this can readily be done in jq using function unique with a single update assignment:\n$ jq '.[].permissions[].collect...
[ 0, 0 ]
[]
[]
[ "json", "python", "python_3.x" ]
stackoverflow_0074635590_json_python_python_3.x.txt
Q: How to effectively use parallelization with Ray in Python? I'm trying to learn how to use the Ray API and comparing with my code for joblib. However, I don't know how to effectively use this (my machine has 16 CPU). Am I doing something incorrectly? If not, why is Ray so much slower? import ray from joblib impor...
How to effectively use parallelization with Ray in Python?
I'm trying to learn how to use the Ray API and comparing with my code for joblib. However, I don't know how to effectively use this (my machine has 16 CPU). Am I doing something incorrectly? If not, why is Ray so much slower? import ray from joblib import Parallel, delayed num_cpus = 16 @ray.remote(num_cpus=num_cpu...
[ "The Ray scheduler decides how many Ray tasks run concurrently based on their num_cpus value (along with other resource types for more advanced use cases). By default, this value is set to 1, meaning that you can run parallel tasks up to the total number of cores. By setting it to 16, you are telling Ray that each ...
[ 2 ]
[]
[]
[ "joblib", "parallel_processing", "python", "ray" ]
stackoverflow_0074635033_joblib_parallel_processing_python_ray.txt
Q: Python click: subcommand from partial func Say I have a function created not by def but by a partial() call (or even just by assignment). In the example below, how can I add bar as a click sub-command to the cli group? I can't use the decorator approach (as with foo). My failed approaches are shown below in-lin...
Python click: subcommand from partial func
Say I have a function created not by def but by a partial() call (or even just by assignment). In the example below, how can I add bar as a click sub-command to the cli group? I can't use the decorator approach (as with foo). My failed approaches are shown below in-line. import functools import click @click.group(...
[ "I think you're missing the fact that the @command decorator turns the foo function into a Command that uses the original foo as callback. The original function is still accessible as foo.callback but foo is a Command. Still, you can't use a partial object as callback because it lacks __name__, but you can work aro...
[ 1 ]
[]
[]
[ "python", "python_click" ]
stackoverflow_0074239499_python_python_click.txt
Q: No error in code but Login is not working for python selenium simple script from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login") driver.implicitly_wait(5) username ="//input[@placehol...
No error in code but Login is not working for python selenium simple script
from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login") driver.implicitly_wait(5) username ="//input[@placeholder='Username']" password ="//input[@placeholder='Password']" driver.find_elemen...
[ "Add the below code and try:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\n\noptions = Options()\noptions.add_experimental_option(\"detach\", True)\n\ndriver = webdriver.Chrome(service=Service(<chromedriver.exe path>), ...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074636120_python_selenium.txt
Q: Pandas creating a new table and convert it to wide format I have this data frame. Type Generation Grass 1 Grass 1 Fire 1 Fire 1 Grass 2 Grass 3 I am trying to create a new column where it adds the number of same types corresponding to its generation ...
Pandas creating a new table and convert it to wide format
I have this data frame. Type Generation Grass 1 Grass 1 Fire 1 Fire 1 Grass 2 Grass 3 I am trying to create a new column where it adds the number of same types corresponding to its generation number, and reshape the data into wide format. looking like; Ty...
[ "crosstab\npd.crosstab(df['Type'], df['Generation']).rename(columns=lambda x: f'Generation_{x}')\n\nresult:\nGeneration Generation_1 Generation_2 Generation_3\nType \nFire 2 0 0\nGrass 2 1 1\n\n\nor you can use add_prefix instead...
[ 0 ]
[]
[]
[ "pandas", "pivot", "python" ]
stackoverflow_0074636192_pandas_pivot_python.txt
Q: How to get reproducible weights initializaiton in Keras? I set both numpy and tensorflow random seeds as suggested Generate some data - this part is reproducible, gives same results always Create a simple network and make a prediction (without training, just with random weights) - prediction is different every ti...
How to get reproducible weights initializaiton in Keras?
I set both numpy and tensorflow random seeds as suggested Generate some data - this part is reproducible, gives same results always Create a simple network and make a prediction (without training, just with random weights) - prediction is different every time import numpy as np from tensorflow.keras.layers import De...
[ "I've been struggling a lot with this and turns out there are quite a few points that have to be set in order to achieve complete consistency for every case:\nFirst of all, make sure the data (and the order of the data) that you feed to your model is consistent. Then, for the model weights initialization:\n1)numpy ...
[ 2, 1, 0 ]
[]
[]
[ "keras", "python", "reproducible_research", "tensorflow" ]
stackoverflow_0065794491_keras_python_reproducible_research_tensorflow.txt
Q: How to add value into sub-list Looking for a way to add value 555 right after 6000 to make it and display it. mylist = [4, 11, [300, 400, [5000, 6000, 555], 500], 30, 40] Original list below. mylist = [4, 11, [300, 400, [5000, 6000], 500], 30, 40] A: Can you try adding append to corresponding index mylist[2][2]...
How to add value into sub-list
Looking for a way to add value 555 right after 6000 to make it and display it. mylist = [4, 11, [300, 400, [5000, 6000, 555], 500], 30, 40] Original list below. mylist = [4, 11, [300, 400, [5000, 6000], 500], 30, 40]
[ "Can you try adding append to corresponding index\nmylist[2][2].append(555)\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074636215_python.txt
Q: ValueError: not enough values to unpack (expected 2, got 1) in a for loop I am tryin to make a field structure but I am having problems while using the for loop with 3 entries in a .items(). dirs = df_vol_erp.groupby(['country', 'primary_volcano_type'])['volcano_name_x'].apply(list) #for pais, (tipos, nombres...
ValueError: not enough values to unpack (expected 2, got 1) in a for loop
I am tryin to make a field structure but I am having problems while using the for loop with 3 entries in a .items(). dirs = df_vol_erp.groupby(['country', 'primary_volcano_type'])['volcano_name_x'].apply(list) #for pais, (tipos, nombres) in dirs.items(): for pais, tipos, nombres in dirs.items(): path_pais...
[ "Assign two variables, then in the loop body you can split the second variable into two more variables.\nfor pais, value in dirs.items():\n tipos, nombres = value\n\n" ]
[ 0 ]
[]
[]
[ "for_loop", "items", "python", "valueerror" ]
stackoverflow_0074636264_for_loop_items_python_valueerror.txt
Q: calling child class method from parent class file in python parent.py: class A(object): def methodA(self): print("in methodA") child.py: from parent import A class B(A): def methodb(self): print("am in methodb") Is there anyway to call methodb() in parent.py? A: Doing this would only ma...
calling child class method from parent class file in python
parent.py: class A(object): def methodA(self): print("in methodA") child.py: from parent import A class B(A): def methodb(self): print("am in methodb") Is there anyway to call methodb() in parent.py?
[ "Doing this would only make sense if A is an abstract base class, meaning that A is only meant to be used as a base for other classes, not instantiated directly. If that were the case, you would define methodB on class A, but leave it unimplemented:\nclass A(object):\n def methodA(self):\n print(\"in meth...
[ 46, 20, 2, 1, 0, 0 ]
[]
[]
[ "class", "inheritance", "parent", "python" ]
stackoverflow_0025062114_class_inheritance_parent_python.txt
Q: Finding difference between list items list = [4, 7, 11, 15] I'm trying to create a function to loop through list items, and find the difference between list[1] and list[0], and then list[2] and list[1], and then list[3] and list[2]... and so on for the entirety of the list. I am thinking of using a for loop but t...
Finding difference between list items
list = [4, 7, 11, 15] I'm trying to create a function to loop through list items, and find the difference between list[1] and list[0], and then list[2] and list[1], and then list[3] and list[2]... and so on for the entirety of the list. I am thinking of using a for loop but there might be a better way. Thanks. output...
[ "If you are in Python 3.10+ you could try pairwise:\nAnd you should try NOT to use the built-in list as the variable name.\nIt's quite easy and straightforward to make this one-line into a function.\n\nfrom itertools import pairwise\n\n>>>[b-a for a, b in pairwise(lst)] # List Comprehension\n[3, 4, 4]\n\n# Or jus...
[ 3, 0, 0 ]
[]
[]
[ "for_loop", "list", "python" ]
stackoverflow_0074636222_for_loop_list_python.txt
Q: why Index error at / list index out of range? hello im having a problem with the index code in my views.py, aparrently the HTML index is out of range for some reason i dont understand, because before i wanted to make the page to add images as avatars work perfectly fine the index .html is in a templates folder , i...
why Index error at / list index out of range?
hello im having a problem with the index code in my views.py, aparrently the HTML index is out of range for some reason i dont understand, because before i wanted to make the page to add images as avatars work perfectly fine the index .html is in a templates folder , inside the APP folder, and i created a media folder ...
[ "def mostrar_index(request):\n imagenes = Avatar.objects.filter(user=request.user.id)\n return render(request, 'index.html', {'avatar': imagenes})\n\n{% if request.user.is_authenticated %}\n {% if avatar %}\n <img src=\"{{avatar.images.url}}\" alt=\"\">\n {% else %}\n <img src=\"{% static ...
[ 0 ]
[]
[]
[ "css", "django", "html", "python" ]
stackoverflow_0074635380_css_django_html_python.txt
Q: How do I install pandas datareader on windows when hit with this error? I am trying to install pandas datareader, but I am hit with this error: Collecting pandas-datareader Using cached pandas_datareader-0.10.0-py3-none-any.whl (109 kB) Collecting lxml Using cached lxml-4.9.1.tar.gz (3.4 MB) Preparing metada...
How do I install pandas datareader on windows when hit with this error?
I am trying to install pandas datareader, but I am hit with this error: Collecting pandas-datareader Using cached pandas_datareader-0.10.0-py3-none-any.whl (109 kB) Collecting lxml Using cached lxml-4.9.1.tar.gz (3.4 MB) Preparing metadata (setup.py) ... done Requirement already satisfied: pandas>=0.23 in c:\user...
[ "try:\n\npip install --upgrade pip\n\nOn Windows the recommended command is:\n\npython -m pip install --upgrade pip\n\n", "You're almost there. Check the error logs carefully. You'll notice it's asking for:\nIs libxml2 installed?\n\nTry installing that with pip then retry.\n" ]
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074636322_pandas_python.txt
Q: Problem with Logging Module in Google Colab I have a python script with an error handling using the logging module. Although this python script works when imported to google colab, it doesn't log the errors in the log file. As an experiment, I tried this following script in google colab just to see if it writes l...
Problem with Logging Module in Google Colab
I have a python script with an error handling using the logging module. Although this python script works when imported to google colab, it doesn't log the errors in the log file. As an experiment, I tried this following script in google colab just to see if it writes log at all import logging logging.basicConfig(file...
[ "Perhaps you've reconfigured your environment somehow? (Try Runtime menu -> Reset all runtimes...) Your snippets works exactly as written for me --\n\n", "logging.basicConfig can be run just once*\nAny subsequent call to basicConfig is ignored.\n* unless you are in Python 3.8 and use the flag force=True\nlogging....
[ 7, 2, 0 ]
[]
[]
[ "error_handling", "google_colaboratory", "jupyter_notebook", "logging", "python" ]
stackoverflow_0054597462_error_handling_google_colaboratory_jupyter_notebook_logging_python.txt
Q: Delete key and pair from Json file I'm trying to delete a key and its pair from a json file . I tried the codes below but nothing triggers or work. Anyone can modify and assist me reda.json file [{"carl": 33}, {"carl": 55}, {"user": "user2", "id": "21780"}, {"user": "user2"}, {"user": "123"}, {"user": []}, {"user...
Delete key and pair from Json file
I'm trying to delete a key and its pair from a json file . I tried the codes below but nothing triggers or work. Anyone can modify and assist me reda.json file [{"carl": 33}, {"carl": 55}, {"user": "user2", "id": "21780"}, {"user": "user2"}, {"user": "123"}, {"user": []}, {"user": []}] import json json_data = json.l...
[ "When you load a JSON file into Python using json.load, it creates a copy of that JSON in Python. When that copy is changed, these changes are not reflected in the file.\nSo what you need to do is then transfer your changed copy back to the file.\nThis can be achieved via a method in the same json library as you're...
[ 2 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074636162_dictionary_python_python_3.x.txt
Q: Using global variables in a function How do I create or use a global variable inside a function? How do I use a global variable that was defined in one function inside other functions? Failing to use the global keyword where appropriate often causes UnboundLocalError. The precise rules for this are explained at U...
Using global variables in a function
How do I create or use a global variable inside a function? How do I use a global variable that was defined in one function inside other functions? Failing to use the global keyword where appropriate often causes UnboundLocalError. The precise rules for this are explained at UnboundLocalError on local variable when re...
[ "You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:\nglobvar = 0\n\ndef set_globvar_to_one():\n global globvar # Needed to modify global copy of globvar\n globvar = 1\n\ndef print_globvar():\n print(globvar) # No need for g...
[ 5007, 874, 267, 115, 74, 68, 57, 41, 35, 33, 30, 30, 27, 23, 20, 17, 9, 8, 8, 7, 6, 5, 1, 0 ]
[ "if you want to access global var you just add global keyword inside your function\nex:\nglobal_var = 'yeah'\ndef someFunc():\n global global_var;\n print(nam_of_var)\n\n" ]
[ -1 ]
[ "global_variables", "python", "scope" ]
stackoverflow_0000423379_global_variables_python_scope.txt
Q: pandas create new column based on divide column by another and check that I not divide by 0 I want to create a new column based on a division of two different columns, but make sure that I do not divide by 0, if the price is 0 set it to none. if I try to just divide I get 'inf' where the price is 0: df['new'] = df...
pandas create new column based on divide column by another and check that I not divide by 0
I want to create a new column based on a division of two different columns, but make sure that I do not divide by 0, if the price is 0 set it to none. if I try to just divide I get 'inf' where the price is 0: df['new'] = df['memory'] / df['price'] id memory price 0 0 7568 751.64 1 1 53...
[ "To avoid division by zero, I would avoid dividing the values by zero. Please take a look at the following example.\nI hope this helps.\nBest regards\nimport pandas as pd\n\ndata = {'id': [0, 1, 2, 3, 4], 'memory': [7568, 53759, 41140, 10558, 44436], 'price': [751.64, 885.17, 1067.78, 0, 1023.13]}\ndf = pd.DataFram...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074636048_python.txt
Q: Plotly Scatter plot: how to create a scatter or line plot for only one group My question might seem very easy, but I am having a difficult time understanding how to create a scatter plot or line plot for only one group of values. For example, my data frame, has 3 columns. My table looks like the following: fruit ...
Plotly Scatter plot: how to create a scatter or line plot for only one group
My question might seem very easy, but I am having a difficult time understanding how to create a scatter plot or line plot for only one group of values. For example, my data frame, has 3 columns. My table looks like the following: fruit lb price orange 1 1.4 orange 2 1.7 apple 3 2.1 apple 1 1.4 kiwi 2 1...
[ "Adding a user selection dropdown will accomplish your goal. Use a graph object to draw a graph for each type of fruit and show the Show/Hide setting. All and only each type will be available as a type of dropdown. Give the list of Show/Hide as input for the button. Now, the drop-down selection will toggle between ...
[ 0 ]
[]
[]
[ "pandas", "plotly", "python" ]
stackoverflow_0074632288_pandas_plotly_python.txt
Q: AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas Str.replace method returns an attribute error. dc_listings['price'].str.replace(',', '') AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas Here are the top 5 rows ...
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
Str.replace method returns an attribute error. dc_listings['price'].str.replace(',', '') AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas Here are the top 5 rows of my price column. This stack overflow thread recommends to check if my column has NAN values but non ...
[ "As the error states, you can only use .str with string columns, and you have a float64. There won't be any commas in a float, so what you have won't really do anything, but in general, you could cast it first:\ndc_listings['price'].astype(str).str.replace...\n\nFor example:\nIn [18]: df\nOut[18]:\n a ...
[ 148, 14, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0052065909_pandas_python.txt
Q: How to add my own parameters into pymongo find function Im building a python application that allows you to query data from mongoDB based on the start time and end time that the user puts in. I have been able to connect to mongoDB and put data there. I just cant seem to get the query right. I will show only the fu...
How to add my own parameters into pymongo find function
Im building a python application that allows you to query data from mongoDB based on the start time and end time that the user puts in. I have been able to connect to mongoDB and put data there. I just cant seem to get the query right. I will show only the function in question because I know that connecting to the data...
[ "Put this format in your function try:\ncollection.find([\n {\n \"$Date\" : {\n \"$gte\": begin, \n \"$lte\": end \n } \n }\n ])\n\n" ]
[ 1 ]
[]
[]
[ "pymongo", "python" ]
stackoverflow_0074636478_pymongo_python.txt
Q: service account does not have storage.objects.get access for Google Cloud Storage I have created a service account in Google Cloud Console and selected role Storage / Storage Admin (i.e. full control of GCS resources). gcloud projects get-iam-policy my_project seems to indicate that the role was actually selected:...
service account does not have storage.objects.get access for Google Cloud Storage
I have created a service account in Google Cloud Console and selected role Storage / Storage Admin (i.e. full control of GCS resources). gcloud projects get-iam-policy my_project seems to indicate that the role was actually selected: - members: - serviceAccount:my_sa@my_project.iam.gserviceaccount.com role: roles/s...
[ "The problem was apparently that the service account was associated with too many roles, perhaps as a results of previous configuration attempts.\nThese steps resolved the issue:\n\nremoved all (three) roles for the offending service account (member) my_sa under IAM & Admin / IAM\ndeleted my_sa under IAM & Admin / ...
[ 24, 18, 16, 1, 1, 0, 0 ]
[]
[]
[ "google_cloud_platform", "google_cloud_storage", "python", "service_accounts" ]
stackoverflow_0051410633_google_cloud_platform_google_cloud_storage_python_service_accounts.txt
Q: How to understand the flaw in my simple three part python code? My Python exercise in 'classes' is as follows: You have been recruited by your friend, a linguistics enthusiast, to create a utility tool that can perform analysis on a given piece of text. Complete the class "analyzedText" with the following methods...
How to understand the flaw in my simple three part python code?
My Python exercise in 'classes' is as follows: You have been recruited by your friend, a linguistics enthusiast, to create a utility tool that can perform analysis on a given piece of text. Complete the class "analyzedText" with the following methods: Constructor (_init_) - This method should take the argument text, ...
[ "On the assumption that by 'errors' you mean a TypeError, this is caused because of line 13, wordDict[word] = wordList(word).\nwordList is a list, and by using the ()/brackets you're telling Python that you want to call that list as a function. Which it cannot do.\nAccording to your task, you are to instead find th...
[ 1 ]
[]
[]
[ "class", "coursera_api", "python" ]
stackoverflow_0074635479_class_coursera_api_python.txt
Q: Use of "DGLGraph.apply_edges" and "DGLGraph.send_and_recv" API (to compute messages) as a replacement of "DGLGraph.send" and "DGLGraph.recv I'm using DGL (Python package dedicated to deep learning on graphs) for training of defining a graph, defining Graph Convolutional Network (GCN) and train. I faced a problem w...
Use of "DGLGraph.apply_edges" and "DGLGraph.send_and_recv" API (to compute messages) as a replacement of "DGLGraph.send" and "DGLGraph.recv
I'm using DGL (Python package dedicated to deep learning on graphs) for training of defining a graph, defining Graph Convolutional Network (GCN) and train. I faced a problem which I’m dealing with for two weeks. I developed my GCN code based on the link below: enter link description here I’m facing an error for this pa...
[ "DGLGraph.apply_edges(func, edges='ALL', etype=None, inplace=False) is used to update edge features using the function 'func' on all the edges in 'edges'.\nDGLGraph.send_and_recv(edges, message_func, reduce_func, apply_node_func=None, etype=None, inplace=False) is used to pass messages, reduce messages and update t...
[ 0, 0 ]
[]
[]
[ "deep_learning", "dgl", "graph", "graph_neural_network", "python" ]
stackoverflow_0071848343_deep_learning_dgl_graph_graph_neural_network_python.txt
Q: how to compare two dictionaries and display the values that differs in template? I try to compare two dictionaries and if on key, value differs from the other dictionary then print the difference key, value in red. I think my views.py is correct. But how to show the difference in the template? So I have views.py: ...
how to compare two dictionaries and display the values that differs in template?
I try to compare two dictionaries and if on key, value differs from the other dictionary then print the difference key, value in red. I think my views.py is correct. But how to show the difference in the template? So I have views.py: def data_compare(): fruits = { "appel": 3962.00, "waspeen": 3304....
[ "Looks dictdiff might be useful in your case. The following example is not the same as your output, but I hope it is useful.\nimport dictdiffer\n\nfruits = {\n \"appel\": 3962.00,\n \"waspeen\": 3304.07,\n \"ananas\": 24,\n}\nfruits2 = {\n \"appel\": 3962.00,\n \"waspeen\": 3304.07,\n \"ananas\": ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074633851_django_python.txt
Q: Nested try/except statement for method I wonder if it is possible to handle the exceptions raised when calling a method via a function (this is necessary as in the production code different objects are created depending on args passed) as in the following example. Function createObj triggers the creation of an obj...
Nested try/except statement for method
I wonder if it is possible to handle the exceptions raised when calling a method via a function (this is necessary as in the production code different objects are created depending on args passed) as in the following example. Function createObj triggers the creation of an object Obj_A based off different criteria and i...
[ "You want to handle an exception with the except clause that will be raised in the future after the corresponding try statement. It's impossible, and unnatural if it's possible.\nInstead, do in other way like this example.\ndef createObj():\n def handle_exception(e):\n print(\"Bad boy!\")\n return Obj_...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074635376_python_python_3.x.txt
Q: List Highest Correlation Pairs from a Large Correlation Matrix in Pandas? How do you find the top correlations in a correlation matrix with Pandas? There are many answers on how to do this with R (Show correlations as an ordered list, not as a large matrix or Efficient way to get highly correlated pairs from large...
List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?
How do you find the top correlations in a correlation matrix with Pandas? There are many answers on how to do this with R (Show correlations as an ordered list, not as a large matrix or Efficient way to get highly correlated pairs from large data set in Python or R), but I am wondering how to do it with pandas? In my c...
[ "You can use DataFrame.values to get an numpy array of the data and then use NumPy functions such as argsort() to get the most correlated pairs. \nBut if you want to do this in pandas, you can unstack and sort the DataFrame:\nimport pandas as pd\nimport numpy as np\n\nshape = (50, 4460)\n\ndata = np.random.normal(s...
[ 128, 71, 60, 29, 20, 14, 13, 3, 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "correlation", "pandas", "python" ]
stackoverflow_0017778394_correlation_pandas_python.txt
Q: pynetdicom on_association_requested() get request type (C_FIND, C_ECHO etc) I'm not able to find the variable that holds the Message Type in event name, "on_association_requested" and "on_association_released" methods. If we give event.event.name it results in "EVT_REQUESTED" or "EVT_RELEASED". INCOMING DIMSE MESS...
pynetdicom on_association_requested() get request type (C_FIND, C_ECHO etc)
I'm not able to find the variable that holds the Message Type in event name, "on_association_requested" and "on_association_released" methods. If we give event.event.name it results in "EVT_REQUESTED" or "EVT_RELEASED". INCOMING DIMSE MESSAGE D: Message Type : C-ECHO RQ D: Presentation Context ID ...
[ "There is no DIMSE message type during association request. Only after an association has already been through request and acceptance are DIMSE messages allowed to be sent.\n" ]
[ 0 ]
[]
[]
[ "pynetdicom", "python" ]
stackoverflow_0074611115_pynetdicom_python.txt
Q: How can a pandas merge preserve order? I have two DataFrames in pandas, trying to merge them. But pandas keeps changing the order. I've tried setting indexes, resetting them, no matter what I do, I can't get the returned output to have the rows in the same order. Is there a trick? Note we start out with the loan...
How can a pandas merge preserve order?
I have two DataFrames in pandas, trying to merge them. But pandas keeps changing the order. I've tried setting indexes, resetting them, no matter what I do, I can't get the returned output to have the rows in the same order. Is there a trick? Note we start out with the loans order 'a,b,c' but after the merge, it's "a...
[ "Hopefully someone will provide a better answer, but in case no one does, this will definitely work, so…\nZeroth, I'm assuming you don't want to just end up sorted on loan, but to preserve whatever original order was in x, which may or may not have anything to do with the order of the loan column. (Otherwise, the p...
[ 27, 6, 4, 4, 0 ]
[ "Use pd.merge_ordered(), documentation here. \nFor your example,\nz = pd.merge_ordered(x, y, how='left', on='state')\n\nEDIT: Just wanted to point out that default behavior for this function is an outer merge, different from the default behavior of the more common .merge()\n" ]
[ -3 ]
[ "pandas", "python" ]
stackoverflow_0020206615_pandas_python.txt
Q: Recursion, Fib Numbers On a call to fib(10), how many times is fib(4) computed? I can't seem to figure this out, could anyone help? def fib ( n ): if n < 3: return 1 else: return fib(n-1) + fib(n-2) Trying to figure out how many times fib(4) is computed. A: Set T(n) =...
Recursion, Fib Numbers
On a call to fib(10), how many times is fib(4) computed? I can't seem to figure this out, could anyone help? def fib ( n ): if n < 3: return 1 else: return fib(n-1) + fib(n-2) Trying to figure out how many times fib(4) is computed.
[ "Set T(n) = the times fib(n) call fib(4)\nWe know that\nT(4)=1, T(5)=1\n\nT(n) = T(n-1)+T(n-2)\n\nSo\nT(6) = T(5) + T(4) = 2\nT(7) = T(6) + T(5) = 3\nT(8) = T(7) + T(6) = 5\nT(9) = T(8) + T(7) = 8\nT(10) = T(9) + T(8) = 13\n\nAlso you can make some changes in your code\na = 0\n\ndef fib ( n ):\n if(n==4):\n ...
[ 1, 0 ]
[]
[]
[ "fibonacci", "python", "recursion" ]
stackoverflow_0074636393_fibonacci_python_recursion.txt
Q: Get nearest low and high values across multiple dataframe columns I have a dataframe similar to this: import pandas as pd id = [1001, 1002, 1003] a = [156, 224, 67] b = [131, 203, 61] c = [97, 165, 54] d = [68, 122, 50] value = [71, 180, 66] df = pd.DataFrame({'id':id, 'a':a, 'b':b...
Get nearest low and high values across multiple dataframe columns
I have a dataframe similar to this: import pandas as pd id = [1001, 1002, 1003] a = [156, 224, 67] b = [131, 203, 61] c = [97, 165, 54] d = [68, 122, 50] value = [71, 180, 66] df = pd.DataFrame({'id':id, 'a':a, 'b':b, 'c':c, 'd':d, 'value':value}) id a b c d value 1001 156 131 ...
[ "you can get nearest low following code:\ndf.apply(lambda x: x[x < x[-1]].max(), axis=1)\n\noutput:\n0 68\n1 165\n2 61\ndtype: int64\n\nget nearest low and high and make result to columns:\ndf[['nxt_low', 'nxt_high']] = df.apply(lambda x: [x[x < x[-1]].max(), x[x > x[-1]].min()], axis=1, result_type='exp...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074636203_dataframe_pandas_python.txt
Q: how to make a discord.py bot not accepts commands from dms How do I make a discord.py bot not react to commands from the bot's DMs? I only want the bot to respond to messages if they are on a specific channel on a specific server. A: If you wanted to only respond to messages on a specific channel and you know th...
how to make a discord.py bot not accepts commands from dms
How do I make a discord.py bot not react to commands from the bot's DMs? I only want the bot to respond to messages if they are on a specific channel on a specific server.
[ "If you wanted to only respond to messages on a specific channel and you know the name of the channel, you could do this:\nchannel = discord.utils.get(ctx.guild.channels, name=\"channel name\")\nchannel_id = channel.id\n\nThen you would check if the id matched the one channel you wanted it to be in. To get a channe...
[ 1, 1, 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0072954461_discord_discord.py_python.txt
Q: How to format a dictionary with a list of items in Python I have a python dictionary that I want to look like this: {"name": "BOB", "item1": { "item name": "bread", "quantity of item ": 10, "price of item": "3.00" }, "item2": { "item name": "milk", "quantity of...
How to format a dictionary with a list of items in Python
I have a python dictionary that I want to look like this: {"name": "BOB", "item1": { "item name": "bread", "quantity of item ": 10, "price of item": "3.00" }, "item2": { "item name": "milk", "quantity of item ": 15, "price of item": "9.00" } } currently...
[ "If you're trying to json.dump() it into a JSON file, using the json.dump() function you could pass in the indent argument for indentation (appears to be what you want) You can read more about it here\nAn example:\njson.dump(jsonData, jsonFile, indent=2) # indentation is usually in spaces, so 2 would mean 2 spaces ...
[ 1 ]
[]
[]
[ "dictionary", "python", "python_re" ]
stackoverflow_0074636613_dictionary_python_python_re.txt
Q: Error: InvalidSignature when trying to connect to SP-API amazon I've trying to connect to amazon api for a week now. I've got stuck in this error and after readig the doc several times I can't realize which is the problem. Here is my code: # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX...
Error: InvalidSignature when trying to connect to SP-API amazon
I've trying to connect to amazon api for a week now. I've got stuck in this error and after readig the doc several times I can't realize which is the problem. Here is my code: # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Important The AWS SDKs sign API...
[ "This is another solution without boto3 and only using requests\nimport hashlib\nimport hmac\nimport logging\nfrom collections import OrderedDict\nfrom urllib.parse import urlencode\nimport defusedxml.ElementTree as ET\nfrom sdc_etl_libs.api_helpers.API import API\nimport sys, datetime, hashlib, hmac \nimport reque...
[ 1, 0 ]
[]
[]
[ "amazon_product_api", "api", "python" ]
stackoverflow_0074558880_amazon_product_api_api_python.txt
Q: what is this error for? 'NoneType' object has no attribute 'round' cm = int(input("Write height in Centimeters:")) inches = 0.394*cm feet = 0.0328*cm print(("The length in inches",round(inches,2))).round(inches,2) print(("The length in feet",round(feet,2))).round(feet,2) this is the code this code should convert...
what is this error for? 'NoneType' object has no attribute 'round'
cm = int(input("Write height in Centimeters:")) inches = 0.394*cm feet = 0.0328*cm print(("The length in inches",round(inches,2))).round(inches,2) print(("The length in feet",round(feet,2))).round(feet,2) this is the code this code should convert cm in feet and inches but there is a error
[ "I'll first break down the error:\nA NoneType object is basically the None object in Python. You could consider it to be basically an object with no value. If you're getting this error, it means you're trying to use the .round() method on something that either returns None, or a None value.\nNow about your code:\nY...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074636711_python.txt
Q: How can I use ParamSpec with method decorators? I was following the example from PEP 0612 (last one in the Motivation section) to create a decorator that can add default parameters to a function. The problem is, the example provided only works for functions but not methods, because Concate doesn't allow inserting ...
How can I use ParamSpec with method decorators?
I was following the example from PEP 0612 (last one in the Motivation section) to create a decorator that can add default parameters to a function. The problem is, the example provided only works for functions but not methods, because Concate doesn't allow inserting self anywhere in the definition. Consider this exampl...
[ "There is surprisingly little about this online. I was able to find someone else's discussion of this over at python/typing's Github, which I distilled using your example.\nThe crux of this solution is Callback Protocols, which are functionally equivalent to Callable, but additionally enable us to modify the return...
[ 0 ]
[]
[]
[ "python", "python_3.10", "typing" ]
stackoverflow_0073856901_python_python_3.10_typing.txt
Q: Using FastAPI in a sync way, how can I get the raw body of a POST request? Using FastAPI in a sync, not async mode, I would like to be able to receive the raw, unchanged body of a POST request. All examples I can find show async code, when I try it in a normal sync way, the request.body() shows up as a coroutine o...
Using FastAPI in a sync way, how can I get the raw body of a POST request?
Using FastAPI in a sync, not async mode, I would like to be able to receive the raw, unchanged body of a POST request. All examples I can find show async code, when I try it in a normal sync way, the request.body() shows up as a coroutine object. When I test it by posting some XML to this endpoint, I get a 500 "Interna...
[ "Using async def endpoint\nIf an object is a co-routine, it needs to be awaited. FastAPI is based on Starlette, and Starlette methods for returning the request body are async methods (see source code here); thus, one needs to await them (using an async def endpoint). For example:\nfrom fastapi import Request\n\n@ap...
[ 9, 0 ]
[]
[]
[ "fastapi", "python", "starlette" ]
stackoverflow_0070658748_fastapi_python_starlette.txt
Q: How can I set and append in column with conditional case in Django? I want to run this sql query in Django UPDATE `TABLE` SET `COLUMN` = (CASE WHEN `COLUMN` = "" THEN '100' ELSE CONCAT(`COLUMN`,'100') END) WHERE `SOMEID` IN [id1,id2,id3]; I tried this from django.db.models import Case, When, F Table.objects.filte...
How can I set and append in column with conditional case in Django?
I want to run this sql query in Django UPDATE `TABLE` SET `COLUMN` = (CASE WHEN `COLUMN` = "" THEN '100' ELSE CONCAT(`COLUMN`,'100') END) WHERE `SOMEID` IN [id1,id2,id3]; I tried this from django.db.models import Case, When, F Table.objects.filter(someid__in=[id1,id2,id3]). update(column= Case( When(column="",th...
[ "You can use the F objects:\nfrom django.db.models import F\n\nTable.objects.filter(...).update(column=F(\"column\") + \"100\")\n\nYou don't need to check if column == \"\" because it won't matter when you append \"100\" to it.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074636423_django_python.txt
Q: Discord bot, current date as status i have looked a bit and tried multiple things and im stumped. Im going to be hosting a discord bot 24/7 and i want the Status to display the current date and time, as example. 11/30/22, 10:51 PM, in eastern time. Thanks! tried methods such as " activity=discord.Game(datetime.dat...
Discord bot, current date as status
i have looked a bit and tried multiple things and im stumped. Im going to be hosting a discord bot 24/7 and i want the Status to display the current date and time, as example. 11/30/22, 10:51 PM, in eastern time. Thanks! tried methods such as " activity=discord.Game(datetime.datetime.utcnow().strftime("%H:%M")),"
[ "You can use tasks.loop, creating a task that updates every minute and changes the bot's Status to the current time.\ntasks.loop is a decorator which executes the decorated function repeatedly at a defined interval. Then you just need to spawn the loop in an asynchronous context, of which I personally use setup_hoo...
[ 0 ]
[]
[]
[ "bots", "discord", "python" ]
stackoverflow_0074636772_bots_discord_python.txt
Q: TypeError: numpy boolean subtract, the `-` operator, is not supported in Scipy.Optimize Using scipy.optimise (code below) - for a battery optimisation problem Getting this error: TypeError: numpy boolean subtract, the - operator, is not supported, use the bitwise_xor, the ^ operator, or the logical_xor function in...
TypeError: numpy boolean subtract, the `-` operator, is not supported in Scipy.Optimize
Using scipy.optimise (code below) - for a battery optimisation problem Getting this error: TypeError: numpy boolean subtract, the - operator, is not supported, use the bitwise_xor, the ^ operator, or the logical_xor function instead. Which came from the minimize function directly, so I'm not sure exactly where its comi...
[ "Is the SLSQP method compatible with functions that return boolean values true and false? I would rework function constraint1 to return real values instead of boolean values. If SLSQP is compatible with boolean functions, could you point me to the documentation that states this?\nWhen I saw this message, \"df = fun...
[ 1 ]
[]
[]
[ "optimization", "python", "scipy", "scipy_optimize", "scipy_optimize_minimize" ]
stackoverflow_0074636794_optimization_python_scipy_scipy_optimize_scipy_optimize_minimize.txt
Q: How to increase the thickness of x-axis in matplotlib.plt I am trying to increase the thickness of the horizontal x-axis in my plot but I could not find a way to do it. I am able to increase the thickness of x-ticks but not the line itself. Here is my code: ax = plt.subplot(3, 1, 3) q1 = sns.pointplot(df1['Tomato'...
How to increase the thickness of x-axis in matplotlib.plt
I am trying to increase the thickness of the horizontal x-axis in my plot but I could not find a way to do it. I am able to increase the thickness of x-ticks but not the line itself. Here is my code: ax = plt.subplot(3, 1, 3) q1 = sns.pointplot(df1['Tomato'][0:191], color='#009966',errwidth = 30, scale=4.5) q2 = sns.po...
[ "You can try ax.spines[\"bottom\"].set_linewidth(3).\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "matplotlib", "python", "seaborn" ]
stackoverflow_0074636391_jupyter_notebook_matplotlib_python_seaborn.txt
Q: pandas returning line number and type? I have a csv file, and using python get the highest average price of avocado from the data. All works fine until printing the region avocadoesDB = pd.read_csv("avocado.csv") avocadoesDB = pd.DataFrame(avocadoesDB) avocadoesDB = avocadoesDB[['AveragePrice', 'type', 'year', 're...
pandas returning line number and type?
I have a csv file, and using python get the highest average price of avocado from the data. All works fine until printing the region avocadoesDB = pd.read_csv("avocado.csv") avocadoesDB = pd.DataFrame(avocadoesDB) avocadoesDB = avocadoesDB[['AveragePrice', 'type', 'year', 'region']] regions = avocadoesDB[['AveragePr...
[ "So i've tried to copy the similar method on a simple dataset and i've seem to make it work, here's the code snippet\nmx = max(df1['Salary'])\nplc = df.loc[df1['Salary']==mx]['Name']\nprint('Max Sal : ' + str(plc.iloc[0]))\n\nOutput:\nMax Sal : Farah\n\nAccording to this post on Stack Overflow, when you use df.loc[...
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074636609_dataframe_python.txt
Q: Creating my first OOP python 'game', its called Battle Bots I'm very new to coding and have just begun OOP with python and my first task is to build a game called Battle Bots. The premise of the game is 2 bots fighting with 100 life points and each turn the bots attack one another with a randomly generated "streng...
Creating my first OOP python 'game', its called Battle Bots
I'm very new to coding and have just begun OOP with python and my first task is to build a game called Battle Bots. The premise of the game is 2 bots fighting with 100 life points and each turn the bots attack one another with a randomly generated "strength." The strength is equivalent to the attack so whatever the pro...
[]
[]
[ "I suggest you to learn about association, composition and aggregation and inheritance and when to use them, so that you have better understanding of relation between objects and classes at the high level.\nalso in your code you can't have two init method in one class i highly recommend to have clear understanding ...
[ -1 ]
[ "class", "object", "python" ]
stackoverflow_0074636709_class_object_python.txt
Q: Django - Sending post request using a nested serializer with many to many relationship. Getting a [400 error code] "This field may not be null] error" I'm fairly new to Django and I'm trying to make a POST request with nested objects. This is the data that I'm sending: { "id":null, "deleted":false, "publi...
Django - Sending post request using a nested serializer with many to many relationship. Getting a [400 error code] "This field may not be null] error"
I'm fairly new to Django and I'm trying to make a POST request with nested objects. This is the data that I'm sending: { "id":null, "deleted":false, "publishedOn":2022-11-28, "decoratedThumbnail":"https://t3.ftcdn.net/jpg/02/48/42/64/360_F_248426448_NVKLywWqArG2ADUxDq6QprtIzsF82dMF.jpg", "rawThumbnail":"...
[ "I would consider changing the serializer as below,\nclass VideoManageSerializer(serializers.ModelSerializer):\n video_tag_id = serializers.PrimaryKeyRelatedField(\n many=True,\n queryset=VideoTag.objects.all(),\n write_only=True,\n )\n tags = VideoVideoTagSerializer(many=True, read_on...
[ 3 ]
[]
[]
[ "api", "django", "django_rest_framework", "python", "sql" ]
stackoverflow_0074606902_api_django_django_rest_framework_python_sql.txt
Q: Python macOS os module: Can't find path when running my python script for saving a .xlsx document on the local computer and trying to open the same file after with the system() function from the python os module, i catch this specific error on screen: image (Translated to English: Path not found) The code used for...
Python macOS os module: Can't find path
when running my python script for saving a .xlsx document on the local computer and trying to open the same file after with the system() function from the python os module, i catch this specific error on screen: image (Translated to English: Path not found) The code used for saving the file is wb.save() from openpyxl w...
[ "So following the steps from @Gordon Davisson:\nI tried pasting open -a '/Applications/Microsoft Excel.app' '/Users/andersballeby/Desktop/McDonalds Programmer/Main Project/McDonalds-Leader-Panel/skiftplaner/November/onsdag d. 30-11/Skiftplan (onsdag - MID - 12:00 - 17:00).xlsx' into my terminal, which returned the ...
[ 0 ]
[]
[]
[ "macos", "openpyxl", "operating_system", "python", "python_3.x" ]
stackoverflow_0074636105_macos_openpyxl_operating_system_python_python_3.x.txt
Q: How do I rename parent field name and nested field value in mongodb using pymongo? I have following document: { "dataset_path":"path_of_dataset", "project_1":{ "model_1":"path_of_model_1", "model_2":"path_of_model_2" } } I want to change "project_1" to "renamed_project_1" and "path_of_m...
How do I rename parent field name and nested field value in mongodb using pymongo?
I have following document: { "dataset_path":"path_of_dataset", "project_1":{ "model_1":"path_of_model_1", "model_2":"path_of_model_2" } } I want to change "project_1" to "renamed_project_1" and "path_of_model_1" to "new_model_1_path". The resultant output should be as follows: { "dataset...
[ "That's because you're trying to mutate project_1 field two times in a single query. Mongo just doesn't know how to deal with that.\nYou should consider splitting two operations:\ndb.collection.update_many({'dataset_path': 'path_to_dataset'}, {'$rename': {\"project_1\": \"renamed_project_1\"}})\ndb.collection.updat...
[ 0, 0 ]
[]
[]
[ "mongodb", "pymongo", "pymongo_3.x", "python" ]
stackoverflow_0066559676_mongodb_pymongo_pymongo_3.x_python.txt
Q: call method using variables in python I want to pass methods as variables. In the below method I have 3 methods that are part of the fuzz library. How can I call them using variable name. from fuzzywuzzy import fuzz from fuzzywuzzy import process method_name1 ='token_sort_ratio' method_name2 ='partial_ratio' metho...
call method using variables in python
I want to pass methods as variables. In the below method I have 3 methods that are part of the fuzz library. How can I call them using variable name. from fuzzywuzzy import fuzz from fuzzywuzzy import process method_name1 ='token_sort_ratio' method_name2 ='partial_ratio' method_name3 ='ratio' def compare_alg(l1, l2, a...
[ "You can use getattr\nfrom fuzzywuzzy import fuzz\nfrom fuzzywuzzy import process\nmethod_name1 ='token_sort_ratio'\nmethod_name2 ='partial_ratio'\nmethod_name3 ='ratio'\n\ndef compare_alg(l1, l2, alg):\n print(getattr(fuzz, alg)(l1,l2))\n\ncompare_alg(\"Catherine M Gitau\",\"Catherine Gitau\", method_name1)\nco...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074637000_python.txt
Q: How can a pass a list to an airflow via a template? I have an airflow operator based off of BaseOperator which has libraries as one of its fields. This field takes a list of python packages that may need to be installed to run the code in the task. I would like to be able to pass that list via a template variable...
How can a pass a list to an airflow via a template?
I have an airflow operator based off of BaseOperator which has libraries as one of its fields. This field takes a list of python packages that may need to be installed to run the code in the task. I would like to be able to pass that list via a template variable but have not had luck doing so. I have tried passing the...
[ "This is now supported via the render_template_as_native_obj.\nPlease add the following argument to your DAG object for Jinja to apply correct typing for basic python objects:\nrender_template_as_native_obj=True\n\n", "This is not supported currently but will be supported when https://github.com/apache/airflow/pu...
[ 1, 0 ]
[]
[]
[ "airflow", "python", "templating" ]
stackoverflow_0067202226_airflow_python_templating.txt
Q: Dotted or dashed line with Python PILLOW How to draw a dotted or dashed line or rectangle with Python PILLOW. Can anyone help me? Using openCV I can do that. But I want it using Pillow. A: Thanks to @martineau's comment, I figured out how to draw a dotted line. Here is my code. cur_x = 0 cur_y = 0 image_width = ...
Dotted or dashed line with Python PILLOW
How to draw a dotted or dashed line or rectangle with Python PILLOW. Can anyone help me? Using openCV I can do that. But I want it using Pillow.
[ "Thanks to @martineau's comment, I figured out how to draw a dotted line. Here is my code.\ncur_x = 0\ncur_y = 0\nimage_width = 600\nfor x in range(cur_x, image_width, 4):\n draw.line([(x, cur_y), (x + 2, cur_y)], fill=(170, 170, 170))\n\nThis will draw a dotted line of gray color.\n", "I decided to write up t...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0051908563_python_python_imaging_library.txt
Q: Using Merge into to update multiple rows in snowflake DB using python I have a snowflake table lets called it as (temp) with ID as my primary key which autoincrements with any new inserts in the table. I learned about merge into statement can be used to update multiple rows in the snowflake table. I have a tkinter...
Using Merge into to update multiple rows in snowflake DB using python
I have a snowflake table lets called it as (temp) with ID as my primary key which autoincrements with any new inserts in the table. I learned about merge into statement can be used to update multiple rows in the snowflake table. I have a tkinter application, which retrieves the user input entered on the form using tree...
[ "Not a fancy solution but I am passing these updates statements as a list. Since I need only up to three update statements for this to work.\nqueries = [update1, update2, update3]\nfor i, q in enumerate(queries):\n df = pd.read_sql(q,con, param= params)\n\n" ]
[ 0 ]
[]
[]
[ "python", "snowflake_cloud_data_platform" ]
stackoverflow_0074633268_python_snowflake_cloud_data_platform.txt
Q: Find strings between 2 substrings with Python I’m trying to get the string starting with p and between 2 substrings ds and svcp. My approach is like this import re string_list = [‘ds-pfoo-svcp’, ‘ds-abc-pbar-svcp’, ‘ds-abc-ptee-xyz-svcp’] for s in string_list: result = re.search(’ds-[p](.*)-svcp’, s) print(...
Find strings between 2 substrings with Python
I’m trying to get the string starting with p and between 2 substrings ds and svcp. My approach is like this import re string_list = [‘ds-pfoo-svcp’, ‘ds-abc-pbar-svcp’, ‘ds-abc-ptee-xyz-svcp’] for s in string_list: result = re.search(’ds-[p](.*)-svcp’, s) print(result.group(1)) the output of my expected list : ...
[ "We can use a list comprehension along with re.search here:\nimport re\n\nstring_list = ['ds-pfoo-svcp', 'ds-abc-pbar-svcp','ds-abc-ptee-xyz-svcp']\noutput = [re.search(r'ds(?:-\\w+)*?-p(\\w+)-', x).group(1) for x in string_list]\nprint(output) # ['foo', 'bar', 'tee']\n\n" ]
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074637091_python_regex.txt
Q: Why are the values of the dict in the list is not printing out? So I want to loop across several list each hasving one or multiple dictionaries. For Example given: r = [{"symbol":10},{"symbol":15},{"symbol":25}] h = [{"sy":15},{"sy":23},{"sk":64}] i = [{"sl":45},{"sl":67},{"sl":98}] I want it to print...
Why are the values of the dict in the list is not printing out?
So I want to loop across several list each hasving one or multiple dictionaries. For Example given: r = [{"symbol":10},{"symbol":15},{"symbol":25}] h = [{"sy":15},{"sy":23},{"sk":64}] i = [{"sl":45},{"sl":67},{"sl":98}] I want it to print: Symbol sy sl 10 15 45 15 23 67 25 ...
[ "I figured it out. First I must say that I wasn't getting the input I wanted in python.\nIn python to get the each list of dictionaries output how I wanted I had to do take this approach:\nr = [{\"symbol\":10},{\"symbol\":15},{\"symbol\":25}]\nh = [{\"sy\":15},{\"sy\":23},{\"sy\":64}]\ni = [{\"sl\":45},{\"sl\":67},...
[ 0 ]
[]
[]
[ "flask", "jinja2", "jinjava", "python" ]
stackoverflow_0074636250_flask_jinja2_jinjava_python.txt
Q: Why won't webbrowser module open my html file in my browser I am using the python webbrowser module to try and open a html file. I added a short thing to get code from a website to view, allowing me to store a web-page incase I ever need to view it without wifi, for instance a news article or something else. The c...
Why won't webbrowser module open my html file in my browser
I am using the python webbrowser module to try and open a html file. I added a short thing to get code from a website to view, allowing me to store a web-page incase I ever need to view it without wifi, for instance a news article or something else. The code itself is fairly short so far, so here it is: import requests...
[ "From the webbrowser documentation:\n\nNote that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.\n\nSo it seems that webbrowser can't do what you want. Why did you expect that it would?\...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074636649_python.txt
Q: Why is my elif statement showing a syntax error? My son is learning Python. He's only ten and just starting out and he's gotten stuck. He has a syntax error - can anyone help please? It's on line 18. The error displayed is as follows: File "main.py", line 23 elif player_choice == "2": ^ SyntaxError: invalid syntax...
Why is my elif statement showing a syntax error?
My son is learning Python. He's only ten and just starting out and he's gotten stuck. He has a syntax error - can anyone help please? It's on line 18. The error displayed is as follows: File "main.py", line 23 elif player_choice == "2": ^ SyntaxError: invalid syntax  Please see code below: # choose a chest import ran...
[ "if player_choice == \"1\":\n print(\"The chest contains billions of dollars but the money seems to\")\nprint(\"be engulfed in a strange green light which happens to be\")\nprint(\"radioactive!\")\nprint(\"You start feeling light headed and then die!\")\nprint(\"GAME OVER!\")\n\nOnly the lines that are indented un...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074636539_python.txt