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: Check if word is contained exactly in a Python string I have this case: a = "I run away without you" if "with" in a: print("s") else: print("n") This expression is True. But, I want to print "n", because a has to have exactly "with" and not a substring. How can I do this? A: Maybe you mean this: "with" ...
Check if word is contained exactly in a Python string
I have this case: a = "I run away without you" if "with" in a: print("s") else: print("n") This expression is True. But, I want to print "n", because a has to have exactly "with" and not a substring. How can I do this?
[ "Maybe you mean this:\n\"with\" - True\n\"without\" - False\n\"with xxx\" - True\n\nyou can try: if \"with\" in a.split(\" \"):\n" ]
[ 2 ]
[ "I am not sure I understand the problem you are having but if what you are trying to do is check whether your variable only contains the string \"with\", then use == instead of in\n" ]
[ -1 ]
[ "python", "python_3.x", "string", "substring" ]
stackoverflow_0074315425_python_python_3.x_string_substring.txt
Q: How do I get list of methods in a Python class? I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods? Also see: How can I list the methods in a Python 2.5 module? Looping over a Python / IronPython Obj...
How do I get list of methods in a Python class?
I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods? Also see: How can I list the methods in a Python 2.5 module? Looping over a Python / IronPython Object Methods Finding the methods an object has How d...
[ "An example (listing the methods of the optparse.OptionParser class):\n>>> from optparse import OptionParser\n>>> import inspect\n#python2\n>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)\n[([('__init__', <unbound method OptionParser.__init__>),\n...\n ('add_option', <unbound method OptionParser.ad...
[ 421, 287, 204, 60, 38, 30, 26, 15, 9, 8, 7, 5, 5, 3, 3, 2, 1, 1, 0, 0 ]
[ "This is just an observation. \"encode\" seems to be a method for string objects\nstr_1 = 'a'\nstr_1.encode('utf-8')\n>>> b'a'\n\nHowever, if str1 is inspected for methods, an empty list is returned\ninspect.getmember(str_1, predicate=inspect.ismethod)\n>>> []\n\nSo, maybe I am wrong, but the issue seems to be not ...
[ -1, -1, -1, -2, -6 ]
[ "python" ]
stackoverflow_0001911281_python.txt
Q: How to scrape all review information from website with load more button? I'm a new bee in programming. For my PhD thesis on tourism management, I am trying to extract some data using Beautifulsoup on the website called whatclinic. link https://www.whatclinic.com/dentists/turkey/mugla-province/yalikavak/dt-ufuk-kay...
How to scrape all review information from website with load more button?
I'm a new bee in programming. For my PhD thesis on tourism management, I am trying to extract some data using Beautifulsoup on the website called whatclinic. link https://www.whatclinic.com/dentists/turkey/mugla-province/yalikavak/dt-ufuk-kayhan The given website has some ratings, reviews about clinics that I like to g...
[ "Just to point in a direction, you have to call the ajax request, that provides 10 additional reviews based on an index:\nf'https://www.whatclinic.com/Consumer/Ajax/AjaxReviewsAndFeedbacks.aspx?clinicid=15797&pid=0&index={i}&showAll=False'\n\nExample\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulS...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "web_scraping" ]
stackoverflow_0074313754_beautifulsoup_html_python_web_scraping.txt
Q: Python regex extract MAC addresses from string I need help writing a regular expression, using the python re engine to: Extract all MAC addresses from a text file Extract all strings with the following format: foo bar ... MAC:ADDRESS ... baz bat \r\n Thanks in advance! I tried the following to extract MAC addres...
Python regex extract MAC addresses from string
I need help writing a regular expression, using the python re engine to: Extract all MAC addresses from a text file Extract all strings with the following format: foo bar ... MAC:ADDRESS ... baz bat \r\n Thanks in advance! I tried the following to extract MAC addresses, without luck: import re p = re.compile(ur'((?:(...
[ "I have concocted the following: ([0-9a-fA-F]:?){12} to match MAC addresses in the text.\nHere is how it is supposed to work:\n\n[0-9a-fA-F] matches the characters used to represent hexadecimal numbers\n:? matches an optional colon\n(...){12} - all of this is then grouped and repeated 12 times. 12 because a MAC add...
[ 12, 9, 3, 0, 0 ]
[ "import re\nprint(re.search(\"([a-f0-9A-F]{4}[.]){2}[a-f0-9A-F]{4}\", \"0000.aaaa.bbbb\").group())\n\n[a-f0-9A-F]{4} -> matches for four occurrences of a-f or 0-9, A-F \n\nhere it will search only for one mac in a string.if you want to search for more than one occurance we need to use re.findall.\n\n", "The best ...
[ -1, -1 ]
[ "python", "regex" ]
stackoverflow_0026891833_python_regex.txt
Q: Merge First Row with the second row of column C if columns A & B are null Need to Merge the second row values with the first row of column C if the rows in columns A&B are null. DATA: A B C 12525 1FWE23 1H654D 14654 24798 14654 S56E82 65116 63546 38945 ...
Merge First Row with the second row of column C if columns A & B are null
Need to Merge the second row values with the first row of column C if the rows in columns A&B are null. DATA: A B C 12525 1FWE23 1H654D 14654 24798 14654 S56E82 65116 63546 38945 46456 46485 R68R45 AD545 A5D66 45346 QA6...
[ "You can solve this by shifting column C and concating:\ndf[\"C\"] = df[\"C\"] + df[\"C\"].shift(-1).fillna(\"\")\n\nShifting will put NaN in column C for the last row, hence we fill NaN with \"\".\nTo filter out the rows that have no value in column A, we do:\ndf[df[\"A\"] != \"\"]\n\n>>>\n\n A B ...
[ 1, 0 ]
[]
[]
[ "conditional_statements", "dataframe", "python" ]
stackoverflow_0074315011_conditional_statements_dataframe_python.txt
Q: Python Mocking framework for RabbitMQ We want to mock Rabbitmq calls from python for writing unit test cases. Are there any fwks which provide this capability. A: Instead of mocking the RabbitMQ server itself, you can mock the dependent service on the other side of the external RabbitMQ server. You can do this u...
Python Mocking framework for RabbitMQ
We want to mock Rabbitmq calls from python for writing unit test cases. Are there any fwks which provide this capability.
[ "Instead of mocking the RabbitMQ server itself, you can mock the dependent service on the other side of the external RabbitMQ server. You can do this using an async API simulation/mocking tool.\nFor example you can use Traffic Parrot which can be run in a Docker container as part of your CI/CD pipeline.\nHere is a ...
[ 1 ]
[]
[]
[ "python", "rabbitmq" ]
stackoverflow_0022405741_python_rabbitmq.txt
Q: Python asyncio subprocess code returns "pipe closed by peer or os.write(pipe, data) raised exception." I am trying to convert a synchronous Python process to asyncio. Any ideas what I am doing wrong? This is the synchronous code which successfully starts ffmpeg and converts a directory of webp files into a video....
Python asyncio subprocess code returns "pipe closed by peer or os.write(pipe, data) raised exception."
I am trying to convert a synchronous Python process to asyncio. Any ideas what I am doing wrong? This is the synchronous code which successfully starts ffmpeg and converts a directory of webp files into a video. import subprocess import shlex from os import listdir from os.path import isfile, join output_filename = '...
[ "Self answer:\nInstead of :\n await proc.communicate(input=f.read())\n\nThe correct way to write to stdin in:\n proc.stdin.write(f.read())\n await proc.stdin.drain()\n\nComplete example:\nimport sys\nfrom os import listdir\nfrom os.path import isfile, join\nimport shlex\nimport asyncio\n\noutputfilename = ...
[ 0 ]
[]
[]
[ "ffmpeg", "python", "python_asyncio" ]
stackoverflow_0074313337_ffmpeg_python_python_asyncio.txt
Q: How to restrict setting an attribute outside of constructor? I want to forbid further assignments on some attributes of a class after it was initialized. For instance; no one can explicitly assign any value to 'ssn' (social security number) property after the Person instance 'p' has been initialized. _setattr_ is ...
How to restrict setting an attribute outside of constructor?
I want to forbid further assignments on some attributes of a class after it was initialized. For instance; no one can explicitly assign any value to 'ssn' (social security number) property after the Person instance 'p' has been initialized. _setattr_ is also being called while assigning the value inside _init_ method, ...
[ "The usual way is to use a \"private\" attribute starting with an underscore, and a read-only property for public access:\nimport operator\n\nclass Person(object):\n def __init__(self, name, ssn):\n self.name = name\n self._ssn = ssn\n ssn = property(operator.attrgetter(\"_ssn\"))\n\nNote that t...
[ 16, 7, 5, 2, 0 ]
[]
[]
[ "python", "setattr", "variable_assignment" ]
stackoverflow_0010929004_python_setattr_variable_assignment.txt
Q: Python - How to prepare vote results data for a cluster analysis - transforming and groupby I have imported a csv as a df in python. Below is an example of the data. I was wondering how I should prepare/transform this data. I would like to see which places vote the most similarly and was thinking of using a cluste...
Python - How to prepare vote results data for a cluster analysis - transforming and groupby
I have imported a csv as a df in python. Below is an example of the data. I was wondering how I should prepare/transform this data. I would like to see which places vote the most similarly and was thinking of using a cluster analysis for this. Anyone have an idea how to prepare this data? Thank you Place Vote % yes...
[ "By your description seems you want to pivot the dataframe:\nprint(df.pivot(index=\"Place\", columns=\"Vote\", values=\"% yes\"))\n\nPrints:\nVote Vote 1 Vote 2 Vote 208\nPlace \nPLace A 54.2 34.6 NaN\nPlace B 55.6 65.3 NaN\nPlace C 46.8 35.7 NaN\...
[ 0 ]
[]
[]
[ "cluster_analysis", "data_preprocessing", "data_transform", "group_by", "python" ]
stackoverflow_0074315374_cluster_analysis_data_preprocessing_data_transform_group_by_python.txt
Q: checking assertions in a lambda in python I'm trying to use assertions to show some invariants (mostly in testing) Thus i want to write something like the following: values = [ range(10) ] expected_values = [ range(10) ] map (lambda x: assert x[0] == x[1] ,zip( [ run_function(i) for i in values ], expected_valu...
checking assertions in a lambda in python
I'm trying to use assertions to show some invariants (mostly in testing) Thus i want to write something like the following: values = [ range(10) ] expected_values = [ range(10) ] map (lambda x: assert x[0] == x[1] ,zip( [ run_function(i) for i in values ], expected_values)) If I use this with unittest.assertEqual t...
[ "From the documentation: \n\nNote that functions created with lambda forms cannot contain statements.\n\nassert is a statement.\nSo no, you cannot use the assert statement in a lambda expression.\n", "Unfortunately, assert is a statement and Pythons limited lambdas don't allow that in them. They also restrict thi...
[ 13, 11, 6, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008477346_python.txt
Q: Install Intel python 3.8 (Older Release) I need to download 3.8 python shell script in Linux. But I can not find it anywhere. I found the below script which can be downloaded for Linux but it has Intel python 3.8 only. https://registrationcenter-download.intel.com/akdlm/irc_nas/18720/l_pythoni39_oneapi_p_2022.1.0....
Install Intel python 3.8 (Older Release)
I need to download 3.8 python shell script in Linux. But I can not find it anywhere. I found the below script which can be downloaded for Linux but it has Intel python 3.8 only. https://registrationcenter-download.intel.com/akdlm/irc_nas/18720/l_pythoni39_oneapi_p_2022.1.0.214.... Could you please help me get Intel pyt...
[ "It seems like you're looking for Intel python 3.8. Do get that, you can try creating a new conda environment with the below command:\nconda create -n idp intelpython3_core python=3.8\nconda activate idp\n\nBut if you're only looking for a shell script to install intel python3.8, you need to buy a license. If you d...
[ 1 ]
[]
[]
[ "intel", "intel_oneapi", "linux", "python" ]
stackoverflow_0074311930_intel_intel_oneapi_linux_python.txt
Q: Beginner - Convert dataframe to rows of strings I'm totally new to python. I am trying to use the azure.servicebus module. https://pypi.org/project/azure-servicebus/ I generate rows of json strings, that I want to pass to the servicebus. If I have 2 or more rows, it works.If I only have 1 row, it splits each char ...
Beginner - Convert dataframe to rows of strings
I'm totally new to python. I am trying to use the azure.servicebus module. https://pypi.org/project/azure-servicebus/ I generate rows of json strings, that I want to pass to the servicebus. If I have 2 or more rows, it works.If I only have 1 row, it splits each char in my string into rows. from ayx import Alteryx from ...
[ "try:\nfor colname in df.columns:\n try:\n df[colname] = df[colname].astype('str')\n print(f\"{colname} converted\")\n except ValueError:\n print(f\"{colname} failed\")\n\n" ]
[ 0 ]
[]
[]
[ "alteryx", "amqp", "azure_servicebus_queues", "azureservicebus", "python" ]
stackoverflow_0074315643_alteryx_amqp_azure_servicebus_queues_azureservicebus_python.txt
Q: Drop rows in a pandas dataframe by criteria from another dataframe I have the following dataframe containing scores for a competition as well as a column that counts what number entry for each person. import pandas as pd df = pd.DataFrame({'Name': ['John', 'Jim', 'John','Jim', 'John','Jim','John','Jim','John','Ji...
Drop rows in a pandas dataframe by criteria from another dataframe
I have the following dataframe containing scores for a competition as well as a column that counts what number entry for each person. import pandas as pd df = pd.DataFrame({'Name': ['John', 'Jim', 'John','Jim', 'John','Jim','John','Jim','John','Jim','Jack','Jack','Jack','Jack'],'Score': [10,8,9,3,5,0, 1, 2,3, 4,5,6,8,...
[ "You can use pandas.merge to create another dataframe and drop columns by your condition:\ndf3 = pd.merge(df, df2, on=\"Name\", how=\"left\")\ndf3[df3[\"Entry_No\"] <= df3[\"Limit\"]][df.columns].reset_index(drop=True)\n Name Score Entry_No\n0 John 10 1\n1 Jim 8 1\n2 John 9...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074315453_pandas_python.txt
Q: Why am I getting this error when installing daphne? First time attempting to run py -m pip install daphne from my django project directory: WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] The system can not find the file speci...
Why am I getting this error when installing daphne?
First time attempting to run py -m pip install daphne from my django project directory: WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] The system can not find the file specified: 'C:\Python39\Scripts\automat-visualize.exe' -> ' C...
[ "Had to run PowerShell as admin then pip install scrapy (in my case) to get past the error your reported.\n" ]
[ 3 ]
[ "just start cmd as Administrator, this will solve the problem.\n" ]
[ -1 ]
[ "daphne", "django", "pip", "python" ]
stackoverflow_0067021253_daphne_django_pip_python.txt
Q: How can I use relative importing in Python3 with an if __name__='__main__' block? I am making a package, and the modules within this package have code inside if __name__=='__main__': blocks for testing purposes. But my attempts to use relative imports in these modules causes errors. I have read this thread and th...
How can I use relative importing in Python3 with an if __name__='__main__' block?
I am making a package, and the modules within this package have code inside if __name__=='__main__': blocks for testing purposes. But my attempts to use relative imports in these modules causes errors. I have read this thread and the billion others: Relative imports for the billionth time Before you mark this as a dup...
[ "According to the Module documentation, for __main__ modules, you have to use absolute imports.\n\nNote that relative imports are based on the name of the current module. Since the name of the main module is always \"main\", modules intended for use as the main module of a Python application must always use absolut...
[ 5, 2, 2, 1 ]
[]
[]
[ "python", "python_3.x", "python_import", "python_packaging", "relative_path" ]
stackoverflow_0054489670_python_python_3.x_python_import_python_packaging_relative_path.txt
Q: Perform merge for specific duplicate rows in pandas DataFrame Let's be the following two DataFrames in python: df: code_1 other 19001 white 19009 blue 19008 red df_1: code_1 code_2 19001 00001 19001 00002 19009 00003 19008 00001 I want to merge df with df_1: df_merge = pd.merge(df, df_1, how="left",...
Perform merge for specific duplicate rows in pandas DataFrame
Let's be the following two DataFrames in python: df: code_1 other 19001 white 19009 blue 19008 red df_1: code_1 code_2 19001 00001 19001 00002 19009 00003 19008 00001 I want to merge df with df_1: df_merge = pd.merge(df, df_1, how="left", on=['code_1']) df_merge: code_1 other ...
[ "In my opinion there is no specifc parameter for pandas.merge() that fit your needs, but you could reduce the result by dropping duplicates before merging, assumed there are only duplicates in df_1:\ndf_merge = df.merge(df_1.drop_duplicates('code_1'), how=\"left\", on=['code_1'])\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "merge", "pandas", "python" ]
stackoverflow_0074315555_dataframe_merge_pandas_python.txt
Q: Mouse button 4,5 in python What's the name for mouse button 4 or 5 when importing mouse, does anyone have experience with that? Tried adding if mouse.is_pressed("mouse5") as an example but it didn't work A: You need to use another module called pynput to listen the input. An answer can be find from here: how i c...
Mouse button 4,5 in python
What's the name for mouse button 4 or 5 when importing mouse, does anyone have experience with that? Tried adding if mouse.is_pressed("mouse5") as an example but it didn't work
[ "You need to use another module called pynput to listen the input.\nAn answer can be find from here:\nhow i can use mouse button 4-5 (gamer) with python?\n" ]
[ 0 ]
[]
[]
[ "mouse", "python" ]
stackoverflow_0074315774_mouse_python.txt
Q: Python Aiohttp: cookies behaviour on same domain Hopefully this is not a too stupid question, but I am having trouble with aiohttp cookie processing. Aiohttp's CookieJar class mentions it implements cookie storage adhering to RFC 6265, which states that: cookies for a given host are shared across all the ports on...
Python Aiohttp: cookies behaviour on same domain
Hopefully this is not a too stupid question, but I am having trouble with aiohttp cookie processing. Aiohttp's CookieJar class mentions it implements cookie storage adhering to RFC 6265, which states that: cookies for a given host are shared across all the ports on that host Cookies do not provide isolation by port. I...
[ "I think the correct way of sharing the cookies between clients would be loading the SimpleCookie object of the resp1 to the core_client.session.cookie_jar.\nChanging the code of the test_some_endpoint_as_logged_in to should fix it:\nasync def test_some_endpoint_as_logged_in(auth_client, core_client):\n resp1 = ...
[ 0 ]
[]
[]
[ "aiohttp", "cookies", "pytest_aiohttp", "python" ]
stackoverflow_0074195374_aiohttp_cookies_pytest_aiohttp_python.txt
Q: Dictionary Recursive indenting I have the following code that tries to cover most cases of a dictionary walk, and output it as indented text (indent based on the items' nesting in the dictionary. There are two problems: I think the check at the start, which caters for "raw_list", is a bit of a hack, but I cannot ...
Dictionary Recursive indenting
I have the following code that tries to cover most cases of a dictionary walk, and output it as indented text (indent based on the items' nesting in the dictionary. There are two problems: I think the check at the start, which caters for "raw_list", is a bit of a hack, but I cannot think of a better way I cannot get t...
[ "You are incrementing the level for each element in a loop. Instead, try removing level += 1 and pass incremented level into the recursive call: process_data(item, level + 1).\n", "def process_data(data,level):\n if not isinstance(data,list) and not isinstance(data,dict) :\n print(\"\\t\"*level + str(da...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074315490_python.txt
Q: Gevent functions aren't running asynchronously In this Gevent tutorial it goes over how to spawn multiple threads to run asynchronously. import gevent import random def task(pid): """ Some non-deterministic task """ gevent.sleep(random.randint(0,2)*0.001) print('Task %s done' % pid) def sync...
Gevent functions aren't running asynchronously
In this Gevent tutorial it goes over how to spawn multiple threads to run asynchronously. import gevent import random def task(pid): """ Some non-deterministic task """ gevent.sleep(random.randint(0,2)*0.001) print('Task %s done' % pid) def synchronous(): for i in range(1,10): task(i)...
[ "Add this on the top of your script(1st line of your script)\nfrom gevent import monkey; monkey.patch_all()\n\n", "gevent is mostly used for I/O-bound operations. Your task is CPU-bound. Only one greenlet can be run at a time.\nTo see the impact of gevent, you should perform an I/O-bound task. Below is a modified...
[ 2, 0 ]
[]
[]
[ "asynchronous", "eel", "gevent", "multithreading", "python" ]
stackoverflow_0056482407_asynchronous_eel_gevent_multithreading_python.txt
Q: Why am I getting 'ValueError: DataFrame constructor not properly called!'? I tried to build a dataframe from api request response, but I'm getting this error. url= 'https://www.reddit.com/r/Wallstreetbets/top.json?limit=10&t=year' r= requests.get(url) json= r.json() message_df = pd.DataFrame(json['message']) error...
Why am I getting 'ValueError: DataFrame constructor not properly called!'?
I tried to build a dataframe from api request response, but I'm getting this error. url= 'https://www.reddit.com/r/Wallstreetbets/top.json?limit=10&t=year' r= requests.get(url) json= r.json() message_df = pd.DataFrame(json['message']) error_df = pd.DataFrame(json['error']) message_df.head() ValueError: DataFrame const...
[ "To get proper response from reddit server set User-Agent HTTP header (otherwise you will receive error message instead of proper response):\nimport json\nimport requests\nimport pandas as pd\n\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:106.0) Gecko/20100101 Firefox/106.0\"\n}\...
[ 1, 0 ]
[]
[]
[ "api", "dataframe", "json", "python", "request" ]
stackoverflow_0074315520_api_dataframe_json_python_request.txt
Q: The Grade being given is wrong for any Grade not 16+ or 1, this is for cs50 readability in python import cs50 text = cs50.get_string("Text: ") letters = 0 words = 0 sentences = 0 for char in text: if char.isalpha(): letters += 1 if char.isspace(): words += 1 if char in [".", "!", "...
The Grade being given is wrong for any Grade not 16+ or 1, this is for cs50 readability in python
import cs50 text = cs50.get_string("Text: ") letters = 0 words = 0 sentences = 0 for char in text: if char.isalpha(): letters += 1 if char.isspace(): words += 1 if char in [".", "!", "?"]: sentences += 1 L = (letters * 100.0) / words S = (sentences * 100.0) / words Grade = int...
[ "Count the words. How many words in that sentence? How many spaces? See the problem?\nAdditionallly, the int function drops everything after the decimal (it does not round).\n" ]
[ 0 ]
[]
[]
[ "cs50", "python" ]
stackoverflow_0074310803_cs50_python.txt
Q: I cannot use spacy or load any language models OS: MacOs software: PyCharm Spacy version: 3.4.2 Python version 3.10.0 I'm having a problem with the Spacy package which is I cannot use it at all, I can't load any of the language models. the download is always successful but I can't use/import it at all. import sp...
I cannot use spacy or load any language models
OS: MacOs software: PyCharm Spacy version: 3.4.2 Python version 3.10.0 I'm having a problem with the Spacy package which is I cannot use it at all, I can't load any of the language models. the download is always successful but I can't use/import it at all. import spacy nlp=spacy.load('en_core_web_md') or import en_...
[ "Make sure that you have installed spacy and the models in the same environement.\nCheck with pip list and pip3 list and install the en-core-web-sm accordingly.\n" ]
[ 0 ]
[]
[]
[ "nlp", "python", "python_3.x", "spacy" ]
stackoverflow_0074315309_nlp_python_python_3.x_spacy.txt
Q: Python, adding a "cashback" for every third iteration Our professor gave us a problem of adding a "cashback" mechanism for an online store setting. We are tasked to use a parent class and a child class to use inheritance. Goal: to add 50 after every third purchase What I have so far: Parent: class Shop: def _...
Python, adding a "cashback" for every third iteration
Our professor gave us a problem of adding a "cashback" mechanism for an online store setting. We are tasked to use a parent class and a child class to use inheritance. Goal: to add 50 after every third purchase What I have so far: Parent: class Shop: def __init__(self): self.__balance = 0 def getBalan...
[ "you need to change child perchase method\nfrom this:\nif self.__numpurchase % 3 == 0:\n result = self.getBalance() + 50\n print(result)\n\nto this:\nif self.__numpurchase % 3 == 0:\n self.loadWallet(50)\n\nbecause you don't do anything to balance with result = self.getBalance() + 50 balance stays the same...
[ 0 ]
[]
[]
[ "attributes", "class", "if_statement", "methods", "python" ]
stackoverflow_0074315735_attributes_class_if_statement_methods_python.txt
Q: When I add a string array to the JSON data of an http put request, I get a 400 bad request error I'm trying to call a put request via python but keep getting a 400 bad request error. Here's an example of what I'm basically trying to do: array = ["abc", "def"] myjson = { "array": array } data = json.dumps(myjson)...
When I add a string array to the JSON data of an http put request, I get a 400 bad request error
I'm trying to call a put request via python but keep getting a 400 bad request error. Here's an example of what I'm basically trying to do: array = ["abc", "def"] myjson = { "array": array } data = json.dumps(myjson) headers = {'Content-type': 'application/json', 'data': data} What's strange is that any other kind o...
[ "The code on the server did accept arrays, but only if it was smaller than the current array. It was weird. Instead of a put/post request changing the entry I needed to do a request to create a new entry.\n" ]
[ 0 ]
[]
[]
[ "httprequest", "put", "python" ]
stackoverflow_0074295010_httprequest_put_python.txt
Q: Docker-compose environment variable is not set Project tree /backend .env.dev docker-compose-dev.yml /project I have the following warning: docker-compose -f docker-compose-dev.yml up --build # i am in the /backend directory WARNING: The DB_USER variable is not set. Defaulting to a blank string. WARNING: ...
Docker-compose environment variable is not set
Project tree /backend .env.dev docker-compose-dev.yml /project I have the following warning: docker-compose -f docker-compose-dev.yml up --build # i am in the /backend directory WARNING: The DB_USER variable is not set. Defaulting to a blank string. WARNING: The DB_PASSWORD variable is not set. Defaulting to a...
[ "If the complaint is coming from docker (compose) itself, try to:\n\nrename ./.env.dev to simply .env.dev;\nif not yet, rename .env.dev to .env (default) and remove the env_file entry from your compose. That will certainly work, then you can go back to investigate the issue with env_file.\n\n[1] https://docs.docker...
[ 1 ]
[]
[]
[ "django", "docker", "docker_compose", "python" ]
stackoverflow_0074315381_django_docker_docker_compose_python.txt
Q: Tensorflow: find points in one set closest to each point of another set of different size I want to find the points in one set (interior) closest to each point of another set (boundary) of different (smaller) size. I can do that like this: interior = tf.random.uniform(shape=[18,3], minval=-1.0, maxval=1.0) boundar...
Tensorflow: find points in one set closest to each point of another set of different size
I want to find the points in one set (interior) closest to each point of another set (boundary) of different (smaller) size. I can do that like this: interior = tf.random.uniform(shape=[18,3], minval=-1.0, maxval=1.0) boundary = tf.random.uniform(shape=[12,3], minval=-1.0, maxval=1.0) for i in range(12): interior[...
[ "We can use broadcasting,\nindices = tf.argmin(tf.reduce_sum(tf.math.squared_difference(tf.expand_dims(interior, 1), tf.expand_dims(boundary, 0)), 2), axis=0)\n\nand then\ntf.gather(interior, indices)\n\n" ]
[ 1 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074315543_python_tensorflow.txt
Q: Robot Framework - EDGE IE Mode Automation Possible? Currently Microsft provided solution via Python/Java to achieve this thing with addition two Options such as Edge_executable_Path,attach_to_edge_chrome. But how to achive the same with Robot Framework with IEDriver A: This is how you run Edge in Ie Mode with ro...
Robot Framework - EDGE IE Mode Automation Possible?
Currently Microsft provided solution via Python/Java to achieve this thing with addition two Options such as Edge_executable_Path,attach_to_edge_chrome. But how to achive the same with Robot Framework with IEDriver
[ "This is how you run Edge in Ie Mode with robot framework\n*** Variables ***\n${edgepath} C:\\\\Program Files (x86)\\\\Microsoft\\\\Edge\\\\Application\\\\msedge.exe\n${AccessURL} google.com\n \n*** Keywords ***\nOpen Edge Browser In IE Mode \n ${dic}= Create Dictionary ie.edgechromium=${True} ie...
[ 0, 0 ]
[]
[]
[ "python", "robotframework", "selenium" ]
stackoverflow_0072011522_python_robotframework_selenium.txt
Q: What does it mean torch.rand(1, 3, 64, 64)? I am beginner in PyTorch. In one tutorial, I saw: torch.rand(1, 3, 64, 64), I understand that it creates a Tensor with random numbers following standard normal distribution. The outputs looks like: tensor([[[[0.1352, 0.5110, 0.7585, ..., 0.9067, 0.4730, 0.8077], ...
What does it mean torch.rand(1, 3, 64, 64)?
I am beginner in PyTorch. In one tutorial, I saw: torch.rand(1, 3, 64, 64), I understand that it creates a Tensor with random numbers following standard normal distribution. The outputs looks like: tensor([[[[0.1352, 0.5110, 0.7585, ..., 0.9067, 0.4730, 0.8077], [0.2471, 0.8726, 0.3580, ..., 0.4983, 0.9747,...
[ "These parameters refer to the tensor dimension. In concrete, this code snippet will generate a 4-dimension tensor of random values between 0 and 1.\n", "Most probably the intention of this stroke is to generate a batch of pictures, containing 1 picture with 3 channels (color planes) and resolution 64x64 pixels, ...
[ 1, 1, 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0070973324_python_pytorch.txt
Q: math.cbrt 10x slower than **(1/3) With Python 3.11, there is a new way of computing the cubic root, but it is significantly slower than the old way. Am I missing something? A: You're not really measuring how fast cbrt is, you're measuring function call overhead. # python -m timeit -s 'cbrt = lambda x: x ** (1/3)...
math.cbrt 10x slower than **(1/3)
With Python 3.11, there is a new way of computing the cubic root, but it is significantly slower than the old way. Am I missing something?
[ "You're not really measuring how fast cbrt is, you're measuring function call overhead.\n# python -m timeit -s 'cbrt = lambda x: x ** (1/3)' 'cbrt(131)'\n5000000 loops, best of 5: 73.3 nsec per loop\n# python -m timeit -s 'from math import cbrt' 'cbrt(131)'\n5000000 loops, best of 5: 54.2 nsec per loop\n\nFurthermo...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074315936_python.txt
Q: How to append positional arguments from a file.txt and use them for graphical shapes I have the positional arguments saved in a file, i have opened the file used keywords to get only the circle positionals saved those positionals to s and, when I try to say circle(s) it says I need more arguments even though their...
How to append positional arguments from a file.txt and use them for graphical shapes
I have the positional arguments saved in a file, i have opened the file used keywords to get only the circle positionals saved those positionals to s and, when I try to say circle(s) it says I need more arguments even though their all inside of s. from tkinter import * root = Tk() root.title('Homework 10') canvas = Can...
[ "How does something like this work?\n\"\"\"\nAssuming that files.txt contains information in the below format\ncircle 50 50 25 red\ncircle 100 100 50 blue\ntriangle 75 75 20 yellow\nrectangle 200 200 100 150 purple\n\"\"\"\n\n\nfrom tkinter import *\nroot = Tk()\nroot.title('Homework 10')\ncanvas = Canvas(root, wid...
[ 0 ]
[]
[]
[ "graphics", "python", "shapes", "tkinter" ]
stackoverflow_0074259260_graphics_python_shapes_tkinter.txt
Q: Matplotlib semi-log plot: minor tick marks are gone when range is large When making a semi-log plot (y is log), the minor tick marks (8 in a decade) on the y axis appear automatically, but it seems that when the axis range exceeds 10**10, they disappear. I tried many ways to force them back in, but to no avail. It...
Matplotlib semi-log plot: minor tick marks are gone when range is large
When making a semi-log plot (y is log), the minor tick marks (8 in a decade) on the y axis appear automatically, but it seems that when the axis range exceeds 10**10, they disappear. I tried many ways to force them back in, but to no avail. It might be that they go away for large ranges to avoid overcrowding, but one s...
[ "solution for matplotlib >= 2.0.2\nLet's consider the following example\n\nwhich is produced by this code:\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker\nimport numpy as np\n\ny = np.arange(12)\nx = 10.0**y\n\nfig, ax=plt.subplots()\nax.plot(x,y)\nax.set_xscale(\"log\")\nplt.show()\n\nThe minor ticklab...
[ 59, 1, 1, 1, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0044078409_matplotlib_python.txt
Q: Anaconda and Git Bash in Windows - conda: command not found I've installed Anaconda and set Path environment variable to C:\Anaconda3; C:\Anaconda3\Scripts. Then I try to run in Git Bash conda install python But there is an error message "bash: conda: command not found". I would like to know why. A: To be able ...
Anaconda and Git Bash in Windows - conda: command not found
I've installed Anaconda and set Path environment variable to C:\Anaconda3; C:\Anaconda3\Scripts. Then I try to run in Git Bash conda install python But there is an error message "bash: conda: command not found". I would like to know why.
[ "To be able to run conda on gitbash you need to add it to the path. Many times I've seen that's done by default - as shown in the setup for this workshop. If it doesn't, as it seems your case, then you can run their setup directly by running:\n. /c/Anaconda3/etc/profile.d/conda.sh\n\nAfter running that you should b...
[ 43, 12, 12, 1, 0, 0 ]
[]
[]
[ "anaconda", "git_bash", "python" ]
stackoverflow_0054501167_anaconda_git_bash_python.txt
Q: Is there a function to only extract/return the value of a field with Pymongo? I'm using MongoDB and want to work with it in Python which is needed for my project. I wanted to extract only the value of a specific field with Pymongo. In my case, I tried returning the name of a charging station which is saved in a da...
Is there a function to only extract/return the value of a field with Pymongo?
I'm using MongoDB and want to work with it in Python which is needed for my project. I wanted to extract only the value of a specific field with Pymongo. In my case, I tried returning the name of a charging station which is saved in a database as a document with the attributes name, standard, location, charging capacit...
[ "ok here is something you can give a try:\nchange:\nresult = chargers.findOne().name\n\nto:\nresult = chargers.findOne({\"name\": \"the value of the document name\"}, {\"name\"})\n\nchange the \"value of the document name\" to the filter, like you have a document which has a field {name: \"abc\"}, so type abc in pl...
[ 1 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0074276820_mongodb_pymongo_python.txt
Q: python variable returns None even if variable can be printed right before the return statement This is a part of a simple tokenizer and parser. I don't understand why the get_token() is returning None even if token_value is successfully printed right before return "returning: " + token_value. s = "int i = 2; i <= ...
python variable returns None even if variable can be printed right before the return statement
This is a part of a simple tokenizer and parser. I don't understand why the get_token() is returning None even if token_value is successfully printed right before return "returning: " + token_value. s = "int i = 2; i <= n; i += 5)" cursor = 0 def is_string(c): return c.isalnum() or c == "_" def has_more_tokens():...
[ "the result from get_token() is not returned when it is recursively called. Thus, it returns None.\nfixed this section:\nif string[0] == \" \":\n cursor += 1\n return get_token() #fix here\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "return", "return_value" ]
stackoverflow_0074315929_python_python_3.x_return_return_value.txt
Q: Why am I getting out of memory error on spark driver when trying to read lots of Avro files? No collect operation happening I am trying to read in a large amount of Avro files in subdirectories from s3 using spark.read.load on databricks. I either get an error due to the max result size exceeding spark.driver.maxR...
Why am I getting out of memory error on spark driver when trying to read lots of Avro files? No collect operation happening
I am trying to read in a large amount of Avro files in subdirectories from s3 using spark.read.load on databricks. I either get an error due to the max result size exceeding spark.driver.maxResultSize, or if I increase that limit, the driver runs out of memory. I am not performing any collect operation so I'm not sure ...
[ "I discovered the problem was the spark.sql.sources.parallelPartitionDiscovery.parallelism option. This was set too low for the large number of files I was trying to read, resulting in the driver crashing. Increased the value of this and now my code is working.\n" ]
[ 0 ]
[]
[]
[ "apache_spark", "databricks", "pyspark", "python" ]
stackoverflow_0074306482_apache_spark_databricks_pyspark_python.txt
Q: How to find the offending attribute with a sqlalchemy IntegrityError I have a very simple SqlAlchemy model class User(Base): """ The SQLAlchemy declarative model class for a User object. """ __tablename__ = 'users' id = Column(Integer, primary_key=True) phone = Column(String, unique=True) email...
How to find the offending attribute with a sqlalchemy IntegrityError
I have a very simple SqlAlchemy model class User(Base): """ The SQLAlchemy declarative model class for a User object. """ __tablename__ = 'users' id = Column(Integer, primary_key=True) phone = Column(String, unique=True) email = Column(String, unique=True) When inserting a new User, an IntegrityErr...
[ "You can use the below way to get the underlying code, message, and format the message accordingly.\nexcept exc.IntegrityError as e:\n errorInfo = e.orig.args\n print(errorInfo[0]) #This will give you error code\n print(errorInfo[1]) #This will give you error message\n\nBTW, you have to import e...
[ 8, 7, 6, 0 ]
[ "I normally use a try catch for this.\ntry:\n session.commit()\ncatch: \nstr(sys.exc_info()[0]) + \" \\nDESCRIPTION: \"+ str(sys.exc_info()[1]) + \"\\n\" + str(sys.exc_info()[2])\n\nWhen I encounter an integrity error, I get the following message and I skip that particular transcation and continue with the re...
[ -4 ]
[ "integrity", "python", "sqlalchemy" ]
stackoverflow_0011313490_integrity_python_sqlalchemy.txt
Q: Read Pyspark Dataframe from CSV with different timestamp/date format I have a CSV file that I need to read with Pyspark. The CSV has various date and timestamp fields with timestamp format yyyyMMddHHmmss and date yyyMMdd. Now I need to declare the schema with StructType([StructField()]), can I use the DateType() a...
Read Pyspark Dataframe from CSV with different timestamp/date format
I have a CSV file that I need to read with Pyspark. The CSV has various date and timestamp fields with timestamp format yyyyMMddHHmmss and date yyyMMdd. Now I need to declare the schema with StructType([StructField()]), can I use the DateType() and TimestampType() for those fields? Or I will have problem with my format...
[ "You can use DateType for date and TimestampType for datetime. Additionally, you need to provide dateFormat and timestampFormat options as mentioned here.\nschema = StructType([StructField('datetime_col', TimestampType()), StructField('date_col', DateType())])\n\ndf = spark.read.option(\"header\", True).option(\"da...
[ 0 ]
[]
[]
[ "apache_spark_sql", "dataframe", "pyspark", "python" ]
stackoverflow_0074314527_apache_spark_sql_dataframe_pyspark_python.txt
Q: Python sort list of dicts by multiple dynamic keys, with None values at last position I want to sort a list of dicts (dict_list) (that can also contain nested dicts) by a list of received keys (groups). The values inside the dicts can generally be None. After sorting, None values should generally be palced in the ...
Python sort list of dicts by multiple dynamic keys, with None values at last position
I want to sort a list of dicts (dict_list) (that can also contain nested dicts) by a list of received keys (groups). The values inside the dicts can generally be None. After sorting, None values should generally be palced in the last position. Example when i have the following group list and dict list groups = ["key1",...
[ "Try:\ndef get_values_from_dict(d, keys):\n out = []\n for k in keys:\n\n root = d\n for kk in k.split(\".\"):\n root = root.get(kk)\n if not root:\n break\n\n out.append(root)\n\n return out\n\n\ndef key_function(lst):\n return [(v is None, v) f...
[ -1 ]
[]
[]
[ "dictionary", "list", "python", "python_3.x" ]
stackoverflow_0074316079_dictionary_list_python_python_3.x.txt
Q: FAILED: No config file 'alembic.ini' found I tried to change in Alembic but when I try to run Alembic current I got error. I'm new in alembic, please tell me why I get this error and how can I solve it? I can see alembic.ini in migration folder and also revision identifiers, used by Alembic and everything seems fi...
FAILED: No config file 'alembic.ini' found
I tried to change in Alembic but when I try to run Alembic current I got error. I'm new in alembic, please tell me why I get this error and how can I solve it? I can see alembic.ini in migration folder and also revision identifiers, used by Alembic and everything seems fine. $alembic current No handlers could be found ...
[ "You must cd to the directory that has the alembic.ini to run the alembic command, that is, the alembic.ini must be found in the current working directory; or you can specify the config file location with alembic -c path/to/alembic.ini.\nAnd it seems that your alembic ini is broken, you ought to have script_locatio...
[ 22, 18, 0 ]
[]
[]
[ "alembic", "python" ]
stackoverflow_0028392347_alembic_python.txt
Q: gunicorn ImportError: No module named flask I have an anaconda virtual environment and I have already install flask in the virtual environment using pip when I run my app using $ python app.py then it's working correctly, But when I run it with gunicorn I't showing that no module flask app.py from flask import ...
gunicorn ImportError: No module named flask
I have an anaconda virtual environment and I have already install flask in the virtual environment using pip when I run my app using $ python app.py then it's working correctly, But when I run it with gunicorn I't showing that no module flask app.py from flask import Flask app = Flask(__name__) @app.route('/') def...
[ "i think you forget to add app when run gunicorn\ngunicorn --bind 0.0.0.0:8000 wsgi:app\n\nit will run like this\n→ gunicorn --bind 0.0.0.0:8000 wsgi:app\n[2021-06-06 12:39:44 +0700] [54561] [INFO] Starting gunicorn 20.1.0\n[2021-06-06 12:39:44 +0700] [54561] [INFO] Listening at: http://0.0.0.0:8000 (54561)\n[2021-...
[ 1, 0 ]
[]
[]
[ "flask", "python", "python_2.7" ]
stackoverflow_0057158673_flask_python_python_2.7.txt
Q: Memory issues Converting large CSV file to excel using Python I am trying to convert a large ~ 100mb csv file to xlsx using python. I tried the solution below, but ran into memory issues https://stackoverflow.com/a/62750402/1266723 Solution below solves the memory issue by writing in chunks, but over-writes the fi...
Memory issues Converting large CSV file to excel using Python
I am trying to convert a large ~ 100mb csv file to xlsx using python. I tried the solution below, but ran into memory issues https://stackoverflow.com/a/62750402/1266723 Solution below solves the memory issue by writing in chunks, but over-writes the files. Can someone please recommend how to append to the same file in...
[ "You can use an ExcelWriter to do multiple writes to an xlsx file.\nYou could even read the csv file in chunks:\nn = 1000 # chunksize\nwith pd.read_csv(\"myFile.csv\", chunksize=n) as reader, \\\n pd.ExcelWriter('new_file.xlsx') as writer:\n for i, df in enumerate(reader):\n df.to_excel(writer, index...
[ 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074315298_pandas_python.txt
Q: Retrieve an Object using Multiple Parameters inside of an Url in Django-Rest-Framework How to retrieve an object using multiple parameters in url? Example : 'customer/3/order/1/' or 'customer/<int:customer_pk>/order/<int:pk>/' Using shell i'm able to get the object like this but i can't seem to do it from the view...
Retrieve an Object using Multiple Parameters inside of an Url in Django-Rest-Framework
How to retrieve an object using multiple parameters in url? Example : 'customer/3/order/1/' or 'customer/<int:customer_pk>/order/<int:pk>/' Using shell i'm able to get the object like this but i can't seem to do it from the views. >>> from temp.models import Customer, Order >>> from temp.serializers import CustomerSeri...
[ "We can override queryset:\nclass OrderDetailView(generics.RetrieveDestroyAPIView):\n lookup_field = \"pk\"\n serializer_class = OrderSerializer \n\n def get_queryset(self):\n return Order.objects.filter(customer_id=self.kwargs[\"customer_pk\"])\n\nJust it, retrieve object Order already handled by g...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "django_views", "python" ]
stackoverflow_0074315170_django_django_models_django_rest_framework_django_views_python.txt
Q: How to fix overlapping annotations / text I'm trying to stop annotation text overlapping in my graphs. The method suggested in the accepted answer to Matplotlib overlapping annotations looks extremely promising, however is for bar graphs. I'm having trouble converting the "axis" methods over to what I want to do, ...
How to fix overlapping annotations / text
I'm trying to stop annotation text overlapping in my graphs. The method suggested in the accepted answer to Matplotlib overlapping annotations looks extremely promising, however is for bar graphs. I'm having trouble converting the "axis" methods over to what I want to do, and I don't understand how the text lines up. i...
[ "I just wanted to post here another solution, a small library I wrote to implement this kind of things: https://github.com/Phlya/adjustText\nAn example of the process can be seen here:\n\nHere is the example image:\nimport matplotlib.pyplot as plt\nfrom adjustText import adjust_text\nimport numpy as np\ntogether = ...
[ 187, 9, 5, 0, 0 ]
[]
[]
[ "annotate", "matplotlib", "python" ]
stackoverflow_0019073683_annotate_matplotlib_python.txt
Q: Pygame .blit() not working in class, or in game loop I was following a pygame tutorial, tested to see if the player blit was working and it wasnt, checked for problems but there were none that I could find, and then I tested a .blit() directly in the game loop and that didnt work so I've been stumped for a good bi...
Pygame .blit() not working in class, or in game loop
I was following a pygame tutorial, tested to see if the player blit was working and it wasnt, checked for problems but there were none that I could find, and then I tested a .blit() directly in the game loop and that didnt work so I've been stumped for a good bit now. player class below, "Player_Down" should be irrelev...
[ "There is no problem with the code in the question. Your suspicion that blit does not work is wrong (alos see How to draw images and sprites in pygame?). The code works fine.\nHowever, I suggest passing the screen Surface as an argument to draw method. See the minimal and working example:\nimport pygame\n\npygame.i...
[ 0 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0074316232_pygame_python_python_3.x.txt
Q: java.lang.OutOfMemoryError: Java heap space in Python I can't understand that this error is regarding to Java or Python. I tried to configure Java to increase the size, but it failed. This code is written in Jupyter Notebook. import jpype import numpy import pandas import win32com.client as win32 import os import...
java.lang.OutOfMemoryError: Java heap space in Python
I can't understand that this error is regarding to Java or Python. I tried to configure Java to increase the size, but it failed. This code is written in Jupyter Notebook. import jpype import numpy import pandas import win32com.client as win32 import os import pyspark import EasyExcel from xlrd import open_workbook i...
[ "From https://jpype.readthedocs.io/en/latest/userguide.html#controlling-the-jvm you can send arguments to startJVM.\nIf you want to increase max memory you would use jpype.startJVM(\"-Xmx2g\"). Adjust the actual size to what is needed.\nRun java --help or java -X to get available options.\n" ]
[ 0 ]
[]
[]
[ "excel", "java", "python" ]
stackoverflow_0074316375_excel_java_python.txt
Q: not able to print contents of sql table in python using pretty table import os import time import mysql.connector as ms from prettytable import from_db_cursor mydb=ms.connect(host="localhost",user="root",passwd="12345") mycursor=mydb.cursor() x=input("DATABASE NAME : ") mycursor.execute("show databases") resul...
not able to print contents of sql table in python using pretty table
import os import time import mysql.connector as ms from prettytable import from_db_cursor mydb=ms.connect(host="localhost",user="root",passwd="12345") mycursor=mydb.cursor() x=input("DATABASE NAME : ") mycursor.execute("show databases") result=mycursor.fetchall() if (x,) in result: mydb=ms.connect(host="localh...
[ "The from_db_cursor() function uses the fetchall() method. You can find it here.\nBut since we have a fetchall() in line 22 (i.e., below the query execution in display( ) function), there's nothing left to fetch after that. So, to get the rows again, you'd have to execute the same query again (without another fetch...
[ 1 ]
[]
[]
[ "mysql_connector", "mysql_python", "prettytable", "python", "python_3.x" ]
stackoverflow_0074315444_mysql_connector_mysql_python_prettytable_python_python_3.x.txt
Q: Is there any way when I enter text in Entry widget it added in Combobox widget of tkinter? When I add or edit a customer in Customer table, it does not appear in customer filed of Sales table, so I have to destroy the window and open it again manually or with refresh button. The refresh button also work 1 time, me...
Is there any way when I enter text in Entry widget it added in Combobox widget of tkinter?
When I add or edit a customer in Customer table, it does not appear in customer filed of Sales table, so I have to destroy the window and open it again manually or with refresh button. The refresh button also work 1 time, means when I add or edit another customer in Customer table, then click the refresh button just th...
[ "I did not look further into your code as it is not reproducible and incomplete. You can achieve what you want by binding a callback to your entry widget (e.g. when hitting Return), and in that callback you first get the current values of your combobox, add the text from the entry to that list (= tuple) and then ov...
[ 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074250115_python_tkinter.txt
Q: MongoDB / PyMongo I'm running a script that scrapes a quite large amount of data, and then use a function to upload that data to mongodb. I keep getting hit by connection closed errors and can't figure out why it happens, as the data gets chunked in 5000 sets every time, but when I only run 15.000 sets, it runs fi...
MongoDB / PyMongo
I'm running a script that scrapes a quite large amount of data, and then use a function to upload that data to mongodb. I keep getting hit by connection closed errors and can't figure out why it happens, as the data gets chunked in 5000 sets every time, but when I only run 15.000 sets, it runs fine. When I run 50.000 s...
[ "Error solved by\nexcept pymongo.errors.AutoReconnect as e:\ncollection.insert_many(i)\n\n" ]
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0074301500_mongodb_pymongo_python.txt
Q: Running google colab every day at a specific time I recently have built a Python program that runs on Google Colaboratory, I need to run the program every day at a specific time, So Is there any way to schedule it to run on Google Colab? A: You need to create a notebooks.csv listing all the Colaboratory URLs. Th...
Running google colab every day at a specific time
I recently have built a Python program that runs on Google Colaboratory, I need to run the program every day at a specific time, So Is there any way to schedule it to run on Google Colab?
[ "You need to create a notebooks.csv listing all the Colaboratory URLs. Then use colabctl to run each notebook (In order, synchronously mentioned in the CSV) and then pauses for a period of n seconds of time before running them again.\nYou can then run python colabctl.py <end-string> <sleep-seconds>,\nThere's a gCoo...
[ 17, 6, 2 ]
[ "You can use DeepNote, even the free plan allows to schedule your scripts.\n" ]
[ -1 ]
[ "airflow", "google_colaboratory", "jupyter_notebook", "python" ]
stackoverflow_0061762045_airflow_google_colaboratory_jupyter_notebook_python.txt
Q: Why read_utf8() gives TypeError: '<' not supported between instances of 'int' and 'NoneType' in Apache Beam/ python I was following the doc and wanted to access filename and content when reading text files. I have the text files in GCP storage, (in compressed format - gzip) while trying to read the files it gives ...
Why read_utf8() gives TypeError: '<' not supported between instances of 'int' and 'NoneType' in Apache Beam/ python
I was following the doc and wanted to access filename and content when reading text files. I have the text files in GCP storage, (in compressed format - gzip) while trying to read the files it gives me the error as below: Error message from worker: Traceback (most recent call last): File "apache_beam/runners/common.p...
[ "If you want to access to the filename and content when you are reading text file from Cloud Storage with Beam Python, you can use the following code :\nPCollection<KV<String, String>> filesAndLines = \n p.apply(FileIO.match().filepattern(...))\n .apply(FileIO.read())\n .apply(ParDo.of(new DoFn<ReadableFile, K...
[ 0, 0 ]
[]
[]
[ "apache_beam", "batch_processing", "google_cloud_dataflow", "pipeline", "python" ]
stackoverflow_0074300725_apache_beam_batch_processing_google_cloud_dataflow_pipeline_python.txt
Q: How to convert python int into numpy.int64? Given a variable in python of type int, e.g. z = 50 type(z) ## outputs <class 'int'> is there a straightforward way to convert this variable into numpy.int64? It appears one would have to convert this variable into a numpy array, and then convert this into int64. Tha...
How to convert python int into numpy.int64?
Given a variable in python of type int, e.g. z = 50 type(z) ## outputs <class 'int'> is there a straightforward way to convert this variable into numpy.int64? It appears one would have to convert this variable into a numpy array, and then convert this into int64. That feels quite convoluted. https://docs.scipy.org/...
[ "z_as_int64 = numpy.int64(z)\n\nIt's that simple. Make sure you have a good reason, though - there are a few good reasons to do this, but most of the time, you can just use a regular int directly.\n", "import numpy as np\nz = 3\nz = np.dtype('int64').type(z)\nprint(type(z))\n\noutputs:\n<class 'numpy.int64'>\n\nB...
[ 42, 10, 0 ]
[]
[]
[ "int", "numpy", "python" ]
stackoverflow_0046699280_int_numpy_python.txt
Q: Can Transcrypt produce React class components? I've tried to convert the Transcrypt react example to use a class component. Full code at the end but the main change is to convert this function component: def ListItems(props): items = props['items'] return [el('li', {'key': item}, item) for item in items] ...
Can Transcrypt produce React class components?
I've tried to convert the Transcrypt react example to use a class component. Full code at the end but the main change is to convert this function component: def ListItems(props): items = props['items'] return [el('li', {'key': item}, item) for item in items] to a class component: class ListItems(React.Compone...
[ "Eventually I found tictacreact which gives a decent example of how to do this. Basically, add this to pyreact.py:\nregistered_components = {}\n\nclass ComponentMeta(type):\n def __new__(meta, name, bases, attribs):\n cls = type.__new__(meta, name, bases, attribs)\n registered_components[name] = c...
[ 1 ]
[]
[]
[ "python", "reactjs", "transcrypt" ]
stackoverflow_0074315435_python_reactjs_transcrypt.txt
Q: Bad Request: can't parse reply keyboard markup JSON object Python If copy/paste the print in the postman, works! but in Python give error This is my code array = '{"chat_id": "' + chat_id + '", "text": "Test Buttons", "reply_markup" : { "inline_keyboard" : [[ { "text" : "web", "url" :"google.es"}]]}}' data3 =...
Bad Request: can't parse reply keyboard markup JSON object Python
If copy/paste the print in the postman, works! but in Python give error This is my code array = '{"chat_id": "' + chat_id + '", "text": "Test Buttons", "reply_markup" : { "inline_keyboard" : [[ { "text" : "web", "url" :"google.es"}]]}}' data3 = json.loads(array) print(array) url = f'https://api.telegram.org/b...
[ "You seem to have used the wrong key for your second button's text, you should use text.\n{\n \"chat_id\": -123456,\n \"text\": \"Test\",\n \"reply_markup\": {\n \"inline_keyboard\": [\n [\n {\n \"text\": \"Button2\",\n \"url\": \"https://example.com\"\n },\n {\n ...
[ 0, 0 ]
[]
[]
[ "python", "telegram" ]
stackoverflow_0073234021_python_telegram.txt
Q: Name dataSet as value from row pandas I am trying to download stock data from yfinance. I have a ticker list called ticker_list_1 with a bunch of symbols. The structure is: array(['A', 'AAP', 'AAPL', 'ABB', 'ABBV', 'ABC', 'ABEV', 'ABMD', 'ABNB',.... Now I am using the following code to download the data: i = 0 xr...
Name dataSet as value from row pandas
I am trying to download stock data from yfinance. I have a ticker list called ticker_list_1 with a bunch of symbols. The structure is: array(['A', 'AAP', 'AAPL', 'ABB', 'ABBV', 'ABC', 'ABEV', 'ABMD', 'ABNB',.... Now I am using the following code to download the data: i = 0 xrz_data = {} for i, len in enumerate (ticker...
[ "I was able to figure it out. With the following code I am able to download the data and access specific tickers through f.e. xrz_data['AAPL‘]\ni = 0\n\nxrz_data = {}\nfor ticker in ticker_list_1: \n data = yf.download(ticker, start =\"2019-01-01\", end=\"2022-10-20\")\n xrz_data[ticker] = data\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074315854_pandas_python.txt
Q: Keep Jupyter notebook running after closing browser tab I use Jupyter Notebook to run a series of experiments that take some time. Certain cells take way too much time to execute so it's normal that I'd like to close the browser tab and come back later. But when I do the kernel interrupts running. I guess there is...
Keep Jupyter notebook running after closing browser tab
I use Jupyter Notebook to run a series of experiments that take some time. Certain cells take way too much time to execute so it's normal that I'd like to close the browser tab and come back later. But when I do the kernel interrupts running. I guess there is a workaround for this but I can't find it
[ "The simplest workaround to this seems to be the built-in cell magic %%capture:\n%%capture output\n# Time-consuming code here\n\nSave, close tab, come back later. The output is now stored in the output variable:\noutput.show()\n\nThis will show all interim print results as well as the plain or rich output cell.\n",...
[ 67, 32, 9, 4, 1, 0, 0 ]
[]
[]
[ "jupyter", "jupyter_lab", "jupyter_notebook", "python" ]
stackoverflow_0032539832_jupyter_jupyter_lab_jupyter_notebook_python.txt
Q: How to do update in pyspark using and operator? I am trying to to update one of my columns in my dataframe by using and operators. First Query df1=df1.withcolumn('department',F.when(F.col('dateofjoining')<'2019-09-01','senior'). otherwise ('')) Second query which I am running after first query Newcolumn=when(...
How to do update in pyspark using and operator?
I am trying to to update one of my columns in my dataframe by using and operators. First Query df1=df1.withcolumn('department',F.when(F.col('dateofjoining')<'2019-09-01','senior'). otherwise ('')) Second query which I am running after first query Newcolumn=when((col('department')=='') & (col('dateofjoining')<'2019...
[ "Here are my 2 cents\n\nCreate a dataframe:\n from pyspark.sql import functions as F\n\n\n schema = StructType([ \\\n StructField(\"department\",StringType(),True), \\\n StructField(\"dateofjoining\",DateType(),True), \\\n ])\n\n import datetime\n\n df = spark.createDataFrame(\n [\n ('deptA',dat...
[ 0, 0 ]
[]
[]
[ "apache_spark", "azure_databricks", "pyspark", "python" ]
stackoverflow_0074030437_apache_spark_azure_databricks_pyspark_python.txt
Q: How can I create a column in my data frame, in Python using if and or statements? I am looking to create a column called "Assign Number 1 or 2" with the following logic: If Posting Archived At (GMT) is between "January 22" and "June 22" and Profile Archive Reason is "Offer Declined*" or "Withdrawn" then assign 1 A...
How can I create a column in my data frame, in Python using if and or statements?
I am looking to create a column called "Assign Number 1 or 2" with the following logic: If Posting Archived At (GMT) is between "January 22" and "June 22" and Profile Archive Reason is "Offer Declined*" or "Withdrawn" then assign 1 AND If Posting Archived At (GMT) is between "July 22" and "December 22" and Profile Arc...
[ "use a function with apply and lambda:\nimport pandas as pd\n\ndef my_func(row):\n if row.bname == \"textbook\":\n return \"something\"\n if row.bname == \"b\":\n return \"something_else\"\n\n return \"not_found\"\n\nbooks = [{\"bname\": \"textbook\", \"weight\": 500, \"price\": 800},\n {\"...
[ 0 ]
[]
[]
[ "if_statement", "pandas", "python" ]
stackoverflow_0074316391_if_statement_pandas_python.txt
Q: String formatting with "{0:d}".format gives Unknown format code 'd' for object of type 'float' If I understood the docs correctly, in python 2.6.5 string formatting "{0:d}" would do the same as "%d" with the String.format() way of formatting strings " I have {0:d} dollars on me ".format(100.113) Should print "I ...
String formatting with "{0:d}".format gives Unknown format code 'd' for object of type 'float'
If I understood the docs correctly, in python 2.6.5 string formatting "{0:d}" would do the same as "%d" with the String.format() way of formatting strings " I have {0:d} dollars on me ".format(100.113) Should print "I have 100 dollars on me " However I get the error : ValueError: Unknown format code 'd' for objec...
[ "That error is signifying that you are passing a float to the format code expecting an integer.\nUse {0:f} instead. Thus:\n\"I have {0:f} dollars on me\".format(100.113)\n\nwill give:\n'I have 100.113000 dollars on me'\n\n", "Yes, you understand correctly. However you are passing float (i.e. 100.113), not int. Ei...
[ 30, 8, 1, 0 ]
[ "delete 'd', since the object type might not be a number as in my case\n" ]
[ -3 ]
[ "python", "string_formatting" ]
stackoverflow_0005627605_python_string_formatting.txt
Q: Construct a matrix using a for loop I have calculated 9 matrix elements named sij, with i and j being variables (i,j = [1, 2, 3]). Here, i denotes rows and j columns. Suppose I want a 3x3 matrix that consists of the matrix elements s11, s12, ... s32, s33 (nine elements in total). s11 = 1 s12 = 2 s13 = 3 (...) s33 ...
Construct a matrix using a for loop
I have calculated 9 matrix elements named sij, with i and j being variables (i,j = [1, 2, 3]). Here, i denotes rows and j columns. Suppose I want a 3x3 matrix that consists of the matrix elements s11, s12, ... s32, s33 (nine elements in total). s11 = 1 s12 = 2 s13 = 3 (...) s33 = 9 How can I use for loops to construct...
[ "I would consider renaming the sij to s[i][j]. Then using them in loops would be trivial.\ns[1][1] = 1\ns[1][2] = 2\ns[1][3] = 3\n(...)\ns[3][3] = 9\n\nThen:\ninstead of:\nmatrix = [[s11, s12, s13], [s21, s22, s23], [s31, s32, s33]]\n\nYou can have the following two nested loops to construct the matrix.\nfor i in (...
[ 1, 0 ]
[ "We can use this code for creating our desired matrix with for loop:\nn = int(input('n:'))\n\nfor i in range(1,n):\n\n for j in range(1,n):\n\n if i<j:\n print(1,end = ' ')\n else :\n\n print('0',end = ' ')\n\n print()\n\nOutput\nn:5\n0 1 1 1 \n0 0 1 1 \n0 0 0 1 \n0 0 0 0\n...
[ -1 ]
[ "matrix", "numpy", "python", "scipy" ]
stackoverflow_0046181761_matrix_numpy_python_scipy.txt
Q: Pytorch LSTM is much slower for a specific range of hidden sizes I'm looking into searching a broader range of hidden sizes for my model and encountered a major slowdown in a specific range. I'm assuming that CUDA may be using different optimisations for different tensor sizes and the one used in this range are ju...
Pytorch LSTM is much slower for a specific range of hidden sizes
I'm looking into searching a broader range of hidden sizes for my model and encountered a major slowdown in a specific range. I'm assuming that CUDA may be using different optimisations for different tensor sizes and the one used in this range are just not well supported by my hardware. Any ideas on how I can get more ...
[ "Whenever you do any timing on GPU, always use torch.cuda.synchronize() (see_here). If you alter your code to include it you'll see a more consistent prediction speed increase.\n def test_speed(hidden_size, n=5, gpu=0):\n\n torch.random.manual_seed(42)\n start = torch.cuda.Event(enable_timing=True)\n end =...
[ 0, 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074306153_python_pytorch.txt
Q: How to save a file (upload file) with fastapi Help needed, How can I save a file with fastAPI. I tried something with this code, but without no doubts didn't have attribute save. @api.post('/images') async def upload(id_: str, file: UploadFile = File(...)): file.save(file.filename) A: Flask has a file.save w...
How to save a file (upload file) with fastapi
Help needed, How can I save a file with fastAPI. I tried something with this code, but without no doubts didn't have attribute save. @api.post('/images') async def upload(id_: str, file: UploadFile = File(...)): file.save(file.filename)
[ "Flask has a file.save wrapper function which allows you to save the uploaded file locally in your disk. There is no such implementation for FastAPI yet at the time of this writing.\nYou can easily implement it inside FastAPI server,for that you need to import the shutil module.\nfrom fastapi import FastAPI, File, ...
[ 0 ]
[]
[]
[ "api", "fastapi", "http", "python" ]
stackoverflow_0074309577_api_fastapi_http_python.txt
Q: Implement a "where" method to select column_name and value from string in Python Ive got a little issue while coding a script that takes a CSV string and is supposed to select a column name and value based on the input. The CSV string contains Names of NBA players, their Universities etc. Now when the input is "na...
Implement a "where" method to select column_name and value from string in Python
Ive got a little issue while coding a script that takes a CSV string and is supposed to select a column name and value based on the input. The CSV string contains Names of NBA players, their Universities etc. Now when the input is "name" && "Andre Brown", it should search for those values in the given CSV string. I hav...
[ "# importing pandas\nimport pandas as pd\n \nrecord = {\n 'Name': ['Ankit', 'Amit', 'Aishwarya', 'Priyanka', 'Priya', 'Shaurya' ],\n 'Age': [21, 19, 20, 18, 17, 21],\n 'Stream': ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'],\n 'Percentage': [88, 92, 95, 70, 65, 78]}\n \n# create a dataframe\ndata...
[ 0, 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python", "where_clause" ]
stackoverflow_0074287697_csv_dataframe_pandas_python_where_clause.txt
Q: What is the point for asyncio synchronization primitives not to be thread safe? It seems that several asyncio functions, like those showed here, for synchronization primitives are not thread safe... By being not thread safe, considering for example asyncio.Lock, I assume that this lock won't lock the global variab...
What is the point for asyncio synchronization primitives not to be thread safe?
It seems that several asyncio functions, like those showed here, for synchronization primitives are not thread safe... By being not thread safe, considering for example asyncio.Lock, I assume that this lock won't lock the global variable, when we're running multiple threads in our computer, so race conditions are probl...
[ "Asyncio is not made for multithreading or multiprocessing work, it is originally made for Asynchronous IO (network) operations with little overhead, hence a lock that is only running in a single thread (as is the case for tasks running in Asyncio eventloop) doesn't need to be threadsafe or process-safe, and theref...
[ 1 ]
[]
[]
[ "multithreading", "python", "python_asyncio" ]
stackoverflow_0074316373_multithreading_python_python_asyncio.txt
Q: In pytorch, it is still possible to train without adding model parameters to the optimizer As far as I know, the parameters of the model are not trainable without putting them into the optimizer. But recently when I was running a project on github, I found that the model parameters can be trained without putting t...
In pytorch, it is still possible to train without adding model parameters to the optimizer
As far as I know, the parameters of the model are not trainable without putting them into the optimizer. But recently when I was running a project on github, I found that the model parameters can be trained without putting them into the optimizer. The code address of this project to add parameters to the optimizer is h...
[ "The model is based on prompt learning, and it is possible to train classifiers without training if prompts are trained.\n" ]
[ 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0073341252_python_pytorch.txt
Q: Capturing salary from a string using capture groups (python, regex) My goal is to extract salary from a string and if this salary comes from collective agreement. I have come up with a following regex: pattern = "([Kk]ollektivvertragliche[sn]|Kollektivvertrag|[Cc]ollective [Aa]greement|[Kk]ollektivvertr|KV) .* ([0...
Capturing salary from a string using capture groups (python, regex)
My goal is to extract salary from a string and if this salary comes from collective agreement. I have come up with a following regex: pattern = "([Kk]ollektivvertragliche[sn]|Kollektivvertrag|[Cc]ollective [Aa]greement|[Kk]ollektivvertr|KV) .* ([0-9]{1,4}[.,][0-9]{2,3}[,]*[0-9]*) .* ([0-9]{1,4}[.,][0-9]{2,3}[,]*[0-9]*)...
[ "Not sure if #t = ' is part of the string that you want in your return values, but using 3 capture groups where the first 2 are optional:\n^.*?(?:\\b([Kk]ollektivvertragliche[sn]|Kollektivvertrag|[Cc]ollective [Aa]greement|[Kk]ollektivvertr|KV)\\b(.*?))?([0-9]{1,4}([.,])\\d{2,3}(?:(?!\\4)[.,]\\d+)?)\n\nRegex demo\n...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074315341_python_regex.txt
Q: kwarg unpacking with mypy I have a function, that accepts inputs of different types, and they all have default values. For example, def my_func(a: str = 'Hello', b: bool = False, c: int = 1): return a, b, c What I want to do is define the non-default kwargs in a dictionary, and then pass this to the function....
kwarg unpacking with mypy
I have a function, that accepts inputs of different types, and they all have default values. For example, def my_func(a: str = 'Hello', b: bool = False, c: int = 1): return a, b, c What I want to do is define the non-default kwargs in a dictionary, and then pass this to the function. For example, input_kwargs = {'...
[ "You can create a class (by inheriting from TypedDict) with class variables that match with my_func parameters. To make all these class variables as optional, you can set total=False.\nThen use this class as the type for input_kwargs to make mypy happy :)\nfrom typing import TypedDict\n\nclass Params(TypedDict, to...
[ 1 ]
[]
[]
[ "keyword_argument", "mypy", "python" ]
stackoverflow_0074316523_keyword_argument_mypy_python.txt
Q: How to Create a Grouped, Stacked, Bar Chart with Proportionately Split Bar Sections in matplotlib and python? For Loan Portfolio Analysis I'm tasked with creating this very complicated bar chart with the purpose of analyzing the joint exposure of loan portfolios to the loans that they share. My data is formatted l...
How to Create a Grouped, Stacked, Bar Chart with Proportionately Split Bar Sections in matplotlib and python? For Loan Portfolio Analysis
I'm tasked with creating this very complicated bar chart with the purpose of analyzing the joint exposure of loan portfolios to the loans that they share. My data is formatted like the table pictured, where "Loan" signifies a loan, "Level" signifies the trust deed priority, "FMV" signifies the fair market value of the ...
[ "Perhaps someone has a more elegant solution. The following one is not pretty, but does the job.\nimport pandas as pd\nimport numpy as np\nimport matplotlib as mtp\nimport matplotlib.pyplot as plt\n\n\ndef loan_analysis(data, ax):\n # standardize to $ millions\n chart_loans = (data.reset_index().set_index([\"...
[ 0 ]
[]
[]
[ "charts", "dataframe", "matplotlib", "pandas", "python" ]
stackoverflow_0074290542_charts_dataframe_matplotlib_pandas_python.txt
Q: Why is scipy's gaussian_filter1d not calculating properly the derivative? I am trying to calculate the derivative of a function using scipy.ndimage.gaussian_filter1d using the keyword order but the result is not working properly. Instead if I apply first the gaussian filter to the function and then differenciate i...
Why is scipy's gaussian_filter1d not calculating properly the derivative?
I am trying to calculate the derivative of a function using scipy.ndimage.gaussian_filter1d using the keyword order but the result is not working properly. Instead if I apply first the gaussian filter to the function and then differenciate it by finite differences it works. For ease of clarity, the function I want to d...
[ "This is coming from the fact that you gaussian kernel is not the same size as your input, if you want to get more consistant result you could increase the truncate value, it gets closer to result you expect. the error is cumulative.\nwith truncate 10 you could get results like this:\n\n\n" ]
[ 1 ]
[]
[]
[ "filtering", "gaussianblur", "python", "scipy" ]
stackoverflow_0074315183_filtering_gaussianblur_python_scipy.txt
Q: Django Deprecation Warning or ImproperlyConfigured error - Passing a 3-tuple to django.conf.urls.include() is not supported I have a deprecation warning in Django 1.11: RemovedInDjango20Warning: Passing a 3-tuple to django.conf.urls.include() is deprecated. Pass a 2-tuple containing the list of patterns and app_na...
Django Deprecation Warning or ImproperlyConfigured error - Passing a 3-tuple to django.conf.urls.include() is not supported
I have a deprecation warning in Django 1.11: RemovedInDjango20Warning: Passing a 3-tuple to django.conf.urls.include() is deprecated. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. url(r'^admin/', include(admin.site.urls)) In Django 2.0 this give...
[ "As of Django 1.9, the old way of including the admin urls is deprecated. You should pass admin.site.urls directly to url(), without the call to include():\nfrom django.contrib import admin\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n ...\n]\n\n", "I struggled with this on my Macbook. I had a vi...
[ 142, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0043324005_django_python.txt
Q: How to make a new line for a sentence after finished sentene with dot? I have a large text file in Python. I want to make a new line for each sentences. For each line should contain only one sentence information. For example: Input: The Mona Lisa is a half-length portrait painting by Italian artist Leonardo da Vin...
How to make a new line for a sentence after finished sentene with dot?
I have a large text file in Python. I want to make a new line for each sentences. For each line should contain only one sentence information. For example: Input: The Mona Lisa is a half-length portrait painting by Italian artist Leonardo da Vinci. Considered an archetypal masterpiece of the Italian Renaissance, it has ...
[ "You only need to replace periods followed by a space and a capital letter:\nimport re\n\nwith open(\"new_all_data.txt\", 'r') as text, open(\"new_all_data2.txt\", \"w\") as new_text2:\n text_lines = text.readlines()\n for line in text_lines:\n if \".\" in line:\n new_lines = re.sub(\n ...
[ 1 ]
[]
[]
[ "file", "list", "python", "textedit", "texteditingcontroller" ]
stackoverflow_0074316824_file_list_python_textedit_texteditingcontroller.txt
Q: Passing python output to a js function I have a JS function in which i want to pass my python output and return its responce an way to do it I tried using js2py but didnt get the output import js2py opt=js2py.run_file("Encrypt.js") js2py.translate_file("Encrypt.js","py.py") print(opt) A: After calling translate_...
Passing python output to a js function
I have a JS function in which i want to pass my python output and return its responce an way to do it I tried using js2py but didnt get the output import js2py opt=js2py.run_file("Encrypt.js") js2py.translate_file("Encrypt.js","py.py") print(opt)
[ "After calling translate_file, you need to import the translated file as well:\nadd.js\nfunction add(a, b) {\n return a+b;\n}\n\ntest.py\nimport js2py\njs2py.translate_file(\"add.js\", \"add.py\")\nfrom add import add\n\nprint(add.add(1, 2)) # prints 3\n\nFor more usage examples, you can refer to Js2Py Github\n"...
[ 0 ]
[]
[]
[ "javascript", "js2py", "module", "parsing", "python" ]
stackoverflow_0074316712_javascript_js2py_module_parsing_python.txt
Q: AttributeError: module 'keras.preprocessing.image' has no attribute 'img_to_array' I am trying to run a code from github of facial emotion teller and I am getting an attribute error, The error is : line 27, in <module> img_pixel = image.img_to_array(roi_gray) AttributeError: module 'keras.preprocessing.image' ...
AttributeError: module 'keras.preprocessing.image' has no attribute 'img_to_array'
I am trying to run a code from github of facial emotion teller and I am getting an attribute error, The error is : line 27, in <module> img_pixel = image.img_to_array(roi_gray) AttributeError: module 'keras.preprocessing.image' has no attribute 'img_to_array' The complete is given below : import os import cv2 impo...
[ "tf.keras.preprocessing.image is deprecated.\nYou can use\nfrom tensorflow.keras.utils import img_to_array\n\n...\n\nimg_pixel = img_to_array(roi_gray)\n\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "facial_identification", "image_preprocessing", "keras", "python" ]
stackoverflow_0074256482_attributeerror_facial_identification_image_preprocessing_keras_python.txt
Q: Python Pandas aggregation error: "No matching signature found" when trying to calculate mode I have a list of pandas dataframes, and I would like to perform a mode operation on all of them. All dataframes have the same layout: index | date | sentiment| ----- | ------ | -------- | 0 |2022-01-01| 1 ...
Python Pandas aggregation error: "No matching signature found" when trying to calculate mode
I have a list of pandas dataframes, and I would like to perform a mode operation on all of them. All dataframes have the same layout: index | date | sentiment| ----- | ------ | -------- | 0 |2022-01-01| 1 | 1 |2022-02-03| -1 | 2 |2021-10-01| 0 | ... with date being a dt.date o...
[ "The error you're getting only occurs if the length of the results is zero. And that occurs when There are only nans in the series you're taking the mode of, since .mode has dropna=True by default.\nimport pandas as pd\n\npd.Series([np.nan, None]).mode()\n\nSeries([], dtype: float64) # produces value error in agg f...
[ 0 ]
[]
[]
[ "aggregation", "group_by", "mode", "pandas", "python" ]
stackoverflow_0074316617_aggregation_group_by_mode_pandas_python.txt
Q: Draw a directed graph in Python I have a data table and I want to show it by a directed graph. My table is following: point,previous_point "A","-" "B","-" "C","A" "D","B" "E","C" "F","C" "G","D,E" "H","F,G" And I need a graph drawn using by the above data. The graph I want is: I have tried with the networkx pack...
Draw a directed graph in Python
I have a data table and I want to show it by a directed graph. My table is following: point,previous_point "A","-" "B","-" "C","A" "D","B" "E","C" "F","C" "G","D,E" "H","F,G" And I need a graph drawn using by the above data. The graph I want is: I have tried with the networkx package. But the result is not good. Some...
[ "You can adjust the layout of your plot like this:\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport pydot\nfrom networkx.drawing.nx_pydot import graphviz_layout\n\nG = nx.DiGraph()\n\nG.add_edges_from(\n[('Start','A'),('Start','B'),\n('A','C'),('B','D'),('C','E'),('C','F'),\n('D','G'),('E','G'),('F',...
[ 3 ]
[ "Instead of networkx one could use mermaid. Here's a chart generated online at https://mermaid.live:\ngraph LR\n A --> C --> E --> G --> H\n C --> F --> H\n B --> D --> G\n\n\nOf course, there is scope for adjusting it to suit your needs. Once the desired format is found, it should be feasible to use Pytho...
[ -1 ]
[ "graph", "networkx", "python" ]
stackoverflow_0074312314_graph_networkx_python.txt
Q: Fill DataFrame based on value from another column Given the following python pandas dataframe: province district Total example NaN other Other NaN NaN example Result example NaN example If the province column is NaN and the value for that row is 'example', I want to fill the province gap with 'example'. Th...
Fill DataFrame based on value from another column
Given the following python pandas dataframe: province district Total example NaN other Other NaN NaN example Result example NaN example If the province column is NaN and the value for that row is 'example', I want to fill the province gap with 'example'. The rest of the rows stay as they are. Data...
[ "You can use .fillna() conditionally with np.where:\ndf[\"province\"] = np.where(\n df[\"district\"] == \"example\", \n df[\"province\"].fillna(value=\"example\"), \n df[\"province\"]\n)\n\n", "You could use loc to find the rows with NaN in your province column and 'example' in your district column and u...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074316955_dataframe_pandas_python.txt
Q: Open a numpad every time a Tkinter Entry is clicked with mouse I'm not a programmer by profession and currently try to program a small app to use on tablets using python's tkinter module. I want a numpad to pop up every time a tinkter Entry widget is clicked/touched. I found the following code on stackoverflow whi...
Open a numpad every time a Tkinter Entry is clicked with mouse
I'm not a programmer by profession and currently try to program a small app to use on tablets using python's tkinter module. I want a numpad to pop up every time a tinkter Entry widget is clicked/touched. I found the following code on stackoverflow which creates a "NumpadEntry" class (inheriting from tk.Entry) that doe...
[ "The problem occurs because you bind to focus in and out, so you have to focus another entry before you can focus the first again. Instead, bind to <Button-1>, which is left click.\nThe program can be simplified a bit by having numPad subclass tk.Toplevel instead of Dialog. This also removes the need for the simple...
[ 0 ]
[]
[]
[ "numpad", "python", "tkinter" ]
stackoverflow_0074316430_numpad_python_tkinter.txt
Q: Multiple imshow on the same plot, with opacity slider With Plotly, I'd like to display two imshow on the same page, at the same place, with opacity. This nearly works: import plotly.express as px, numpy as np from skimage import io img = io.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Neb...
Multiple imshow on the same plot, with opacity slider
With Plotly, I'd like to display two imshow on the same page, at the same place, with opacity. This nearly works: import plotly.express as px, numpy as np from skimage import io img = io.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg') fig = px.imshow(img) x = np...
[ "The main problem is that pre-computing all traces is an essential step to create the layer.Slider in Plotly as documented here. Therefore, we want to compute the only required trace on the fly rather than pre-computing all traces upfront. Moreover, I totally agree with you that it is ineffective solution to build ...
[ 2, 2, 1 ]
[]
[]
[ "numpy", "plotly", "plotly_python", "python" ]
stackoverflow_0074191241_numpy_plotly_plotly_python_python.txt
Q: How to read multiple images from two different folders one by one using python? I am new to python and in a learning stage. I am trying to read multiple images from two different folders in a similar order. Each folder contains 147 images. In one folder there is thermal image (FLIR1271) and second folder contains ...
How to read multiple images from two different folders one by one using python?
I am new to python and in a learning stage. I am trying to read multiple images from two different folders in a similar order. Each folder contains 147 images. In one folder there is thermal image (FLIR1271) and second folder contains visible RGB image (FLIR1272) corresponding to thermal image. My task is to read and d...
[ "Although in your case, (you have fixed length strings, the prefix is also the same) you might get the expected output after sorting, it's better not to compare/sort numbers when they are strings. Always pay attention to how you're sorting the strings containing numbers. i.e \"8\" is bigger than \"12\"\nAnd from yo...
[ 0 ]
[]
[]
[ "iterator", "loops", "python" ]
stackoverflow_0074316898_iterator_loops_python.txt
Q: Dictionaries inside dictionary not working with open('personnages.txt') as file: my_file = file.read() f = my_file.split('\n\n') final_dict = {} for row1 in f: data = row1.strip().split('\n') d = {} for row2 in data: key, value = row2.split(':') d[key] = value for row3 in d: ...
Dictionaries inside dictionary not working
with open('personnages.txt') as file: my_file = file.read() f = my_file.split('\n\n') final_dict = {} for row1 in f: data = row1.strip().split('\n') d = {} for row2 in data: key, value = row2.split(':') d[key] = value for row3 in d: name_dict = {} final_dict[...
[ "This ...\n\n for row3 in d:\n name_dict = {}\n final_dict[d['nom']] = name_dict\n\n\n... maps an empty dict to key d['nom'] in dict final_dict. Multiple times. Instead, you want to either\n\nCollect all the the data for one 'nom' into a dictionary first, then add that dictionary, OR\...
[ 0 ]
[ "nested_dict = { 'dictA': {'key_1': 'value_1'},\n'dictB': {'key_2': 'value_2'}}\n" ]
[ -1 ]
[ "dictionary", "python" ]
stackoverflow_0074312152_dictionary_python.txt
Q: How to make link in python Tabulate? see my following code I have this code Where I want to hyperlink urlvalue to the title I tried to insert HTML hyperlink but got exception error... But I like to get hyperlink in the table with two values like Title will be clickable with url value A: Use 'unsafehtml' format ...
How to make link in python Tabulate? see my following code
I have this code Where I want to hyperlink urlvalue to the title I tried to insert HTML hyperlink but got exception error... But I like to get hyperlink in the table with two values like Title will be clickable with url value
[ "Use 'unsafehtml' format like this.\ntabulate(output, tablefmt='unsafehtml')\n\nBut don't forget to escape other cell values by yourself.(using the html.escape())\n" ]
[ 0 ]
[]
[]
[ "python", "tabulate" ]
stackoverflow_0074312975_python_tabulate.txt
Q: How to make QCombobox hide popup and keep focus when a window has Escape button as shortcut key I have a form created using Pyside2. I have a QCombobox in a form that also has a QToolbutton. The QToolbutton has a shortcut using the Escape key to close the window if triggered. When my Combobox displays its popup an...
How to make QCombobox hide popup and keep focus when a window has Escape button as shortcut key
I have a form created using Pyside2. I have a QCombobox in a form that also has a QToolbutton. The QToolbutton has a shortcut using the Escape key to close the window if triggered. When my Combobox displays its popup and I press the Escape key the form is closed too. What I want is when Combobox popup is shown and I pr...
[ "Don't use a shortcut for this as its activation priority is too high. The window must only receive the event if no other widget wants it. A QDialog will handle this automatically, but if that cannot be used, a simple solution is to override the keyPressEvent of the window.\nHere's a demo based on your example:\nim...
[ 2 ]
[]
[]
[ "keyboard_shortcuts", "pyside2", "python", "qcombobox" ]
stackoverflow_0074312047_keyboard_shortcuts_pyside2_python_qcombobox.txt
Q: How to improve the label placement in scatter plot I use matplotlib to plot a scatter chart: And label the bubble using a transparent box according to the tip at How to annotate point on a scatter automatically placed arrow Here is the code: if show_annote: for i in range(len(x)): annote_text = annote...
How to improve the label placement in scatter plot
I use matplotlib to plot a scatter chart: And label the bubble using a transparent box according to the tip at How to annotate point on a scatter automatically placed arrow Here is the code: if show_annote: for i in range(len(x)): annote_text = annotes[i][0][0] # STK_ID ax.annotate(annote_text, xy...
[ "The following builds on tcaswell's answer. \nNetworkx layout methods such as nx.spring_layout rescale the positions so that they all fit in a unit square (by default). Even the position of the fixed data_nodes are rescaled. So, to apply the pos to the original scatter_data, an unshifting and unscaling must be perf...
[ 28, 28, 22, 0, 0 ]
[]
[]
[ "matplotlib", "plot_annotations", "python", "scatter_plot" ]
stackoverflow_0014938541_matplotlib_plot_annotations_python_scatter_plot.txt
Q: Why is the request ignoring my proxy parameter and returning my IP to me? It all started with the fact that I reinstalled paycharm on my computer, reinstalled python For example, I write normal code, it always worked: import os import requests proxies = {'https': 'https://181.232.190.130:999'} s = requests.Session...
Why is the request ignoring my proxy parameter and returning my IP to me?
It all started with the fact that I reinstalled paycharm on my computer, reinstalled python For example, I write normal code, it always worked: import os import requests proxies = {'https': 'https://181.232.190.130:999'} s = requests.Session() s.proxies = proxies r = s.get(url = 'http://wtfismyip.com/text', verify=Fals...
[ "There is nothing wrong with your code requests/urllib contains bug i believe.\nHere modified version code:\nDon't use https with your proxy, it will throw version errors. And use proxy for all protocols http/https. Just make changes to these two lines.\n\nproxy = 'http://198.59.191.234:8080'\nsession.proxies = {\"...
[ 0 ]
[]
[]
[ "proxy", "python", "python_requests", "urllib3" ]
stackoverflow_0073348411_proxy_python_python_requests_urllib3.txt
Q: Process finished with exit code -1073740791 (0xC0000409) without any reports The program is based on PyQt5 and python 3.9 and it receives data from server. The program sends request of data to server with QEventLoop.exec_() till receving data is done. The server send data to the program. After receiving all data t...
Process finished with exit code -1073740791 (0xC0000409) without any reports
The program is based on PyQt5 and python 3.9 and it receives data from server. The program sends request of data to server with QEventLoop.exec_() till receving data is done. The server send data to the program. After receiving all data the QEventLoop.exit() is called. There are many downloading items. The error(107374...
[ "i suggest to use try and except to log the error.\n" ]
[ 1 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0074290492_pyqt5_python.txt
Q: multiprocessing.SimpleQueue hangs when given too many items I am trying to test the performance of multiprocessing.SimpleQueue compared to multiprocessing.Queue, so I made the following program: import multiprocessing as MP import time def worker_func(job_queue: MP.Queue, result_queue: MP.Queue): count = 0 ...
multiprocessing.SimpleQueue hangs when given too many items
I am trying to test the performance of multiprocessing.SimpleQueue compared to multiprocessing.Queue, so I made the following program: import multiprocessing as MP import time def worker_func(job_queue: MP.Queue, result_queue: MP.Queue): count = 0 while True: job = job_queue.get() result_queue...
[ "After doing lots of searches, I found Bug 41550.\nIt seems SimpleQueue uses os.pipe, which has limited capacity (64k iirc). So if resq is not consumed regularly, it will block.\nThe solution for my purpose is to add yet one more worker whose function is none other than consuming resq.\n" ]
[ 0 ]
[]
[]
[ "python", "python_multiprocessing" ]
stackoverflow_0074317252_python_python_multiprocessing.txt
Q: I need compare two dataframe with pandas I have two dataframes, equipment alarms obtained at two different moments of time, each alarm is a row of the dataframe, I need to compare them and find out if the new alarm exists, I give an example alarms time 0: Sequence AlarmId Level ...
I need compare two dataframe with pandas
I have two dataframes, equipment alarms obtained at two different moments of time, each alarm is a row of the dataframe, I need to compare them and find out if the new alarm exists, I give an example alarms time 0: Sequence AlarmId Level Description 0 142527 0x813007C ...
[ "You can use the isin function without merge. Check the value in the second df in the first df. Drop what's in both dataframes using ~.\n:\nalarm_time_1 = alarm_time_1[~alarm_time_1['Sequence'].isin(alarms_time_0['Sequence'])]\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074314937_pandas_python.txt
Q: How can I find out / print with which version of the protocol a pickle file has been generated In some cases, when I load an existing pickle file, and after that dump it again, the size is almost halved. I wonder why, and the first suspect is the protocol version. Can I somehow find out with which protocol version...
How can I find out / print with which version of the protocol a pickle file has been generated
In some cases, when I load an existing pickle file, and after that dump it again, the size is almost halved. I wonder why, and the first suspect is the protocol version. Can I somehow find out with which protocol version a file was pickled?
[ "There may be a more elegant way but to get down to the metal you can use pickletools:\nimport pickle\nimport pickletools\ns = pickle.dumps('Test')\nproto_op = next(pickletools.genops(s))\nassert proto_op[0].name == 'PROTO'\nproto_ver = proto_op[1]\n\nTo figure out the version required to decode this, you'll need t...
[ 7, 0 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0053431125_pickle_python.txt
Q: Count amount of comparison using naive string matching algorithm python In my code I try to found index of the pattern, count every comparison and I also want to stop this algorithm then my pattern is too long for comparison to rest of the text. Something is wrong with counter and I couldn't stop algorithm. I am b...
Count amount of comparison using naive string matching algorithm python
In my code I try to found index of the pattern, count every comparison and I also want to stop this algorithm then my pattern is too long for comparison to rest of the text. Something is wrong with counter and I couldn't stop algorithm. I am beginner and I don't have idea what to do. def search(W, T): count = 0 ...
[ "First of all, as you are a beginner in Python here's some tips:\n\nYou do not need brackets in if: if j == len(W): is ok, moreover these brackets are against PEP8 codestyle.\nYou don't need this condition:\n\n if i > len(T)-len(W):\n break\n\nrange() is smart guy. He won't let i be more then len(T)-len(W...
[ 1 ]
[]
[]
[ "algorithm", "python", "string" ]
stackoverflow_0074311412_algorithm_python_string.txt
Q: How to group a pandas timeseries index into groups with the same frequency? I have a timeseries with sub-sequences of the same timedelta between rows, but this timedelta is not the same between all sub-sequences. series >>> timestamp 2018-06-12 08:01:00 0.5456 # minute intervals 2018-06-12 08:02:00 0.4734 ...
How to group a pandas timeseries index into groups with the same frequency?
I have a timeseries with sub-sequences of the same timedelta between rows, but this timedelta is not the same between all sub-sequences. series >>> timestamp 2018-06-12 08:01:00 0.5456 # minute intervals 2018-06-12 08:02:00 0.4734 2018-06-12 08:03:00 0.6723 ... 2018-09-12 15:00:00 1.2449 # hour interval...
[ "You could use a np.diff to create a new column with time deltas, and the use the pandas groupby.\nimport pandas as pd\nimport numpy as np\n\n# Dummy data\ndata=[0.45,0.47,0.62,1.21,1.21,0.21,2.54,3.45,4.12,2.01,2.1]\nid1 = pd.date_range(start='2018-06-12 08:01:00', periods=6, freq='T')\nid2 = pd.date_range(start='...
[ 0 ]
[]
[]
[ "datetime", "group_by", "pandas", "python", "time_series" ]
stackoverflow_0074306749_datetime_group_by_pandas_python_time_series.txt
Q: Classes in python: IDE said Instance attributes defined outside __init__: Everything works, but can't make it work in __init__ This is my first program after a bunch of small tutorials, and my file explorer works wonderfully. Did some custom icons, thumbnail for images, and I can scroll, multyselect stuff and brow...
Classes in python: IDE said Instance attributes defined outside __init__: Everything works, but can't make it work in __init__
This is my first program after a bunch of small tutorials, and my file explorer works wonderfully. Did some custom icons, thumbnail for images, and I can scroll, multyselect stuff and browse with my icons. Originally it took 3.2 seconds to open/resize/blend-paste/display 81 pictures(100x100), and managed to bring it to...
[ "This IDE recommendation is for organizing your code only, and should not affect how it works. However, it exists to remind you to put just the behavior necessary for instantiate your class in __init__, if your class has data that does not depend on initialization you can put it before __init__.\nFor example:\nclas...
[ 1 ]
[]
[]
[ "class", "initialization", "python" ]
stackoverflow_0074316745_class_initialization_python.txt
Q: Finding the sum of each level in a list with nested lists I need to create a python function that takes a list of numbers (and possibly lists) and returns a list of both the nested level and the sum of that level. For example: given a list [1,4,[3,[100]],3,2,[1,[101,1000],5],1,[7,9]] I need to count the values of ...
Finding the sum of each level in a list with nested lists
I need to create a python function that takes a list of numbers (and possibly lists) and returns a list of both the nested level and the sum of that level. For example: given a list [1,4,[3,[100]],3,2,[1,[101,1000],5],1,[7,9]] I need to count the values of all the integers at level 0 and sum them together, then count t...
[ "I would do it like this:\narray = [1, 4, [3, [100]], 3, 2, [1, [101, 1000], 5], 1, [7, 9]]\n\nsum_by_level = []\nwhile array:\n numbers = (element for element in array if not isinstance(element, list))\n sum_by_level.append(sum(numbers))\n\n array = [element for list_element in array if isinstance(list_el...
[ 1 ]
[]
[]
[ "loops", "nested_lists", "python", "recursion", "sum" ]
stackoverflow_0074297647_loops_nested_lists_python_recursion_sum.txt
Q: Coordinate problems and inverted map I'm using the salinity data of ORAS5 and the preview variables and information: salinity =xr.open_dataset('....salinity_ORAS5.nc') sal = salinity['sosaline'] So, the big problem is each "nav_lon" and "nav_lat" have 2D in x and y. Where in the normal case, for example, the lat ...
Coordinate problems and inverted map
I'm using the salinity data of ORAS5 and the preview variables and information: salinity =xr.open_dataset('....salinity_ORAS5.nc') sal = salinity['sosaline'] So, the big problem is each "nav_lon" and "nav_lat" have 2D in x and y. Where in the normal case, for example, the lat data have 1D. sal.nav_lon In the previe...
[ "I got to transform the coordinates in 'normal' lat/lon using CDO.\ncdo remapbil \n\nI hope that helps :)\n" ]
[ 1 ]
[]
[]
[ "coordinates", "latitude_longitude", "maps", "projection", "python" ]
stackoverflow_0074265230_coordinates_latitude_longitude_maps_projection_python.txt
Q: How to control field label case generated by Pydantic? I have the following pydantic model: import pydantic class Creator(pydantic.BaseModel): firstName: str = None lastName: str = None middle_name: str = None and the output of print(Creator.schema_json(indent=2)) is { "title": "Creator", "type":...
How to control field label case generated by Pydantic?
I have the following pydantic model: import pydantic class Creator(pydantic.BaseModel): firstName: str = None lastName: str = None middle_name: str = None and the output of print(Creator.schema_json(indent=2)) is { "title": "Creator", "type": "object", "properties": { "firstName": { "title...
[ "Is this answering your question?\nimport pydantic\n\nclass SampleModel(pydantic.BaseModel):\n firstName: str = pydantic.Field(\n None,\n title='First Name',\n description='the first name'\n )\n middle_name: str = pydantic.Field(\n None,\n title='Middle Name',\n de...
[ 1 ]
[]
[]
[ "pydantic", "python" ]
stackoverflow_0074317070_pydantic_python.txt
Q: How to adjust Plotly legend/colorbar background transparency/colour I'm trying to edit the appearance of a map I have made, but if I choose to have the colorbar/legend visible, it sits on a white background: This white is a bit jarring for the rest of the color scheme. At the moment, I'm just hiding the whole thi...
How to adjust Plotly legend/colorbar background transparency/colour
I'm trying to edit the appearance of a map I have made, but if I choose to have the colorbar/legend visible, it sits on a white background: This white is a bit jarring for the rest of the color scheme. At the moment, I'm just hiding the whole thing with: fig.update_coloraxes(showscale=False) But that obviously makes ...
[ "You can use the attribute bgcolor of colorbar:\ncolor = ... # your color\nfig.update_coloraxes(colorbar=dict(bgcolor=color))\n\n" ]
[ 1 ]
[]
[]
[ "colorbar", "plotly_python", "python" ]
stackoverflow_0074317352_colorbar_plotly_python_python.txt
Q: Password protect a SPECIFIC Jupyter notebook The docs describe how to create a password to protect your jupyter notebooks. I would like to be able to create and share a particular notebook with a special password for just that notebook. Is this possible? A: No, it is not possible. The password protects the whole...
Password protect a SPECIFIC Jupyter notebook
The docs describe how to create a password to protect your jupyter notebooks. I would like to be able to create and share a particular notebook with a special password for just that notebook. Is this possible?
[ "No, it is not possible. The password protects the whole Jupyter server. Once somebody has logged into the server, there's nothing that could stop them from accessing all of the notebooks stored in the file system.\n", "I needed to share password prtected notebook recently and after some research I found 3 ways t...
[ 1, 0 ]
[]
[]
[ "ipython", "ipython_notebook", "jupyter", "jupyter_notebook", "python" ]
stackoverflow_0044580965_ipython_ipython_notebook_jupyter_jupyter_notebook_python.txt
Q: How to block size change of QTableWidget? Have table, when i resize window, table also resize with it, and blank spaces to the right and down appear. How to block resize of table when window change size? Table will have 6 col and 5 rows. import sys from PyQt5.QtWidgets import QWidget,QApplication,QTableWidget,QTab...
How to block size change of QTableWidget?
Have table, when i resize window, table also resize with it, and blank spaces to the right and down appear. How to block resize of table when window change size? Table will have 6 col and 5 rows. import sys from PyQt5.QtWidgets import QWidget,QApplication,QTableWidget,QTableWidgetItem,QVBoxLayout def getSelectedItemDa...
[ "you can set \"setMaximumSize\" and \"setMinimumSize\" to fix the whole table size\nself.table.setMaximumSize(100, 100)\n\n" ]
[ 1 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0074317280_pyqt5_python.txt
Q: Groupby function throwing error when attempting to get the second smallest date Python I am trying to pull the second closest date for each as of date in a data set. Below is some example data asOfDate maturityDate value 0 2022-09-01 2022-10-01 57.273 1 2022-09-01 2022-11-01 55.861 2 2022-09-01 2022-1...
Groupby function throwing error when attempting to get the second smallest date Python
I am trying to pull the second closest date for each as of date in a data set. Below is some example data asOfDate maturityDate value 0 2022-09-01 2022-10-01 57.273 1 2022-09-01 2022-11-01 55.861 2 2022-09-01 2022-12-01 59.231 3 2022-09-01 2023-01-01 59.305 4 2022-09-01 2023-02-01 58.081 5 2022-0...
[ "import pandas as pd\ncolumns = [\"asOfDate\", \"maturityDate\", \"value\"]\ndata = [\n[\"2022-09-01\", \"2022-10-01\", 57.273]\n,[\"2022-09-01\", \"2022-11-01\", 55.861]\n,[\"2022-09-01\", \"2022-12-01\", 59.231]\n,[\"2022-09-01\", \"2023-01-01\", 59.305]\n,[\"2022-09-01\", \"2023-02-01\", 58.081]\n...
[ 2, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074307140_dataframe_pandas_python.txt
Q: Remove values from columns that meet simultaneous DataFrame pandas condition Be the following DataFrame in pandas. country ctry city cty other important other_important other_1 France France París París blue 019210 0011119 red Spain Spain Madrid Barcelona blue 1211 0019210 blue Germany Spain Barcelona Barcelon...
Remove values from columns that meet simultaneous DataFrame pandas condition
Be the following DataFrame in pandas. country ctry city cty other important other_important other_1 France France París París blue 019210 0011119 red Spain Spain Madrid Barcelona blue 1211 0019210 blue Germany Spain Barcelona Barcelona white 019210 1212 red France UK Bourdeux London blue 019210 91021 red ...
[ "Use DataFrame.loc with set misisng value by conditions:\ncols = ['other','other_1']\ndf.loc[df.country.ne(df.ctry) | df.city.ne(df.cty), cols] = np.nan\ndf = df.drop(['country', 'city'], axis=1)\n\nSolution with remove columns country, city use DataFrame.pop:\ncols = ['other','other_1']\ndf.loc[df.pop('country').n...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074317498_dataframe_pandas_python.txt
Q: What does the underscore suffix in PyTorch functions mean? In PyTorch, many methods of a tensor exist in two versions - one with a underscore suffix, and one without. If I try them out, they seem to do the same thing: In [1]: import torch In [2]: a = torch.tensor([2, 4, 6]) In [3]: a.add(10) Out[3]: tensor([12, ...
What does the underscore suffix in PyTorch functions mean?
In PyTorch, many methods of a tensor exist in two versions - one with a underscore suffix, and one without. If I try them out, they seem to do the same thing: In [1]: import torch In [2]: a = torch.tensor([2, 4, 6]) In [3]: a.add(10) Out[3]: tensor([12, 14, 16]) In [4]: a.add_(10) Out[4]: tensor([12, 14, 16]) What ...
[ "You have already answered your own question that the underscore indicates in-place operations in PyTorch. However I want to point out briefly why in-place operations can be problematic:\n\nFirst of all on the PyTorch sites it is recommended to not use in-place operations in most cases. Unless working under heavy m...
[ 10, 4 ]
[ "In PyTorch, the ends with an underscore, a convention in PyTorch that indicates the method will not return a new tensor but will instead modify the tensor in place. For example, scatter_.\nhttps://yuyangyy.medium.com/understand-torch-scatter-b0fd6275331c\n" ]
[ -1 ]
[ "python", "pytorch" ]
stackoverflow_0052920098_python_pytorch.txt