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: Best method to measure execution time of a python snippet I want to compare execution time of two snippets and see which one is faster. So, I want an accurate method to measure execution time of my python snippets. I already tried using time.time(), time.process_time(), time.perf_counter_ns() as well as timeit.tim...
Best method to measure execution time of a python snippet
I want to compare execution time of two snippets and see which one is faster. So, I want an accurate method to measure execution time of my python snippets. I already tried using time.time(), time.process_time(), time.perf_counter_ns() as well as timeit.timeit(), but I am facing the same issues with all of the them. Th...
[ "The execution time of a given code snippet will almost always be different every time you run it. Most tools that are available for profiling a single function/snippet of code take this into account, and run the code multiple times to be able to provide an average execution time. The reason for this is that ther...
[ 3 ]
[]
[]
[ "python", "time", "timeit" ]
stackoverflow_0074495814_python_time_timeit.txt
Q: How to create a pandas dataframe using a list of 'epoch dates' into '%Y-%m-%d %s:%m:%f%z' format? My objective is to create the following pandas dataframe (with the 'date_time' column in '%Y-%m-%d %s:%m:%f%z' format): batt_no date_time 3 4 2019-09-19 20:59:06+00:00 4 5 201...
How to create a pandas dataframe using a list of 'epoch dates' into '%Y-%m-%d %s:%m:%f%z' format?
My objective is to create the following pandas dataframe (with the 'date_time' column in '%Y-%m-%d %s:%m:%f%z' format): batt_no date_time 3 4 2019-09-19 20:59:06+00:00 4 5 2019-09-19 23:44:07+00:00 5 6 2019-09-20 00:44:06+00:00 6 7 2019-09-20 01:14:06+00:00 ...
[ "As suggested, I put the solution in comment as an answer here.\npd.DataFrame({'batt_volt':[4,5,6,7], 'date_time': pd.to_datetime([1568926746,1568936647,1568940246,1568942046], unit='s', utc=True).strftime('%Y-%m-%d %s:%m:%f%z')}, index=[3,4,5,6])\n\npd.to_datetime works with dates, or list of dates, ...
[ 1 ]
[]
[]
[ "dataframe", "datetime", "numpy", "pandas", "python" ]
stackoverflow_0074346335_dataframe_datetime_numpy_pandas_python.txt
Q: discord bot is replying to every message that contains a word from a phrase in a list @client.event async def on_message(message): if message.author == client.user: return List = open("D:/code/code/DIscord bot/myFile.txt").readlines() List = str(List).replace("\\n", " ") if message.content in List: msg = ...
discord bot is replying to every message that contains a word from a phrase in a list
@client.event async def on_message(message): if message.author == client.user: return List = open("D:/code/code/DIscord bot/myFile.txt").readlines() List = str(List).replace("\\n", " ") if message.content in List: msg = 'REAL!' await message.reply(msg) im trying to get the bot to read all the sentences in...
[ "You assign List to be a string, not an array. What you likely want is this:\nList = open(\"D:/code/code/DIscord bot/myFile.txt\").readlines()\nList = str(List).split(\"\\\\n\")\n\nThis allows your in statement to check for entire sentences instead of individual words. Note, you may want to convert all the text to ...
[ 0, 0, 0 ]
[]
[]
[ "discord", "nextcord", "python" ]
stackoverflow_0074495513_discord_nextcord_python.txt
Q: How to identify the unfinished rectangle by image processing? I have a color image. After several preprocessing I am able to get the following image. However, as you have seen the door portion is not complete, only 3 lines are visible on the post processed one. Not the 4th boundary lin, because on the original p...
How to identify the unfinished rectangle by image processing?
I have a color image. After several preprocessing I am able to get the following image. However, as you have seen the door portion is not complete, only 3 lines are visible on the post processed one. Not the 4th boundary lin, because on the original photo, the color portion was missing at that part. Now I can identif...
[ "You want an image processing algorithm that given 3 sides of a rectangle will know to \"close\" the fourth one.\nSuppose we give you such an algorithm, how do you expect it to differentiate between the green rectangle (the door you want to detect) and the red rectangle (you do not want)?\n\n", "I beleive you sho...
[ 0, 0 ]
[]
[]
[ "image_processing", "image_segmentation", "opencv", "python" ]
stackoverflow_0071503894_image_processing_image_segmentation_opencv_python.txt
Q: Why can't I establish a tcp connection, via sockets in python, with a root name server? Background: I want to establish a TCP connection with a root name server so I can send a dns query and inspect the response I tried establishing a TCP connection with a root name server using the socket module in python, partic...
Why can't I establish a tcp connection, via sockets in python, with a root name server?
Background: I want to establish a TCP connection with a root name server so I can send a dns query and inspect the response I tried establishing a TCP connection with a root name server using the socket module in python, particularly with a.root-servers.net I wrote the code below in an interactive python shell, in Wind...
[ "I get good virtual circuit (TCP) results from this:\n$ time dig +vc +norec ns . @a.root-servers.net\n\n; <<>> DiG 9.10.6 <<>> +vc +norec ns . @a.root-servers.net\n;; global options: +cmd\n;; Got answer:\n;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 60546\n;; flags: qr aa; QUERY: 1, ANSWER: 13, AUTHORITY: 0...
[ 1 ]
[]
[]
[ "dns", "python", "sockets", "tcp", "windows" ]
stackoverflow_0074495961_dns_python_sockets_tcp_windows.txt
Q: Attempt to scrape search results from a site - Python I needed to scrape the telefone numbers and the email addreses from the following using python: url = 'https://rma.cultura.gob.ar/#/app/museos/resultados?provincias=Buenos%20Aires' source = requests.get(url).text soup = BeautifulSoup(source, 'lxml') print(so...
Attempt to scrape search results from a site - Python
I needed to scrape the telefone numbers and the email addreses from the following using python: url = 'https://rma.cultura.gob.ar/#/app/museos/resultados?provincias=Buenos%20Aires' source = requests.get(url).text soup = BeautifulSoup(source, 'lxml') print(soup) The problem is that what I get from the requests.get i...
[ "The data you see on the page is loaded from external URL via JavaScript. To get the data you can use requests/json modules, for example:\nimport json\nimport requests\n\napi_url = \"https://rmabackend.cultura.gob.ar/api/museos\"\n\nparams = {\n \"estado\": \"Publicado\",\n \"grupo\": \"Museo\",\n \"o\": \...
[ 1, 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074495820_python_web_scraping.txt
Q: How to connect to GCP Memorystore redis from local? I am able to access GCP Memorystore Redis from gcp cloud run through vpc connector. But how can I do that from my localhost ? A: You can connect from a localhost machine with port forwarding and it can be helpful to connect to your Redis instance during develo...
How to connect to GCP Memorystore redis from local?
I am able to access GCP Memorystore Redis from gcp cloud run through vpc connector. But how can I do that from my localhost ?
[ "You can connect from a localhost machine with port forwarding and it can be helpful to connect to your Redis instance during development.\nCreate a compute engine instance by running the following command:\n gcloud compute instances create NAME --machine-type=f1-micro --zone=ZONE\n\nOpen a new terminal on ...
[ 2, 0 ]
[]
[]
[ "google_cloud_platform", "python" ]
stackoverflow_0068407501_google_cloud_platform_python.txt
Q: With list of tuples corresponding to int values, want to create a unique list of those tuples corresponding to the sum of all the int values (python) I have a huge list of sublists, each sublist consisting of a tuple and an int. Example: [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5]...
With list of tuples corresponding to int values, want to create a unique list of those tuples corresponding to the sum of all the int values (python)
I have a huge list of sublists, each sublist consisting of a tuple and an int. Example: [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]] I want to create a unique list of those tuples corresponding...
[ "You can try this (though there's probably a shorter way):\na= [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]]\n\nb = {}\n\nfor l in a:\n if b.get(l[0]):\n b[l[0]] += l[1]\n else:\...
[ 1, 1, 1 ]
[]
[]
[ "list", "python", "tuples", "unique" ]
stackoverflow_0074495864_list_python_tuples_unique.txt
Q: How to use a parameter and its reciprocal in a CVXPY DPP? In the following test program import cvxpy as cp def cp_log_ratio_norm(a, b): # Both `a * cp.inv_pos(b)` and `a / b` make this problem non-DPP return cp.maximum(a * b, b * cp.inv_pos(a)) var = cp.Variable(pos=True) param = cp.Parameter(pos=True) param...
How to use a parameter and its reciprocal in a CVXPY DPP?
In the following test program import cvxpy as cp def cp_log_ratio_norm(a, b): # Both `a * cp.inv_pos(b)` and `a / b` make this problem non-DPP return cp.maximum(a * b, b * cp.inv_pos(a)) var = cp.Variable(pos=True) param = cp.Parameter(pos=True) param.value = 5 objective = cp.Minimize(cp_log_ratio_norm(var, param...
[ "Looking at the docs we find that this is expected:\n\nAs another example, the quotient expr / p is not DPP-compliant when p is a parameter, but this can be rewritten as expr * p_tilde, where p_tilde is a parameter that represents 1/p.\n\nBut in your case we need both p and 1 / p? Keeping those two synchronized is ...
[ 1 ]
[]
[]
[ "convex_optimization", "cvxpy", "mathematical_optimization", "python" ]
stackoverflow_0074496052_convex_optimization_cvxpy_mathematical_optimization_python.txt
Q: Add multiple unknowns to a string in Pyton I need to add to the line: url="items.point&point1={item}%2C{item}&point2C{item}%2C{item}" four values ​​of possible coordinates instead of "item" value. We have to generate these coordinate values ​​in a loop. I tried many different options for how to do this, but the p...
Add multiple unknowns to a string in Pyton
I need to add to the line: url="items.point&point1={item}%2C{item}&point2C{item}%2C{item}" four values ​​of possible coordinates instead of "item" value. We have to generate these coordinate values ​​in a loop. I tried many different options for how to do this, but the program displays a lot of extra values. My code: ...
[ "I remember reading recently something related to your problem. Can't remember the post, else I'd link it, but I took notes about the beautiful method! So try this:\nurls=[]\nfor item1, item2 in zip(*[iter(coordinates)]*2):\n urls.append(f\"items.point&point1{item1}%2C{item2}&point2=39.073557%2C45.005125\")\npri...
[ 1, 0 ]
[]
[]
[ "loops", "python", "string" ]
stackoverflow_0074495932_loops_python_string.txt
Q: How do I open the main window and all the other Windows remain hidden untill called? I have a bunch of Tk() throughout my program. So when I first run main all these other windows come on to the screen and I have to minimize them to get the main window on front. How do I prevent these windows from opening and just...
How do I open the main window and all the other Windows remain hidden untill called?
I have a bunch of Tk() throughout my program. So when I first run main all these other windows come on to the screen and I have to minimize them to get the main window on front. How do I prevent these windows from opening and just open the main window? There are 3 or 4 .py files imported by the main. I've tried withdra...
[ "i figured out how to get the main window to come up in front of the other tkinter windows that are created by my imports\nroot1.focus_force()\ncalled it right before\nroot1.mainloop()\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074494090_python_tkinter.txt
Q: Pyinstaller raise a warning when I run it Hi when I try to convert my kivy python application to an executable file , it gives me the following error , any ideas on how to fix it ? PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_kivy required by hook for module /Li...
Pyinstaller raise a warning when I run it
Hi when I try to convert my kivy python application to an executable file , it gives me the following error , any ideas on how to fix it ? PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_kivy required by hook for module /Library/Frameworks/Python.framework/Versions/3.7/...
[ "pip install -U pyinstaller-hooks-contrib\n" ]
[ 0 ]
[]
[]
[ "kivy", "pyinstaller", "python" ]
stackoverflow_0072601797_kivy_pyinstaller_python.txt
Q: Change python version to 3.x According to poetry's docs, the proper way to setup a new project is with poetry new poetry-demo, however this creates a project based on the now deprecated python2.7 by creating the following toml file: [tool.poetry] name = "poetry-demo" version = "0.1.0" description = "" authors = ["...
Change python version to 3.x
According to poetry's docs, the proper way to setup a new project is with poetry new poetry-demo, however this creates a project based on the now deprecated python2.7 by creating the following toml file: [tool.poetry] name = "poetry-demo" version = "0.1.0" description = "" authors = ["Harsha Goli <harshagoli@gmail.com>...
[ "Poetry makes it super easy to work with different Python versions or virtual environments. The recommended way to specify your Python version according to Poetry docs is\npoetry env use /path/to/preferred/python/version\n\nYou can get the path to your Python version by running\nwhich python3.7\non Linux or\npy -0p...
[ 54, 42, 32, 9, 9, 6, 4, 3, 3, 0, 0, 0 ]
[]
[]
[ "python", "python_poetry" ]
stackoverflow_0060580113_python_python_poetry.txt
Q: how to convert the result of product to hex? how to use a method to change it into hexadecimal. It looks i made an mistake. please help me to find a solution. print("Full Names:" " "+ string, [ord(i) for i in string]) product = reduce(lambda x,y: x*y, [ord(i) for i in string]) print(product) random.seed(2) random....
how to convert the result of product to hex?
how to use a method to change it into hexadecimal. It looks i made an mistake. please help me to find a solution. print("Full Names:" " "+ string, [ord(i) for i in string]) product = reduce(lambda x,y: x*y, [ord(i) for i in string]) print(product) random.seed(2) random.uniform(len(string) ,2000000) product = reduce(lam...
[ "Printing in different bases can be done in a few ways:\nFirst of all there is the hex() function:\n>>> print(\"The result is: \", hex(28))\nThe result is: 0x1c\n\nThis returns the hex as most other applications would want it.\nHowever, if you only want the hex itself, without the 0x to start it, you can use format...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074495749_python.txt
Q: Asynchronous Web Scraping, Python Im trying to run this function every 2seconds forever : import requests from bs4 import BeautifulSoup import asyncio async def scrape(): test = [] r = requests.get(coin_desk) soup = BeautifulSoup(r.text, features='xml') title = soup.find_all('title')[2] await...
Asynchronous Web Scraping, Python
Im trying to run this function every 2seconds forever : import requests from bs4 import BeautifulSoup import asyncio async def scrape(): test = [] r = requests.get(coin_desk) soup = BeautifulSoup(r.text, features='xml') title = soup.find_all('title')[2] await asyncio.sleep(2) for x in title: ...
[ "The async routine (scrape) was never placed into the event loop.\nYou can add it with\nloop.create_task(routine)\n\nSee:\nWhat does asyncio.create_task() do?\n" ]
[ 0 ]
[]
[]
[ "asynchronous", "beautifulsoup", "python", "request", "web_scraping" ]
stackoverflow_0074495579_asynchronous_beautifulsoup_python_request_web_scraping.txt
Q: Simple Python chatbot in Replit I'm a lawyer and (very) beginning programmer. I'm at step 1 of learning to build a chatbot that can hopefully help me advise my clients someday. I'm trying to follow this Medium post on how to build a simple python chatbot: https://towardsdatascience.com/how-to-create-a-chatbot-wit...
Simple Python chatbot in Replit
I'm a lawyer and (very) beginning programmer. I'm at step 1 of learning to build a chatbot that can hopefully help me advise my clients someday. I'm trying to follow this Medium post on how to build a simple python chatbot: https://towardsdatascience.com/how-to-create-a-chatbot-with-python-deep-learning-in-less-than-a...
[ "\nNo, a main.py doesn't have any specific meaning, it's just conventional to name the \"entry point\" that name. Any other name can be used for an \"entry point\" too.\n\nYou probably need to use libraries shown in the tutorial, but you need to import them in those files where they are used.\n\nIt's probably just ...
[ 0 ]
[]
[]
[ "chatbot", "python", "replit" ]
stackoverflow_0074496023_chatbot_python_replit.txt
Q: Recursive function to go through list of references to indices in same list I have this list: [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []] It could be described as a list of references to other items in th...
Recursive function to go through list of references to indices in same list
I have this list: [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 14], [15, 16], [15, 16], [15, 16], [17], [18], [19], [20], [21], [20], [21], [], [], [], [], []] It could be described as a list of references to other items in the same list, like this: 0 --> 1 2 3 4 1 --> 5 2 --> 6 7 3 --> 8 4 --> 9 5 --> 10...
[ "Here is my implementation of what I understood from my requirements\n\ndef dfs(graph, u, curr,res):\n c = curr+ [u]\n if(len(graph[u]) == 0):\n res.append(c)\n for v in graph[u]:\n dfs(graph, v, c, res)\n \n \n \ngraph = [[1, 2, 3, 4], [5], [6, 7], [8], [9], [10, 11], [12, 13, 1...
[ 1, 1 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074495938_python_recursion.txt
Q: How to show first 5 characters within a column in Python? Need the Zip column to only show the first 5 characters Result: enter image description here Expected Result: enter image description here Source Code: import pandas as pd import numpy as np #numpy is the module which can replace errors from huge datasets ...
How to show first 5 characters within a column in Python?
Need the Zip column to only show the first 5 characters Result: enter image description here Expected Result: enter image description here Source Code: import pandas as pd import numpy as np #numpy is the module which can replace errors from huge datasets from openpyxl import load_workbook from openpyxl.styles import ...
[ "You're not assigning the sliced string back to the dataframe. You just have to replace df_all['Zip'].str[:5] with df_all['Zip'] = df_all['Zip'].str[:5]\nExample:\n>>> import pandas as pd\n>>> data = [[\"Alice\"],[\"Bob\"],[\"Eve\"]]\n>>> df = pd.DataFrame(data,columns=['Name'])\n>>> df\nName\n0 Alice\n1 Bob\n2...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074495737_pandas_python.txt
Q: How to interact with shell in Python and get return code There are questions like this, that show how to interact with a shell in Python, sending stuff to its stdin and reading back stuff from its stdout. I'd just like to do one more thing on top of that: Start a process running a shell -- say: subprocess.Popen([...
How to interact with shell in Python and get return code
There are questions like this, that show how to interact with a shell in Python, sending stuff to its stdin and reading back stuff from its stdout. I'd just like to do one more thing on top of that: Start a process running a shell -- say: subprocess.Popen(["powershell --someArgs"]) interact with that shell/process by:...
[]
[]
[ "That's on the contrary the easiest part.\nWhen the subprocess terminates, it sends its exit code.\nIt is the return value of wait method\nimport subprocess\np=subprocess.Popen(['sh', '-c', 'sleep 5 ; exit 12'])\nx=p.wait()\nprint(f'exit code was {x}')\n\nNote that you are not forced to literally wait the process f...
[ -1 ]
[ "interactive", "powershell", "python", "shell", "subprocess" ]
stackoverflow_0074495770_interactive_powershell_python_shell_subprocess.txt
Q: Pandas with MatplotLib: plotting regression line with log-x scale The issue is this one: I'm trying to plot a lineal regression line over a scatter plot, from two Pandas Series obtained from a Panda DataFrame. Each one of these Series represents a column of the DataFrame. Here, the 'X' axis of my scatter plot is r...
Pandas with MatplotLib: plotting regression line with log-x scale
The issue is this one: I'm trying to plot a lineal regression line over a scatter plot, from two Pandas Series obtained from a Panda DataFrame. Each one of these Series represents a column of the DataFrame. Here, the 'X' axis of my scatter plot is represented in a logarithmic scale. I've looked for a similar issue here...
[ "I could achieve this using Seaborn, like this ('municipios' is my whole Pandas DataFrame):\nx=np.log(municipios['DENSIDAD_HABITACIONAL'])\ny=municipios['PORCENTAJE_NBI']\n\ns=sns.regplot(x=x, y=y,fit_reg=True)\ns.figure.set_size_inches(18.5, 10.5)\n\nsns.despine()\n\nAnd also:\nx=np.log(municipios['POBLACION'])\ny...
[ 0 ]
[]
[]
[ "jupyter_notebook", "matplotlib", "numpy", "pandas", "python" ]
stackoverflow_0074437281_jupyter_notebook_matplotlib_numpy_pandas_python.txt
Q: Accessing a DataFrame inside of a class I have created a DataFrame inside of a class but I am having trouble using it outside of the class or even calling it. How would I do that? I just want to print the DataFrame outside of the class. class Youpi(Baseball, Soccer): def __init__(self): Baseball.__in...
Accessing a DataFrame inside of a class
I have created a DataFrame inside of a class but I am having trouble using it outside of the class or even calling it. How would I do that? I just want to print the DataFrame outside of the class. class Youpi(Baseball, Soccer): def __init__(self): Baseball.__init__(self, self) self.Random_df = pd....
[ "I would try print(dictionary.Attendance)\n" ]
[ 0 ]
[]
[]
[ "class", "dataframe", "python" ]
stackoverflow_0074496000_class_dataframe_python.txt
Q: Python: How to access list object deep within a nested dictionary structure? I have a rather deep python nested array(converted from XML for ease in processing) that has a list within a bunch of dictionaries. I need to access the list object (which should be 'Apparatus') so I can do a number of manipulations. A)...
Python: How to access list object deep within a nested dictionary structure?
I have a rather deep python nested array(converted from XML for ease in processing) that has a list within a bunch of dictionaries. I need to access the list object (which should be 'Apparatus') so I can do a number of manipulations. A) Count the current number of list objects so I can add another; B) Change some of ...
[ "Your desired list can be obtained like this:\ndesired_list = my_dict['CadData']['FireIncidentCollection']['FireIncident']['ApparatusCollection']['Apparatus']\n\nTrying print (desired_list) returns:\n[{'ApparatusPersonnelCollection': {'ApparatusPersonnel': [{'FirstName': 'Jon',\n 'LastName': 'Snow',\n 'Leve...
[ 0 ]
[]
[]
[ "arrays", "dictionary", "indexing", "list", "python" ]
stackoverflow_0074496130_arrays_dictionary_indexing_list_python.txt
Q: Converting from np.float64 to np.float32 completely changes the value of some numbers I have a numpy array of dtype=float64, when attempting to convert it the types to float 32, some values change completely. for example, i have the following array: `test_64 = np.array([20110927.00000,20110928.00000,20110929.00000...
Converting from np.float64 to np.float32 completely changes the value of some numbers
I have a numpy array of dtype=float64, when attempting to convert it the types to float 32, some values change completely. for example, i have the following array: `test_64 = np.array([20110927.00000,20110928.00000,20110929.00000,20110930.00000,20111003.00000,20111004.00000,20111005.00000,20111006.00000,20111007.00000,...
[ "Well, yes, that is what float32 are.\nShortest way to see it, float32 have 24 bits significand (1 bit of sign, and 8 bits of exponents). That is 33 bits in all. But the 1st significand bit is not stored, because it is assumed to be 1.\nnp.log2(20110927.)\n# 24.2614762474699\n\nSo, see the problem. You would need 2...
[ 3 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074495636_arrays_numpy_python.txt
Q: Import "flask_sqlalchemy" could not be resolved from source: Pylance I have tried all of the other solutions before posting here so I hope this does not get removed. Error comes form this line: from flask_sqlalchemy import SQLAlchemy I am running the latest version of VSCode. Things I've tried from within my virt...
Import "flask_sqlalchemy" could not be resolved from source: Pylance
I have tried all of the other solutions before posting here so I hope this does not get removed. Error comes form this line: from flask_sqlalchemy import SQLAlchemy I am running the latest version of VSCode. Things I've tried from within my virtual envionment (venv) 1. pip install flask_sqlalchemy 2. pip3 install flas...
[ "I was having the same problem, I messed around a lot reinstalling things so I'm not 100% sure what the perfect solution is but this is what finally worked for me.\nView -> Command Pallete -> Python: Select Interpreter -> Select the version that says 'Global'\nThen follow the same steps but instead select the versi...
[ 1, 0 ]
[]
[]
[ "pylance", "python", "visual_studio_code" ]
stackoverflow_0071489531_pylance_python_visual_studio_code.txt
Q: How to migrate password hashes from Passlib.bcrypt to Django's default pbkdf2_sha256? I had a FastAPI app that had been using Passlib's bcrypt module to hash passwords. Here's an example string that is stored in the database as a password: $2b$12$62GCnIkiQp7dE/N2.Al4t.ODW.JYXCz8rHHmaLt63NnML4xDgKhFK Now, the probl...
How to migrate password hashes from Passlib.bcrypt to Django's default pbkdf2_sha256?
I had a FastAPI app that had been using Passlib's bcrypt module to hash passwords. Here's an example string that is stored in the database as a password: $2b$12$62GCnIkiQp7dE/N2.Al4t.ODW.JYXCz8rHHmaLt63NnML4xDgKhFK Now, the problem is I'm not sure whether it's possible to migrate this hash over to my new django applica...
[ "Okay, so after trying around I came up with the solution\nFirst: add \"django.contrib.auth.hashers.BCryptPasswordHasher\" to settings.PASSWORD_HASHERS\nNow, you can to every string that looks $2b$12$62GCnIkiQp7dE/N2.Al4t.ODW.JYXCz8rHHmaLt63NnML4xDgKhFK you add bcrypt$ for the result to look like bcrypt$$2b$12$62GC...
[ 0 ]
[]
[]
[ "bcrypt", "hash", "pbkdf2", "python" ]
stackoverflow_0074478134_bcrypt_hash_pbkdf2_python.txt
Q: Plotly express: text is "flying in" in animations Added some text (to be displayed on the bars) in a bar chart with animation frames. And well, the text instead of rising along with the bar (like in the beginning of the GIF when I manually move the slider), flies in from the top left corner at each frame until the...
Plotly express: text is "flying in" in animations
Added some text (to be displayed on the bars) in a bar chart with animation frames. And well, the text instead of rising along with the bar (like in the beginning of the GIF when I manually move the slider), flies in from the top left corner at each frame until the bar is big enough to fit in the number. Now, tweaking...
[ "I realize this question was asked a long time ago, but I'm still going to answer it. Essentially, since the text doesn't 'fit', it flies. I think that that will make more sense by the time you get to the end of this answer. If you render this code in too small of a space, you can still reproduce the 'flying' effec...
[ 0 ]
[]
[]
[ "animation", "data_visualization", "plotly", "plotly_python", "python" ]
stackoverflow_0067972110_animation_data_visualization_plotly_plotly_python_python.txt
Q: Stripe implementation in django not redirecting to success page I was trying to implement stripe in Django and everything worked fine until I tried to redirect the user to a success page after the payment. Can anybody have a look at my code and tell me what I am doing wrong? views.py @csrf_exempt def create_checko...
Stripe implementation in django not redirecting to success page
I was trying to implement stripe in Django and everything worked fine until I tried to redirect the user to a success page after the payment. Can anybody have a look at my code and tell me what I am doing wrong? views.py @csrf_exempt def create_checkout_session(request, id): request_data = json.loads(request.body) ...
[ "The issue is that the point when you create the Checkout Session and set the order data is disconnected from the point at which you render your success page with the PaymentSuccessView class. Just because those two pieces of code are in the same file does not mean the state will be maintained between different re...
[ 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0074489504_django_django_models_django_templates_django_views_python.txt
Q: Why does Python allow a module to import itself? In a simple Program in BugTest.py: from BugTest import * print("Hello World") note my error in importing BugTest.py from BugTest.py Here is the output: Hello World Hello World My question is: Why doesn't this cause a compile error? Is this a bug in Python? Why do...
Why does Python allow a module to import itself?
In a simple Program in BugTest.py: from BugTest import * print("Hello World") note my error in importing BugTest.py from BugTest.py Here is the output: Hello World Hello World My question is: Why doesn't this cause a compile error? Is this a bug in Python? Why does it only import twice, rather than enter an infinite...
[ "\nWhy doesn't this cause a compile error?\n\nBecause it's completely valid syntax. The only error (absent a problem in the Python runtime itself, such as running out of memory or failing to find the source code) that can occur at compile time in Python is SyntaxError. Names are only resolved at runtime.\nThat said...
[ 4, 2 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0074496200_python_python_import.txt
Q: Tesseract doesn't recognize certain pictures. Python Tesseract works fine when I use other pictures but whenever I use this picture it doesn't recognize the picture. Can someone explain me why please? import cv2 import pytesseract import time import random from pynput.keyboard import Controller keyboard = Control...
Tesseract doesn't recognize certain pictures. Python
Tesseract works fine when I use other pictures but whenever I use this picture it doesn't recognize the picture. Can someone explain me why please? import cv2 import pytesseract import time import random from pynput.keyboard import Controller keyboard = Controller() # Create the controller pytesseract.pytesseract.te...
[ "I fixed my problem, all I needed to do was add this code to my script.\ntext = pytesseract.image_to_string(\n img, config=(\"-c tessedit\"\n \"_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \" --psm 10\"\n \" \"))\n\n" ]
[ 0 ]
[]
[]
[ "ocr", "python", "tesseract" ]
stackoverflow_0074495663_ocr_python_tesseract.txt
Q: Recursive function that filter names (python) I need to define a recursive function that takes two parameters (a list with names and an initial), and returns a new list with all the names that start with the initial. Right now I have got this code, and i don't know why it doesn't work: def filter_names(names, init...
Recursive function that filter names (python)
I need to define a recursive function that takes two parameters (a list with names and an initial), and returns a new list with all the names that start with the initial. Right now I have got this code, and i don't know why it doesn't work: def filter_names(names, initial): result = [] if names[0][0] == initial...
[ "Your recursive call isn't appending to the same result that's defined in the outer scope.\nUsually in a recursive function you combine the result of your recursive call with whatever work you've done in the current frame. In this case that might look like this:\ndef filter_names(names, initial):\n if not names...
[ 1, 0 ]
[]
[]
[ "function", "python", "recursion" ]
stackoverflow_0074496273_function_python_recursion.txt
Q: Recursive python function that checks if a string represents the" relief of a landscape" I'm trying to build a recursive function to represent the relief of a landscape using a string. The string can have a random length but only contains '\' '/' '_' '¯'. For example: If I give (/¯\/\__/¯¯\/\_/\__) it should ...
Recursive python function that checks if a string represents the" relief of a landscape"
I'm trying to build a recursive function to represent the relief of a landscape using a string. The string can have a random length but only contains '\' '/' '_' '¯'. For example: If I give (/¯\/\__/¯¯\/\_/\__) it should return True. If the string is empty, it's also valid. It's not valid if there's a discontinuit...
[ "You want a datastructure like this:\nlevel = {\n \"_\": (0, 0), # initial level, final level\n \"¯\": (1, 1),\n \"/\": (0, 1),\n r\"\\\": (1, 0),\n}\n\nNow it's just a matter of iterating through\ncharacters and looking up the levels.\nVerify that final level of character i\nis identical to initial le...
[ 0 ]
[]
[]
[ "function", "list", "python", "recursion", "string" ]
stackoverflow_0074495856_function_list_python_recursion_string.txt
Q: No type hint with return values for TypedDict in PyCharm Atm I am starting with the typing library. When I create a wrong dict in-line I will get a typehint that the created dictionary is indeed not correct, and 'type hint': 42 is highlighted. Is it normal that the wrong return value in the function is not highlig...
No type hint with return values for TypedDict in PyCharm
Atm I am starting with the typing library. When I create a wrong dict in-line I will get a typehint that the created dictionary is indeed not correct, and 'type hint': 42 is highlighted. Is it normal that the wrong return value in the function is not highlighted? Which is 'no type hint': 88 in this case. from typing im...
[ "I think this question should end up getting closed, but here's what I see in PyCharm 2022.2.3 with a Python 3.10 environment on Windows 10:\n\nAnd:\n\nNote that the squigly lines are the result of there not being sufficient empty lines between the function definitions and the rest of the main body code.\n" ]
[ 1 ]
[]
[]
[ "pycharm", "python", "python_typing" ]
stackoverflow_0074495944_pycharm_python_python_typing.txt
Q: Numpy masking in 3 channel array The following Snippet will create a test image # Create 3x3x3 image test_image = [] for i in range(9): if i < 6: image.append([255, 22, 96]) else: image.append([255, 0, 0]) Out: array([[[255, 22, 96], [255, 22, 96], [255, 22, 96]], ...
Numpy masking in 3 channel array
The following Snippet will create a test image # Create 3x3x3 image test_image = [] for i in range(9): if i < 6: image.append([255, 22, 96]) else: image.append([255, 0, 0]) Out: array([[[255, 22, 96], [255, 22, 96], [255, 22, 96]], [[255, 22, 96], [255, ...
[ "You can convert msk to a 3-D array using array broadcasting:\nhttps://numpy.org/doc/stable/user/basics.broadcasting.html\nThe command .reshape can be used to change the dimensions of an array. Numpy will automatically fill out the \"thin\" dimension. So for example,comparing arrays with shapes (n,n,3) and(1,1,3) i...
[ 1 ]
[]
[]
[ "image", "numpy", "opencv", "python", "rgb" ]
stackoverflow_0074496375_image_numpy_opencv_python_rgb.txt
Q: how to convert text file data to python dictionary I have seen quite a few questions like this however none like mine specific separation of items with newlines. text file: John City: New york Job: surgeon Happy: no Terry City: Miami House: Yes Job: nurse Married: No Joe City: LA Married: No Job: None Dictionar...
how to convert text file data to python dictionary
I have seen quite a few questions like this however none like mine specific separation of items with newlines. text file: John City: New york Job: surgeon Happy: no Terry City: Miami House: Yes Job: nurse Married: No Joe City: LA Married: No Job: None Dictionary should have separate items which are determined by the...
[ "Try:\ntext = \"\"\"\\\nJohn\nCity: New york\nJob: surgeon\nHappy: no\n\nTerry\nCity: Miami\nHouse: Yes\nJob: nurse\nMarried: No\n\nJoe\nCity: LA\nMarried: No\nJob: None\"\"\"\n\nout = {}\nfor group in text.split(\"\\n\\n\"):\n lines = group.split(\"\\n\")\n out[lines[0]] = dict(l.split(\": \") for l in lines...
[ 0 ]
[]
[]
[ "dictionary", "list", "python", "python_3.x" ]
stackoverflow_0074496420_dictionary_list_python_python_3.x.txt
Q: PYTHONPATH works in interactive mode but fails in script Problem I've been trying to run a python script which imports from the Foundation package: from Foundation import ... Whenever I try to run this I get the following error: Things I've done: I've installed the Foundation package and verified that it was inst...
PYTHONPATH works in interactive mode but fails in script
Problem I've been trying to run a python script which imports from the Foundation package: from Foundation import ... Whenever I try to run this I get the following error: Things I've done: I've installed the Foundation package and verified that it was installed in /usr/local/lib/python3.7/site-packages I've added exp...
[ "First, you run Python as your user (say ~joe or whatever your UID is) but then you bring sudo to the table. And that's where things starts to differ, because it will not inherit your environment. Simple test for you to replay (substitute python3 by whatever path/version you want):\n$ python3\n>>> import sys\n>>> s...
[ 1 ]
[]
[]
[ "python", "pythonpath", "sys.path" ]
stackoverflow_0074496416_python_pythonpath_sys.path.txt
Q: Remove a value of a data frame based on a condition between columns I have this df with 9 columns x y1_x y2_x y3_x y4_x 0 -17.7 -0.785430 NaN NaN NaN 1 -15.0 NaN NaN NaN -3820.085000 2 -12.5 NaN NaN 2.138833 ...
Remove a value of a data frame based on a condition between columns
I have this df with 9 columns x y1_x y2_x y3_x y4_x 0 -17.7 -0.785430 NaN NaN NaN 1 -15.0 NaN NaN NaN -3820.085000 2 -12.5 NaN NaN 2.138833 NaN 3 -12.4 NaN NaN 1.721205 NaN 4...
[ "you can use:\n#get count of nans between ('y1_x', 'y2_x', 'y3_x', 'y4_x', 'd1', 'd2', 'd3', 'd4')\nfinal['mask']=final.iloc[:,1:5].isna().sum(axis=1)\n\n#if the mask is 2, it means it will be filled with nan.\ncount=len(final[final['mask']==2])\n\n#We enter the loop as many as the number of rows with a mask value ...
[ 2, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074495116_dataframe_pandas_python.txt
Q: Problems filtering columns that have many rows with a None value(Django database) I am filtering a certain column in PostgreSQL database. n = Database.objects.values(column).count() for i in range(0, n): name = list(Database.objects.all().values_list(column, flat=True))[i] There are 105 lines...
Problems filtering columns that have many rows with a None value(Django database)
I am filtering a certain column in PostgreSQL database. n = Database.objects.values(column).count() for i in range(0, n): name = list(Database.objects.all().values_list(column, flat=True))[i] There are 105 lines. From line 86 onwards the values are None. However, when querying line 43, the returne...
[ "\nI want to know if there is any problem when filtering columns that have many None values\n\nNo, there is no problem with that.\n\nA relational database contains sets of rows,\nnamed \"tables\".\nSets are unordered. Yet you speak of values\nstarting at this or that offset, as though\nwe had a list of values where...
[ 1 ]
[]
[]
[ "django", "django_database", "python" ]
stackoverflow_0074496489_django_django_database_python.txt
Q: Finding a Sum of Series in Python Write a python program that calculate the sum of the series: (1,2,9,28, ... , 1000001). The sum of that series is represented using the equation below. Find the value of y and print it. I can't figure it out A: Since you haven't provided the equation, I'm just going to give gene...
Finding a Sum of Series in Python
Write a python program that calculate the sum of the series: (1,2,9,28, ... , 1000001). The sum of that series is represented using the equation below. Find the value of y and print it. I can't figure it out
[ "Since you haven't provided the equation, I'm just going to give general advice.\nIf we imagine that our education is: x*2 {from 0 to 20}, we can use a list and the sum() function to solve it.\nresult = sum([x*2 for x in range(0,21)])\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074496247_python.txt
Q: Adding another argument to my discord.py command I'm trying to add an additional argument to this mute command I have made for my discord.py bot but I'm getting a SyntaxError and have been having trouble understanding the syntax for what I'm trying to do. Here is the part of my program that is relevant to my issue...
Adding another argument to my discord.py command
I'm trying to add an additional argument to this mute command I have made for my discord.py bot but I'm getting a SyntaxError and have been having trouble understanding the syntax for what I'm trying to do. Here is the part of my program that is relevant to my issue: #Tempmute Command @bot.command(name='tempmute') @com...
[ "\nThe error I get is: SyntaxError: positional argument follows keyword argument\n\nRather than:\n...muted successfully for\", reason, color=...\n\ntry a simple reason=reason kwarg call:\n...muted successfully for\", reason=reason, color=...\n\n\nThe motivation for this diagnostic\nis to improve code clarity at the...
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074496484_discord_discord.py_python.txt
Q: how to translate javascript child inheritance into python I'm having trouble translating the following JavaScript code into python. My problem is inheriting the parent properties and methods in the ChildNode class by using super.__init__(). In js, you just call super() and get all the props. It doesn't seem to be ...
how to translate javascript child inheritance into python
I'm having trouble translating the following JavaScript code into python. My problem is inheriting the parent properties and methods in the ChildNode class by using super.__init__(). In js, you just call super() and get all the props. It doesn't seem to be the same in python. The super function is demanding to have val...
[ "The child class's __init__ method needs to pass the appropriate arguments in the super().__init__() call.\n# having trouble inheriting here\nclass ChildNode(BinarySearchTree):\n def __init__(self, val: int):\n super().__init__(val, '')\n\n del self.key\n\nYou don't need to do self.val = val in the...
[ 1, 1 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0074496525_javascript_python.txt
Q: root.iconbitmap() forces tkinter to enter a temporary eventloop? Does wm_iconbitmap method forces tkinter to enter an event loop while it processes the icon file? Is there a way to avoid this? Check this example that illustrates this: from tkinter import * import time root = Tk() root.iconbitmap('images/logo.ico'...
root.iconbitmap() forces tkinter to enter a temporary eventloop?
Does wm_iconbitmap method forces tkinter to enter an event loop while it processes the icon file? Is there a way to avoid this? Check this example that illustrates this: from tkinter import * import time root = Tk() root.iconbitmap('images/logo.ico') # Without `mainloop()` shows the window, means the events have start...
[ "The eventloop and the created window are different things. In your case it is the window that is forced into existence and is mentioned in the source code as a side effect:\n\nSide effects:\nOne or all windows may have their icon changed.\nThe Tcl result may be modified. The window-manager will be\ninitialised if ...
[ 1 ]
[]
[]
[ "event_loop", "python", "tkinter" ]
stackoverflow_0070777760_event_loop_python_tkinter.txt
Q: How can I include the absolute value of a decision variable in PuLP objective function The problem setup is fairly simple. There are 5 available instruments in a portfolio that can be traded. The optimizer needs to figure out which instruments need to be bought and / or sold to make max profit, There are the estim...
How can I include the absolute value of a decision variable in PuLP objective function
The problem setup is fairly simple. There are 5 available instruments in a portfolio that can be traded. The optimizer needs to figure out which instruments need to be bought and / or sold to make max profit, There are the estimates for price change and some risk constraints. Now as in the real world, there are always ...
[ "\nIntroduce a non-negative variable say absv[i].\nAdd the two constraints: absv[i] >= instr_avl[i] and absv[i] >= -instr_avl[i].\nAdd the term: -absv[i]*df[df['instrument']==i]['spread_cost'].values[0] to the objective.\n\nThis type of formulation is described in detail in basically any book on linear programming....
[ 1 ]
[]
[]
[ "linear_programming", "optimization", "pulp", "python" ]
stackoverflow_0074496539_linear_programming_optimization_pulp_python.txt
Q: date countdown not working as intended. time keeps printing I have made a script to show the difference between today's date and a date you put in and ended it with the print function and an f string. from datetime import datetime today = datetime.today() print("Please enter the date you want to find out how many...
date countdown not working as intended. time keeps printing
I have made a script to show the difference between today's date and a date you put in and ended it with the print function and an f string. from datetime import datetime today = datetime.today() print("Please enter the date you want to find out how many days until below: ") year = int(input("What year? ")) month = in...
[ "You could use date for this calculation.\nfrom datetime import date\n\ntoday = date.today()\nprint(\"Please enter the date you want to find out how many days until below: \")\nyear = int(input(\"What year? \"))\nmonth = int(input(\"What month? \"))\nday = int(input(\"What day? \"))\n\n\ndate2 = date(year, month, d...
[ 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074496577_datetime_python.txt
Q: PYTHON - extract list element using keyword My goal is to extract an element from many list that similar like this. Taking elements that is food. test_list = ['Tools: Pen', 'Food: Sandwich', 'Fruit: Apple' ] I the final result would be "Sandwich" by look list element with the word "Food:" and split from there. My...
PYTHON - extract list element using keyword
My goal is to extract an element from many list that similar like this. Taking elements that is food. test_list = ['Tools: Pen', 'Food: Sandwich', 'Fruit: Apple' ] I the final result would be "Sandwich" by look list element with the word "Food:" and split from there. My usual method is lookup by index test_list[1].spl...
[ "I would consider using a dictionary for this application.\nto translate a list of the form you gave into a dictionary:\ntest_dict = {i.split(\": \")[0]: i.split(\": \")[1] for i in test_list}\n\nAnd then you can access elements by key\ntest_dict['Food']\n\n", "What you want is a dictionary.\ntest_list_2 =\n{'Too...
[ 2, 0 ]
[]
[]
[ "list", "pdfplumber", "python" ]
stackoverflow_0074496611_list_pdfplumber_python.txt
Q: Issues with continuously nesting while loops in python I'm writing a text-based RPG in python 3. I'm writing it with individual scenes that will execute related functions based on user input in that specific scene. Some of those inputs will move the user to a new scene. The player is stuck in a scene with a while ...
Issues with continuously nesting while loops in python
I'm writing a text-based RPG in python 3. I'm writing it with individual scenes that will execute related functions based on user input in that specific scene. Some of those inputs will move the user to a new scene. The player is stuck in a scene with a while True loop until they move to a new scene, where they are onc...
[ "Based on the comments the answer is yes, nesting while loops can cause issues by both exceeding the limited stack size and because while loops are generally \"blocking\" in nature (which I don't fully understand, but I'm including this for people that will). In this specific case, there is also the issue of possib...
[ 0 ]
[]
[]
[ "python", "python_3.x", "while_loop" ]
stackoverflow_0074491570_python_python_3.x_while_loop.txt
Q: using ray + light gbm + limited memory So, I would like to train a lightGBM on a remote, large ray cluster and a large dataset. Before that, I would like to write the code such that I can run the training also in a memory-constrained setting, e.g. my local laptop, where the dataset does not fit in-mem. That will r...
using ray + light gbm + limited memory
So, I would like to train a lightGBM on a remote, large ray cluster and a large dataset. Before that, I would like to write the code such that I can run the training also in a memory-constrained setting, e.g. my local laptop, where the dataset does not fit in-mem. That will require some way of lazy loading the data. Th...
[ "LightGBM requires loading the entire dataset for training, so in this case, you can test on your laptop with a subset of the data (i.e. only pass a subset of the parquet filenames in).\nThe lazy=True flag delays the data loading to be split across the actors, rather than loading into memory first, then splitting+s...
[ 0 ]
[]
[]
[ "lightgbm", "python", "ray" ]
stackoverflow_0074446130_lightgbm_python_ray.txt
Q: How can I compare this template list to a list of words? I'm trying to find out which words fit into this template but don't know how to compare them. Is there any way to do this without counting specific alphabetic characters in the template, getting their indices, and then checking each letter in each word? The ...
How can I compare this template list to a list of words?
I'm trying to find out which words fit into this template but don't know how to compare them. Is there any way to do this without counting specific alphabetic characters in the template, getting their indices, and then checking each letter in each word? The desired output is a list of words from words that fit the temp...
[ "You can use zip to compare the word to template:\ndef word_fits(word, template):\n if len(word) != len(template):\n return False\n\n for w, t in zip(word, template):\n if t != \"_\" and w != t:\n return False\n\n return True\n\n\ntemplate = [\"_\", \"_\", \"l\", \"_\", \"_\"]\nwor...
[ 4, 1 ]
[]
[]
[ "comparison", "for_loop", "list", "loops", "python" ]
stackoverflow_0074496668_comparison_for_loop_list_loops_python.txt
Q: Flatten broken horizontal bar chart to line graph or heatmap I have data for all the time I've spent coding. This data is represented as a dictionary where the key is the date and the value is a list of tuples containing the time I started a coding session and how long the coding session lasted. I have successfull...
Flatten broken horizontal bar chart to line graph or heatmap
I have data for all the time I've spent coding. This data is represented as a dictionary where the key is the date and the value is a list of tuples containing the time I started a coding session and how long the coding session lasted. I have successfully plotted this on a broken_barh using the below code, where the y-...
[ "You can find some great examples of how to create a heatmap from matplotlib website.\nHere is a basic code with some random data:\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nindex_labels = np.arange(0,24)\ncolumn_labels = pd.date_range(start='1/1/2022', end='1/31/2022').strftime('%...
[ 0, 0 ]
[]
[]
[ "charts", "matplotlib", "python" ]
stackoverflow_0074482626_charts_matplotlib_python.txt
Q: how to groupby rows and create new columns on pyspark original dataframe id email name 1 id1@first.com john 2 id2@first.com Maike 2 id2@second Maike 1 id1@second.com john I want to convert to this id email email1 name 1 id1@first.com id1@second.com john 2 id2@first.com id2@second Maike it's only an examp...
how to groupby rows and create new columns on pyspark
original dataframe id email name 1 id1@first.com john 2 id2@first.com Maike 2 id2@second Maike 1 id1@second.com john I want to convert to this id email email1 name 1 id1@first.com id1@second.com john 2 id2@first.com id2@second Maike it's only an example, I have very large file and more t...
[ "In order to do it deterministically in Spark, you must have some rule to determine which email is first and which is second. The row order in the CSV file (not having a specified column for row number) is a bad rule when you work with Spark, because every row may go to a different node, and then you will cannot s...
[ 1, 1, 0 ]
[]
[]
[ "apache_spark", "csv", "group_by", "pyspark", "python" ]
stackoverflow_0074484873_apache_spark_csv_group_by_pyspark_python.txt
Q: why it doesn't work when I write comments in python Image of the code and error I'm getting A: You didn't save the file :)...
why it doesn't work when I write comments in python
Image of the code and error I'm getting
[ "You didn't save the file :)...\n" ]
[ 3 ]
[]
[]
[ "comments", "python" ]
stackoverflow_0074496776_comments_python.txt
Q: How do I put an attribute as a variable in a python function? I have this function: def webdriver_wait(browser, delay, tag_name, tag, succesful_message, fail_message): try: wait_by_var = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.tag_name, tag))) print(succesful_mess...
How do I put an attribute as a variable in a python function?
I have this function: def webdriver_wait(browser, delay, tag_name, tag, succesful_message, fail_message): try: wait_by_var = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.tag_name, tag))) print(succesful_message) return wait_by_var except TimeoutException: ...
[ "Use the getattr() function to get an arbitrary attribute of a function by its name.\ngetattr(By, tag_name)\n\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "python", "selenium", "selenium_webdriver", "webdriverwait" ]
stackoverflow_0074496772_attributeerror_python_selenium_selenium_webdriver_webdriverwait.txt
Q: How can I add a string inside a string? The problem is simple, I'm given a random string and a random pattern and I'm told to get all the posible combinations of that pattern that occur in the string and mark then with [target] and [endtarget] at the beggining and end. For example: given the following text: "XuyZB...
How can I add a string inside a string?
The problem is simple, I'm given a random string and a random pattern and I'm told to get all the posible combinations of that pattern that occur in the string and mark then with [target] and [endtarget] at the beggining and end. For example: given the following text: "XuyZB8we4" and the following pattern: "XYZAB" The ...
[ "re.sub allows you to pass backreferences to matched groups within your pattern. so you do need to enclose your pattern in parentheses, or create a named group, and then it will replace all matches in the entire string at once with your desired replacements:\nIn [10]: re.sub(r'([XYZAB]+)', r'[target]\\1[endtarget]'...
[ 3 ]
[]
[]
[ "python", "python_re", "string" ]
stackoverflow_0074496812_python_python_re_string.txt
Q: Failed to install Calliope I am trying to install the package calliope on python 3.7 using pycharm and I am getting this error that I don't understand. I also tryed o install it via anaconda but still I am getting the same problem. Any help please would be highly appreciated. It is really imporant where I need t...
Failed to install Calliope
I am trying to install the package calliope on python 3.7 using pycharm and I am getting this error that I don't understand. I also tryed o install it via anaconda but still I am getting the same problem. Any help please would be highly appreciated. It is really imporant where I need this package to run a program abo...
[ "\nDownload HDF5 https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.12/hdf5-1.12.1/bin/windows/\n\nSet the environment variable HDF5_DIR to C:/Program Files/HDF_Group/HDF5/<your unzipped location>\n\n\n" ]
[ 0 ]
[]
[]
[ "anaconda", "calliope", "pip", "python", "python_3.x" ]
stackoverflow_0074490226_anaconda_calliope_pip_python_python_3.x.txt
Q: Output values in a list below a user defined amount - functions Python programming problem for first year college kids. Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, get the last value from the input, and output ...
Output values in a list below a user defined amount - functions
Python programming problem for first year college kids. Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, get the last value from the input, and output all integers less than or equal to that value. Ex: If the input is: 5...
[ "You went to all the trouble to separate the threshold value, and then you don't use it. Change one line:\ndef output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):\n user_values = [i for i in user_values if i <= upper_threshold]\n print(*user_values, sep = \"\\n\")\n\n", "def get_user...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0069656068_python.txt
Q: How do I create test and train samples from one dataframe with pandas? I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing. Thanks! A: Scikit Learn's train_test_split is a good one. ...
How do I create test and train samples from one dataframe with pandas?
I have a fairly large dataset in the form of a dataframe and I was wondering how I would be able to split the dataframe into two random samples (80% and 20%) for training and testing. Thanks!
[ "Scikit Learn's train_test_split is a good one. It will split both numpy arrays and dataframes.\nfrom sklearn.model_selection import train_test_split\n\ntrain, test = train_test_split(df, test_size=0.2)\n\n", "I would just use numpy's randn:\nIn [11]: df = pd.DataFrame(np.random.randn(100, 2))\n\nIn [12]: msk = n...
[ 916, 469, 391, 42, 27, 26, 15, 8, 6, 6, 5, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_2.7" ]
stackoverflow_0024147278_dataframe_pandas_python_python_2.7.txt
Q: Is there a way to find the directory of a file that imports another? I am looking for a way to find the directory of a file that imports another. This most likely seems very unspecific so, I am going to try to fix that. Lets say we have a file in a directory named "library.py", and we have another file named "main...
Is there a way to find the directory of a file that imports another?
I am looking for a way to find the directory of a file that imports another. This most likely seems very unspecific so, I am going to try to fix that. Lets say we have a file in a directory named "library.py", and we have another file named "main.py." If in main.py, you import library.py, is the a way to call a functio...
[ "in your main.py file do this\nimport os\nimport library\n\nprint(os.path.abspath(library.__file__))\n\nthis will give you the directory to the library.py file\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074496928_python.txt
Q: How to add error bars to a grouped bar plot? I would like to add error bar in my plot that I can show the min max of each plot. Please, anyone can help me. Thanks in advance. The min max is as follow: Delay = (53.46 (min 0, max60) , 36.22 (min 12,max 70), 83 (min 21,max 54), 17 (min 12,max 70)) Latency = (38 (min ...
How to add error bars to a grouped bar plot?
I would like to add error bar in my plot that I can show the min max of each plot. Please, anyone can help me. Thanks in advance. The min max is as follow: Delay = (53.46 (min 0, max60) , 36.22 (min 12,max 70), 83 (min 21,max 54), 17 (min 12,max 70)) Latency = (38 (min 2,max 70), 44 (min 12,max 87), 53 (min 9,max 60), ...
[ "\nIn order to plot in the correct location on a bar plot, the patch data for each bar must be extracted.\nAn ndarray is returned with one matplotlib.axes.Axes per column.\n\nIn the case of this figure, ax.patches contains 8 matplotlib.patches.Rectangle objects, one for each segment of each bar.\n\nBy using the ass...
[ 3, 0 ]
[]
[]
[ "data_science", "matplotlib", "pandas", "python" ]
stackoverflow_0063866002_data_science_matplotlib_pandas_python.txt
Q: django update database everyday I made a wordlegolf site, www.wordlegolfing.com, where my friends and I play wordle and it tracks our scores daily. I keep track of all the users scores and have a scoreboard shown on the site. If someone forgets to do the wordle that day I currently manually adjust there scores to ...
django update database everyday
I made a wordlegolf site, www.wordlegolfing.com, where my friends and I play wordle and it tracks our scores daily. I keep track of all the users scores and have a scoreboard shown on the site. If someone forgets to do the wordle that day I currently manually adjust there scores to reflect that but I would like to make...
[ "You don't need Celery to run a daily job.\nYou do need a script that does what you want. Since you want to interact with the Django database, a custom management command might be your best bet.\nOnce you have a script that does what you want, you can schedule it to run on your preferred schedule, e.g. daily at 2am...
[ 0 ]
[]
[]
[ "celery", "django", "heroku", "python" ]
stackoverflow_0074493765_celery_django_heroku_python.txt
Q: 5*2=55 not 10! Why? I want to output 5 * 2 = 10 but python output is 55! How do I resolve this problem? a = 0 b = 2 a = input("a? :") #(get 5 as input) c = a * b print (c) This is my code. when I input a number it repeat same number I entered two times insterd of showing multipiy it. What do I have to do to so...
5*2=55 not 10! Why?
I want to output 5 * 2 = 10 but python output is 55! How do I resolve this problem? a = 0 b = 2 a = input("a? :") #(get 5 as input) c = a * b print (c) This is my code. when I input a number it repeat same number I entered two times insterd of showing multipiy it. What do I have to do to solve this?
[ "a is a string,\nso it will be\n'5'*2='55'\n\nif you want 10, you need to cast a to int.\na=int(input())\n\nhere is the link to document\nhttps://docs.python.org/3/library/functions.html#input\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074496965_python.txt
Q: tkinter ttk Radiobutton layout - apply padding between indicator and label Is it possible to add a padding between Radiobutton's label and the checkbox? For example I want to move "Option 1" and "Option 2" texts to lower from their checkboxes: screen = Tk() canvas = Canvas(screen, width=600, height=600) canvas.pa...
tkinter ttk Radiobutton layout - apply padding between indicator and label
Is it possible to add a padding between Radiobutton's label and the checkbox? For example I want to move "Option 1" and "Option 2" texts to lower from their checkboxes: screen = Tk() canvas = Canvas(screen, width=600, height=600) canvas.pack() s = ttk.Style() s.layout('TRadiobutton', [('Radiobutton.padding'...
[ "So basically the trick to simulate what you want is to use ipady which is available for grid and pack. Example:\nrad_button = ttk.Radiobutton(root, text='abc')\nrad_button.pack(expand=False, fill=None,ipady=15)\n\nThen all you need to do is to stick the parts to the right side with a layout that could look like th...
[ 2 ]
[]
[]
[ "python", "tkinter", "ttk" ]
stackoverflow_0074496540_python_tkinter_ttk.txt
Q: Genetic Algorithm using fixed length vector I am trying to implement a genetic algorithm using fixed-length vectors of real numbers. I found a simple implementation online using a binary encoded values. My confusion arises when I am trying to figure out a way to initialise the array and set the bounds for this alg...
Genetic Algorithm using fixed length vector
I am trying to implement a genetic algorithm using fixed-length vectors of real numbers. I found a simple implementation online using a binary encoded values. My confusion arises when I am trying to figure out a way to initialise the array and set the bounds for this algorithm. Below is a snippet of the code with binar...
[ "It appears that you are referencing the code in this article: Simple Genetic Algorithm From Scratch in Python.\nThe bit-vector representation of individuals that is used in the starting code is an encoding of a real-valued vector. If you want your representation of an individual to be a real-valued vector, it mean...
[ 1 ]
[]
[]
[ "evolutionary_algorithm", "genetic_algorithm", "python" ]
stackoverflow_0074496593_evolutionary_algorithm_genetic_algorithm_python.txt
Q: Code for the game and there is error in operating Here I want to operate the code in line 14. But is is type error. Can we make remove it making both int or anything. A: Try: sticks_remaining = len(sticks_remaining) - pickup Since, sticks_remaining is a string. Or if you just want the number of | remaining you ...
Code for the game and there is error in operating
Here I want to operate the code in line 14. But is is type error. Can we make remove it making both int or anything.
[ "Try:\nsticks_remaining = len(sticks_remaining) - pickup\n\nSince, sticks_remaining is a string.\nOr\nif you just want the number of | remaining you can do:\nsticks_remaining = (len(sticks_remaining) - pickup) * '|'\n\n", "Line 14 is causing the Type Error. This is because you are trying to subtract an int from a...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074497027_python.txt
Q: How to find third and fourth max in list? I am trying find the third and fourth max number in a list and then sum them. The solution must be linear O(n). eg: >>> Max_34([1000, 1, 100, 2, 99, 200,100]) 199 Here's what I did: The problem is that it will work for max_34([1,2,3,4]), but it won't work for max_3...
How to find third and fourth max in list?
I am trying find the third and fourth max number in a list and then sum them. The solution must be linear O(n). eg: >>> Max_34([1000, 1, 100, 2, 99, 200,100]) 199 Here's what I did: The problem is that it will work for max_34([1,2,3,4]), but it won't work for max_34([1000, 1, 100, 2, 99, 200,100]). Why ? Could...
[]
[]
[ "The reason your code does not work is because you can not iterate over a list and have it skip values you deleted after you started. The loop iterates over the original list. Here's what I would do instead\ndef removeall(l, item):\n while item in l:\n l.remove(item)\n return l\ndef max_34(a):\n max...
[ -1, -1 ]
[ "python" ]
stackoverflow_0074496871_python.txt
Q: Adding multiple lines to a strip plot in plotly I would like to add multiple short lines to a strip plot in plotly, preferably in a way that scales to adding more columns/categories. In my actual problem I have quite a few more columns. It would also be awesome if these lines could have their own hover label. I go...
Adding multiple lines to a strip plot in plotly
I would like to add multiple short lines to a strip plot in plotly, preferably in a way that scales to adding more columns/categories. In my actual problem I have quite a few more columns. It would also be awesome if these lines could have their own hover label. I got the first one manually, but for the rest it is/woul...
[ "Since the content is a boxplot, I will reuse it for the graph of the graph object. What needs a little work is that the boxplot is the x-axis of a categorical variable. The best way to programmatically create a line segment is in the line mode of a scatter plot; to make the x-axis coordinates numerical, I add a ne...
[ 0 ]
[]
[]
[ "graphics", "plotly", "plotly_python", "python" ]
stackoverflow_0074495538_graphics_plotly_plotly_python_python.txt
Q: Cannot plot this small dataset after transpose This is my data set after i transpose it. When I try to plot this dataset I get different type of errors based off of the codes I use: when using df.plot("Country Name", "China") I get KeyError: 'Country Name' df.plot.line() Gives KeyError: ('Country Name', 'China')...
Cannot plot this small dataset after transpose
This is my data set after i transpose it. When I try to plot this dataset I get different type of errors based off of the codes I use: when using df.plot("Country Name", "China") I get KeyError: 'Country Name' df.plot.line() Gives KeyError: ('Country Name', 'China') x = dfg1_2_4.iloc[:,0] y = dfg1_2_4.iloc[:,1] plt....
[ "Try\ndf = df.reindex(df.index.drop('Country Name'))\n\nthen\ndf.plot()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "dataset", "pandas", "plot", "python" ]
stackoverflow_0074495748_dataframe_dataset_pandas_plot_python.txt
Q: How to match a string with pythons regex with optional character, but only if that optional character is preceded by another character I need to match a string that optionally ends with numbers, but only if the numbers aren't preceded by a 0. so AAAA should match, AAA1 should, AA20 should, but AA02 should not. I c...
How to match a string with pythons regex with optional character, but only if that optional character is preceded by another character
I need to match a string that optionally ends with numbers, but only if the numbers aren't preceded by a 0. so AAAA should match, AAA1 should, AA20 should, but AA02 should not. I can figure out the optionality of it, but I'm not sure if python has a "preceded by" or "followed by" flag. if s.isalnum() and re.match("^[A-...
[ "Try:\n^[A-Z]+(?:[1-9][0-9]*)?$\n\nRegex demo.\n\n^[A-Z]+ - match letters from the beginning of string\n(?:[1-9][0-9]*)? - optionally match a number that doesn't start from 0\n$ - end of string\n" ]
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074497079_python_regex.txt
Q: How to connect points on a 3D plot using ax.scatter and ax.plot in Numpy? I have to make a 3D plot with multiple parallel line plots. I can put the points (for three lines) on plot using the following code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits...
How to connect points on a 3D plot using ax.scatter and ax.plot in Numpy?
I have to make a 3D plot with multiple parallel line plots. I can put the points (for three lines) on plot using the following code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits import mplot3d ax = plt.gca(projection ='3d') ax.scatter(0, 0, 100, color = ...
[ "The arguments to ax.plot() should not be the individual points, but the individual dimensions: first a list of all the x-values, then all the y-values, and then all the z-values. You can use the same syntax for ax.scatter().\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axe...
[ 1 ]
[]
[]
[ "plot", "python", "scatter_plot" ]
stackoverflow_0074491620_plot_python_scatter_plot.txt
Q: printing test grades and test score average within functions using python The assignment is to get 5 test score and use them to display the corresponding letter grade and test score average using functions. I don't know if I'm on the right track and I was having trouble calling the other functions within the main ...
printing test grades and test score average within functions using python
The assignment is to get 5 test score and use them to display the corresponding letter grade and test score average using functions. I don't know if I'm on the right track and I was having trouble calling the other functions within the main function. def main(): s1 = int(input('Enter score one: ')) s2 =...
[ "return should be at the end of the main function\ndef main():\n s1 = int(input('Enter score one: '))\n s2 = int(input('Enter score two: '))\n s3 = int(input('Enter score three: '))\n s4 = int(input('Enter score four: '))\n s5 = int(input('Enter score five: '))\n \n \n ...
[ 0 ]
[]
[]
[ "average", "function", "if_statement", "input", "python" ]
stackoverflow_0074497006_average_function_if_statement_input_python.txt
Q: Python; User Prompts; choose multiple files I would like to have my code bring up a window where you can select multiple files within a folder and it assigns these filenames to elements of a list. Currently, I can only select a single file at a time and it assigns the filename to a single variable. from Tkinter im...
Python; User Prompts; choose multiple files
I would like to have my code bring up a window where you can select multiple files within a folder and it assigns these filenames to elements of a list. Currently, I can only select a single file at a time and it assigns the filename to a single variable. from Tkinter import Tk from tkFileDialog import askopenfilename ...
[ "You need to use the askopenfilenames method instead.\n", "You can encapsulate all that in a function:\ndef get_filename_from_user(message):\n root = Tk()\n root.withdraw()\n filename = tkFileDialog.askopenfilename(title=message)\n return filename\n\nThen you can call it as many times as you like:\nfilename1 ...
[ 2, 0 ]
[ "from easygui import fileopenbox\nfiles = []\n#how many file you want choice\nfileCount = int(input(\"How many file need open\"))\nfor x in range(fileCount):\n files.append(fileopenbox())\nprint(files)\n\n" ]
[ -1 ]
[ "file", "prompt", "python", "user_interface" ]
stackoverflow_0017958230_file_prompt_python_user_interface.txt
Q: Extract two specified words from the dataframe and place them in a new column, then delete the rows This is the dataframe: data = {"Company" : [["ConsenSys"] , ["Cognizant"], ["IBM"], ["IBM"], ["Reddit, Inc"], ["Reddit, Inc"], ["IBM"]], "skills" : [['services', 'scientist technical expertise', 'databases'], ['data...
Extract two specified words from the dataframe and place them in a new column, then delete the rows
This is the dataframe: data = {"Company" : [["ConsenSys"] , ["Cognizant"], ["IBM"], ["IBM"], ["Reddit, Inc"], ["Reddit, Inc"], ["IBM"]], "skills" : [['services', 'scientist technical expertise', 'databases'], ['datacomputing tools experience', 'deep learning models', 'cloud services'], ['quantitative analytical project...
[ "You can use a lambda with a list comp\nwords = [\"services\", \"statistical analysis\"]\ndff[\"found\"] = dff[\"skills\"].apply(lambda x: \", \".join(set([i for i in x if i in words])).split(\", \"))\n\n", "word = ['services', 'statistical analysis']\ns1 = df['skills'].apply(lambda x: [i for i in word if i in x]...
[ 1, 0 ]
[]
[]
[ "dataframe", "nlp", "pandas", "python" ]
stackoverflow_0074497075_dataframe_nlp_pandas_python.txt
Q: Python rising/falling edge oscilloscope-like trigger I'm trying to detect rising and/or falling edges in a numpy vector, based on a trigger value. This is kinda like how oscilloscope triggering works. The numpy vector contains floating point values. The trigger itself is a floating point value. I would expect this...
Python rising/falling edge oscilloscope-like trigger
I'm trying to detect rising and/or falling edges in a numpy vector, based on a trigger value. This is kinda like how oscilloscope triggering works. The numpy vector contains floating point values. The trigger itself is a floating point value. I would expect this to work as such: import numpy as np data = np.array([-1, ...
[ "We could slice one-off and compare against the trigger for smaller than and greater than, like so -\nIn [41]: data = np.array([-1, -0.5, 0, 0.5, 1, 1.5, 2, 0, 0.5])\n\nIn [43]: trigger_val = 0.3\n\nIn [44]: np.flatnonzero((data[:-1] < trigger_val) & (data[1:] > trigger_val))+1\nOut[44]: array([3, 8])\n\nIf you wou...
[ 8, 0 ]
[]
[]
[ "edge_detection", "numpy", "python" ]
stackoverflow_0050365310_edge_detection_numpy_python.txt
Q: How to create list of dictionary from nested list of strings in python? I have dataframe with sparse columns values and I vectorized it, now I want to create key-value dictionary by row-wise. However, I need to create dictionary where column name is key and column value is value by each row of dataframe. How to cr...
How to create list of dictionary from nested list of strings in python?
I have dataframe with sparse columns values and I vectorized it, now I want to create key-value dictionary by row-wise. However, I need to create dictionary where column name is key and column value is value by each row of dataframe. How to create such dictionary from my current attempt? any thoughts? approach 1 here i...
[ "There exists a technical problem\nthat you hope one or more people will solve, possibly\nincluding yourself.\nHere is my current understanding\nof the problem as presented.\nThe \"expected\" values apparently\ndon't match your expectation.\nIt would be helpful if you could\ndescribe them in code.\nMaybe you wish t...
[ 1 ]
[]
[]
[ "dataframe", "list", "pandas", "python" ]
stackoverflow_0074496442_dataframe_list_pandas_python.txt
Q: Convert scientific to decimal - dynamic float precision? I have a random set of numbers in a SQL database: 1.2 0.4 5.1 0.0000000000232 1 7.54 0.000000000000006534 The decimals way below zero are displayed as scientific notation num = 0.0000000000232 print(num) > 2.23e-11 But that causes the rest of my code to b...
Convert scientific to decimal - dynamic float precision?
I have a random set of numbers in a SQL database: 1.2 0.4 5.1 0.0000000000232 1 7.54 0.000000000000006534 The decimals way below zero are displayed as scientific notation num = 0.0000000000232 print(num) > 2.23e-11 But that causes the rest of my code to bug out as the api behind it expects a decimal number. I checke...
[ "If Python provides a way to do this, they've hidden it very well. But a simple function can do it.\ndef float_to_str(x):\n to_the_left = 1 + floor(log(x, 10))\n to_the_right = sys.float_info.dig - to_the_left\n if to_the_right <= 0:\n s = str(int(x))\n else:\n s = format(x, f'0.{to_the_r...
[ 1 ]
[]
[]
[ "floating_point", "precision", "python" ]
stackoverflow_0074495972_floating_point_precision_python.txt
Q: How do I fix this: TypeError: Entry.get() takes 1 positional argument but 3 were given I am very new to coding and can't figure out what is wrong. I am just trying to print something that the user types in a text box. I have a button that calls a function to take the info from the textbox, do some math with the nu...
How do I fix this: TypeError: Entry.get() takes 1 positional argument but 3 were given
I am very new to coding and can't figure out what is wrong. I am just trying to print something that the user types in a text box. I have a button that calls a function to take the info from the textbox, do some math with the number, then print its output in the console. When I run the program it starts off fine but wh...
[ "The get method takes no parameters (other than self, which is why the error mentions one parameter). You are calling it as if the widget was a Text widget, but it's an Entry widget. The way to call get on an entry widget is by passing no parameters:\nyear = boxYear.get()\n\n" ]
[ 0 ]
[]
[]
[ "python", "tkinter", "tkinter_button", "tkinter_entry", "typeerror" ]
stackoverflow_0074496351_python_tkinter_tkinter_button_tkinter_entry_typeerror.txt
Q: How do I remove items from a list based off of class data class Student: def __init__(self, name, major, gpa, onProbation): self.name = name self.major = major self.gpa = gpa self.onProbation = onProbation Student1 = Student("Josh", "Business", 3.8, False) Stud...
How do I remove items from a list based off of class data
class Student: def __init__(self, name, major, gpa, onProbation): self.name = name self.major = major self.gpa = gpa self.onProbation = onProbation Student1 = Student("Josh", "Business", 3.8, False) Student2 = Student("Maya", "Accountancy", 2.5, True) Studen...
[ "I believe I have found an answer to your question. I would also like to note that it is best not to create your student objects in the init method and storing all the students in a list is useful.. Here it is:\nclass Student:\n\n def __init__(self, name, major, gpa, onProbation):\n self.name = name\n ...
[ 0, 0 ]
[ "this is kinda how i do it. When you make classes it remembers the attribute assignments even in lists. There called pylist in cpython\n\nclass Student:\n\n def __init__(self, name: str, major: str, gpa:float, onProbation: bool):\n self.name = name\n self.major = major\n self.gpa = gpa\n ...
[ -1 ]
[ "class", "list", "python", "python_3.x" ]
stackoverflow_0074497208_class_list_python_python_3.x.txt
Q: Data download from a REST API directly on AWS S3 bucket I need to download data from a REST api by making a GET request from AWS cloud and land the data in S3. Do we have a REST connector available in AWS to make direct connection to API? If not, then I plan to write Python code using requests library to make GET ...
Data download from a REST API directly on AWS S3 bucket
I need to download data from a REST api by making a GET request from AWS cloud and land the data in S3. Do we have a REST connector available in AWS to make direct connection to API? If not, then I plan to write Python code using requests library to make GET request to API using BASIC auth, write the response json into...
[ "You need to create a presigned url first, then you can upload files directly to s3.\nEverytime your api gets an upload request it will create a presigned url first then use that to upload data to s3.\nThis might help.\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "api", "python", "rest" ]
stackoverflow_0074489867_amazon_s3_amazon_web_services_api_python_rest.txt
Q: How to use cmp() in Python 3? I cannot get the command cmp() to work. Here is the code: a = [1,2,3] b = [1,2,3] c = cmp(a,b) print (c) I am getting the error: Traceback (most recent call last): File "G:\Dropbox\Code\a = [1,2,3]", line 3, in <module> c = cmp(a,b) NameError: name 'cmp' is not defined [Finish...
How to use cmp() in Python 3?
I cannot get the command cmp() to work. Here is the code: a = [1,2,3] b = [1,2,3] c = cmp(a,b) print (c) I am getting the error: Traceback (most recent call last): File "G:\Dropbox\Code\a = [1,2,3]", line 3, in <module> c = cmp(a,b) NameError: name 'cmp' is not defined [Finished in 0.1s]
[ "As mentioned in the comments, cmp doesn't exist in Python 3. If you really want it, you could define it yourself:\ndef cmp(a, b):\n return (a > b) - (a < b) \n\nwhich is taken from the original What's New In Python 3.0. It's pretty rare -- though not unheard of -- that it's really needed, though, so you might...
[ 93, 10, 1, 0, 0, 0 ]
[ "If a or b is a class object,\nthen the above answers will have the compilation error as below:\nFor example: a is Class Clock:\n File \"01_ClockClass_lab16.py\", line 14, in cmp\n return (a > b) - (a < b)\nTypeError: '>' not supported between instances of 'Clock' and 'Clock'\n\nChange the type with int() to re...
[ -1, -1, -3 ]
[ "python", "python_3.x" ]
stackoverflow_0022490366_python_python_3.x.txt
Q: Overriding parent methods Programmatically I need to use a company logger library that requires a Message object as an argument instead of a plain string like vanilla python logging library (the rest works exactly like vanilla logging). To avoid having to migrate each log individually across all the applications I...
Overriding parent methods Programmatically
I need to use a company logger library that requires a Message object as an argument instead of a plain string like vanilla python logging library (the rest works exactly like vanilla logging). To avoid having to migrate each log individually across all the applications I maintain, I am trying to extend this custom log...
[ "Since I'm overriding a method, I needed to pass self as well when overriding\ndef override_loglevels(self, level):\n\n def log(message):\n logger = getattr(SantanderLogger, level)\n if isinstance(message, Message):\n logger(self, message)\n else :\n logger(self, Messag...
[ 1 ]
[]
[]
[ "inheritance", "overriding", "python" ]
stackoverflow_0074497254_inheritance_overriding_python.txt
Q: How can I use torch.fft.fft2 to output the same result as troch.fft? In the documentation of pytorch 1.1.0, the description of the return of torch.fft is "Returns the real and the imaginary part together as an tensor of the same shape input" In pytorch1.8.1, torch.fft is replaced by torch.fft.fft2, and torch.fft...
How can I use torch.fft.fft2 to output the same result as troch.fft?
In the documentation of pytorch 1.1.0, the description of the return of torch.fft is "Returns the real and the imaginary part together as an tensor of the same shape input" In pytorch1.8.1, torch.fft is replaced by torch.fft.fft2, and torch.fft.fft2 outputs the result in complex For the same data, the output of torch...
[ "I was struggle in this for few days, then i try all parameters in torch.fft.fft2,finally i found set norm='ortho' make the same result with old pytorch torch.fft . Hope this will help you.\n" ]
[ 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0069764891_python_pytorch.txt
Q: mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) I am following along with lecturer's code and videos. He has this set up, and I have followed exactly. His works, mine doesn't and I cant figure out why. It is set up as user "root" and passwor...
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
I am following along with lecturer's code and videos. He has this set up, and I have followed exactly. His works, mine doesn't and I cant figure out why. It is set up as user "root" and password is blank. I have tried pip install mysql-connector-python. I want to keep the same user and password as his so as to fol...
[ "The same problem occurred when my friend tried to run a python script in the Ubuntu Windows Linux Subsystem that uses a MySQL database set up.\nWe fixed the problem by running the following three commands in the MySQL 8.0 Command Line Client and then restarting the machine to reboot everything. We are using Flask ...
[ 0, 0, 0, 0 ]
[]
[]
[ "mysql", "python", "wampserver" ]
stackoverflow_0064936683_mysql_python_wampserver.txt
Q: Slow Requests on Local Flask Server Just starting to play around with Flask on a local server and I'm noticing the request/response times are way slower than I feel they should be. Just a simple server like the following takes close to 5 seconds to respond. from flask import Flask app = Flask(__name__) @app.rout...
Slow Requests on Local Flask Server
Just starting to play around with Flask on a local server and I'm noticing the request/response times are way slower than I feel they should be. Just a simple server like the following takes close to 5 seconds to respond. from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "index" i...
[ "Ok I figured it out. It appears to be an issue with Werkzeug and os's that support ipv6.\nFrom the Werkzeug site http://werkzeug.pocoo.org/docs/serving/:\n\nOn operating systems that support ipv6 and have it configured such as modern Linux systems, OS X 10.4 or higher as well as Windows Vista some browsers can be ...
[ 99, 97, 17, 14, 8, 5, 4, 0, 0, 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0011150343_flask_python.txt
Q: PyQt6 - Dummy child class not showing when inheriting from QWidget (but shows when inheriting from QLabel) I'm learning PyQt / Qt and I am facing a basic problem. I want to make a child class that inherits from QWidget but for some reason it does not show. For trouble shooting, I've used a simple dummy child class...
PyQt6 - Dummy child class not showing when inheriting from QWidget (but shows when inheriting from QLabel)
I'm learning PyQt / Qt and I am facing a basic problem. I want to make a child class that inherits from QWidget but for some reason it does not show. For trouble shooting, I've used a simple dummy child class. from PyQt6.QtWidgets import QWidget, QApplication,QMainWindow, QLabel import sys class TestWidget(QWidget): ...
[ "It's because the QWidget class is the base class of all widgets and designed to have no drawing(painting) logic in it even for the background by default. In most cases of deriving from the QWidget, you either implement a custom drawing logic by overriding paintEvent() or use it as an invisible event receiver.\nThe...
[ 0 ]
[]
[]
[ "pyqt6", "python" ]
stackoverflow_0074496042_pyqt6_python.txt
Q: Why my code is not accepted in the contest? def is_the_same(palavraa): i=0 j=1 n=2 while len(palavraa)!=0: if palavraa[0]==palavraa[i] and palavraa[1]==palavraa[j] and palavraa[2]==palavraa[n]: if i+3<len(palavraa): i=i+3 elif j+3<len(palavraa): ...
Why my code is not accepted in the contest?
def is_the_same(palavraa): i=0 j=1 n=2 while len(palavraa)!=0: if palavraa[0]==palavraa[i] and palavraa[1]==palavraa[j] and palavraa[2]==palavraa[n]: if i+3<len(palavraa): i=i+3 elif j+3<len(palavraa): j=j+3 elif n+3<len(palavra...
[ "def is_the_same(palavraa):\ni=0\nj=1\nn=2\nwhile len(palavraa)!=0:\n if palavraa[0]==palavraa[i] and palavraa[1]==palavraa[j] and palavraa[2]==palavraa[n]:\n if i+3<len(palavraa):\n i=i+3\n elif j+3<len(palavraa):\n j=j+3\n elif n+3<len(palavraa):\n n=n+3\n ...
[ 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074497310_python_string.txt
Q: Change the output shape of Pytorch GAN Generator? I'm trying to build a GAN model that outputs sound, specifically the speech of the digits 0-9. I'm basing my GAN model on a conditional GAN used for the regular image MNIST dataset. One of the main differences is that the shape of my data is 256x64, where as MNIST ...
Change the output shape of Pytorch GAN Generator?
I'm trying to build a GAN model that outputs sound, specifically the speech of the digits 0-9. I'm basing my GAN model on a conditional GAN used for the regular image MNIST dataset. One of the main differences is that the shape of my data is 256x64, where as MNIST is 64x64. How can I modify the Generator to output 256x...
[ "There are a number of ways to do this - using a linear layer at the end of the sequential layer will work but it will be the equivalent of stretching a 64 x 64 output to a 256 x 64 output.\nA more effective method would be to set the kernel size of the first convolutional layer so that the subsequent image resolut...
[ 0 ]
[]
[]
[ "generative_adversarial_network", "python", "pytorch" ]
stackoverflow_0074497317_generative_adversarial_network_python_pytorch.txt
Q: Can i use input while using write mode for files crud operation in Python? """10-3. Guest: Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt.""" filename2 = "../Data/guest.txt" with open(filename2, "w") as guest_info: filename = input(str(gues...
Can i use input while using write mode for files crud operation in Python?
"""10-3. Guest: Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt.""" filename2 = "../Data/guest.txt" with open(filename2, "w") as guest_info: filename = input(str(guest_info)) for info in guest_info: print(f"name: {info}") I already c...
[]
[]
[ "Take a look at the responses to this question: reading and writing to the same file simultaneously in python\nIt is possible to perform read and write operations with w+, you may find it more straightforward to add the new entry in write mode, then open in read mode to check the contents.\nDouble-check how you are...
[ -1 ]
[ "file", "python" ]
stackoverflow_0074497123_file_python.txt
Q: resample data each column together in dataframe i have a dataframe named zz zz columns name ['Ancolmekar','Cidurian','Dayeuhkolot','Hantap','Kertasari','Meteolembang','Sapan'] for col in zz.columns: df = pd.DataFrame(zz[col],index=pd.date_range('2017-01-01 00:00:00', '2021-12-31 23:50:00', freq='10T')) df.res...
resample data each column together in dataframe
i have a dataframe named zz zz columns name ['Ancolmekar','Cidurian','Dayeuhkolot','Hantap','Kertasari','Meteolembang','Sapan'] for col in zz.columns: df = pd.DataFrame(zz[col],index=pd.date_range('2017-01-01 00:00:00', '2021-12-31 23:50:00', freq='10T')) df.resample('1M').mean() error : invalid syntax i want to ...
[ "You are re-assigninig variable df to a dataframe with a single column during each pass through the for loop. The last column is sapan. Hence, only this column is shown.\nAdditionally, you are setting the index on df that probably isn't the index in zz, therefore you get Not A Number NaN for non-existing values.\n...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074497216_pandas_python.txt
Q: Abstracting away pyodbc connection in a function Python I'm running a lot of python scripts that need to access different servers of a SQL database. I'm hoping to be ab le to abstract away some of the heavy lifting of connecting using pyodbc. In a separate py file I'm defining the default driver and server (in the...
Abstracting away pyodbc connection in a function Python
I'm running a lot of python scripts that need to access different servers of a SQL database. I'm hoping to be ab le to abstract away some of the heavy lifting of connecting using pyodbc. In a separate py file I'm defining the default driver and server (in the future I want to be able to add to this file so that differe...
[ "Depending on the context, I would say what you're doing is fine.\nerror 1: i don't think we have enough information to answer. an import error like this is likely the cause of something like how the file structure is set up that is making the other script not be able to see it.\nerror 2 (_multiarray_umath): specif...
[ 0 ]
[]
[]
[ "abstraction", "pyodbc", "python" ]
stackoverflow_0074497385_abstraction_pyodbc_python.txt
Q: Iterating two lists with two different sliding windows in one loop I have two very large lists, and I want use one loop for iterating over two of them with the different sliding windows. Is that possible? if not, what is the best way? For example, I have A and B, I want a loop which provide the summation of slidi...
Iterating two lists with two different sliding windows in one loop
I have two very large lists, and I want use one loop for iterating over two of them with the different sliding windows. Is that possible? if not, what is the best way? For example, I have A and B, I want a loop which provide the summation of sliding window 2 of list B and sliding window of size 3 of A. A = [1, 2, 3, ...
[ "You could write this as a map over slices as follows:\nfrom operator import add\nres = map(add, A[::3], B[::2])\n\nAnother option is with a list comprehension / generator expression:\nres = [a + b for a, b in zip(A[::3], B[::2])]\n\n", "I found my answer with this way: for those, who maybe have same problem in f...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074497401_python.txt
Q: ModuleNotFoundError: No module named 'tensorflow_docs' when creating TensorFlow docs I'm trying to follow the contribution guide for documentation. The required steps are: git clone https://github.com/tensorflow/tensorflow tensorflow cd tensorflow/tensorflow/tools/docs pip install tensorflow==2.0.0-alpha0 python...
ModuleNotFoundError: No module named 'tensorflow_docs' when creating TensorFlow docs
I'm trying to follow the contribution guide for documentation. The required steps are: git clone https://github.com/tensorflow/tensorflow tensorflow cd tensorflow/tensorflow/tools/docs pip install tensorflow==2.0.0-alpha0 python generate2.py --output_dir=/tmp/out But the last command gives me: Traceback (most recen...
[ "First install tensorflow_docs using this command:\npip install git+https://github.com/tensorflow/docs \n", "first, you need to install git.\ninstall git by using this command conda install git in anaconda prompt. then run the following command\n!pip install -q git+https://github.com/tensorflow/docs \n\nin jupyte...
[ 18, 3, 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0055535518_python_tensorflow.txt
Q: The view basket.views.basket_add didn't return an HttpResponse object. It returned None instead So when previously i tried to add the price, it worked. When I added the quantity of the product something failed. I watched it many times but without luck. If someone can help me I would be grateful. So that is my the ...
The view basket.views.basket_add didn't return an HttpResponse object. It returned None instead
So when previously i tried to add the price, it worked. When I added the quantity of the product something failed. I watched it many times but without luck. If someone can help me I would be grateful. So that is my the error:enter image description here Then there are my views: enter image description here The HTML, an...
[ "In your view, you are returning JsonResponse from the POST request. For the GET request, you are not producing any response. By default, the request is GET. Most probably you are making a GET request. Just add return HttpReponse('') at the end of the view or make sure you are making a proper POST request.\ndef ad...
[ 0 ]
[]
[]
[ "ajax", "django", "jquery", "python" ]
stackoverflow_0074494556_ajax_django_jquery_python.txt
Q: Does Python have a maximum group refer for regex (like Perl)? Context: When running a regex match in Perl, $1, $2 can be used as references to captured regex references from the match, similarly in Python \g<0>,\g<1> can be used Perl also has a $+ special reference which refers to the captured group with highest n...
Does Python have a maximum group refer for regex (like Perl)?
Context: When running a regex match in Perl, $1, $2 can be used as references to captured regex references from the match, similarly in Python \g<0>,\g<1> can be used Perl also has a $+ special reference which refers to the captured group with highest numerical value My question: Does Python have an equivalent of $+ ? ...
[ "The method captures in the regex module provides the same functionality: it \"returns a list of all the captures of a group.\" So get the last one\n>>> import regex\n>>> str = 'fza'\n>>> m = regex.search(r'(a)|(f)', str)\n>>> print(m.captures()[-1])\nf\n\nWhen the str has a before f this code prints a. This is t...
[ 3, 2 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0074496411_perl_python_regex.txt
Q: What am I doing wrong turning Pandas DF to dict? I have a csv that looks like AccountExternalID Customer 1 RogerInc 2 FredLLC I am turning that into a Pandas DF, and I want to turn that into a dict that looks like {'RogerInc': 1, 'FredLLC': 2} This is what I tried; def bui...
What am I doing wrong turning Pandas DF to dict?
I have a csv that looks like AccountExternalID Customer 1 RogerInc 2 FredLLC I am turning that into a Pandas DF, and I want to turn that into a dict that looks like {'RogerInc': 1, 'FredLLC': 2} This is what I tried; def build_custid_dict(csv_path: str=None) -> dict[str]: c...
[ "Example\ndata = {'AccountExternalID': {0: 1, 1: 2}, 'Customer': {0: 'RogerInc', 1: 'FredLLC'}}\ndf = pd.DataFrame(data)\n\noutput(df):\n AccountExternalID Customer\n0 1 RogerInc\n1 2 FredLLC\n\nCode\nuse following code in your func:\ndict(df.iloc[:, [1, 0]].values)\n\nr...
[ 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074497395_dictionary_pandas_python.txt
Q: I have this issue with my vscode executing a python file I can enter into my terminal (wsl) python3 filename.py and the code executes in the terminal just fine. But when I hit the play button (Run Python File) I get errors C:/Users/user1/AppData/Local/Programs/Python/Python311/python.exe "c:/Online Learning/Coder ...
I have this issue with my vscode executing a python file
I can enter into my terminal (wsl) python3 filename.py and the code executes in the terminal just fine. But when I hit the play button (Run Python File) I get errors C:/Users/user1/AppData/Local/Programs/Python/Python311/python.exe "c:/Online Learning/Coder Academy/Python/Lesson-3/test.py" zsh: no such file or director...
[ "I'm not totally sure, but it seems to be coughing up that \"python.exe\" doesn't exist. What I remember doing is checking if \"py.exe\" works and see if the problem is resolved. If so, go to where VSCode says Python is and copy py.exe to your desktop, rename it to python.exe and paste it back to the folder where ...
[ 0, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074497048_python_visual_studio_code.txt
Q: I have 40 columns and I want to concatenate every 2 columns of those 40 columns into 2 columns by using a loop How do I load the data and rearrange them so that x of shape (2000, 2) values and y of shape (2000,) that represent the labels? This is what I am currently doing now. This is the info I know: The datafram...
I have 40 columns and I want to concatenate every 2 columns of those 40 columns into 2 columns by using a loop
How do I load the data and rearrange them so that x of shape (2000, 2) values and y of shape (2000,) that represent the labels? This is what I am currently doing now. This is the info I know: The dataframe has 100 rows × 40 columns so I p1 = q2_data.iloc[:,0:2] p2 = q2_data.iloc[:,2:4] ....... p20 = q2_data.iloc[:,38:4...
[ "If you are looking for the loop logic, this probably works, not the best looking script tho.\ncolumns_name = [\"x1\", \"x2\"] # initiate the column name\nnew_df = pd.DataFrame(columns=columns_name) # create an empty dataframe with column name\n\nfor col_index in range(0,len(q2_data.columns))[::2]: # create a loop ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074497104_python.txt
Q: How to patch/mock import? I'm writing tests for airflow dag and running into issue mocking/patching the dag. # dag.py from airflow.models import Variable ENVIRONMENT = Variable.get("environment") # test_dag.py import dag class TestDAG(TestCase): def test_something(self): pass Because I'm just setti...
How to patch/mock import?
I'm writing tests for airflow dag and running into issue mocking/patching the dag. # dag.py from airflow.models import Variable ENVIRONMENT = Variable.get("environment") # test_dag.py import dag class TestDAG(TestCase): def test_something(self): pass Because I'm just setting variable outside of function...
[ "You'll need to defer importing the file until you can set a Variable value into the test database. A startTestRun method would be the perfect place. \n", "I have some workarounds but not a definite answer:\n\nYou can move this line ENVIRONMENT = Variable.get(\"environment\") into inside a function, instead of gl...
[ 0, 0, 0 ]
[]
[]
[ "airflow", "mocking", "python", "testing", "unit_testing" ]
stackoverflow_0062314746_airflow_mocking_python_testing_unit_testing.txt
Q: Read all Excel sheets except one of them I'm using this line code to get all sheets from an Excel file: excel_file = pd.read_excel('path_file',skiprows=35,sheet_name=None) sheet_name=None option gets all the sheets. How do I get all sheets except one of them? A: If all you want to do is exclude one of the shee...
Read all Excel sheets except one of them
I'm using this line code to get all sheets from an Excel file: excel_file = pd.read_excel('path_file',skiprows=35,sheet_name=None) sheet_name=None option gets all the sheets. How do I get all sheets except one of them?
[ "If all you want to do is exclude one of the sheets, there is not much to change from your base code.\nAssume file.xlsx is an excel file with multiple sheets, and you want to skip 'Sheet1'.\nOne possible solution is as follows:\nimport pandas as pd\n\n# Returns a dictionary with key:value := sheet_name:df\nxlwb = p...
[ 1 ]
[]
[]
[ "google_colaboratory", "pandas", "python" ]
stackoverflow_0074451953_google_colaboratory_pandas_python.txt
Q: How do i generate a string consisting of m number of rows and n number of cols, using random function Write a function named place_random_bricks(m, n, colours) that randomly places bricks row-wise (completes the current row placement before moving to the next row) on the baseplate. It must have three parameters: ...
How do i generate a string consisting of m number of rows and n number of cols, using random function
Write a function named place_random_bricks(m, n, colours) that randomly places bricks row-wise (completes the current row placement before moving to the next row) on the baseplate. It must have three parameters: m - the number of rows on the base-plate, n - the number of columns on the base-plate, and colours - a rand...
[ "I would recommend using numpy to generate random 2d arrays since. and the using a lookup string to convert those numbers to the list of random colours you want it to be converted to.\nimport numpy as np\ndef place_random_bricks(m,n, colors):\n ar = np.random.randint(0,len(colors),(m,n))\n return '\\n'.join([...
[ 1, 1 ]
[]
[]
[ "import", "python", "random", "string" ]
stackoverflow_0074480998_import_python_random_string.txt
Q: How can i print a function contained within another function and called by a third function? I would like to print 10, but I get the error: AttributeError: 'function' object has no attribute 'x' How to fix? Thank you def function1(): def x(): a=10 return a def function2(): y = function1...
How can i print a function contained within another function and called by a third function?
I would like to print 10, but I get the error: AttributeError: 'function' object has no attribute 'x' How to fix? Thank you def function1(): def x(): a=10 return a def function2(): y = function1.x() return y function2()
[ "Functions are not containers you can reference into - classes, objects, structs or records (depending on your language) provide that, but never functions. All a function can or should do is take parameters, run and return a result.\nBTW, one very good reason for this is that functions only have memory for their lo...
[ 0, 0, -1 ]
[ "def function1(func):\n def x():\n a=10\n return func(a)\n return x\n\n@function1\ndef function2(y):\n return y\n\n\nprint(function2())\n \n\nThis should work...\n" ]
[ -1 ]
[ "function", "python", "python_3.x" ]
stackoverflow_0074497414_function_python_python_3.x.txt
Q: How can I isolate the capacitor in these images? I'm having a lot of difficulty isolating these capacitors, yellow squares, in these images. The end goal would be to draw a minAreaRectangle around it and get the location and rotation. I can dim the brightness a bit but that's the least desirable outcome as other i...
How can I isolate the capacitor in these images?
I'm having a lot of difficulty isolating these capacitors, yellow squares, in these images. The end goal would be to draw a minAreaRectangle around it and get the location and rotation. I can dim the brightness a bit but that's the least desirable outcome as other inspections rely on that same level of brightness. I've...
[ "I think you are too quick to exclude color thresholding and morphology to clean up in Python/OpenCV.\nI get the following from color thresholding using cv2.inRange() for yellow color range.\nInput:\n\nlower = (100,200,200)\nupper = (160,255,255)\nresult = cv2.inRange(input, lower, upper)\n\nFrom that you should be...
[ 3 ]
[]
[]
[ "computer_vision", "image_processing", "opencv", "python" ]
stackoverflow_0074496980_computer_vision_image_processing_opencv_python.txt
Q: Check if a file is modified in Python I am trying to create a box that tells me if a file text is modified or not, if it is modified it prints out the new text inside of it. This should be in an infinite loop (the bot sleeps until the text file is modified). I have tried this code but it doesn't work. while True: ...
Check if a file is modified in Python
I am trying to create a box that tells me if a file text is modified or not, if it is modified it prints out the new text inside of it. This should be in an infinite loop (the bot sleeps until the text file is modified). I have tried this code but it doesn't work. while True: tfile1 = open("most_recent_follower.txt...
[ "def read_file():\n with open(\"most_recent_follower.txt\", \"r\") as f:\n SMRF1 = f.readlines()\n return SMRF1\n\ninitial = read_file()\nwhile True:\n current = read_file()\n if initial != current:\n for line in current:\n if line not in initial:\n print(line)\n ...
[ 1, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0028057308_file_python.txt