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: Python not iterating over array with for loop Write a program that fills an array of 10 elements with random numbers from 1 to 10, and then swaps the first element with the second, the third with the fourth, and so on. Display the original and transformed array Here is my solution, but Python doesn't want to sort ...
Python not iterating over array with for loop
Write a program that fills an array of 10 elements with random numbers from 1 to 10, and then swaps the first element with the second, the third with the fourth, and so on. Display the original and transformed array Here is my solution, but Python doesn't want to sort the array and it stays the same: from random import...
[ "There's a couple things here:\n1: as @bereal said, range() has a tird optional step argument, and I've never seen a better time to use it. Check out the documentation for range() https://docs.python.org/3/library/functions.html#func-range\n2: I see you reference numbers[-1] even though I think you mean number[-i],...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074629510_python.txt
Q: Flask deprecated before_first_request How to update I'm learning web developing for simple applications and I've created one that uses before_first_request decorator. According with the new release notes, the before_first_request is deprecated and will be removed from Flask 2.3: Deprecated since version 2.2: Will...
Flask deprecated before_first_request How to update
I'm learning web developing for simple applications and I've created one that uses before_first_request decorator. According with the new release notes, the before_first_request is deprecated and will be removed from Flask 2.3: Deprecated since version 2.2: Will be removed in Flask 2.3. Run setup code when creating th...
[ "I don't know if this is answered but for anyone looking for the answer:\nin place of the @app.before_first_request decorated function use the app instance like this:\ni.e.\n# In place of something like this\n@app.before_first_request\ndef create_tables():\n db.create_all()\n ...\n\n# USE THIS INSTEAD\nwith a...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0073570041_flask_python.txt
Q: Library for numerical Integration of a function over a tetrahedron (3D) I am looking for å python library that has a function to solve 3D integrals over a tetrahedron. I would like to be able to input four points on the form (x, y, z) and a function f(x, y, z) where f is a polynomial function. Have only found func...
Library for numerical Integration of a function over a tetrahedron (3D)
I am looking for å python library that has a function to solve 3D integrals over a tetrahedron. I would like to be able to input four points on the form (x, y, z) and a function f(x, y, z) where f is a polynomial function. Have only found functions that accepts integration boundaries that go from function to function, ...
[ "You can use the quadpy library to integrate a function over a tetrahedron.\nBut for a polynomial function f, it is possible to calculate the exact value of the integral of f over a tetrahedron (more generally over a simplex in any dimension). This method is implemented in the R package SimplicialCubature. This pap...
[ 0 ]
[]
[]
[ "finite_element_analysis", "math", "numerical_integration", "python" ]
stackoverflow_0074345108_finite_element_analysis_math_numerical_integration_python.txt
Q: accessing values incorrectly from list in python I have two example files. myheader.h #define MACRO1 42 #define lang_init () c_init() #define min(X, Y) ((X) < (Y) ? (X) : (Y)) and pyparser.py from pyparsing import * # define the structure of a macro definition (the empty term is used # to advance to the next ...
accessing values incorrectly from list in python
I have two example files. myheader.h #define MACRO1 42 #define lang_init () c_init() #define min(X, Y) ((X) < (Y) ? (X) : (Y)) and pyparser.py from pyparsing import * # define the structure of a macro definition (the empty term is used # to advance to the next non-whitespace character) macroDef = "#define" + Word(...
[ "Question, what is the value of len(res).\nIn python when you have a list inside of a list you can use a second indexer to access the elements inside of it. So for example if the first element res[0] was a list, you could do res[0][0] to get '#define'.\nHowever, your output that you have shown is in a different for...
[ 0 ]
[]
[]
[ "list", "pyparsing", "python" ]
stackoverflow_0074629430_list_pyparsing_python.txt
Q: Extract value from a dataframe column of dictionary of lists lists and create a new column I have a dataframe with one of the columns as a list and another column as a dictionary. However, this is not consistent. It could be a single element or NULL too df = pd.DataFrame({'item_id':[1,1,1,2,3,4,4], 'shop_id':['S1'...
Extract value from a dataframe column of dictionary of lists lists and create a new column
I have a dataframe with one of the columns as a list and another column as a dictionary. However, this is not consistent. It could be a single element or NULL too df = pd.DataFrame({'item_id':[1,1,1,2,3,4,4], 'shop_id':['S1','S2','S3','S2','S3','S1','S2'], 'price_list':["{'10':['S1','S2'], '20':['S3'], '30':['S4']}","...
[ "I would use a list comprehension with a generator to search for the key from the value:\ndf['price'] = [next((k for k,l in d.items() if s in l), None)\n if isinstance(d, dict) else d\n for s, d in zip(df['shop_id'], df.pop('price_list'))]\n\nNB. pop removes the \"price_list\" column in ...
[ 3 ]
[]
[]
[ "dataframe", "dictionary", "list_comprehension", "pandas", "python" ]
stackoverflow_0074629686_dataframe_dictionary_list_comprehension_pandas_python.txt
Q: F string inside For Loop I dont understand why this doesn't work. I am trying to do a For Loop to save my error measures: error = [] naive_list = list(['24', '168', 'standard', 'custom']) for i in naive_list: for j in range(1,5): rmse = mean_squared_error(df_test["f'Price_REG{j}'"], f'df_test_{i}'["f'P...
F string inside For Loop
I dont understand why this doesn't work. I am trying to do a For Loop to save my error measures: error = [] naive_list = list(['24', '168', 'standard', 'custom']) for i in naive_list: for j in range(1,5): rmse = mean_squared_error(df_test["f'Price_REG{j}'"], f'df_test_{i}'["f'Price_REG{j}'"], squared=False)...
[ "This df_test[\"f'Price_REG{j}'\"] literally means the string df_test[\"f'Price_REG{j}'\"]. It will not be evaluated further. It's a string-literal.\nInstead df_test[f'Price_REG{j}'] WOULD be evaluated and would return whatever is in Price_REG{j} and then fetch the column of the same name from the df.\nThat being s...
[ 0 ]
[]
[]
[ "for_loop", "pandas", "python" ]
stackoverflow_0074629389_for_loop_pandas_python.txt
Q: how to color text with condition in django? I have a django app and I want to color some text, if that text is true in dictionary. So I have this method:views.py def data_compare2(request): template = get_template("main/data_compare.html") dict2 = {"appel": 3962.00, "waspeen": 3304.07, "ananas":24} co...
how to color text with condition in django?
I have a django app and I want to color some text, if that text is true in dictionary. So I have this method:views.py def data_compare2(request): template = get_template("main/data_compare.html") dict2 = {"appel": 3962.00, "waspeen": 3304.07, "ananas":24} context = {"dict2": dict2} res = dict((v,k) for...
[ "I would separate fruits from the condition, inside the context. Transform the condition into a list to check on the template.\nviews.py\ndef data_compare2(request):\n fruits = {\"appel\": 3962.00, \"waspeen\": 3304.07, \"ananas\":24,}\n condition = ['appel', 'ananas']\n\n context = {\n 'fruits': fr...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074629358_django_python.txt
Q: Why isn't my .Dockerignore file ignoring files? When I build the container and I check the files that should have been ignored, most of them haven't been ignored. This is my folder structure. Root/ data/ project/ __pycache__/ media/ static/ app/ __pycache__/ migrations/ templates/ ...
Why isn't my .Dockerignore file ignoring files?
When I build the container and I check the files that should have been ignored, most of them haven't been ignored. This is my folder structure. Root/ data/ project/ __pycache__/ media/ static/ app/ __pycache__/ migrations/ templates/ .dockerignore .gitignore .env docker-compose...
[ "You're actually injecting your source code using volumes:, not during the image build, and this doesn't honor .dockerignore.\nRunning a Docker application like this happens in two phases:\n\nYou build a reusable image that contains the application runtime, any OS and language-specific library dependencies, and the...
[ 6, 0 ]
[]
[]
[ "django", "docker", "dockerignore", "python" ]
stackoverflow_0069297600_django_docker_dockerignore_python.txt
Q: Trouble with while true and if function in python The question is "Ask user to enter age, Check if age entered is > 0. if age less than 12 ticket price is 12 dollars otherwise the ticket price is 18 dollars" def main() : n = int(input("Insert your age : ")) #asking for users age while True : # checking if ...
Trouble with while true and if function in python
The question is "Ask user to enter age, Check if age entered is > 0. if age less than 12 ticket price is 12 dollars otherwise the ticket price is 18 dollars" def main() : n = int(input("Insert your age : ")) #asking for users age while True : # checking if users age is more than 0 if n > 0 : ...
[ "Just check if the number is less than or equal to 0 instead of a while loop\ndef main() :\n n = int(input(\"Insert your age : \")) #asking for users age\n if n <= 0:\n print(\"Please enter an age greater than 0\")\n elif price_checker(n) :\n print(\"Price is 12 dollars\")\n else :\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074629827_python.txt
Q: using map() with dictionary I have a dictionary. prices = {'n': 99, 'a': 99, 'c': 147} using map () I need to receive new dictionary : def formula(value): value = value -value * 0.05 return value new_prices = dict(map(formula, prices.values())) but it doesn't work TypeError: cannot convert dictionary up...
using map() with dictionary
I have a dictionary. prices = {'n': 99, 'a': 99, 'c': 147} using map () I need to receive new dictionary : def formula(value): value = value -value * 0.05 return value new_prices = dict(map(formula, prices.values())) but it doesn't work TypeError: cannot convert dictionary update sequence element #0 to a se...
[ "you can do this using zip and map\nnew_prices = dict(zip(prices, map(formula, prices.values())))\n\n", "Use dictionary comprehension:\nnew_prices = {k: formula(prices[k]) for k in prices}\nprint(new_prices)\n# {'n': 94.05, 'a': 94.05, 'c': 139.65}\n\n", "Use map() with a helper lambda to create new dict\nnew_p...
[ 6, 2, 1, 0 ]
[ "When you create a map, you get a map object. It's nice to have an helper function to iterate through this object.\ndef print_results(map_object):\n for i in map_object:\n print(i)\n\ndef formula(value):\n return value * 0.95 # one-liner\n\nm = map(formula, prices.values())\n\nprint_results(m)\n\n# out...
[ -2 ]
[ "dictionary", "list", "python" ]
stackoverflow_0074629567_dictionary_list_python.txt
Q: How do I read the pictures in the file in order? I want to read the pictures in a file in the order they are in the file. But when I read it with python it reads mixed. I don't want it sorted. How can I fix this? def read_img(path): st = os.path.join(path, "*.JPG") st_ = os.path.join(path, "*.jpg...
How do I read the pictures in the file in order?
I want to read the pictures in a file in the order they are in the file. But when I read it with python it reads mixed. I don't want it sorted. How can I fix this? def read_img(path): st = os.path.join(path, "*.JPG") st_ = os.path.join(path, "*.jpg") for filename in glob.glob(st): pr...
[ "If you want the list populated in the order that os.listdir() reveals files then:\nfrom os import listdir\nfrom os.path import join, splitext\n\nBASE = '.' # directory to be parsed\nEXTS = {'jpg', 'JPG', 'jpeg', 'JPEG'} # file extensions of interest\n\ndef ext(p):\n _, ext = splitext(p)\n if ext:\n re...
[ 0 ]
[]
[]
[ "image", "python", "readfile" ]
stackoverflow_0074629247_image_python_readfile.txt
Q: what am I missing in this def (type Error : int object is not callable), beginner question Wrote this function but when I want to call it it doesnt work, gives error int object is not callable. def pole_trojkata(xa, ya, xb, yb, xc, yc ): p = 1/2*abs((xb - xa)(yc - ya) - (yb - ya)(xc - xa)) return p pole_tr...
what am I missing in this def (type Error : int object is not callable), beginner question
Wrote this function but when I want to call it it doesnt work, gives error int object is not callable. def pole_trojkata(xa, ya, xb, yb, xc, yc ): p = 1/2*abs((xb - xa)(yc - ya) - (yb - ya)(xc - xa)) return p pole_trojkata(2, 3, 1, 3, 2, 5)
[ "you forget * for multiplication\ndef pole_trojkata(xa, ya, xb, yb, xc, yc):\n return abs((xb-xa)*(yc-ya)-(xc-xa)*(yb-ya))/2\n\npole_trojkata(2, 3, 1, 3, 2, 5)\n\noutput:\n1.0\n\n" ]
[ 0 ]
[]
[]
[ "area", "function", "parameters", "python" ]
stackoverflow_0074629876_area_function_parameters_python.txt
Q: How can I do a python API request with the body? if I do a POST request on Postman with my local API server it works: But if I try in python with this syntax it doesn't work: requests.post('http://127.0.0.1:5001/api/v0/add', data={'path': 'test'}).text it returns: "file argument 'path' is required\n" Can you plea...
How can I do a python API request with the body?
if I do a POST request on Postman with my local API server it works: But if I try in python with this syntax it doesn't work: requests.post('http://127.0.0.1:5001/api/v0/add', data={'path': 'test'}).text it returns: "file argument 'path' is required\n" Can you please explain me why it doesn't work?
[ "If I pass the files parameter instead of data or json, it works!\nrequests.post(url = api_url, files={'path':'test'}).text\n\n", "The issue is that using data on requests.post defaults to application/x-www-form-urlencoded while your application wants multipart/form-data. Try using files instead of data:\nrequest...
[ 0, 0 ]
[]
[]
[ "api", "postman", "python", "python_requests" ]
stackoverflow_0074629233_api_postman_python_python_requests.txt
Q: How can I rotate the bounding boxes from findcontours function in Python OpenCV? I have the following image: I am using OpenCV to find the contours in this image in order to separate the "122" into "1","2", and "2". I am using OCR to classify the numbers after. The code I am using to do this is as follows: invert...
How can I rotate the bounding boxes from findcontours function in Python OpenCV?
I have the following image: I am using OpenCV to find the contours in this image in order to separate the "122" into "1","2", and "2". I am using OCR to classify the numbers after. The code I am using to do this is as follows: invert = cv2.bitwise_not(image) gray = cv2.cvtColor(invert, cv2.COLOR_BGR2GRAY) blurred = cv...
[ "It's hard to give specific recommendations without understanding how the bounding box will be used downstream.\nEasiest method would be to use the boxPoints function. That will return the coordinates of the corners for the minimum bounding box around the contour. Alternatively, you could fit a line to the contour ...
[ 0 ]
[]
[]
[ "mnist", "opencv", "python" ]
stackoverflow_0074629780_mnist_opencv_python.txt
Q: creating a config file with configparser with a custom file path i've been trying to create a way to generate config files for a help tool that i've been making. i would like to have the code create a config file in a specific default location that is dependant on the current user on which the code is ran. this is...
creating a config file with configparser with a custom file path
i've been trying to create a way to generate config files for a help tool that i've been making. i would like to have the code create a config file in a specific default location that is dependant on the current user on which the code is ran. this is my basic setup for the code i've been trying to find a way to have us...
[ "You need to use\nwith open(r'C:\\Users\\'' + system_user + '\\Documents\\5e_helper\\character cofig', 'w') as configfile:\n testconfig.write(configfile)\n\nError is happening because you are using an escape sequence of \\' in 'C:\\Users\\'. You can also avoid it using double quotes around path string.\nBTW good...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074629624_python.txt
Q: error when exiting tkinter window update and update_idletasks I have a problem with functions update() and update_idletasks() in tkinter they work fine except that when closing the window, either by cliking the "Exit" button or the "x" to close the window in Windows, the following error lines show up: Traceback (...
error when exiting tkinter window update and update_idletasks
I have a problem with functions update() and update_idletasks() in tkinter they work fine except that when closing the window, either by cliking the "Exit" button or the "x" to close the window in Windows, the following error lines show up: Traceback (most recent call last): File "D:\Python\VisualStudio\test4\test4\te...
[ "I want to display the characters coming asynchronously from a wifi on a Tkinter window\nAfter several problems I was able to come to the following solution.\nMany thanks to JRiggles and Bryan Oakles\nThis is my source code:\nimport tkinter as tk\n\ndef my_async(): # this simulates my asynchronous function, i will ...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074618786_python_tkinter.txt
Q: ERROR: admin.E108 and admin.E116 Django Framework Python <class 'blog.admin.CommentAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'active', which is not a callable, an attribute of 'CommentAdmin', or an attribute or method on 'blog.Comment'. <class 'blog.admin.CommentAdmin'>: (admin.E116) The value...
ERROR: admin.E108 and admin.E116 Django Framework Python
<class 'blog.admin.CommentAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'active', which is not a callable, an attribute of 'CommentAdmin', or an attribute or method on 'blog.Comment'. <class 'blog.admin.CommentAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'active', which does not refer ...
[ "status = models.IntegerField(choices=STATUS, default=0)\n\nshould be:\nactive = models.IntegerField(choices=STATUS, default=0)\n\n", "The message is clear 'active' is not a field\nclass Comment(models.Model):\n post = models.ForeignKey(\n Post, on_delete=models.CASCADE, related_name='comments')\n name ...
[ 0, 0 ]
[]
[]
[ "blogs", "django", "html", "python" ]
stackoverflow_0074629902_blogs_django_html_python.txt
Q: why does my for loop keep on removing the append element so I am trying to create a list that have different list as it element the for loop bellow will extend an element to the bag then append it to the list bag and finally remove the extended element to repeat the cyclec the bag contains these elements ['B', 'D...
why does my for loop keep on removing the append element
so I am trying to create a list that have different list as it element the for loop bellow will extend an element to the bag then append it to the list bag and finally remove the extended element to repeat the cyclec the bag contains these elements ['B', 'D'] and the rf contains these elements ['C', 'A', 'G', 'E'] lis...
[ "You can accomplish what you want with a list comprehension.\nlist_bag = [bag + [item] for item in rf]\n\n" ]
[ 0 ]
[]
[]
[ "append", "extend", "list", "python" ]
stackoverflow_0074629918_append_extend_list_python.txt
Q: Python not running from terminal I already have 2 versions of python installed on my windows, and the interpreters work well, but when I try to run python from cmd or PowerShell, I'm asked to get python again from windows store, how do I fix this I opened cmd and PowerShell and typed python expecting it to open th...
Python not running from terminal
I already have 2 versions of python installed on my windows, and the interpreters work well, but when I try to run python from cmd or PowerShell, I'm asked to get python again from windows store, how do I fix this I opened cmd and PowerShell and typed python expecting it to open the python interpreter and I made a .py ...
[ "You need to add python path to the path on the environment variables.\nWhat you should do:\n\nRight click \"my computer\"\nGo to \"properties\"\nclick on \"advanced system settings\"\nGo to \"environment variables\"\nOn system Variables look for \"path\" (if there isn't one create one)\nClick on \"path\" and click...
[ 0 ]
[]
[]
[ "cmd", "powershell", "python", "windows_store" ]
stackoverflow_0074629889_cmd_powershell_python_windows_store.txt
Q: tuple unpacking in a list cannot be performed Basically the question is to see if a number is a t-prime number or not (t-prime number has 3 distinct positive divisors), I have written the code it gives me a list like below: [(4, 1), (4, 2), (4, 4), (5, 1), (5, 5), (6, 1), (6, 2), (6, 3), (6, 6)] I need a func to ...
tuple unpacking in a list cannot be performed
Basically the question is to see if a number is a t-prime number or not (t-prime number has 3 distinct positive divisors), I have written the code it gives me a list like below: [(4, 1), (4, 2), (4, 4), (5, 1), (5, 5), (6, 1), (6, 2), (6, 3), (6, 6)] I need a func to return the number of j in each i value (i,j) in the...
[ "It looks like your goal is to count the number of tuples with a given first element. Try this:\ncounter = {}\nvalues = [(4, 1), (4, 2), (4, 4), (5, 1), (5, 5), (6, 1), (6, 2), (6, 3), (6, 6)]\n\nfor value, divisor in values:\n current = counter.get(value, 0) + 1\n counter[value] = current\n\nThen, to get the...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074629967_python.txt
Q: How to compile Tkinter as an executable for MacOS? I'm trying to compile a Tkinter app as an executable for MacOs. I tried to use py2app and pyinstaller. I almost succeed using py2app, but it returns the following error: Traceback The Info.plist file must have a PyRuntimeLocations array containing string values fo...
How to compile Tkinter as an executable for MacOS?
I'm trying to compile a Tkinter app as an executable for MacOs. I tried to use py2app and pyinstaller. I almost succeed using py2app, but it returns the following error: Traceback The Info.plist file must have a PyRuntimeLocations array containing string values for preferred Python runtime locations. These strings sh...
[ "The problem was that you need to give an executable path for the python framework you have on your MacOs. So I modify the setup.py\nsetup.py\nfrom setuptools import setup\n\nclass CONFIG:\n VERSION = 'v1.0.1'\n platform = 'darwin-x86_64'\n executable_stub = '/opt/homebrew/Frameworks/Python.framework/Versi...
[ 0 ]
[]
[]
[ "macos", "py2app", "pyinstaller", "python", "tkinter" ]
stackoverflow_0074619476_macos_py2app_pyinstaller_python_tkinter.txt
Q: Can I make PyInstaller optimize the compilation? When I use PyInstaller, it builds my modules as .pyc files. But I'd prefer it to run the compilation with -OO to optmize and remove docstrings. Is this possible? A: Since pyinstaller is a Python script, it is sufficient to run it with optimisation activated: e.g...
Can I make PyInstaller optimize the compilation?
When I use PyInstaller, it builds my modules as .pyc files. But I'd prefer it to run the compilation with -OO to optmize and remove docstrings. Is this possible?
[ "Since pyinstaller is a Python script, it is sufficient to run it with optimisation activated: e.g.\nPYTHONOPTIMIZE=2 pyinstaller script.py\n\nso that during bundling .pyo files are created instead of .pyc\n", "i would like to add that in cmd.exe you can type\n>set PYTHONOPTIMIZE=1\n>pyinstaller skript.py \n\nthe...
[ 4, 0 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0036401229_pyinstaller_python.txt
Q: How to extract the output froman NLP model to a dataframe? I have trained an NLP Model (NER) and I have results in the below format: for text, _ in TEST_DATA: doc = nlp(text) print([(ent.text, ent.label_) for ent in doc.ents]) #Output [('1131547', 'ID'), ('12/9/2019', 'Date'), ('USA', 'ShippingAddress')] ...
How to extract the output froman NLP model to a dataframe?
I have trained an NLP Model (NER) and I have results in the below format: for text, _ in TEST_DATA: doc = nlp(text) print([(ent.text, ent.label_) for ent in doc.ents]) #Output [('1131547', 'ID'), ('12/9/2019', 'Date'), ('USA', 'ShippingAddress')] [('567456', 'ID'), ('Hills', 'ShippingAddress')] #I need the ou...
[ "In order to import the data into a Pandas dataframe, you can use\ndata_array = []\n\nfor text, _ in TEST_DATA:\n doc = nlp(text)\n data_array.append({ent.label_:ent.text for ent in doc.ents})\n\nimport pandas as pd\ndf = pd.DataFrame.from_dict(data_array)\n\nThe test result:\n>>> pd.DataFrame.from_dict(data_...
[ 1 ]
[]
[]
[ "dictionary", "named_entity_recognition", "nlp", "python", "spacy" ]
stackoverflow_0074629474_dictionary_named_entity_recognition_nlp_python_spacy.txt
Q: Python regex to get the closest match without duplicated content What I need I have a list of img src link. Here is an example: https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg&nocache=1 https://studiocake.kiev.ua/wp...
Python regex to get the closest match without duplicated content
What I need I have a list of img src link. Here is an example: https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/uploads/photo_2020-12-27_12-18-00-2-333x444.jpg&nocache=1 https://studiocake.kiev.ua/wp-content/webpc-passthru.php?src=https://studiocake.kiev.ua/wp-content/...
[ "You can let a greedy .* consume the starting match and capture the latter.\nimport re\n\nmatches = re.findall(r\"(?i).*\\b(studiocake\\.kiev\\.ua\\S*\\b(?:jpeg|png|jpg))\\b\", s)\n\nSee this demo at regex101 (matches in group 1) or a Python demo at tio.run\n\nInside used \\S* to match any amount of characters othe...
[ 4, 3, 0 ]
[]
[]
[ "extract", "python", "regex", "string", "url" ]
stackoverflow_0074628727_extract_python_regex_string_url.txt
Q: Infinite continued Fraction in Python I am currently trying to implement a function that approximate the e constant in Python. from fractions import Fraction def fractionalSum(number, array): def inside(index, place): if place >= 0: return Fraction(1, index + place) else: ...
Infinite continued Fraction in Python
I am currently trying to implement a function that approximate the e constant in Python. from fractions import Fraction def fractionalSum(number, array): def inside(index, place): if place >= 0: return Fraction(1, index + place) else: return Fraction(1, index) if numbe...
[ "I haven't investigated what exactly you may have done wrong, but a recursive implementation of Continued Fraction should be fairly simple, so I'm suggesting this instead:\nONE = Fraction(1, 1)\n\ndef continuedFraction(array):\n return _continuedFraction(array, 0)\n\ndef _continuedFraction(array, index):\n re...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074629996_python_python_3.x.txt
Q: Get folder and files Google Drive API with Shared Device and Service Account I'm working with a Google Service Account, I have access to Google Drive API and a Shared Unit. I need to get access to all the files and folders from a Shared Unit. I tried a lot of different ways to do this. drive_service.files().list( ...
Get folder and files Google Drive API with Shared Device and Service Account
I'm working with a Google Service Account, I have access to Google Drive API and a Shared Unit. I need to get access to all the files and folders from a Shared Unit. I tried a lot of different ways to do this. drive_service.files().list( q = f"'{parent_folder}' in parents", spaces = 'drive', supportsTeamDri...
[ "I figure it out.\nAn additional parameter had to be passed:\nincludeItemsFromAllDrives = True,\nsupportsAllDrives = True\n\nThis works:\ndrive_service.files().list(\n q = f\"'{parent_folder}' in parents\",\n spaces = 'drive',\n includeItemsFromAllDrives = True,\n supportsAllDrives = True\n).execute()\n...
[ 0 ]
[]
[]
[ "google_drive_api", "google_drive_shared_drive", "python" ]
stackoverflow_0074629750_google_drive_api_google_drive_shared_drive_python.txt
Q: Getting TransactionManagementError on bulk_create with mysql db I'm trying to create a few objects using Django's bulk_create but I'm getting TransactionManagementError. Django is on django-2.2.24 Mysql is running via docker and I'm using mariadb:10.10.2. Traceback (most recent call last): File "/Users/xyz/Docum...
Getting TransactionManagementError on bulk_create with mysql db
I'm trying to create a few objects using Django's bulk_create but I'm getting TransactionManagementError. Django is on django-2.2.24 Mysql is running via docker and I'm using mariadb:10.10.2. Traceback (most recent call last): File "/Users/xyz/Documents/dev/django-proj/sliphy/manage.py", line 21, in <module> main...
[ "Probably you should wrap your function with transaction.atomic, here is example from the django docs:\nfrom django.db import transaction\n@transaction.atomic\ndef viewfunc(request):\n # This code executes inside a transaction.\n do_stuff()\n\nand as a context manager:\nfrom django.db import transaction\n\nde...
[ 0 ]
[]
[]
[ "django", "mysql", "python", "python_3.x" ]
stackoverflow_0074569599_django_mysql_python_python_3.x.txt
Q: KivyMD: ToolBar doesn't work on Android. App crashes I'm stuck with a strange problem. My app works perfect with kivymd toolbar MDTopAppBar on Windows (after compiling with pyinstaller too) and Ubuntu. But, when I try to add this element even in the simpliest app and create .apk using buildozer, my app crashes imm...
KivyMD: ToolBar doesn't work on Android. App crashes
I'm stuck with a strange problem. My app works perfect with kivymd toolbar MDTopAppBar on Windows (after compiling with pyinstaller too) and Ubuntu. But, when I try to add this element even in the simpliest app and create .apk using buildozer, my app crashes immediatly after launch. Here are examples of main.py and mai...
[ "For anyone out there facing this, there has been an issue on the kivymd github repo about this and this problem is caused by changes in the latest opengl version and changes in sdl versions. The best thing to do for now is to use kivymd==1.0.2 in the requirements while compiling apk and it should work fine.\n" ]
[ 0 ]
[]
[]
[ "android", "buildozer", "kivy", "kivymd", "python" ]
stackoverflow_0074379030_android_buildozer_kivy_kivymd_python.txt
Q: How to change sphinx's _static folder output location? I have several projects that use the readthedocs theme that I'm hoping to can share a single _static folder location. It's two levels up at ../../_static. Is it possible to set this easily? What I've tried: various conf.py settings such as static_file_path ch...
How to change sphinx's _static folder output location?
I have several projects that use the readthedocs theme that I'm hoping to can share a single _static folder location. It's two levels up at ../../_static. Is it possible to set this easily? What I've tried: various conf.py settings such as static_file_path changing all the _static paths in the template files to ../../...
[ "Adding .nojekyll file, as sometimes suggested, only tells github not to apply it's own templates.\nAnyway, I figured this out a long time ago. Just change a couple of paths in config file and change all the paths in layout.html. There maybe other ways, but that method works for me. Here's a live example where 10 ...
[ 1, 0 ]
[]
[]
[ "path", "python", "python_sphinx" ]
stackoverflow_0067324605_path_python_python_sphinx.txt
Q: 'WSGIRequest' object has no attribute 'htmx' Hi just looking for some help at solving this error in Django whilst trying to call a view that to accept a htmx request. The final result is to display a popup Modal of images from a Gallery when a thumbnail is clicked. HTMX installed via script in head. View if r...
'WSGIRequest' object has no attribute 'htmx'
Hi just looking for some help at solving this error in Django whilst trying to call a view that to accept a htmx request. The final result is to display a popup Modal of images from a Gallery when a thumbnail is clicked. HTMX installed via script in head. View if request.htmx: slug = request.GET.get('slug'...
[ "This error mostly occurs if you haven't included django-htmx in the settings.py.\nTry making the below changes and see if it works :\n\nAdd \"django_htmx.middleware.HtmxMiddleware\" to the MIDDLEWARE.\nAdd \"django_htmx\" to the INSTALLED_APPS.\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_views", "htmx", "python" ]
stackoverflow_0073682746_django_django_views_htmx_python.txt
Q: Evaluating many random states in python I am working with python and I have a code that looks like this. for index in range (1, 5): Rndm1 = RFC(n_estimators=500, random_state= index) Rndm1.fit(X_train, y_train) y_pred = Rndm1.predict(x_test) print("selected random state:", index) print("Accuracy:", accuracy_score(...
Evaluating many random states in python
I am working with python and I have a code that looks like this. for index in range (1, 5): Rndm1 = RFC(n_estimators=500, random_state= index) Rndm1.fit(X_train, y_train) y_pred = Rndm1.predict(x_test) print("selected random state:", index) print("Accuracy:", accuracy_score(y_test, y_pred)) And I get a result like thi...
[ "Accumulate the intermediate accuracies into a list, then take the mean of the list:\nimport numpy as np\n\naccuracies = []\n\nfor index in range(1, 5):\n Rndm1 = RFC(n_estimators=500, random_state= index)\n Rndm1.fit(X_train, y_train)\n y_pred = Rndm1.predict(x_test)\n accuracies.append(accuracy_score(...
[ 1 ]
[]
[]
[ "python", "random_forest" ]
stackoverflow_0074620191_python_random_forest.txt
Q: Import Spacy Error "cannot import name dataclass_transform" I am working on a jupyter notebook project which should use spacy. I already used pip install to install spacy in anaconda prompt. However, when I tried to import spacy, it gives me the follwing error. I wonder what the problem is and what I can do to sol...
Import Spacy Error "cannot import name dataclass_transform"
I am working on a jupyter notebook project which should use spacy. I already used pip install to install spacy in anaconda prompt. However, when I tried to import spacy, it gives me the follwing error. I wonder what the problem is and what I can do to solve that. --------------------------------------------------------...
[ "You may have to try the below.\npip install -U pip setuptools wheel\npip install -U spacy\npython -m spacy download en_core_web_sm\nAfter installation restart the kernal if you are using jupyter notebook/lab\nFor me Issue resolved.\n" ]
[ 0 ]
[]
[]
[ "import", "nlp", "python", "python_packaging", "spacy" ]
stackoverflow_0074451907_import_nlp_python_python_packaging_spacy.txt
Q: ValueError: y should be a 1d array, got an array of shape (295, 9) instead I have a sentiment dataset about opinions on Twitter after I process them and I label these sentiments and I want to share the data based on the sentiments I labeled. now when I share it using the model train_test_split code it works when I...
ValueError: y should be a 1d array, got an array of shape (295, 9) instead
I have a sentiment dataset about opinions on Twitter after I process them and I label these sentiments and I want to share the data based on the sentiments I labeled. now when I share it using the model train_test_split code it works when I match it to the predict stage model using naive bayes there is an error value V...
[ "According to the documentation https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html\n\nfit(X, y, sample_weight=None) Fit Naive Bayes classifier according to\nX, y.\n\n\nyarray-like of shape (n_samples,) Target values.\n\ny should be a one-dimensional array\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "naivebayes", "python", "sentiment_analysis", "tf_idf" ]
stackoverflow_0074630204_machine_learning_naivebayes_python_sentiment_analysis_tf_idf.txt
Q: Passing Line Break "\n" or "" from the Main Function to Jinja I have a list with the name of colors: colors = [red, green, blue] And I want it to be printed out on my web page as red green blue I tried this by using an argument in my HTML template {{colors_out}}, where I pass a string with "\n" to it as follows...
Passing Line Break "\n" or "" from the Main Function to Jinja
I have a list with the name of colors: colors = [red, green, blue] And I want it to be printed out on my web page as red green blue I tried this by using an argument in my HTML template {{colors_out}}, where I pass a string with "\n" to it as follows: colors_out = "" for i in range(len(colors)): colors_out += (st...
[ "One way, which you can try to use a for loop in Jinja2 in your HTML.\nYou can simply pass a list to the HTML and then use for loop in Jinja2 along with the tags to print the outputs on seperate lines -\nFor example in your case -\nIn your Flask code -\nfrom flask import Flask, render_template, request\napp = Flas...
[ 1 ]
[]
[]
[ "flask", "html", "jinja2", "python", "python_3.x" ]
stackoverflow_0074629901_flask_html_jinja2_python_python_3.x.txt
Q: how to check and change elements of array in 2d array? I started a game project(small project) on Python3 but i dunno how to iterate 2d array and change 'em. IS IT POSSIBLE TO write a game logic (Tic-Tac-Toe ''3 symbols on one line wins'') with 2d array with 0 index and if it changed to 'O' or 'X' replace curren...
how to check and change elements of array in 2d array?
I started a game project(small project) on Python3 but i dunno how to iterate 2d array and change 'em. IS IT POSSIBLE TO write a game logic (Tic-Tac-Toe ''3 symbols on one line wins'') with 2d array with 0 index and if it changed to 'O' or 'X' replace current iterating element index to one or two ?!. in two words - m...
[ ">>> a= []\n>>> a.append(9)\n>>> print(a.append(9))\nNone\n>>>\n\nWhat's going on here? Well, list.append returns None. As fo most functions which mutate data rather than generating new values. You can see this in your code with:\n[[mtrx[i][j].append(0) for i in range(3)] for j in range(3)]\n\nThose indices also do...
[ 0 ]
[]
[]
[ "python", "python_3.8", "tic_tac_toe" ]
stackoverflow_0074630144_python_python_3.8_tic_tac_toe.txt
Q: How to write string to csv that contain escape chars? I am trying to write a list of strings to csv using csv.writer. writer = csv.writer(f) writer.writerow(some_text) However, some of the strings contain a random escape character, which seems to be causing the following error : _csv.Error: need to escape, but n...
How to write string to csv that contain escape chars?
I am trying to write a list of strings to csv using csv.writer. writer = csv.writer(f) writer.writerow(some_text) However, some of the strings contain a random escape character, which seems to be causing the following error : _csv.Error: need to escape, but no escapechar set I've tried using the escapechar option in ...
[ "What format do you want to achieve in the end? Writing this to a csv seems to be leading to some odd outcomes anyway.\nIn any case, both of these code work for me without errors, both giving slightly different results with respect to escape characters.\nWith normal string:\nimport csv\n\nwith open('test2.csv', 'w'...
[ 0 ]
[]
[]
[ "csv", "python", "string" ]
stackoverflow_0074630046_csv_python_string.txt
Q: how to make discord emoji with hyperlink with python I'm trying to make an emoji with click, but I don't know how to do it... this is the code i am using: import discord from discord.ext import commands bot = commands.Bot(command_prefix='!', description="help") bot.remove_command("help") @bot.command() asy...
how to make discord emoji with hyperlink with python
I'm trying to make an emoji with click, but I don't know how to do it... this is the code i am using: import discord from discord.ext import commands bot = commands.Bot(command_prefix='!', description="help") bot.remove_command("help") @bot.command() async def emojibot(ctx): #Comando a decir await ctx.send(...
[ "As the message you are sending isn't an embed but is plain text, I believe this should work:\nasync def emojibot(ctx): #Comando a decir\n await ctx.send('[:HabboHotel:](https://habbo.es)') \n\n" ]
[ 0 ]
[]
[]
[ "emoji", "python" ]
stackoverflow_0074629465_emoji_python.txt
Q: why doesn't pandas column get overwritten by other column? I am trying to overwrite the row values for column A and B in df1 with the values from df2. My dfs look as such: df1 'A' 'B' 'C' 23 0 cat orange 24 0 cat orange 25 0 cat orange df2 'A' 'B' 'C' 56 2 dog yellow 64 4 ...
why doesn't pandas column get overwritten by other column?
I am trying to overwrite the row values for column A and B in df1 with the values from df2. My dfs look as such: df1 'A' 'B' 'C' 23 0 cat orange 24 0 cat orange 25 0 cat orange df2 'A' 'B' 'C' 56 2 dog yellow 64 4 rat orange 85 2 bat red The indices here are different...
[ "Cause df1[['A','B']] is a new DataFrame, try:\ndf1.loc[25, ['A','B']] = df2[['A','B']].loc[64]\n\n", "df1.loc[25, ['A', 'B']] = df2.loc[64, ['A', 'B']]\n\n" ]
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074630226_pandas_python.txt
Q: Creating multiple dataframes from a stored procedure I'm working with a stored procedure in which I pass it a start and end date and it returns data. Im passing it ten different dates and making ten calls to it, see below: match1 = sp_data(startDate = listOfDates[0], endDate=listOfDates[0]) match2 = sp_data(startD...
Creating multiple dataframes from a stored procedure
I'm working with a stored procedure in which I pass it a start and end date and it returns data. Im passing it ten different dates and making ten calls to it, see below: match1 = sp_data(startDate = listOfDates[0], endDate=listOfDates[0]) match2 = sp_data(startDate = listOfDates[1], endDate=listOfDates[1]) match3 = sp_...
[ "You could use a list comprehension to make a list of matches:\nmatches = [sp_data(startDate=trade_date, endDate=trade_date) for trade_date in listOfDates]\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "loops", "pandas", "python" ]
stackoverflow_0074630195_dataframe_loops_pandas_python.txt
Q: Loopin a comprehension of list I have a list: lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]] And i want to turn it into: new_lst = [['X', 1, 2, 3], ['A', 1, 2, 3] ['Y', 1, 2, 3], ['B', 1, 2, 3], ['Z', 1, 2, 3], ['C', 1, 2, 3]] I've got it to work with a a single one of them with ...
Loopin a comprehension of list
I have a list: lst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]] And i want to turn it into: new_lst = [['X', 1, 2, 3], ['A', 1, 2, 3] ['Y', 1, 2, 3], ['B', 1, 2, 3], ['Z', 1, 2, 3], ['C', 1, 2, 3]] I've got it to work with a a single one of them with comprehension. lst2 = [['X', 'Y'], ...
[ "You can unpack each sublist into the list of letters and the \"rest\", then iterate over the letters to build new sublists from a letter and the rest.\nnew_lst = [[c, *rest] for letters, *rest in lst for c in letters]\n\n", "You're only missing the loop to iterate through the lst\nfrom pprint import pprint\n\n\n...
[ 3, 2, 2 ]
[ "You could just replace the first term right with the first letter right?\nlst = [[['X', 'A'], 1, 2, 3], [['Y', 'B'], 1, 2, 3], [['Z', 'C'], 1, 2, 3]]\n\nfor item in lst:\n item[0] = item[0][0];\n\nprint(lst)\n\n" ]
[ -1 ]
[ "list", "list_comprehension", "python" ]
stackoverflow_0074630132_list_list_comprehension_python.txt
Q: Apply rank with percentile, on python polars, for a set of columns on a dataframe df = pl.DataFrame( { "era": ["01", "01", "02", "02", "03", "03"], "pred1": [1, 2, 3, 4, 5,6], "pred2": [2,4,5,6,7,8], "pred3": [3,5,6,8,9,1], "something_else": [5,4,3,67,5,4], } ) pr...
Apply rank with percentile, on python polars, for a set of columns on a dataframe
df = pl.DataFrame( { "era": ["01", "01", "02", "02", "03", "03"], "pred1": [1, 2, 3, 4, 5,6], "pred2": [2,4,5,6,7,8], "pred3": [3,5,6,8,9,1], "something_else": [5,4,3,67,5,4], } ) pred_cols = ["pred1", "pred2", "pred3"] ERA_COL = "era" I'm trying to do an equivalent t...
[ "You can use the .rank() / .count() from the previous question combined with .over()\n>>> df.select(\n... (pl.col(pred_cols).rank() / pl.col(pred_cols).count())\n... .over(ERA_COL)\n... )\nshape: (6, 3)\n┌───────┬───────┬───────┐\n│ pred1 | pred2 | pred3 │\n│ --- | --- | --- │\n│ f64 | f64 | f64 │...
[ 2 ]
[]
[]
[ "pandas", "python", "python_polars", "rank" ]
stackoverflow_0074628569_pandas_python_python_polars_rank.txt
Q: Python Docx Module Is Not Inside The Site-Packages Folder I am new to python and I am trying to install the docx module, however it does not appear inside the site-packages folder. First, I thought it was not showing up because my pycharm was outdated. Updated the base interpreter from 3.9 to 3.10 as well as pycha...
Python Docx Module Is Not Inside The Site-Packages Folder
I am new to python and I am trying to install the docx module, however it does not appear inside the site-packages folder. First, I thought it was not showing up because my pycharm was outdated. Updated the base interpreter from 3.9 to 3.10 as well as pycharm. Deleted the venv folder and all that jazz. Opened the windo...
[ "My site-packages folder in Pycharm showed that they were disabled, colored orange, but it turns out that I just had to delete everthing inside the venv folder again and just check the box inherit global site-packages when changing the base interpreter. Everthing is fixed now!\n", "Seems like python-docx doesn't ...
[ 0, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0072070938_module_python.txt
Q: Ansible run recursive script or module In Ansible, I can run a python script if it contains code in the same script. However, if i try to use name: Restarting service on different nodes hosts: nodes connection: ssh tasks: - name: Restarting tomcat service script: main.py 1 args: execu...
Ansible run recursive script or module
In Ansible, I can run a python script if it contains code in the same script. However, if i try to use name: Restarting service on different nodes hosts: nodes connection: ssh tasks: - name: Restarting tomcat service script: main.py 1 args: executable: python3 And main.py has import resta...
[ "I think you should write a custom module; note that when you run any script, ansible creates a copy of it to a temp location. So any relative path you provided in the import will be messed up. You can run your playbook task with -vvv to confirm this.\nHere is an example(high level) of setting up a custom module:\n...
[ 4 ]
[]
[]
[ "ansible", "jenkins", "python" ]
stackoverflow_0074629645_ansible_jenkins_python.txt
Q: Discord.py List all server names where the bot is in I made a bot but I want the bot to make list all the server names where it is when you type a command. Can any one help me, please? A: await ctx.send('\n'.join(guild.name for guild in bot.guilds)) Just remember to pass an intent with guilds enabled in your bo...
Discord.py List all server names where the bot is in
I made a bot but I want the bot to make list all the server names where it is when you type a command. Can any one help me, please?
[ "\nawait ctx.send('\\n'.join(guild.name for guild in bot.guilds))\n\nJust remember to pass an intent with guilds enabled in your bot's constructor\n", "@commands.command()\nasync def servers(self, ctx):\n activeservers = client.guilds\n for guild in activeservers:\n await ctx.send(guild.name)\n ...
[ 2, 0, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0067058040_discord.py_python.txt
Q: Django JSONField is not able to encode smileys properly I plan to store a dict in a Django JSONField. One key of this dict is a comment a user can enter. And users like a lot to add some smileys in their comments... The problem is that some smileys, are saved properly in DB. The database is MySQL 8.0.31, Django ve...
Django JSONField is not able to encode smileys properly
I plan to store a dict in a Django JSONField. One key of this dict is a comment a user can enter. And users like a lot to add some smileys in their comments... The problem is that some smileys, are saved properly in DB. The database is MySQL 8.0.31, Django version is 4.0.8 : JSONField is supported for this environment ...
[ "The database settings was utf8mb4, the tables were also the same, but not the columns that were in utf8mb3. After altering columns encoding to utf8mb4, everything is going right now.\n" ]
[ 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0074534059_django_mysql_python.txt
Q: python merge tuples elements with index/key I'm trying to merge columns values from tuples with an index: source tuples with a lot of timestamps (1440 ~): tuples = [('2022-10-15 01:16:00', '5', '', '', 'hdd1', '1234'), ('2022-10-15 01:16:00', '', '4', '', 'hdd1', '1234'), ('2022-10-15 01:17:00'...
python merge tuples elements with index/key
I'm trying to merge columns values from tuples with an index: source tuples with a lot of timestamps (1440 ~): tuples = [('2022-10-15 01:16:00', '5', '', '', 'hdd1', '1234'), ('2022-10-15 01:16:00', '', '4', '', 'hdd1', '1234'), ('2022-10-15 01:17:00', '10', '', '', 'hdd1', '1234'), ('2022...
[ "I think something like this is what you want:\nfrom itertools import groupby\nresult = []\nkey = lambda t: t[0]\nfor _,items in groupby(sorted(tuples, key=key), key):\n item = None\n for i, it in enumerate(items):\n # First item in group. Need to convert to list to edit.\n if not item: item = l...
[ 1, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0074630148_python_tuples.txt
Q: set dask workers with an event loop for actors Context I am trying to instantiate a legacy data extractor by my dask worker using an actor pattern from dask.distributed import Client client = Client() connector = Sharepoint(CONF.sources["sharepoint"]) items = connector.enumerate_items() # extraction remote_ex...
set dask workers with an event loop for actors
Context I am trying to instantiate a legacy data extractor by my dask worker using an actor pattern from dask.distributed import Client client = Client() connector = Sharepoint(CONF.sources["sharepoint"]) items = connector.enumerate_items() # extraction remote_extractor = client.submit( SharepointExtractor, CO...
[ "OK, I think there is some confusion going on in this question, so I will do my best to clarify the situation. There are three main points:\n\nsome things cannot be serialised between processes easily or at all\nsome objects are expensive to create per process, and it would be nice to only do it once\nthe work must...
[ 1 ]
[]
[]
[ "actor", "asynchronous", "dask", "python" ]
stackoverflow_0074615867_actor_asynchronous_dask_python.txt
Q: How to make a spectrum plot I am trying to replicate a spectrum plot like the figure below with both Python and Matlab, no success so far. The image is from Electric Field Instrument data. The plot should have time on x-axis, frequency on y-axis and colorbar on the right y-axis. The data is a two dimensional matr...
How to make a spectrum plot
I am trying to replicate a spectrum plot like the figure below with both Python and Matlab, no success so far. The image is from Electric Field Instrument data. The plot should have time on x-axis, frequency on y-axis and colorbar on the right y-axis. The data is a two dimensional matrix, each row represents the time ...
[ "You shouldn't use imshow because this will display it as if it were an image (because you have a 2D matrix).\nYou need to plot each row separately, like so:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsin1 = np.sin(np.linspace(0, 2*np.pi, 100))\nsin2 = np.sin(np.linspace(0, 2*np.pi, 100)) + 0.5\nsin3 =...
[ 0 ]
[]
[]
[ "python", "spectrum" ]
stackoverflow_0074630384_python_spectrum.txt
Q: Pandas - Parent child relationship - Duplicative data/Index issues I am trying to work with parent child relational data in pandas and having some issues getting the proper parent/child mapping on portions of my data. I attempted to use ffill and fillna to no avail, but I may have conducted that incorrectly. I hav...
Pandas - Parent child relationship - Duplicative data/Index issues
I am trying to work with parent child relational data in pandas and having some issues getting the proper parent/child mapping on portions of my data. I attempted to use ffill and fillna to no avail, but I may have conducted that incorrectly. I have tried two methods with issues on both. Any assistance getting over thi...
[ "You can create a dictionary that has the information of \"child\" column as key's and \"child_string\" as values.\nchild_info = df[['child_string','child']].dropna()\nchild_string_to_child_dict = dict(zip(child_info.child,child_info.child_string))\n\n>>> child_string_to_child_dict\n \n{8675.0: 'string23',\n 8676.0...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074630349_dataframe_pandas_python_python_3.x.txt
Q: spaCy Matcher conditional or/and Python I want to categorize the following keywords: import spacy from spacy.matcher import PhraseMatcher nlp = spacy.load("en_core_web_sm") phrase_matcher = PhraseMatcher(nlp.vocab) cat_patterns = [nlp(text) for text in ('cat', 'cute', 'fat')] dog_patterns = [nlp(text) for text i...
spaCy Matcher conditional or/and Python
I want to categorize the following keywords: import spacy from spacy.matcher import PhraseMatcher nlp = spacy.load("en_core_web_sm") phrase_matcher = PhraseMatcher(nlp.vocab) cat_patterns = [nlp(text) for text in ('cat', 'cute', 'fat')] dog_patterns = [nlp(text) for text in ('dog', 'fat')] matcher = PhraseMatcher(nl...
[ "From the spaCy documentation on Matchers (https://spacy.io/usage/rule-based-matching), there is no way to detect 2 different tokens separated by an arbitrary number of tokens. If you knew how many tokens were between \"cat\" and \"fat\", for example, then you could use wildcard patterns (https://spacy.io/usage/rul...
[ 0 ]
[]
[]
[ "matcher", "nlp", "python", "spacy" ]
stackoverflow_0066442191_matcher_nlp_python_spacy.txt
Q: How do I convert this xlsx to JSON in Python I have a following excel file with two sheets: and I want to convert this excel into a json format using python that looks like this: { "app_id_c":"string", "cust_id_n":"string", "laa_app_a":"string", "laa_promc":"string", "laa_branch":"string", "la...
How do I convert this xlsx to JSON in Python
I have a following excel file with two sheets: and I want to convert this excel into a json format using python that looks like this: { "app_id_c":"string", "cust_id_n":"string", "laa_app_a":"string", "laa_promc":"string", "laa_branch":"string", "laa_app_type_o":"string", "los_input_from_sas":[ ...
[ "First of all, you have to provide a minimal sample easy to copy and paste not an image of samples. But I have created a minimal sample similar to your images. It doesn't change the solution.\nRead xlsx files and convert them to list of dictionaries in Python, then you will have objects like these:\nsheet1 = [{\n ...
[ 0 ]
[]
[]
[ "excel", "json", "python", "python_3.x" ]
stackoverflow_0074625645_excel_json_python_python_3.x.txt
Q: finding a specific object within duplicate element names, python with json I'm looking to grab the displayValue from objectAttributeValues where the objectTypeAttributeId = 14 there are multiple arrays like this, and the position of objectTypeAttributeId = 14 isn't always the same. how do I loop over every array t...
finding a specific object within duplicate element names, python with json
I'm looking to grab the displayValue from objectAttributeValues where the objectTypeAttributeId = 14 there are multiple arrays like this, and the position of objectTypeAttributeId = 14 isn't always the same. how do I loop over every array to get that specific displayValue? I've got something that looks through every po...
[ "If structure is not changing then this can the solution It will iterate over all objects and add displayValue in search_values list\ndisplay_values = []\nfor object_entries in output_dict.get(\"objectEntries\", []):\n for attribute in object_entries.get(\"attributes\"):\n if attribute.get(\"objectTypeAtt...
[ 1, 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074630263_json_python.txt
Q: Is sklearn.model_selection.GridSearchCV can do custom threshold? My goal is to do threshold tuning before parameter tuning. The idea is simple, in imbalanced dataset, if class 1 is minority, then the threshold should be lower than 0.5, so it predict more instance as class 1 instead of 0. Therefore, I believe, by c...
Is sklearn.model_selection.GridSearchCV can do custom threshold?
My goal is to do threshold tuning before parameter tuning. The idea is simple, in imbalanced dataset, if class 1 is minority, then the threshold should be lower than 0.5, so it predict more instance as class 1 instead of 0. Therefore, I believe, by changing the threshold early, we can improve the model predictive power...
[ "You can't directly change the threshold used by predict (which gets called by your scorer, presumably), but you can provide a customer scoring method. See the User Guide. Here I think you'd want something like:\ndef f2_score_at_thresh(y_true, y_pos_prob, threshold):\n y_pred = y_pos_prob > threshold\n retu...
[ 1 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0074624735_python_scikit_learn.txt
Q: How to get row number in dataframe in Pandas? How can I get the number of the row in a dataframe that contains a certain value in a certain column using Pandas? For example, I have the following dataframe: ClientID LastName 0 34 Johnson 1 67 Smith 2 53 Brows How can I find th...
How to get row number in dataframe in Pandas?
How can I get the number of the row in a dataframe that contains a certain value in a certain column using Pandas? For example, I have the following dataframe: ClientID LastName 0 34 Johnson 1 67 Smith 2 53 Brows How can I find the number of the row that has 'Smith' in 'LastName' ...
[ "Note that a dataframe's index could be out of order, or not even numerical at all. If you don't want to use the current index and instead renumber the rows sequentially, then you can use df.reset_index() together with the suggestions below\nTo get all indices that matches 'Smith'\n>>> df[df['LastName'] == 'Smith']...
[ 74, 14, 8, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0043193880_pandas_python.txt
Q: Why does my print execute after the second loop even if I use print first? I'm a beginner of python, and I wanted to try to make a timer. import time sets=int(input("How many sets?: ")) seconds=int(input("How many seconds per set?: ")) for i in range(sets): print("set {0} of {1} started".format(i + 1, sets))...
Why does my print execute after the second loop even if I use print first?
I'm a beginner of python, and I wanted to try to make a timer. import time sets=int(input("How many sets?: ")) seconds=int(input("How many seconds per set?: ")) for i in range(sets): print("set {0} of {1} started".format(i + 1, sets)) for j in range(seconds, 0, -1): print(j, end=" ") print("Finished w...
[ "By default print terminates with a newline character. When you define end in the print function, you modify this behavior. I have added a bare print which will simply output a newline character to stdout, correcting the format issues.\nfor i in range(sets):\n print(\"set {0} of {1} started\".format(i + 1, sets)...
[ 0 ]
[]
[]
[ "loops", "python", "python_3.x" ]
stackoverflow_0074629811_loops_python_python_3.x.txt
Q: Creating an SQLAlchemy column to dynamically generate a list of models with an expression I want to create a relationship column on my model, where it will be built with an expression so that it can be queried. Here's a brief example of my setup: I have each application (eg. Python) stored in the App table. Each v...
Creating an SQLAlchemy column to dynamically generate a list of models with an expression
I want to create a relationship column on my model, where it will be built with an expression so that it can be queried. Here's a brief example of my setup: I have each application (eg. Python) stored in the App table. Each version of the application (eg. Python 3.7) is stored under the AppVersion table. My items (in t...
[ "It's possible via a relationship but it took a lot of trial and error with joins to get there. Below is what was needed to get it working, although I wouldn't be surprised if there's a more optimal way.\nclass ItemVersion(Base):\n ...\n version_min_val = column_property(\n select(AppVersion.value)\n ...
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074478264_python_sqlalchemy.txt
Q: style.css not loading in django html template I created a login page and calling a static css sheet for styling but its not working. I load static in my login.html and use <html> <head> <title>PWC Login</title> <link rel="stylesheet" href="{% static 'css/style.css'%}"> </head> <body> <div class="loginb...
style.css not loading in django html template
I created a login page and calling a static css sheet for styling but its not working. I load static in my login.html and use <html> <head> <title>PWC Login</title> <link rel="stylesheet" href="{% static 'css/style.css'%}"> </head> <body> <div class="loginbox"> <img src="{% static 'images/avatar.png...
[ "STATIC_URL = '/static/'\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, \"static/\"),\n)\n\n" ]
[ 0 ]
[]
[]
[ "css", "django", "html", "python", "static" ]
stackoverflow_0074578616_css_django_html_python_static.txt
Q: assuming IAM role multiple times using boto3 in python I'm new to working with aws and I'm not sure if I'm wording it correctly but basically, I need to sso in an account -> assume a role in account A -> then assume a role in account B. I am following this article (https://medium.com/geekculture/programming-aws-ia...
assuming IAM role multiple times using boto3 in python
I'm new to working with aws and I'm not sure if I'm wording it correctly but basically, I need to sso in an account -> assume a role in account A -> then assume a role in account B. I am following this article (https://medium.com/geekculture/programming-aws-iam-using-aws-python-sdk-boto3-part-4-62f2f1c21584) on how to ...
[ "Check the AWS Official Code Library that contains this use case. When looking for an AWS code example, check this New AWS Doc.\n\nAs you can see, the code library shows this use case in different supported programming langanges. The topic is here:\nCreate an IAM user and assume a role with AWS STS using an AWS SDK...
[ 0 ]
[]
[]
[ "amazon_iam", "amazon_web_services", "assume_role", "boto3", "python" ]
stackoverflow_0074630630_amazon_iam_amazon_web_services_assume_role_boto3_python.txt
Q: Different color of every single bar of seaborn bar plot I have a very wide range of data that I plot using seaborn bar plot. As I use hue, the two different colors are the same for all the data, but I want that every single bar is a different color. #This is the colors I want for every bar: palette = ["#fee090","#...
Different color of every single bar of seaborn bar plot
I have a very wide range of data that I plot using seaborn bar plot. As I use hue, the two different colors are the same for all the data, but I want that every single bar is a different color. #This is the colors I want for every bar: palette = ["#fee090","#fdae61","#4575b4","#313695","#e0f3f8","#abd9e9","#d73027", "#...
[ "When working with hue, seaborn assigns one color per hue value. In this case there seem to be two hue values (1.70 and 3.00), so two colors are used.\nTo give each bar a separate color, you could iterate through the generated bars and manually assign the colors. Note that for each hue value, a container is create...
[ 0 ]
[]
[]
[ "bar_chart", "colors", "matplotlib", "python", "seaborn" ]
stackoverflow_0074617540_bar_chart_colors_matplotlib_python_seaborn.txt
Q: generate dynamic task using hooks without running them in backend I have a simple dag - that takes argument from mysql db - (like sql, subject) Then I have a function creating report out and send to particular email. Here is code snippet. def s_report(k,**kwargs): body_sql = list2[k][4] request1 = "({})".format(bo...
generate dynamic task using hooks without running them in backend
I have a simple dag - that takes argument from mysql db - (like sql, subject) Then I have a function creating report out and send to particular email. Here is code snippet. def s_report(k,**kwargs): body_sql = list2[k][4] request1 = "({})".format(body_sql) dwh_hook = SnowflakeHook(snowflake_conn_id="snowflake_conn") df...
[ "A couple of things:\nBy looking at your code, in particular the lines:\nfor j in range(len(list)):\nmysql_list >> [ s_report(j)] >> end_operator\n\nwe can determine that if your first task succeeds, namely, mysql_list, then the tasks downstream to it, namely, the s_report calls should begin executing. You have pre...
[ 0 ]
[]
[]
[ "airflow", "python", "snowflake_cloud_data_platform" ]
stackoverflow_0074596752_airflow_python_snowflake_cloud_data_platform.txt
Q: Why am I getting leading and trailing backslash when I replace my placeholder in Python? I have this sample query string: """SELECT security_id AS securityID, trade_date AS date, available, currency_code AS sourceCurrency FROM cppib_market_passive_swap_availability WHERE tr...
Why am I getting leading and trailing backslash when I replace my placeholder in Python?
I have this sample query string: """SELECT security_id AS securityID, trade_date AS date, available, currency_code AS sourceCurrency FROM cppib_market_passive_swap_availability WHERE trade_date = '{file_date}' """.format(file_date=passive_availablity_date.strftime('%Y-%m-%d') W...
[ "The backslashes you see around the datetime (\\') are likely just artifacts to remind you that they are literal single quotes, perhaps inside of a singly quoted string.\nAs a side note, it is generally bad practice to be injecting a value into a SQL query this way. Instead, you should learn how to use a prepared ...
[ 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0074630736_python_sql.txt
Q: QMessage in a function thread? I want to do a popup when the function in a thread finish but when it run the popup the program crash. I tried doing a thread in the main function thread but crash the app. I put a large and slow funtion in a thread to not crash the GUI but I want when this slow function finish, run ...
QMessage in a function thread?
I want to do a popup when the function in a thread finish but when it run the popup the program crash. I tried doing a thread in the main function thread but crash the app. I put a large and slow funtion in a thread to not crash the GUI but I want when this slow function finish, run a popup with QMessageBox, my solluti...
[ "You must not use any GUI functions outside of the main thread. So you can not call popup() from your calculation thread and you can't create a new thread in your calculation thread and have that call it. You must make the main thread call it.\nFor possible solutions see How to properly execute GUI operations in Qt...
[ 0 ]
[]
[]
[ "multithreading", "popup", "pyqt", "python", "qmessagebox" ]
stackoverflow_0074630412_multithreading_popup_pyqt_python_qmessagebox.txt
Q: Should I have everything in one script or should I have more scripts and connect them? I'm making a game and I don't know if I should have the whole game in one script or the script for the main menu alone and for the options menu alone and the for the actual gameplay alone... and connect them. So, what is the bet...
Should I have everything in one script or should I have more scripts and connect them?
I'm making a game and I don't know if I should have the whole game in one script or the script for the main menu alone and for the options menu alone and the for the actual gameplay alone... and connect them. So, what is the better option and if I should make more scripts how can I connect them? Is it making a manager ...
[ "If you have separate files for each class, (my opinion by the way, it generally depends on you) it would be much easier to manage your different classes, especially without having to scroll through one giant file. Also fun fact, this is known as modular programming\nOf course, sometimes it may be too complex to re...
[ 2 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0074630623_class_function_python.txt
Q: Not able to import libraries in my python project of face recognization i am working on python project of face recognization but i am anable to import libraries in my program . this are not working i try to import different libraries and run the code but every times it fails in python 3.9 enter image description h...
Not able to import libraries in my python project of face recognization
i am working on python project of face recognization but i am anable to import libraries in my program . this are not working i try to import different libraries and run the code but every times it fails in python 3.9 enter image description here
[ "Have you installed the library? Also if you haven't I suggest you use an virtual environment and install inside it.\nTo install your library type in your terminal:\npip install NAME-OF-THE-LIBRARY\n\nExample for the face_recognition:\npip install face-recognition\n\n" ]
[ 0 ]
[]
[]
[ "libraries", "python" ]
stackoverflow_0074630594_libraries_python.txt
Q: Errors using a list of integers (Python + Google Ads API) I have a list of IDs that are integers. If I do print(data_clients["id"]) I get something like: 4323324234 2342342344 5464564565 Then I want to call an API (Google Ads) that uses those numbers as IDs (to know which data to retrieve). I have to do a loop (o...
Errors using a list of integers (Python + Google Ads API)
I have a list of IDs that are integers. If I do print(data_clients["id"]) I get something like: 4323324234 2342342344 5464564565 Then I want to call an API (Google Ads) that uses those numbers as IDs (to know which data to retrieve). I have to do a loop (or something similar) to get the data from each ID. I've tried t...
[ "Assuming data_clients[\"id\"] is a list of customer IDs, this should work:\nfor cust_id in data_clients[\"id\"]:\n query = (f''' WHATEVER ''')\n stream = ga_service.search_stream(customer_id=cust_id, query=query)\n\n" ]
[ 0 ]
[]
[]
[ "google_ads_api", "python" ]
stackoverflow_0074604670_google_ads_api_python.txt
Q: How to apply multiple functions to same column in Python? I need help on applying my below case statement functions to the same column at once or in parallel? Not sure if I am doing it in the most efficient way, are there alternative ways I can do this? #Accrued Calc for ACT/360 def bbb(bb): if bb["Basis"] ==...
How to apply multiple functions to same column in Python?
I need help on applying my below case statement functions to the same column at once or in parallel? Not sure if I am doing it in the most efficient way, are there alternative ways I can do this? #Accrued Calc for ACT/360 def bbb(bb): if bb["Basis"] == "ACT/360" and bb['Type'] == 'L' and bb['Current Filter'] == 'C...
[ "You should have one function to decide which function to call. Apply that function to your dataframe. Depending on your conditions, this function can then call the correct function that will contain the meat of your calculations. Also, in the interest of readability, rename your functions and variables to somethin...
[ 1 ]
[]
[]
[ "apply", "finance", "function", "pandas", "python" ]
stackoverflow_0074630318_apply_finance_function_pandas_python.txt
Q: How do I make 2 hour windows using data thats all 1 hour windows I have data that looks like this: Datetime Price and was just wondering how about I would turn them into 2 hour windows instead and use the average of the price of the two A: Let us do resample with 2h freq df['Datetime'] = pd.to_datetime(df[...
How do I make 2 hour windows using data thats all 1 hour windows
I have data that looks like this: Datetime Price and was just wondering how about I would turn them into 2 hour windows instead and use the average of the price of the two
[ "Let us do resample with 2h freq\ndf['Datetime'] = pd.to_datetime(df['Datetime'], dayfirst=True)\ndf.resample('2h', on='Datetime', origin='start')['Price'].mean()\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074630183_numpy_pandas_python.txt
Q: diff list of multiline strings with difflib without knowing which were added, deleted or modified I have two lists of multiline strings and I try to get the the diff lines for these strings. First I tried to just split all lines of each string and handled all these strings as one big "file" and get the diff for it...
diff list of multiline strings with difflib without knowing which were added, deleted or modified
I have two lists of multiline strings and I try to get the the diff lines for these strings. First I tried to just split all lines of each string and handled all these strings as one big "file" and get the diff for it but I had a lot of bugs. I cannot just diff by index since I do not know, which multiline string was a...
[ "I had to implmenent my own code in order to get the desired output. It is basically the same as Differ.compare() with the difference that we have a look at multiline blocks instead of lines. So the code would be:\ndiffString = \"\"\noldList = [\"one\\ntwo\\nthree\",\"four\\nfive\\nsix\",\"seven\\neight\\nnine\"]\n...
[ 0 ]
[]
[]
[ "difflib", "python" ]
stackoverflow_0074593945_difflib_python.txt
Q: Does the unit passed to the datetime64 data type in pandas do anything? Does the unit passed to the datetime64 data type in pandas do anything? Consider this code: import pandas as pd v1 = pd.DataFrame({'Date':['2020-01-01']*1000}).astype({'Date':'datetime64'}) v2 = pd.DataFrame({'Date':['2020-01-01']*1000}).asty...
Does the unit passed to the datetime64 data type in pandas do anything?
Does the unit passed to the datetime64 data type in pandas do anything? Consider this code: import pandas as pd v1 = pd.DataFrame({'Date':['2020-01-01']*1000}).astype({'Date':'datetime64'}) v2 = pd.DataFrame({'Date':['2020-01-01']*1000}).astype({'Date':'datetime64[ns]'}) v3 = pd.DataFrame({'Date':['2020-01-01']*1000})...
[ "First of all: The Pandas version of the datetime64 type only timezone support. Specifically, when you try to a datetime64 variant in a Pandas series, it'll only support as (attosecond), fs (femtosecond), ps (picosecond) and ns (nanosecond) resolutions, anything less precise is replaced by datetime64[ns]. The datet...
[ 3 ]
[]
[]
[ "datetime64", "pandas", "python", "python_datetime" ]
stackoverflow_0074630783_datetime64_pandas_python_python_datetime.txt
Q: Detecting changes in a txt file I am a beginner python programmer and I am wondering if there is any way to detect a change in a txt file on windows. Any suggestion is appreciated. A: There are many ways to go with it : You can for example check the last modification date of the file every few seconds with os.p...
Detecting changes in a txt file
I am a beginner python programmer and I am wondering if there is any way to detect a change in a txt file on windows. Any suggestion is appreciated.
[ "There are many ways to go with it :\n\nYou can for example check the last modification date of the file every few seconds with os.path.getmtime(path), when the date change you know the file was edited.\n\nYou can also use some form of checksum (generate md5 hash of a file) on the file and check every few seconds i...
[ 2, 0 ]
[]
[]
[ "python", "txt", "windows" ]
stackoverflow_0074630038_python_txt_windows.txt
Q: Scrapy: Importing a package from the project that's not in the same directory I'm trying to import a package from my project which is not in the same directory as scrapy is in. The directory structure for my project is as follows: Main __init__.py /XPaths __init.py XPaths.py /scrapper scrapy.cfg ...
Scrapy: Importing a package from the project that's not in the same directory
I'm trying to import a package from my project which is not in the same directory as scrapy is in. The directory structure for my project is as follows: Main __init__.py /XPaths __init.py XPaths.py /scrapper scrapy.cfg /scrapper __init.py settings.py items.py pipelines.py ...
[ "I know its a little bit messy solution but only one I could find when I had same problem as you. Before including files from your project you need to manually append the system path to your top most package level, i.e:\nsys.path.append(os.path.join(os.path.dirname(__file__), '../..'))\nfrom XPaths.XPaths import XP...
[ 1, 0, 0 ]
[]
[]
[ "import", "python", "scrapy" ]
stackoverflow_0018196458_import_python_scrapy.txt
Q: Add specific selected fields in plotly text annotations I have a graph that looks like this: I want to color the dots in the following way, one dot for every time the version is different, like for 0.1-SNAPSHOT there are 8 dots, but I only want the first one labelled and the rest just dots (without the version),s...
Add specific selected fields in plotly text annotations
I have a graph that looks like this: I want to color the dots in the following way, one dot for every time the version is different, like for 0.1-SNAPSHOT there are 8 dots, but I only want the first one labelled and the rest just dots (without the version),similarly for all others. This is how my data looks like: ...
[ "Try creating a duplicate row of first occurrence to drive the text of your annotations.\ndf['dupe'] = df.info_version.where(~df.info_version.duplicated(), '')\n\n| | API_paths | info_version | Commit-growth | dupe |\n|---:|------------:|:---------------|----------------:|:----------|\n| 0 | ...
[ 1 ]
[]
[]
[ "pandas", "plotly", "python" ]
stackoverflow_0074628926_pandas_plotly_python.txt
Q: Reorder the information on pandas DataFrame having the dates and time on a row basis I have a small doubt. I have a dataframe where I have one column displaying the hourly time and the columns with the dates, is there a way to put all this together? (In this case using pandas) actual dataframe The desired output ...
Reorder the information on pandas DataFrame having the dates and time on a row basis
I have a small doubt. I have a dataframe where I have one column displaying the hourly time and the columns with the dates, is there a way to put all this together? (In this case using pandas) actual dataframe The desired output The dataset https://docs.google.com/spreadsheets/d/1BNPmSZlFHmEkGJC--iBgZiCdM81a5Dt4wj8C8...
[ "This looks like a good use of pd.melt\nimport pandas as pd\ndf = pd.DataFrame({'August': ['00:00 - 01:00', '01:00 - 02:00', '02:00 - 03:00'], '1/ aug/': ['273,285', '2,708,725', '2,702,913'], '2/ aug/': ['310,135', '2,876,725', '28,409'], '3/ aug/': ['3,077,438', '3,076,075', '307,595'], '4/ aug/': ['2,911,175', '...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074630956_dataframe_pandas_python_python_3.x.txt
Q: Python no module named pip I use windows 7 32 bit and python 3.7. I was trying to install a module with pip and this error came up: C:\Windows\System32>pip install pyttsx3 Traceback (most recent call last): File "d:\python\python 3.7\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) Fil...
Python no module named pip
I use windows 7 32 bit and python 3.7. I was trying to install a module with pip and this error came up: C:\Windows\System32>pip install pyttsx3 Traceback (most recent call last): File "d:\python\python 3.7\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\python\python 3.7\lib\runp...
[ "Make sure you have python path added to the PATH variable. Then run\npython -m ensurepip\n\n", "Could you try?\npip3 install pyttsx3\n\n", "To me for Ubuntu 20.04 helped the following:\nls -al /usr/bin/python # check before removal that 'python' is link\nsudo rm /usr/bin/python # remove link to old version of ...
[ 27, 1, 1, 0, 0, 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0065336695_pip_python.txt
Q: Using Wild Card on Airflow GoogleCloudStorageToBigQueryOperator Is it possible to use a wildcard on GoogleCloudStorageToBigQueryOperator? So I have a collection of files inside a certain folder in GCS file_sample_1.json file_sample_2.json file_sample_3.json ... file_sample_n.json I want to ingest these files usin...
Using Wild Card on Airflow GoogleCloudStorageToBigQueryOperator
Is it possible to use a wildcard on GoogleCloudStorageToBigQueryOperator? So I have a collection of files inside a certain folder in GCS file_sample_1.json file_sample_2.json file_sample_3.json ... file_sample_n.json I want to ingest these files using airflow with GoogleCloudStorageToBigQueryOperator. below is my code...
[ "Yes, but you should include the string in a list. So if you use\nsource_objects = ['file_sample_*.json'],\n\nit will ingest all files starting with 'file_sample_' and ending with '.json'.\n", "I had the same problem after updating apache-airflow-providers-google to version 8.5.0. where wildcard stoped to work.\n...
[ 0, 0 ]
[]
[]
[ "airflow", "python" ]
stackoverflow_0074626222_airflow_python.txt
Q: How to know the index of an element in a list If I have a list like [[a, b], [c, d], [e, f]] How would I know that element a is in index 0 of the big list. I'm unsure on how to do this with a 2 dimensional array. I tried to use index, but it not works s = [['a', 'b'], ['c', 'd'], ['e', 'f']] s.index('a') Trace...
How to know the index of an element in a list
If I have a list like [[a, b], [c, d], [e, f]] How would I know that element a is in index 0 of the big list. I'm unsure on how to do this with a 2 dimensional array. I tried to use index, but it not works s = [['a', 'b'], ['c', 'd'], ['e', 'f']] s.index('a') Traceback (most recent call last): File "C:/Users/xxy/...
[ "You can solve it with a loop\ns = [['a', 'b'], ['c', 'd'], ['e', 'f']]\nx = 'a'\nfind = False\nfor i, line in enumerate(s):\n if x in line:\n print(f'find {x} at', i, line.index(x))\n find = True\n break\nif not find:\n print(f'{x} is not in list')\n\n", "More simpler way you can use a...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074630965_python.txt
Q: Python Beginner Question: Can someone help me understand why the output is [1,1,1,1,2,3]? my_list = [1,2,3] for v in range (len(my_list)): my_list.insert(1,my_list[v]) print(my_list) #outputs [1,1,1,1,2,3] I am getting tripped up on why the value of V is set to 1 instead of iterating through the other number...
Python Beginner Question: Can someone help me understand why the output is [1,1,1,1,2,3]?
my_list = [1,2,3] for v in range (len(my_list)): my_list.insert(1,my_list[v]) print(my_list) #outputs [1,1,1,1,2,3] I am getting tripped up on why the value of V is set to 1 instead of iterating through the other number found in the list. I've tried reading up on W3 schools but still confused
[ "This is because you insert the value 1 before the #1 position in the list,\nbut because the list updates every iteration, the value in the #1 position\nis always 1.\nto see this clearly, you can print the list in every iteration\n[1,1,2,3]\n[1,1,1,2,3]\n[1,1,1,1,2,3]\n\nthe only thing not updating is the range() t...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0069138557_python.txt
Q: scrollable canvas working with .pack but not .place I am trying to get my scrollable canvas to work. It works when I pack the elements using .pack, however when I insert the elements via .place, the scrollbar stops working. Here is a minimal reproducable example of my code. startup.py file: import frame as f impor...
scrollable canvas working with .pack but not .place
I am trying to get my scrollable canvas to work. It works when I pack the elements using .pack, however when I insert the elements via .place, the scrollbar stops working. Here is a minimal reproducable example of my code. startup.py file: import frame as f import placeWidgetsOnFrame as p p.populate3() f.window.mainlo...
[ "The reason is because pack by default will cause the containing frame to grow or shrink to fit all of the child widgets, but place does not. If your frame starts out as 1x1 and you use place to add widgets to it, the size will remain 1x1. When you use place, it is your responsibility to make the containing widget ...
[ 3 ]
[]
[]
[ "customtkinter", "python", "scrollbar", "tkinter" ]
stackoverflow_0074630052_customtkinter_python_scrollbar_tkinter.txt
Q: Customise a FastAPI response if query = null I have a table set-up in Postgres that contains some user information. I am trying to work out how to query that table with a user ID, and return a custom response if the user ID does not appear in the table. I am using the following table and schema to store the data: ...
Customise a FastAPI response if query = null
I have a table set-up in Postgres that contains some user information. I am trying to work out how to query that table with a user ID, and return a custom response if the user ID does not appear in the table. I am using the following table and schema to store the data: class User(Base): __tablename__ = "users" ...
[ "I managed to find an answer in the FastAPI documentation here. The below seemed to work for me.\n@router.get(\"/{id}\", response_model=schemas.UserResponse)\ndef get_user(id: int, db: Session = Depends(get_db)):\n \n user = db.query(models.User).filter(models.User.id == id).first()\n print(user) # checkin...
[ 0 ]
[]
[]
[ "fastapi", "get", "json", "postgresql", "python" ]
stackoverflow_0074630913_fastapi_get_json_postgresql_python.txt
Q: Python problem involving 2 For loops that I can't work out EPLgames2018/19 CSVI am fairly new to python. I am reading in a CSV file that contains the stats from every english premier league match in 2018/19. I have created a list of all of the teams. I am then trying to take each team in turn and loop through all ...
Python problem involving 2 For loops that I can't work out
EPLgames2018/19 CSVI am fairly new to python. I am reading in a CSV file that contains the stats from every english premier league match in 2018/19. I have created a list of all of the teams. I am then trying to take each team in turn and loop through all of the matches to calculate each teams total points for the seas...
[ "You are adding teams to eplteams based on some condition:\nif x['HomeTeam'] not in eplteams:\n eplteams.append(x['HomeTeam'])\n teamcount += 1\n\nAnd then using eplteam element in condition:\nif eplteams[i] == match_result:\n points += 3\n\nif eplteams[i] == x['HomeTeam']:\n if match_result == \"Draw\"...
[ 0, 0 ]
[]
[]
[ "csv", "for_loop", "list", "python" ]
stackoverflow_0074630823_csv_for_loop_list_python.txt
Q: Create a list of Triangle objects I'm very new to Python and have an issue. I was wondering if there was a way I could create a list of objects created. For example, say I have a class: list_triangles = [] def class Triangle: def __init__(self, h, w): self.h = h self.w = w a = Triangle(5,6) b = Trian...
Create a list of Triangle objects
I'm very new to Python and have an issue. I was wondering if there was a way I could create a list of objects created. For example, say I have a class: list_triangles = [] def class Triangle: def __init__(self, h, w): self.h = h self.w = w a = Triangle(5,6) b = Triangle(3,3) What I would have to add such...
[ "Put the arguments in a list, then iterate over that.\nparams = [(5, 6), (3, 3)]\nlist_triangles = [Triangle(*p) for p in params]\n\n", "If I understand you correctly, you want to have globaly accessible list of every created object, if so you can declare class variable and then append self to it in constructor t...
[ 3, 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074630799_for_loop_python.txt
Q: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) I'm trying to execute a Python script, but I am getting the following error: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) I'm using python 3.5.2 on a Linux Mint 18.1 Serena OS Can someone tell me why this happens, a...
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
I'm trying to execute a Python script, but I am getting the following error: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) I'm using python 3.5.2 on a Linux Mint 18.1 Serena OS Can someone tell me why this happens, and how can I solve?
[ "The SIGSEGV signal indicates a \"segmentation violation\" or a \"segfault\". More or less, this equates to a read or write of a memory address that's not mapped in the process.\nThis indicates a bug in your program. In a Python program, this is either a bug in the interpreter or in an extension module being used...
[ 59, 19, 10, 6, 6, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "found on other page.\ninterpreter: python 3.8\ncv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\nthis solved issue for me. \ni was getting SIGSEGV with 2.7, upgraded my python to 3.8 then got different error with OpenCV. and found answer on OpenCV 4.0.0 SystemError: <class 'cv...
[ -2 ]
[ "linux_mint", "python", "python_3.5", "segmentation_fault" ]
stackoverflow_0049414841_linux_mint_python_python_3.5_segmentation_fault.txt
Q: getting a list of dictionaries as a list of lists Ok so I have a list of the same dictionaries and I want to get the values of the dictionaries into a list of lists. For example this is what one dictionary might look like: mylist = [{'a': 0, 'b': 2},{'a':1, 'b':3}] I want the lists of lists to look like: [[0,2],[1...
getting a list of dictionaries as a list of lists
Ok so I have a list of the same dictionaries and I want to get the values of the dictionaries into a list of lists. For example this is what one dictionary might look like: mylist = [{'a': 0, 'b': 2},{'a':1, 'b':3}] I want the lists of lists to look like: [[0,2],[1,3]] I have tried doing zip(*[d.values() for d in mylis...
[ "As the comments suggest, I don't think you need zip() for this to work, instead just try something simpler such as [list(i.values()) for i in mylist]\nYou convert the values into a list with the list() function, and the values are already obtained with the .values() method\n", "Try this [list(i.values()) for i i...
[ 2, 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074631072_dictionary_list_python.txt
Q: Django lookup by JSONField array value Let's say I have MySQL database records with this structure { "id": 44207, "actors": [ { "id": "9c88bd9c-f41b-59fa-bfb6-427b1755ea64", "name": "APT41", "scope": "confirmed" ...
Django lookup by JSONField array value
Let's say I have MySQL database records with this structure { "id": 44207, "actors": [ { "id": "9c88bd9c-f41b-59fa-bfb6-427b1755ea64", "name": "APT41", "scope": "confirmed" }, { ...
[ "Following this answer and the linked answer in the same post.\n'contains' or 'icontains' looks for the patterns '%string%', which in your case assumes '67' is between characters. But, the number pattern is at the end of your actor name.\nSo, based on the answers I linked, you should probably try endswith or iendsw...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "mysql", "python" ]
stackoverflow_0074617447_django_django_models_django_rest_framework_mysql_python.txt
Q: Sorting list based on values from another list I have a list of strings like this: X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ] What is the shortest way of sorting X using values from Y to get the following output? ["a", "d", "h", "b", "c", "e", "i", "f", "g"...
Sorting list based on values from another list
I have a list of strings like this: X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1 ] What is the shortest way of sorting X using values from Y to get the following output? ["a", "d", "h", "b", "c", "e", "i", "f", "g"] The order of the elements having the same "key" d...
[ "Shortest Code\n[x for _, x in sorted(zip(Y, X))]\n\nExample:\nX = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\"]\nY = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]\n\nZ = [x for _,x in sorted(zip(Y,X))]\nprint(Z) # [\"a\", \"d\", \"h\", \"b\", \"c\", \"e\", \"i\", \"f\", \"g\"]\n\n\nGenerally Spe...
[ 769, 139, 121, 48, 36, 25, 17, 16, 7, 4, 2, 2, 2, 2, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0006618515_list_python_sorting.txt
Q: Discord.py getting empty messages I was developing a small discord bot for some time, and it was working fine until I started testing to play mp3 in a voice channel. I was following this question because discord.py throwed an error that I needed pynacl lib: RuntimeError: PyNaCl library needed in order to use voice...
Discord.py getting empty messages
I was developing a small discord bot for some time, and it was working fine until I started testing to play mp3 in a voice channel. I was following this question because discord.py throwed an error that I needed pynacl lib: RuntimeError: PyNaCl library needed in order to use voice Bot stopped working after running this...
[ "You need to make sure that the message_content intent is configured correctly on both the discord developer portal and in the code:\nintents = discord.Intents()\nintents.message_content = True\nclient = discord.Bot(intents=intents)\n\n" ]
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074490633_discord.py_python.txt
Q: Hi. I'm trying to scrape infinite scrolling website. It stuck in 200th data I scrolled with selenium and grabbed all urls and used these urls in beautifulsoup.But there are so many duplicates in scraped data.I tried to left them with drop_duplicates but it stack in about 200th data .I cannot detect the problem. I ...
Hi. I'm trying to scrape infinite scrolling website. It stuck in 200th data
I scrolled with selenium and grabbed all urls and used these urls in beautifulsoup.But there are so many duplicates in scraped data.I tried to left them with drop_duplicates but it stack in about 200th data .I cannot detect the problem. I add the code which i use. I want to grab all prices,areas,rooms et.c. import re...
[ "A cause of duplicates is that every time you get lnks, you're getting the products you scraped before scrolling as well. You can probably skip duplicate scrapes by initiating scrapedUrls = [] somewhere at the beginning of your code (OUTSIDE of all loops), and then checking urel against it, as well as adding to it\...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074598056_beautifulsoup_python_selenium_selenium_webdriver_web_scraping.txt
Q: How do i turn this iterative function to recursive function? def itr(n): s = 0 for i in range(0, n+1): s = s + i * i return s I have difficulties turning this iterative function to a recursive function called rec(n). A: Honestly, this program doesn't need to be converted recursively, but...
How do i turn this iterative function to recursive function?
def itr(n): s = 0 for i in range(0, n+1): s = s + i * i return s I have difficulties turning this iterative function to a recursive function called rec(n).
[ "Honestly, this program doesn't need to be converted recursively, but if so, you would probably write something like this:\ndef rec(n, s = 0): # s = 0 is a default variable, so if we don't specify what s is when we call the function, it's default variable will be 0\n if n == 0: # base case, so if we've run throu...
[ 1, 0 ]
[]
[]
[ "function", "iteration", "loops", "python", "recursion" ]
stackoverflow_0074630841_function_iteration_loops_python_recursion.txt
Q: Python/rpy2 does not recognize %>% pipe in r code I have a Python script that will pass dataframes into an R package and get the results. The R script works as expected in R studio. However I cannot get it to wokr when executing through python/rpy2. rpy2.rinterface_lib.embedded.RRuntimeError: Error in ataframe d%...
Python/rpy2 does not recognize %>% pipe in r code
I have a Python script that will pass dataframes into an R package and get the results. The R script works as expected in R studio. However I cannot get it to wokr when executing through python/rpy2. rpy2.rinterface_lib.embedded.RRuntimeError: Error in ataframe d%>% dplyr::rename(domain = Domain, variable = Variable, ...
[ "%>% is from the magrittr package. If you have R version 4.1 or later you can use the native |> pipe instead.\n" ]
[ 2 ]
[]
[]
[ "dplyr", "python", "r", "rpy2" ]
stackoverflow_0074630873_dplyr_python_r_rpy2.txt
Q: TypeError: > not supported between instances of 'int' and 'list' scores = input("Input a list of student scores\n ").split() for n in range(0, len(scores)): scores[n] = int(scores[n]) print(scores) # for loop way highest=0 for s in scores: if s > highest: highest=scores print(f"the highest score is {...
TypeError: > not supported between instances of 'int' and 'list'
scores = input("Input a list of student scores\n ").split() for n in range(0, len(scores)): scores[n] = int(scores[n]) print(scores) # for loop way highest=0 for s in scores: if s > highest: highest=scores print(f"the highest score is {highest}") please help me how to solve it? I searched it they are sa...
[ "In this line\nhighest=scores\n\nYou are assigning a list (scores) to an int var (highest), and this is the reason for the error.\nI think you have to change the line in\nhighest=s\n\n" ]
[ 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0074608661_loops_python.txt
Q: Pandas zfill multiple items in single cell I have multiple values in a single cell Q3 1 4 1 3 3 4 11 3 4 6 15 16 How can I zfill or pad to add leading zeros to each value in each cell? df['Q3'].str.split(' ').apply(lambda x: x.zfill(8)) AttributeError: 'list' object has no attribute 'zfill' looking for Q3 00000...
Pandas zfill multiple items in single cell
I have multiple values in a single cell Q3 1 4 1 3 3 4 11 3 4 6 15 16 How can I zfill or pad to add leading zeros to each value in each cell? df['Q3'].str.split(' ').apply(lambda x: x.zfill(8)) AttributeError: 'list' object has no attribute 'zfill' looking for Q3 00000001 00000004 00000001 00000003 00000003 00000004...
[ "Simple. Split the values then apply zfill on each value and join back\ndf['Q3'].map(lambda x: ' '.join(y.zfill(8) for y in x.split()))\n\n\n0 00000001 00000004\n1 00000001 00000003\n2 00000003 00000004 00000011\n3 00000003 00000004...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074631092_dataframe_pandas_python.txt
Q: TKInter frame losing grid layout when insert scrollbar I'm trying to create an app with a frame with two frames inside, but I want one of then to be wider than the other... I found a way to do it using grid, but when I add a scrollbar on one of the frames it readjusts the grid and both frames get the same size. He...
TKInter frame losing grid layout when insert scrollbar
I'm trying to create an app with a frame with two frames inside, but I want one of then to be wider than the other... I found a way to do it using grid, but when I add a scrollbar on one of the frames it readjusts the grid and both frames get the same size. Here is the code working without the scrollbar: def __init__(s...
[ "Set the size of the canvas explicitly\nself.__image_canvas = ctk.CTkCanvas(self.__image_frame, width=900)\n\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074628240_python_tkinter.txt
Q: Decorator that logs information to a file in Python My task is: Write a decorator that logs information about calls of decorated functions, the values of its arguments, keyword arguments, and execution time. The log should be written to a file. **Example of Using ** @log def foo(a, b, c): ... foo(1, 2, c=3) log.tx...
Decorator that logs information to a file in Python
My task is: Write a decorator that logs information about calls of decorated functions, the values of its arguments, keyword arguments, and execution time. The log should be written to a file. **Example of Using ** @log def foo(a, b, c): ... foo(1, 2, c=3) log.txt ... foo; args: a=1, b=2; kwargs: c=3; execution time: 0...
[ "Try this\nfrom time import time\n\ndef log(func):\n def wrapper(*args, **kwargs):\n\n start_time = time()\n func(*args, **kwargs)\n end_time = time() - start_time\n \n args_names = func.__code__.co_varnames[:func.__code__.co_argcount]\n args_names ={**dict(zip(args_names, a...
[ 0 ]
[]
[]
[ "decorator", "logging", "python", "python_3.x" ]
stackoverflow_0074631125_decorator_logging_python_python_3.x.txt
Q: Find path between two nodes using Networkx library, Having single source and multiple targets? Hello I'm using networkx library, I have created graph but the i'm having issue in finding multiple targets and target values are bit tricky because target has to be matched with substring within the given target value. ...
Find path between two nodes using Networkx library, Having single source and multiple targets?
Hello I'm using networkx library, I have created graph but the i'm having issue in finding multiple targets and target values are bit tricky because target has to be matched with substring within the given target value. Example: Nodes = ['C0111', 'N6186', 'C5572', 'N6501', 'C0850-IASW-NO01', 'C1182-IUPE-NO01'] Edges = ...
[ "One solution is to use the pattern to subset the target nodes before looking for the shortest paths:\ntarget_nodes = [n for n in G if \"IASW\" in str(n) or \"IUPE\" in str(n)]\n\nWith a list of target nodes, now it's possible to iterate over them and find the shortest path of interest (as you describe).\n" ]
[ 0 ]
[]
[]
[ "networkx", "python", "shortest_path" ]
stackoverflow_0074630352_networkx_python_shortest_path.txt
Q: How to test if a function gets called when another function executes in django test? I've a method inside a manager, this method calls a function imported from different module now I'm trying to write a test that make sure the function gets called, when the manager method executes. I've tried some methods by it di...
How to test if a function gets called when another function executes in django test?
I've a method inside a manager, this method calls a function imported from different module now I'm trying to write a test that make sure the function gets called, when the manager method executes. I've tried some methods by it didn't work here is the code example. hint: I'm using pytest as testrunner from unittest imp...
[ "I assume the function that you want to test is items_bulk_updated.\nSince you are testing ItemsManager.bulk_update() and you want to verify that items_bulk_updated is being called inside that method, the path in your @mock.patch should be the file path where the function is being imported in instead of its origin....
[ 1 ]
[]
[]
[ "django", "pytest_django", "python", "python_unittest" ]
stackoverflow_0074628499_django_pytest_django_python_python_unittest.txt
Q: Long paths in Python on Windows I have a problem when programming in Python running under Windows. I need to work with file paths, that are longer than 256 or whatsathelimit characters. Now, I've read basically about two solutions: Use GetShortPathName from kernel32.dll and access the file in this way. That is...
Long paths in Python on Windows
I have a problem when programming in Python running under Windows. I need to work with file paths, that are longer than 256 or whatsathelimit characters. Now, I've read basically about two solutions: Use GetShortPathName from kernel32.dll and access the file in this way. That is nice, but I cannot use it, since I n...
[ "Well it seems that, as always, I've found the answer to what's been bugging me for a week twenty minutes after I seriously ask somebody about it. \nSo I've found that I need to make sure two things are done correctly:\n\nThe path can contain only backslashes, no forward slashes.\nIf I want to do something like lis...
[ 17, 11, 1, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0029557760_python_windows.txt
Q: Join lines which start with spaces to previous line I have a text file that has some data of the following format that I want to extract and append. I'm new to Python and would like some advice on the approach. Data Format is as follows: Position 1 is a number followed by 5 white spaces followed by non-white spac...
Join lines which start with spaces to previous line
I have a text file that has some data of the following format that I want to extract and append. I'm new to Python and would like some advice on the approach. Data Format is as follows: Position 1 is a number followed by 5 white spaces followed by non-white space of variable length then no more data. However the next...
[ "Just collect lines until you get one which doesn't have the six spaces, and then print what you have accrued so far before starting over. Don't forget to handle the last one when you fall off the end of the loop.\nfn = \"AFilenameHere.txt\"\nlines = []\nwith open(fn, \"r\") as fileObject:\n for line in fileObj...
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074631361_python_regex.txt
Q: I can't log in to Instagram: "CSRF token missing or incorrect" I was using Selenium Python to log in to Instagram and open some pages. It worked fine, but after two days the Instagram started sending the message "CSRF token missing or incorrect". And now I can't even log in with my script or manually to any accoun...
I can't log in to Instagram: "CSRF token missing or incorrect"
I was using Selenium Python to log in to Instagram and open some pages. It worked fine, but after two days the Instagram started sending the message "CSRF token missing or incorrect". And now I can't even log in with my script or manually to any accounts and with any browsers such as Chrome or FireFox on my laptop. I'm...
[ "It seems that the web-Instagram login page has been down for about a week!\nFrom last week until now, most users can't login to Instagram on the web!\nRead chif.j's solution and comments for a temporary fix!\n", "Open your Chrome browser developer tools, and then go to the login page of Instagram. In the network...
[ 14, 12, 2, 1 ]
[]
[]
[ "csrf_token", "instagram", "python", "python_3.x", "selenium" ]
stackoverflow_0074243874_csrf_token_instagram_python_python_3.x_selenium.txt
Q: Passing SSL certificate and key as string to psycopg2.connect My app is deployed in GCP, I'm trying to make a connection to DB using psycopg2. The SSL certificates and key are not stored as files, so I'll be getting them as strings. When I try to make a connection by passing the filepath for these certificate pem ...
Passing SSL certificate and key as string to psycopg2.connect
My app is deployed in GCP, I'm trying to make a connection to DB using psycopg2. The SSL certificates and key are not stored as files, so I'll be getting them as strings. When I try to make a connection by passing the filepath for these certificate pem files, it works. psycopg2.connect(host='hostname',port=1234, connec...
[ "I was facing the same situation a couple of hours ago. What I did to resolve this is creating the files in python with the value of the variable:\ncert = \"\"\"cert\"\"\"\nfile = open(\"cert.txt\",\"w\")\nfile.write(cert)\nfile.close()\n\nAnd then, just pass the path to the psycopg2 connection.\n" ]
[ 0 ]
[]
[]
[ "google_cloud_platform", "postgresql", "psycopg2", "python", "ssl" ]
stackoverflow_0074235247_google_cloud_platform_postgresql_psycopg2_python_ssl.txt
Q: Pathname too long to open? This is a screenshot of the execution: As you see, the error says that the directory "JSONFiles/Apartment/Rent/dubizzleabudhabiproperty" is not there. But look at my files, please: The folder is definitely there. Update 2 The code self.file = open("JSONFiles/"+ item["category"]+"/" + i...
Pathname too long to open?
This is a screenshot of the execution: As you see, the error says that the directory "JSONFiles/Apartment/Rent/dubizzleabudhabiproperty" is not there. But look at my files, please: The folder is definitely there. Update 2 The code self.file = open("JSONFiles/"+ item["category"]+"/" + item["action"]+"/"+ item['source'...
[ "Regular DOS paths are limited to MAX_PATH (260) characters, including the string's terminating NUL character. You can exceed this limit by using an extended-length path that starts with the \\\\?\\ prefix. This path must be a Unicode string, fully qualified, and only use backslash as the path separator. Per Micros...
[ 42, 13, 1, 0, 0 ]
[]
[]
[ "python", "python_2.7", "windows" ]
stackoverflow_0036219317_python_python_2.7_windows.txt