content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Can't install python libraries, common solutions aren't working I know this is a common problem and I've tried the solutions, but I'm stuck. I want to install gazpacho, I do pip3 install <library-name> which works, but in my IDE I still get the No module named 'gazpacho' error. This happens with any library, not j...
Can't install python libraries, common solutions aren't working
I know this is a common problem and I've tried the solutions, but I'm stuck. I want to install gazpacho, I do pip3 install <library-name> which works, but in my IDE I still get the No module named 'gazpacho' error. This happens with any library, not just gazpacho. I've tried python -m pip3 install <library-name> but I ...
[ "In PyCharm there is a terminal(cmd) too. Just install it using a built-in terminal. Because in PyCharm with default settings every project has a virtual environment.\n" ]
[ 1 ]
[]
[]
[ "cmd", "python" ]
stackoverflow_0074226693_cmd_python.txt
Q: Find all words from a list of letters, including duplicate letters? I am trying to write a Python script that more or less mimics the New York Times game Spelling Bee (if you've played it). I have a code that prints out all the words from a list of letters, but I want to be able to repeat letters. For example, fsd...
Find all words from a list of letters, including duplicate letters?
I am trying to write a Python script that more or less mimics the New York Times game Spelling Bee (if you've played it). I have a code that prints out all the words from a list of letters, but I want to be able to repeat letters. For example, fsde produces nothing, but I want feed to be part of the results. Another ex...
[ "Looks like you don't need any combinatorics for this, just a simple set comparison:\nletters = 'etmxr'\n\nwith open('/usr/share/dict/words') as fp:\n for word in fp:\n if set(word.strip()).issubset(letters):\n print(word, end='')\n\nresult:\ne\neer\nem\neme\nemeer\nemmer\nemmet\ner\nere\nerr\n...
[ 2, 1, 0 ]
[]
[]
[ "permutation", "python", "repeat", "string" ]
stackoverflow_0074226662_permutation_python_repeat_string.txt
Q: My python code won't give me other random numbers My code keeps printing out the same numbers even thou i answer the question correctly. This is supposed to be a math game were the code randomizes operations of 2 numbers that the user has to guess import random print("Enter A for addition:") print("Enter B for su...
My python code won't give me other random numbers
My code keeps printing out the same numbers even thou i answer the question correctly. This is supposed to be a math game were the code randomizes operations of 2 numbers that the user has to guess import random print("Enter A for addition:") print("Enter B for subtraction:") print("Enter C for multiplication:") print...
[ "Each time your while loop runs, you need to create two new random numbers. Since you originally had those numbers outside of your loop, they would never change they were outside of the scope of your while loop.\nimport random\n\nprint(\"Enter A for addition:\")\nprint(\"Enter B for subtraction:\")\nprint(\"Enter C...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074226902_python.txt
Q: Python threading.Lock not working as a mutex I'd always assumed a threading.Lock object would act as a mutex to prevent race conditions from occuring in a multithreading Python script, but I'm finding that either my assumption is false (contradicting years of experience), or Python itself has a bug (in, at the ve...
Python threading.Lock not working as a mutex
I'd always assumed a threading.Lock object would act as a mutex to prevent race conditions from occuring in a multithreading Python script, but I'm finding that either my assumption is false (contradicting years of experience), or Python itself has a bug (in, at the very least, versions 2.7-3.9) regarding this. Theor...
[ "It's possible that this is the answer, the lock object must be persistent and shared amongst the threads.\nThis works :\n#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport sys\nimport threading\nimport time\n\nStop = False\n\n\nclass T(threading.Thread):\n\n lock = threading.Lock()\n def __in...
[ 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0074225302_multithreading_python.txt
Q: Draw a rectangle around a string of words using pytesseract Here is my image: I can recognize the words: I need to check if there is a line with specific text in the image and highlight this line with a rectangle. For example. I check if there is "times, it was the worst". And then I expect to see: How can I ac...
Draw a rectangle around a string of words using pytesseract
Here is my image: I can recognize the words: I need to check if there is a line with specific text in the image and highlight this line with a rectangle. For example. I check if there is "times, it was the worst". And then I expect to see: How can I achieve this? My code: import cv2 as cv from pytesseract import pyt...
[ "pytesseract.image_to_data provides line_num for each recognized text block. You can group all the recognitions by line_num and then concatenate words into a text line. Also you need to find a bounding box that includes all the text boxes of each word (you can get them using left, top, width, height). You can find ...
[ 2 ]
[]
[]
[ "document_layout_analysis", "opencv", "python", "tesseract" ]
stackoverflow_0074221064_document_layout_analysis_opencv_python_tesseract.txt
Q: Get substring with code from different strings I'm working on a web scraper. Among the fields it scrapes there is a Description tag like this one, different for each product: <div class="productDescription" style="overflow: hidden; display: block;"> Black Tshirt <br> <br> REF.: V23T87C88EC <br> <br> COMPOSIÇÃO: <b...
Get substring with code from different strings
I'm working on a web scraper. Among the fields it scrapes there is a Description tag like this one, different for each product: <div class="productDescription" style="overflow: hidden; display: block;"> Black Tshirt <br> <br> REF.: V23T87C88EC <br> <br> COMPOSIÇÃO: <br> 90% Poliamida </div> I can get the content of th...
[ "Possible solution is the following:\nhtml = \"\"\"<div class=\"productDescription\" style=\"overflow: hidden; \ndisplay: block;\">\nBlack Tshirt\n<br>\n<br>\nREF.: V23T87C88EC\n<br>\n<br>\nCOMPOSIÇÃO:\n<br>\n90% Poliamida\n</div>\"\"\"\n\nimport re\n\npattern = re.compile(r'REF\\.: (.+?)$')\n\nfound = pattern.fin...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074226485_python.txt
Q: functools.cache - notify that the result is cached import functools @functools.cache def get_some_results(): return results Is there a way to notify the user of the function that the results they are getting are a cached version of the original for any other time they are calling the function? A: This isn'...
functools.cache - notify that the result is cached
import functools @functools.cache def get_some_results(): return results Is there a way to notify the user of the function that the results they are getting are a cached version of the original for any other time they are calling the function?
[ "This isn't a perfect approach, but you could use a custom decorator instead of @functools.cache which would then wrap your function with functools.cache and gather the cache stats before and after the call to determine if the lookup resulted in a cache hit.\nThis was hastily thrown together but seems to work:\ndef...
[ 1 ]
[]
[]
[ "caching", "functools", "python" ]
stackoverflow_0074225875_caching_functools_python.txt
Q: Django timezone.now() giving the time when i started the server I'm using timezone.now() (django.utils impor timezone) to set the initial date of my model. But, the timezone.now() is fixed to the time when i set the server up, and doesnt change. How can i fix this? I wanna that the timezone.now() return the dateti...
Django timezone.now() giving the time when i started the server
I'm using timezone.now() (django.utils impor timezone) to set the initial date of my model. But, the timezone.now() is fixed to the time when i set the server up, and doesnt change. How can i fix this? I wanna that the timezone.now() return the datetime when the user is creating an object and not the time when i run th...
[ "You should pass a reference to the function to it, so:\nfrom django.db import models\nfrom django.utils import timezone\n\n\nclass MyModel(models.Model):\n created_at = models.DateTimeField(default=timezone.now)\nBut likely you want to use auto_now_add=True [Django-doc], which will also make the field non-edita...
[ 0 ]
[]
[]
[ "django", "python", "timezone" ]
stackoverflow_0074226982_django_python_timezone.txt
Q: TypeError: zip argument #1 must support iteration when using lambda function with zip I have some code below that gives me an error message of TypeError: zip argument #1 must support iteration. I believe the error is due to the function: get_account_jira_account_name(year_month, outage['tenant']) returning Emp...
TypeError: zip argument #1 must support iteration when using lambda function with zip
I have some code below that gives me an error message of TypeError: zip argument #1 must support iteration. I believe the error is due to the function: get_account_jira_account_name(year_month, outage['tenant']) returning Empty. I am wondering how can I return an Empty value that can support iteration? def get_acc...
[ "Technically speaking, an empty sequence (empty list, empty string, etc.) is \"an empty value that supports iteration.\"\nHowever, you haven't shown enough of your code for us to know if that solution would actually work in your specific situation.\nIn your function, when the first if statement is true, no return s...
[ 0 ]
[]
[]
[ "lambda", "pandas", "python", "zip" ]
stackoverflow_0074226919_lambda_pandas_python_zip.txt
Q: How to solve the error for import torch on macOs? ImportError Traceback (most recent call last) Input In [1], in <cell line: 1>() ----> 1 import torch File /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/torch/__init__.py:202, in <module> 200 if ...
How to solve the error for import torch on macOs?
ImportError Traceback (most recent call last) Input In [1], in <cell line: 1>() ----> 1 import torch File /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/torch/__init__.py:202, in <module> 200 if USE_GLOBAL_DEPS: 201 _load_global_deps() --...
[ "Check your interpreter (The python version you are using at the moment).\nTo check the Python version in your Jupyter notebook, first import the python_version function with “ from platform import python_version “. Then call the function python_version() that returns a string with the version number running in you...
[ 0 ]
[]
[]
[ "jupyter_notebook", "macos", "python", "pytorch", "torch" ]
stackoverflow_0074227036_jupyter_notebook_macos_python_pytorch_torch.txt
Q: Pandas - Sort dataframe but limit the amount in every page for a specific element in another column I was wondering if there's a way to sort a dataframe by a numeric value but keep just X ocurrencies based on another column? For example, let's say I want to use a dataframe as a catalog and paginate him (so every p...
Pandas - Sort dataframe but limit the amount in every page for a specific element in another column
I was wondering if there's a way to sort a dataframe by a numeric value but keep just X ocurrencies based on another column? For example, let's say I want to use a dataframe as a catalog and paginate him (so every page would have 5 items). And in every 5 items I need to have at max 2 items of the categorical column. pr...
[ "Let us try with cumcount\nout = df.sort_values(by = 'seller', key = lambda x : df.groupby('seller').cumcount()//2)\nOut[145]: \n product seller\n0 10 seller1\n1 9 seller1\n2 8 seller2\n3 7 seller2\n5 5 seller3\n4 6 seller2\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074226865_dataframe_pandas_python.txt
Q: Sample from list of lists until condition is met I have a list of lists that I am randomly choosing a value from. The issue I am having now is that since the loop I wrote is using random.choice() there is the possibility that a given value won't be present, which will cause an error in downstream code. So I basica...
Sample from list of lists until condition is met
I have a list of lists that I am randomly choosing a value from. The issue I am having now is that since the loop I wrote is using random.choice() there is the possibility that a given value won't be present, which will cause an error in downstream code. So I basically want to sample from this list of lists until the f...
[ "You could create a set, which contains all values which are already in the probe in the current \"run\". Then you could always check, whether the size of the set is 8. If you begin a new \"run\", then you have to clear() the set and the probe.\nimport random \n\nprobe_list = [['7', '6'], ['5', '8'], ['3', '2'], ['...
[ 0 ]
[]
[]
[ "psychopy", "python", "random" ]
stackoverflow_0074226817_psychopy_python_random.txt
Q: Data loss when sorting points After finding a large set of points I'm now trying to sort them such that: arr = [(1,2)(1,3)(1,4)(2,1)(2,3)] becomes: [[(1,2)(1,3)(1,4)],[(2,1)(2,3)]] In other words I'm trying to group the points by their x coordinate. I wrote below function to do this: def sortPoints(points): ...
Data loss when sorting points
After finding a large set of points I'm now trying to sort them such that: arr = [(1,2)(1,3)(1,4)(2,1)(2,3)] becomes: [[(1,2)(1,3)(1,4)],[(2,1)(2,3)]] In other words I'm trying to group the points by their x coordinate. I wrote below function to do this: def sortPoints(points): prev = NULL sorted = [] gro...
[ "As mark suggested you should use itertools.groupby for such cases\nfrom itertools import groupby\narr = [(1,2),(1,3),(1,4),(2,1),(2,3)]\narr.sort(key=lambda x: x[0])\n[list(v) for _,v in groupby(arr, lambda y: y[0])]\n# output\n[[(1, 2), (1, 3), (1, 4)], [(2, 1), (2, 3)]]\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074227139_python.txt
Q: Merge PDF Files in subfolders raises FileNotFoundError In my case, I have a main folder "Documents" and inside the folder there are subfolders. Inside the subfolders, there pdf files that I am seeking to merge into one pdf file for each sub folder Here's my try till now import os from PyPDF2 import PdfFileMerger ...
Merge PDF Files in subfolders raises FileNotFoundError
In my case, I have a main folder "Documents" and inside the folder there are subfolders. Inside the subfolders, there pdf files that I am seeking to merge into one pdf file for each sub folder Here's my try till now import os from PyPDF2 import PdfFileMerger myDirectory = 'Documents' mylist = list(map(lambda x: os.pat...
[ "You need to change only this part:\nfor pdf in x:\n merger.append(open(os.path.join(d, pdf), 'rb'))\n\nThe complete code below worked for me.\nimport os\nfrom PyPDF2 import PdfFileMerger\n\nmyDirectory = 'Documents'\nmylist = list(map(lambda x: os.path.join(os.path.abspath(myDirectory), x),os.listdir(myDirector...
[ 1 ]
[]
[]
[ "pdf", "python" ]
stackoverflow_0074227061_pdf_python.txt
Q: Do I need to make a variable for values and keys in dictionaries if I just want input to be keys and to count up 1 for every user input def get_animals(): animals_dict=dict() max_length = 3 while len(animals_dict) < max_length: animals = input("enter an animal:") if animals not in an...
Do I need to make a variable for values and keys in dictionaries if I just want input to be keys and to count up 1 for every user input
def get_animals(): animals_dict=dict() max_length = 3 while len(animals_dict) < max_length: animals = input("enter an animal:") if animals not in animals_dict: print(animals_dict) here is my code so far, I am trying to get user input for different animals, and if the animal is not in t...
[ "You need a dictionary where the key is the animal and the value is the count. You can initialize an unseen animal by doing animals_dict[animals] = 0 then adding the counter every loop:\ndef get_animals():\n animals_dict=dict()\n\n max_length = 3\n\n while len(animals_dict) < max_length:\n animals =...
[ 1 ]
[]
[]
[ "dictionary", "loops", "python" ]
stackoverflow_0074227043_dictionary_loops_python.txt
Q: Additional field to enum members in Python I would like to use enum mechanism properly on Python side. There is a fantastic example for django because the text feature of enum items can be changed without touching enum mechanism. However, I am looking for an example in Python side. I am aware of this support for e...
Additional field to enum members in Python
I would like to use enum mechanism properly on Python side. There is a fantastic example for django because the text feature of enum items can be changed without touching enum mechanism. However, I am looking for an example in Python side. I am aware of this support for enumerations and this post in order to add additi...
[ "Your first two print()s are invalid -- Enum does not work like that.\nTo get something similar to what you want:\nfrom enum import Enum, unique\nclass Animals(Enum):\n #\n CAT = 1, \"Cat\"\n DOG = 2, \"Dog\"\n SHARK = 3, \"custom shark name\"\n #\n def __new__(cls, value, label):\n ...
[ 0 ]
[]
[]
[ "enumerate", "enumeration", "enums", "ienumerable", "python" ]
stackoverflow_0074225249_enumerate_enumeration_enums_ienumerable_python.txt
Q: How to print in python the "right triangle pattern" (5, 54, 543, 5432, 54321) How to print following sequence of number by while loop in python? 5 54 543 5432 54321 Below I show my code: while (i <= n): j = 1 while (j <= 1): print(j,end='') j+=1 print() i += 1 A: i = 5 while i>= ...
How to print in python the "right triangle pattern" (5, 54, 543, 5432, 54321)
How to print following sequence of number by while loop in python? 5 54 543 5432 54321 Below I show my code: while (i <= n): j = 1 while (j <= 1): print(j,end='') j+=1 print() i += 1
[ "i = 5\nwhile i>= 1:\n j = 5\n while j >= i:\n print(j, end=\" \")\n j -= 1\n i-=1\n print()\n\n#try this code.\n", "for i in range(5,0,-1):\n for j in range(5,i-1,-1):\n print(j, end = \" \")\n print()\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074216778_python_while_loop.txt
Q: Folium not recognizing JSON from TravelTime Greeting everyone. I'm attempting to create a isochrone map in Jupyter Notebook/Folium showing how far from downtown Chicago you could get in 45 minutes by car. TravelTime (TravelTime.com) has a ton of excellent APIs to do this, but I'm unable to plot them into Folium/Ju...
Folium not recognizing JSON from TravelTime
Greeting everyone. I'm attempting to create a isochrone map in Jupyter Notebook/Folium showing how far from downtown Chicago you could get in 45 minutes by car. TravelTime (TravelTime.com) has a ton of excellent APIs to do this, but I'm unable to plot them into Folium/Jupyter Notebook. Here's a link to the JSON produce...
[ "Anybody having the same problem as me, see this post by a Travel Time dev to get Travel Time to directly generate a GeoJson for you.\n" ]
[ 0 ]
[]
[]
[ "folium", "json", "jupyter_notebook", "python", "travel_time" ]
stackoverflow_0074225662_folium_json_jupyter_notebook_python_travel_time.txt
Q: Retrieve specific key value pair from nested dictionary within nested list in Python I have below nested list, I want to retrieve only key value pair from this list i.e - 'ticker': 'ABC 0.737 03/15/23' list = [[{'data': [{'figi': 'BBG00ZTHB2X0', 'name': 'AMERISOURCEBERGEN CORP', 'ticker': 'ABC 0.737 03/15/23', '...
Retrieve specific key value pair from nested dictionary within nested list in Python
I have below nested list, I want to retrieve only key value pair from this list i.e - 'ticker': 'ABC 0.737 03/15/23' list = [[{'data': [{'figi': 'BBG00ZTHB2X0', 'name': 'AMERISOURCEBERGEN CORP', 'ticker': 'ABC 0.737 03/15/23', 'exchCode': 'NEW YORK', 'compositeFIGI': None, 'uniqueID': None, 'securityType': 'GLOBAL', ...
[ "If your list has always the same structure, you only have to go step by step until you reach the dictionary from which you want to extract the data.\nHere is an example:\nls = [[{'data': [{'figi': 'BBG00ZTHB2X0', 'name': 'AMERISOURCEBERGEN CORP', 'ticker': 'ABC 0.737 03/15/23', 'exchCode': 'NEW YORK', 'compositeFI...
[ 0 ]
[]
[]
[ "dictionary_comprehension", "list_comprehension", "nested_lists", "python", "python_3.x" ]
stackoverflow_0074227171_dictionary_comprehension_list_comprehension_nested_lists_python_python_3.x.txt
Q: How to get the height of Windows Taskbar using Python/PyQT/Win32 I am trying to make my GUI program align to the bottom-right of the screen on Windows. When the taskbar is not hidden, my program will just stand on top of the taskbar! When using Python/PyQT/Win32, how can I: Check if the taskbar's autohide functio...
How to get the height of Windows Taskbar using Python/PyQT/Win32
I am trying to make my GUI program align to the bottom-right of the screen on Windows. When the taskbar is not hidden, my program will just stand on top of the taskbar! When using Python/PyQT/Win32, how can I: Check if the taskbar's autohide function is on Get the height of the taskbar
[ "As David Heffernan mentioned, you can use GetMonitorInfo with pywin32 to retrieve the monitor size. In particular, the work area will exclude the size of the taskbar.\nTo get the work area size (desktop minus taskbar):\nfrom win32api import GetMonitorInfo, MonitorFromPoint\n\nmonitor_info = GetMonitorInfo(MonitorF...
[ 23, 4, 4, 0 ]
[]
[]
[ "pyqt", "python", "winapi", "windows" ]
stackoverflow_0004357258_pyqt_python_winapi_windows.txt
Q: Django - Call variable on input user text I have a excel data with multiple colums, inside the I have a name colum, now by HTML input the user can write a custom text. I need that the user can use something to call name variable when he like. If use f'User cutsom text {name}' or something like that not work, djang...
Django - Call variable on input user text
I have a excel data with multiple colums, inside the I have a name colum, now by HTML input the user can write a custom text. I need that the user can use something to call name variable when he like. If use f'User cutsom text {name}' or something like that not work, django keep input user text like a text. Do you know...
[ "This question isn't very clear, but based on f'User cutsom text {name}' I assume you are posting HTML input data to a view and then using python to read in a CSV.. there is a way to dynamically format strings\nPre-Knowlege\nYou can dynamically pass any kwargs to any function using **{keyword: value} (this is super...
[ 0 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0074226432_django_django_templates_django_views_python.txt
Q: How can i save a pandas dataframe to csv in overwrite mode? I want to save pandas dataframe to csv in overwrite mode. I want that whenever the program will run again with any changes then it should save the dataframe to csv and overwrite the already saved csv file at the location. A: I think you can do: df.to_cs...
How can i save a pandas dataframe to csv in overwrite mode?
I want to save pandas dataframe to csv in overwrite mode. I want that whenever the program will run again with any changes then it should save the dataframe to csv and overwrite the already saved csv file at the location.
[ "I think you can do:\ndf.to_csv('file_name.csv',mode='w+' )\n\nForm more info goto documentation\n", "Python knows different file modes, among those w stands for\n\nOpens a file for writing only. Overwrites the file if the file exists.\nIf the file does not exist, creates a new file for writing.\n\nBecause w is t...
[ 6, 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0063354050_pandas_python.txt
Q: Using binary search to find the duplicate number in an array The problem: Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array num...
Using binary search to find the duplicate number in an array
The problem: Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space. Here is one of the possible ...
[ "The solution keeps halving the range of numbers the answer can still be in.\nFor example, if the function starts with nums == [1, 3, 4, 2, 2], then the duplicate number must be between 1 and 4 inclusive by definition.\nBy counting how many of the numbers are smaller than or equal to the middle of that range (2), y...
[ 3, 0, 0 ]
[]
[]
[ "arrays", "binary_search", "python" ]
stackoverflow_0074177308_arrays_binary_search_python.txt
Q: Define a @property and @classproperty with the same name (Python, Django) Background The Django LiveServerTestCase class has a live_server_url method with a @classproperty decorator. (django.utils.functional.classproperty.) The class starts its test server before any tests run, and thus knows the test server's URL...
Define a @property and @classproperty with the same name (Python, Django)
Background The Django LiveServerTestCase class has a live_server_url method with a @classproperty decorator. (django.utils.functional.classproperty.) The class starts its test server before any tests run, and thus knows the test server's URL before any tests run. I have a similar MyTestCase class that has a live_server...
[ "One option might be to use a metaclass. (Example)\nBut since I read that metaclasses should usually be avoided, here is what I did:\nfrom django.utils.functional import classproperty\n\n\nclass MyTestCase(TransactionTestCase):\n def __getattribute__(self, attr: str):\n if attr == 'live_server_url':\n ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074227284_django_python.txt
Q: databricks: check if the mountpoint already mounted How to check if the mount point is already mounted before mount in databricks python ?? dbutils.fs.mount Thanks A: Try this: def sub_unmount(str_path): if any(mount.mountPoint == str_path for mount in dbutils.fs.mounts()): dbutils.fs.unmount(str_pa...
databricks: check if the mountpoint already mounted
How to check if the mount point is already mounted before mount in databricks python ?? dbutils.fs.mount Thanks
[ "Try this:\ndef sub_unmount(str_path):\n if any(mount.mountPoint == str_path for mount in dbutils.fs.mounts()):\n dbutils.fs.unmount(str_path)\n\nsub_unmount('/mnt/flightdata')\n\nResult:\n/mnt/flightdata has been unmounted.\nVerify with this:\ndbutils.fs.ls(\"/mnt/\")\n\nInspired by this:\nhttps://forums...
[ 14, 5, 2, 0 ]
[]
[]
[ "azure", "azure_databricks", "databricks", "python" ]
stackoverflow_0058514603_azure_azure_databricks_databricks_python.txt
Q: how to parse a json that contains a list to a more readable json with python? this time I have some strange json that I want to convert to something more readable but I don't know how to do it in Python language: Current json format: {'data': [{'VALUE': '{"filters":[ {"field":"example1","operation":"like","values"...
how to parse a json that contains a list to a more readable json with python?
this time I have some strange json that I want to convert to something more readable but I don't know how to do it in Python language: Current json format: {'data': [{'VALUE': '{"filters":[ {"field":"example1","operation":"like","values":["Completed"]},{"field":"example2","operation":"like","values":["value1","value2",...
[ "Try:\nimport json\n\ndata = {\n \"data\": [\n {\n \"VALUE\": '{\"filters\":[ {\"field\":\"example1\",\"operation\":\"like\",\"values\":[\"Completed\"]},{\"field\":\"example2\",\"operation\":\"like\",\"values\":[\"value1\",\"value2\",\"value3\"]}]}'\n }\n ]\n}\n\ndct = json.loads(data...
[ 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074227405_json_python.txt
Q: How can I use pandas concat instead of pandas append now it is depreciating? I have an empty dataframe and I want to loop over an API call and input data into it based on the stock symbol in my spreadsheet. final_dataframe = final_dataframe.append( pd.Series( [ symbol, data[...
How can I use pandas concat instead of pandas append now it is depreciating?
I have an empty dataframe and I want to loop over an API call and input data into it based on the stock symbol in my spreadsheet. final_dataframe = final_dataframe.append( pd.Series( [ symbol, data[symbol]['price'], data[symbol]['stats']['year1ChangePercent'], ...
[ "Not sure concat supports concatenating a DataFrame with a Series so maybe try .to_frame(), and I've also moved a closing bracket:\nfinal_dataframe = pd.concat([final_dataframe,\n pd.Series(\n [\n symbol,\n data[symbol]['price'],\n data[symbol]['stats']['year1ChangePercent'], \n 'N...
[ 0, 0, 0 ]
[]
[]
[ "append", "concatenation", "pandas", "python" ]
stackoverflow_0070978630_append_concatenation_pandas_python.txt
Q: How to write a python program that finds the first n numbers that are not divisible by any other prime number except 2, 3, and 5 I need to create a program that takes user input n and the finds the first n numbers that aren't divisible by any other prime numbers except 2, 3, and 5. This is what I've got so far: de...
How to write a python program that finds the first n numbers that are not divisible by any other prime number except 2, 3, and 5
I need to create a program that takes user input n and the finds the first n numbers that aren't divisible by any other prime numbers except 2, 3, and 5. This is what I've got so far: def is_divisible(i): for k in range(7, i): if is_prime(k) == 1 and i % k == 0: return 1 else: ...
[ "Here's a bit of code that looks for values that have other factors besides 2,3,5. If there are other factors in there, they must be other prime values because we remove the prime factors 2,3,5 from the number.\nprimes = [ 2, 3, 5] \n\ncount = 10\n\nanswers = []\nvalue = 2\nwhile len(answers) < count:\n \n test_...
[ 1, 1, 0 ]
[]
[]
[ "function", "primes", "python" ]
stackoverflow_0074227007_function_primes_python.txt
Q: Not able to drop a column in a pandas dataframe I am a beginner in data analysis with python, and I am currently stuck on why I keep getting a key error even after looking up multiple sources on how to fix it. Here is a small sample of my data (https://i.stack.imgur.com/X1N4q.png) I have tried running this code: S...
Not able to drop a column in a pandas dataframe
I am a beginner in data analysis with python, and I am currently stuck on why I keep getting a key error even after looking up multiple sources on how to fix it. Here is a small sample of my data (https://i.stack.imgur.com/X1N4q.png) I have tried running this code: SATdf.drop(['School ID'], axis=1, inplace= True) SATdf...
[ "Have you tried SATdf.drop(columns=['School ID','Building Code'], inplace= True) ?\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074227409_pandas_python.txt
Q: Field 'activity_id' expected a number but got <QueryDict: Django I'm creating a small django CRUD project and working on creating the create functionality, however everytime I try to create an activity through teh sites frontend I get the following error Field 'activity_id' expected a number but got <QueryDict: {'...
Field 'activity_id' expected a number but got <QueryDict: Django
I'm creating a small django CRUD project and working on creating the create functionality, however everytime I try to create an activity through teh sites frontend I get the following error Field 'activity_id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['DnM8yrfIrvYgvN6rShEOtR9DFwjpryNtHHs6ytHK1CSAYg...
[ "You create an ActivityForm with the form_data, so:\ndef create_activity(request):\n if request.method == 'POST':\n form = ActivityForm(request.POST) # 🖘 ActivityForm\n if form.is_valid():\n form.save()\n return redirect('name-of-some-view')\n else:\n form = Activi...
[ 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0074227403_django_mysql_python.txt
Q: django queryset: How I can override values in django queryset before sending the response? I am on something where I need to override the values according to the URL parameters. Model: Person Name Alias Alex {"Alex", "Jacob" Alias column is the Array type I get alias from the URL parameter like: example.com/?al...
django queryset: How I can override values in django queryset before sending the response?
I am on something where I need to override the values according to the URL parameters. Model: Person Name Alias Alex {"Alex", "Jacob" Alias column is the Array type I get alias from the URL parameter like: example.com/?alias=Alex here alias = Alex and my query is queryset = Person.objects.filter(name=alias)...
[ "I was able to solve the issue\nfor qs in queryset:\n qs.alias = \"Alex\"\nreturn queryset \n\n" ]
[ 1 ]
[]
[]
[ "django", "django_filter", "django_queryset", "django_rest_framework", "python" ]
stackoverflow_0074223096_django_django_filter_django_queryset_django_rest_framework_python.txt
Q: How to use did you mean and showing results for suggestions from google So basically I would like to use a spell checker for different places, countries, types of foods in my program google search engine does a pretty good job in identifying mistakes in the sentences. Am trying to get the suggestion as a text i ha...
How to use did you mean and showing results for suggestions from google
So basically I would like to use a spell checker for different places, countries, types of foods in my program google search engine does a pretty good job in identifying mistakes in the sentences. Am trying to get the suggestion as a text i have no earthly idea how to do this but here is what I did and it doesn't work....
[ "To use a spell checker for different places, countries, and types of foods in your python program, you can use the pyenchant library. This library provides a wrapper for the Enchant spell checking library, which supports multiple languages and dictionaries.\nExplanation\nThe pyenchant library allows you to create ...
[ 1 ]
[]
[]
[ "google_search", "google_search_api", "python" ]
stackoverflow_0074227426_google_search_google_search_api_python.txt
Q: 1.7 LAB: Adjust values in a list by normalizing_zybook 1.7 LAB: Adjust values in a list by normalising When analysing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This can be done by normalising to values between 0 and 1, or throwing away outliers. Write a pr...
1.7 LAB: Adjust values in a list by normalizing_zybook
1.7 LAB: Adjust values in a list by normalising When analysing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This can be done by normalising to values between 0 and 1, or throwing away outliers. Write a program that first gets a list of integers from input. The inp...
[ "You could use list comprehension:\ninput = [5,30,50,10,70,65]\ninput = input[1:]\noutput = [i - min(input) for i in input]\n\n\nprint(output)\n[20, 40, 0, 60, 55]\n\n", "This may be helpful for your lab:\nuser_int = []\n\nwhile True:\n user_input = int(input())\n user_int.append(int(user_input))\n\n if len(us...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "normalization", "python" ]
stackoverflow_0059939914_normalization_python.txt
Q: Changing date format and x-axis tick labels I have read in a monthly temperature anomalies csv file using Pandas read.csv() function. Years are from 1881 to 2022. I excluded the last 3 months of 202 to avoid -999 values). Date format is yyyy-mm-dd. How can I just plot the year and only one value instead of 12 on t...
Changing date format and x-axis tick labels
I have read in a monthly temperature anomalies csv file using Pandas read.csv() function. Years are from 1881 to 2022. I excluded the last 3 months of 202 to avoid -999 values). Date format is yyyy-mm-dd. How can I just plot the year and only one value instead of 12 on the x-axis (i.e., I don't need 12 1851s, 1852s, et...
[ "You could:\n\nCreate a new column year from your Date column.\nCompute the average temperature for each year (using mean or median): df.groupby(['year']).mean()\n\n", "So, I found a good, but maybe not perfect solution. First thing I needed to do was use parse_dates & infer_datetime_format when reading in the cs...
[ 0, 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074225641_matplotlib_pandas_python.txt
Q: Can I query Microsoft SQL Server using pure Python? I need to query SQL Server from Python in a machine that I don't have admin rights. I can't install drivers in it. I'll query mainly from a Linux machine, but it would be nice if I it can also be used from Windows during development. I want to make a simple query...
Can I query Microsoft SQL Server using pure Python?
I need to query SQL Server from Python in a machine that I don't have admin rights. I can't install drivers in it. I'll query mainly from a Linux machine, but it would be nice if I it can also be used from Windows during development. I want to make a simple query in MS SQL Server with a Python lib. A lib that doesn't n...
[ "A quick search turns up pydts but it's not supported by Microsoft and I have no idea how widely adopted it is or if it's being actively maintained. Here's the GitHub repo.\n" ]
[ 1 ]
[]
[]
[ "python", "sql_server" ]
stackoverflow_0074227339_python_sql_server.txt
Q: Bad Request : The CSRF token has expired. Flask / SQLAlchemy I have an issue while trying to develop a Flask webform to interact with SQLAlchemy. It gives me this CSRF error message even thought I initiated a secret key and the CSRF protection on my app. I don't know where the error comes from I have to use SQLlit...
Bad Request : The CSRF token has expired. Flask / SQLAlchemy
I have an issue while trying to develop a Flask webform to interact with SQLAlchemy. It gives me this CSRF error message even thought I initiated a secret key and the CSRF protection on my app. I don't know where the error comes from I have to use SQLlite and SQLAlchemy as a constraint in building this simple website. ...
[ "You need to render your form using the FlaskForm objects you created.\n<form method=\"POST\">\n{{ form.csrf_token }}\n{{ form.name.label }}\n{{ form.name() }}\n\n{{ form.lastname.label }}\n{{ form.lastname() }}\n\n# ... do this for each field in the testForm class\n\nSide note, when you apply attributes to HTML ta...
[ 0 ]
[]
[]
[ "flask", "flask_wtforms", "python" ]
stackoverflow_0074222469_flask_flask_wtforms_python.txt
Q: Counting number of similar rows short python question: I have the following df with fake data in it: I need to count for each hour (purchase_hour column) the maximum consecutive tickets sold to a show. meaning, I expect to see for 9 AM adel sold 2 consecutive (she sold 4, but not consecutively), and kanye didn't ...
Counting number of similar rows
short python question: I have the following df with fake data in it: I need to count for each hour (purchase_hour column) the maximum consecutive tickets sold to a show. meaning, I expect to see for 9 AM adel sold 2 consecutive (she sold 4, but not consecutively), and kanye didn't sell anything consecutively. For 10 ...
[ "Here's how you can do it:\ndf['tmp'] = (df['ticket_desc'] != df['ticket_desc'].shift()).cumsum()\nresult = df.groupby(\n ['purchase_hour', 'tmp', 'ticket_desc'],\n as_index=False,\n).size().drop(columns='tmp')\n\nLet's make an example:\n>>> df\n ticket_desc purchase_hour\n0 a 9\n1 ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074221378_python.txt
Q: python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S" I would like a python datetime object to output (and use the result in django) like this: Thu the 2nd at 4:30 But I find no way in python to output st, nd, rd, or th like I can with PHP datetime format with the S string (Wh...
python format datetime with "st", "nd", "rd", "th" (english ordinal suffix) like PHP's "S"
I would like a python datetime object to output (and use the result in django) like this: Thu the 2nd at 4:30 But I find no way in python to output st, nd, rd, or th like I can with PHP datetime format with the S string (What they call "English Ordinal Suffix") (http://uk.php.net/manual/en/function.date.php). Is there...
[ "The django.utils.dateformat has a function format that takes two arguments, the first one being the date (a datetime.date [[or datetime.datetime]] instance, where datetime is the module in Python's standard library), the second one being the format string, and returns the resulting formatted string. The uppercase...
[ 31, 24, 10, 6, 1 ]
[ "Following solution I got for above problem:\ndatetime.strptime(mydate, '%dnd %B %Y')\ndatetime.strptime(mydate, '%dst %B %Y')\ndatetime.strptime(mydate, '%dth %B %Y')\ndatetime.strptime(mydate, '%drd %B %Y')\n\n" ]
[ -2 ]
[ "datetime", "django", "format", "php", "python" ]
stackoverflow_0003644417_datetime_django_format_php_python.txt
Q: Why am I getting Internal Server Error when I'm using Flask? I'm currently working on my machine learning svm_hog model. Now I want to connect my model to my flask. However, everytime I click on the prediction button on my webpage, it brings me to a page that says Internal Server Error. My model works just fine, a...
Why am I getting Internal Server Error when I'm using Flask?
I'm currently working on my machine learning svm_hog model. Now I want to connect my model to my flask. However, everytime I click on the prediction button on my webpage, it brings me to a page that says Internal Server Error. My model works just fine, and I think the problem is in my Flask code but I still get error u...
[ "if name=='main':\n app.run(debug=True,port=9989,use_reloader=False)\n\n\nUse above code\nIf you are using jupyter notebook for flask app then I will recommend you\nto switch the spyder ,pycharm or Vs code IDE\nBecause you can easily debug things in IDE as compare to Jupyter notebook\n\n", "If you still encounter...
[ 1, 0 ]
[]
[]
[ "flask", "internal_server_error", "machine_learning", "python" ]
stackoverflow_0068282753_flask_internal_server_error_machine_learning_python.txt
Q: Django Admin add support for HEIC for ImageField please has someone experience with adding support of new image formats to the Django Admin module? I want to use this one called pyheif-pillow-opener pyheif-pillow-opener for HEIC support. It should be registered, but I am not sure where exactly. I tried to install ...
Django Admin add support for HEIC for ImageField
please has someone experience with adding support of new image formats to the Django Admin module? I want to use this one called pyheif-pillow-opener pyheif-pillow-opener for HEIC support. It should be registered, but I am not sure where exactly. I tried to install that module and then in Django Admin upload an image t...
[ "Another solution(add it to admin.py as TS suggest):\ntry:\n from pillow_heif import HeifImagePlugin\nexcept ImportError:\n HeifImagePlugin = None # here you can log a warning\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "heic", "heif", "python" ]
stackoverflow_0067898407_django_django_admin_heic_heif_python.txt
Q: With a PANDAS dataframe, how do I print out the variable name along with the data inside it Using the Python package PANDAS, I have a simple loop where I want to print some data frame information for df in (df1, df2, df3, df4, df5, df6, df7): print(df.keys()) However, I also want to label each dataframe with ...
With a PANDAS dataframe, how do I print out the variable name along with the data inside it
Using the Python package PANDAS, I have a simple loop where I want to print some data frame information for df in (df1, df2, df3, df4, df5, df6, df7): print(df.keys()) However, I also want to label each dataframe with its variable name (ex: df1 or df2). Is there a way to print the variable name? Looking at How do ...
[ "Use zip() to iterate over two lists simultaneously.\ndfs=[df1, df2, df3, df4, df5, df6, df7]\ndfs_names=['df1', 'df2', 'df3', 'df4', 'df5', 'df6', 'df7']\n\nfor name, df in zip(dfs_names, dfs):\n print(n ,df.keys())\n\n" ]
[ 2 ]
[]
[]
[ "dataframe", "pandas", "printing", "python" ]
stackoverflow_0074226731_dataframe_pandas_printing_python.txt
Q: Convert string to name of variable? I have this code: all_list_combinations = itertools.product(#here must be variables) the amount of variables< every time is different so i can't just put variables. So, can I convert name of variables from string to variable or can I put any other code I tried use compile() but...
Convert string to name of variable?
I have this code: all_list_combinations = itertools.product(#here must be variables) the amount of variables< every time is different so i can't just put variables. So, can I convert name of variables from string to variable or can I put any other code I tried use compile() but it didn't work
[ "Just use eval to evaluate the variable by its name:\nmy_variable = ...\nvarible_name = \"my_variable\"\nall_list_combinations = itertools.product(eval(varible_name))\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_itertools", "variables" ]
stackoverflow_0074227652_python_python_itertools_variables.txt
Q: How do I construct pandas DataFrame from nested dictionary Here is my dict: {'ItemA': {'margin': 0.52, 'Factory': 'CA', 'Qty': '50'}, 'ItemB': {'ItemB1': {'margin': 0.4, 'Factory': 'CHI', 'Qty': '80'}, 'ItemB2': {'margin': 0.1,'Factory': 'CHI', 'Qty': '60'}}} How do I convert this dictionary to a da...
How do I construct pandas DataFrame from nested dictionary
Here is my dict: {'ItemA': {'margin': 0.52, 'Factory': 'CA', 'Qty': '50'}, 'ItemB': {'ItemB1': {'margin': 0.4, 'Factory': 'CHI', 'Qty': '80'}, 'ItemB2': {'margin': 0.1,'Factory': 'CHI', 'Qty': '60'}}} How do I convert this dictionary to a data frame like this? Item Item member Margin Factory Qty ...
[ "import pandas as pd\n\ndata = {'ItemA': {'margin': 0.52, 'Factory': 'CA', 'Qty': '50'},\n 'ItemB': {'ItemB1': {'margin': 0.4, 'Factory': 'CHI', 'Qty': '80'},\n 'ItemB2': {'margin': 0.1, 'Factory': 'CHI', 'Qty': '60'}}}\n\nnew_dict = {\n 'Item': [],\n 'Item member': [],\n 'Margin': ...
[ 0 ]
[]
[]
[ "database", "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074226620_database_dataframe_dictionary_pandas_python.txt
Q: Add fixed sequence to each row of a numpy array I have the following cycle: comprehensive_merged_function = np.zeros(shape=(0, 1)) for i in range(256): comprehensive_merged_function = np.append(comprehensive_merged_function, utils.dec_to_bin(i, 8)) comprehensive_merged_function = np.array([list(s) for s ...
Add fixed sequence to each row of a numpy array
I have the following cycle: comprehensive_merged_function = np.zeros(shape=(0, 1)) for i in range(256): comprehensive_merged_function = np.append(comprehensive_merged_function, utils.dec_to_bin(i, 8)) comprehensive_merged_function = np.array([list(s) for s in comprehensive_merged_function]).astype(int) which...
[ "You can use np.hstack(arrays) to combine two arrays. For example:\nimport numpy as np\n\na = np.arange(25).reshape(5, 5)\nb = np.zeros((5, 4), dtype=int) - 1\n\nnp.hstack([a, b])\n\nWhich results in:\narray([[ 0, 1, 2, 3, 4, -1, -1, -1, -1],\n [ 5, 6, 7, 8, 9, -1, -1, -1, -1],\n [10, 11, 12, 13...
[ 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074227547_numpy_python.txt
Q: Can someone help me with random "spawning" in Python I want to do that enemies spawn random but nothing never happens. My idea was that on some time like 0.1 second there is new random coordinate to spawn enemy but I don't know how to use time.sleep in loop without stopping ALL of the code. CODE: import random imp...
Can someone help me with random "spawning" in Python
I want to do that enemies spawn random but nothing never happens. My idea was that on some time like 0.1 second there is new random coordinate to spawn enemy but I don't know how to use time.sleep in loop without stopping ALL of the code. CODE: import random import pygame import sys pygame.init() from pygame.locals imp...
[ "You need to call\npygame.display.update()\n\nto show the circle on the screen.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074227253_python.txt
Q: Python socket.gethostbyaddr(ip) Trying to get a host name from lists of IP's and Hostnames - I'm not getting the desired return when it parses through the IP addresses, it still just returns an IP. example: 192.10.20.1 ouput: Found hostname 192.10.20.1 instead of converting it to the hostname. def reverse_dns(IP):...
Python socket.gethostbyaddr(ip)
Trying to get a host name from lists of IP's and Hostnames - I'm not getting the desired return when it parses through the IP addresses, it still just returns an IP. example: 192.10.20.1 ouput: Found hostname 192.10.20.1 instead of converting it to the hostname. def reverse_dns(IP): try: socket.gethostbyadd...
[ "You need to return the hostname that's returned by gethostbyaddr(). Then\ndef reverse_dns(IP):\n try:\n hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(IP)\n print ('Found hostname', IP)\n return hostname\n except socket.error :\n print (IP)\n return (False)\n\ndef g...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074227491_python.txt
Q: How to check for a list item and the one after it in a list of integers So I want to keep a subtotal but I want to subtract the number from the subtotal if it's smaller than the one to its right. Example: for i in list: if i < i+1: num += int(i) else: num -= int(i) ...
How to check for a list item and the one after it in a list of integers
So I want to keep a subtotal but I want to subtract the number from the subtotal if it's smaller than the one to its right. Example: for i in list: if i < i+1: num += int(i) else: num -= int(i) return num I wanted this code to give me 397 but it adds the 10, doesn't su...
[ "For this use case, I think you want to iterate over the list indexes, not the list values. Then you can easily use the index to fetch the current value and the next value.\nmylist = [100, 100, 100, 10, 100, 5, 1, 1]\n\nfor i in range(len(mylist)):\n curval = mylist[i]\n if i < len(mylist) - 1:\n next...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "integer", "list", "python", "sum" ]
stackoverflow_0074227513_integer_list_python_sum.txt
Q: Python: Trying to Count Number of 1 Bits in an Integer But Missing One 1 Input: n = 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. When I run my code below it appears that only two 1's are recognized ... why is that? ...
Python: Trying to Count Number of 1 Bits in an Integer But Missing One 1
Input: n = 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. When I run my code below it appears that only two 1's are recognized ... why is that? class Solution(object): def hammingWeight(self, n): """ :t...
[ "Python 3.10 introduces int.bit_count() but if you have to implement the algorithm yourself then you can try something like this:\ntest.py:\ndef count(n):\n bits = 0\n\n while n:\n bits += 1\n n &= n - 1\n\n return bits\n\n\ndef main():\n n = 0b110001010000000000111\n c = count(n)\n\n ...
[ 1, 0 ]
[]
[]
[ "bit", "count", "function", "python" ]
stackoverflow_0072441824_bit_count_function_python.txt
Q: link two numpy arrays centered I have the following numpy array blackImg = np.zeros((1920, 1080, 3), np.uint8) I then have another numpy array which is an actual image with a resolution smaller than 1920x1080. I then want to insert the actual image over the black 1920x1080 image. The image should be inserted cent...
link two numpy arrays centered
I have the following numpy array blackImg = np.zeros((1920, 1080, 3), np.uint8) I then have another numpy array which is an actual image with a resolution smaller than 1920x1080. I then want to insert the actual image over the black 1920x1080 image. The image should be inserted centered. Like this:
[ "Assuming:\nImg = np.ones((480, 640, 3), np.uint8)\n\nis the image, then:\nNewImg = np.pad(Img, [(720, 720), (220, 220),(0,0)], mode='constant')\n\nshould add a black padding around the original image. (720, 720) add 720 black pixels at top and bottom (220, 220) adds 220 left and right and (0,0) is to not add paddi...
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074227472_numpy_python.txt
Q: Circular import with python When module A imports B, and B imports A, I get error: ImportError: cannot import name from partially initialized module (most likely due to a circular import). However, if I merge contents of both modules into one, no error happens. Is there a reason why python does not treat circularl...
Circular import with python
When module A imports B, and B imports A, I get error: ImportError: cannot import name from partially initialized module (most likely due to a circular import). However, if I merge contents of both modules into one, no error happens. Is there a reason why python does not treat circularly imported files as one big one? ...
[ "I think the main reason that answers your question lays in that Python is an interpreted language. Your script does not run, it is read by the interpreter line by line subsequently (if a different, specific, pattern is not explicitly coded), and the interpreter executes the code you ask for.\nFor many reasons, one...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074225877_python.txt
Q: python: how to get list item with the combination of first name and second name in the name list I have a list that has names and I want to get the list element which has some part of my string for example: names = ["David Benj Jacob", "Alex"] so if I search with "David Jacob" then how can I get the first element...
python: how to get list item with the combination of first name and second name in the name list
I have a list that has names and I want to get the list element which has some part of my string for example: names = ["David Benj Jacob", "Alex"] so if I search with "David Jacob" then how can I get the first element of the list "David Benj Jacob"? I tried if "David Jacob" in names
[ "You need to check if all parts of the substring are in any of the names\nnames = [\"David Benj Jacob\", \"Alex\"]\nsubstr = \"David Jacob\"\n\nvalid_names = []\nfor name in names:\n if all(part in name for part in substr.split()):\n valid_names.append(name)\n\n", "names = ['David benj Jacob', 'John Leg...
[ 2, 1, 0 ]
[ "Try splitting the querying string to substrings and check if that substring is present in items from an names array.\nnames = [\"David Benj Jacob\", \"Alex\"]\n\ndef search(names: list[str], query: str) -> str:\n # Split words \n split = query.split(\" \")\n\n # Iterate over all names\n for item in nam...
[ -1 ]
[ "list", "python", "string" ]
stackoverflow_0074227568_list_python_string.txt
Q: Threading in Pygame causing Memory leak I am creating an Asteroids Game. the game is intended for use over long periods of time. on startup (using pycharms debugg tool) i am using roughly 30.1 MB of system memory. however i have noticed that while running, it increases by roughly 0.1 MB every second (with a fixed ...
Threading in Pygame causing Memory leak
I am creating an Asteroids Game. the game is intended for use over long periods of time. on startup (using pycharms debugg tool) i am using roughly 30.1 MB of system memory. however i have noticed that while running, it increases by roughly 0.1 MB every second (with a fixed fps of 60). while testing and setting fps to ...
[ "Removed threading entirely. from the issue and fixed the initial image loading of every class instance\n" ]
[ -1 ]
[]
[]
[ "memory_leaks", "pygame", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0074167303_memory_leaks_pygame_python_python_3.x_python_multithreading.txt
Q: How to compare multidimensional two numpy arrays and delete elements from one if the element is also in the other one I have two numpy arrays with shapes (n,3,2) and (n,2). I want to delete the element or elements from the first array(so that it's going to have shape of (n-1),3,2 or (n-2),3,2 etc.) if these are al...
How to compare multidimensional two numpy arrays and delete elements from one if the element is also in the other one
I have two numpy arrays with shapes (n,3,2) and (n,2). I want to delete the element or elements from the first array(so that it's going to have shape of (n-1),3,2 or (n-2),3,2 etc.) if these are also element of the second array. What would be the best way to do something like that? Any help is really appreciated. Let's...
[ "One possible way to achieve this is to use np.isin function, which returns a boolean array indicating whether each element of one array is contained in another array. For example, np.isin(array1, array2) will return a boolean array of shape (n, 3, 2) with True values where the elements of array1 match the elements...
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074227754_arrays_numpy_python.txt
Q: How I can to set array data to the cells in column xlwings I work with excel sheet with python and xlwings I need to format information from column N and set it in column Q I managed to format the date Uploaded data to the array Now I need to upload this data to the Q column I tried different options, but only the...
How I can to set array data to the cells in column xlwings
I work with excel sheet with python and xlwings I need to format information from column N and set it in column Q I managed to format the date Uploaded data to the array Now I need to upload this data to the Q column I tried different options, but only the last value is loaded from the array to the entire column How do...
[ "For my task I find solution in module xlsx writer\nI just need this code from the documentation\nimport xlsxwriter\n\nworkbook = xlsxwriter.Workbook('write_list.xlsx')\nworksheet = workbook.add_worksheet()\nmy_list = [1, 2, 3, 4, 5]\nfor row_num, data in enumerate(my_list):\nworksheet.write(row_num, 0, data)\nwork...
[ 0 ]
[]
[]
[ "excel", "python", "xlwings" ]
stackoverflow_0074212069_excel_python_xlwings.txt
Q: Effect of word length on the popularity of tweets using Python? First, you will write tweet_length The function will take one parameter tweet, a string that represents a tweet The function will return an integer, the number of words in that tweet. Second, you will write average_tweet_length The function will take...
Effect of word length on the popularity of tweets using Python?
First, you will write tweet_length The function will take one parameter tweet, a string that represents a tweet The function will return an integer, the number of words in that tweet. Second, you will write average_tweet_length The function will take one parameter tweet_list, a list of strings (where each string repr...
[ "There are two mistakes:\n\nThis is probably why you get an error. You are trying to access the average variable in the get_long_tweets()-Function, but it's not defined outside the average_tweet_length()-Function, because you are only printing it. And not storing the return value as average\nThe calculation in aver...
[ 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0074227714_python_twitter.txt
Q: Highlighting text in a document from a set that has multi word elements? I need to highlight some text in large documents based on a set of keywords. Seems pretty straightforward, split the text by spaces and check if in list. The issue is that some keywords in the list are multiple words. See my simplified code b...
Highlighting text in a document from a set that has multi word elements?
I need to highlight some text in large documents based on a set of keywords. Seems pretty straightforward, split the text by spaces and check if in list. The issue is that some keywords in the list are multiple words. See my simplified code below from termcolor import cprint text = "I enjoy Virtual Reality games" keyw...
[ "You can try using re module and re.split:\nimport re\nfrom termcolor import cprint\n\ntext = \"I enjoy Virtual Reality games\"\nkeywords = {\"virtual\", \"virtual reality\"} # <-- make it set\n\npat = re.compile(\n r\"\\b(\"\n + \"|\".join(map(re.escape, sorted(keywords, key=len, reverse=True)))\n + r\")...
[ 2 ]
[]
[]
[ "highlight", "python", "split", "string", "text" ]
stackoverflow_0074227744_highlight_python_split_string_text.txt
Q: Selenium: Can't find element by class name in any way I have this problem where I can't access a button trough it's class name in any way I could think of. This is the HTML: <button class="expand-button"> <faceplate-number pretty="" number="18591"><!---->18.591</faceplate-number> weitere Kommentare anzeigen ...
Selenium: Can't find element by class name in any way
I have this problem where I can't access a button trough it's class name in any way I could think of. This is the HTML: <button class="expand-button"> <faceplate-number pretty="" number="18591"><!---->18.591</faceplate-number> weitere Kommentare anzeigen </button> I tried to access it using: driver.find_element(...
[ "Possible issue 1\nIt could be because you check before the element is created in the DOM.\nOne way to solve this problem is by using the waites option like below\ndriver.implicitly_wait(10)\ndriver.get(\"http://somedomain/url_that_delays_loading\")\nmy_dynamic_element = driver.find_element(By.ID, \"myDynamicElemen...
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074227305_python_selenium.txt
Q: subprocess in python cannot create & activate conda venv Currently I am tryting to, in a python script, create a conda venv in a temp dir with a different python version I am using in my system install some packages into this temp conda venv Execute other python script using this new venv Kill the process (which ...
subprocess in python cannot create & activate conda venv
Currently I am tryting to, in a python script, create a conda venv in a temp dir with a different python version I am using in my system install some packages into this temp conda venv Execute other python script using this new venv Kill the process (which is automatic since it is under with .... as ..:) import subpr...
[ "So, the problem is that conda expects your shell to be initialized normally (an interactive shell). But when you use subprocess, you are in a non-login, non-interactive shell. So, one hack would be to manually call the shell startup script. So for example, on my Macbook Pro:\nsubprocess.run([\n f\"\"\"\n con...
[ 0 ]
[]
[]
[ "conda", "python", "subprocess" ]
stackoverflow_0074227760_conda_python_subprocess.txt
Q: How to install psqlparse python package in jupyter? I am trying to install psqlparse package in jupyter with this command: pip install -U psqlparse==1.0rc7 But there is an error. Is there a way I can install this package using jupyter or conda? In addition, the version 1.0rc7 file of this package and the setup.py...
How to install psqlparse python package in jupyter?
I am trying to install psqlparse package in jupyter with this command: pip install -U psqlparse==1.0rc7 But there is an error. Is there a way I can install this package using jupyter or conda? In addition, the version 1.0rc7 file of this package and the setup.py file are available in my system, if it helps. Collecting...
[ "Don't. According to the README, psqlparse is no longer maintained, and the last release was 3 years ago. It was also an rc release, so probably something was left unfinished.\nFind another package.\n" ]
[ 0 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0074227898_postgresql_python.txt
Q: Is there a way to shrink the column width of the drop-down widgets in tkinter ttk Treeview? When I create a treeview with children, it has these widgets to click in the left most column to expand/hide parents. Once I run the program I am able to click and drag to resize this column smaller, but I cannot figure out...
Is there a way to shrink the column width of the drop-down widgets in tkinter ttk Treeview?
When I create a treeview with children, it has these widgets to click in the left most column to expand/hide parents. Once I run the program I am able to click and drag to resize this column smaller, but I cannot figure out how to resize it in code. I honestly haven't tried much because I don't even know where to star...
[ "That column can be identified with the name \"#0\". You can configure the width of that column like any other column, with the column method.\ntree.column('#0', width=10)\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter", "treeview" ]
stackoverflow_0074227897_python_tkinter_treeview.txt
Q: python web scraping Max retries exceeded with url I wish to download a buildings database from BREEAM(Building Research Establishment Environmental Assessment Methodology). It has 65 pages so I would like to write a code to download more efficiently. I had the following code import library from bs4 import Beautifu...
python web scraping Max retries exceeded with url
I wish to download a buildings database from BREEAM(Building Research Establishment Environmental Assessment Methodology). It has 65 pages so I would like to write a code to download more efficiently. I had the following code import library from bs4 import BeautifulSoup import requests Request to website and download H...
[ "For me this already works:\nimport requests\n\nurl = \"https://tools.breeam.com/projects/explore/buildings.jsp?sectionid=0&projectType=Offices&rating=&countryID=56&client=&description=&certBody=&certNo=&developer=&location=London&buildingName=&assessor=&subschemeid=0&Submit=Search\"\n\nresponse = requests.get(url)...
[ 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074225365_python_web_scraping.txt
Q: What is a fast way to change a whole column of a python DataFrame to a single value? I am trying an algorithm to test the sensitivity of a simple machine learning model. For that I need to change all the values of one column to a value that has occured at least once in that column, while keeping the other columns ...
What is a fast way to change a whole column of a python DataFrame to a single value?
I am trying an algorithm to test the sensitivity of a simple machine learning model. For that I need to change all the values of one column to a value that has occured at least once in that column, while keeping the other columns unchanged. This will be then be passed into the model to make a prediction and then we rep...
[ "There is another question: Set value to an entire column of a pandas dataframe.\nYou can use:\ndf = df.assign(column_name=value)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074227981_dataframe_python.txt
Q: What is the regex expression to find everything between --[[ and ]]? I'm trying to clean up some Lua code files using a Python script and regex by removing comments. I'm using the following regular regular expression to find multiline comments: "--\[\[[^]\]]+" For example: --[[ This is a comment on multiple lines ...
What is the regex expression to find everything between --[[ and ]]?
I'm trying to clean up some Lua code files using a Python script and regex by removing comments. I'm using the following regular regular expression to find multiline comments: "--\[\[[^]\]]+" For example: --[[ This is a comment on multiple lines that needs to be removed ]] The expression picks these up without a probl...
[ "You might try a pattern like\n^[^\\S\\n]*--\\[\\[.*(?:\\n(?!.*\\]\\]).*)*\\n.*\\]\\]\n\nRegex demo\n" ]
[ 0 ]
[]
[]
[ "capture", "lua", "python", "regex" ]
stackoverflow_0074227978_capture_lua_python_regex.txt
Q: How to build a python DataFrame starting json results with different structures (some in list, some in dict)? I want to know in which French university libraries 3 books are located (corresponding to 3 urls). I want to get the json data of these 3 urls but all the results are not the same : if a book is in several...
How to build a python DataFrame starting json results with different structures (some in list, some in dict)?
I want to know in which French university libraries 3 books are located (corresponding to 3 urls). I want to get the json data of these 3 urls but all the results are not the same : if a book is in several french libraries, a list is created, but if they are in only 1 library, the results are in a dictionary. This dist...
[ "I don't know what the dataframe should exactly look like at the end, but just put the dict into a list and the magic is hopefully done :)\nimport requests\nimport pandas as pd\n\nurls = ['https://www.sudoc.fr/services/multiwhere/23284545X&format=text/json',\n 'https://www.sudoc.fr/services/multiwhere/056068646&for...
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "json", "python", "python_requests" ]
stackoverflow_0074223224_dataframe_dictionary_json_python_python_requests.txt
Q: GTK Python. How to add a key event in a scrolled window? I'm working with GTK on Python. I have a scrolled window displayed on a window. I'm trying to add a key event that trigger an event when i press ENTER. So far I tried this in different configurations but the key-press-event is never detected : def press_spac...
GTK Python. How to add a key event in a scrolled window?
I'm working with GTK on Python. I have a scrolled window displayed on a window. I'm trying to add a key event that trigger an event when i press ENTER. So far I tried this in different configurations but the key-press-event is never detected : def press_space(self,event): if event.keyval == gtk.keysyms.space: ...
[ "self.treeview.connect(\"row-activated\", self.test)\nself.treeview.set_activate_on_single_click(False)\n\ndef test(self, tree_view, path, column):\n print('Return!')\n\n" ]
[ 0 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0073964272_gtk_python.txt
Q: Invalid NaN comparison for system of Abs/Piecewise equations in SymPy I try to solve a system of equations in python (with sympy) but I get "TypeError: Invalid NaN comparison". The equations are "almost linear" (linear equations but also contains an abs part). For a function f I try to find 2 points [x0, x1] such ...
Invalid NaN comparison for system of Abs/Piecewise equations in SymPy
I try to solve a system of equations in python (with sympy) but I get "TypeError: Invalid NaN comparison". The equations are "almost linear" (linear equations but also contains an abs part). For a function f I try to find 2 points [x0, x1] such that f(x0) = x1 and f(x1) = x0 (so these 2 equations form a system) I have:...
[ "solve is not set up to solve systems of Piecewise equations (which are what the two Abs-equations are turned into). But if you fold the And of the system and then solve each of the possible expressions, you can see the solutions:\n>>> pw=(piecewise_fold(And(ec1.rewrite(Piecewise), ec2.rewrite(Piecewise))))\n>>> fo...
[ 1 ]
[]
[]
[ "equation_solving", "python", "sympy", "typeerror" ]
stackoverflow_0074224719_equation_solving_python_sympy_typeerror.txt
Q: Tkinter image placement I have trouble placing my text where I want. In the following code, my image is placed in the middle of the screen, which is what I want, but my text is at the very botton of the screen, but I want them to be together at the middle. Here is what it displays. from tkinter import * fenetre ...
Tkinter image placement
I have trouble placing my text where I want. In the following code, my image is placed in the middle of the screen, which is what I want, but my text is at the very botton of the screen, but I want them to be together at the middle. Here is what it displays. from tkinter import * fenetre = Tk() width = 350 height = ...
[ "The problem is that you have used expand=YES for the canvas. That means that all extra space in the window will be allocated to the canvas, even if the canvas doesn't use it. This causes any widgets packed below the canvas to be pushed all of the way to the bottom of the window.\nIt's hard to say what the right so...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074227946_python_tkinter.txt
Q: How to select and change every other row's value of a particular column? I have an idea of how to do this but I'm getting stuck putting it all together. I tried: df[::2, 'my_column'] = 0 Because I want to take every other row (i.e. the "::2" selector) of a specific column ('my_column'), and set those values to so...
How to select and change every other row's value of a particular column?
I have an idea of how to do this but I'm getting stuck putting it all together. I tried: df[::2, 'my_column'] = 0 Because I want to take every other row (i.e. the "::2" selector) of a specific column ('my_column'), and set those values to something (0). Error: pandas.errors.InvalidIndexError: (slice(None, None, 2), '...
[ "here is one way to to it\ndf.loc[::2, 'my_column'] = 0\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074228099_pandas_python.txt
Q: Simpler way to send data to mysql with flask Abstract: My problem: I think my code a bit verbose. What I want: Simplify my code in order to make it easier to read and execute. What I use: Python/Flask/MySql I built a simple login and register site with Flask. However I think one of my functions in a route is a bit...
Simpler way to send data to mysql with flask
Abstract: My problem: I think my code a bit verbose. What I want: Simplify my code in order to make it easier to read and execute. What I use: Python/Flask/MySql I built a simple login and register site with Flask. However I think one of my functions in a route is a bit verbose. First I created the route: @app.route('/...
[ "if request.method=='POST' and set(['nome','cpf','cep','whatsapp','aniversario','senha']).issubset(request.form):\nThat might help make the code less \"verbose\", assuming request.form is a list.\nYou could also consider using and ORM, such as SQLAlchemy. It makes the database interaction more pythonic (You won't h...
[ 0 ]
[]
[]
[ "flask", "mysql", "python" ]
stackoverflow_0074225360_flask_mysql_python.txt
Q: Turning loop of string inputs from Excel into Python lists I have an Excel file with three columns (Prefix, Feature, Values). All three are strings in Excel, but I need to turn the 'Values' entry from a string into a list when Prefix and Column equal the loop values. Data looks like this: Prefix Feature Value P...
Turning loop of string inputs from Excel into Python lists
I have an Excel file with three columns (Prefix, Feature, Values). All three are strings in Excel, but I need to turn the 'Values' entry from a string into a list when Prefix and Column equal the loop values. Data looks like this: Prefix Feature Value Prefix_1 Feature1 Value1,Value2,Value3 Prefix_1 Feature2 ...
[ "Use this instead:\nfiltered_input.loc[filtered_input.Feature==column,'Value'].str.split(',').squeeze()\n\n", "Alert\nFrom now on whenever you are trying to work with any pandas column values please avoid using the direct typecast ( bad practice ) and rather use astype() to change value type.\nAnd Now For the sol...
[ 2, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074227813_dataframe_pandas_python.txt
Q: How to scrape tables based on keywords in plain text outside the table There's a website which I want to scrape tables from, however, not all tables. Every table has a description that comes before it, in plain text, and I want to make sure I only scrape the tables which are preceded by "GOOD_KEYWORD", however, I ...
How to scrape tables based on keywords in plain text outside the table
There's a website which I want to scrape tables from, however, not all tables. Every table has a description that comes before it, in plain text, and I want to make sure I only scrape the tables which are preceded by "GOOD_KEYWORD", however, I also need to know whether tables have been skipped so the program needs to c...
[ "A simple approach would be to split the html on the table end tag </table>, filter out non-table items from the resulting list, and then extracting only tables that are in the same list item with the good keyword:\nimport pandas as pd\n\nhtml = '''<html>\n <head></head>\n <body>\n <h2>HTML Table</h2>\n ...
[ 1 ]
[]
[]
[ "beautifulsoup", "pandas", "python" ]
stackoverflow_0074227535_beautifulsoup_pandas_python.txt
Q: Create a dictionary with list index as keys and input data as values I can't figure out how to create a dictionary that will be based on an input of a list of whole numbers (no problem with getting the input) and have the list indexes as keys and input data as values. For example if the input is [75, 48, 23, 89] t...
Create a dictionary with list index as keys and input data as values
I can't figure out how to create a dictionary that will be based on an input of a list of whole numbers (no problem with getting the input) and have the list indexes as keys and input data as values. For example if the input is [75, 48, 23, 89] then the end result should be [(0, 75), (1, 48), (2, 23), (3, 89)].
[ "Use enumerate and convert the result to a list as follows:\nl = # your list\nnew_list = list(enumerate(l))\n\n" ]
[ 1 ]
[ "I'm not 100% sure if I understood your question right but this would generate a dict with the index of the list as keys and their values as values.\nlst = [75, 48, 23, 89]\n\nd = dict(zip(list(range(len(last))), lst))\n\n", "Use enumerate\nvalues = [75, 48, 23, 89]\nresult = list(enumerate(values))\nprint(result...
[ -1, -2 ]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074228111_dictionary_python_python_3.x.txt
Q: Create from DateFrame plot - empty plot i something don't understand and have some question. Thats my data after processing: year date power 0 2019 01-01 43.611 1 2019 01-02 40.811 2 2019 01-03 14.491 3 2019 01-04 12.649 4 2019 01-05 7.295 .. ... ... ... 726 2020 12-2...
Create from DateFrame plot - empty plot
i something don't understand and have some question. Thats my data after processing: year date power 0 2019 01-01 43.611 1 2019 01-02 40.811 2 2019 01-03 14.491 3 2019 01-04 12.649 4 2019 01-05 7.295 .. ... ... ... 726 2020 12-27 0.246 727 2020 12-28 10.500 728 2020 ...
[ "You have one very high value in your dataset.\nEither eliminate this datapoint or set the ylim parameter in your plot to only show a specific range.\nhttps://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.plot.html\nTo not plot the datapoint, you could restrict the data to every row that is ...
[ 2 ]
[]
[]
[ "dataframe", "matplotlib", "pandas", "plot", "python" ]
stackoverflow_0074228130_dataframe_matplotlib_pandas_plot_python.txt
Q: How to make lightweight docker image for python app with pipenv I can produce working image for my python app with following simple Dockerfile: FROM python:3.7 WORKDIR /myapp COPY Pipfile* ./ RUN pip install pipenv RUN pipenv install --system --deploy COPY src . CMD ["python3", "app.py"] However, it will produce ...
How to make lightweight docker image for python app with pipenv
I can produce working image for my python app with following simple Dockerfile: FROM python:3.7 WORKDIR /myapp COPY Pipfile* ./ RUN pip install pipenv RUN pipenv install --system --deploy COPY src . CMD ["python3", "app.py"] However, it will produce ~1 GB image, which can contain temporary files, and is heavy to deplo...
[ "The problem comes when you need things like ciso8601, or some libraries, requiring build process. Build tools are not \"incorporated\" into the both slim and alpine variants, for low-size footprint.\nSo to install deps, you'll have to:\n\nInstall build tools\nDeploy dependencies from Pipfile.lock system-wide\nUnin...
[ 13, 6, 3, 0 ]
[]
[]
[ "alpine_linux", "docker", "dockerfile", "pipenv", "python" ]
stackoverflow_0058300046_alpine_linux_docker_dockerfile_pipenv_python.txt
Q: Download image with selenium python I want get captcha image from browser. I have got a url of this picture, but the this picture changes each updated time (url is constant). Is there any solution to get picture from browser (like 'save picture as' button)? From the other hand, I think it should be work: get scr...
Download image with selenium python
I want get captcha image from browser. I have got a url of this picture, but the this picture changes each updated time (url is constant). Is there any solution to get picture from browser (like 'save picture as' button)? From the other hand, I think it should be work: get screenshot of the browser get position of pi...
[ "Here's a complete example (using google's recaptcha as a target):\nimport urllib\nfrom selenium import webdriver\n\ndriver = webdriver.Firefox()\ndriver.get('http://www.google.com/recaptcha/demo/recaptcha')\n\n# get the image source\nimg = driver.find_element_by_xpath('//div[@id=\"recaptcha_image\"]/img')\nsrc = i...
[ 66, 27, 5, 3, 1, 1, 0 ]
[]
[]
[ "firefox", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0017361742_firefox_python_selenium_selenium_webdriver.txt
Q: Timeout Issues inside Kubernetes Cluster Powerdns I'm running PowerDNS recursor inside my k8s cluster. My python script is on a different pod that is doing rdns to my powerdns rescursor app. I have my hpa Max replica set to 8. However, I do not think the load is the problem here. I'm unsure what to do to resolve t...
Timeout Issues inside Kubernetes Cluster Powerdns
I'm running PowerDNS recursor inside my k8s cluster. My python script is on a different pod that is doing rdns to my powerdns rescursor app. I have my hpa Max replica set to 8. However, I do not think the load is the problem here. I'm unsure what to do to resolve this timeout error that I'm getting below. I can increas...
[ "The error code 12 indicates that the PowerDNS recursor did not receive a response from any of the authoritative servers for the queried domain within the configured timeout. This could be due to network issues, firewall rules, rate limiting, or misconfiguration of the recursor or the authoritative servers.\nPossib...
[ 3 ]
[]
[]
[ "amazon_web_services", "kubernetes", "powerdns", "python", "ubuntu" ]
stackoverflow_0074130752_amazon_web_services_kubernetes_powerdns_python_ubuntu.txt
Q: Python data formatting rows to columns I am trying to scraping the web from there I am getting all the data and I am trying out different formats to represent data. Here is the code: import requests import pandas as pd from bs4 import BeautifulSoup url = "https://99petshops.com.au/Search?brandName=Ziwi%20Peak&ani...
Python data formatting rows to columns
I am trying to scraping the web from there I am getting all the data and I am trying out different formats to represent data. Here is the code: import requests import pandas as pd from bs4 import BeautifulSoup url = "https://99petshops.com.au/Search?brandName=Ziwi%20Peak&animalCode=DOG&storeId=89%2F&page=1" soup = Be...
[ "Try:\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://99petshops.com.au/Search?brandName=Ziwi%20Peak&animalCode=DOG&storeId=89%2F&page=1\"\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\nall_info = []\nfor item in soup.select(\".pd-info\"):\n title =...
[ 3, 1 ]
[]
[]
[ "beautifulsoup", "csv", "pandas", "python", "python_3.x" ]
stackoverflow_0074215950_beautifulsoup_csv_pandas_python_python_3.x.txt
Q: Get usb camera id with open cv2 on windows 10 I have 4 usb cameras interfaced to my computer via usb. Currently I am using opencv-python==4.5.5.64 to connect to the cameras. The problem is, I can't seem to read a unique id of each camera. Currently my code snippet look like below where cameraIndex is an integer. T...
Get usb camera id with open cv2 on windows 10
I have 4 usb cameras interfaced to my computer via usb. Currently I am using opencv-python==4.5.5.64 to connect to the cameras. The problem is, I can't seem to read a unique id of each camera. Currently my code snippet look like below where cameraIndex is an integer. The question is, what should I do after obtaining th...
[ "I had the same problem recently, I was able to find an answer here that uses pywin32 and another here that uses a custom .pyd library. The first answer ended up being easier to implement, here is a snippet:\nimport asyncio\nimport winrt.windows.devices.enumeration as windows_devices\n\n\nCAMERA_NAME = \"Dino-Lite ...
[ 0 ]
[]
[]
[ "camera", "ms_media_foundation", "opencv", "python", "windows" ]
stackoverflow_0073946689_camera_ms_media_foundation_opencv_python_windows.txt
Q: Running flask application in docker container on google run, will not connect to mongodb database I have launched my flask server on google run using docker. Here is my docker file. FROM python:3.9.7-slim # copy the requirements file into the image COPY ./requirements.txt /app/ # switch working directory WORKDIR ...
Running flask application in docker container on google run, will not connect to mongodb database
I have launched my flask server on google run using docker. Here is my docker file. FROM python:3.9.7-slim # copy the requirements file into the image COPY ./requirements.txt /app/ # switch working directory WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends \ bzip2 \ g++ \ ...
[ "Missing an Environment variable, apparently docker automatically ignores your env file?\nI added the mongo url as a env variable\n" ]
[ 0 ]
[]
[]
[ "docker", "google_cloud_platform", "mongodb", "python" ]
stackoverflow_0074226526_docker_google_cloud_platform_mongodb_python.txt
Q: If number is not in list return next highest number + python I need method of checking whether a number exists is a list/series, and if it does not returning the next highest number in the list. For example:- in the list nums = [1,2,3,5,7,8,20] if I were to enter the number 4 the function would return 5 and anythi...
If number is not in list return next highest number + python
I need method of checking whether a number exists is a list/series, and if it does not returning the next highest number in the list. For example:- in the list nums = [1,2,3,5,7,8,20] if I were to enter the number 4 the function would return 5 and anything > 8 < 20 would return 20 and so on. Below is a very basic examp...
[ "Here's one way using standard Python (nums doesn't need to be sorted):\ndef coerce_num(x):\n return min((n for n in nums if n >= x), default=None)\n\n>>> coerce_num(4)\n5\n>>> coerce_num(9)\n20\n\n(added default=None in case no numbers are greater than x)\n", "You can achieve this using the recursive function...
[ 2, 0, 0, 0 ]
[]
[]
[ "coercion", "dataframe", "list", "pandas", "python" ]
stackoverflow_0074227665_coercion_dataframe_list_pandas_python.txt
Q: local variable 'counter' referenced before assignment I am running the below code and getting this error. I am used to c# syntax but this doesn't make any sense The rest of the code is working i have tested. Only counter is the problem at the moment import logging from transformers import pipeline counter = 1 #s...
local variable 'counter' referenced before assignment
I am running the below code and getting this error. I am used to c# syntax but this doesn't make any sense The rest of the code is working i have tested. Only counter is the problem at the moment import logging from transformers import pipeline counter = 1 #summarizer = pipeline("summarization", model="csebuetnlp/mT...
[ "You are changing counter inside your function summarize_text and this is a global variable. By using global counter, you are stating that counter is a global variable, so when you change it, the interpreter knows you are changing the global variable and not a local variable to the function summarize_text called co...
[ 0 ]
[]
[]
[ "python", "python_3.9", "python_3.x" ]
stackoverflow_0074228282_python_python_3.9_python_3.x.txt
Q: Running Dash on a public IP : werkzeug.exceptions.NotFound: 404 Not Found I'm trying to run a Dash app on a VM which is accessible using a public IP (behind a NAT). Here is the basic Dash app: from dash import Dash, html import dash_bootstrap_components as dbc import dash_daq as daq from dash import Input, Output,...
Running Dash on a public IP : werkzeug.exceptions.NotFound: 404 Not Found
I'm trying to run a Dash app on a VM which is accessible using a public IP (behind a NAT). Here is the basic Dash app: from dash import Dash, html import dash_bootstrap_components as dbc import dash_daq as daq from dash import Input, Output, State, dcc from flask import Flask, url_for import os import numpy as np serv...
[ "What happens if you completely omit the setting of the SERVER_NAME configuration variable?\nFlask/Werkzeug does check if the SERVER_NAME you have set in the configuration of your application matches the Host part of the HTTP header sent to the application as part of the HTTP request. If it does not match you get t...
[ 0 ]
[]
[]
[ "flask", "gunicorn", "python" ]
stackoverflow_0073784593_flask_gunicorn_python.txt
Q: Python (If, Then) with DataFrames I have a data frame with months (by year), and ID number. I am trying to calculate the attrition rate, but I am getting stuck on obtaining unique ID counts when a month equals a certain month in pandas. ID. Month 1 Sept. 2022 2 Oct. 2022 etc... with possible duplicates in ID a...
Python (If, Then) with DataFrames
I have a data frame with months (by year), and ID number. I am trying to calculate the attrition rate, but I am getting stuck on obtaining unique ID counts when a month equals a certain month in pandas. ID. Month 1 Sept. 2022 2 Oct. 2022 etc... with possible duplicates in ID and 1.75 years worth of data. ...
[ "You need to use one of the iterator functions, like items().\nfor (columnName, columnData) in data.iteritems():\n if columnName = 'Month'\n [code]\n\n", "The way you do this with a dataframe, conceptually, is to filter the entire dataframe to be just the rows where your comparison is true, and then do...
[ 1, 1, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074228293_dataframe_pandas_python.txt
Q: pipenv sync and pipenv install --system --ignore-pipfile in docker environment According to pipenv official documentation: sync pipenv sync [OPTIONS] Installs all packages specified in Pipfile.lock. install pipenv install [OPTIONS] [PACKAGES]... Installs provided packages and adds them to Pipfile, or (if no packa...
pipenv sync and pipenv install --system --ignore-pipfile in docker environment
According to pipenv official documentation: sync pipenv sync [OPTIONS] Installs all packages specified in Pipfile.lock. install pipenv install [OPTIONS] [PACKAGES]... Installs provided packages and adds them to Pipfile, or (if no packages are given), installs all packages from Pipfile. --ignore-pipfile Ignore Pipfile ...
[ "you can see the notes in Advanced usage of pipenv\n\npipenv install --ignore-pipfile is nearly equivalent to pipenv sync, but pipenv sync will never attempt to re-lock your dependencies as it is considered an atomic operation. pipenv install by default does attempt to re-lock unless using the --deploy flag.\n\nso ...
[ 13, 7, 1, 0 ]
[]
[]
[ "docker", "pip", "pipenv", "python" ]
stackoverflow_0052922688_docker_pip_pipenv_python.txt
Q: Coin flip loop with specific number of heads My instructions: Write a program that “flips” a coin repeatedly and displays the results to the screen. The program only stops when a specific # of heads has been flipped. That number of heads is specified by the user. Your program should output the total number of flip...
Coin flip loop with specific number of heads
My instructions: Write a program that “flips” a coin repeatedly and displays the results to the screen. The program only stops when a specific # of heads has been flipped. That number of heads is specified by the user. Your program should output the total number of flips made during execution. My question is that I don...
[ "There are multiple ways to solve this problem, but considering you are a beginner.\nimport random\n\ntail = 0\nhead = 1\n\nnumber_of_heads = 0\nheads_flips= int(input(\"Enter the amount of flips for heads:\"))\n\n\nwhile number_of_heads < heads_flips:\n flip = random.randrange(2)\n if flip == head:\n ...
[ 0 ]
[]
[]
[ "coin_flipping", "for_loop", "loops", "python", "while_loop" ]
stackoverflow_0074228340_coin_flipping_for_loop_loops_python_while_loop.txt
Q: How to copy a file from s3 into the same exact location? I have tried boto3 copy and copy_object methods but I keep getting this error. Error I am getting: botocore.exceptions.ClientError: An error occurred (InvalidRequest) when calling the CopyObject operation: This copy request is illegal because it is trying to...
How to copy a file from s3 into the same exact location?
I have tried boto3 copy and copy_object methods but I keep getting this error. Error I am getting: botocore.exceptions.ClientError: An error occurred (InvalidRequest) when calling the CopyObject operation: This copy request is illegal because it is trying to copy an object to itself without changing the object’s metada...
[ "You can specify some metadata, eg:\ns3_client.copy_object(Bucket=BUCKET, Key=KEY, CopySource=SOURCE, Metadata={'foo':'bar'})\n\nThis will replace the existing metadata with foo/bar. If you wish to retain the existing metadata too, then you'll need to add it to the Metadata object. Basically, the Metadata needs to ...
[ 1 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "python", "python_3.x" ]
stackoverflow_0074227323_amazon_s3_amazon_web_services_boto3_python_python_3.x.txt
Q: Web scraping is not getting links in selenium using python I am going to scrape all links of product and details of each product. If I use vpn, it's opening product list. But it's not working if I use normal browser or proxy. So far, I tried below code, but no result. from selenium.webdriver import ActionChains fr...
Web scraping is not getting links in selenium using python
I am going to scrape all links of product and details of each product. If I use vpn, it's opening product list. But it's not working if I use normal browser or proxy. So far, I tried below code, but no result. from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdrive...
[ "When you load a site you want to scrape, always inspect what it loads with the network monitor. In this case you see that it loads the data dynamically from an api. This means that you can skip scraping altogether and load the data directly from the api into pandas:\nimport requests\nr = requests.get('https://reds...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074174553_beautifulsoup_python_selenium_selenium_webdriver_web_scraping.txt
Q: Palindrome doesn't work inside of a function I got error of below code while placed in def : " UnboundLocalError: local variable 'czy_to_palindrome' referenced before assignment" It works fine without. DOES NOT WORK: while True: print("Podaj liczbe: ", end="") number = input() czy_to_palindrome = True ...
Palindrome doesn't work inside of a function
I got error of below code while placed in def : " UnboundLocalError: local variable 'czy_to_palindrome' referenced before assignment" It works fine without. DOES NOT WORK: while True: print("Podaj liczbe: ", end="") number = input() czy_to_palindrome = True def palindrome_check(number): for i in...
[ "As they say in the comments, just add a global variable or pass the variable to the function. Here are the two options:\n while True:\n print(\"Podaj liczbe: \", end=\"\")\n number = input()\n czy_to_palindrome = True\n def palindrome_check(number, czy_to_palindrome):\n for ...
[ 0 ]
[]
[]
[ "function", "palindrome", "python" ]
stackoverflow_0074228248_function_palindrome_python.txt
Q: filtering rows which have highest consecutive values in pandas I have a dataframe containing 3 million records. It has two columns, column A and column B which is the timestamp of data gathering. I am trying to split it into multiple dataframes according to the following conditions: First, after grouping by Colum...
filtering rows which have highest consecutive values in pandas
I have a dataframe containing 3 million records. It has two columns, column A and column B which is the timestamp of data gathering. I am trying to split it into multiple dataframes according to the following conditions: First, after grouping by Column A, any group with less than 3 members should be dropped. Second, a...
[ "I reproduced your example with the following code:\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ncolumnA = ['D', 'A', 'A', 'A', 'A', 'C', 'D', 'D', 'F', 'F', 'F', 'F', 'F', 'G', 'B', 'N', 'N', 'N', 'N', 'N', 'N']\ncolumnB = [3, 2, 2, 8, 13, 15, 8, 6, 3, 14, 2, 5, 2, 20, 12, 15, 1, 2,...
[ 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074227360_group_by_pandas_python.txt
Q: Why is MyApp Instance not executing on python run enter image description hereI'm writing a simple code for executing an application in python kivy module I use Pycharm, the syntax is okay but its returning an error saying: File "C:\Users\USER\PycharmProjects\pythonProject7\main.py", line 12, in <module> Tes...
Why is MyApp Instance not executing on python run
enter image description hereI'm writing a simple code for executing an application in python kivy module I use Pycharm, the syntax is okay but its returning an error saying: File "C:\Users\USER\PycharmProjects\pythonProject7\main.py", line 12, in <module> TestNas().run() TypeError: TestNas() missing 1 required p...
[ "First of all TestNas() should be a class and I'm guessing it needs to be a subclass of App() that you imported. So change TestNas() to a class and capitalize App().\nI think this is the code you need:\nimport kivy\nfrom kivy.app import App\nfrom kivy.uix.label import Label\n\n\nclass TestNas(App):\n def build(s...
[ 1 ]
[]
[]
[ "kivy", "python" ]
stackoverflow_0074228318_kivy_python.txt
Q: aggregation with respect to one field except one value of that field I am writing a query to do aggregation with respect to one field, however, I want to exclude this aggregation for one value of that field let coAuthorCutThreshold =100 network.aggregate([ { $group: { _id: '$title', title :{$ne: "class notes"},...
aggregation with respect to one field except one value of that field
I am writing a query to do aggregation with respect to one field, however, I want to exclude this aggregation for one value of that field let coAuthorCutThreshold =100 network.aggregate([ { $group: { _id: '$title', title :{$ne: "class notes"}, count: { $sum: 1 } }} , { $match: { count: { $gt: coAuthorCutThreshold ...
[ "Match in order to filter out the documents you don't want to group before the group stage.\nlet coAuthorCutThreshold = 100\n\nnetwork.aggregate([\n { $match: { title: { $ne: \"class notes\" }}},\n { $group: { _id: '$title', count: { $sum: 1 }}},\n { $match: { count: { $gt: coAuthorCutThreshold }}},\n { $sort: ...
[ 1 ]
[]
[]
[ "aggregation_framework", "javascript", "mongodb", "mongodb_query", "python" ]
stackoverflow_0074227745_aggregation_framework_javascript_mongodb_mongodb_query_python.txt
Q: Converting CSV to HTML Table in Python I'm trying to take data from a .csv file and importing into a HTML table within python. This is the csv file https://www.mediafire.com/?mootyaa33bmijiq Context: The csv is populated with data from a football team [Age group, Round, Opposition, Team Score, Opposition Score, Lo...
Converting CSV to HTML Table in Python
I'm trying to take data from a .csv file and importing into a HTML table within python. This is the csv file https://www.mediafire.com/?mootyaa33bmijiq Context: The csv is populated with data from a football team [Age group, Round, Opposition, Team Score, Opposition Score, Location]. I need to be able to select a spec...
[ "First install pandas:\npip install pandas\n\nThen run:\nimport pandas as pd\n\ncolumns = ['age', 'week', 'opp', 'ACscr', 'OPPscr', 'location']\ndf = pd.read_csv('Crushers.csv', names=columns)\n\n# This you can change it to whatever you want to get\nage_15 = df[df['age'] == 'U15']\n# Other examples:\nbye = df[df['o...
[ 22, 5, 4, 2, 2, 2, 0 ]
[]
[]
[ "html", "html_table", "import_from_csv", "python" ]
stackoverflow_0044320329_html_html_table_import_from_csv_python.txt
Q: Results from Python linearmodels PanelOLS and Stata areg differ For a fixed effect model I was planning to switch from Stata's areg to Python's linearmodels.panel.PanelOLS. But the results are different. In Stata I get R-squared = 0.6047 and in Python I get R-squared = 0.1454. How come that I get so different R-sq...
Results from Python linearmodels PanelOLS and Stata areg differ
For a fixed effect model I was planning to switch from Stata's areg to Python's linearmodels.panel.PanelOLS. But the results are different. In Stata I get R-squared = 0.6047 and in Python I get R-squared = 0.1454. How come that I get so different R-squared from the commands below? Stata command and results: use ./linea...
[ "man. How are you?\nYou are trying to run an absorbing regression (.areg). Specifically, you're trying to run 'a linear regression absorbing one categorical factor'. To do this, you can just run the following model linearmodels.iv.absorbing.AbsorbingLS(endog_variable, exog_variables, categorical_variable_absorb)\nS...
[ 0 ]
[]
[]
[ "linearmodels", "python" ]
stackoverflow_0070954911_linearmodels_python.txt
Q: Match all punctuation not surrounded by alphanumeric characters? I am trying to write a regular expression that removes all non alphanumeric characters from a string, except for those that are surrounded by alphanumeric characters. For example, consider the following three examples. 1. it's -> it's 2. its. -> its ...
Match all punctuation not surrounded by alphanumeric characters?
I am trying to write a regular expression that removes all non alphanumeric characters from a string, except for those that are surrounded by alphanumeric characters. For example, consider the following three examples. 1. it's -> it's 2. its. -> its 3. It's a: beautiful day? I'm =sure it is. The coca-cola (is frozen ri...
[ "If alphanumeric characters can also be word characters like \\w (including an underscore) you can use word boundaries:\n[^a-zA-Z\\s](?<!\\b.\\b)\n\nExplanation\n\n[^a-zA-Z\\s]\n(?<!\\b.\\b) Negative lookbehind, assert not a char to the left surrounded by word boundaries\n\nRegex demo\nOr another alternative using ...
[ 2, 0 ]
[]
[]
[ "punctuation", "python", "python_re", "regex", "string" ]
stackoverflow_0074228080_punctuation_python_python_re_regex_string.txt
Q: Does running pygame usually make computers warm When I run a simple pygame program using PyCharm on my M1 MacBook, I notice that my laptop gets kinda warm after running the program for 5-10 minutes. Is this normal, or does the while loop "tax" the computer. Thanks. Code below: import pygame # INITIALIZE pygame.ini...
Does running pygame usually make computers warm
When I run a simple pygame program using PyCharm on my M1 MacBook, I notice that my laptop gets kinda warm after running the program for 5-10 minutes. Is this normal, or does the while loop "tax" the computer. Thanks. Code below: import pygame # INITIALIZE pygame.init #CREATE THE SCREEN screen=pygame.display.set_mode((...
[ "limit the frames per second to limit CPU usage with pygame.time.Clock.tick The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():\n\nThis method should be called once per frame.\n\nThat means tha...
[ 6 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074228538_pygame_python.txt
Q: make python3.5 as default in AWS? Is there a way to make python3.5 as the default python in AWS. every time i try the next time i connect python2.7 is the default one and pip 6 is the last version, knowing that I did updated it some minutes before. here is the method i followed : amazon_link here is another link ...
make python3.5 as default in AWS?
Is there a way to make python3.5 as the default python in AWS. every time i try the next time i connect python2.7 is the default one and pip 6 is the last version, knowing that I did updated it some minutes before. here is the method i followed : amazon_link here is another link of amazon telling the versions, actuall...
[ "alternatives --set python /usr/bin/python3.5\nand then back if you want to\nalternatives --set python /usr/bin/python2.7\nIf you want to see what it currently points to \nalternatives --display python\nThis is a system-wide setting not just for the current user. The system settings are stored in /etc/alternatives\...
[ 28, 15, 1, 0, 0, 0, 0 ]
[]
[]
[ "amazon_web_services", "default", "pip", "python", "python_3.x" ]
stackoverflow_0045220230_amazon_web_services_default_pip_python_python_3.x.txt
Q: Attempting to find location of values in a pandas Dataframe if certain conditions are met I have this DataFrame. High Close Close Time 2022-10-23 21:41:59.999 19...
Attempting to find location of values in a pandas Dataframe if certain conditions are met
I have this DataFrame. High Close Close Time 2022-10-23 21:41:59.999 19466.02 19461.29 2022-10-23 21:42:59.999 19462.48 19457.83 2022-10-23 21:43:5...
[ "Using regular for loop to iterate over dataframe is slow, instead you should use pandas built-in methods for dataframe because they are much faster.\nSeries has a built-in method diff() that iterates over that series and compares every value to previous one. So you could get 2 new serieses that each has informatio...
[ 1, 1 ]
[]
[]
[ "algorithmic_trading", "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074200820_algorithmic_trading_dataframe_numpy_pandas_python.txt
Q: Django - AttributeError: 'User' object has no attribute 'fullclean' I am working on a Django project on the IntelliJ IDEA IDE. I am writing unit tests in the test.py file for the User model class. When running the test.py file with the command python manage.py test it throws 2 errors on the test_username_cannot_be...
Django - AttributeError: 'User' object has no attribute 'fullclean'
I am working on a Django project on the IntelliJ IDEA IDE. I am writing unit tests in the test.py file for the User model class. When running the test.py file with the command python manage.py test it throws 2 errors on the test_username_cannot_be_blank method and the test_valid_user method. The error is the same for b...
[ "I've never even used Django before, but in 3 seconds of googling I was able to determine that the function is full_clean\n", "You have a typo in the method name. It is full_clean.\n" ]
[ 4, 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0074228586_django_django_models_python.txt
Q: How to replace values in a column from another column in a dataframe based on certain conditions using python? df1: Name Code 2000667 - APPLE IPHONE 2000667 2000667 - APPLE IPHONE 2000667 2005565 - APPLE IPHONE CASE 2005565 - APPLE IPHONE CASE 2005450 ...
How to replace values in a column from another column in a dataframe based on certain conditions using python?
df1: Name Code 2000667 - APPLE IPHONE 2000667 2000667 - APPLE IPHONE 2000667 2005565 - APPLE IPHONE CASE 2005565 - APPLE IPHONE CASE 2005450 2002130 2637440 2637409 2003598 - SAMSUNG ...
[ "Perhaps you could use the Code column plus everything after the first space for non-null columns.\nNote: this would actually work without the .isnull() filter, but I would recommend leaving it so that it's more clear what you're trying to do.\ndf.loc[~df['Name'].isnull(), 'Name'] = df['Code'] + \" \" + df['Name']....
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074228556_dataframe_pandas_python.txt
Q: how can i send mysql database table in a nice tabular format to slack use this code : def test(): conn = pymysql.connect(host=rds_host, user=name, password=password, db=db_name, charset='utf8') curs = conn.cursor(pymysql.cursors.DictCursor) sql = "sql" curs.execute(sql) da = curs.fetchall() ...
how can i send mysql database table in a nice tabular format to slack
use this code : def test(): conn = pymysql.connect(host=rds_host, user=name, password=password, db=db_name, charset='utf8') curs = conn.cursor(pymysql.cursors.DictCursor) sql = "sql" curs.execute(sql) da = curs.fetchall() df = pd.DataFrame(data=da, columns=['sale_date', 'total_amt']) df['to...
[ "The issue is that for formatting regular text (so what you write in the chat), Slack doesn't use fixed-space font. This means that the output won't be aligned (as you have experienced).\nTo fix this, you should wrap the portion of the message you're trying to format properly inside ```. This will tell Slack to use...
[ 0 ]
[]
[]
[ "mysql", "python", "slack" ]
stackoverflow_0074216733_mysql_python_slack.txt